<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <title>Verify Your Thyme Crunch Account</title>

    <link rel="stylesheet" th:href="@{/css/login.css}">

    <link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head>
<body>

<div class="header-wrap">
    <a th:href="@{/explore}">
        <header class="top-header">
            <img th:src="@{/images/header_left.png}" class="swirl">
            <h1 class="site-name">Thyme Crunch</h1>
            <img th:src="@{/images/header_right.png}" class="swirl">
        </header>
    </a>
</div>

<div class="align-decor">
    <img th:src="@{/images/decor_left.png}" class="vert_swirl">

    <main class="main-content">
        <div class="login-box">
            <h2>Verify Your Account</h2>
            <p>Enter the 6-digit code sent to your email.</p>

            <div class="rows">
                <label for="otpInput">Verification Code</label>
                <input type="text" id="otpInput" maxlength="6" placeholder="000000" required>
            </div>

            <p id="message"></p>

            <button onclick="verifyOtp()">Verify</button>
            
            <p class="resend-text">
				 Didn’t get the code? Check your spam folder or wait a minute and try again.
            <button id="resendBtn" onclick="resendOtp()" disabled>
                Resend code (60s)
            </button>
        </div>
    </main>

    <img th:src="@{/images/decor_right.png}" class="vert_swirl">
</div>

<script>
const COOLDOWN_SECONDS = 60;
let countdownInterval = null;

function startCooldown() {
    const btn = document.getElementById("resendBtn");
    let remaining = COOLDOWN_SECONDS;

    btn.disabled = true;
    btn.textContent = `Resend code (${remaining}s)`;

    countdownInterval = setInterval(() => {
        remaining--;
        btn.textContent = `Resend code (${remaining}s)`;

        if (remaining <= 0) {
            clearInterval(countdownInterval);
            btn.disabled = false;
            btn.textContent = "Resend code";
        }
    }, 1000);
}

async function resendOtp() {
    const email = sessionStorage.getItem("pendingEmail");
    const message = document.getElementById("message");

    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    startCooldown();

    try {
        const response = await fetch(`/api/email/send?email=${encodeURIComponent(email)}`, {
            method: "POST",
            headers: { [csrfHeader]: csrfToken }
        });

        if (response.ok) {
            message.style.color = "green";
            message.textContent = "A new code has been sent.";
        } else {
            message.style.color = "red";
            message.textContent = "Couldn't resend code.";
        }
    } catch (err) {
        message.style.color = "red";
        message.textContent = "Network error.";
    }
}

window.addEventListener("DOMContentLoaded", startCooldown);

async function verifyOtp() {
    const otp = document.getElementById("otpInput").value;
    const email = sessionStorage.getItem("pendingEmail");
    const pendingUser = JSON.parse(sessionStorage.getItem("pendingUser"));
    const message = document.getElementById("message");

    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    const response = await fetch(`/api/email/verify?email=${encodeURIComponent(email)}&otp=${encodeURIComponent(otp)}`, {
        method: "POST",
        headers: { [csrfHeader]: csrfToken }
    });

    if (response.ok) {

        await fetch("/api/users", {
            method: "POST",
            headers: {
                [csrfHeader]: csrfToken,
                "Content-Type": "application/json"
            },
            body: JSON.stringify(pendingUser)
        });

        sessionStorage.removeItem("pendingEmail");
        sessionStorage.removeItem("pendingUser");

        message.style.color = "green";
        message.textContent = "Account verified! Redirecting...";
        setTimeout(() => window.location.href = "/login", 1500);
    } else {
        message.style.color = "red";
        message.textContent = "Invalid or expired code.";
    }
}
</script>

</body>
</html>