/**
 * CoinRush Missions Page Component
 * Beautiful missions UI with daily/weekly missions, rewards, and animations
 */

const { useState, useEffect, useRef, useCallback } = React;

// ============================================
// MISSION ICONS
// ============================================
const MissionIcons = {
    battle: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M14.5 10c-.83 0-1.5-.67-1.5-1.5v-5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5z"/>
            <path d="M20.5 10H19V8.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
            <path d="M9.5 14c.83 0 1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5S8 21.33 8 20.5v-5c0-.83.67-1.5 1.5-1.5z"/>
            <path d="M3.5 14H5v1.5c0 .83-.67 1.5-1.5 1.5S2 16.33 2 15.5 2.67 14 3.5 14z"/>
        </svg>
    ),
    trophy: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/>
            <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/>
            <path d="M4 22h16"/>
            <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/>
            <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/>
            <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/>
        </svg>
    ),
    coins: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="12" cy="12" r="10"/>
            <path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/>
            <path d="M12 18V6"/>
        </svg>
    ),
    fire: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>
        </svg>
    ),
    calendar: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
            <line x1="16" y1="2" x2="16" y2="6"/>
            <line x1="8" y1="2" x2="8" y2="6"/>
            <line x1="3" y1="10" x2="21" y2="10"/>
            <path d="M8 14h.01"/>
            <path d="M12 14h.01"/>
            <path d="M16 14h.01"/>
            <path d="M8 18h.01"/>
            <path d="M12 18h.01"/>
        </svg>
    ),
    star: (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
        </svg>
    ),
};

// Rarity colors
const RarityColors = {
    common: { bg: 'rgba(156, 163, 175, 0.15)', border: 'rgba(156, 163, 175, 0.4)', text: '#9ca3af', glow: 'rgba(156, 163, 175, 0.3)' },
    uncommon: { bg: 'rgba(34, 197, 94, 0.15)', border: 'rgba(34, 197, 94, 0.4)', text: '#22c55e', glow: 'rgba(34, 197, 94, 0.3)' },
    rare: { bg: 'rgba(59, 130, 246, 0.15)', border: 'rgba(59, 130, 246, 0.4)', text: '#3b82f6', glow: 'rgba(59, 130, 246, 0.3)' },
    epic: { bg: 'rgba(168, 85, 247, 0.15)', border: 'rgba(168, 85, 247, 0.4)', text: '#a855f7', glow: 'rgba(168, 85, 247, 0.4)' },
    legendary: { bg: 'rgba(245, 158, 11, 0.15)', border: 'rgba(245, 158, 11, 0.5)', text: '#f59e0b', glow: 'rgba(245, 158, 11, 0.5)' },
};

// ============================================
// FLOATING REWARD ANIMATION
// ============================================
function FloatingReward({ reward, onComplete }) {
    const [visible, setVisible] = useState(true);
    
    useEffect(() => {
        const timer = setTimeout(() => {
            setVisible(false);
            setTimeout(onComplete, 300);
        }, 2000);
        return () => clearTimeout(timer);
    }, [onComplete]);
    
    return (
        <div className={`floating-reward ${visible ? 'show' : 'hide'}`}>
            <div className="floating-reward-content">
                {reward.coins > 0 && (
                    <div className="floating-coins">
                        <span>+{reward.coins}</span>
                        <img src="/static/coinrushlogos.png" alt="coins" />
                    </div>
                )}
                {reward.xp > 0 && (
                    <div className="floating-xp">+{reward.xp} XP</div>
                )}
                {reward.lottery_tickets > 0 && (
                    <div className="floating-tickets">🎟️ +{reward.lottery_tickets} Lottery Ticket{reward.lottery_tickets > 1 ? 's' : ''}</div>
                )}
                {reward.badge && (
                    <div className="floating-badge">🏆 Badge Unlocked!</div>
                )}
                {reward.bonus && (
                    <div className="floating-bonus">{reward.bonus.message}</div>
                )}
            </div>
        </div>
    );
}

