{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Verify Your Identity — SwiftPOS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'css/auth.css' %}?v=5">
</head>
<body class="auth-body">

<div class="swiftpos-toast-container">
    {% if messages %}
        {% for message in messages %}
            <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}"
                 style="background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,0.12);padding:1rem 1.25rem;display:flex;align-items:center;gap:0.75rem;min-width:280px;border-left:4px solid {% if message.tags == 'success' %}#10b981{% elif message.tags == 'error' or message.tags == 'danger' %}#ef4444{% elif message.tags == 'warning' %}#f59e0b{% else %}#3b82f6{% endif %};">
                <i class="fas {% if message.tags == 'success' %}fa-check-circle{% elif message.tags == 'error' or message.tags == 'danger' %}fa-exclamation-circle{% elif message.tags == 'warning' %}fa-exclamation-triangle{% else %}fa-info-circle{% endif %}"
                   style="color:{% if message.tags == 'success' %}#10b981{% elif message.tags == 'error' or message.tags == 'danger' %}#ef4444{% elif message.tags == 'warning' %}#f59e0b{% else %}#3b82f6{% endif %};font-size:1.1rem;flex-shrink:0;"></i>
                <span style="font-size:0.9rem;color:#1e293b;">{{ message }}</span>
            </div>
        {% endfor %}
    {% endif %}
</div>

<div class="container-fluid min-vh-100 d-flex align-items-center justify-content-center py-4">
    <div class="w-100" style="max-width:900px;animation:fadeUp 0.6s ease-out forwards;opacity:0;transform:translateY(20px);">
        <div class="row justify-content-center">
            <div class="col-lg-10 col-xl-9">
                <div class="auth-card row g-0">

                    <!-- Form side -->
                    <div class="col-md-6 auth-form-side">
                        <!-- Brand -->
                        <div class="d-flex align-items-center gap-3 mb-4">
                            <img src="{% static 'core/icons/icon-192.png' %}" alt="SwiftPOS"
                                 style="height:40px;border-radius:10px;" onerror="this.src='https://cdn-icons-png.flaticon.com/512/3225/3225066.png'">
                            <div>
                                <div style="font-family:'Outfit',sans-serif;font-weight:700;font-size:1.1rem;color:#1e293b;">SwiftPOS</div>
                                <div style="font-size:0.75rem;color:#94a3b8;">Security Verification</div>
                            </div>
                        </div>

                        <h1 class="auth-title mb-2">Check your email</h1>
                        <p class="auth-subtitle mb-3">
                            We sent a 6-digit code to
                        </p>
                        <div class="mb-4">
                            <span class="email-badge">
                                <i class="fas fa-envelope" style="font-size:0.75rem;"></i>
                                {{ masked_email }}
                            </span>
                        </div>

                        <form method="post" id="otpForm">
                            {% csrf_token %}

                            <!-- 6 separate boxes -->
                            <div class="otp-group" id="otpGroup">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="one-time-code" id="d0" tabindex="1">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" id="d1" tabindex="2">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" id="d2" tabindex="3">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" id="d3" tabindex="4">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" id="d4" tabindex="5">
                                <input class="otp-input" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" id="d5" tabindex="6">
                            </div>

                            <!-- Hidden combined field for server -->
                            <input type="hidden" name="otp_code" id="otp_code">

                            <!-- Countdown -->
                            <div class="text-center mb-3">
                                <span id="expiryNote" style="font-size:0.8rem;color:#94a3b8;">
                                    <i class="fas fa-clock me-1"></i>
                                    Code expires in <span id="countdown" style="font-weight:600;color:#475569;">10:00</span>
                                </span>
                            </div>

                            <div class="d-grid mb-3">
                                <button type="submit" class="btn btn-auth-primary" id="verifyBtn">
                                    <i class="fas fa-shield-check me-1"></i>
                                    Verify and Sign In
                                </button>
                            </div>
                        </form>

                        <!-- Resend -->
                        <div class="d-flex align-items-center justify-content-between mt-2">
                            <form method="post" action="{% if request.company %}/{{ request.company.slug }}/accounts/2fa/resend/{% else %}{% url 'two_fa_resend' %}{% endif %}" style="margin:0;">
                                {% csrf_token %}
                                <button type="submit" class="btn-resend" id="resendBtn"
                                    {% if resend_cooldown > 0 %}disabled{% endif %}>
                                    <i class="fas fa-rotate-right me-1"></i>
                                    {% if resend_cooldown > 0 %}
                                        Resend in <span id="resendTimer">{{ resend_cooldown }}</span>s
                                    {% else %}
                                        Resend code
                                    {% endif %}
                                </button>
                            </form>
                            <a href="{% url 'login' %}" class="back-link">
                                <i class="fas fa-arrow-left me-1"></i> Back to login
                            </a>
                        </div>
                    </div>

                    <!-- Hero side -->
                    <div class="col-md-6 auth-hero-side d-none d-md-flex flex-column justify-content-center align-items-center text-center">
                        <div class="shield-icon mb-3">
                            <i class="fas fa-shield-halved"></i>
                        </div>
                        <h2 class="text-white mb-2" style="font-size:1.4rem;">Two-Factor Authentication</h2>
                        <p style="font-size:0.9rem;color:#94a3b8;max-width:260px;line-height:1.6;">
                            Your account at <strong style="color:#a5b4fc;">{{ company_name }}</strong> is protected with an additional layer of security.
                        </p>

                        <div class="mt-4 d-flex flex-column gap-3 w-100" style="max-width:280px;">
                            <div class="security-pill">
                                <i class="fas fa-lock" style="color:#a5b4fc;"></i>
                                Email-based OTP
                            </div>
                            <div class="security-pill">
                                <i class="fas fa-clock" style="color:#a5b4fc;"></i>
                                Expires in 10 minutes
                            </div>
                            <div class="security-pill">
                                <i class="fas fa-ban" style="color:#a5b4fc;"></i>
                                5 attempts maximum
                            </div>
                        </div>
                    </div>

                </div>
                <div class="text-center mt-3" style="font-size:0.8rem;color:#475569;">
                    &copy; {% now "Y" %} SwiftPOS. All rights reserved.
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ── OTP box navigation ──────────────────────────────────────────────
const boxes = Array.from(document.querySelectorAll('.otp-input'));
const combined = document.getElementById('otp_code');

