import { describe, expect, it } from "vitest";

import {
  looksLikeLoginInterstitial,
  pickBestSearchInputCandidate,
  pickBestSearchSubmitCandidate,
} from "./search-page-utils.js";

describe("pickBestSearchInputCandidate", () => {
  it("rejects login-only inputs", () => {
    const winner = pickBestSearchInputCandidate([
      {
        domIndex: 0,
        id: "fm-sms-login-id",
        name: "fm-sms-login-id",
        placeholder: "请输入手机号",
        className: "fm-text",
        rect: { x: 379, y: 398, width: 300, height: 29 },
      },
      {
        domIndex: 1,
        id: "fm-smscode",
        name: "fm-smscode",
        placeholder: "请输入验证码",
        className: "fm-text",
        rect: { x: 379, y: 451, width: 300, height: 29 },
      },
    ]);

    expect(winner).toBeNull();
  });

  it("prefers the real search input over login fields", () => {
    const winner = pickBestSearchInputCandidate([
      {
        domIndex: 0,
        id: "fm-sms-login-id",
        name: "fm-sms-login-id",
        placeholder: "请输入手机号",
        className: "fm-text",
        rect: { x: 379, y: 398, width: 300, height: 29 },
      },
      {
        domIndex: 2,
        id: "search-bar-input",
        name: "keywords",
        placeholder: "请输入关键词",
        className: "search-input",
        formAction: "https://s.1688.com/selloffer/offer_search.htm",
        rect: { x: 248, y: 122, width: 640, height: 42 },
      },
    ]);

    expect(winner?.name).toBe("keywords");
  });
});

describe("pickBestSearchSubmitCandidate", () => {
  it("prefers the search button next to the input", () => {
    const winner = pickBestSearchSubmitCandidate(
      [
        {
          domIndex: 0,
          type: "button",
          text: "登录",
          className: "login-btn",
          rect: { x: 620, y: 398, width: 80, height: 32 },
        },
        {
          domIndex: 1,
          type: "button",
          text: "搜索",
          className: "search-btn",
          formAction: "https://s.1688.com/selloffer/offer_search.htm",
          rect: { x: 908, y: 122, width: 96, height: 42 },
        },
      ],
      { x: 248, y: 122, width: 640, height: 42 },
    );

    expect(winner?.text).toBe("搜索");
  });
});

describe("looksLikeLoginInterstitial", () => {
  it("detects login overlays from text and visible login inputs", () => {
    expect(
      looksLikeLoginInterstitial({
        url: "https://www.1688.com/",
        bodyText: "短信登录 请输入手机号 请输入验证码",
        inputCandidates: [
          {
            id: "fm-sms-login-id",
            name: "fm-sms-login-id",
            placeholder: "请输入手机号",
            rect: { x: 379, y: 398, width: 300, height: 29 },
          },
        ],
      }),
    ).toBe(true);
  });
});