// my-sea-seats.js — one-shot "seated" animation for the my-sea table hex.
//
// When a seat is occupied (owner draws → seat 1C; visitor deposits a token →
// seat 2C), the FIRST time a given viewer sees that occupancy the seat plays
// a one-shot glow: chair fills --terUser + glows --ninUsers for ~1.5s, then
// settles back to --secUser at FULL opacity (the steady `.seated` look), with
// `.fa-ban` already swapped for `.fa-circle-check` server-side. "First time"
// is tracked per-browser in localStorage, keyed on a stable per-occupancy
// token (`data-seat-token`) so a fresh draw / fresh invite re-animates but a
// reload does not. (Spec: user 2026-05-27.)
(function () {
    'use strict';
    var STORE_PREFIX = 'mysea-seat-seen:';
    // 2s flare (user-spec 2026-05-29) — matches the `my-sea-seat-flare`
    // keyframe duration in _room.scss so the class is removed exactly as the
    // chair settles into its steady `.seated` --secUser look.
    var GLOW_MS = 2000;

    function alreadySeen(token) {
        try {
            return window.localStorage.getItem(STORE_PREFIX + token) === '1';
        } catch (e) {
            return false;  // private mode / storage disabled → always animate
        }
    }

    function markSeen(token) {
        try { window.localStorage.setItem(STORE_PREFIX + token, '1'); }
        catch (e) { /* no-op */ }
    }

    // Play the one-shot glow on a `.table-seat` element unless this viewer has
    // already seen this exact occupancy. Safe to call on a seat with no token
    // (always animates, never persists).
    function playSeatGlow(seat) {
        if (!seat) return;
        var token = seat.getAttribute('data-seat-token');
        if (token && alreadySeen(token)) return;
        seat.classList.add('seat-just-seated');
        window.setTimeout(function () {
            seat.classList.remove('seat-just-seated');
        }, GLOW_MS);
        if (token) markSeen(token);
    }

    // Exposed so the owner's FREE DRAW flow can fire the same glow the moment
    // seat 1C transitions to `.seated` client-side (my_sea.html).
    window.playSeatGlow = playSeatGlow;

    // Re-render the table-seat ring from a `sea_seats` broadcast payload when
    // presence changes (a deposit takes a seat / a BYE frees one), so EVERY
    // member — the owner on my_sea AND each spectator on my_sea_visit — sees
    // members come + go live, no refresh. Shared by both pages (DRY); each
    // passes its own `myToken` so the viewer's own chair gets the `--self`
    // marker (the owner's `owner-<id>-<draw>` token, a visitor's `visit-<inv>`).
    // Mirrors the server seat loop (`_my_sea_seats`) in markup.
    function renderSeats(seats, myToken) {
        var scene = document.querySelector('.room-table-scene');
        if (!scene || !seats) return;
        scene.querySelectorAll('.table-seat').forEach(function (s) { s.remove(); });
        seats.forEach(function (seat) {
            var isSelf = myToken && seat.token && seat.token === myToken;
            var div = document.createElement('div');
            div.className = 'table-seat' + (seat.present ? ' seated' : '')
                          + (isSelf ? ' table-seat--self' : '');
            div.setAttribute('data-slot', seat.n);
            if (seat.present && seat.token) div.setAttribute('data-seat-token', seat.token);
            div.innerHTML =
                '<i class="fa-solid fa-chair"></i>' +
                '<span class="seat-position-label">' + seat.label + '</span>' +
                '<i class="position-status-icon fa-solid ' +
                    (seat.present ? 'fa-circle-check' : 'fa-ban') + '"></i>';
            scene.appendChild(div);
        });
        // Re-fire the one-shot "just seated" glow for fresh occupancies
        // (localStorage-gated per token, so it only flares once per viewer).
        scene.querySelectorAll('.table-seat.seated[data-seat-token]')
             .forEach(playSeatGlow);
    }
    window.mySeaRenderSeats = renderSeats;

    // Subscribe a page to the my-sea spectate WS for live `sea_seats` ring
    // updates. The owner (my_sea) AND spectators (my_sea_visit) both connect to
    // `mysea_<ownerId>`; the consumer gate admits the owner + present invitees.
    // `myToken` marks the caller's own chair on re-render. Capped reconnect so a
    // down spectate server/Redis can't spin forever. Spectators keep their own
    // richer socket (it also carries `sea_draw`); this helper is for the OWNER
    // page, which only needs the seat ring (it draws its own hand locally).
    function connectSeatRing(ownerId, myToken) {
        if (!('WebSocket' in window) || !ownerId) return;
        var tries = 0;
        function open() {
            var scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';
            var ws;
            try {
                ws = new WebSocket(scheme + '://' + window.location.host +
                                   '/ws/my-sea-spectate/' + ownerId + '/');
            } catch (e) { return; }
            ws.onmessage = function (ev) {
                var msg;
                try { msg = JSON.parse(ev.data); } catch (e) { return; }
                if (msg && msg.type === 'sea_seats') renderSeats(msg.seats, myToken);
            };
            ws.onclose = function () { if (tries++ < 5) setTimeout(open, 3000); };
        }
        open();
    }
    window.mySeaConnectSeatRing = connectSeatRing;

    document.addEventListener('DOMContentLoaded', function () {
        var seats = document.querySelectorAll('.table-seat.seated[data-seat-token]');
        Array.prototype.forEach.call(seats, function (seat) {
            playSeatGlow(seat);
        });
    });
}());
