import { useCallback, useState } from "react";

let nextWinZ = 1;

export interface ManagedWindow<T> {
  id: string;
  x: number;
  y: number;
  w: number;
  h: number;
  zIndex: number;
  data: T;
}

export function useWindowManager<T>(defaults?: { w: number; h: number }) {
  const defaultW = defaults?.w ?? 480;
  const defaultH = defaults?.h ?? 400;
  const [windows, setWindows] = useState<ManagedWindow<T>[]>([]);
  const [focusedId, setFocusedId] = useState<string | null>(null);

  const open = useCallback((id: string, data: T, size?: { w: number; h: number }) => {
    setWindows((prev) => {
      const existing = prev.find((w) => w.id === id);
      if (existing) {
        const z = ++nextWinZ;
        setFocusedId(existing.id);
        return prev.map((w) => w.id === existing.id ? { ...w, zIndex: z } : w);
      }
      const winW = size?.w ?? defaultW;
      const winH = size?.h ?? defaultH;
      const margin = 20;
      const z = ++nextWinZ;
      const win: ManagedWindow<T> = {
        id, data,
        x: Math.round(margin + Math.random() * (Math.max(margin, window.innerWidth - winW - margin) - margin)),
        y: Math.round(margin + Math.random() * (Math.max(margin, window.innerHeight - winH - margin) - margin)),
        w: winW, h: winH, zIndex: z,
      };
      setFocusedId(win.id);
      return [...prev, win];
    });
  }, [defaultW, defaultH]);

  const update = useCallback((id: string, patch: Partial<ManagedWindow<T>>) => {
    setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, ...patch } : w)));
  }, []);

  const close = useCallback((id: string) => {
    setWindows((prev) => prev.filter((w) => w.id !== id));
    setFocusedId((cur) => cur === id ? null : cur);
  }, []);

  const focus = useCallback((id: string) => {
    setFocusedId((cur) => {
      if (cur === id) return cur;
      const z = ++nextWinZ;
      setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, zIndex: z } : w)));
      return id;
    });
  }, []);

  return { windows, focusedId, open, update, close, focus };
}
