"use client";
import * as React from "react";
import { loadInjectionWidgetsForSpot } from "@open-mercato/shared/modules/widgets/injection-loader";
import { hasAllFeatures } from "@open-mercato/shared/security/features";
import { apiCall } from "../../backend/utils/apiCall.js";
function collectRequiredFeatures(widgets) {
  const set = /* @__PURE__ */ new Set();
  for (const widget of widgets) {
    for (const feature of widget.metadata.features ?? []) {
      if (!feature || feature.trim().length === 0) continue;
      set.add(feature);
    }
  }
  return Array.from(set);
}
async function readPortalGrantedFeatures(features) {
  if (features.length === 0) return /* @__PURE__ */ new Set();
  try {
    const { ok, result: data } = await apiCall("/api/customer_accounts/portal/feature-check", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ features })
    });
    if (!ok || !data?.ok) return /* @__PURE__ */ new Set();
    return new Set(data.granted ?? []);
  } catch {
    return /* @__PURE__ */ new Set();
  }
}
function usePortalDashboardWidgets(spotId) {
  const [widgets, setWidgets] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [grantedFeatures, setGrantedFeatures] = React.useState(/* @__PURE__ */ new Set());
  React.useEffect(() => {
    let mounted = true;
    const load = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const loaded = await loadInjectionWidgetsForSpot(spotId);
        if (!mounted) return;
        const uiWidgets = loaded.filter((w) => typeof w.Widget === "function");
        setWidgets(uiWidgets);
        const required = collectRequiredFeatures(uiWidgets);
        const granted = await readPortalGrantedFeatures(required);
        if (!mounted) return;
        setGrantedFeatures(granted);
      } catch (loadError) {
        if (!mounted) return;
        console.error(`[usePortalDashboardWidgets] Failed to load widgets for spot ${spotId}:`, loadError);
        setError(loadError instanceof Error ? loadError.message : String(loadError));
        setWidgets([]);
      } finally {
        if (mounted) setIsLoading(false);
      }
    };
    void load();
    return () => {
      mounted = false;
    };
  }, [spotId]);
  const grantedFeatureList = React.useMemo(() => Array.from(grantedFeatures), [grantedFeatures]);
  const visibleWidgets = React.useMemo(
    () => widgets.filter((widget) => {
      const required = widget.metadata.features ?? [];
      return required.length === 0 || hasAllFeatures(grantedFeatureList, required);
    }),
    [widgets, grantedFeatureList]
  );
  return { widgets: visibleWidgets, isLoading, error };
}
export {
  usePortalDashboardWidgets
};
//# sourceMappingURL=usePortalDashboardWidgets.js.map
