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

test("API login shows correct TUTOR dashboard", async ({ page }) => {
  const errors: string[] = [];
  page.on("pageerror", (err) => errors.push(err.message));

  // Login via API
  const loginRes = await page.request.post("http://localhost:3000/api/auth/login", {
    data: { email: "testtutora2026@example.com", password: "Test1234!" },
    headers: { "Content-Type": "application/json", Accept: "application/json" },
  });
  const loginData = await loginRes.json();
  const token = loginData.access_token;
  const role = loginData.user?.active_role || "TUTOR";

  // Inject auth
  await page.goto("http://localhost:3000/");
  await page.waitForLoadState("networkidle");
  await page.evaluate(
    ({ token, role }) => {
      const payload = {
        email: "testtutora2026@example.com",
        fullName: "Test User",
        roleKey: role.toLowerCase(),
        role: role.toLowerCase(),
        active_role: role,
        selectedProfessionalRole: role,
        user: { id: "test-id", email: "testtutora2026@example.com", full_name: "Test User", active_role: role },
      };
      window.sessionStorage.setItem("nxtgauge_access_token", token);
      window.sessionStorage.setItem("nxtgauge_frontend_access_token", token);
      window.localStorage.setItem("nxtgauge_auth_user", JSON.stringify(payload));
      window.localStorage.setItem("nxtgauge_user", JSON.stringify(payload));
      window.localStorage.setItem("nxtgauge_signup_profile_v1", JSON.stringify(payload));
    },
    { token, role }
  );

  // Navigate to dashboard
  await page.goto(`http://localhost:3000/dashboard?role=${role}`);
  await page.waitForLoadState("domcontentloaded");
  await page.waitForTimeout(3000);
  await page.screenshot({ path: "test-results/dashboard-tutor-check.png", fullPage: true });

  // Check sidebar
  const aside = page.locator("aside");
  const asideCount = await aside.count();
  console.log("Aside count:", asideCount);

  if (asideCount > 0) {
    // Check Active Role badge
    const activeRoleText = await aside.locator("text=Active Role").locator("..").locator("p").last().textContent().catch(() => "NOT FOUND");
    console.log("Active Role:", activeRoleText);

    // Check sidebar items
    const buttons = await aside.locator("nav button").allTextContents();
    console.log("Sidebar items:", buttons.join(", "));

    // Assertions
    expect(activeRoleText?.toUpperCase()).toContain(role);
    expect(buttons).toContain("Leads");
    expect(buttons).not.toContain("Jobs"); // TUTOR has Leads, not Jobs
  }

  if (errors.length > 0) {
    console.log("Page errors:", errors.slice(0, 3));
  }
});