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

test.describe("Admin shell layout", () => {
  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      window.localStorage.setItem("locale", "ko");
      window.localStorage.setItem("admin_session", "fake-token");
      (
        window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
      )._IS_TEST_MODE = true;

      const authority = "http://localhost:5000/oidc";
      const client_id = "adminfront";
      const key = `oidc.user:${authority}:${client_id}`;
      window.localStorage.setItem(
        key,
        JSON.stringify({
          access_token: "fake-token",
          token_type: "Bearer",
          profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
          expires_at: Math.floor(Date.now() / 1000) + 36000,
        }),
      );
    });

    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin-user",
            name: "Admin",
            role: "super_admin",
            manageableTenants: [],
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: { items: [], total: 0, limit: 1000, offset: 0 },
          headers,
        });
      }

      return route.fulfill({ json: { items: [], total: 0 }, headers });
    });

    await page.route("**/oidc/**", async (route) => {
      await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
    });
  });

  test("keeps navigation in the left sidebar without covering content", async ({
    page,
  }) => {
    await page.setViewportSize({ width: 900, height: 700 });
    await page.goto("/tenants");

    const sidebar = page.locator("aside").first();
    const main = page.locator("main").first();

    await expect(sidebar).toBeVisible();
    await expect(main).toBeVisible();

    const sidebarBox = await sidebar.boundingBox();
    const mainBox = await main.boundingBox();

    expect(sidebarBox).not.toBeNull();
    expect(mainBox).not.toBeNull();
    expect(sidebarBox?.x).toBeLessThanOrEqual(1);
    expect(sidebarBox?.width).toBeLessThanOrEqual(260);
    expect(mainBox?.x).toBeGreaterThanOrEqual(
      (sidebarBox?.x ?? 0) + (sidebarBox?.width ?? 0) - 1,
    );
  });
});