// ============================================
// MISSION CARD COMPONENT
// ============================================
function MissionCard({ mission, onClaim, isAnimating }) {
    const progress = Math.min(mission.progress || 0, mission.target);
    const progressPercent = Math.min(100, (progress / mission.target) * 100);
    const isCompleted = progress >= mission.target;
    const isClaimed = mission.claimed;
    const rarity = mission.rarity || 'common';
    const colors = RarityColors[rarity];
    const icon = MissionIcons[mission.icon] || MissionIcons.star;
    
    // Format target for display
    const formatTarget = (target, category) => {
        if (category === 'wager') {
            return Math.round(target / 100); // Convert hundredths to coins
        }
        return target;
    };
    
    const formatProgress = (progress, category) => {
        if (category === 'wager') {
            return Math.round(progress / 100);
        }
        return progress;
    };
    
    const displayProgress = formatProgress(progress, mission.category);
    const displayTarget = formatTarget(mission.target, mission.category);
    
    return (
        <div 
            className={`mission-card ${isCompleted ? 'completed' : ''} ${isClaimed ? 'claimed' : ''} ${isAnimating ? 'claiming' : ''} rarity-${rarity}`}
            style={{
                '--rarity-bg': colors.bg,
                '--rarity-border': colors.border,
                '--rarity-glow': colors.glow,
            }}
        >
            {/* Rarity indicator */}
            <div className="mission-rarity" style={{ color: colors.text }}>
                {rarity.charAt(0).toUpperCase() + rarity.slice(1)}
            </div>
            
            {/* Status badge */}
            {isClaimed && <div className="mission-status claimed">✓ Claimed</div>}
            {isCompleted && !isClaimed && <div className="mission-status ready">Ready!</div>}
            
            {/* Mission header */}
            <div className="mission-header">
                <div className="mission-icon" style={{ color: colors.text, background: colors.bg }}>
                    {icon}
                </div>
                <div className="mission-info">
                    <h3 className="mission-name">{mission.name}</h3>
                    <p className="mission-desc">{mission.description}</p>
                </div>
            </div>
            
            {/* Progress bar */}
            <div className="mission-progress">
                <div className="progress-bar-container">
                    <div 
                        className="progress-bar-fill" 
                        style={{ 
                            width: `${progressPercent}%`,
                            background: isCompleted 
                                ? 'linear-gradient(90deg, #22c55e, #4ade80)' 
                                : `linear-gradient(90deg, ${colors.text}, ${colors.glow})`
                        }}
                    />
                    <div className="progress-bar-shine" />
                </div>
                <div className="progress-text">
                    <span className="progress-current" style={{ color: isCompleted ? '#22c55e' : colors.text }}>
                        {displayProgress} / {displayTarget}
                    </span>
                    <span className="progress-percent">{Math.round(progressPercent)}%</span>
                </div>
            </div>
            
            {/* Rewards */}
            <div className="mission-rewards">
                <div className="rewards-list">
                    {mission.coin_reward > 0 && (
                        <div className="reward-item coins">
                            <img src="/static/coinrushlogos.png" alt="coins" />
                            <span>+{mission.coin_reward}</span>
                        </div>
                    )}
                    <div className="reward-item xp">
                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                        </svg>
                        <span>+{mission.xp_reward} XP</span>
                    </div>
                    {mission.bonus_reward && (
                        <div className="reward-item bonus" title={getBonusDescription(mission.bonus_reward)}>
                            <span className="bonus-badge">BONUS</span>
                            <span>{getBonusShortText(mission.bonus_reward)}</span>
                        </div>
                    )}
                </div>
                
                <button 
                    className={`claim-btn ${isCompleted && !isClaimed ? 'ready' : ''} ${isClaimed ? 'claimed' : ''}`}
                    onClick={() => onClaim(mission)}
                    disabled={!isCompleted || isClaimed || isAnimating}
                >
                    {isClaimed ? '✓ Claimed' : isCompleted ? 'Claim Reward' : `${Math.round(progressPercent)}%`}
                </button>
            </div>
        </div>
    );
}

