import SideBarInput from "./SideBarInput";
import { useEffect } from "react";
import handleSave from "./handleSave";


export default function SideBar({ currentActiveWord, matches, currentWordIndex, replaceWord, setReplaceWord, handleReplaceWord, editableContent, onClose, setCurrentActiveWord, setCurrentWordIndex }) {
    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.key === "Escape") {
                e.preventDefault();
                onClose();
                setCurrentActiveWord("");
                setCurrentWordIndex(0);
            }
        };

        document.addEventListener("keydown", handleKeyDown);
        return () => document.removeEventListener("keydown", handleKeyDown);
    }, [onClose, setCurrentActiveWord, setCurrentWordIndex]);

    return (
        <div className="modal-sidebar">
            {!currentActiveWord || !matches[currentWordIndex]?.bad ? (
                // Case: no active word OR active word is empty
                <p className="no-restricted-word">No restricted word found</p>
            ) : (
                // Case: active word exists and has content
                <SideBarInput
                    matches={matches}
                    currentWordIndex={currentWordIndex}
                    replaceWord={replaceWord}
                    setReplaceWord={setReplaceWord}
                    handleReplaceWord={handleReplaceWord}
                />
            )}

            {/* Navigation + Save pinned at bottom */}
            <div className="modal-actions">
                <div className="modal-nav">{/* prev/next buttons */}</div>
                <button
                    type="button"
                    className="button button-primary"
                    onClick={() => {
                        handleSave(editableContent);
                        onClose();
                        setCurrentActiveWord("");
                        setCurrentWordIndex(0);
                    }}
                >
                    Done
                </button>
            </div>
        </div>
    );
}
