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

const E2E_API = process.env.MATRIX_CLIENT_PC_E2E_API || "http://127.0.0.1:8767";

async function api(path: string, init: RequestInit = {}): Promise<any> {
  const res = await fetch(E2E_API + path, init);
  if (!res.ok) {
    const body = await res.text();
    throw new Error(`E2E API ${path} -> ${res.status}: ${body}`);
  }
  return res.json();
}

test.describe("Entry flow — LoginScreen → click Sign in → HomeScreen with rooms", () => {
  test.beforeEach(async () => {
    // Reset backend state: wipe last_user so frontend lands on LoginScreen.
    await api("/wipe_session", { method: "POST" });
  });

  test("user can sign in and see their rooms", async ({ page }) => {
    await page.goto("/", { waitUntil: "domcontentloaded" });

    // LoginScreen visible
    await expect(page.getByRole("heading", { name: "matrix_client_pc" })).toBeVisible({
      timeout: 10_000,
    });
    const signInBtn = page.getByRole("button", { name: /Sign in with Matrix/i });
    await expect(signInBtn).toBeVisible();

    // Click Sign in → shim calls /signin_admin → returns user_id
    await signInBtn.click();

    // HomeScreen header buttons appear once authenticated.
    await expect(page.getByRole("button", { name: /Health/i })).toBeVisible({
      timeout: 15_000,
    });
    await expect(page.getByRole("button", { name: /Logs/i })).toBeVisible();
    await expect(page.getByRole("button", { name: /Logout/i })).toBeVisible();

    // Sidebar has at least one room (rooms are fetched after Start triggers sync).
    const firstRoom = page.locator('nav a, [role="navigation"] a').first();
    await expect(firstRoom).toBeVisible({ timeout: 30_000 });

    // Backend sanity: diagnostics says we're synced with rooms.
    const diag = await api("/diagnostics");
    expect(diag.started).toBe(true);
    expect(diag.rooms_count).toBeGreaterThan(0);
  });

  test("Logout returns to LoginScreen", async ({ page }) => {
    await page.goto("/", { waitUntil: "domcontentloaded" });

    // Sign in first
    await page.getByRole("button", { name: /Sign in with Matrix/i }).click();
    await expect(page.getByRole("button", { name: /Logout/i })).toBeVisible({
      timeout: 15_000,
    });

    // Logout
    await page.getByRole("button", { name: /Logout/i }).click();

    // Back to LoginScreen
    await expect(page.getByRole("button", { name: /Sign in with Matrix/i })).toBeVisible({
      timeout: 10_000,
    });
  });
});
