"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCall } from "../utils/apiCall.js";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue
} from "../../primitives/select.js";
function EventSelect({
  value,
  onChange,
  placeholder,
  className,
  disabled,
  categories,
  modules,
  excludeTriggerExcluded = true,
  size = "default"
}) {
  const t = useT();
  const resolvedPlaceholder = placeholder ?? t("ui.inputs.eventSelect.placeholder", "Select an event...");
  const loadingPlaceholder = t("ui.inputs.eventSelect.loading", "Loading...");
  const emptyPlaceholder = t("ui.inputs.eventSelect.empty", "No events available");
  const { data: allEvents = [], isLoading } = useQuery({
    queryKey: ["declared-events", excludeTriggerExcluded],
    queryFn: async () => {
      const result = await apiCall(
        `/api/events?excludeTriggerExcluded=${excludeTriggerExcluded}`
      );
      if (!result.ok) return [];
      return result.result?.data || [];
    },
    staleTime: 5 * 60 * 1e3
    // Cache for 5 minutes
  });
  const filteredEvents = useMemo(() => {
    let events = allEvents;
    if (categories?.length) {
      events = events.filter((e) => e.category && categories.includes(e.category));
    }
    if (modules?.length) {
      events = events.filter((e) => e.module && modules.includes(e.module));
    }
    return events;
  }, [allEvents, categories, modules]);
  const eventsByModule = useMemo(() => {
    const grouped = {};
    for (const event of filteredEvents) {
      const module = event.module || "other";
      if (!grouped[module]) grouped[module] = [];
      grouped[module].push(event);
    }
    return Object.fromEntries(
      Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b))
    );
  }, [filteredEvents]);
  const formatModuleName = (module) => {
    return module.charAt(0).toUpperCase() + module.slice(1).replace(/_/g, " ");
  };
  const isEmpty = !isLoading && filteredEvents.length === 0;
  return /* @__PURE__ */ jsxs(
    Select,
    {
      value: value || void 0,
      onValueChange: (next) => onChange(next ?? ""),
      disabled: disabled || isLoading,
      children: [
        /* @__PURE__ */ jsx(SelectTrigger, { size, className, children: /* @__PURE__ */ jsx(
          SelectValue,
          {
            placeholder: isLoading ? loadingPlaceholder : isEmpty ? emptyPlaceholder : resolvedPlaceholder
          }
        ) }),
        /* @__PURE__ */ jsx(SelectContent, { children: Object.entries(eventsByModule).map(([module, moduleEvents]) => /* @__PURE__ */ jsxs(SelectGroup, { children: [
          /* @__PURE__ */ jsx(SelectLabel, { children: formatModuleName(module) }),
          moduleEvents.map((event) => /* @__PURE__ */ jsx(SelectItem, { value: event.id, children: event.label }, event.id))
        ] }, module)) })
      ]
    }
  );
}
function useAvailableEvents(options) {
  const excludeTriggerExcluded = options?.excludeTriggerExcluded !== false;
  const { data: allEvents = [], isLoading, error, refetch } = useQuery({
    queryKey: ["declared-events", excludeTriggerExcluded],
    queryFn: async () => {
      const result = await apiCall(
        `/api/events?excludeTriggerExcluded=${excludeTriggerExcluded}`
      );
      if (!result.ok) return [];
      return result.result?.data || [];
    },
    staleTime: 5 * 60 * 1e3
  });
  const filteredEvents = useMemo(() => {
    let events = allEvents;
    if (options?.categories?.length) {
      events = events.filter((e) => e.category && options.categories.includes(e.category));
    }
    if (options?.modules?.length) {
      events = events.filter((e) => e.module && options.modules.includes(e.module));
    }
    return events;
  }, [allEvents, options]);
  const eventsByModule = useMemo(() => {
    const grouped = {};
    for (const event of filteredEvents) {
      const module = event.module || "other";
      if (!grouped[module]) grouped[module] = [];
      grouped[module].push(event);
    }
    return Object.fromEntries(
      Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b))
    );
  }, [filteredEvents]);
  return {
    events: filteredEvents,
    eventsByModule,
    isLoading,
    error,
    refetch
  };
}
var EventSelect_default = EventSelect;
export {
  EventSelect,
  EventSelect_default as default,
  useAvailableEvents
};
//# sourceMappingURL=EventSelect.js.map
