/**
 * useLayout hook — manages widget config state for customizable pages.
 * Returns the current widgets, editing state, and helpers for
 * WidgetWrapper + LayoutCustomizer props.
 */

import { useCallback, useState } from "react";
import { arrayMove } from "@dnd-kit/sortable";
import { buildDefaultWidgets, type WidgetConfig, type WidgetSize } from "@/lib/layouts/widget-registry";

export function useLayout(page: string) {
  const [widgets, setWidgets] = useState<WidgetConfig[]>(buildDefaultWidgets(page));
  const [editing, setEditing] = useState(false);

  const onLayoutChange = useCallback((next: WidgetConfig[]) => setWidgets(next), []);

  const reorder = useCallback((activeId: string, overId: string) => {
    setWidgets((prev) => {
      const oldIdx = prev.findIndex((w) => w.id === activeId);
      const newIdx = prev.findIndex((w) => w.id === overId);
      if (oldIdx < 0 || newIdx < 0) return prev;
      return arrayMove(prev, oldIdx, newIdx).map((w, i) => ({ ...w, order: i }));
    });
  }, []);

  const toggleVisible = useCallback((id: string) => {
    setWidgets((prev) => prev.map((w) => w.id === id ? { ...w, visible: !w.visible } : w));
  }, []);

  const changeSize = useCallback((id: string, size: WidgetSize) => {
    setWidgets((prev) => prev.map((w) => w.id === id ? { ...w, size } : w));
  }, []);

  const isVisible = useCallback((id: string) => {
    const w = widgets.find((w) => w.id === id);
    return w ? w.visible : true;
  }, [widgets]);

  const getSize = useCallback((id: string): WidgetSize => {
    return widgets.find((w) => w.id === id)?.size ?? "full";
  }, [widgets]);

  return { widgets, editing, setEditing, onLayoutChange, reorder, toggleVisible, changeSize, isVisible, getSize };
}
