import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  RouteFocusModal
} from "./chunk-FWJLS7XD.js";

// src/components/tabbed-form/tabbed-form.tsx
import { Button, ProgressTabs } from "@medusajs/ui";
import {
  Children,
  createContext,
  useContext,
  useMemo as useMemo2
} from "react";
import { useTranslation } from "react-i18next";

// src/components/tabbed-form/use-tab-management.ts
import { useCallback, useEffect, useMemo, useState } from "react";
var validateTab = async (form, tab) => {
  if (tab.validationFields?.length) {
    return form.trigger(tab.validationFields);
  }
  return form.trigger();
};
var validateTabRange = async (form, tabs, fromIndex, toIndex) => {
  for (let i = fromIndex; i <= toIndex; i++) {
    if (!await validateTab(form, tabs[i])) {
      return false;
    }
  }
  return true;
};
var useTabManagement = ({
  tabs,
  form
}) => {
  const visibleTabs = useMemo(
    () => tabs.filter((t) => !t.isVisible || t.isVisible(form)),
    [tabs, form]
  );
  const [activeTabId, setActiveTabId] = useState(
    visibleTabs[0]?.id ?? ""
  );
  const [tabState, setTabState] = useState(() => {
    const state = {};
    visibleTabs.forEach((t, i) => {
      state[t.id] = i === 0 ? "in-progress" : "not-started";
    });
    return state;
  });
  useEffect(() => {
    let resolvedActiveId = activeTabId;
    const activeExists = visibleTabs.some((t) => t.id === activeTabId);
    if (!activeExists && visibleTabs.length > 0) {
      resolvedActiveId = visibleTabs[0].id;
      setActiveTabId(resolvedActiveId);
    }
    const newState = {};
    const resolvedIndex = visibleTabs.findIndex(
      (t) => t.id === resolvedActiveId
    );
    visibleTabs.forEach((t, i) => {
      if (i < resolvedIndex) {
        newState[t.id] = "completed";
      } else if (i === resolvedIndex) {
        newState[t.id] = "in-progress";
      } else {
        newState[t.id] = tabState[t.id] ?? "not-started";
      }
    });
    setTabState(newState);
  }, [activeTabId, visibleTabs]);
  const activeIndex = visibleTabs.findIndex((t) => t.id === activeTabId);
  const isLastTab = activeIndex === visibleTabs.length - 1;
  const onNext = useCallback(async () => {
    const currentTab = visibleTabs[activeIndex];
    if (!currentTab) return;
    const valid = await validateTab(form, currentTab);
    if (!valid) return;
    if (activeIndex < visibleTabs.length - 1) {
      setActiveTabId(visibleTabs[activeIndex + 1].id);
    }
  }, [form, activeIndex, visibleTabs]);
  const onTabChange = useCallback(
    async (tabId) => {
      const targetIndex = visibleTabs.findIndex((t) => t.id === tabId);
      if (targetIndex === -1) return;
      const currentIndex = visibleTabs.findIndex(
        (t) => t.id === activeTabId
      );
      if (currentIndex === -1) {
        setActiveTabId(tabId);
        return;
      }
      if (targetIndex <= currentIndex) {
        setActiveTabId(tabId);
        return;
      }
      const valid = await validateTabRange(
        form,
        visibleTabs,
        currentIndex,
        targetIndex - 1
      );
      if (!valid) return;
      setActiveTabId(tabId);
    },
    [form, visibleTabs, activeTabId]
  );
  return {
    activeTabId,
    setActiveTabId,
    tabState,
    visibleTabs,
    isLastTab,
    onNext,
    onTabChange
  };
};

