<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Watchlist - Ohm Stream Downloader</title>
    <link rel="stylesheet" href="/static/css/style.css">

</head>
<body class="watchlist-body">
    <!-- Main Header -->
    <div style="text-align: center; margin-bottom: 20px;">
        <h1 style="background: linear-gradient(45deg, #00d9ff, #00ff88); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 32px; margin: 0;">⚡ Ohm Stream Downloader</h1>
        <p style="color: #888; font-size: 14px; margin: 5px 0 0;">Téléchargez vos vidéos, animes et séries</p>
    </div>
    
    <!-- User Info -->
    <div id="userInfo" style="display: none; max-width: 1200px; margin: 0 auto 15px; padding: 10px; background: rgba(0,217,255,0.1); border-radius: 8px; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #00d9ff;">👤 Connecté</span>
        <button class="btn-secondary btn-small" onclick="handleLogout()">🚪 Déconnexion</button>
    </div>
    
    <!-- Tabs -->
    <div class="tabs" style="max-width: 1200px; margin: 0 auto 20px; display: flex; gap: 5px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 10px;">
        <button class="tab" onclick="window.location.href='/web'">🏠 Accueil</button>
        <button class="tab" onclick="window.location.href='/web#anime'">🎬 Anime</button>
        <button class="tab" onclick="window.location.href='/web#series'">📺 Série</button>
        <button class="tab" onclick="window.location.href='/web#providers'">📦 Fournisseurs</button>
        <button class="tab active" onclick="window.location.href='/watchlist'">📋 Watchlist</button>
    </div>
    
    <div class="watchlist-container">
        <!-- Header -->
        <div class="watchlist-header">
            <h1>📋 Ma Watchlist</h1>
            <p>Suivez vos animes préférés et téléchargez automatiquement les nouveaux épisodes</p>
            <button type="button" class="btn-secondary watchlist-header-back-btn" onclick="window.location.href = '/web'">
                ← Retour à l'accueil
            </button>
        </div>

        <!-- Scheduler Status -->
        <div class="scheduler-status" id="schedulerStatus">
            <div class="scheduler-status-header">
                <div>
                    <h3>⏰ Planificateur Automatique</h3>
                    <div id="nextRunInfo" class="next-run-info">Chargement...</div>
                </div>
                <div class="scheduler-controls">
                    <button id="startSchedulerBtn" class="btn-primary btn-small watchlist-btn-small" onclick="handleStartScheduler()" style="display:none;">
                        ▶️ Démarrer
                    </button>
                    <button id="stopSchedulerBtn" class="btn-secondary btn-small watchlist-btn-small" onclick="handleStopScheduler()" style="display:none;">
                        ⏸️ Arrêter
                    </button>
                    <button class="btn-secondary btn-small watchlist-btn-small" onclick="handleCheckAll()">
                        🔍 Vérifier tout
                    </button>
                    <button class="btn-secondary btn-small watchlist-btn-small" onclick="handleOpenSettings()">
                        ⚙️ Paramètres
                    </button>
                </div>
            </div>
        </div>

        <!-- Filter Tabs -->
        <div class="filter-tabs">
            <button class="filter-tab active" onclick="filterWatchlist('all', this)">Tous</button>
            <button class="filter-tab" onclick="filterWatchlist('active', this)">Actifs</button>
            <button class="filter-tab" onclick="filterWatchlist('paused', this)">En pause</button>
            <button class="filter-tab" onclick="filterWatchlist('completed', this)">Terminés</button>
        </div>

        <!-- Watchlist Items -->
        <div id="watchlistContainer">
            <div class="watchlist-loading">Chargement de la watchlist...</div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="/static/js/api.js"></script>
    <script src="/static/js/utils.js"></script>
    <script src="/static/js/watchlist.js"></script>
    <script src="/static/js/watchlist-ui.js"></script>
    <script src="/static/js/auth.js"></script>

    <script>
        // Current filter
        let currentFilter = 'all';

        // Load watchlist on page load
        document.addEventListener('DOMContentLoaded', async () => {
            await checkAuth();
            await loadSchedulerStatus();
            await displayWatchlist();
        });

        /**
         * Check authentication
         */
        async function checkAuth() {
            const token = localStorage.getItem('auth_token');
            if (!token) {
                window.location.href = '/login';
                return false;
            }

            // Verify token with server
            try {
                const response = await fetch('/api/auth/me', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    // Token invalid, remove it and redirect
                    localStorage.removeItem('auth_token');
                    localStorage.removeItem('user');
                    window.location.href = '/login';
                    return false;
                }
                return true;
            } catch (error) {
                console.error('Auth check error:', error);
                window.location.href = '/login';
                return false;
            }
        }

        /**
         * Load scheduler status
         */
        async function loadSchedulerStatus() {
            try {
                const status = await getSchedulerStatus();
                updateSchedulerUI(status);
            } catch (error) {
                console.error('Error loading scheduler status:', error);
            }
        }

        /**
         * Update scheduler UI
         */
        function updateSchedulerUI(status) {
            const startBtn = document.getElementById('startSchedulerBtn');
            const stopBtn = document.getElementById('stopSchedulerBtn');
            const nextRunInfo = document.getElementById('nextRunInfo');

            // nextRunInfo is required, but buttons are optional
            if (!nextRunInfo) {
                console.warn('nextRunInfo element not found');
                return;
            }

            if (status.running) {
                // Update buttons if they exist
                if (startBtn) startBtn.style.display = 'none';
                if (stopBtn) stopBtn.style.display = 'inline-block';

                if (status.next_run) {
                    const nextRun = new Date(status.next_run);
                    nextRunInfo.innerHTML = `✓ En cours<br>Prochaine vérification: ${nextRun.toLocaleString('fr-FR')}`;
                } else {
                    // Scheduler running but no next_run yet (just started)
                    const interval = status.settings?.check_interval_hours || 6;
                    nextRunInfo.innerHTML = `✓ En cours<br>Vérification toutes les ${interval}h`;
                }
            } else {
                // Update buttons if they exist
                if (startBtn) startBtn.style.display = 'inline-block';
                if (stopBtn) stopBtn.style.display = 'none';
                nextRunInfo.innerHTML = '⏸️ Arrêté';
            }
        }

        /**
         * Filter watchlist
         */
        async function filterWatchlist(status, tabElement) {
            currentFilter = status;

            // Update tab styles
            document.querySelectorAll('.filter-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            tabElement.classList.add('active');

            // Reload with filter
            await displayWatchlist(status === 'all' ? null : status);
        }

        /**
         * Handle start scheduler
         */
        async function handleStartScheduler() {
            try {
                await startScheduler();
                await loadSchedulerStatus();
                alert('✅ Planificateur démarré!');
            } catch (error) {
                console.error('Error starting scheduler:', error);
                alert(`❌ Erreur: ${error.message}`);
            }
        }

        /**
         * Handle stop scheduler
         */
        async function handleStopScheduler() {
            try {
                await stopScheduler();
                await loadSchedulerStatus();
                alert('✅ Planificateur arrêté!');
            } catch (error) {
                console.error('Error stopping scheduler:', error);
                alert(`❌ Erreur: ${error.message}`);
            }
        }

        /**
         * Handle check all
         */
        async function handleCheckAll() {
            try {
                await checkAllWatchlistItems();
                await loadSchedulerStatus();
            } catch (error) {
                console.error('Error checking all:', error);
                alert(`❌ Erreur: ${error.message}`);
            }
        }

        /**
         * Handle open settings
         */
        async function handleOpenSettings() {
            try {
                const settings = await getWatchlistSettings();
                const modalHtml = createSettingsModal(settings);
                
                // Add modal to body
                const modalContainer = document.createElement('div');
                modalContainer.innerHTML = modalHtml;
                document.body.appendChild(modalContainer);
            } catch (error) {
                console.error('Error loading settings:', error);
                alert(`❌ Erreur: ${error.message}`);
            }
        }

        // Auto-refresh scheduler status every 30 seconds
        setInterval(loadSchedulerStatus, 30000);
    </script>
</body>
</html>