import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { storeAdminSession } from "../lib/adminSession";
import { adminApi } from "../lib/api";
import AppRoutes from "../routes";

vi.mock("../lib/api", () => ({
  adminApi: {
    get: vi.fn(),
  },
}));

describe("AdminLayout", () => {
  beforeEach(() => {
    localStorage.clear();
    vi.clearAllMocks();
    storeAdminSession({
      expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
      operatorEmail: "ops@xtablo.com",
      operatorId: "operator-1",
      role: "operator",
      sessionToken: "admin-session-token",
    });
    vi.mocked(adminApi.get).mockResolvedValue({
      data: {
        alerts: [],
        metrics: [],
        shortcuts: [],
      },
    });
  });

  it("shows the production badge and admin sections", async () => {
    render(
      <MemoryRouter initialEntries={["/"]}>
        <AppRoutes />
      </MemoryRouter>
    );

    expect(await screen.findByText(/^production$/i)).toBeInTheDocument();
    expect(
      screen.getByRole("heading", {
        name: /production command deck for privileged supabase operations/i,
      })
    ).toBeInTheDocument();
    expect(screen.getByRole("link", { name: /operations home/i })).toBeInTheDocument();
    expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument();
    expect(screen.getByRole("link", { name: /analytics studio/i })).toBeInTheDocument();
    expect(screen.getByRole("link", { name: /action center/i })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: /lock admin app/i })).toBeInTheDocument();
  });

  it("clears the stored admin session when locking the app", async () => {
    render(
      <MemoryRouter initialEntries={["/"]}>
        <AppRoutes />
      </MemoryRouter>
    );

    const button = await screen.findByRole("button", { name: /lock admin app/i });
    fireEvent.click(button);

    expect(localStorage.getItem("xtablo-admin-session")).toBeNull();
  });
});
