import { expect, type BrowserContext, type Page } from "@playwright/test";

import {
  defaultCharacterChatPath,
  defaultCharacterChatUrl,
  defaultCharacterSplashPath,
  seedEmailSession,
} from "./auth";

export async function clearBrowserState(context: BrowserContext, page: Page, baseURL?: string) {
  await context.clearCookies();
  const client = await context.newCDPSession(page);
  const origins = new Set([new URL(baseURL ?? "http://127.0.0.1:3000").origin, "http://127.0.0.1:3000", "http://localhost:3000"]);
  for (const origin of origins) {
    await client.send("Storage.clearDataForOrigin", { origin, storageTypes: "all" }).catch(() => {});
  }
}

export async function enterChatFromSplash(page: Page, options: { expectedUrl?: RegExp; timeout?: number; waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle" } = {}) {
  const {
    expectedUrl = defaultCharacterChatUrl,
    timeout = 10_000,
    waitUntil,
  } = options;
  await page.goto(defaultCharacterSplashPath, { waitUntil });
  const startChatButton = page.getByRole("button", { name: "Start Chatting" });
  await expect(startChatButton).toBeVisible({ timeout });
  await expect(startChatButton).toBeEnabled();
  for (let attempt = 0; attempt < 3; attempt += 1) {
    await startChatButton.click({ timeout: 3_000 }).catch(() => {});
    try { await expect(page).toHaveURL(expectedUrl, { timeout: 3_000 }); return; } catch { await page.waitForTimeout(500); }
  }
  await expect(page).toHaveURL(expectedUrl, { timeout });
}

export async function dismissChatInterruptions(page: Page) {
  for (const buttonName of ["Later", "Cancel", "OK"]) {
    const button = page.getByRole("button", { name: buttonName }).first();
    if (await button.isVisible().catch(() => false)) await button.click();
  }
}

export async function signInWithEmailAndOpenChat(page: Page) {
  await seedEmailSession(page);
  await page.goto(defaultCharacterChatPath);
  await dismissChatInterruptions(page);
  await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled({ timeout: 20_000 });
}
