{% 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/style.css' %}?v=2fa1">
    <style>
        :root {
            --sp-primary: #4F46E5;
            --sp-secondary: #6366F1;
            --sp-text-main: #1e293b;
            --sp-text-muted: #64748b;
        }
        body.auth-body {
            margin: 0; padding: 0; min-height: 100vh;
            font-family: 'Inter', sans-serif;
            background-color: #020617;
            background-image:
                radial-gradient(circle at 15% 50%, rgba(79, 70, 229, 0.15), transparent 25%),
                radial-gradient(circle at 85% 30%, rgba(147, 51, 234, 0.15), transparent 25%);
            color: #f8fafc;
            display: flex; align-items: center;
        }
        h1,h2,h3 { font-family: 'Outfit', sans-serif; }

        .auth-card {
            border-radius: 24px;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.1);
            animation: fadeUp 0.6s ease-out forwards;
            opacity: 0; transform: translateY(20px);
        }
        @keyframes fadeUp { to { opacity:1; transform:translateY(0); } }

        .auth-form-side {
            background-color: #ffffff;
            color: var(--sp-text-main);
            padding: 3rem 3.5rem;
        }
        .auth-hero-side {
            background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
            color: #f8fafc;
            padding: 3rem 2.5rem;
            position: relative; overflow: hidden;
        }

        /* OTP inputs */
        .otp-group {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin: 1.5rem 0;
        }
        .otp-input {
            width: 52px; height: 60px;
            text-align: center;
            font-size: 1.6rem;
            font-weight: 700;
            font-family: 'Outfit', monospace;
            border: 2px solid #cbd5e1;
            border-radius: 12px;
            background: #f8fafc;
            color: #1e293b;
            transition: all 0.2s ease;
            outline: none;
        }
        .otp-input:focus {
            border-color: var(--sp-primary);
            box-shadow: 0 0 0 4px rgba(79,70,229,0.12);
            background: #fff;
        }
        .otp-input.filled {
            border-color: var(--sp-primary);
            background: #eef2ff;
        }

        /* Hidden combined input for form submission */
        #otp_code { display: none; }

        .auth-title { font-size: 1.7rem; font-weight: 700; letter-spacing: -0.02em; color: var(--sp-text-main); }
        .auth-subtitle { font-size: 0.95rem; color: var(--sp-text-muted); line-height: 1.5; }

        .btn-auth-primary {
            background: var(--sp-primary); border: 1px solid var(--sp-primary);
            border-radius: 12px; font-size: 1rem; font-weight: 600;
            padding: 0.8rem; color: #ffffff;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px -1px rgba(79,70,229,0.2);
        }
        .btn-auth-primary:hover {
            background: var(--sp-secondary); color: #fff;
            transform: translateY(-1px);
            box-shadow: 0 10px 15px -3px rgba(79,70,229,0.3);
        }
        .btn-resend {
            background: none; border: 1px solid #cbd5e1;
            border-radius: 10px; font-size: 0.9rem; font-weight: 500;
            padding: 0.55rem 1.2rem; color: #475569;
            transition: all 0.2s ease; cursor: pointer;
        }
        .btn-resend:hover:not(:disabled) { border-color: var(--sp-primary); color: var(--sp-primary); background: #eef2ff; }
        .btn-resend:disabled { opacity: 0.5; cursor: not-allowed; }

        .email-badge {
            display: inline-flex; align-items: center; gap: 0.4rem;
            background: #eef2ff; color: #4338ca;
            border: 1px solid #c7d2fe; border-radius: 999px;
            padding: 0.3rem 0.9rem; font-size: 0.85rem; font-weight: 600;
            font-family: 'Courier New', monospace;
        }

        .back-link { font-size: 0.85rem; color: #94a3b8; text-decoration: none; }
        .back-link:hover { color: var(--sp-primary); }

        /* Hero side */
        .shield-icon {
            width: 80px; height: 80px;
            background: rgba(99,102,241,0.2);
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            font-size: 2rem; color: #a5b4fc; margin: 0 auto 1.5rem;
            border: 2px solid rgba(99,102,241,0.3);
        }
        .security-pill {
            border: 1px solid rgba(255,255,255,0.15);
            border-radius: 10px; padding: 0.6rem 1rem;
            background: rgba(255,255,255,0.05);
            font-size: 0.85rem; color: #e2e8f0;
            backdrop-filter: blur(4px);
            display: flex; align-items: center; gap: 0.5rem;
        }

        @media (max-width: 767px) {
            .auth-hero-side { display: none !important; }
            .auth-form-side { padding: 2rem 1.5rem; }
        }

        /* Toast styles (reuse from login) */
        .swiftpos-toast-container {
            position: fixed; top: 1rem; right: 1rem; z-index: 9999;
            display: flex; flex-direction: column; gap: 0.5rem;
        }
    </style>
</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="{% url 'two_fa_resend' %}" 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>
