{% extends 'base.html' %}
{% load static %}

{% block title %}Changer mon mot de passe - Contrôle Technique{% endblock %}

{% block extra_css %}
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --danger-gradient: linear-gradient(135deg, #f56565 0%, #c53030 100%);
        --success-gradient: linear-gradient(135deg, #48bb78 0%, #2f855a 100%);
        --warning-gradient: linear-gradient(135deg, #ed8936 0%, #c05621 100%);
    }

    .password-page {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        min-height: calc(100vh - 72px);
        padding: 40px 0;
    }

    .password-card {
        background: white;
        border-radius: 30px;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        overflow: hidden;
        animation: slideUpFade 0.8s ease-out;
        max-width: 600px;
        margin: 0 auto;
    }

    @keyframes slideUpFade {
        from {
            opacity: 0;
            transform: translateY(50px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Header */
    .password-header {
        background: var(--primary-gradient);
        padding: 40px 30px;
        text-align: center;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .password-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 70%);
        animation: rotate 20s linear infinite;
    }

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

    .password-header i {
        font-size: 4rem;
        background: rgba(255, 255, 255, 0.2);
        padding: 20px;
        border-radius: 50%;
        margin-bottom: 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        animation: float 3s ease-in-out infinite;
    }

    @keyframes float {
        0% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
        100% { transform: translateY(0px); }
    }

    .password-header h2 {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 10px;
        letter-spacing: -0.5px;
    }

    .password-header p {
        opacity: 0.9;
        font-size: 1rem;
        margin: 0;
    }

    /* Body */
    .password-body {
        padding: 40px;
    }

    /* Form groups */
    .form-group {
        margin-bottom: 25px;
        position: relative;
    }

    .form-group i {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #a0aec0;
        font-size: 1.2rem;
        transition: all 0.3s ease;
        z-index: 10;
    }

    .form-group.focused i {
        color: #667eea;
        transform: translateY(-50%) scale(1.1);
    }

    .form-control {
        height: 55px;
        padding-left: 45px;
        padding-right: 45px;
        border: 2px solid #e2e8f0;
        border-radius: 15px;
        font-size: 1rem;
        font-weight: 500;
        transition: all 0.3s ease;
        width: 100%;
    }

    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        outline: none;
    }

    .toggle-password {
        position: absolute;
        right: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #a0aec0;
        cursor: pointer;
        font-size: 1.2rem;
        transition: all 0.3s ease;
        z-index: 10;
    }

    .toggle-password:hover {
        color: #667eea;
    }

    /* Password strength meter */
    .password-strength {
        margin-top: 10px;
        padding: 0 5px;
    }

    .strength-bars {
        display: flex;
        gap: 5px;
        margin-bottom: 5px;
    }

    .strength-bar {
        height: 5px;
        flex: 1;
        background: #e2e8f0;
        border-radius: 5px;
        transition: all 0.3s ease;
    }

    .strength-bar.active {
        background: var(--primary-gradient);
    }

    .strength-bar.weak {
        background: linear-gradient(135deg, #f56565 0%, #c53030 100%);
    }

    .strength-bar.medium {
        background: linear-gradient(135deg, #ed8936 0%, #c05621 100%);
    }

    .strength-bar.strong {
        background: linear-gradient(135deg, #48bb78 0%, #2f855a 100%);
    }

    .strength-text {
        font-size: 0.85rem;
        color: #718096;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .strength-label {
        font-weight: 600;
    }

    .strength-value {
        padding: 3px 10px;
        border-radius: 20px;
        font-size: 0.8rem;
        font-weight: 600;
    }

    .strength-value.weak {
        background: #fed7d7;
        color: #c53030;
    }

    .strength-value.medium {
        background: #feebc8;
        color: #c05621;
    }

    .strength-value.strong {
        background: #c6f6d5;
        color: #2f855a;
    }

    /* Password requirements */
    .password-requirements {
        background: #f7fafc;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 25px;
        border: 2px solid #e2e8f0;
    }

    .requirements-title {
        font-size: 0.95rem;
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .requirements-list {
        list-style: none;
        padding: 0;
        margin: 0;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
    }

    .requirement-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 0.9rem;
        color: #4a5568;
        transition: all 0.3s ease;
    }

    .requirement-item i {
        font-size: 1rem;
        color: #a0aec0;
    }

    .requirement-item.valid i {
        color: #48bb78;
    }

    .requirement-item.invalid i {
        color: #f56565;
    }

    /* Buttons */
    .btn-submit {
        width: 100%;
        height: 55px;
        background: var(--primary-gradient);
        border: none;
        border-radius: 15px;
        color: white;
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        margin-bottom: 15px;
    }

    .btn-submit::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
        transition: left 0.5s ease;
    }

    .btn-submit:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
    }

    .btn-submit:hover::before {
        left: 100%;
    }

    .btn-submit:active {
        transform: translateY(0);
    }

    .btn-submit:disabled {
        opacity: 0.7;
        cursor: not-allowed;
    }

    .btn-cancel {
        width: 100%;
        height: 55px;
        background: white;
        border: 2px solid #e2e8f0;
        border-radius: 15px;
        color: #4a5568;
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        text-decoration: none;
    }

    .btn-cancel:hover {
        background: #f7fafc;
        border-color: #cbd5e0;
        transform: translateY(-2px);
    }

    /* Alerts */
    .custom-alert {
        border-radius: 15px;
        padding: 15px 20px;
        margin-bottom: 25px;
        border: none;
        display: flex;
        align-items: center;
        gap: 10px;
        animation: slideInRight 0.5s ease-out;
    }

    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(30px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    .alert-danger {
        background: linear-gradient(135deg, #fee 0%, #ffe5e5 100%);
        color: #e53e3e;
        border-left: 4px solid #e53e3e;
    }

    .alert-success {
        background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
        color: #2e7d32;
        border-left: 4px solid #2e7d32;
    }

    .alert-warning {
        background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
        color: #ef6c00;
        border-left: 4px solid #ef6c00;
    }

    .alert-info {
        background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
        color: #1976d2;
        border-left: 4px solid #1976d2;
    }

    /* Loading spinner */
    .loader {
        display: none;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(255,255,255,0.3);
        border-top: 3px solid white;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
        margin-left: 10px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .btn-content {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }

    /* Password match indicator */
    .password-match {
        margin-top: 10px;
        font-size: 0.9rem;
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 15px;
        border-radius: 10px;
        transition: all 0.3s ease;
    }

    .password-match.match {
        background: #c6f6d5;
        color: #2f855a;
    }

    .password-match.no-match {
        background: #fed7d7;
        color: #c53030;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .password-body {
            padding: 30px 20px;
        }

        .requirements-list {
            grid-template-columns: 1fr;
        }

        .password-header h2 {
            font-size: 1.5rem;
        }

        .password-header i {
            font-size: 3rem;
            padding: 15px;
        }
    }

    /* Animation for success */
    @keyframes checkmark {
        0% { transform: scale(0); }
        50% { transform: scale(1.2); }
        100% { transform: scale(1); }
    }

    .success-check {
        animation: checkmark 0.5s ease-in-out;
    }
</style>
{% endblock %}

{% block content %}
<div class="password-page">
    <div class="container">
        <div class="password-card">
            <!-- Header -->
            <div class="password-header">
                <i class="bi bi-shield-lock"></i>
                <h2>Changer mon mot de passe</h2>
                <p>Protégez votre compte avec un mot de passe sécurisé</p>
            </div>

            <!-- Body -->
            <div class="password-body">
                {% if messages %}
                    {% for message in messages %}
                        <div class="custom-alert alert-{{ message.tags }} animate__animated animate__fadeInDown">
                            <i class="bi bi-{% if message.tags == 'success' %}check-circle{% elif message.tags == 'error' %}exclamation-triangle{% else %}info-circle{% endif %}-fill"></i>
                            <span>{{ message }}</span>
                        </div>
                    {% endfor %}
                {% endif %}

                {% if form.errors %}
                    <div class="custom-alert alert-danger">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <strong>Erreurs :</strong>
                            <ul class="mb-0 mt-2">
                                {% for field, errors in form.errors.items %}
                                    {% for error in errors %}
                                        <li>{{ error }}</li>
                                    {% endfor %}
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                {% endif %}

                <form method="post" action="{% url 'cores:change_password' %}" id="password-form">
                    {% csrf_token %}

                    <!-- Ancien mot de passe -->
                    <div class="form-group" id="old-password-group">
                        <i class="bi bi-lock"></i>
                        <input type="password" 
                               name="old_password" 
                               class="form-control" 
                               placeholder="Ancien mot de passe" 
                               required
                               id="old-password"
                               autofocus>
                        <i class="bi bi-eye toggle-password" data-target="old-password"></i>
                    </div>

                    <!-- Nouveau mot de passe -->
                    <div class="form-group" id="new-password1-group">
                        <i class="bi bi-shield"></i>
                        <input type="password" 
                               name="new_password1" 
                               class="form-control" 
                               placeholder="Nouveau mot de passe" 
                               required
                               id="new-password1">
                        <i class="bi bi-eye toggle-password" data-target="new-password1"></i>
                    </div>

                    <!-- Password strength meter -->
                    <div class="password-strength" id="password-strength" style="display: none;">
                        <div class="strength-bars">
                            <div class="strength-bar" id="bar1"></div>
                            <div class="strength-bar" id="bar2"></div>
                            <div class="strength-bar" id="bar3"></div>
                            <div class="strength-bar" id="bar4"></div>
                            <div class="strength-bar" id="bar5"></div>
                        </div>
                        <div class="strength-text">
                            <span class="strength-label">Force du mot de passe :</span>
                            <span class="strength-value" id="strength-value">Faible</span>
                        </div>
                    </div>

                    <!-- Password requirements -->
                    <div class="password-requirements">
                        <div class="requirements-title">
                            <i class="bi bi-check-circle"></i>
                            Exigences du mot de passe
                        </div>
                        <ul class="requirements-list">
                            <li class="requirement-item" id="req-length">
                                <i class="bi bi-x-circle"></i>
                                Au moins 8 caractères
                            </li>
                            <li class="requirement-item" id="req-uppercase">
                                <i class="bi bi-x-circle"></i>
                                Une lettre majuscule
                            </li>
                            <li class="requirement-item" id="req-lowercase">
                                <i class="bi bi-x-circle"></i>
                                Une lettre minuscule
                            </li>
                            <li class="requirement-item" id="req-number">
                                <i class="bi bi-x-circle"></i>
                                Un chiffre
                            </li>
                            <li class="requirement-item" id="req-special">
                                <i class="bi bi-x-circle"></i>
                                Un caractère spécial
                            </li>
                            <li class="requirement-item" id="req-no-username">
                                <i class="bi bi-x-circle"></i>
                                Pas similaire au nom d'utilisateur
                            </li>
                        </ul>
                    </div>

                    <!-- Confirmation -->
                    <div class="form-group" id="new-password2-group">
                        <i class="bi bi-shield-check"></i>
                        <input type="password" 
                               name="new_password2" 
                               class="form-control" 
                               placeholder="Confirmer le nouveau mot de passe" 
                               required
                               id="new-password2">
                        <i class="bi bi-eye toggle-password" data-target="new-password2"></i>
                    </div>

                    <!-- Password match indicator -->
                    <div class="password-match" id="password-match" style="display: none;">
                        <i class="bi bi-check-circle-fill"></i>
                        <span>Les mots de passe correspondent</span>
                    </div>

                    <!-- Buttons -->
                    <button type="submit" class="btn-submit" id="submit-btn">
                        <span class="btn-content">
                            <i class="bi bi-shield-check"></i>
                            <span>Changer le mot de passe</span>
                            <span class="loader" id="loader"></span>
                        </span>
                    </button>

                    <a href="{% url 'cores:profile' %}" class="btn-cancel">
                        <i class="bi bi-arrow-left"></i>
                        Retour au profil
                    </a>
                </form>

                <!-- Security tips -->
                <div class="alert alert-info mt-4" style="background: #e3f2fd; border-left: 4px solid #1976d2; border-radius: 10px;">
                    <div class="d-flex align-items-center gap-3">
                        <i class="bi bi-shield-fill-check" style="font-size: 2rem; color: #1976d2;"></i>
                        <div>
                            <h6 style="color: #1976d2; font-weight: 600;">Conseils de sécurité :</h6>
                            <p class="mb-0 small" style="color: #2c3e50;">
                                Utilisez un mot de passe unique que vous n'utilisez pas ailleurs. 
                                Évitez les informations personnelles comme votre nom ou date de naissance.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Elements
        const oldPassword = document.getElementById('old-password');
        const newPassword1 = document.getElementById('new-password1');
        const newPassword2 = document.getElementById('new-password2');
        const submitBtn = document.getElementById('submit-btn');
        const loader = document.getElementById('loader');
        const form = document.getElementById('password-form');
        const username = "{{ user.username }}";

        // Password strength elements
        const strengthDiv = document.getElementById('password-strength');
        const strengthValue = document.getElementById('strength-value');
        const bars = [
            document.getElementById('bar1'),
            document.getElementById('bar2'),
            document.getElementById('bar3'),
            document.getElementById('bar4'),
            document.getElementById('bar5')
        ];

        // Requirement elements
        const reqLength = document.getElementById('req-length');
        const reqUppercase = document.getElementById('req-uppercase');
        const reqLowercase = document.getElementById('req-lowercase');
        const reqNumber = document.getElementById('req-number');
        const reqSpecial = document.getElementById('req-special');
        const reqNoUsername = document.getElementById('req-no-username');

        // Password match elements
        const matchDiv = document.getElementById('password-match');

        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(toggle => {
            toggle.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const target = document.getElementById(targetId);
                const type = target.getAttribute('type') === 'password' ? 'text' : 'password';
                target.setAttribute('type', type);
                this.classList.toggle('bi-eye');
                this.classList.toggle('bi-eye-slash');
            });
        });

        // Input focus effects
        [oldPassword, newPassword1, newPassword2].forEach(input => {
            if (!input) return;
            
            const group = input.closest('.form-group');
            
            input.addEventListener('focus', function() {
                group.classList.add('focused');
            });
            
            input.addEventListener('blur', function() {
                group.classList.remove('focused');
            });
        });

        // Password strength checker
        function checkPasswordStrength(password) {
            let score = 0;
            const checks = {
                length: password.length >= 8,
                uppercase: /[A-Z]/.test(password),
                lowercase: /[a-z]/.test(password),
                number: /[0-9]/.test(password),
                special: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password),
                noUsername: password.length > 0 && !password.toLowerCase().includes(username.toLowerCase())
            };

            // Update requirement icons
            updateRequirement(reqLength, checks.length);
            updateRequirement(reqUppercase, checks.uppercase);
            updateRequirement(reqLowercase, checks.lowercase);
            updateRequirement(reqNumber, checks.number);
            updateRequirement(reqSpecial, checks.special);
            updateRequirement(reqNoUsername, checks.noUsername);

            // Calculate score
            if (checks.length) score++;
            if (checks.uppercase) score++;
            if (checks.lowercase) score++;
            if (checks.number) score++;
            if (checks.special) score++;
            if (checks.noUsername) score++;

            return { score, checks };
        }

        function updateRequirement(element, isValid) {
            const icon = element.querySelector('i');
            if (isValid) {
                element.classList.add('valid');
                element.classList.remove('invalid');
                icon.className = 'bi bi-check-circle-fill';
            } else {
                element.classList.add('invalid');
                element.classList.remove('valid');
                icon.className = 'bi bi-x-circle-fill';
            }
        }

        // Update strength meter
        function updateStrengthMeter(password) {
            if (password.length === 0) {
                strengthDiv.style.display = 'none';
                return;
            }

            strengthDiv.style.display = 'block';
            const { score, checks } = checkPasswordStrength(password);
            
            // Update bars
            bars.forEach((bar, index) => {
                bar.classList.remove('weak', 'medium', 'strong', 'active');
                if (index < score) {
                    bar.classList.add('active');
                    if (score <= 2) {
                        bar.classList.add('weak');
                    } else if (score <= 4) {
                        bar.classList.add('medium');
                    } else {
                        bar.classList.add('strong');
                    }
                }
            });

            // Update text
            if (score <= 2) {
                strengthValue.textContent = 'Faible';
                strengthValue.className = 'strength-value weak';
            } else if (score <= 4) {
                strengthValue.textContent = 'Moyen';
                strengthValue.className = 'strength-value medium';
            } else {
                strengthValue.textContent = 'Fort';
                strengthValue.className = 'strength-value strong';
            }
        }

        // Check password match
        function checkPasswordMatch() {
            const password1 = newPassword1.value;
            const password2 = newPassword2.value;

            if (password2.length === 0) {
                matchDiv.style.display = 'none';
                return;
            }

            if (password1 === password2) {
                matchDiv.style.display = 'flex';
                matchDiv.className = 'password-match match';
                matchDiv.innerHTML = '<i class="bi bi-check-circle-fill"></i><span>Les mots de passe correspondent</span>';
            } else {
                matchDiv.style.display = 'flex';
                matchDiv.className = 'password-match no-match';
                matchDiv.innerHTML = '<i class="bi bi-exclamation-triangle-fill"></i><span>Les mots de passe ne correspondent pas</span>';
            }
        }

        // Validate form before submit
        function validateForm() {
            const password1 = newPassword1.value;
            const password2 = newPassword2.value;
            const { score } = checkPasswordStrength(password1);

            if (password1.length === 0 || password2.length === 0) {
                showNotification('Veuillez remplir tous les champs', 'warning');
                return false;
            }

            if (password1 !== password2) {
                showNotification('Les mots de passe ne correspondent pas', 'error');
                return false;
            }

            if (score < 3) {
                showNotification('Veuillez choisir un mot de passe plus fort', 'warning');
                return false;
            }

            return true;
        }

        // Show notification
        function showNotification(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `custom-alert alert-${type} animate__animated animate__fadeInDown`;
            alertDiv.innerHTML = `
                <i class="bi bi-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-triangle' : 'info-circle'}-fill"></i>
                <span>${message}</span>
            `;
            
            const passwordBody = document.querySelector('.password-body');
            passwordBody.insertBefore(alertDiv, passwordBody.firstChild);
            
            setTimeout(() => {
                alertDiv.classList.add('animate__fadeOutUp');
                setTimeout(() => alertDiv.remove(), 500);
            }, 3000);
        }

        // Event listeners
        if (newPassword1) {
            newPassword1.addEventListener('input', function() {
                updateStrengthMeter(this.value);
                checkPasswordMatch();
            });
        }

        if (newPassword2) {
            newPassword2.addEventListener('input', checkPasswordMatch);
        }

        // Form submission
        if (form) {
            form.addEventListener('submit', function(e) {
                if (!validateForm()) {
                    e.preventDefault();
                    return;
                }

                const btnText = submitBtn.querySelector('.btn-content span:not(.loader):not(i)');
                btnText.style.opacity = '0.7';
                loader.style.display = 'inline-block';
                submitBtn.disabled = true;
            });
        }

        // Prevent form resubmission on page refresh
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }

        // Add confirmation for cancel
        const cancelBtn = document.querySelector('.btn-cancel');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function(e) {
                if (newPassword1.value || newPassword2.value || oldPassword.value) {
                    if (!confirm('Vous avez des modifications non enregistrées. Êtes-vous sûr de vouloir quitter ?')) {
                        e.preventDefault();
                    }
                }
            });
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+Enter to submit
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                form.dispatchEvent(new Event('submit'));
            }
            
            // Escape to cancel
            if (e.key === 'Escape') {
                if (confirm('Annuler les modifications ?')) {
                    window.location.href = cancelBtn.href;
                }
            }
        });

        // Initial check for password requirements
        if (newPassword1) {
            checkPasswordStrength(newPassword1.value);
        }
    });
</script>
{% endblock %}