import { chromium } from "playwright";

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({ state: "visible", timeout: 60_000 });
  await page.waitForTimeout(2000);

  const before = await page.evaluate(() => {
    return [...document.querySelectorAll("#origin-zip")].map((el, i) => {
      const input = el as HTMLInputElement;
      const r = el.getBoundingClientRect();
      return {
        i,
        inMh: !!el.closest("#container-mh"),
        visible: r.width > 0 && r.height > 0,
        disabled: input.disabled,
        value: input.value,
      };
    });
  });
  console.log("before LTL:", JSON.stringify(before, null, 2));

  await page.locator("#cb_st_ltl").click({ noWaitAfter: true });
  await page.waitForTimeout(1500);
  await page.locator("#container-mh #origin-zip").waitFor({ state: "visible" });

  const after = await page.evaluate(() => {
    return [...document.querySelectorAll("#origin-zip")].map((el, i) => {
      const input = el as HTMLInputElement;
      const r = el.getBoundingClientRect();
      return {
        i,
        inMh: !!el.closest("#container-mh"),
        visible: r.width > 0 && r.height > 0,
        disabled: input.disabled,
        value: input.value,
      };
    });
  });
  console.log("after LTL:", JSON.stringify(after, null, 2));

  const loc = page.locator("#container-mh #origin-zip").first();
  console.log("visible:", await loc.isVisible());
  console.log("enabled:", await loc.isEnabled());

  try {
    await loc.click({ noWaitAfter: true });
    await loc.fill("10118", { timeout: 10_000, force: true });
    console.log("fill ok, value:", await loc.inputValue());
  } catch (e) {
    console.log("fill failed:", e instanceof Error ? e.message : e);
  }

  const loc2 = page.locator("#container-mh #origin-zip").first();
  try {
    await loc2.click({ noWaitAfter: true });
    await loc2.pressSequentially("10118", { delay: 30 });
    await loc2.evaluate((el) => {
      el.dispatchEvent(new Event("input", { bubbles: true }));
      el.dispatchEvent(new Event("change", { bubbles: true }));
      el.dispatchEvent(new Event("blur", { bubbles: true }));
    });
    console.log("sequential ok, value:", await loc2.inputValue());
  } catch (e) {
    console.log("sequential failed:", e instanceof Error ? e.message : e);
  }

  await browser.close();
}

main().catch(console.error);
