import React, { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import './GameDropdown.css';

interface GameDropdownProps {
    isOpen: boolean;
    onClose: () => void;
    position: { x: number; y: number };
    children: React.ReactNode;
    className?: string;
    width?: string;
}

/**
 * GameDropdown
 * 
 * A reusable dropdown component that renders outside the DOM hierarchy 
 * to avoid z-index/overflow issues. 
 * Closes when clicking outside.
 */
export const GameDropdown: React.FC<GameDropdownProps> = ({
    isOpen,
    onClose,
    position,
    children,
    className = '',
    width = '200px'
}) => {
    const dropdownRef = useRef<HTMLDivElement>(null);

    // Handle click outside
    useEffect(() => {
        if (!isOpen) return;

        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                onClose();
            }
        };

        // Use mousedown to catch clicks before they might trigger other things
        document.addEventListener('mousedown', handleClickOutside);

        // Handle scroll to update position or close? 
        // For now, simpler to just close on scroll or let it float (fixed pos)
        const handleScroll = () => {
            // Optional: onClose(); 
        };
        window.addEventListener('scroll', handleScroll, true);

        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
            window.removeEventListener('scroll', handleScroll, true);
        };
    }, [isOpen, onClose]);

    if (!isOpen) return null;

    // Adjust position to keep within viewport
    let { x, y } = position;

    // Simple adjustment logic (can be improved with measuring ref)
    // We'll trust the parent passed reasonable coords, but ensure it doesn't go off-screen right/bottom
    if (typeof window !== 'undefined') {
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        // Approximate width if not measured yet (or use min-width)
        const estimatedWidth = parseInt(width) || 200;
        const estimatedHeight = 200; // Guess for now

        if (x + estimatedWidth > viewportWidth) {
            x = viewportWidth - estimatedWidth - 10;
        }

        if (y + estimatedHeight > viewportHeight) {
            // Flip up if space
            y = y - estimatedHeight;
            // Or just limit to bottom
            if (y < 0) y = 10;
        }
    }

    return createPortal(
        <div
            ref={dropdownRef}
            className={`game-dropdown-menu ${className}`}
            style={{
                top: y,
                left: x,
                width: width
            }}
            onClick={(e) => e.stopPropagation()} // Prevent clicks inside from closing
        >
            {children}
        </div>,
        document.body
    );
};
