import { describe, expect, it, beforeEach } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { MemoryRouter } from "react-router-dom";
import { useApplicantRegistrationState } from "./useApplicantRegistrationState";
import {
  APPLICANT_CASE_ID_SESSION_KEY,
  APPLICANT_REPORT_STEP_SESSION_KEY,
} from "@/lib/applicantRegistrationSession";

function wrapperWithRoute(initialEntry: string) {
  return function Wrapper({ children }: { children: ReactNode }) {
    return <MemoryRouter initialEntries={[initialEntry]}>{children}</MemoryRouter>;
  };
}

describe("useApplicantRegistrationState", () => {
  beforeEach(() => {
    sessionStorage.clear();
  });

  it("resets to a fresh registration on /dashboard without explicit caseId", async () => {
    sessionStorage.setItem(APPLICANT_CASE_ID_SESSION_KEY, "CASE-OLD-123");
    sessionStorage.setItem(APPLICANT_REPORT_STEP_SESSION_KEY, "1");

    const { result } = renderHook(() => useApplicantRegistrationState(), {
      wrapper: wrapperWithRoute("/dashboard"),
    });

    await waitFor(() => {
      expect(result.current.applicationCaseId).toBe("");
    });
    expect(result.current.activeApplicantTab).toBe("report");
    expect(result.current.reportStepCompleted).toBe(false);
    expect(sessionStorage.getItem(APPLICANT_CASE_ID_SESSION_KEY)).toBeNull();
    expect(sessionStorage.getItem(APPLICANT_REPORT_STEP_SESSION_KEY)).toBeNull();
  });

  it("keeps resume flow when caseId is explicitly provided in URL", async () => {
    const { result } = renderHook(() => useApplicantRegistrationState(), {
      wrapper: wrapperWithRoute("/dashboard?caseId=CASE-KEEP-1"),
    });

    await waitFor(() => {
      expect(result.current.applicationCaseId).toBe("CASE-KEEP-1");
    });
  });

  it("keeps application tab after report « Tiếp theo » (no reset from reportStepCompleted)", async () => {
    const { result } = renderHook(() => useApplicantRegistrationState(), {
      wrapper: wrapperWithRoute("/dashboard"),
    });

    await waitFor(() => {
      expect(result.current.reportStepCompleted).toBe(false);
    });

    await act(async () => {
      result.current.handleReportNext();
    });

    expect(result.current.reportStepCompleted).toBe(true);
    expect(result.current.activeApplicantTab).toBe("application");
  });
});
