<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password - Local Deep Research</title>

    <!-- Vite HMR for development -->
    {{ vite_hmr() }}

    <!-- SafeLogger must load before app.js which uses it at init -->
    <script src="/static/js/security/safe-logger.js"></script>
    <script src="/static/js/security/auth-validation.js"></script>
    <!-- Load all vendor dependencies and styles through Vite -->
    {{ vite_asset('js/app.js') }}
    <link rel="stylesheet" href="/static/css/themes.css">
    <link rel="stylesheet" href="/static/css/styles.css">
    <style>
        body {
            background-color: var(--bg-primary);
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
        }
        .ldr-change-password-container {
            background: var(--bg-secondary);
            padding: 2rem;
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            width: 100%;
            max-width: 450px;
        }
        .ldr-change-password-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .ldr-change-password-header h1 {
            color: var(--text-primary);
            font-size: 1.8rem;
            margin-bottom: 0.5rem;
        }
        .ldr-change-password-header p {
            color: var(--text-muted);
            margin: 0;
        }
        .form-floating {
            margin-bottom: 1rem;
        }
        .ldr-btn-change {
            width: 100%;
            padding: 0.75rem;
            font-size: 1.1rem;
        }
        .alert {
            margin-bottom: 1rem;
        }
        .ldr-warning-box {
            background-color: rgba(var(--accent-tertiary-rgb), 0.1);
            border-left: 4px solid var(--accent-tertiary);
            padding: 1rem;
            margin-bottom: 1.5rem;
            font-size: 0.9rem;
            color: var(--text-primary);
        }
        .ldr-warning-box i {
            color: var(--accent-tertiary);
        }
        .ldr-process-info {
            background-color: var(--bg-tertiary);
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1.5rem;
            font-size: 0.85rem;
            color: var(--text-secondary);
        }
        .ldr-process-info ul {
            margin-bottom: 0;
            padding-left: 1.5rem;
        }
        .ldr-auth-links {
            text-align: center;
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--border-color);
        }
        .ldr-password-strength {
            height: 4px;
            border-radius: 2px;
            margin-top: 0.5rem;
            transition: all 0.3s ease;
        }
        .ldr-strength-weak { background-color: var(--error-color); width: 33%; }
        .ldr-strength-medium { background-color: var(--warning-color); width: 66%; }
        .ldr-strength-strong { background-color: var(--success-color); width: 100%; }
    </style>
