import { expect, test } from "../../../frontend/node_modules/@playwright/test/index.mjs";

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => {
    const originalFetch = window.fetch.bind(window);
    const jsonResponse = (body, status = 200) =>
      new Response(JSON.stringify(body), {
        status,
        headers: { "content-type": "application/json" },
      });

    window.fetch = (resource, options) => {
      const requestUrl = typeof resource === "string" ? resource : resource?.url || "";
      const url = new URL(requestUrl, window.location.origin);
      if (url.pathname === "/api/auth/config") {
        return Promise.resolve(jsonResponse({ enabled: true, reset_url: "https://sso.example.dev/reset" }));
      }
      if (url.pathname === "/api/lab/status") {
        if (window.__LAB_STATUS_FAIL__) {
          return Promise.resolve(jsonResponse({ error: "status 503" }, 503));
        }
        return Promise.resolve(
          jsonResponse({
            connected: true,
            atlas: { up: true, known: true },
            active_service: { known: true, label: "Nextcloud", url: "https://cloud.bstein.dev", window: "15m" },
            dedicated_hosts: {
              known: true,
              up: true,
              up_count: 2,
              total: 2,
              hosts: [
                { label: "Database node", known: true, up: true },
                { label: "Jumphost", known: true, up: true },
              ],
            },
            checked_at: 1000,
          }),
        );
      }
      return originalFetch(resource, options);
    };
  });

  await page.route("**/api/auth/config", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({ enabled: true, reset_url: "https://sso.example.dev/reset" }),
    });
  });
  await page.route("**/api/lab/status*", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        connected: true,
        atlas: { up: true, known: true },
        active_service: { known: true, label: "Nextcloud", url: "https://cloud.bstein.dev", window: "15m" },
        dedicated_hosts: {
          known: true,
          up: true,
          up_count: 2,
          total: 2,
          hosts: [
            { label: "Database node", known: true, up: true },
            { label: "Jumphost", known: true, up: true },
          ],
        },
        checked_at: 1000,
      }),
    });
  });
});

test("shows Brad's professional homepage and opens the platform diagram overlay", async ({ page }) => {
  await page.goto("/", { waitUntil: "domcontentloaded" });

  await expect(page.getByRole("heading", { name: "Brad Stein" })).toBeVisible();
  await expect(page.getByRole("heading", { name: "Senior SDET / DevOps Automation Engineer" })).toBeVisible();
  await expect(page.getByRole("link", { name: "Discuss a Project" })).toBeVisible();
  await expect(page.getByRole("link", { name: "View Résumé" })).toBeVisible();
  await expect(page.getByRole("link", { name: "Explore the Live Platform" })).toBeVisible();
  await expect(page.getByRole("button", { name: "Login" })).toBeVisible();
  await expect(
    page.getByLabel("Primary navigation").getByRole("link", { name: "Register" }),
  ).toBeVisible();
  await expect(page.getByRole("heading", { name: "Quality Systems I Can Take From Zero to Reliable" })).toBeVisible();
  await expect(page.getByRole("link", { name: "Nextcloud", exact: true })).toBeVisible();
  await expect(page.getByText("2 of 2 online")).toBeVisible();
  await expect(page.getByText("Database machine")).toBeVisible();

  await page.getByRole("link", { name: "Explore the Live Platform" }).click();
  await expect(page.getByRole("heading", { name: "Titan Lab: Live Platform" })).toBeVisible();
  await expect(page.getByRole("link", { name: "IaC source" })).toBeVisible();
  await expect(page.getByText("Live data connected")).toBeVisible();
  await expect(page.locator(".service-grid .service").filter({ hasText: "Nextcloud" }).first()).toBeVisible();

  await page.locator("details.source-diagrams summary").click();
  const firstCard = page.locator("details.source-diagrams .mermaid-card").first();
  await expect(firstCard).toBeVisible();
  await firstCard.locator(".diagram").click();
  await expect(page.locator(".overlay")).toBeVisible();
  await page.keyboard.press("Escape");
  await expect(page.locator(".overlay")).toHaveCount(0);
});

test("keeps the homepage usable when public status fails", async ({ page }) => {
  await page.addInitScript(() => {
    window.__LAB_STATUS_FAIL__ = true;
  });
  await page.route("**/api/lab/status*", async (route) => {
    await route.fulfill({
      status: 503,
      contentType: "application/json",
      body: JSON.stringify({ error: "status 503" }),
    });
  });

  await page.goto("/", { waitUntil: "domcontentloaded" });

  await expect(page.getByRole("heading", { name: "Brad Stein" })).toBeVisible();
  await expect(page.getByText("Live status is temporarily unavailable").first()).toBeVisible();
  await expect(page.getByText("status 503")).toHaveCount(0);
});

test("serves developer and SDET homepage modes", async ({ page }) => {
  await page.goto("/developer", { waitUntil: "domcontentloaded" });
  await expect(page.getByRole("heading", { name: "Full-Stack Platform Engineer / Senior SDET" })).toBeVisible();
  await expect(page.getByText("Product and Platform Showcase")).toBeVisible();
  await expect(page.getByRole("link", { name: "Developer", exact: true })).toHaveClass(/active/);
  await page.getByRole("link", { name: "View Résumé" }).click();
  await expect(page).toHaveURL(/\/developer\/about$/);
  await expect(page.getByText("AI Services · Vue · Python · Kubernetes")).toBeVisible();

  await page.goto("/sdet", { waitUntil: "domcontentloaded" });
  await expect(page.getByRole("heading", { name: "Senior SDET / DevOps Automation Engineer" })).toBeVisible();
  await expect(page.getByText("Testing, Automation, and Platform Work")).toBeVisible();
  await expect(page.getByRole("link", { name: "SDET", exact: true })).toHaveClass(/active/);
  await page.getByRole("link", { name: "View Résumé" }).click();
  await expect(page).toHaveURL(/\/about$/);
  await expect(page.getByText("Test Automation · Release Quality · CI/CD")).toBeVisible();
});