function getBonusDescription(bonus) {
    switch (bonus.type) {
        case 'lottery_tickets': return `${bonus.amount} lottery ticket${bonus.amount > 1 ? 's' : ''} for the monthly draw`;
        case 'profile_badge': return `Unlock the "${bonus.badge_id}" profile badge`;
        case 'chat_emote': return `Unlock a new chat emote`;
        case 'xp_boost': return `${bonus.amount}% XP boost for ${bonus.duration / 60} minutes`;
        default: return 'Special bonus';
    }
}

function getBonusShortText(bonus) {
    switch (bonus.type) {
        case 'lottery_tickets': return `🎟️ ${bonus.amount} Ticket${bonus.amount > 1 ? 's' : ''}`;
        case 'profile_badge': return `🏆 Badge`;
        case 'chat_emote': return `😎 Emote`;
        case 'xp_boost': return `⚡ ${bonus.amount}% XP`;
        default: return 'Bonus';
    }
}

// ============================================
// COUNTDOWN TIMER
// ============================================
function CountdownTimer({ seconds, label }) {
    const [remaining, setRemaining] = useState(seconds);
    
    useEffect(() => {
        setRemaining(seconds);
    }, [seconds]);
    
    useEffect(() => {
        const interval = setInterval(() => {
            setRemaining(r => Math.max(0, r - 1));
        }, 1000);
        return () => clearInterval(interval);
    }, []);
    
    const hours = Math.floor(remaining / 3600);
    const minutes = Math.floor((remaining % 3600) / 60);
    const secs = remaining % 60;
    
    return (
        <div className="countdown-timer">
            <span className="countdown-label">{label}</span>
            <div className="countdown-time">
                <span className="time-block">{String(hours).padStart(2, '0')}</span>
                <span className="time-sep">:</span>
                <span className="time-block">{String(minutes).padStart(2, '0')}</span>
                <span className="time-sep">:</span>
                <span className="time-block">{String(secs).padStart(2, '0')}</span>
            </div>
        </div>
    );
}

// ============================================
// SUMMARY CARD
// ============================================
function SummaryCard({ icon, label, value, color, subtext }) {
    return (
        <div className="summary-card" style={{ '--card-color': color }}>
            <div className="summary-icon">{icon}</div>
            <div className="summary-content">
                <span className="summary-label">{label}</span>
                <span className="summary-value">{value}</span>
                {subtext && <span className="summary-subtext">{subtext}</span>}
            </div>
        </div>
    );
}