// src/components/tabbed-form/tabbed-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var TabbedFormContext = createContext(null);
var useTabbedForm = () => {
  const form = useContext(TabbedFormContext);
  if (!form) {
    throw new Error("useTabbedForm must be used within a TabbedForm");
  }
  return form;
};
function resolveTabMeta(child) {
  const type = child.type;
  const meta = type?._tabMeta;
  if (!meta && !child.props?.id) {
    return null;
  }
  const id = child.props?.id ?? meta?.id ?? "";
  const labelKey = meta?.labelKey ?? "";
  const label = child.props?.label;
  if (process.env.NODE_ENV !== "production") {
    if (!id) {
      console.warn(
        "[TabbedForm] A child component is missing a tab id. Either set _tabMeta.id or pass an id prop."
      );
    }
    if (!labelKey && !label) {
      console.warn(
        `[TabbedForm] Tab "${id}" has no label or labelKey \u2014 header will be empty.`
      );
    }
  }
  return {
    id,
    labelKey,
    label,
    validationFields: child.props?.validationFields ?? meta?.validationFields,
    isVisible: child.props?.isVisible ?? meta?.isVisible
  };
}
function collectTabs(children) {
  const tabs = [];
  const elements = [];
  Children.forEach(children, (child) => {
    if (!child || typeof child !== "object" || !("type" in child)) {
      return;
    }
    const meta = resolveTabMeta(child);
    if (meta) {
      tabs.push(meta);
      elements.push(child);
    }
  });
  return { tabs, elements };
}
function Root({
  form,
  onSubmit,
  children,
  isLoading,
  footer,
  transformTabs
}) {
  const { t } = useTranslation();
  const { tabs: rawTabs, elements } = useMemo2(
    () => collectTabs(children),
    [children]
  );
  const tabs = useMemo2(
    () => transformTabs ? transformTabs(rawTabs) : rawTabs,
    [transformTabs, rawTabs]
  );
  const {
    activeTabId,
    tabState,
    visibleTabs,
    isLastTab,
    onNext,
    onTabChange
  } = useTabManagement({
    tabs,
    form
  });
  const visibleElements = elements.filter((el) => {
    const meta = resolveTabMeta(el);
    return meta && visibleTabs.some((vt) => vt.id === meta.id);
  });
  return /* @__PURE__ */ jsx(TabbedFormContext.Provider, { value: form, children: /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onKeyDown: (e) => {
        if (e.key === "Enter") {
          if (e.target instanceof HTMLTextAreaElement && !(e.metaKey || e.ctrlKey)) {
            return;
          }
          e.preventDefault();
          if (e.metaKey || e.ctrlKey) {
            if (isLoading) {
              return;
            }
            if (!isLastTab) {
              e.preventDefault();
              e.stopPropagation();
              onNext();
              return;
            }
            onSubmit();
          }
        }
      },
      onSubmit,
      className: "flex h-full flex-col",
      children: [
        /* @__PURE__ */ jsxs(
          ProgressTabs,
          {
            value: activeTabId,
            onValueChange: onTabChange,
            className: "flex h-full flex-col overflow-hidden",
            children: [
              /* @__PURE__ */ jsx(RouteFocusModal.Header, { children: /* @__PURE__ */ jsx("div", { className: "-my-2 w-full border-l", children: /* @__PURE__ */ jsx(ProgressTabs.List, { className: "justify-start-start flex w-full items-center", children: visibleTabs.map((tab) => /* @__PURE__ */ jsx(
                ProgressTabs.Trigger,
                {
                  status: tabState[tab.id] ?? "not-started",
                  value: tab.id,
                  className: "max-w-[200px] truncate",
                  children: tab.label ?? t(tab.labelKey)
                },
                tab.id
              )) }) }) }),
              /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "size-full overflow-hidden", children: visibleElements.map((element) => {
                const meta = resolveTabMeta(element);
                return /* @__PURE__ */ jsx(
                  ProgressTabs.Content,
                  {
                    className: "size-full overflow-y-auto",
                    value: meta.id,
                    children: element
                  },
                  meta.id
                );
              }) })
            ]
          }
        ),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: footer ? footer({ isLastTab, onNext, isLoading }) : /* @__PURE__ */ jsx(
          DefaultFooter,
          {
            isLastTab,
            onNext,
            isLoading
          }
        ) })
      ]
    }
  ) }) });
}
var DefaultFooter = ({
  isLastTab,
  onNext,
  isLoading
}) => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
    isLastTab ? /* @__PURE__ */ jsx(
      Button,
      {
        type: "submit",
        variant: "primary",
        size: "small",
        isLoading,
        children: t("actions.save")
      },
      "submit-button"
    ) : /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "primary",
        size: "small",
        onClick: () => onNext(),
        children: t("actions.continue")
      },
      "next-button"
    )
  ] });
};
var Tab = ({
  children
}) => {
  return /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center p-16", children: /* @__PURE__ */ jsx("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8", children }) });
};
var TabbedForm = Object.assign(Root, { Tab, useForm: useTabbedForm });

// src/components/tabbed-form/types.ts
var defineTabMeta = (meta) => {
  if (process.env.NODE_ENV !== "production") {
    if (!meta.id) {
      console.warn("[TabbedForm] Tab meta is missing required 'id' field");
    }
    if (!meta.labelKey && !meta.label) {
      console.warn(
        `[TabbedForm] Tab "${meta.id}" has neither 'labelKey' nor 'label' \u2014 the tab header will be empty`
      );
    }
  }
  return meta;
};

export {
  useTabbedForm,
  TabbedForm,
  defineTabMeta
};
