import { chromium } from "@playwright/test";

const baseUrl = process.env.SITE_URL || "http://localhost:3000";

async function dialogIsVisible(page) {
  return page.getByRole("dialog").isVisible().catch(() => false);
}

async function closeDialog(page) {
  await page.getByRole("button", { name: "Close cash offer form" }).click();
  await page.locator(".modal-layer").waitFor({ state: "hidden" });
}

const browser = await chromium.launch({
  executablePath: process.env.CHROMIUM_PATH || "/usr/bin/chromium",
  headless: true,
});
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });

try {
  await page.goto(baseUrl, { waitUntil: "networkidle" });

  if (!(await dialogIsVisible(page))) {
    throw new Error("Expected the shared cash-offer dialog to be open on initial load.");
  }

  await closeDialog(page);
  if (await dialogIsVisible(page)) {
    throw new Error("Expected the shared cash-offer dialog to close before trigger checks.");
  }

  const floatingOfferButton = page.locator(".mobile-fab");
  await floatingOfferButton.scrollIntoViewIfNeeded();
  await floatingOfferButton.click();
  if (!(await dialogIsVisible(page))) {
    throw new Error("The floating cash-offer button did not open the shared dialog.");
  }

  await closeDialog(page);
  await page.goto(`${baseUrl}/sell-as-is.html`, { waitUntil: "networkidle" });
  if (!(await dialogIsVisible(page))) {
    throw new Error("Expected the shared cash-offer dialog to be open on the seller-education page.");
  }

  await closeDialog(page);
  const hashOfferLink = page.locator('.content-cta a[href="/#offer-form"]').first();
  if ((await hashOfferLink.count()) === 0) {
    throw new Error("Expected at least one hash-based cash-offer link on the seller-education page.");
  }

  await hashOfferLink.click();
  if (!(await dialogIsVisible(page))) {
    throw new Error("The hash-based cash-offer link did not open the shared dialog.");
  }

  console.log("Verified floating and hash-based cash-offer triggers open the shared dialog.");
} finally {
  await browser.close();
}
