"use client";

/**
 * WidgetGrid — renders widgets in a responsive grid with dnd-kit sorting.
 * Pages pass a widgetMap of { widgetId → ReactNode } and the hook state.
 */

import { type ReactNode } from "react";
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import WidgetWrapper from "./widget-wrapper";
import { getWidgetDef, type WidgetConfig, type WidgetSize } from "@/lib/layouts/widget-registry";

interface Props {
  page: string;
  widgets: WidgetConfig[];
  editing: boolean;
  widgetMap: Record<string, ReactNode>;
  onReorder: (activeId: string, overId: string) => void;
  onToggleVisible: (id: string) => void;
  onChangeSize: (id: string, size: WidgetSize) => void;
}

export default function WidgetGrid({ page, widgets, editing, widgetMap, onReorder, onToggleVisible, onChangeSize }: Props) {
  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));

  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;
    if (over && active.id !== over.id) onReorder(String(active.id), String(over.id));
  }

  const sorted = [...widgets].sort((a, b) => a.order - b.order);

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={sorted.map((w) => w.id)} strategy={verticalListSortingStrategy}>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          {sorted.map((w) => {
            const def = getWidgetDef(page, w.id);
            const content = widgetMap[w.id];
            if (!content && !editing) return null;
            return (
              <WidgetWrapper
                key={w.id}
                id={w.id}
                name={def?.name ?? w.id}
                visible={w.visible}
                size={w.size}
                editing={editing}
                onToggleVisible={() => onToggleVisible(w.id)}
                onChangeSize={(s) => onChangeSize(w.id, s)}
              >
                {content ?? <div className="bg-slate-50 rounded-xl px-4 py-8 text-center text-xs text-slate-400">{def?.name ?? w.id}</div>}
              </WidgetWrapper>
            );
          })}
        </div>
      </SortableContext>
    </DndContext>
  );
}
