{% extends "base.html" %}
{% block title %}Order Confirmation -- {{ PLATFORM_NAME }}{% endblock %}
{% block content %}
<div style="min-height:60vh;display:flex;align-items:center;justify-content:center;padding:var(--space-8);">
    <div class="card" style="max-width:480px;width:100%;text-align:center;">
        <div class="loading mb-6"><div class="spinner" id="loadingSpinner"></div></div>
        <h2 id="statusTitle" style="margin-bottom:var(--space-3);">Confirming Your Order</h2>
        <p class="text-secondary" id="statusMessage">Verifying your payment. Please do not close this page...</p>
        <div id="successActions" class="hidden mt-6">
            <a href="{% url 'sales:detail' slug %}" class="btn btn--primary btn--block">Return to Sale Page</a>
        </div>
        <div id="failedActions" class="hidden mt-6">
            <a href="{% url 'sales:detail' slug %}" class="btn btn--secondary btn--block">Return to Sale Page</a>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const reference = '{{ reference }}';
const slug = '{{ slug }}';
if (reference) {
    let attempts = 0;
    const poll = setInterval(async () => {
        attempts++;
        try {
            const resp = await fetch('/payments/booking/status/' + reference + '/');
            const data = await resp.json();
            if (data.status === 'verified') {
                clearInterval(poll);
                document.getElementById('loadingSpinner').style.display = 'none';
                document.getElementById('statusTitle').textContent = 'Order Confirmed!';
                document.getElementById('statusMessage').textContent = 'Thank you for your purchase! A confirmation email has been sent.';
                document.getElementById('successActions').classList.remove('hidden');
                // Clear local cart
                localStorage.removeItem('cart_' + slug);
            } else if (data.status === 'failed' || attempts > 30) {
                clearInterval(poll);
                document.getElementById('loadingSpinner').style.display = 'none';
                document.getElementById('statusTitle').textContent = 'Order Verification Failed';
                document.getElementById('statusMessage').textContent = 'Payment could not be verified or timed out. If you were charged, please contact support.';
                document.getElementById('failedActions').classList.remove('hidden');
            }
        } catch (e) {
            if (attempts > 30) clearInterval(poll);
        }
    }, 3000);
}
</script>
{% endblock %}
