export default function MainAreaButton({ wordOffsets, currentActiveWord, setCurrentActiveWord, setCurrentWordIndex }) {
    return (
        <div className="word-buttons">
            {(() => {
                const wordMap = new Map();

                // Group words case-insensitively
                wordOffsets.forEach((item) => {
                    const key = item.word.toLowerCase(); // normalize to lowercase
                    if (wordMap.has(key)) {
                        wordMap.get(key).push(item);
                    } else {
                        wordMap.set(key, [item]);
                    }
                });

                const groupedWords = Array.from(wordMap.values());

                // Ensure first word is active by default
                if (!currentActiveWord && groupedWords.length > 0) {
                    const firstItem = groupedWords[0][0];
                    setTimeout(() => {
                        setCurrentActiveWord(firstItem.word);
                        setCurrentWordIndex(firstItem.matchIndex);
                    }, 0);
                }

                return groupedWords.map((items) => {
                    const firstItem = items[0];
                    const isActive = currentActiveWord?.toLowerCase() === firstItem.word.toLowerCase();

                    return (
                        <button
                            key={firstItem.spanId}
                            type="button"
                            className={`scan-button ${isActive ? "button-primary" : "button-secondary"}`}
                            onClick={() => {
                                // Scroll to the first occurrence
                                const spanEl = document.getElementById(firstItem.spanId);
                                if (spanEl) spanEl.scrollIntoView({ behavior: "smooth", block: "start" });

                                // Update active selection
                                setCurrentWordIndex(firstItem.matchIndex);
                                setCurrentActiveWord(firstItem.word);
                            }}
                        >
                            {firstItem.word.toLowerCase()}
                        </button>
                    );
                });
            })()}
        </div>
    );
}
