"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { InjectedField } from "./InjectedField.js";
import { Button } from "../../primitives/button.js";
import { Spinner } from "../../primitives/spinner.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
function StepIndicator({
  steps,
  currentIndex
}) {
  const t = useT();
  return /* @__PURE__ */ jsx("nav", { "aria-label": t("ui.wizard.steps", "Steps"), className: "mb-6", children: /* @__PURE__ */ jsx("ol", { className: "flex items-center gap-2", children: steps.map((step, index) => {
    const status = index < currentIndex ? "completed" : index === currentIndex ? "current" : "pending";
    const label = t(step.label, step.label);
    return /* @__PURE__ */ jsxs("li", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsx(
        "div",
        {
          className: cn(
            "flex size-8 shrink-0 items-center justify-center rounded-full text-sm font-medium transition-colors",
            status === "completed" && "bg-primary text-primary-foreground",
            status === "current" && "border-2 border-primary bg-background text-primary",
            status === "pending" && "border border-muted-foreground/30 bg-muted text-muted-foreground"
          ),
          "aria-current": status === "current" ? "step" : void 0,
          children: status === "completed" ? /* @__PURE__ */ jsx("svg", { className: "size-4", viewBox: "0 0 16 16", fill: "currentColor", children: /* @__PURE__ */ jsx("path", { d: "M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z" }) }) : index + 1
        }
      ),
      /* @__PURE__ */ jsx(
        "span",
        {
          className: cn(
            "hidden text-sm sm:inline",
            status === "current" ? "font-medium text-foreground" : "text-muted-foreground"
          ),
          children: label
        }
      ),
      index < steps.length - 1 && /* @__PURE__ */ jsx(
        "div",
        {
          className: cn(
            "h-px w-6 sm:w-12",
            index < currentIndex ? "bg-primary" : "bg-muted-foreground/30"
          )
        }
      )
    ] }, step.id);
  }) }) });
}
function StepFieldsRenderer({
  step,
  data,
  onChange,
  context,
  fieldErrors
}) {
  if (!step.fields || step.fields.length === 0) return null;
  const fieldContext = {
    organizationId: context.organizationId,
    tenantId: context.tenantId,
    userId: context.userId,
    record: data
  };
  return /* @__PURE__ */ jsx("div", { className: "space-y-4", children: step.fields.map((field) => /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(
      InjectedField,
      {
        field,
        value: data[field.id],
        onChange,
        context: fieldContext,
        formData: data
      }
    ),
    fieldErrors[field.id] && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-destructive", children: fieldErrors[field.id] })
  ] }, field.id)) });
}
function InjectionWizard({ widget, context, onClose }) {
  const t = useT();
  const [currentStepIndex, setCurrentStepIndex] = React.useState(0);
  const [allData, setAllData] = React.useState({});
  const [validating, setValidating] = React.useState(false);
  const [completing, setCompleting] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState(null);
  const [fieldErrors, setFieldErrors] = React.useState({});
  const steps = widget.steps;
  const currentStep = steps[currentStepIndex];
  const isFirstStep = currentStepIndex === 0;
  const isLastStep = currentStepIndex === steps.length - 1;
  const handleFieldChange = React.useCallback((key, value) => {
    setAllData((prev) => ({ ...prev, [key]: value }));
    setFieldErrors((prev) => {
      if (!prev[key]) return prev;
      const next = { ...prev };
      delete next[key];
      return next;
    });
    setErrorMessage(null);
  }, []);
  const handleSetData = React.useCallback((next) => {
    setAllData(next);
    setErrorMessage(null);
    setFieldErrors({});
  }, []);
  const validateCurrentStep = React.useCallback(async () => {
    if (!currentStep?.validate) return true;
    setValidating(true);
    setErrorMessage(null);
    setFieldErrors({});
    try {
      const result = await currentStep.validate(allData, context);
      if (!result.ok) {
        setErrorMessage(result.message ?? t("ui.wizard.validationFailed", "Validation failed"));
        if (result.fieldErrors) {
          setFieldErrors(result.fieldErrors);
        }
        return false;
      }
      return true;
    } catch (err) {
      setErrorMessage(err instanceof Error ? err.message : t("ui.wizard.validationFailed", "Validation failed"));
      return false;
    } finally {
      setValidating(false);
    }
  }, [currentStep, allData, context, t]);
  const handleNext = React.useCallback(async () => {
    const valid = await validateCurrentStep();
    if (!valid) return;
    setCurrentStepIndex((prev) => Math.min(prev + 1, steps.length - 1));
    setErrorMessage(null);
    setFieldErrors({});
  }, [validateCurrentStep, steps.length]);
  const handleBack = React.useCallback(() => {
    setCurrentStepIndex((prev) => Math.max(prev - 1, 0));
    setErrorMessage(null);
    setFieldErrors({});
  }, []);
  const handleComplete = React.useCallback(async () => {
    const valid = await validateCurrentStep();
    if (!valid) return;
    if (!widget.onComplete) {
      onClose?.();
      return;
    }
    setCompleting(true);
    setErrorMessage(null);
    try {
      await widget.onComplete(allData, context);
      onClose?.();
    } catch (err) {
      setErrorMessage(err instanceof Error ? err.message : t("ui.wizard.completeFailed", "Failed to complete"));
    } finally {
      setCompleting(false);
    }
  }, [validateCurrentStep, widget, allData, context, onClose, t]);
  React.useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === "Escape" && onClose) {
        event.preventDefault();
        onClose();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);
  if (!currentStep) return null;
  const stepLabel = t(currentStep.label, currentStep.label);
  const stepDescription = currentStep.description ? t(currentStep.description, currentStep.description) : void 0;
  const title = widget.metadata.title ? t(widget.metadata.title, widget.metadata.title) : void 0;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    title && /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: title }),
    /* @__PURE__ */ jsx(StepIndicator, { steps, currentIndex: currentStepIndex }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h3", { className: "text-base font-medium", children: stepLabel }),
        stepDescription && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: stepDescription })
      ] }),
      currentStep.fields && currentStep.fields.length > 0 && /* @__PURE__ */ jsx(
        StepFieldsRenderer,
        {
          step: currentStep,
          data: allData,
          onChange: handleFieldChange,
          context,
          fieldErrors
        }
      ),
      currentStep.customComponent && /* @__PURE__ */ jsx(React.Suspense, { fallback: /* @__PURE__ */ jsx(Spinner, { size: "sm" }), children: /* @__PURE__ */ jsx(
        currentStep.customComponent,
        {
          data: allData,
          setData: handleSetData,
          context
        }
      ) }),
      errorMessage && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", role: "alert", children: errorMessage })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-t pt-4", children: [
      /* @__PURE__ */ jsx("div", { children: !isFirstStep && /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: handleBack,
          disabled: validating || completing,
          children: t("ui.wizard.back", "Back")
        }
      ) }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        onClose && /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            onClick: onClose,
            disabled: completing,
            children: t("ui.wizard.cancel", "Cancel")
          }
        ),
        isLastStep ? /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            onClick: handleComplete,
            disabled: validating || completing,
            children: completing ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(Spinner, { size: "sm", className: "mr-2" }),
              t("ui.wizard.completing", "Completing...")
            ] }) : t("ui.wizard.complete", "Complete")
          }
        ) : /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            onClick: handleNext,
            disabled: validating || completing,
            children: validating ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(Spinner, { size: "sm", className: "mr-2" }),
              t("ui.wizard.validating", "Validating...")
            ] }) : t("ui.wizard.next", "Next")
          }
        )
      ] })
    ] })
  ] });
}
var InjectionWizard_default = InjectionWizard;
export {
  InjectionWizard,
  InjectionWizard_default as default
};
//# sourceMappingURL=InjectionWizard.js.map
