(function(){
    function init(){
    var container = document.querySelector('.cp-live-boards-container');
    if (!container) return;
    var url = container.getAttribute('data-live-moves-url');
    if (!url) return;
    var boards = {};
    var liveData = [];
    var boardMoveIdx = {};
    var blockEls = container.querySelectorAll('.cp-live-board-block');
    function fenFromPgn(pgn) {
        if (!pgn || typeof Chess === 'undefined') return null;
        var loadPgn = function(c, s) {
            return (c.load_pgn && c.load_pgn(s)) || (c.loadPgn && c.loadPgn(s));
        };
        try {
            var chess = new Chess();
            var stripLichess = function(s) {
                if (!s || typeof s !== 'string') return '';
                return s.replace(/\s*\{[^}]*\}\s*/g, ' ')
                    .replace(/\[\%[a-zA-Z]+\s+[^\]]*\]/g, '')
                    .replace(/\s*\$\d+\s*/g, ' ')
                    .replace(/\s+/g, ' ').trim();
            };
            var stripped = stripLichess(pgn);
            if (loadPgn(chess, stripped)) return chess.fen();
            if (loadPgn(chess, pgn)) return chess.fen();
            var idx = pgn.search(/\d+\.\s*(?:[NBRQK]?[a-h]?[1-8]?x?[a-h][1-8]|O-O-O|O-O)/i);
            if (idx >= 0) {
                var movePart = stripLichess(pgn.substring(idx));
                movePart = movePart.replace(/\s*(?:1-0|0-1|1\/2-1\/2|\*)\s*$/, '').trim();
                if (movePart && loadPgn(chess, movePart)) return chess.fen();
            }
        } catch (e) {}
        return null;
    }
    var pieceTheme = (typeof chessPodiumConfig !== 'undefined' && chessPodiumConfig.pieceTheme ? chessPodiumConfig.pieceTheme : '') || '';
    function stripPgnForReplay(pgn) {
        if (!pgn || typeof pgn !== 'string') return '';
        return pgn.replace(/\s*\{[^}]*\}\s*/g, ' ')
            .replace(/\[\%[a-zA-Z]+\s+[^\]]*\]/g, '')
            .replace(/\s*\$\d+\s*/g, ' ')
            .replace(/\s*(?:1-0|0-1|1\/2-1\/2|\*)\s*$/i, '')
            .replace(/\s+/g, ' ').trim();
    }
    function getMovesFromPgn(pgn) {
        if (!pgn || typeof Chess === 'undefined') return [];
        var loadPgn = function(c, s) { return (c.load_pgn && c.load_pgn(s)) || (c.loadPgn && c.loadPgn(s)); };
        try {
            var chess = new Chess();
            var stripped = stripPgnForReplay(pgn);
            if (!loadPgn(chess, stripped)) return [];
            var hist = chess.history ? chess.history() : [];
            return Array.isArray(hist) ? hist : [];
        } catch (e) { return []; }
    }
    function getFenAtMove(pgn, moveIdx) {
        if (!pgn || typeof Chess === 'undefined') return null;
        var loadPgn = function(c, s) { return (c.load_pgn && c.load_pgn(s)) || (c.loadPgn && c.loadPgn(s)); };
        try {
            var chess = new Chess();
            var stripped = stripPgnForReplay(pgn);
            if (!loadPgn(chess, stripped)) return chess.fen();
            var hist = chess.history ? chess.history() : [];
            chess.reset();
            for (var i = 0; i <= moveIdx && i < hist.length; i++) chess.move(hist[i]);
            return chess.fen();
        } catch (e) { return null; }
    }
    blockEls.forEach(function(block){
        var pid = parseInt(block.getAttribute('data-pairing-id'), 10);
        var boardEl = block.querySelector('.cp-live-board');
        if (!boardEl || typeof ChessBoard === 'undefined') return;
        var fen = boardEl.getAttribute('data-initial-fen') || 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
        var pgn = block.getAttribute('data-pgn') || '';
        var derived = fenFromPgn(pgn);
        if (derived) fen = derived;
        boards[pid] = ChessBoard(boardEl.id, { position: fen, pieceTheme: pieceTheme, draggable: false });
        liveData.push({ pairing_id: pid, round: block.getAttribute('data-round'), white: block.getAttribute('data-white') || '', black: block.getAttribute('data-black') || '', fen: fen, result: block.getAttribute('data-result') || '', pgn: block.getAttribute('data-pgn') || '', blockEl: block });
    });
    liveData.forEach(function(d){
        if (boards[d.pairing_id] && boards[d.pairing_id].resize) {
            setTimeout(function(){ try { boards[d.pairing_id].resize(); } catch(e) {} }, 100);
        }
    });
    function updateFen(pid, fen) {
        var d = liveData.filter(function(x){ return x.pairing_id === pid; })[0];
        if (d && d.result && String(d.result).trim().length > 0) return;
        liveData.forEach(function(o){ if (o.pairing_id === pid) o.fen = fen; });
        d = liveData.filter(function(x){ return x.pairing_id === pid; })[0];
        var moves = (d && d.pgn) ? getMovesFromPgn(d.pgn) : [];
        var atLive = (moves.length === 0) || (typeof boardMoveIdx[pid] === 'undefined' || boardMoveIdx[pid] >= moves.length - 1);
        if (atLive && boards[pid]) try { boards[pid].position(fen); } catch(e) {}
        if (atLive && moves.length > 0) boardMoveIdx[pid] = moves.length - 1;
    }
    function updateResult(pid, result) {
        liveData.forEach(function(d){
            if (d.pairing_id !== pid) return;
            d.result = result || '';
            if (!d.blockEl) return;
            var header = d.blockEl.querySelector('.cp-live-board-header');
            if (!header) return;
            var span = header.querySelector('.cp-live-result');
            if (result) {
                if (!span) { span = document.createElement('span'); span.className = 'cp-live-result'; span.style.cssText = 'color:#059669;font-weight:700;'; header.appendChild(document.createTextNode(' ')); header.appendChild(span); }
                span.textContent = result;
            } else if (span) span.remove();
        });
    }
    function poll() {
        var fetchUrl = url + (url.indexOf('?') >= 0 ? '&' : '?') + 't=' + Date.now();
        fetch(fetchUrl, { cache: 'no-store', headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' } }).then(function(r){ return r.json(); }).then(function(data){
            var moves = data.live_moves || [];
            moves.forEach(function(m){
                var fen = null;
                if (m.pgn) fen = fenFromPgn(m.pgn);
                if (!fen && m.fen) fen = m.fen;
                if (fen) updateFen(m.pairing_id, fen);
                if (m.result) updateResult(m.pairing_id, m.result);
                if (m.pgn) {
                    liveData.forEach(function(d){ if (d.pairing_id === m.pairing_id) d.pgn = m.pgn || ''; });
                    var block = null;
                    for (var bi = 0; bi < blockEls.length; bi++) { if (parseInt(blockEls[bi].getAttribute('data-pairing-id'),10) === m.pairing_id) { block = blockEls[bi]; break; } }
                    if (block) buildPgnNav(block, m.pairing_id);
                }
            });
        }).catch(function(){});
    }
    poll();
    setInterval(poll, 1500);

    function buildPgnNav(block, pid, forceEnd) {
        var navEl = block.querySelector('.cp-live-board-pgn-nav[data-pairing-id="' + pid + '"]');
        if (!navEl) return;
        var d = liveData.filter(function(x){ return x.pairing_id === pid; })[0];
        if (!d) return;
        var moves = (d && d.pgn) ? getMovesFromPgn(d.pgn) : [];
        if (!d.pgn || moves.length === 0) {
            navEl.style.display = 'block';
            navEl.innerHTML = '<div class="cp-live-pgn-controls"><button type="button" class="cp-live-pgn-first" aria-label="Start">|&larr;</button><button type="button" class="cp-live-pgn-prev" aria-label="Previous">&larr;</button><span class="cp-live-pgn-info">—</span><button type="button" class="cp-live-pgn-next" aria-label="Next">&rarr;</button><button type="button" class="cp-live-pgn-last" aria-label="End">&rarr;|</button></div><div class="cp-live-pgn-moves"></div>';
            navEl.onclick = function(e){ e.stopPropagation(); };
            var firstBtn = navEl.querySelector('.cp-live-pgn-first'), prevBtn = navEl.querySelector('.cp-live-pgn-prev'), nextBtn = navEl.querySelector('.cp-live-pgn-next'), lastBtn = navEl.querySelector('.cp-live-pgn-last');
            firstBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if (boards[pid]) try { boards[pid].position('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'); } catch(x){} });
            prevBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if (boards[pid]) try { boards[pid].position('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'); } catch(x){} });
            nextBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if (boards[pid] && d.fen) try { boards[pid].position(d.fen); } catch(x){} });
            lastBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if (boards[pid] && d.fen) try { boards[pid].position(d.fen); } catch(x){} });
            return;
        }
        if (forceEnd || typeof boardMoveIdx[pid] === 'undefined') boardMoveIdx[pid] = moves.length - 1;
        else boardMoveIdx[pid] = Math.min(boardMoveIdx[pid], moves.length - 1);
        var cur = boardMoveIdx[pid];
        navEl.style.display = 'block';
        navEl.innerHTML = '<div class="cp-live-pgn-controls"><button type="button" class="cp-live-pgn-first" aria-label="Start">|&larr;</button><button type="button" class="cp-live-pgn-prev" aria-label="Previous">&larr;</button><span class="cp-live-pgn-info"></span><button type="button" class="cp-live-pgn-next" aria-label="Next">&rarr;</button><button type="button" class="cp-live-pgn-last" aria-label="End">&rarr;|</button></div><div class="cp-live-pgn-moves"></div>';
        var infoEl = navEl.querySelector('.cp-live-pgn-info');
        var movesEl = navEl.querySelector('.cp-live-pgn-moves');
        var firstBtn = navEl.querySelector('.cp-live-pgn-first');
        var prevBtn = navEl.querySelector('.cp-live-pgn-prev');
        var nextBtn = navEl.querySelector('.cp-live-pgn-next');
        var lastBtn = navEl.querySelector('.cp-live-pgn-last');
        function fmtMove(i) { return (Math.floor(i/2)+1) + (i%2===0 ? '. ' : ' ') + moves[i]; }
        function renderMoves() {
            var html = '';
            for (var i = 0; i < moves.length; i++) {
                var cls = (i === cur) ? ' cp-live-pgn-move-current' : '';
                html += '<span class="cp-live-pgn-move' + cls + '" data-move-idx="' + i + '">' + (i%2===0 ? (Math.floor(i/2)+1) + '. ' : '') + moves[i] + '</span> ';
            }
            movesEl.innerHTML = html;
            movesEl.querySelectorAll('.cp-live-pgn-move').forEach(function(span){
                span.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); var idx = parseInt(span.getAttribute('data-move-idx'),10); setBoardPosition(pid, idx); });
            });
        }
        function setBoardPosition(pid, moveIdx) {
            boardMoveIdx[pid] = moveIdx;
            var fen = moveIdx < 0 ? 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' : getFenAtMove(d.pgn, moveIdx);
            if (fen && boards[pid]) try { boards[pid].position(fen); } catch(e) {}
            var nav = block.querySelector('.cp-live-board-pgn-nav[data-pairing-id="' + pid + '"]');
            if (!nav) return;
            cur = moveIdx;
            firstBtn.disabled = false;
            prevBtn.disabled = false;
            nextBtn.disabled = false;
            lastBtn.disabled = false;
            infoEl.textContent = cur < 0 ? '0' : (cur >= moves.length - 1 ? moves.length + ' moves' : (Math.floor(cur/2)+1) + (cur%2===0 ? '.' : '...'));
            renderMoves();
        }
        function updateNav() {
            cur = boardMoveIdx[pid];
            firstBtn.disabled = false;
            prevBtn.disabled = false;
            nextBtn.disabled = false;
            lastBtn.disabled = false;
            infoEl.textContent = cur < 0 ? '0' : (cur >= moves.length - 1 ? moves.length + ' moves' : (Math.floor(cur/2)+1) + (cur%2===0 ? '.' : '...'));
            renderMoves();
        }
        firstBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); setBoardPosition(pid, -1); });
        prevBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); setBoardPosition(pid, Math.max(-1, cur - 1)); });
        nextBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); setBoardPosition(pid, Math.min(moves.length - 1, cur + 1)); });
        lastBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); setBoardPosition(pid, moves.length - 1); });
        navEl.onclick = function(e){ e.preventDefault(); e.stopPropagation(); };
        setBoardPosition(pid, cur);
    }
    blockEls.forEach(function(block){
        var pid = parseInt(block.getAttribute('data-pairing-id'), 10);
        buildPgnNav(block, pid);
    });

    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
