import { useState } from "react";
import { CheckboxOption } from "../../src/components/ui/Checkbox";

// First real component test — mounts CheckboxOption in isolation (no
// router, no backend), unlike everything under cypress/e2e/ which always
// visits a full routed page. See cypress.config.ts's `component` block.

describe("CheckboxOption", () => {
  it("renders its label content", () => {
    cy.mount(
      <CheckboxOption checked={false} onChange={() => {}}>
        Végétarien
      </CheckboxOption>,
    );

    cy.contains("label", "Végétarien").should("be.visible");
  });

  it("reflects the checked prop on the native input, and the is-selected class", () => {
    cy.mount(
      <CheckboxOption checked={false} onChange={() => {}}>
        Végétarien
      </CheckboxOption>,
    );
    cy.get("input[type=checkbox]").should("not.be.checked");
    cy.get("label").should("not.have.class", "is-selected");

    cy.mount(
      <CheckboxOption checked={true} onChange={() => {}}>
        Végétarien
      </CheckboxOption>,
    );
    cy.get("input[type=checkbox]").should("be.checked");
    cy.get("label").should("have.class", "is-selected");
  });

  it("calls onChange with the toggled value when clicked", () => {
    const onChange = cy.stub().as("onChange");
    cy.mount(
      <CheckboxOption checked={false} onChange={onChange}>
        Végétarien
      </CheckboxOption>,
    );

    cy.get("input[type=checkbox]").click();

    cy.get("@onChange").should("have.been.calledOnceWith", true);
  });

  it("is a controlled component — stays checked only while the parent says so", () => {
    // A tiny stateful wrapper, since CheckboxOption itself takes no
    // internal state — this is what actually exercises the checked/onChange
    // contract the way a real caller (AllergySelect, the theme picker…)
    // would.
    function Wrapper() {
      const [checked, setChecked] = useState(false);
      return (
        <CheckboxOption checked={checked} onChange={setChecked}>
          Végétarien
        </CheckboxOption>
      );
    }
    cy.mount(<Wrapper />);

    cy.get("input[type=checkbox]").should("not.be.checked").click();
    cy.get("input[type=checkbox]").should("be.checked");
  });
});
