<!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: 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: 500px;
            border: 1px solid var(--color-border);
        }

        .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;
        }

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

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

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

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

        .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;
        }

        .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;
        }

        .security-tips {
            margin-top: 1.5rem;
            padding: 1rem;
            background: var(--color-info-light);
            border: 1px solid var(--color-info);
            border-radius: 8px;
            font-size: 0.85rem;
            color: var(--color-text-secondary);
        }

        .security-tips h4 {
            margin: 0 0 0.5rem 0;
            color: var(--color-info);
            font-size: 0.9rem;
        }

        .security-tips ul {
            margin: 0;
            padding-left: 1.2rem;
            line-height: 1.4;
        }

        .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);
            }
        }
    </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>Let's set up your master password to secure your anime collection.</p>
            </div>

            <form class="setup-form" id="setup-form">
                <div class="form-group">
                    <label for="directory" class="form-label">Anime Directory</label>
                    <input type="text" id="directory" name="directory" class="form-input" placeholder="C:\Anime"
                        value="{{ current_directory }}" required>
                    <div class="form-help">
                        The directory where your anime series are stored. This can be changed later in settings.
                    </div>
                </div>

                <div class="form-group">
                    <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">
                    <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 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 class="security-tips">
                <h4><i class="fas fa-shield-alt"></i> Security Tips</h4>
                <ul>
                    <li>Use a password with at least 12 characters</li>
                    <li>Include uppercase, lowercase, numbers, and symbols</li>
                    <li>Don't use personal information or common words</li>
                    <li>Consider using a password manager</li>
                </ul>
            </div>
        </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 = [];

            // Length check
            if (password.length >= 8) score++;
            if (password.length >= 12) score++;

            // Character variety
            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++;

            // Penalties
            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)';
            }
        }

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

        // Real-time password confirmation
        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)';
            }
        }

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

            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;
            const directory = directoryInput.value.trim();

            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;
            }

            if (!directory) {
                showMessage('Please enter a valid anime directory', 'error');
                return;
            }

            setLoading(true);

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

                const data = await response.json();

                if (response.ok && data.status === 'ok') {
                    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
        [passwordInput, confirmPasswordInput, directoryInput].forEach(input => {
            input.addEventListener('input', () => {
                messageContainer.innerHTML = '';
            });
        });
    </script>
</body>

</html>