import { chromium } from "playwright";

const FEATHERY_CLICK = { noWaitAfter: true as const };

async function typeField(page: import("playwright").Page, sel: string, value: string) {
  const loc = page.locator(`#container-mh ${sel}`).first();
  await loc.click(FEATHERY_CLICK);
  await loc.fill("");
  await loc.pressSequentially(value, { delay: 30 });
  await loc.evaluate((el, v) => {
    const input = el as HTMLInputElement;
    const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
    setter?.call(input, v);
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
    input.dispatchEvent(new Event("blur", { bubbles: true }));
  }, value);
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto("https://www.priority1.com/instant-freight-quotes/#New%20Step%201", {
    waitUntil: "domcontentloaded",
  });
  await page.locator("#container-mh").waitFor();
  await page.waitForTimeout(1500);

  await page.locator("#container-mh").getByText(/Less Than Truckload/i).first().click(FEATHERY_CLICK);
  await page.waitForTimeout(800);
  await typeField(page, "#origin-zip", "10118");
  await typeField(page, "#destination-zip", "90017");
  await page.locator("#container-mh #freight-shipment").selectOption("One Time Shipment");
  await typeField(page, "#pickup-date", "07/01/2026");
  await typeField(page, "#business-email", "niqijiti542@gmail.com");
  await typeField(page, "#client-phone", "5551234567");

  const btn = page.locator("#container-mh").getByRole("button", { name: /GET INSTANT QUOTES/i }).first();
  await Promise.race([
    btn.click({ timeout: 15_000 }).catch(() => undefined),
    page.waitForTimeout(15_000),
  ]);
  await page.waitForTimeout(3000);

  const diag = await page.evaluate(() => {
    const texts = [...document.querySelectorAll("body *")]
      .map((el) => el.textContent?.trim() || "")
      .filter((t) => /required|invalid|error|please|must/i.test(t) && t.length < 120);
    return {
      url: location.href,
      lengthVisible: !!document.querySelector("#container-mh #length"),
      errors: [...new Set(texts)].slice(0, 15),
    };
  });
  console.log(JSON.stringify(diag, null, 2));
  await browser.close();
}

main().catch(console.error);
