import type { JSX } from "solid-js";
import { createUniqueId, onCleanup, onMount, splitProps } from "solid-js";
import { useWizardContext, WizardStepContextProvider, type WizardStepContextValue } from "./wizard-context";
import type { WizardStepProps } from "./wizard.props";

/** A single step container. Provides per-step context to its children. */
export function WizardStep(props: WizardStepProps): JSX.Element {
  const [local, rest] = splitProps(props, ["index", "disabled", "completed", "children"]);
  const ctx = useWizardContext();

  const triggerId = `${ctx.baseId}-trigger-${local.index}`;
  const contentId = `${ctx.baseId}-content-${local.index}`;

  const isActive = () => ctx.currentStep() === local.index;
  const isCompleted = () => local.completed ?? ctx.completedSteps().has(local.index);
  const isDisabled = () => local.disabled ?? false;

  const dataState = () => {
    if (isActive()) return "active";
    if (isCompleted()) return "completed";
    return "upcoming";
  };

  onMount(() => { ctx.registerStep(); });
  onCleanup(() => { ctx.unregisterStep(); });

  const stepCtx: WizardStepContextValue = {
    index: local.index,
    isActive,
    isCompleted,
    isDisabled,
    triggerId,
    contentId,
  };

  return (
    <WizardStepContextProvider value={stepCtx}>
      <div
        data-state={dataState()}
        data-disabled={isDisabled() || undefined}
        {...rest}
      >
        {local.children}
      </div>
    </WizardStepContextProvider>
  );
}