</head>
<body>
    <div class="ldr-change-password-container">
        <div class="ldr-change-password-header">
            <h1><i aria-hidden="true" class="fas fa-key"></i> Change Password</h1>
            <p>Update your encryption password</p>
        </div>

        <div class="ldr-warning-box">
            <i aria-hidden="true" class="fas fa-info-circle"></i>
            <strong>What happens when you change your password:</strong><br>
            Your entire database will be re-encrypted with the new password. This process may take a few moments.
        </div>

        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    {% if category == 'error' %}
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    {% elif category == 'success' %}
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {% elif category == 'info' %}
                    <div class="alert alert-info alert-dismissible fade show" role="alert">
                    {% elif category == 'warning' %}
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    {% else %}
                    <div class="alert alert-info alert-dismissible fade show" role="alert">
                    {% endif %}
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <form method="post" action="{{ url_for('auth.change_password') }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

            <div class="form-floating">
                <input type="password"
                       class="ldr-form-control"
                       id="current_password"
                       name="current_password"
                       placeholder="Current Password"
                       autocomplete="off"
                       required
                       autofocus>
                <label for="current_password">Current Password</label>
            </div>

            <hr class="my-3">

            <div class="ldr-process-info">
                <strong>New Password Requirements:</strong>
                <ul>
                    {% for req in password_requirements %}
                    <li>{{ req }}</li>
                    {% endfor %}
                    <li>Different from your current password</li>
                    <li>Remember to update your password manager</li>
                </ul>
            </div>

            <div class="form-floating">
                <input type="password"
                       class="ldr-form-control"
                       id="new_password"
                       name="new_password"
                       placeholder="New Password"
                       autocomplete="off"
                       required
                       minlength="8">
                <label for="new_password">New Password</label>
                <div id="password-strength" class="ldr-password-strength" style="display: none;"></div>
            </div>

            <div class="form-floating">
                <input type="password"
                       class="ldr-form-control"
                       id="confirm_password"
                       name="confirm_password"
                       placeholder="Confirm New Password"
                       autocomplete="off"
                       required
                       minlength="8">
                <label for="confirm_password">Confirm New Password</label>
            </div>

            <button type="submit" class="btn btn-primary ldr-btn-change">
                <i aria-hidden="true" class="fas fa-sync-alt"></i> Change Password
            </button>
        </form>

        <div class="ldr-auth-links">
            <a href="{{ url_for('index') }}">
                <i aria-hidden="true" class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
            <p class="text-muted small mt-3">
                <i aria-hidden="true" class="fas fa-shield-alt"></i>
                Your data remains encrypted during the password change
            </p>
        </div>
    </div>

    <script>
        const csrfToken = document.querySelector('input[name="csrf_token"]').value;
        const strengthBar = document.getElementById('password-strength');

        // Blur validation on new password field
        const newPasswordInput = document.getElementById('new_password');
        newPasswordInput.addEventListener('blur', function() {
            const value = this.value;
            if (value.length > 0) {
                validatePasswordViaAPI(value, csrfToken).then(result => {
                    if (!result.valid && result.errors.length > 0) {
                        this.classList.add('is-invalid');
                        // Show first error via alert-style inline (reuse existing pattern)
                        let errorEl = document.getElementById('new-password-error');
                        if (!errorEl) {
                            errorEl = document.createElement('div');
                            errorEl.id = 'new-password-error';
                            errorEl.style.color = 'var(--error-color)';
                            errorEl.style.fontSize = '0.85rem';
                            errorEl.style.marginTop = '0.25rem';
                            this.parentNode.appendChild(errorEl);
                        }
                        errorEl.textContent = result.errors[0];
                    } else {
                        this.classList.remove('is-invalid');
                        const errorEl = document.getElementById('new-password-error');
                        if (errorEl) errorEl.textContent = '';
                    }
                });
            }
        });

        // Strength indicator + clear error on input
        newPasswordInput.addEventListener('input', function() {
            const value = this.value;

            // Strength indicator (always show during typing - helpful feedback)
            if (value.length === 0) {
                strengthBar.style.display = 'none';
                this.classList.remove('is-invalid');
                var errorEl = document.getElementById('new-password-error');
                if (errorEl) errorEl.textContent = '';
                return;
            }

            strengthBar.style.display = 'block';
            let strength = 0;
            if (value.length >= 8) strength++;
            if (value.length >= 12) strength++;
            if (/[a-z]/.test(value)) strength++;
            if (/[0-9]/.test(value)) strength++;

            strengthBar.className = 'ldr-password-strength';
            if (strength <= 1) {
                strengthBar.classList.add('ldr-strength-weak');
            } else if (strength <= 3) {
                strengthBar.classList.add('ldr-strength-medium');
            } else {
                strengthBar.classList.add('ldr-strength-strong');
            }

            // If field was marked invalid, re-check via API to clear error
            if (this.classList.contains('is-invalid')) {
                validatePasswordViaAPI(value, csrfToken).then(result => {
                    if (result.valid) {
                        this.classList.remove('is-invalid');
                        const errorEl = document.getElementById('new-password-error');
                        if (errorEl) errorEl.textContent = '';
                    }
                });
            }
        });

        // Form validation
        document.querySelector('form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const currentPassword = document.getElementById('current_password').value;
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;

            if (newPassword !== confirmPassword) {
                alert('New passwords do not match!');
                return;
            }

            if (currentPassword === newPassword) {
                alert('New password must be different from current password!');
                return;
            }

            // Validate password strength via API (single source of truth)
            const result = await validatePasswordViaAPI(newPassword, csrfToken);
            if (!result.valid) {
                alert(result.errors?.[0] ?? 'Password does not meet requirements');
                return;
            }

            // All valid — submit the form
            this.submit();
        });
    </script>
</body>
</html>