// ============================================
// MAIN MISSIONS APP
// ============================================
function MissionsApp() {
    const [missions, setMissions] = useState({ daily: [], weekly: [] });
    const [activeTab, setActiveTab] = useState('daily');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [claimingId, setClaimingId] = useState(null);
    const [floatingRewards, setFloatingRewards] = useState([]);
    const [dailyResetIn, setDailyResetIn] = useState(0);
    const [weeklyResetIn, setWeeklyResetIn] = useState(0);
    
    // Load missions
    const loadMissions = useCallback(async () => {
        try {
            const response = await fetch('/api/missions');
            if (!response.ok) {
                if (response.status === 401) {
                    setError('login');
                    return;
                }
                throw new Error('Failed to load missions');
            }
            const data = await response.json();
            setMissions({ daily: data.daily || [], weekly: data.weekly || [] });
            setDailyResetIn(data.daily_reset_in || 0);
            setWeeklyResetIn(data.weekly_reset_in || 0);
            setError(null);
        } catch (err) {
            console.error('Error loading missions:', err);
            setError('Failed to load missions');
        } finally {
            setLoading(false);
        }
    }, []);
    
    useEffect(() => {
        loadMissions();
    }, [loadMissions]);
    
    // Claim reward
    const handleClaim = async (mission) => {
        if (claimingId) return;
        
        setClaimingId(mission.id);
        
        try {
            const response = await fetch(`/api/missions/${mission.id}/claim`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            
            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Failed to claim');
            }
            
            const result = await response.json();
            
            // Show floating reward
            const rewardId = Date.now();
            setFloatingRewards(prev => [...prev, {
                id: rewardId,
                coins: result.coins_earned || 0,
                xp: result.xp_earned || 0,
                lottery_tickets: result.lottery_tickets_earned || 0,
                badge: result.badge_earned,
                bonus: result.bonus
            }]);
            
            // Update navbar balance
            if (window.CoinRushBalance && result.new_balance !== undefined) {
                window.CoinRushBalance.update(result.new_balance, (result.coins_earned || 0) * 100);
            }
            
            // Reload missions
            await loadMissions();
            
            // Show level up notification if applicable
            if (result.level_up) {
                // Could trigger a level up animation here
                console.log('Level up to', result.new_level);
            }
            
        } catch (err) {
            console.error('Claim error:', err);
            alert(err.message);
        } finally {
            setClaimingId(null);
        }
    };
    
    const removeFloatingReward = (id) => {
        setFloatingRewards(prev => prev.filter(r => r.id !== id));
    };
    
    // Calculate summary stats
    const activeMissions = activeTab === 'daily' ? missions.daily : missions.weekly;
    const completedCount = activeMissions.filter(m => m.claimed).length;
    const totalCoins = activeMissions.filter(m => !m.claimed).reduce((sum, m) => sum + (m.coin_reward || 0), 0);
    const totalXP = activeMissions.filter(m => !m.claimed).reduce((sum, m) => sum + (m.xp_reward || 0), 0);
    
    // Count unclaimed missions for badges
    const unclaimedDaily = missions.daily.filter(m => !m.claimed).length;
    const unclaimedWeekly = missions.weekly.filter(m => !m.claimed).length;
    const totalUnclaimed = unclaimedDaily + unclaimedWeekly;
    
    if (loading) {
        return (
            <div className="missions-loading">
                <div className="loading-spinner-large" />
                <span>Loading missions...</span>
            </div>
        );
    }
    
    if (error === 'login') {
        return (
            <div className="missions-login-required">
                <div className="login-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="64" height="64">
                        <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
                        <polyline points="10 17 15 12 10 7"/>
                        <line x1="15" y1="12" x2="3" y2="12"/>
                    </svg>
                </div>
                <h2>Login Required</h2>
                <p>Please log in to view and complete missions</p>
                <button className="login-btn" onClick={() => window.dispatchEvent(new CustomEvent('openAuthModal'))}>
                    Log In
                </button>
            </div>
        );
    }
    
    return (
        <div className="missions-app">
            {/* Floating rewards */}
            {floatingRewards.map(reward => (
                <FloatingReward 
                    key={reward.id} 
                    reward={reward} 
                    onComplete={() => removeFloatingReward(reward.id)}
                />
            ))}
            
            {/* Header */}
            <header className="missions-header">
                <div className="header-content">
                    <h1 className="missions-title">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="title-icon">
                            <path d="M9 11l3 3L22 4"/>
                            <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
                        </svg>
                        Daily Missions
                    </h1>
                    <p className="missions-subtitle">Complete missions to earn coins, XP, and exclusive rewards!</p>
                </div>
            </header>
            
            {/* Tab navigation */}
            <div className="missions-tabs">
                <button 
                    className={`tab-btn ${activeTab === 'daily' ? 'active' : ''}`}
                    onClick={() => setActiveTab('daily')}
                >
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="18" height="18">
                        <circle cx="12" cy="12" r="10"/>
                        <polyline points="12 6 12 12 16 14"/>
                    </svg>
                    <span>Daily</span>
                    <span className="tab-count">{unclaimedDaily}</span>
                </button>
                <button 
                    className={`tab-btn ${activeTab === 'weekly' ? 'active' : ''}`}
                    onClick={() => setActiveTab('weekly')}
                >
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="18" height="18">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                        <line x1="16" y1="2" x2="16" y2="6"/>
                        <line x1="8" y1="2" x2="8" y2="6"/>
                        <line x1="3" y1="10" x2="21" y2="10"/>
                    </svg>
                    <span>Weekly</span>
                    <span className="tab-count">{unclaimedWeekly}</span>
                </button>
                
                {/* Reset timer */}
                <CountdownTimer 
                    seconds={activeTab === 'daily' ? dailyResetIn : weeklyResetIn}
                    label={activeTab === 'daily' ? 'Resets in' : 'Week ends in'}
                />
            </div>
            
            {/* Summary cards */}
            <div className="missions-summary">
                <SummaryCard 
                    icon={<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>}
                    label="Progress"
                    value={`${completedCount}/${activeMissions.length}`}
                    color="#a855f7"
                    subtext="missions completed"
                />
                <SummaryCard 
                    icon={<img src="/static/coinrushlogos.png" alt="coins" style={{ width: 24, height: 24 }} />}
                    label="Coins Available"
                    value={totalCoins}
                    color="#4fffb0"
                    subtext="from unclaimed"
                />
                <SummaryCard 
                    icon={<svg viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>}
                    label="XP Available"
                    value={totalXP}
                    color="#f59e0b"
                    subtext="from unclaimed"
                />
            </div>
            
            {/* Mission grid */}
            <div className="missions-grid">
                {activeMissions.length === 0 ? (
                    <div className="no-missions">
                        <span>No missions available</span>
                    </div>
                ) : (
                    activeMissions.map(mission => (
                        <MissionCard 
                            key={mission.id}
                            mission={mission}
                            onClaim={handleClaim}
                            isAnimating={claimingId === mission.id}
                        />
                    ))
                )}
            </div>
        </div>
    );
}

