{% extends "ewoooc_base.html" %}

{% block title %}修改密碼 - EwoooC{% endblock %}

{% block extra_css %}
<style>
.change-password-page {
    color: var(--momo-text-primary);
}

.change-password-card {
    overflow: hidden;
    background: var(--momo-bg-surface);
    border: 1px solid var(--momo-border-light);
    border-radius: var(--momo-radius-md);
    box-shadow: none;
}

.change-password-card__head {
    background: var(--momo-bg-paper);
    border-bottom: 1px solid var(--momo-border-light);
    color: var(--momo-text-primary);
}

.change-password-card__head h5 {
    color: var(--momo-text-primary);
    font-family: var(--momo-font-display);
    font-size: var(--momo-text-title);
    font-weight: 800;
    letter-spacing: 0;
}

.password-rule-note {
    padding: 12px 14px;
    background: var(--momo-info-bg);
    border: 1px solid var(--momo-info-border);
    border-radius: var(--momo-radius-md);
    color: var(--momo-info-text);
}

.password-rule-note h6 {
    color: var(--momo-info-text);
    font-family: var(--momo-font-display);
    font-weight: 800;
}

.change-password-alert {
    position: relative;
    padding: 12px 42px 12px 14px;
    margin-bottom: var(--momo-space-4);
    border: 1px solid var(--momo-border-light);
    border-radius: var(--momo-radius-md);
    background: var(--momo-bg-paper);
    color: var(--momo-text-primary);
    font-weight: 700;
}

.change-password-alert--success {
    background: var(--momo-success-bg);
    border-color: var(--momo-success-border);
    color: var(--momo-success-text);
}

.change-password-alert--danger {
    background: var(--momo-danger-bg);
    border-color: var(--momo-danger-border);
    color: var(--momo-danger-text);
}

.change-password-alert--warning {
    background: var(--momo-warning-bg);
    border-color: var(--momo-warning-border);
    color: var(--momo-warning-text);
}

.change-password-strength-bar {
    border-radius: var(--momo-radius-pill);
}

.change-password-strength-bar--danger {
    background: var(--momo-danger);
}

.change-password-strength-bar--warning {
    background: var(--momo-warning);
}

.change-password-strength-bar--success {
    background: var(--momo-success);
}

.change-password-feedback {
    font-weight: 800;
}

.change-password-feedback.is-danger {
    color: var(--momo-danger-text);
}

.change-password-feedback.is-warning {
    color: var(--momo-warning-text);
}

.change-password-feedback.is-success {
    color: var(--momo-success-text);
}

@media (max-width: 760px) {
    .change-password-page .container {
        padding-left: var(--momo-space-3);
        padding-right: var(--momo-space-3);
    }
}
</style>
{% endblock %}

{% block content %}
<div class="change-password-page">
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card change-password-card">
                <div class="card-header change-password-card__head">
                    <h5 class="mb-0">
                        <i class="fas fa-key me-2"></i>修改密碼
                    </h5>
                </div>
                <div class="card-body">
                    <div id="alertContainer"></div>

                    <form id="changePasswordForm">
                        <div class="mb-3">
                            <label for="oldPassword" class="form-label">舊密碼 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="oldPassword" required>
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('oldPassword')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="newPassword" class="form-label">新密碼 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="newPassword" required oninput="checkPasswordStrength()">
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('newPassword')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div id="passwordStrength" class="mt-2"></div>
                        </div>

                        <div class="mb-4">
                            <label for="confirmPassword" class="form-label">確認新密碼 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="confirmPassword" required oninput="checkPasswordMatch()">
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirmPassword')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div id="passwordMatch" class="mt-2"></div>
                        </div>

                        <!-- 密碼要求提示 -->
                        <div class="password-rule-note">
                            <h6 class="alert-heading"><i class="fas fa-info-circle me-2"></i>帳號保護要求</h6>
                            <ul class="mb-0 ps-3">
                                {% for req in password_requirements %}
                                <li>{{ req }}</li>
                                {% endfor %}
                            </ul>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-save me-2"></i>變更密碼
                            </button>
                            <a href="{{ url_for('dashboard.index') }}" class="btn btn-secondary">
                                <i class="fas fa-times me-2"></i>取消
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.getElementById('changePasswordForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        // 前端驗證
        if (newPassword !== confirmPassword) {
            showAlert('新密碼與確認密碼不符', 'danger');
            return;
        }

        if (newPassword === oldPassword) {
            showAlert('新密碼不能與舊密碼相同', 'danger');
            return;
        }

        const submitBtn = document.getElementById('submitBtn');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>處理中...';

        try {
            const response = await fetch('/api/change_password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    old_password: oldPassword,
                    new_password: newPassword
                })
            });

            const data = await response.json();

            if (data.success) {
                showAlert('密碼變更成功！即將跳轉至登入頁面...', 'success');
                setTimeout(() => {
                    window.location.href = '/logout';
                }, 2000);
            } else {
                showAlert(data.message, 'danger');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-save me-2"></i>變更密碼';
            }
        } catch (error) {
            console.error('密碼變更失敗:', error);
            showAlert('密碼變更失敗，請稍後再試', 'danger');
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-save me-2"></i>變更密碼';
        }
    });

    function togglePassword(inputId) {
        const input = document.getElementById(inputId);
        const icon = input.parentElement.querySelector('.fa-eye, .fa-eye-slash');

        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    }

    function checkPasswordStrength() {
        const password = document.getElementById('newPassword').value;
        const strengthDiv = document.getElementById('passwordStrength');

        if (!password) {
            strengthDiv.innerHTML = '';
            return;
        }

        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 (/[!@#$%^&*]/.test(password)) score++;

        let strengthText, strengthTone;
        if (score < 3) {
            strengthText = '弱';
            strengthTone = 'danger';
        } else if (score < 5) {
            strengthText = '中等';
            strengthTone = 'warning';
        } else {
            strengthText = '強';
            strengthTone = 'success';
        }

        strengthDiv.innerHTML = `
            <div class="progress" style="height: 5px;">
                <div class="progress-bar change-password-strength-bar change-password-strength-bar--${strengthTone}"
                     style="width: ${(score / 6) * 100}%"></div>
            </div>
            <small class="change-password-feedback is-${strengthTone}">密碼強度：${strengthText}</small>
        `;
    }

    function checkPasswordMatch() {
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const matchDiv = document.getElementById('passwordMatch');

        if (!confirmPassword) {
            matchDiv.innerHTML = '';
            return;
        }

        if (newPassword === confirmPassword) {
            matchDiv.innerHTML = '<small class="change-password-feedback is-success"><i class="fas fa-check me-1"></i>密碼相符</small>';
        } else {
            matchDiv.innerHTML = '<small class="change-password-feedback is-danger"><i class="fas fa-times me-1"></i>密碼不相符</small>';
        }
    }

    function showAlert(message, type) {
        const container = document.getElementById('alertContainer');
        container.innerHTML = `
            <div class="change-password-alert change-password-alert--${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
    }
</script>
{% endblock %}
