<!DOCTYPE html>
<html lang="fr" data-theme="ohmstream">
<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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body class="min-h-screen bg-base-100">
    <!-- Navbar -->
    <div class="navbar bg-base-200 border-b border-base-300 px-4">
        <div class="flex-1">
            <a href="/web" class="text-xl font-bold text-primary gap-2">
                <i class="fa-solid fa-bolt"></i> Ohm Stream
            </a>
        </div>
        <div class="flex-none">
            <ul class="menu menu-horizontal px-1 gap-1">
                <li><a href="/web"><i class="fa-solid fa-house"></i> Accueil</a></li>
                <li><a href="/web#anime"><i class="fa-solid fa-film"></i> Anime</a></li>
                <li><a href="/web#series"><i class="fa-solid fa-tv"></i> Série</a></li>
                <li><a href="/web#providers"><i class="fa-solid fa-box"></i> Fournisseurs</a></li>
                <li><a href="/watchlist" class="active bg-primary text-primary-content rounded-lg"><i class="fa-solid fa-clipboard-list"></i> Watchlist</a></li>
            </ul>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-6xl mx-auto px-4 py-6">
        <!-- Page Header -->
        <div class="flex justify-between items-start flex-wrap gap-4 mb-6">
            <div>
                <h1 class="text-2xl font-bold">
                    <i class="fa-solid fa-clipboard-list text-primary"></i> Ma Watchlist
                </h1>
                <p class="text-sm text-base-content/60 mt-1">
                    Suivez vos animes préférés et téléchargez automatiquement les nouveaux épisodes
                </p>
            </div>
            <a href="/web" class="btn btn-ghost btn-sm">
                <i class="fa-solid fa-arrow-left"></i> Retour à l'accueil
            </a>
        </div>

        <!-- Scheduler Status -->
        <div class="alert bg-base-200 border border-base-300 mb-4" id="schedulerStatus">
            <div class="flex-1">
                <div class="flex justify-between items-start flex-wrap gap-3">
                    <div>
                        <h3 class="font-semibold text-base-content">
                            <i class="fa-solid fa-clock text-primary"></i> Planificateur Automatique
                        </h3>
                        <div id="nextRunInfo" class="text-sm text-base-content/60 mt-1">Chargement...</div>
                    </div>
                    <div class="flex gap-2 flex-wrap">
                        <button id="startSchedulerBtn" class="btn btn-primary btn-sm hidden" onclick="handleStartScheduler()">
                            <i class="fa-solid fa-play"></i> Démarrer
                        </button>
                        <button id="stopSchedulerBtn" class="btn btn-ghost btn-sm hidden" onclick="handleStopScheduler()">
                            <i class="fa-solid fa-pause"></i> Arrêter
                        </button>
                        <button class="btn btn-ghost btn-sm" onclick="handleCheckAll()">
                            <i class="fa-solid fa-magnifying-glass"></i> Vérifier tout
                        </button>
                        <button class="btn btn-ghost btn-sm" onclick="handleOpenSettings()">
                            <i class="fa-solid fa-gear"></i> Paramètres
                        </button>
                    </div>
                </div>
            </div>
        </div>

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

        <!-- Watchlist Items -->
        <div id="watchlistContainer" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div class="col-span-full text-center py-12">
                <span class="loading loading-spinner loading-lg text-primary"></span>
                <p class="text-base-content/60 mt-3">Chargement de la watchlist...</p>
            </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.classList.add('hidden');
                if (stopBtn) stopBtn.classList.remove('hidden');

                if (status.next_run) {
                    const nextRun = new Date(status.next_run);
                    nextRunInfo.innerHTML = `<i class="fa-solid fa-check text-success"></i> 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 = `<i class="fa-solid fa-check text-success"></i> En cours<br>Vérification toutes les ${interval}h`;
                }
            } else {
                // Update buttons if they exist
                if (startBtn) startBtn.classList.remove('hidden');
                if (stopBtn) stopBtn.classList.add('hidden');
                nextRunInfo.innerHTML = '<i class="fa-solid fa-pause text-base-content/40"></i> Arrêté';
            }
        }

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

            // Update tab styles — DaisyUI uses tab-active
            document.querySelectorAll('.filter-tab').forEach(tab => {
                tab.classList.remove('tab-active');
            });
            tabElement.classList.add('tab-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>
