import { useRef, useState, useCallback, useEffect } from 'react';

interface FloatingWindowProps {
  title: string;
  visible: boolean;
  defaultPosition: { x: number; y: number };
  defaultSize?: { width: number; height?: number };
  onClose: () => void;
  children: React.ReactNode;
  testId?: string;
}

export function FloatingWindow({ title, visible, defaultPosition, defaultSize, onClose, children, testId }: FloatingWindowProps) {
  const [pos, setPos] = useState(defaultPosition);
  const dragging = useRef(false);
  const dragOffset = useRef({ x: 0, y: 0 });

  useEffect(() => { setPos(defaultPosition); }, [defaultPosition.x, defaultPosition.y]);

  const onMouseDown = useCallback((e: React.MouseEvent) => {
    dragging.current = true;
    dragOffset.current = { x: e.clientX - pos.x, y: e.clientY - pos.y };
    e.preventDefault();
  }, [pos]);

  useEffect(() => {
    const onMove = (e: MouseEvent) => {
      if (!dragging.current) return;
      setPos({ x: Math.max(0, e.clientX - dragOffset.current.x), y: Math.max(0, e.clientY - dragOffset.current.y) });
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, []);

  if (!visible) return null;

  return (
    <div data-testid={testId} style={{
      position: 'fixed', left: pos.x, top: pos.y,
      width: defaultSize?.width || 240,
      background: '#f5f5f5', border: '1px solid #a0a0a0', borderRadius: 4,
      boxShadow: '2px 2px 8px rgba(0,0,0,0.2)', zIndex: 150,
      fontFamily: 'system-ui, sans-serif', fontSize: 12, color: '#1a1a1a',
    }}>
      <div data-testid="floating-titlebar" onMouseDown={onMouseDown} style={{
        padding: '4px 8px', background: '#e0e0e0', borderBottom: '1px solid #c0c0c0',
        display: 'flex', justifyContent: 'space-between', cursor: 'move', fontWeight: 'bold', fontSize: 11,
      }}>
        <span>{title}</span>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>×</button>
      </div>
      <div style={{ maxHeight: 400, overflowY: 'auto' }}>{children}</div>
    </div>
  );
}
