{% include 'header.twig' %}

{% if user['auth'] %}
{% else %}
<style>
    @media (max-width: 991.98px) {
        .main-top {padding: 70px 0 40px 0!important}
    }
    .lgn-btn {display: none!important}
    @media (min-width: 1199.98px) {
        .main-top { padding: 400px 0 40px 0}
        .app-content { margin-top: -300px }
    }
</style>
<div class="main-top">
    <div class="main-top-bg"></div>
</div>
{% endif %}

<style>
/* ═══ OTP Verification Styles ═══ */
.otp-container {
    max-width: 480px;
    margin: 0 auto;
    padding: 40px 30px;
    text-align: center;
}
.otp-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 24px;
    box-shadow: 0 8px 25px rgba(67, 97, 238, 0.3);
    animation: otpPulse 2s infinite;
}
@keyframes otpPulse {
    0%, 100% { box-shadow: 0 8px 25px rgba(67, 97, 238, 0.3); }
    50% { box-shadow: 0 8px 35px rgba(67, 97, 238, 0.5); }
}
.otp-icon i {
    font-size: 36px;
    color: #fff;
}
.otp-title {
    font-size: 24px;
    font-weight: 700;
    color: #1a1a2e;
    margin-bottom: 8px;
}
.otp-subtitle {
    font-size: 14px;
    color: #666;
    margin-bottom: 30px;
    line-height: 1.5;
}
.otp-email {
    font-weight: 600;
    color: #4361ee;
}

/* ── OTP Input Boxes ── */
.otp-inputs {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-bottom: 24px;
}
.otp-inputs input {
    width: 50px;
    height: 56px;
    text-align: center;
    font-size: 24px;
    font-weight: 700;
    border: 2px solid #e0e0e0;
    border-radius: 12px;
    outline: none;
    transition: all 0.3s ease;
    background: #fafbff;
    color: #1a1a2e;
    caret-color: #4361ee;
}
.otp-inputs input:focus {
    border-color: #4361ee;
    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
    background: #fff;
    transform: scale(1.05);
}
.otp-inputs input.filled {
    border-color: #4361ee;
    background: #f0f4ff;
}
.otp-inputs input.error-shake {
    animation: shake 0.5s ease-in-out;
    border-color: #e74c3c !important;
}
@keyframes shake {
    0%, 100% { transform: translateX(0); }
    20% { transform: translateX(-8px); }
    40% { transform: translateX(8px); }
    60% { transform: translateX(-6px); }
    80% { transform: translateX(6px); }
}

