import * as React from "react";
import { useCustomFieldDefs } from "./customFieldDefs.js";
import { mapCustomFieldKindToFilterType } from "./customFieldColumns.js";
import { filterCustomFieldDefs, fetchCustomFieldDefs as loadCustomFieldDefs } from "./customFieldDefs.js";
import { apiCall } from "./apiCall.js";
import { CURRENCY_OPTIONS_URL } from "@open-mercato/shared/modules/entities/kinds";
function buildOptionsUrl(base, query) {
  if (!query) return base;
  try {
    const isAbsolute = /^([a-z][a-z\d+\-.]*:)?\/\//i.test(base);
    const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
    const url = isAbsolute ? new URL(base) : new URL(base, origin);
    if (!url.searchParams.has("query")) url.searchParams.append("query", query);
    if (!url.searchParams.has("q")) url.searchParams.append("q", query);
    if (isAbsolute) return url.toString();
    return `${url.pathname}${url.search}`;
  } catch {
    const sep = base.includes("?") ? "&" : "?";
    if (base.includes("query=")) return `${base}${sep}q=${encodeURIComponent(query)}`;
    return `${base}${sep}query=${encodeURIComponent(query)}`;
  }
}
async function loadRemoteOptions(url) {
  try {
    const call = await apiCall(url, void 0, { fallback: { items: [] } });
    if (!call.ok) return [];
    const payload = call.result ?? { items: [] };
    const items = Array.isArray(payload?.items) ? payload.items : [];
    return items.map((it) => ({
      value: String(it?.value ?? it),
      label: String(it?.label ?? it?.value ?? it)
    }));
  } catch {
    return [];
  }
}
function normalizeOptions(options) {
  if (!Array.isArray(options)) return [];
  return options.map((option) => {
    if (option && typeof option === "object" && "value" in option) {
      const rawValue = option.value;
      const rawLabel = option.label ?? rawValue;
      const value2 = String(rawValue);
      const label = typeof rawLabel === "string" ? rawLabel : String(rawLabel);
      return { value: value2, label };
    }
    const value = String(option);
    return { value, label: value.charAt(0).toUpperCase() + value.slice(1) };
  });
}
function buildFilterDefsFromCustomFields(defs) {
  const f = [];
  const visible = filterCustomFieldDefs(defs, "filter");
  const seenKeys = /* @__PURE__ */ new Set();
  for (const d of visible) {
    const keyLower = String(d.key).toLowerCase();
    if (seenKeys.has(keyLower)) continue;
    seenKeys.add(keyLower);
    const id = `cf_${d.key}`;
    const label = d.label || d.key;
    if (d.kind === "boolean") {
      f.push({ id, label, type: "checkbox" });
    } else if (d.kind === "select" || d.kind === "currency" || d.kind === "relation" || d.kind === "dictionary") {
      const options = normalizeOptions(d.options);
      const base = { id: d.multi ? `${id}In` : id, label, type: "select", multiple: !!d.multi, options };
      const optionsUrl = d.kind === "currency" ? CURRENCY_OPTIONS_URL : d.optionsUrl;
      if (optionsUrl) {
        ;
        base.loadOptions = async (query) => {
          const url = buildOptionsUrl(optionsUrl, query);
          return loadRemoteOptions(url);
        };
      }
      f.push(base);
    } else if (d.kind === "text" && d.multi) {
      const base = {
        id: `${id}In`,
        label,
        type: "tags",
        // If static options provided, pass them for suggestions
        options: normalizeOptions(d.options)
      };
      if (d.optionsUrl) {
        ;
        base.loadOptions = async (query) => {
          const url = buildOptionsUrl(d.optionsUrl, query);
          return loadRemoteOptions(url);
        };
      }
      f.push(base);
    } else {
      f.push({ id, label, type: "text" });
    }
  }
  const out = [];
  const seen = /* @__PURE__ */ new Set();
  for (const item of f) {
    if (seen.has(item.id)) continue;
    seen.add(item.id);
    out.push(item);
  }
  const order = new Map(visible.map((v, idx) => [v.key, idx]));
  out.sort((a, b) => (order.get(a.id.replace(/^cf_/, "").replace(/In$/, "")) ?? 0) - (order.get(b.id.replace(/^cf_/, "").replace(/In$/, "")) ?? 0));
  return out;
}
function buildAdvancedFilterFieldsFromCustomFields(defs, groupLabel) {
  const visible = filterCustomFieldDefs(defs, "filter");
  const seenKeys = /* @__PURE__ */ new Set();
  const fields = [];
  for (const d of visible) {
    const keyLower = String(d.key).toLowerCase();
    if (seenKeys.has(keyLower)) continue;
    seenKeys.add(keyLower);
    const type = mapCustomFieldKindToFilterType(d.kind);
    const field = {
      key: `cf_${d.key}`,
      label: d.label || d.key,
      type,
      group: groupLabel ?? "Custom Fields"
    };
    if (type === "select") {
      const opts = normalizeOptions(d.options);
      if (opts.length) field.options = opts;
    }
    fields.push(field);
  }
  return fields;
}
async function fetchCustomFieldFilterDefs(entityIds, fetchImpl, options) {
  const defs = await loadCustomFieldDefs(
    entityIds,
    fetchImpl,
    options?.fieldset ? { fieldset: options.fieldset } : void 0
  );
  return buildFilterDefsFromCustomFields(defs);
}
function useCustomFieldFilterDefs(entityIds, options = {}) {
  const { select, ...rest } = options;
  const selectFn = React.useCallback(
    (defs) => select ? select(defs) : buildFilterDefsFromCustomFields(defs),
    [select]
  );
  return useCustomFieldDefs(entityIds, { ...rest, select: selectFn });
}
export {
  buildAdvancedFilterFieldsFromCustomFields,
  buildFilterDefsFromCustomFields,
  fetchCustomFieldFilterDefs,
  useCustomFieldFilterDefs
};
//# sourceMappingURL=customFieldFilters.js.map
