import { render, screen } from "@testing-library/react";
import { vi, describe, it, expect, beforeEach } from "vitest";
import CheckinPage from "../page";

const getBranding = vi.fn();
vi.mock("@/lib/checkin/api", () => ({
  checkinApi: { getBranding: (...a: unknown[]) => getBranding(...a) },
}));

// The interactive form is exercised in Task 3/4; stub it so this test focuses
// on the server branding states.
vi.mock("../CheckinForm", () => ({
  CheckinForm: ({ token }: { token: string }) => (
    <div data-testid="checkin-form">form for {token}</div>
  ),
}));

// Inner payload of CheckinBranding (the endpoint wraps it in `{ data }`).
const HAPPY = {
  name: "Wax & Wane Records",
  logo: "https://cdn.test/logo.png",
  description: null,
  hours: "Mon–Sat 10–6",
  status_visibility: "live",
  terms_version: "2026-01",
  checkin_enabled: true,
  checkin_paused: false,
};

async function renderPage(token = "tok123") {
  const ui = await CheckinPage({ params: Promise.resolve({ token }) });
  return render(ui);
}

describe("CheckinPage branding states", () => {
  beforeEach(() => {
    getBranding.mockReset();
  });

  it("renders store name, logo, and the form on the happy path", async () => {
    getBranding.mockResolvedValue({ data: HAPPY });
    await renderPage("tok123");

    expect(screen.getByText("Wax & Wane Records")).toBeInTheDocument();
    // The wizard is lazy-loaded (next/dynamic), so await its chunk.
    expect(await screen.findByTestId("checkin-form")).toHaveTextContent(
      "form for tok123",
    );
    expect(getBranding).toHaveBeenCalledWith("tok123");
  });

  it("renders a dead-link message on 410", async () => {
    getBranding.mockRejectedValue({ status: 410, message: "Gone" });
    await renderPage();

    expect(
      screen.getByText(/no longer active/i),
    ).toBeInTheDocument();
    expect(screen.queryByTestId("checkin-form")).not.toBeInTheDocument();
  });

  it("renders the paused notice on 423", async () => {
    getBranding.mockRejectedValue({ status: 423, message: "Locked" });
    await renderPage();

    expect(screen.getByText(/not accepting check-ins/i)).toBeInTheDocument();
    expect(screen.queryByTestId("checkin-form")).not.toBeInTheDocument();
  });

  it("renders the paused notice when branding reports the lane paused", async () => {
    getBranding.mockResolvedValue({ data: { ...HAPPY, checkin_paused: true } });
    await renderPage();

    expect(screen.getByText(/not accepting check-ins/i)).toBeInTheDocument();
    expect(screen.queryByTestId("checkin-form")).not.toBeInTheDocument();
  });

  it("renders the paused notice when the lane is disabled", async () => {
    getBranding.mockResolvedValue({ data: { ...HAPPY, checkin_enabled: false } });
    await renderPage();

    expect(screen.getByText(/not accepting check-ins/i)).toBeInTheDocument();
  });
});