boxes[0].focus();

boxes.forEach((box, i) => {
    box.addEventListener('input', () => {
        const val = box.value.replace(/\D/g, '');
        box.value = val;
        box.classList.toggle('filled', val !== '');
        if (val && i < boxes.length - 1) boxes[i+1].focus();
        updateCombined();
    });

    box.addEventListener('keydown', e => {
        if (e.key === 'Backspace' && !box.value && i > 0) {
            boxes[i-1].focus();
            boxes[i-1].value = '';
            boxes[i-1].classList.remove('filled');
            updateCombined();
        }
    });

    box.addEventListener('paste', e => {
        e.preventDefault();
        const pasted = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
        pasted.split('').forEach((ch, idx) => {
            if (boxes[idx]) { boxes[idx].value = ch; boxes[idx].classList.add('filled'); }
        });
        const nextEmpty = boxes.findIndex(b => !b.value);
        if (nextEmpty !== -1) boxes[nextEmpty].focus(); else boxes[boxes.length-1].focus();
        updateCombined();
    });
});

function updateCombined() {
    combined.value = boxes.map(b => b.value).join('');
}

document.getElementById('otpForm').addEventListener('submit', function(e) {
    updateCombined();
    if (combined.value.length < 6) {
        e.preventDefault();
        boxes[0].focus();
        const firstEmpty = boxes.findIndex(b => !b.value);
        if (firstEmpty !== -1) boxes[firstEmpty].focus();
    }
});

// ── Expiry countdown (10 min) ─────────────────────────────────────
let remaining = 600; // 10 minutes in seconds
const countdownEl = document.getElementById('countdown');
const expiryNote = document.getElementById('expiryNote');

const tick = setInterval(() => {
    remaining--;
    if (remaining <= 0) {
        clearInterval(tick);
        countdownEl.textContent = '0:00';
        expiryNote.innerHTML = '<i class="fas fa-exclamation-circle text-danger me-1"></i><span class="text-danger fw-semibold">Code expired — please go back and log in again.</span>';
        document.getElementById('verifyBtn').disabled = true;
        return;
    }
    const m = Math.floor(remaining / 60);
    const s = remaining % 60;
    countdownEl.textContent = `${m}:${s.toString().padStart(2,'0')}`;
}, 1000);

// ── Resend cooldown ───────────────────────────────────────────────
const resendBtn = document.getElementById('resendBtn');
const resendTimerEl = document.getElementById('resendTimer');
let resendRemaining = {{ resend_cooldown }};

if (resendRemaining > 0 && resendTimerEl) {
    const resendTick = setInterval(() => {
        resendRemaining--;
        if (resendRemaining <= 0) {
            clearInterval(resendTick);
            resendBtn.disabled = false;
            resendBtn.innerHTML = '<i class="fas fa-rotate-right me-1"></i>Resend code';
        } else if (resendTimerEl) {
            resendTimerEl.textContent = resendRemaining;
        }
    }, 1000);
}

// Auto-dismiss toasts
setTimeout(() => {
    document.querySelectorAll('.swiftpos-toast').forEach(t => {
        t.style.transition = 'opacity 0.4s';
        t.style.opacity = '0';
        setTimeout(() => t.remove(), 400);
    });
}, 4000);
</script>
</body>
</html>
