import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { vi, describe, it, expect, beforeEach } from "vitest";
import type { CheckinBrandingData, CheckinStatusData } from "@alqove/api-client";

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

import { CheckinForm } from "../CheckinForm";
import { StatusView } from "../s/[statusToken]/StatusPoller";

const BRANDING: CheckinBrandingData = {
  name: "Wax & Wane Records",
  logo: null,
  description: null,
  hours: null,
  status_visibility: "live",
  terms_version: "2026-01",
  checkin_enabled: true,
  checkin_paused: false,
};

function renderForm() {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  render(
    <QueryClientProvider client={qc}>
      <CheckinForm token="tok1" branding={BRANDING} />
    </QueryClientProvider>,
  );
}

async function driveToSubmit(user: ReturnType<typeof userEvent.setup>) {
  await user.type(screen.getByLabelText(/first name/i), "Ada");
  await user.type(screen.getByLabelText(/last name/i), "Lovelace");
  await user.type(screen.getByLabelText(/phone/i), "5125551234");
  await user.click(screen.getByRole("button", { name: /next/i }));
  await user.click(screen.getByRole("button", { name: /next/i }));
  await user.click(screen.getByRole("button", { name: /check in/i }));
}

describe("check-in accessibility", () => {
  beforeEach(() => {
    submit.mockReset();
    localStorage.clear();
  });

  it("moves focus to the new step heading when advancing", async () => {
    const user = userEvent.setup();
    renderForm();
    await user.type(screen.getByLabelText(/first name/i), "Ada");
    await user.type(screen.getByLabelText(/last name/i), "Lovelace");
    await user.type(screen.getByLabelText(/phone/i), "5125551234");
    await user.click(screen.getByRole("button", { name: /next/i }));

    const heading = screen.getByRole("heading", { name: /what are you bringing/i });
    expect(heading).toHaveFocus();
  });

  it("announces a submit failure via an alert region", async () => {
    const user = userEvent.setup();
    submit.mockRejectedValue(new TypeError("network down"));
    renderForm();
    await driveToSubmit(user);

    expect(await screen.findByRole("alert")).toHaveTextContent(/couldn't submit/i);
  });

  it("wraps the polling status in a polite live region", () => {
    const status: CheckinStatusData = {
      status: "queued",
      status_label: "In line",
      container_count: 1,
      queue_position: 2,
      estimated_wait_minutes: 10,
    };
    render(<StatusView status={status} />);

    const live = screen.getByRole("status");
    expect(live).toHaveAttribute("aria-live", "polite");
    expect(live).toHaveTextContent(/#2/);
  });
});
