<!DOCTYPE html>
<html lang="en" data-theme="light">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AniWorld Manager - Setup</title>
    <link rel="stylesheet" href="/static/css/styles.css?v={{ static_v }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .setup-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, var(--color-primary-light) 0%, var(--color-primary) 100%);
            padding: 2rem 1rem;
        }

        .setup-card {
            background: var(--color-surface);
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 700px;
            border: 1px solid var(--color-border);
            max-height: 90vh;
            overflow-y: auto;
        }

        .setup-header {
            text-align: center;
            margin-bottom: 2rem;
        }

        .setup-header .logo {
            font-size: 3rem;
            color: var(--color-primary);
            margin-bottom: 0.5rem;
        }

        .setup-header h1 {
            margin: 0;
            color: var(--color-text);
            font-size: 1.8rem;
            font-weight: 600;
        }

        .setup-header p {
            margin: 1rem 0 0 0;
            color: var(--color-text-secondary);
            font-size: 1rem;
            line-height: 1.5;
        }

        .setup-form {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .config-section {
            border: 1px solid var(--color-border);
            border-radius: 8px;
            padding: 1rem;
            background: var(--color-background);
        }

        .section-header {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--color-text);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-header i {
            color: var(--color-primary);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-weight: 500;
            color: var(--color-text);
            font-size: 0.9rem;
        }

        .form-input, .form-select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid var(--color-border);
            border-radius: 8px;
            font-size: 1rem;
            background: var(--color-surface);
            color: var(--color-text);
            transition: all 0.2s ease;
            box-sizing: border-box;
        }

        .form-input:focus, .form-select:focus {
            outline: none;
            border-color: var(--color-primary);
            box-shadow: 0 0 0 3px rgba(var(--color-primary-rgb), 0.1);
        }

        .form-checkbox {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            cursor: pointer;
        }

        .form-checkbox input[type="checkbox"] {
            width: 1.2rem;
            height: 1.2rem;
            cursor: pointer;
        }

        .password-input-group {
            position: relative;
        }

        .password-input {
            padding-right: 3rem;
        }

        .password-toggle {
            position: absolute;
            right: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--color-text-secondary);
            cursor: pointer;
            padding: 0.25rem;
            border-radius: 4px;
            transition: color 0.2s ease;
        }

        .password-toggle:hover {
            color: var(--color-primary);
        }

        .password-strength {
            display: flex;
            gap: 0.25rem;
            margin-top: 0.5rem;
        }

        .strength-bar {
            flex: 1;
            height: 4px;
            background: var(--color-border);
            border-radius: 2px;
            transition: background-color 0.2s ease;
        }

        .strength-bar.active.weak {
            background: var(--color-error);
        }

        .strength-bar.active.fair {
            background: var(--color-warning);
        }

        .strength-bar.active.good {
            background: var(--color-info);
        }

        .strength-bar.active.strong {
            background: var(--color-success);
        }

        .strength-text {
            font-size: 0.8rem;
            color: var(--color-text-secondary);
            margin-top: 0.25rem;
        }

        .form-help {
            font-size: 0.8rem;
            color: var(--color-text-secondary);
            line-height: 1.4;
        }

        .scheduler-days-row {
            display: flex;
            flex-wrap: wrap;
            gap: 0.4rem;
            margin-top: 0.25rem;
        }

        .scheduler-day-toggle-label {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            cursor: pointer;
            padding: 0.3rem 0.6rem;
            border: 2px solid var(--color-border);
            border-radius: 6px;
            font-size: 0.85rem;
            font-weight: 500;
            background: var(--color-surface);
            color: var(--color-text-secondary);
            transition: all 0.15s ease;
            user-select: none;
        }

        .scheduler-day-toggle-label input[type="checkbox"] {
            display: none;
        }

        .scheduler-day-toggle-label:has(input:checked) {
            border-color: var(--color-primary);
            background: rgba(var(--color-primary-rgb), 0.12);
            color: var(--color-primary);
        }

        details.form-advanced > summary {
            cursor: pointer;
            color: var(--color-text-secondary);
            font-size: 0.85rem;
            margin-top: 0.5rem;
            user-select: none;
        }

        .setup-button {
            width: 100%;
            padding: 0.75rem;
            background: var(--color-primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }

        .setup-button:hover:not(:disabled) {
            background: var(--color-primary-dark);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(var(--color-primary-rgb), 0.3);
        }

        .setup-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .error-message {
            background: var(--color-error-light);
            color: var(--color-error);
            padding: 0.75rem;
            border-radius: 8px;
            border: 1px solid var(--color-error);
            font-size: 0.9rem;
        }

        .success-message {
            background: var(--color-success-light);
            color: var(--color-success);
            padding: 0.75rem;
            border-radius: 8px;
            border: 1px solid var(--color-success);
            font-size: 0.9rem;
        }

        .theme-toggle {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.5rem;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.2s ease;
            width: 2.5rem;
            height: 2.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .theme-toggle:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: scale(1.1);
        }

        .loading-spinner {
            width: 1rem;
            height: 1rem;
            border: 2px solid transparent;
            border-top: 2px solid currentColor;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="setup-container">
        <button class="theme-toggle" id="theme-toggle" title="Toggle theme">
            <i class="fas fa-moon"></i>
        </button>

        <div class="setup-card">
            <div class="setup-header">
                <div class="logo">
                    <i class="fas fa-play-circle"></i>
                </div>
                <h1>Welcome to AniWorld Manager</h1>
                <p>Configure your anime manager with all the settings you need.</p>
            </div>

            <form class="setup-form" id="setup-form">
                <!-- General Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-cog"></i>
                        General Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="name" class="form-label">Application Name</label>
                            <input type="text" id="name" name="name" class="form-input" value="Aniworld" required>
                        </div>
                        <div class="form-group">
                            <label for="data_dir" class="form-label">Data Directory</label>
                            <input type="text" id="data_dir" name="data_dir" class="form-input" value="data" required>
                        </div>
                        <div class="form-group full-width">
                            <label for="directory" class="form-label">Anime Directory *</label>
                            <input type="text" id="directory" name="directory" class="form-input" 
                                   placeholder="/path/to/your/anime" value="{{ current_directory }}" required>
                            <div class="form-help">
                                The directory where your anime series are stored.
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Security Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-shield-alt"></i>
                        Security Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="password" class="form-label">Master Password *</label>
                            <div class="password-input-group">
                                <input type="password" id="password" name="password" class="form-input password-input"
                                       placeholder="Create a strong password" required minlength="8">
                                <button type="button" class="password-toggle" id="password-toggle" tabindex="-1">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div class="password-strength">
                                <div class="strength-bar" id="strength-1"></div>
                                <div class="strength-bar" id="strength-2"></div>
                                <div class="strength-bar" id="strength-3"></div>
                                <div class="strength-bar" id="strength-4"></div>
                            </div>
                            <div class="strength-text" id="strength-text">Password strength will be shown here</div>
                        </div>
                        <div class="form-group full-width">
                            <label for="confirm-password" class="form-label">Confirm Password *</label>
                            <div class="password-input-group">
                                <input type="password" id="confirm-password" name="confirm-password"
                                       class="form-input password-input" placeholder="Confirm your password" required minlength="8">
                                <button type="button" class="password-toggle" id="confirm-password-toggle" tabindex="-1">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Scheduler Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-clock"></i>
                        Scheduler Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="scheduler_enabled" name="scheduler_enabled" checked>
                                <span>Enable Scheduler</span>
                            </label>
                            <div class="form-help">Automatically check for new episodes</div>
                        </div>
                        <div class="form-group">
                            <label for="scheduler_schedule_time" class="form-label">Run at (HH:MM)</label>
                            <input type="time" id="scheduler_schedule_time" name="scheduler_schedule_time"
                                   class="form-input" value="03:00">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group full-width">
                            <label class="form-label">Days of week</label>
                            <div class="scheduler-days-row">
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_mon" class="scheduler-day-setup-cb" value="mon" checked>
                                    <span>Mon</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_tue" class="scheduler-day-setup-cb" value="tue" checked>
                                    <span>Tue</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_wed" class="scheduler-day-setup-cb" value="wed" checked>
                                    <span>Wed</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_thu" class="scheduler-day-setup-cb" value="thu" checked>
                                    <span>Thu</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_fri" class="scheduler-day-setup-cb" value="fri" checked>
                                    <span>Fri</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_sat" class="scheduler-day-setup-cb" value="sat" checked>
                                    <span>Sat</span>
                                </label>
                                <label class="scheduler-day-toggle-label">
                                    <input type="checkbox" id="scheduler_day_sun" class="scheduler-day-setup-cb" value="sun" checked>
                                    <span>Sun</span>
                                </label>
                            </div>
                            <div class="form-help">Scheduler runs at the selected time on checked days. Uncheck all to disable scheduling.</div>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="scheduler_auto_download" name="scheduler_auto_download">
                                <span>Auto-download missing episodes after rescan</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="scheduler_folder_scan" name="scheduler_folder_scan">
                                <span>Run folder maintenance (NFO repair, renaming, poster checks)</span>
                            </label>
                            <div class="form-help">Automatically repair NFOs, rename folders, and check posters during scheduled runs</div>
                        </div>
                    </div>
                </div>

                <!-- Logging Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-file-alt"></i>
                        Logging Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="logging_level" class="form-label">Log Level</label>
                            <select id="logging_level" name="logging_level" class="form-select">
                                <option value="DEBUG">DEBUG</option>
                                <option value="INFO" selected>INFO</option>
                                <option value="WARNING">WARNING</option>
                                <option value="ERROR">ERROR</option>
                                <option value="CRITICAL">CRITICAL</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="logging_file" class="form-label">Log File (optional)</label>
                            <input type="text" id="logging_file" name="logging_file" class="form-input" 
                                   placeholder="logs/app.log">
                        </div>
                        <div class="form-group">
                            <label for="logging_max_bytes" class="form-label">Max File Size (bytes)</label>
                            <input type="number" id="logging_max_bytes" name="logging_max_bytes" 
                                   class="form-input" placeholder="10485760" min="0">
                        </div>
                        <div class="form-group">
                            <label for="logging_backup_count" class="form-label">Backup Count</label>
                            <input type="number" id="logging_backup_count" name="logging_backup_count" 
                                   class="form-input" value="3" min="0" required>
                        </div>
                    </div>
                </div>

                <!-- Backup Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-save"></i>
                        Backup Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="backup_enabled" name="backup_enabled">
                                <span>Enable Backups</span>
                            </label>
                            <div class="form-help">Automatically backup configuration</div>
                        </div>
                        <div class="form-group">
                            <label for="backup_keep_days" class="form-label">Keep Days</label>
                            <input type="number" id="backup_keep_days" name="backup_keep_days" 
                                   class="form-input" value="30" min="0" required>
                        </div>
                        <div class="form-group full-width">
                            <label for="backup_path" class="form-label">Backup Path</label>
                            <input type="text" id="backup_path" name="backup_path" class="form-input" 
                                   value="data/backups" required>
                        </div>
                    </div>
                </div>

                <!-- NFO/Metadata Settings -->
                <div class="config-section">
                    <div class="section-header">
                        <i class="fas fa-info-circle"></i>
                        NFO & Metadata Settings
                    </div>
                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="nfo_tmdb_api_key" class="form-label">TMDB API Key (optional)</label>
                            <input type="text" id="nfo_tmdb_api_key" name="nfo_tmdb_api_key" class="form-input" 
                                   placeholder="Enter your TMDB API key">
                            <div class="form-help">Required for fetching metadata from TMDB</div>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="nfo_auto_create" name="nfo_auto_create" checked>
                                <span>Auto-create NFO files</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="nfo_update_on_scan" name="nfo_update_on_scan" checked>
                                <span>Update on scan</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="nfo_download_poster" name="nfo_download_poster" checked>
                                <span>Download posters</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="nfo_download_logo" name="nfo_download_logo" checked>
                                <span>Download logos</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label class="form-checkbox">
                                <input type="checkbox" id="nfo_download_fanart" name="nfo_download_fanart" checked>
                                <span>Download fanart</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label for="nfo_image_size" class="form-label">Image Size</label>
                            <select id="nfo_image_size" name="nfo_image_size" class="form-select">
                                <option value="original" selected>Original</option>
                                <option value="w500">W500</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div id="message-container"></div>

                <button type="submit" class="setup-button" id="setup-button">
                    <i class="fas fa-check"></i>
                    <span>Complete Setup</span>
                </button>
            </form>
        </div>
    </div>

    <script>
        // Theme toggle functionality
        const themeToggle = document.getElementById('theme-toggle');
        const htmlElement = document.documentElement;

        const savedTheme = localStorage.getItem('theme') || 'light';
        htmlElement.setAttribute('data-theme', savedTheme);
        updateThemeIcon(savedTheme);

        themeToggle.addEventListener('click', () => {
            const currentTheme = htmlElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';

            htmlElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcon(newTheme);
        });

        function updateThemeIcon(theme) {
            const icon = themeToggle.querySelector('i');
            icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        }

        // Password visibility toggles
        document.querySelectorAll('.password-toggle').forEach(toggle => {
            toggle.addEventListener('click', () => {
                const input = toggle.parentElement.querySelector('input');
                const type = input.getAttribute('type');
                const newType = type === 'password' ? 'text' : 'password';
                const icon = toggle.querySelector('i');

                input.setAttribute('type', newType);
                icon.className = newType === 'password' ? 'fas fa-eye' : 'fas fa-eye-slash';
            });
        });

        // Password strength checker
        const passwordInput = document.getElementById('password');
        const strengthBars = document.querySelectorAll('.strength-bar');
        const strengthText = document.getElementById('strength-text');

        passwordInput.addEventListener('input', () => {
            const password = passwordInput.value;
            const strength = calculatePasswordStrength(password);
            updatePasswordStrength(strength);
        });

        function calculatePasswordStrength(password) {
            let score = 0;
            let feedback = [];

            if (password.length >= 8) score++;
            if (password.length >= 12) score++;
            if (/[a-z]/.test(password)) score++;
            if (/[A-Z]/.test(password)) score++;
            if (/[0-9]/.test(password)) score++;
            if (/[^A-Za-z0-9]/.test(password)) score++;

            if (password.length < 8) {
                feedback.push('Too short');
                score = Math.max(0, score - 2);
            }

            if (!/[A-Z]/.test(password)) feedback.push('Add uppercase');
            if (!/[0-9]/.test(password)) feedback.push('Add numbers');
            if (!/[^A-Za-z0-9]/.test(password)) feedback.push('Add symbols');

            const strengthLevels = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong', 'Very Strong'];
            const strengthLevel = Math.min(Math.floor(score / 1.2), 5);

            return {
                score: Math.min(score, 6),
                level: strengthLevel,
                text: strengthLevels[strengthLevel],
                feedback
            };
        }

        function updatePasswordStrength(strength) {
            const colors = ['weak', 'weak', 'fair', 'good', 'strong', 'strong'];
            const color = colors[strength.level];

            strengthBars.forEach((bar, index) => {
                bar.className = 'strength-bar';
                if (index < strength.score) {
                    bar.classList.add('active', color);
                }
            });

            if (passwordInput.value) {
                let text = `Password strength: ${strength.text}`;
                if (strength.feedback.length > 0) {
                    text += ` (${strength.feedback.join(', ')})`;
                }
                strengthText.textContent = text;
                strengthText.style.color = strength.level >= 3 ? 'var(--color-success)' : 'var(--color-warning)';
            } else {
                strengthText.textContent = 'Password strength will be shown here';
                strengthText.style.color = 'var(--color-text-secondary)';
            }
        }

        // Real-time password confirmation
        const confirmPasswordInput = document.getElementById('confirm-password');
        confirmPasswordInput.addEventListener('input', validatePasswordMatch);
        passwordInput.addEventListener('input', validatePasswordMatch);

        function validatePasswordMatch() {
            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;

            if (confirmPassword && password !== confirmPassword) {
                confirmPasswordInput.setCustomValidity('Passwords do not match');
                confirmPasswordInput.style.borderColor = 'var(--color-error)';
            } else {
                confirmPasswordInput.setCustomValidity('');
                confirmPasswordInput.style.borderColor = 'var(--color-border)';
            }
        }

        // Form submission
        const setupForm = document.getElementById('setup-form');
        const setupButton = document.getElementById('setup-button');
        const messageContainer = document.getElementById('message-container');

        setupForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;

            if (password !== confirmPassword) {
                showMessage('Passwords do not match', 'error');
                return;
            }

            const strength = calculatePasswordStrength(password);
            if (strength.level < 2) {
                showMessage('Password is too weak. Please use a stronger password.', 'error');
                return;
            }

            setLoading(true);

            // Collect all form data
            const formData = {
                master_password: password,
                anime_directory: document.getElementById('directory').value.trim(),
                name: document.getElementById('name').value.trim(),
                data_dir: document.getElementById('data_dir').value.trim(),
                scheduler_enabled: document.getElementById('scheduler_enabled').checked,
                scheduler_schedule_time: document.getElementById('scheduler_schedule_time').value || '03:00',
                scheduler_schedule_days: Array.from(document.querySelectorAll('.scheduler-day-setup-cb:checked')).map(cb => cb.value),
                scheduler_auto_download_after_rescan: document.getElementById('scheduler_auto_download').checked,
                scheduler_folder_scan_enabled: document.getElementById('scheduler_folder_scan').checked,
                logging_level: document.getElementById('logging_level').value,
                logging_file: document.getElementById('logging_file').value.trim() || null,
                logging_max_bytes: document.getElementById('logging_max_bytes').value ? 
                    parseInt(document.getElementById('logging_max_bytes').value) : null,
                logging_backup_count: parseInt(document.getElementById('logging_backup_count').value),
                backup_enabled: document.getElementById('backup_enabled').checked,
                backup_path: document.getElementById('backup_path').value.trim(),
                backup_keep_days: parseInt(document.getElementById('backup_keep_days').value),
                nfo_tmdb_api_key: document.getElementById('nfo_tmdb_api_key').value.trim() || null,
                nfo_auto_create: document.getElementById('nfo_auto_create').checked,
                nfo_update_on_scan: document.getElementById('nfo_update_on_scan').checked,
                nfo_download_poster: document.getElementById('nfo_download_poster').checked,
                nfo_download_logo: document.getElementById('nfo_download_logo').checked,
                nfo_download_fanart: document.getElementById('nfo_download_fanart').checked,
                nfo_image_size: document.getElementById('nfo_image_size').value
            };

            try {
                const response = await fetch('/api/auth/setup', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                if (response.ok && data.status === 'ok') {
                    // Redirect to loading page if provided, otherwise go to login
                    if (data.redirect) {
                        showMessage('Setup saved! Initializing your anime library...', 'success');
                        setTimeout(() => {
                            window.location.href = data.redirect;
                        }, 500);
                    } else {
                        showMessage('Setup completed successfully! Redirecting to login...', 'success');
                        setTimeout(() => {
                            window.location.href = '/login';
                        }, 2000);
                    }
                } else {
                    const errorMessage = data.detail || data.message || 'Setup failed';
                    showMessage(errorMessage, 'error');
                }
            } catch (error) {
                showMessage('Setup failed. Please try again.', 'error');
                console.error('Setup error:', error);
            } finally {
                setLoading(false);
            }
        });

        function showMessage(message, type) {
            messageContainer.innerHTML = `
                <div class="${type}-message">
                    ${message}
                </div>
            `;
        }

        function setLoading(loading) {
            setupButton.disabled = loading;
            const buttonText = setupButton.querySelector('span');
            const buttonIcon = setupButton.querySelector('i');

            if (loading) {
                buttonIcon.className = 'loading-spinner';
                buttonText.textContent = 'Setting up...';
            } else {
                buttonIcon.className = 'fas fa-check';
                buttonText.textContent = 'Complete Setup';
            }
        }

        // Clear message on input
        document.querySelectorAll('input, select').forEach(input => {
            input.addEventListener('input', () => {
                messageContainer.innerHTML = '';
            });
        });
    </script>
</body>

</html>
