{% extends "base.html" %}
{% from 'components/ui.html' import page_header %}

{% block content %}
{{ page_header(
    icon_class='fas fa-user-edit',
    title_text='Edit Profile',
    breadcrumbs=[
        {'text': 'Profile', 'url': url_for('auth.profile')},
        {'text': 'Edit'}
    ]
) }}

<div class="bg-card-light dark:bg-card-dark p-4 sm:p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm max-w-2xl mx-auto">
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div class="space-y-6">
            <div class="flex flex-col sm:flex-row items-center gap-4">
                <div class="relative">
                    {% if current_user.get_avatar_url() %}
                        <img id="avatar-preview" src="{{ current_user.get_avatar_url() }}" alt="{{ current_user.display_name }}" class="w-20 h-20 rounded-full object-cover border-4 border-primary shadow-lg" onerror="this.onerror=null; this.style.display='none'; document.getElementById('avatarPreviewFallback').style.display='flex';">
                        <div id="avatarPreviewFallback" class="w-20 h-20 rounded-full bg-gradient-to-br from-primary to-blue-600 text-white flex items-center justify-center font-bold text-3xl border-4 border-primary shadow-lg" style="display: none;">
                            {{ current_user.display_name[0:1].upper() }}
                        </div>
                    {% else %}
                        <img id="avatar-preview" style="display: none;" class="w-20 h-20 rounded-full object-cover border-4 border-primary shadow-lg">
                        <div id="avatarPreviewFallback" class="w-20 h-20 rounded-full bg-gradient-to-br from-primary to-blue-600 text-white flex items-center justify-center font-bold text-3xl border-4 border-primary shadow-lg">
                            {{ current_user.display_name[0:1].upper() }}
                        </div>
                    {% endif %}
                    <div class="absolute bottom-0 right-0 bg-primary text-white rounded-full p-1.5 shadow-lg">
                        <i class="fas fa-camera text-xs"></i>
                    </div>
                </div>
                <div class="flex-1">
                    <label for="avatar" class="form-label">Profile picture</label>
                    <input type="file" name="avatar" id="avatar" accept="image/png,image/jpeg,image/jpg,image/gif,image/webp" class="mt-1 block w-full text-sm text-gray-900 dark:text-gray-100 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary/90" onchange="previewAvatar(this)">
                    <p class="mt-1 text-xs text-text-muted-light dark:text-text-muted-dark">PNG, JPG, GIF, or WEBP up to 5MB.</p>
                    {% if current_user.has_avatar() %}
                    <form method="POST" action="{{ url_for('auth.remove_avatar') }}" class="mt-2" onsubmit="handleRemoveAvatar(event)">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="submit" class="text-red-600 hover:text-red-700 text-sm flex items-center gap-1">
                            <i class="fas fa-trash text-xs"></i>
                            Remove current picture
                        </button>
                    </form>
                    {% endif %}
                </div>
            </div>
            <div>
                <label for="username" class="form-label">Username</label>
                <input type="text" name="username" id="username" value="{{ current_user.username }}" disabled class="form-input bg-gray-100 dark:bg-gray-700">
            </div>
            <div>
                <label for="full_name" class="form-label">Full Name</label>
                <input type="text" name="full_name" id="full_name" value="{{ current_user.full_name or '' }}" class="form-input">
            </div>
            <div>
                <label for="preferred_language" class="form-label">Language</label>
                <select name="preferred_language" id="preferred_language" class="form-input">
                    {% for code, label in config['LANGUAGES'].items() %}
                    <option value="{{ code }}" {% if (current_user.preferred_language or current_language_code) == code %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
            </div>
            {% if requires_password %}
            <div>
                <label for="password" class="form-label">New Password</label>
                <input type="password" name="password" id="password" class="form-input" placeholder="{{ _('Leave blank to keep current password') }}" minlength="8">
                <div id="password-error" class="mt-1 text-sm text-red-600 dark:text-red-400 hidden"></div>
            </div>
            <div>
                <label for="password_confirm" class="form-label">Confirm New Password</label>
                <input type="password" name="password_confirm" id="password_confirm" class="form-input">
                <div id="password_confirm-error" class="mt-1 text-sm text-red-600 dark:text-red-400 hidden"></div>
            </div>
            {% endif %}
        </div>
        <div class="mt-8 border-t border-border-light dark:border-border-dark pt-6 flex flex-col-reverse sm:flex-row justify-end gap-3">
            <a href="{{ url_for('auth.profile') }}" class="btn btn-secondary text-center">Cancel</a>
            <button type="submit" id="save-button" class="btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">{{ _('Save Changes') }}</button>
        </div>
    </form>
</div>

<div class="bg-card-light dark:bg-card-dark p-4 sm:p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm max-w-2xl mx-auto mt-6">
    <h2 class="text-lg font-semibold mb-2">{{ _('Security') }}</h2>
    <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-4">
        {{ _('Manage two-factor authentication for your account.') }}
    </p>
    <a href="{{ url_for('auth.two_factor_setup') }}" class="btn btn-secondary">
        <i class="fas fa-shield-alt mr-2"></i>{{ _('Two-factor authentication') }}
    </a>
</div>

<script>
function previewAvatar(input) {
    const preview = document.getElementById('avatar-preview');
    const fallback = document.getElementById('avatarPreviewFallback');
    
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // Validate file size (5MB limit)
        if (file.size > 5 * 1024 * 1024) {
            alert('File size must be less than 5MB');
            input.value = '';
            return;
        }
        
        // Validate file type
        const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            alert('Invalid file type. Please select a valid image file (PNG, JPG, GIF, or WEBP).');
            input.value = '';
            return;
        }
        
        // Read and display the image
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            preview.onerror = null; // Reset error handler
            if (fallback) fallback.style.display = 'none';
        };
        reader.readAsDataURL(file);
    }
}

