/**
 * Chess Podium admin: CP Connect config modal (copy params).
 *
 * @package Chess_Podium
 */
(function() {
    var btn = document.querySelector('.cp-generate-config-btn');
    var modal = document.getElementById('cp-config-modal');
    if (!btn || !modal) return;
    var copyMsg = (typeof window.chessPodiumAdmin !== 'undefined' && window.chessPodiumAdmin.copyMsg) ? window.chessPodiumAdmin.copyMsg : 'Copied to clipboard.';
    btn.addEventListener('click', function() {
        var tid = btn.getAttribute('data-tid');
        var round = btn.getAttribute('data-round');
        var apiUrl = btn.getAttribute('data-api-url');
        var rows = document.querySelectorAll('.cp-results-table tbody tr[data-is-bye="0"]');
        var mapping = [];
        rows.forEach(function(r) {
            mapping.push(r.getAttribute('data-board') + '→' + r.getAttribute('data-pairing-id'));
        });
        document.getElementById('cp-config-api-url').textContent = apiUrl || '';
        document.getElementById('cp-config-tid').textContent = tid || '';
        document.getElementById('cp-config-round').textContent = round || '';
        document.getElementById('cp-config-mapping').textContent = mapping.length ? mapping.join(', ') : '—';
        modal.style.display = 'flex';
    });
    var closeBtn = modal.querySelector('.cp-config-close-btn');
    if (closeBtn) closeBtn.addEventListener('click', function() { modal.style.display = 'none'; });
    modal.addEventListener('click', function(e) { if (e.target === modal) modal.style.display = 'none'; });
    var copyBtn = modal.querySelector('.cp-copy-config-btn');
    if (copyBtn) {
        copyBtn.addEventListener('click', function() {
            var txt = 'API URL: ' + document.getElementById('cp-config-api-url').textContent + '\n' +
                'tournament_id: ' + document.getElementById('cp-config-tid').textContent + '\n' +
                'round_no: ' + document.getElementById('cp-config-round').textContent + '\n' +
                'Board mapping (board_no→pairing_id): ' + document.getElementById('cp-config-mapping').textContent;
            navigator.clipboard.writeText(txt).then(function() { alert(copyMsg); });
        });
    }
})();
