import { render, screen, fireEvent } from "@testing-library/react";
import SimpleProgram from "../../../src/pages/SimpleProgram/SimpleProgram";
import useProgramStore from "../../../src/utils/programStore";

/**
 * Helper to preload the program store before rendering.
 */
function loadProgram(phases: Record<string, unknown>[]) {
  useProgramStore.getState().setProgramState({ phases });
}

describe("SimpleProgram", () => {
  beforeEach(() => {
    loadProgram([]);
  });

  test("shows empty state when no program is loaded", () => {
    render(<SimpleProgram />);
    expect(screen.getByText("No program loaded.")).toBeInTheDocument();
  });

  test("renders first phase content", () => {
    loadProgram([
      {
        id: "phase-1",
        norms: [{ id: "n1", norm: "Be polite" }],
        goals: [{ id: "g1", description: "Finish task", achieved: true }],
        triggers: [{ id: "t1", label: "Keyword trigger" }],
      },
    ]);

    render(<SimpleProgram />);

    expect(screen.getByText("Phase 1 / 1")).toBeInTheDocument();
    expect(screen.getByText("Be polite")).toBeInTheDocument();
    expect(screen.getByText("Finish task")).toBeInTheDocument();
    expect(screen.getByText("Keyword trigger")).toBeInTheDocument();
  });

  test("allows navigating between phases", () => {
    loadProgram([
      {
        id: "phase-1",
        norms: [],
        goals: [],
        triggers: [],
      },
      {
        id: "phase-2",
        norms: [{ id: "n2", norm: "Be careful" }],
        goals: [],
        triggers: [],
      },
    ]);

    render(<SimpleProgram />);

    expect(screen.getByText("Phase 1 / 2")).toBeInTheDocument();

    fireEvent.click(screen.getByText("Next ▶"));

    expect(screen.getByText("Phase 2 / 2")).toBeInTheDocument();
    expect(screen.getByText("Be careful")).toBeInTheDocument();
  });

  test("prev button is disabled on first phase", () => {
    loadProgram([
      { id: "phase-1", norms: [], goals: [], triggers: [] },
    ]);

    render(<SimpleProgram />);
    expect(screen.getByText("◀ Prev")).toBeDisabled();
  });

  test("next button is disabled on last phase", () => {
    loadProgram([
      { id: "phase-1", norms: [], goals: [], triggers: [] },
    ]);

    render(<SimpleProgram />);
    expect(screen.getByText("Next ▶")).toBeDisabled();
  });
});
