"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { GripVertical, X, ChevronRight } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { IconButton } from "../../primitives/icon-button.js";
import { Switch } from "../../primitives/switch.js";
import { SearchInput } from "../../primitives/search-input.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors
} from "@dnd-kit/core";
import {
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
  useSortable
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
function SortableColumnItem({
  column,
  onToggle
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: column.key });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      style,
      className: "flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",
      children: [
        /* @__PURE__ */ jsx("span", { className: "cursor-grab text-muted-foreground", ...attributes, ...listeners, children: /* @__PURE__ */ jsx(GripVertical, { className: "size-4" }) }),
        /* @__PURE__ */ jsx("span", { className: "truncate flex-1 min-w-0", children: column.label }),
        /* @__PURE__ */ jsx(
          Switch,
          {
            checked: true,
            disabled: column.alwaysVisible,
            onCheckedChange: () => onToggle(column.key),
            className: "shrink-0 scale-90"
          }
        )
      ]
    }
  );
}
function ColumnChooserSection({
  availableColumns,
  visibleColumnKeys,
  columnOrder,
  onToggleColumn,
  onReorderColumns,
  dndContextId = "column-chooser"
}) {
  const t = useT();
  const [searchQuery, setSearchQuery] = React.useState("");
  const [expandedGroups, setExpandedGroups] = React.useState(/* @__PURE__ */ new Set());
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );
  const visibleSet = React.useMemo(() => new Set(visibleColumnKeys), [visibleColumnKeys]);
  const selectedColumns = React.useMemo(() => {
    const ordered = [];
    for (const key of columnOrder) {
      const col = availableColumns.find((c) => c.key === key);
      if (col && visibleSet.has(key)) ordered.push(col);
    }
    for (const col of availableColumns) {
      if (visibleSet.has(col.key) && !ordered.some((o) => o.key === col.key)) {
        ordered.push(col);
      }
    }
    if (!searchQuery) return ordered;
    const lowerQuery = searchQuery.toLowerCase();
    return ordered.filter((c) => c.label.toLowerCase().includes(lowerQuery));
  }, [availableColumns, visibleSet, columnOrder, searchQuery]);
  const groupedAvailable = React.useMemo(() => {
    const lowerQuery = searchQuery.toLowerCase();
    const filtered = availableColumns.filter((c) => !visibleSet.has(c.key)).filter((c) => !searchQuery || c.label.toLowerCase().includes(lowerQuery));
    const groups = /* @__PURE__ */ new Map();
    for (const col of filtered) {
      const group = col.group || t("ui.columnChooser.ungrouped", "Other");
      const list = groups.get(group) ?? [];
      list.push(col);
      groups.set(group, list);
    }
    return groups;
  }, [availableColumns, searchQuery, visibleSet, t]);
  const toggleGroup = React.useCallback((group) => {
    setExpandedGroups((prev) => {
      const next = new Set(prev);
      if (next.has(group)) next.delete(group);
      else next.add(group);
      return next;
    });
  }, []);
  const handleDragEnd = React.useCallback((event) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    const oldIndex = selectedColumns.findIndex((c) => c.key === active.id);
    const newIndex = selectedColumns.findIndex((c) => c.key === over.id);
    if (oldIndex === -1 || newIndex === -1) return;
    const reordered = [...selectedColumns];
    const [moved] = reordered.splice(oldIndex, 1);
    reordered.splice(newIndex, 0, moved);
    onReorderColumns(reordered.map((c) => c.key));
  }, [selectedColumns, onReorderColumns]);
  const handleHideAll = React.useCallback(() => {
    for (const col of selectedColumns) {
      if (!col.alwaysVisible) onToggleColumn(col.key);
    }
  }, [selectedColumns, onToggleColumn]);
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
    /* @__PURE__ */ jsx("div", { className: "px-4 py-3 border-t", children: /* @__PURE__ */ jsx(
      SearchInput,
      {
        size: "sm",
        placeholder: t("ui.columnChooser.search", "Search columns..."),
        value: searchQuery,
        onChange: setSearchQuery
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { children: [
      selectedColumns.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "px-4 py-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-baseline gap-2", children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("ui.columnChooser.shown", "Shown") }),
            /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
              selectedColumns.length,
              "/",
              availableColumns.length
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "link",
              size: "sm",
              className: "h-auto px-0 text-sm text-muted-foreground hover:text-foreground",
              onClick: handleHideAll,
              children: t("ui.columnChooser.hideAll", "Hide all")
            }
          )
        ] }),
        /* @__PURE__ */ jsx(DndContext, { id: dndContextId, sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd, children: /* @__PURE__ */ jsx(SortableContext, { items: selectedColumns.map((c) => c.key), strategy: verticalListSortingStrategy, children: /* @__PURE__ */ jsx("div", { className: "space-y-2", children: selectedColumns.map((col) => /* @__PURE__ */ jsx(SortableColumnItem, { column: col, onToggle: onToggleColumn }, col.key)) }) }) })
      ] }) : null,
      /* @__PURE__ */ jsxs("div", { className: "border-t px-4 py-3 mt-4 mb-4", children: [
        /* @__PURE__ */ jsx("div", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground mb-3", children: t("ui.columnChooser.available", "Available columns") }),
        Array.from(groupedAvailable.entries()).map(([group, columns]) => {
          const isCollapsed = !searchQuery && !expandedGroups.has(group);
          return /* @__PURE__ */ jsxs("div", { className: "mb-2", children: [
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "ghost",
                size: "sm",
                className: "w-full justify-start gap-2 h-auto px-1 py-2 text-xs font-medium uppercase text-muted-foreground",
                onClick: () => toggleGroup(group),
                children: [
                  /* @__PURE__ */ jsx(ChevronRight, { className: `size-4 transition-transform ${isCollapsed ? "" : "rotate-90"}` }),
                  /* @__PURE__ */ jsx("span", { children: group })
                ]
              }
            ),
            !isCollapsed ? /* @__PURE__ */ jsx("div", { className: "space-y-2 mt-2", children: columns.map((col) => /* @__PURE__ */ jsxs(
              "div",
              {
                className: "flex items-center gap-2 rounded pl-7 pr-2 py-1.5 text-sm hover:bg-muted/50 cursor-pointer",
                onClick: () => {
                  if (!col.alwaysVisible) onToggleColumn(col.key);
                },
                children: [
                  /* @__PURE__ */ jsx("span", { className: "truncate flex-1 min-w-0", children: col.label }),
                  /* @__PURE__ */ jsx(
                    Switch,
                    {
                      checked: false,
                      disabled: col.alwaysVisible,
                      onCheckedChange: () => onToggleColumn(col.key),
                      onClick: (e) => e.stopPropagation(),
                      className: "shrink-0 scale-90"
                    }
                  )
                ]
              },
              col.key
            )) }) : null
          ] }, group);
        })
      ] })
    ] })
  ] });
}
function ColumnChooserPanel({
  open,
  onOpenChange,
  ...sectionProps
}) {
  const t = useT();
  React.useEffect(() => {
    if (!open) return;
    if (typeof document === "undefined") return;
    document.body.dataset.columnChooserOpen = "true";
    return () => {
      delete document.body.dataset.columnChooserOpen;
    };
  }, [open]);
  if (!open) return null;
  return /* @__PURE__ */ jsxs("div", { className: "fixed inset-y-0 right-0 z-modal w-80 border-l bg-background shadow-lg flex flex-col", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-3", children: [
      /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm", children: t("ui.columnChooser.title", "Columns") }),
      /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", type: "button", onClick: () => onOpenChange(false), "aria-label": t("ui.columnChooser.close", "Close"), children: /* @__PURE__ */ jsx(X, { className: "size-4" }) })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-auto", children: /* @__PURE__ */ jsx(ColumnChooserSection, { ...sectionProps }) })
  ] });
}
export {
  ColumnChooserPanel,
  ColumnChooserSection
};
//# sourceMappingURL=ColumnChooserPanel.js.map