function handleRemoveAvatar(event) {
    // Show fallback after removing avatar
    const preview = document.getElementById('avatar-preview');
    const fallback = document.getElementById('avatarPreviewFallback');
    
    // Let the form submit, but prepare the UI for the fallback
    setTimeout(() => {
        if (preview) preview.style.display = 'none';
        if (fallback) fallback.style.display = 'flex';
    }, 100);
}

// Password validation
{% if requires_password %}
document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.getElementById('password');
    const passwordConfirmInput = document.getElementById('password_confirm');
    const passwordError = document.getElementById('password-error');
    const passwordConfirmError = document.getElementById('password_confirm-error');
    const saveButton = document.getElementById('save-button');
    const form = document.querySelector('form');
    
    if (!passwordInput || !passwordConfirmInput) {
        return; // Password fields not present
    }
    
    function validatePasswords() {
        const password = passwordInput.value.trim();
        const passwordConfirm = passwordConfirmInput.value.trim();
        let isValid = true;
        
        // Clear previous errors
        if (passwordError) {
            passwordError.classList.add('hidden');
            passwordError.textContent = '';
        }
        if (passwordConfirmError) {
            passwordConfirmError.classList.add('hidden');
            passwordConfirmError.textContent = '';
        }
        
        // If both fields are empty, that's valid (user wants to keep current password)
        if (!password && !passwordConfirm) {
            if (saveButton) {
                saveButton.disabled = false;
            }
            return true;
        }
        
        // If one field is filled but not the other, show error
        if ((password && !passwordConfirm) || (!password && passwordConfirm)) {
            if (passwordConfirmError) {
                passwordConfirmError.textContent = '{{ _("Please fill both password fields or leave both empty") }}';
                passwordConfirmError.classList.remove('hidden');
            }
            isValid = false;
        }
        
        // Validate password length if password is provided
        if (password) {
            if (password.length < 8) {
                if (passwordError) {
                    passwordError.textContent = '{{ _("Password must be at least 8 characters long") }}';
                    passwordError.classList.remove('hidden');
                }
                isValid = false;
            }
            
            // Check if passwords match
            if (passwordConfirm && password !== passwordConfirm) {
                if (passwordConfirmError) {
                    passwordConfirmError.textContent = '{{ _("Passwords do not match") }}';
                    passwordConfirmError.classList.remove('hidden');
                }
                isValid = false;
            }
        }
        
        // Enable/disable save button based on validation
        if (saveButton) {
            saveButton.disabled = !isValid;
        }
        
        return isValid;
    }
    
    // Add event listeners for real-time validation
    passwordInput.addEventListener('input', validatePasswords);
    passwordInput.addEventListener('blur', validatePasswords);
    passwordConfirmInput.addEventListener('input', validatePasswords);
    passwordConfirmInput.addEventListener('blur', validatePasswords);
    
    // Validate on form submit
    form.addEventListener('submit', function(e) {
        if (!validatePasswords()) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });
    
    // Initial validation
    validatePasswords();
});
{% endif %}
</script>
{% endblock %}


