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

const formatToday = () => {
  const today = new Date();
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const day = String(today.getDate()).padStart(2, "0");
  const year = today.getFullYear();
  return `${month}/${day}/${year}`;
};

export async function acceptEulaIfPresent(page) {
  const eulaDialog = page.getByRole("dialog", { name: "Terms and Conditions" });

  const eulaVisible =
    (await eulaDialog.isVisible().catch(() => false)) ||
    (await eulaDialog
      .waitFor({
        state: "visible",
        timeout: 5000
      })
      .then(() => true)
      .catch(() => false));

  if (!eulaVisible) {
    return;
  }

  const markdownCard = page.locator(".eula-markdown-card");
  await markdownCard.evaluate((element) => {
    element.scrollTop = element.scrollHeight;
    element.dispatchEvent(new Event("scroll", { bubbles: true }));
  });

  await page.getByRole("textbox", { name: "First Name" }).fill("Codex");
  await page.getByRole("textbox", { name: "Last Name" }).fill("Tester");
  await page.getByRole("textbox", { name: "Legal Business Name" }).fill("Codex QA");
  await page.getByRole("textbox", { name: "Date Accepted" }).fill(formatToday());
  await page.getByRole("checkbox", { name: "I accept the terms and conditions of this agreement." }).check();

  const acceptButton = page.getByRole("button", { name: "Accept EULA" });
  await expect(acceptButton).toBeEnabled({ timeout: 10000 });
  await acceptButton.click();
  await expect(eulaDialog).not.toBeVisible({ timeout: 10000 });
}

export async function login(page, { email, password }) {
  // Navigate to the login page
  await page.goto("/"); // Adjust if your login route differs (e.g., '/login')

  // Fill email field
  await page.fill('input[placeholder="Username"]', email); // Matches Ant Design Input placeholder

  // Fill password field
  await page.fill('input[placeholder="Password"]', password);

  // Click login button
  await page.click("button.login-btn");

  // Wait for navigation or success indicator (e.g., redirect to /manage/)
  await page.waitForURL(/\/manage\//, { timeout: 10000 }); // Adjust based on redirect

  await acceptEulaIfPresent(page);

  // Verify successful login (e.g., check for a dashboard element)
  await expect(page.locator("text=Manage")).toBeVisible(); // Adjust to your app’s post-login UI
}
