// Game history sidebar — list of past games + settings panel

function TokenUsageBar() {
    const [usage, setUsage] = React.useState(null);

    React.useEffect(() => {
        if (typeof firebaseClient === 'undefined') return;
        const applyProfile = (profile) => {
            if (!profile) return;
            const sub = profile.subscription || {};
            const u = profile.usage || {};
            const limit = sub.tokenLimit || 0;
            const used = u.tokensUsed || 0;
            const bonus = u.bonusTokens || 0;
            setUsage({ used, limit, bonus });
        };
        // Use cached if available, otherwise fetch
        const cached = firebaseClient.getCachedProfile();
        if (cached) {
            applyProfile(cached);
        } else {
            firebaseClient.getUserProfile().then(applyProfile);
        }
        // Listen for profile updates
        const unsub = firebaseClient.onProfileChange(applyProfile);
        return () => unsub();
    }, []);

    if (!usage) return (
        <div className="token-usage-bar" style={{ marginBottom: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginBottom: 3 }}>
                <span className="shimmer" style={{ width: 32, height: 10, borderRadius: 3 }} />
                <span className="shimmer" style={{ width: 56, height: 10, borderRadius: 3 }} />
            </div>
            <div className="shimmer" style={{ height: 3, width: '100%', borderRadius: 2 }} />
        </div>
    );

    const total = usage.limit + usage.bonus;
    const remaining = Math.max(0, total - usage.used);
    const fmt = (n) => n >= 1000000 ? (n / 1000000).toFixed(1) + 'M' : n >= 1000 ? Math.round(n / 1000) + 'k' : String(n);
    const low = total <= 0 || remaining / total < 0.1;

    return (
        <div style={{ marginBottom: 4, fontSize: 13, color: low ? 'var(--color-danger)' : 'var(--color-text-muted)' }}>
            {fmt(remaining)} tokens remaining
        </div>
    );
}

function GameHistory({ games, currentGameId, onSelectGame, onNewGame, onDeleteGame, onDownload, onSignOut, user, isOpen, onSettingsPage, onCloseSettings, settingsPage, showSettings, onToggleSettings }) {
    const setShowSettings = (v) => onToggleSettings(v);

    const formatDate = (date) => {
        if (!date) return '';
        const now = new Date();
        const d = new Date(date);
        const diffMs = now - d;
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays === 0) return 'Today';
        if (diffDays === 1) return 'Yesterday';
        if (diffDays < 7) return `${diffDays}d ago`;
        if (diffDays < 30) {
            const weeks = Math.floor(diffDays / 7);
            return `${weeks}w ago`;
        }
        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    };

    return (
        <div className={`game-history ${isOpen ? 'open' : ''}`}>
            {/* Header: brand + new game */}
            <div className="game-history-header">
                <span className="game-history-brand">RISK</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <MusicPlayer />
                    <button onClick={onNewGame} className="new-game-btn" title="New game">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                            <path d="M12 5v14M5 12h14"></path>
                        </svg>
                    </button>
                </div>
            </div>

            {/* Sliding container: both panels side by side */}
            <div className="game-history-slider-wrapper">
                <div className={`game-history-slider ${showSettings ? 'show-settings' : ''}`}>
                    {/* Panel 1: Game list */}
                    <div className="game-history-panel">
                        <div className="game-history-list">
                            {games.map((game) => (
                                <div
                                    key={game.gameId}
                                    className={`game-history-item ${game.gameId === currentGameId ? 'active' : ''} ${game.gamePhase === 'game_over' ? 'game-over' : game.gamePhase === 'victory' ? 'game-victory' : ''}`}
                                    onClick={() => onSelectGame(game.gameId)}
                                >
                                    <div className="game-history-item-content">
                                        <div className="game-history-item-title">
                                            {game.playerTheme || 'New game'}
                                        </div>
                                        <div className="game-history-item-meta">
                                            {game.turn > 0 && (
                                                <span>Turn {game.turn}</span>
                                            )}
                                            {game.updatedAt && (
                                                <span>{formatDate(game.updatedAt)}</span>
                                            )}
                                        </div>
                                    </div>
                                    <div className="game-history-actions">
                                        {game.gameId === currentGameId && game.turn > 0 && (
                                            <button
                                                className="game-history-action-btn"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onDownload(game.gameId);
                                                }}
                                                title="Download"
                                            >
                                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                                    <polyline points="7 10 12 15 17 10"></polyline>
                                                    <line x1="12" y1="15" x2="12" y2="3"></line>
                                                </svg>
                                            </button>
                                        )}
                                        <button
                                            className="game-history-action-btn game-history-delete"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                onDeleteGame(game.gameId);
                                            }}
                                            title="Delete"
                                        >
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                                <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            ))}

                            {games.length === 0 && (
                                <div className="game-history-empty">
                                    No games yet
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Panel 2: Settings */}
                    <div className="game-history-panel">
                        <div className="game-history-list settings-list">
                            <div className="settings-spacer" />

                            <button className="settings-item" onClick={() => onSettingsPage('subscription')}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
                                    <line x1="1" y1="10" x2="23" y2="10"></line>
                                </svg>
                                Tokens
                            </button>

                            <button className="settings-item" onClick={() => onSettingsPage('ladder')}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M6 9H4.5a2.5 2.5 0 010-5C7 4 7 7 7 7"></path>
                                    <path d="M18 9h1.5a2.5 2.5 0 000-5C17 4 17 7 17 7"></path>
                                    <path d="M4 22h16"></path>
                                    <path d="M10 22V2h4v20"></path>
                                </svg>
                                Ladder
                            </button>

                            <button className="settings-item" onClick={() => onSettingsPage('privacy')}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
                                </svg>
                                Privacy policy
                            </button>

                            <button className="settings-item" onClick={() => onSettingsPage('terms')}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"></path>
                                    <polyline points="14 2 14 8 20 8"></polyline>
                                    <line x1="16" y1="13" x2="8" y2="13"></line>
                                    <line x1="16" y1="17" x2="8" y2="17"></line>
                                </svg>
                                Terms of use
                            </button>

                            {user?.uid === '1dsRA9mue0ORuGHUsbirBlAyRXr2' && (
                                <button className="settings-item" onClick={() => onSettingsPage('admin')}>
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
                                    </svg>
                                    Admin
                                </button>
                            )}

                            <button className="settings-item settings-item-danger" onClick={() => { if (typeof gtag === 'function') gtag('event', 'logout'); onSignOut(); }}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"></path>
                                    <polyline points="16 17 21 12 16 7"></polyline>
                                    <line x1="21" y1="12" x2="9" y2="12"></line>
                                </svg>
                                Sign out
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            {/* Footer: user email + token usage */}
            <div className="game-history-footer" onClick={() => { const next = !showSettings; setShowSettings(next); if (next) { if (typeof gtag === 'function') gtag('event', 'settings_open'); onSettingsPage('subscription'); } else { onCloseSettings?.(); } }}>
                <TokenUsageBar />
                <div className="game-history-user-row">
                    <div className="game-history-user-email">{user?.email}</div>
                    <svg className="game-history-user-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ transform: showSettings ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>
                        <polyline points="9 6 15 12 9 18"></polyline>
                    </svg>
                </div>
            </div>
        </div>
    );
}
