"use strict";

// Polls /Kiosk/PollSession every 3 seconds and navigates when staff triggers an intake.
// SignalR was replaced with polling because Azure App Service's ingress proxy cancels
// anonymous WebSocket and SSE handshakes before the SignalR protocol exchange completes.
(function () {
    const el = document.getElementById("kiosk-welcome-root");
    if (!el) return;

    const dot   = document.getElementById("kiosk-conn-dot");
    const label = document.getElementById("kiosk-conn-label");

    function setStatus(color, text) {
        if (dot)   dot.style.background = color;
        if (label) label.textContent = text;
    }

    setStatus("#94a3b8", "Connecting…");

    let active = true;

    async function poll() {
        if (!active) return;
        try {
            const res  = await fetch("/Kiosk/PollSession", { cache: "no-store" });
            if (!res.ok) throw new Error("HTTP " + res.status);
            const data = await res.json();
            setStatus("#16a34a", "Ready");
            if (data.smsConsentPending && data.customerId) {
                active = false;
                setStatus("#2563eb", "Loading consent…");
                window.location.href = `/Kiosk/SmsConsent/${data.customerId}`;
                return;
            }
            if (data.hasSession && data.sessionToken) {
                active = false;
                setStatus("#2563eb", "Starting…");
                window.location.href = `/Kiosk/Intake/${data.sessionToken}/Contact`;
                return;
            }
        } catch {
            setStatus("#f59e0b", "Connection issue — retrying…");
        }
        if (active) setTimeout(poll, 3000);
    }

    setTimeout(poll, 500);  // first poll quickly; subsequent every 3s
})();
