import type { Accessor } from "solid-js";
import { createContext, useContext } from "solid-js";

/** Shared state provided by WizardRoot to all descendant wizard parts. */
export interface WizardContextValue {
  currentStep: Accessor<number>;
  completedSteps: Accessor<Set<number>>;
  totalSteps: Accessor<number>;
  linear: Accessor<boolean>;
  orientation: Accessor<"horizontal" | "vertical">;
  registerStep: () => number;
  unregisterStep: () => void;
  goToStep: (index: number) => void;
  goToNext: () => void;
  goToPrev: () => void;
  isStepReachable: (index: number) => boolean;
  baseId: string;
}

/** Per-step state provided by WizardStep to its trigger, content, etc. */
export interface WizardStepContextValue {
  index: number;
  isActive: Accessor<boolean>;
  isCompleted: Accessor<boolean>;
  isDisabled: Accessor<boolean>;
  triggerId: string;
  contentId: string;
}

const WizardContext = createContext<WizardContextValue>();
const WizardStepContext = createContext<WizardStepContextValue>();

/** Returns the Wizard root context. Throws if used outside <Wizard>. */
export function useWizardContext(): WizardContextValue {
  const ctx = useContext(WizardContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] Wizard parts must be used within <Wizard>. Fix: Wrap Wizard.Step, Wizard.StepList, and Wizard.StepContent inside <Wizard>.",
    );
  }
  return ctx;
}

/** Returns the WizardStep context. Throws if used outside <Wizard.Step>. */
export function useWizardStepContext(): WizardStepContextValue {
  const ctx = useContext(WizardStepContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] Wizard step parts must be used within <Wizard.Step>. Fix: Wrap Wizard.StepTrigger and Wizard.StepContent inside <Wizard.Step>.",
    );
  }
  return ctx;
}

export const WizardContextProvider = WizardContext.Provider;
export const WizardStepContextProvider = WizardStepContext.Provider;