/* ── Timer ── */
.otp-timer {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-bottom: 20px;
    font-size: 14px;
    color: #666;
}
.otp-timer i { color: #4361ee; }
.otp-timer .timer-value {
    font-weight: 600;
    color: #4361ee;
    font-family: monospace;
    font-size: 16px;
}
.otp-timer.expired .timer-value { color: #e74c3c; }
.otp-timer.expired i { color: #e74c3c; }

/* ── Buttons ── */
.otp-submit-btn {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%);
    color: #fff;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 16px;
    letter-spacing: 0.5px;
}
.otp-submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(67, 97, 238, 0.35);
}
.otp-submit-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* ── Resend ── */
.otp-resend {
    font-size: 14px;
    color: #888;
    margin-top: 8px;
}
.otp-resend-btn {
    background: none;
    border: none;
    color: #4361ee;
    font-weight: 600;
    cursor: pointer;
    font-size: 14px;
    text-decoration: underline;
    padding: 0;
    transition: color 0.2s;
}
.otp-resend-btn:hover { color: #3a0ca3; }
.otp-resend-btn:disabled {
    color: #aaa;
    cursor: not-allowed;
    text-decoration: none;
}
.resend-cooldown {
    color: #888;
    font-family: monospace;
    font-weight: 600;
}

/* ── Alerts ── */
.otp-alert {
    padding: 12px 16px;
    border-radius: 10px;
    margin-bottom: 20px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideDown 0.3s ease;
}
@keyframes slideDown {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}
.otp-alert.alert-error {
    background: #fef2f2;
    color: #dc2626;
    border: 1px solid #fecaca;
}
.otp-alert.alert-success {
    background: #f0fdf4;
    color: #16a34a;
    border: 1px solid #bbf7d0;
}
.otp-alert.alert-info {
    background: #eff6ff;
    color: #2563eb;
    border: 1px solid #bfdbfe;
}
.otp-attempts {
    font-size: 13px;
    color: #888;
    margin-bottom: 20px;
}
.otp-attempts .attempts-count {
    font-weight: 600;
    color: #e74c3c;
}

/* ── Success Animation ── */
.otp-success-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 9999;
    justify-content: center;
    align-items: center;
}
.otp-success-overlay.show { display: flex; }
.otp-success-box {
    background: #fff;
    border-radius: 20px;
    padding: 40px;
    text-align: center;
    animation: popIn 0.4s ease;
    max-width: 350px;
}
@keyframes popIn {
    from { transform: scale(0.8); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
}
.otp-success-check {
    width: 70px; height: 70px;
    background: #16a34a;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
}
.otp-success-check i { font-size: 32px; color: #fff; }

/* ── Dark Mode ── */
@media (prefers-color-scheme: dark) {
    .otp-title { color: #e0e0e0; }
    .otp-subtitle { color: #aaa; }
    .otp-inputs input {
        background: #2a2a3e;
        border-color: #3a3a50;
        color: #e0e0e0;
    }
    .otp-inputs input:focus {
        background: #2a2a3e;
        border-color: #4361ee;
    }
    .otp-inputs input.filled { background: #2a2a4e; }
}

/* ── Mobile ── */
@media (max-width: 480px) {
    .otp-container { padding: 30px 15px; }
    .otp-inputs input {
        width: 42px;
        height: 48px;
        font-size: 20px;
    }
    .otp-inputs { gap: 6px; }
    .otp-title { font-size: 20px; }
}
</style>

<div class="app-content">
    {% if user['auth'] %}
        <div class="container-fluid">
    {% else %}
        <div class="container">
    {% endif %}
        <section class="app-childs">
            <div class="row justify-content-center">
                <div class="col-lg-6 col-md-8 col-12">
                    <div class="d-card h-100">
                        <div class="d-card-body">
                            <div class="otp-container">
                                <!-- Icon -->
                                <div class="otp-icon">
                                    <i class="fas fa-shield-alt"></i>
                                </div>
                                
                                <h2 class="otp-title">Email Verification</h2>
                                <p class="otp-subtitle">
                                    We've sent a 6-digit verification code to<br>
                                    <span class="otp-email">{{ maskedEmail }}</span>
                                </p>

                                <!-- Alerts -->
                                {% if errorText %}
                                <div class="otp-alert alert-error">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ errorText }}</span>
                                </div>
                                {% endif %}
                                {% if successText %}
                                <div class="otp-alert alert-success">
                                    <i class="fas fa-check-circle"></i>
                                    <span>{{ successText }}</span>
                                </div>
                                {% endif %}
                                <div id="otp-ajax-msg" class="otp-alert alert-info" style="display:none;">
                                    <i class="fas fa-info-circle"></i>
                                    <span id="otp-ajax-msg-text"></span>
                                </div>

                                <!-- Timer -->
                                <div class="otp-timer" id="otp-timer-container">
                                    <i class="fas fa-clock"></i>
                                    <span>Code expires in:</span>
                                    <span class="timer-value" id="otp-timer">--:--</span>
                                </div>

                                <!-- OTP Form -->
                                <form method="post" action="{{ site['url'] }}/verify_otp" id="otp-form">
                                    <input type="hidden" name="csrf_token" value="{{ csrfToken }}">
                                    
                                    <div class="otp-inputs" id="otp-inputs">
                                        <input type="text" name="otp_digit_1" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="one-time-code" autofocus>
                                        <input type="text" name="otp_digit_2" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                        <input type="text" name="otp_digit_3" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                        <input type="text" name="otp_digit_4" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                        <input type="text" name="otp_digit_5" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                        <input type="text" name="otp_digit_6" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                    </div>

                                    <div class="otp-attempts">
                                        Attempts remaining: <span class="attempts-count" id="attempts-remaining">{{ attemptsRemaining }}</span>
                                    </div>

                                    <button type="submit" class="otp-submit-btn" id="otp-submit-btn">
                                        <i class="fas fa-check-circle"></i> Verify Code
                                    </button>
                                </form>

                                <!-- Resend -->
                                <div class="otp-resend">
                                    Didn't receive the code? 
                                    <button type="button" class="otp-resend-btn" id="resend-btn" disabled>
                                        Resend Code
                                    </button>
                                    <span class="resend-cooldown" id="resend-cooldown"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<!-- Success Overlay -->
<div class="otp-success-overlay" id="success-overlay">
    <div class="otp-success-box">
        <div class="otp-success-check">
            <i class="fas fa-check"></i>
        </div>
        <h3 style="margin:0 0 8px;font-weight:700;">Verified!</h3>
        <p style="color:#666;margin:0;">Redirecting to dashboard...</p>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const inputs = document.querySelectorAll('.otp-inputs input');
    const form = document.getElementById('otp-form');
    const submitBtn = document.getElementById('otp-submit-btn');
    const resendBtn = document.getElementById('resend-btn');
    const resendCooldownEl = document.getElementById('resend-cooldown');
    const timerEl = document.getElementById('otp-timer');
    const timerContainer = document.getElementById('otp-timer-container');
    const ajaxMsg = document.getElementById('otp-ajax-msg');
    const ajaxMsgText = document.getElementById('otp-ajax-msg-text');

    // ── Auto-focus next input ──
    inputs.forEach((input, index) => {
        input.addEventListener('input', function(e) {
            const val = this.value.replace(/[^0-9]/g, '');
            this.value = val;
            
            if (val.length === 1) {
                this.classList.add('filled');
                if (index < inputs.length - 1) {
                    inputs[index + 1].focus();
                }
            }
        });

        input.addEventListener('keydown', function(e) {
            if (e.key === 'Backspace' && !this.value && index > 0) {
                inputs[index - 1].focus();
                inputs[index - 1].value = '';
                inputs[index - 1].classList.remove('filled');
            }
            if (e.key === 'ArrowLeft' && index > 0) {
                e.preventDefault();
                inputs[index - 1].focus();
            }
            if (e.key === 'ArrowRight' && index < inputs.length - 1) {
                e.preventDefault();
                inputs[index + 1].focus();
            }
        });

        input.addEventListener('focus', function() {
            this.select();
        });
    });

    // ── Paste handling ──
    inputs[0].addEventListener('paste', function(e) {
        e.preventDefault();
        const pasted = (e.clipboardData || window.clipboardData).getData('text').replace(/[^0-9]/g, '');
        if (pasted.length >= 6) {
            for (let i = 0; i < 6; i++) {
                inputs[i].value = pasted[i];
                inputs[i].classList.add('filled');
            }
            inputs[5].focus();
        }
    });

    // ── OTP Expiry Timer ──
    let expirySeconds = {{ otpRemainingSeconds }};
    
    function updateTimer() {
        if (expirySeconds <= 0) {
            timerEl.textContent = 'Expired';
            timerContainer.classList.add('expired');
            submitBtn.disabled = true;
            return;
        }
        const min = Math.floor(expirySeconds / 60);
        const sec = expirySeconds % 60;
        timerEl.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
        expirySeconds--;
        setTimeout(updateTimer, 1000);
    }
    updateTimer();

    // ── Resend Cooldown Timer ──
    let resendCooldown = {{ resendCooldownRemaining }};
    
    function updateResendCooldown() {
        if (resendCooldown <= 0) {
            resendBtn.disabled = false;
            resendCooldownEl.textContent = '';
            return;
        }
        resendBtn.disabled = true;
        resendCooldownEl.textContent = '(' + resendCooldown + 's)';
        resendCooldown--;
        setTimeout(updateResendCooldown, 1000);
    }
    updateResendCooldown();

    // ── Resend AJAX ──
    resendBtn.addEventListener('click', function() {
        resendBtn.disabled = true;
        resendBtn.textContent = 'Sending...';
        
        const formData = new FormData();
        formData.append('csrf_token', '{{ csrfToken }}');

        fetch('{{ site["url"] }}/verify_otp/resend', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(data => {
            resendBtn.textContent = 'Resend Code';
            
            if (data.success) {
                showAjaxMsg(data.message, 'success');
                // Reset timers
                if (data.expiry) {
                    expirySeconds = data.expiry;
                    timerContainer.classList.remove('expired');
                    submitBtn.disabled = false;
                    updateTimer();
                }
                if (data.cooldown) {
                    resendCooldown = data.cooldown;
                    updateResendCooldown();
                }
                // Clear inputs
                inputs.forEach(inp => {
                    inp.value = '';
                    inp.classList.remove('filled');
                });
                inputs[0].focus();
            } else {
                showAjaxMsg(data.message, 'error');
                if (data.cooldown) {
                    resendCooldown = data.cooldown;
                    updateResendCooldown();
                } else {
                    resendBtn.disabled = false;
                }
            }
        })
        .catch(() => {
            resendBtn.textContent = 'Resend Code';
            resendBtn.disabled = false;
            showAjaxMsg('Network error. Please try again.', 'error');
        });
    });

    function showAjaxMsg(msg, type) {
        ajaxMsg.className = 'otp-alert alert-' + (type === 'success' ? 'success' : type === 'error' ? 'error' : 'info');
        ajaxMsgText.textContent = msg;
        ajaxMsg.style.display = 'flex';
        setTimeout(() => { ajaxMsg.style.display = 'none'; }, 5000);
    }

    // ── Error shake on existing error ──
    {% if errorText %}
    inputs.forEach(input => {
        input.classList.add('error-shake');
        setTimeout(() => input.classList.remove('error-shake'), 600);
    });
    {% endif %}
});
</script>

{% include 'footer.twig' %}
