"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";
function normalizeTenant(tenant) {
  if (!tenant || typeof tenant.id !== "string" || tenant.id.trim().length === 0) return null;
  const id = tenant.id.trim();
  const name = typeof tenant.name === "string" && tenant.name.trim().length > 0 ? tenant.name.trim() : id;
  const isActive = tenant.isActive !== false;
  return { id, name, isActive };
}
function sanitizeTenantList(list) {
  if (!Array.isArray(list)) return [];
  const seen = /* @__PURE__ */ new Map();
  for (const tenant of list) {
    const normalized = normalizeTenant(tenant);
    if (!normalized) continue;
    seen.set(normalized.id, normalized);
  }
  return Array.from(seen.values());
}
function mergeTenantLists(...lists) {
  const map = /* @__PURE__ */ new Map();
  for (const list of lists) {
    for (const tenant of list) {
      if (!tenant || typeof tenant.id !== "string" || tenant.id.trim().length === 0) continue;
      const id = tenant.id.trim();
      const existing = map.get(id);
      if (!existing) {
        map.set(id, {
          id,
          name: typeof tenant.name === "string" && tenant.name.length > 0 ? tenant.name : id,
          isActive: tenant.isActive !== false
        });
      } else {
        const name = typeof tenant.name === "string" && tenant.name.length > 0 ? tenant.name : existing.name;
        const isActive = tenant.isActive !== void 0 ? tenant.isActive !== false : existing.isActive;
        map.set(id, { id, name, isActive });
      }
    }
  }
  return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
}
function filterTenantsByStatus(list, status) {
  if (status === "active") return list.filter((tenant) => tenant.isActive);
  if (status === "inactive") return list.filter((tenant) => !tenant.isActive);
  return list;
}
const DIRECTORY_TENANTS_PAGE_SIZE = 100;
const DIRECTORY_TENANTS_MAX_PAGES = 200;
function normalizeTenantItems(items) {
  return items.map((item) => {
    if (!item || typeof item !== "object") return null;
    const entry = item;
    const rawId = entry.id;
    const id = typeof rawId === "string" ? rawId : null;
    if (!id || !id.length) return null;
    const rawName = entry.name;
    const name = typeof rawName === "string" && rawName.length > 0 ? rawName : id;
    const isActive = entry.isActive !== false;
    return { id, name, isActive };
  }).filter((tenant) => tenant !== null);
}
async function fetchDirectoryTenants(status, errorMessage) {
  const collected = [];
  let page = 1;
  let totalPages = 1;
  do {
    const search = new URLSearchParams();
    search.set("page", String(page));
    search.set("pageSize", String(DIRECTORY_TENANTS_PAGE_SIZE));
    search.set("sortField", "name");
    search.set("sortDir", "asc");
    if (status === "active") search.set("isActive", "true");
    if (status === "inactive") search.set("isActive", "false");
    const json = await readApiResultOrThrow(
      `/api/directory/tenants?${search.toString()}`,
      void 0,
      { errorMessage, allowNullResult: true }
    );
    const items = Array.isArray(json?.items) ? json.items : [];
    collected.push(...normalizeTenantItems(items));
    totalPages = typeof json?.totalPages === "number" && Number.isFinite(json.totalPages) ? Math.max(1, Math.floor(json.totalPages)) : 1;
    if (items.length < DIRECTORY_TENANTS_PAGE_SIZE) break;
    page += 1;
  } while (page <= totalPages && page <= DIRECTORY_TENANTS_MAX_PAGES);
  return mergeTenantLists(filterTenantsByStatus(collected, status));
}
async function fetchTenantsFromOrganizationSwitcher(status, errorMessage) {
  const payload = await readApiResultOrThrow(
    "/api/directory/organization-switcher",
    void 0,
    { errorMessage, allowNullResult: true }
  );
  const json = payload ?? {};
  const rawTenants = Array.isArray(json.tenants) ? json.tenants : [];
  const sanitized = sanitizeTenantList(rawTenants);
  return mergeTenantLists(filterTenantsByStatus(sanitized, status));
}
const TenantSelect = React.forwardRef(function TenantSelect2({
  value,
  onChange,
  disabled = false,
  required = false,
  className,
  id,
  name,
  includeEmptyOption = false,
  emptyOptionLabel,
  fetchOnMount = true,
  status = "all",
  tenants: providedTenantsInput = null
}, ref) {
  const t = useT();
  const providedTenants = React.useMemo(() => sanitizeTenantList(providedTenantsInput), [providedTenantsInput]);
  const [remoteTenants, setRemoteTenants] = React.useState([]);
  const [fetchStatus, setFetchStatus] = React.useState(fetchOnMount ? "loading" : "idle");
  React.useEffect(() => {
    const fetchErrorMessage = t("tenantSelect.error", "Failed to load tenants");
    if (!fetchOnMount) {
      setFetchStatus((prev) => prev === "loading" ? "idle" : prev);
      return;
    }
    let cancelled = false;
    const loadTenants = async () => {
      setFetchStatus("loading");
      const autoSelect = (tenants) => {
        if (!value && !includeEmptyOption && tenants.length > 0) {
          onChange?.(tenants[0].id);
        }
      };
      try {
        const tenants = await fetchDirectoryTenants(status, fetchErrorMessage);
        if (cancelled) return;
        setRemoteTenants(tenants);
        autoSelect(tenants);
        setFetchStatus("success");
        return;
      } catch {
        try {
          const fallbackTenants = await fetchTenantsFromOrganizationSwitcher(status, fetchErrorMessage);
          if (cancelled) return;
          setRemoteTenants(fallbackTenants);
          autoSelect(fallbackTenants);
          setFetchStatus("success");
          return;
        } catch {
          if (cancelled) return;
          setFetchStatus("error");
        }
      }
    };
    void loadTenants();
    return () => {
      cancelled = true;
    };
  }, [fetchOnMount, status, t]);
  const mergedTenants = React.useMemo(
    () => mergeTenantLists(providedTenants, remoteTenants),
    [providedTenants, remoteTenants]
  );
  const fallbackTenant = React.useMemo(() => {
    const tenantId = typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
    if (!tenantId) return null;
    if (mergedTenants.some((tenant) => tenant.id === tenantId)) return null;
    return { id: tenantId, name: tenantId, isActive: true };
  }, [mergedTenants, value]);
  const tenantsForRender = React.useMemo(
    () => fallbackTenant ? mergeTenantLists(mergedTenants, [fallbackTenant]) : mergedTenants,
    [mergedTenants, fallbackTenant]
  );
  const showLoading = fetchStatus === "loading" && tenantsForRender.length === 0;
  const showError = fetchStatus === "error" && tenantsForRender.length === 0;
  const handleChange = React.useCallback((event) => {
    if (!onChange) return;
    const next = event.target.value;
    onChange(next ? next : null);
  }, [onChange]);
  const selectValue = value ?? "";
  const resolvedEmptyOptionLabel = emptyOptionLabel ?? t("tenantSelect.empty");
  const loadingLabel = t("tenantSelect.loading");
  const errorLabel = t("tenantSelect.error");
  const inactiveSuffix = ` (${t("tenantSelect.inactive")})`;
  return /* @__PURE__ */ jsxs(
    "select",
    {
      ref,
      id,
      name,
      value: selectValue,
      onChange: handleChange,
      disabled: disabled || showError && tenantsForRender.length === 0,
      required,
      className,
      children: [
        includeEmptyOption ? /* @__PURE__ */ jsx("option", { value: "", children: resolvedEmptyOptionLabel }) : null,
        showLoading ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: loadingLabel }) : null,
        showError ? /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: errorLabel }) : null,
        !showLoading && tenantsForRender.length > 0 ? tenantsForRender.map((tenant) => /* @__PURE__ */ jsxs("option", { value: tenant.id, children: [
          tenant.name,
          tenant.isActive ? "" : inactiveSuffix
        ] }, tenant.id)) : null
      ]
    }
  );
});
export {
  TenantSelect
};
//# sourceMappingURL=TenantSelect.js.map
