import React, { createContext, useContext, useState, useCallback, useRef } from 'react';

interface WindowState {
  id: string;
  title: string;
  charName?: string;
  zIndex: number;
}

interface WindowManagerValue {
  windows: WindowState[];
  openWindow: (id: string, title: string, charName?: string) => void;
  closeWindow: (id: string) => void;
  bringToFront: (id: string) => void;
}

const Ctx = createContext<WindowManagerValue>({
  windows: [],
  openWindow: () => {},
  closeWindow: () => {},
  bringToFront: () => {},
});

export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [windows, setWindows] = useState<WindowState[]>([]);
  const zRef = useRef(10000);

  const openWindow = useCallback((id: string, title: string, charName?: string) => {
    setWindows(prev => {
      const existing = prev.find(w => w.id === id);
      if (existing) {
        return prev.map(w => w.id === id ? { ...w, zIndex: ++zRef.current } : w);
      }
      return [...prev, { id, title, charName, zIndex: ++zRef.current }];
    });
  }, []);

  const closeWindow = useCallback((id: string) => {
    setWindows(prev => prev.filter(w => w.id !== id));
  }, []);

  const bringToFront = useCallback((id: string) => {
    setWindows(prev => prev.map(w => w.id === id ? { ...w, zIndex: ++zRef.current } : w));
  }, []);

  return <Ctx.Provider value={{ windows, openWindow, closeWindow, bringToFront }}>{children}</Ctx.Provider>;
};

export const useWindowManager = () => useContext(Ctx);