// ============================================
// MAIN PAGE WRAPPER (manages user state for navbar)
// ============================================
function MissionsPage() {
    const [user, setUser] = useState(null);
    const [userLoading, setUserLoading] = useState(true);
    
    // Fetch user on mount
    const fetchUser = useCallback(async () => {
        try {
            const res = await fetch('/me', { credentials: 'include' });
            if (res.ok) {
                const data = await res.json();
                setUser(data);
            } else {
                setUser(null);
            }
        } catch (e) {
            console.error('Failed to fetch user:', e);
            setUser(null);
        } finally {
            setUserLoading(false);
        }
    }, []);
    
    useEffect(() => {
        fetchUser();
        
        // Listen for login/logout events
        const handleUserUpdated = () => fetchUser();
        window.addEventListener('userLoggedIn', handleUserUpdated);
        window.addEventListener('userLoggedOut', handleUserUpdated);
        
        return () => {
            window.removeEventListener('userLoggedIn', handleUserUpdated);
            window.removeEventListener('userLoggedOut', handleUserUpdated);
        };
    }, [fetchUser]);
    
    const handleLogout = async () => {
        try {
            await fetch('/logout', { method: 'POST', credentials: 'include' });
            setUser(null);
            window.dispatchEvent(new CustomEvent('userLoggedOut'));
        } catch (e) {
            console.error('Logout failed:', e);
        }
    };
    
    return (
        <div className="missions-page-wrapper">
            <CoinRushNavbar 
                user={user} 
                activePage="missions"
                isConnected={true}
                onLogout={handleLogout}
            />
            <main className="missions-main">
                <MissionsApp />
            </main>
        </div>
    );
}

// ============================================
// MOUNT APPLICATION
// ============================================
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MissionsPage />);
