"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { formatOrganizationTreeLabel } from "../lib/tree.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
async function fetchTree(params, errorMessage) {
  const search = new URLSearchParams();
  search.set("view", "tree");
  if (params.tenantId) search.set("tenantId", params.tenantId);
  if (params.status) search.set("status", params.status);
  const json = await readApiResultOrThrow(
    `/api/directory/organizations?${search.toString()}`,
    void 0,
    { errorMessage, allowNullResult: true }
  );
  return Array.isArray(json?.items) ? json.items : [];
}
function normalizeNodes(nodes) {
  if (!Array.isArray(nodes)) return [];
  return nodes;
}
function buildOptions(nodes, includeInactiveSet, labelKey, inactiveSuffix) {
  const acc = [];
  const walk = (list, depth) => {
    for (const node of list) {
      if (!node || typeof node.id !== "string") continue;
      const children = Array.isArray(node.children) ? node.children : [];
      const isInactive = node.isActive === false;
      const allowed = !isInactive || includeInactiveSet.has(node.id);
      const nodeDepth = typeof node.depth === "number" ? node.depth : depth;
      if (allowed) {
        const display = labelKey === "pathLabel" ? node.pathLabel || node.name || node.id : node.name || node.pathLabel || node.id;
        const baseLabel = formatOrganizationTreeLabel(display, nodeDepth);
        const label = `${baseLabel}${isInactive ? inactiveSuffix : ""}`;
        acc.push({
          value: node.id,
          label,
          disabled: node.selectable === false
        });
        walk(children, nodeDepth + 1);
      } else {
        walk(children, nodeDepth + 1);
      }
    }
  };
  walk(nodes, 0);
  return acc;
}
const OrganizationSelect = React.forwardRef(function OrganizationSelect2({
  value,
  onChange,
  disabled = false,
  required = false,
  className,
  id,
  name,
  nodes: providedNodes,
  includeInactiveIds = null,
  includeAllOption = false,
  allOptionLabel,
  includeEmptyOption = false,
  emptyOptionLabel,
  fetchOnMount = true,
  tenantId = null,
  status = "all",
  labelKey = "name"
}, ref) {
  const t = useT();
  const [fetchState, setFetchState] = React.useState(() => {
    if (providedNodes) {
      return { status: "success", nodes: normalizeNodes(providedNodes) };
    }
    return { status: fetchOnMount ? "loading" : "idle" };
  });
  React.useEffect(() => {
    const errorMessage = t("organizationSelect.error", "Failed to load organizations");
    if (providedNodes) {
      setFetchState({ status: "success", nodes: normalizeNodes(providedNodes) });
      return;
    }
    if (!fetchOnMount) {
      setFetchState({ status: "idle" });
      return;
    }
    let cancelled = false;
    setFetchState({ status: "loading" });
    fetchTree({ tenantId, status }, errorMessage).then((nodes2) => {
      if (!cancelled) setFetchState({ status: "success", nodes: nodes2 });
    }).catch(() => {
      if (!cancelled) setFetchState({ status: "error" });
    });
    return () => {
      cancelled = true;
    };
  }, [providedNodes, fetchOnMount, tenantId, status, t]);
  const nodes = React.useMemo(() => {
    if (providedNodes) {
      return normalizeNodes(providedNodes);
    }
    if (fetchState.status === "success") return fetchState.nodes;
    return [];
  }, [providedNodes, fetchState]);
  const isLoading = !providedNodes && fetchState.status === "loading";
  const isError = !providedNodes && fetchState.status === "error";
  const includeInactiveSet = React.useMemo(() => {
    const set = /* @__PURE__ */ new Set();
    if (!includeInactiveIds) return set;
    for (const raw of includeInactiveIds) {
      if (!raw) continue;
      const idValue = String(raw).trim();
      if (idValue) set.add(idValue);
    }
    return set;
  }, [includeInactiveIds]);
  const inactiveSuffix = React.useMemo(() => ` (${t("organizationSelect.inactive")})`, [t]);
  const options = React.useMemo(
    () => buildOptions(nodes, includeInactiveSet, labelKey, inactiveSuffix),
    [nodes, includeInactiveSet, labelKey, inactiveSuffix]
  );
  const handleChange = React.useCallback((event) => {
    const next = event.target.value;
    if (!onChange) return;
    onChange(next ? next : null);
  }, [onChange]);
  const selectValue = value ?? "";
  const shouldShowStatusOption = options.length === 0 && !includeAllOption && !includeEmptyOption;
  const resolvedAllOptionLabel = includeAllOption ? allOptionLabel ?? t("organizationSelect.all") : null;
  const resolvedEmptyOptionLabel = includeEmptyOption && !includeAllOption ? emptyOptionLabel ?? t("organizationSelect.empty") : null;
  const loadingLabel = t("organizationSelect.loading");
  const errorLabel = t("organizationSelect.error");
  return /* @__PURE__ */ jsxs(
    "select",
    {
      ref,
      id,
      name,
      value: selectValue,
      onChange: handleChange,
      disabled: disabled || isLoading || isError,
      required,
      className: className ?? "h-9 rounded border pl-2 pr-7 text-sm truncate",
      children: [
        resolvedAllOptionLabel ? /* @__PURE__ */ jsx("option", { value: "", children: resolvedAllOptionLabel }) : null,
        resolvedEmptyOptionLabel ? /* @__PURE__ */ jsx("option", { value: "", children: resolvedEmptyOptionLabel }) : null,
        shouldShowStatusOption && isLoading ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: loadingLabel }) : null,
        shouldShowStatusOption && isError ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: errorLabel }) : null,
        !isLoading && !isError ? options.map((opt) => /* @__PURE__ */ jsx("option", { value: opt.value, disabled: opt.disabled, children: opt.label }, opt.value)) : null
      ]
    }
  );
});
export {
  OrganizationSelect
};
//# sourceMappingURL=OrganizationSelect.js.map
