"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { formatCategoryTreeLabel } from "../../lib/categoryTree.js";
async function fetchTree(status, errorMessage) {
  const search = new URLSearchParams();
  search.set("view", "tree");
  if (status !== "all") search.set("status", status);
  const response = await readApiResultOrThrow(
    `/api/catalog/categories?${search.toString()}`,
    void 0,
    { errorMessage, allowNullResult: true }
  );
  const items = Array.isArray(response?.items) ? response.items : [];
  return items;
}
function normalizeNodes(nodes) {
  if (!Array.isArray(nodes)) return [];
  return nodes;
}
function buildOptions(nodes, inactiveSuffix) {
  const list = [];
  const walk = (entries, depth) => {
    for (const node of entries) {
      if (!node || typeof node.id !== "string") continue;
      const children = Array.isArray(node.children) ? node.children : [];
      const nodeDepth = typeof node.depth === "number" ? node.depth : depth;
      const display = node.pathLabel?.length ? node.pathLabel : node.name;
      const label = `${formatCategoryTreeLabel(display ?? node.id, nodeDepth)}${node.isActive === false ? inactiveSuffix : ""}`;
      list.push({
        value: node.id,
        label,
        disabled: node.selectable === false
      });
      if (children.length) {
        walk(children, nodeDepth + 1);
      }
    }
  };
  walk(nodes, 0);
  return list;
}
const CategorySelect = React.forwardRef(function CategorySelect2({
  value = null,
  onChange,
  disabled = false,
  required = false,
  className,
  id,
  name,
  nodes: providedNodes,
  includeEmptyOption = true,
  emptyOptionLabel,
  fetchOnMount = true,
  status = "all"
}, ref) {
  const t = useT();
  const [fetchState, setFetchState] = React.useState(() => {
    if (providedNodes) return { status: "success", nodes: normalizeNodes(providedNodes) };
    return { status: fetchOnMount ? "loading" : "idle" };
  });
  React.useEffect(() => {
    if (providedNodes) {
      setFetchState({ status: "success", nodes: normalizeNodes(providedNodes) });
      return;
    }
    if (!fetchOnMount) {
      setFetchState({ status: "idle" });
      return;
    }
    let cancelled = false;
    setFetchState({ status: "loading" });
    const errorMessage = t("catalog.categories.select.error", "Failed to load categories");
    fetchTree(status, errorMessage).then((nodes2) => {
      if (!cancelled) setFetchState({ status: "success", nodes: nodes2 });
    }).catch(() => {
      if (!cancelled) setFetchState({ status: "error" });
    });
    return () => {
      cancelled = true;
    };
  }, [providedNodes, fetchOnMount, status, t]);
  const nodes = React.useMemo(() => {
    if (providedNodes) return normalizeNodes(providedNodes);
    if (fetchState.status === "success") return fetchState.nodes;
    return [];
  }, [providedNodes, fetchState]);
  const inactiveSuffix = React.useMemo(() => ` (${t("catalog.categories.select.inactive", "inactive")})`, [t]);
  const options = React.useMemo(() => buildOptions(nodes, inactiveSuffix), [nodes, inactiveSuffix]);
  const handleChange = React.useCallback(
    (event) => {
      const next = event.target.value;
      onChange?.(next ? next : null);
    },
    [onChange]
  );
  const selectValue = value ?? "";
  const showLoading = !providedNodes && fetchState.status === "loading";
  const showError = !providedNodes && fetchState.status === "error";
  const resolvedEmptyLabel = emptyOptionLabel ?? t("catalog.categories.select.empty", "Root level");
  return /* @__PURE__ */ jsxs(
    "select",
    {
      ref,
      id,
      name,
      className,
      value: selectValue,
      onChange: handleChange,
      disabled: disabled || fetchState.status === "loading",
      required,
      children: [
        includeEmptyOption ? /* @__PURE__ */ jsx("option", { value: "", children: resolvedEmptyLabel }) : null,
        showLoading ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: t("catalog.categories.select.loading", "Loading categories\u2026") }) : null,
        showError ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: t("catalog.categories.select.error", "Failed to load categories") }) : null,
        options.map((option) => /* @__PURE__ */ jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value))
      ]
    }
  );
});
export {
  CategorySelect
};
//# sourceMappingURL=CategorySelect.js.map
