// Sidebar component
const { useState: useSidebarState, useRef: useSidebarRef, useEffect: useSidebarEffect } = React;

function Sidebar({
    chatHistory,
    choices,
    isLoading,
    gameLoaded,
    onSendMessage,
    onSelectChoice,
    gamePhase,
    epitaph,
    turn,
    onSelectScenario,
    onCustomGame,
    playerTheme,
    shareSummary,
    settingsPage,
    onCloseSettings,
    onDismissSettings,
    gameList,
    achievements,
    onShowLadder,
    scenarioId,
    gameId,
    published,
    customScenario,
    onRetry,
    onRequestIntel,
}) {
    const [inputValue, setInputValue] = useSidebarState('');
    const chatEndRef = useSidebarRef(null);
    const chatContainerRef = useSidebarRef(null);
    const prevCountRef = useSidebarRef(0);

    // Auto-scroll: when player sends a message, scroll it to the top of viewport
    // When narrator responds, just scroll to the end
    useSidebarEffect(() => {
        const count = chatHistory.length;
        if (count > prevCountRef.current) {
            const lastMsg = chatHistory[count - 1];
            if (lastMsg?.noScroll) {
                // Advisor consultations stay in place — don't jump the view
                prevCountRef.current = count;
                return;
            }
            if (lastMsg?.role === 'player') {
                // Scroll player's message to top of the chat area
                const container = chatContainerRef.current;
                if (container) {
                    const playerMsgs = container.querySelectorAll('.chat-message.player');
                    const msgEl = playerMsgs[playerMsgs.length - 1];
                    if (msgEl) {
                        const offset = msgEl.offsetTop - 16;
                        container.scrollTo({ top: offset, behavior: 'smooth' });
                    }
                }
            } else {
                chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
            }
        }
        prevCountRef.current = count;
    }, [chatHistory]);

    const handleSubmit = (e) => {
        e.preventDefault();
        const text = inputValue.trim();
        if (text && !isLoading) {
            setInputValue('');
            // Restore the text if the message was rejected (too long, out of
            // tokens, preflight failure) so the player never loses what they typed
            const restore = () => setInputValue(prev => prev || text);
            Promise.resolve(onSendMessage(text))
                .then(accepted => { if (accepted === false) restore(); })
                .catch(restore);
        }
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit(e);
        }
    };

    const showScenarios = gameLoaded && turn === 0 && chatHistory.length === 0 && !isLoading;

    return (
        <div className="sidebar" onClick={!settingsPage ? onDismissSettings : undefined}>
            {settingsPage ? (
                <div className="chat-container">
                    <SettingsPageView page={settingsPage} onClose={onDismissSettings} />
                </div>
            ) : showScenarios ? (
                <div className="chat-container">
                    <ScenarioSelector
                        onSelectScenario={onSelectScenario}
                        onCustomGame={onCustomGame}
                        gameList={gameList}
                        onShowLadder={onShowLadder}
                    />
                </div>
            ) : (
            <div className="chat-container" ref={chatContainerRef}>
                <div className="chat-scroll-row">
                    <div className="chat-messages">
                        {chatHistory.map((message) => (
                            <ChatMessage key={message.id} message={message} onRetry={onRetry} />
                        ))}
                        {isLoading && !chatHistory.some(m => m.streaming && m.content) && <TypingIndicator />}
                        {(gamePhase === 'game_over' || gamePhase === 'victory') ? (
                            <GameOverBanner epitaph={epitaph} turn={turn} playerTheme={playerTheme} shareSummary={shareSummary} achievements={achievements} isVictory={gamePhase === 'victory'} scenarioId={scenarioId} gameId={gameId} published={published} customScenario={customScenario} />
                        ) : choices && choices.length > 0 ? (
                            <ChoiceButtons
                                choices={choices}
                                onSelect={onSelectChoice}
                                disabled={isLoading}
                                onRequestIntel={onRequestIntel}
                            />
                        ) : null}
                        <div ref={chatEndRef} />
                    </div>
                </div>
            </div>
            )}

            {!settingsPage && !showScenarios && gamePhase !== 'game_over' && gamePhase !== 'victory' && (() => {
                const charLimit = turn === 0 ? 1000 : 500;
                const charWarning = Math.floor(charLimit * 0.8);
                return <form onSubmit={handleSubmit} className="chat-input-container">
                <div className="chat-input-box">
                    <AutoResizeTextarea
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder={turn === 0 ? "Describe your scenario..." : "Write a message..."}
                        className="chat-input"
                        disabled={isLoading}
                        maxLength={charLimit}
                    />
                    <div className="chat-input-footer">
                        {inputValue.length > charWarning && (
                            <span className="char-counter" style={{ color: inputValue.length >= charLimit ? 'var(--color-danger)' : '#888', fontSize: '11px', marginRight: 'auto' }}>
                                {inputValue.length}/{charLimit}
                            </span>
                        )}
                        <button
                            type="submit"
                            disabled={!inputValue.trim() || isLoading}
                            className="chat-send-btn"
                            aria-label="Send"
                        >
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                                <line x1="12" y1="19" x2="12" y2="5"></line>
                                <polyline points="5 12 12 5 19 12"></polyline>
                            </svg>
                        </button>
                    </div>
                </div>
            </form>;
            })()}
        </div>
    );
}
