import React, { useEffect, useRef } from 'react';

const SlashCommandMenu = ({ commands, selectedIndex, onSelect, onHover }) => {
    const scrollerRef = useRef(null);

    useEffect(() => {
        if (!scrollerRef.current) return;
        const selected = scrollerRef.current.querySelector('.slash-command-row.selected');
        if (selected) selected.scrollIntoView({ block: 'nearest' });
    }, [selectedIndex]);

    if (!commands || commands.length === 0) return null;

    const grouped = {};
    for (const cmd of commands) {
        const cat = cmd.category || 'Built-In';
        if (!grouped[cat]) grouped[cat] = [];
        grouped[cat].push(cmd);
    }

    let globalIndex = 0;

    return (
        <div className="slash-command-menu">
            <div className="slash-command-scroller" ref={scrollerRef}>
                {Object.entries(grouped).map(([category, cmds]) => (
                    <React.Fragment key={category}>
                        <div className="slash-command-section-header">{category}</div>
                        {cmds.map((cmd) => {
                            const idx = globalIndex++;
                            return (
                                <div
                                    key={cmd.name}
                                    className={`slash-command-row${idx === selectedIndex ? ' selected' : ''}`}
                                    onMouseDown={(e) => e.preventDefault()}
                                    onClick={() => onSelect(cmd)}
                                    onMouseEnter={() => onHover(idx)}
                                >
                                    <span className="slash-command-name">/{cmd.name}</span>
                                    <span className="slash-command-description">{cmd.description}</span>
                                </div>
                            );
                        })}
                    </React.Fragment>
                ))}
            </div>
        </div>
    );
};

export default SlashCommandMenu;
