import { chromium } from "playwright";

const FEATHERY_CLICK = { noWaitAfter: true as const };

async function featheryFill(
  page: import("playwright").Page,
  selector: string,
  value: string,
): Promise<void> {
  const field = page.locator(`#container-mh ${selector}`).first();
  await field.click(FEATHERY_CLICK);
  await field.fill("");
  await field.fill(value);
  await field.evaluate((el) => {
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
    el.dispatchEvent(new Event("blur", { bubbles: true }));
  });
}

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" });
  await page.waitForTimeout(1000);

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

  const values = await page.evaluate(() => ({
    origin: (document.querySelector("#container-mh #origin-zip") as HTMLInputElement)?.value,
    dest: (document.querySelector("#container-mh #destination-zip") as HTMLInputElement)?.value,
    date: (document.querySelector("#container-mh #pickup-date") as HTMLInputElement)?.value,
    email: (document.querySelector("#container-mh #business-email") as HTMLInputElement)?.value,
    phone: (document.querySelector("#container-mh #client-phone") as HTMLInputElement)?.value,
    ltl: (document.querySelector("#container-mh #cb_st_ltl") as HTMLInputElement)?.checked,
  }));
  console.log("values:", values);

  const btn = page
    .locator("#container-mh")
    .getByRole("button", { name: /GET INSTANT QUOTES/i })
    .first();
  console.log("btn visible:", await btn.isVisible());
  console.log("btn enabled:", await btn.isEnabled());

  await btn.click(FEATHERY_CLICK);
  await page.waitForTimeout(3000);

  console.log("url:", page.url());
  console.log("length visible:", await page.locator("#container-mh #length").isVisible().catch(() => false));

  const errors = await page.evaluate(() =>
    [...document.querySelectorAll("[class*='error'],[role='alert']")]
      .map((e) => e.textContent?.trim())
      .filter(Boolean)
      .slice(0, 10),
  );
  console.log("errors:", errors);

  await browser.close();
}

main().catch(console.error);
