// custom-scoreboard.js - Manual scoreboard for game participants

let scoreboardData = [];
let nextRowId = 1;
let isAnimating = false;
let _sbSuppressBroadcast = false; // Prevent broadcast loops during incoming sync
const REORDER_ANIMATION_DURATION = 300; // ms

// BroadcastChannel for two-way scoreboard sync between main and pop-out
let _scoreboardChannel = null;
try {
    _scoreboardChannel = new BroadcastChannel('jongvoter-scoreboard');
    _scoreboardChannel.onmessage = function(e) {
        if (e.data.type === 'scoreboardSync') {
            _sbSuppressBroadcast = true;
            scoreboardData = e.data.scoreboardData || [];
            nextRowId = e.data.nextRowId || 1;
            // Update title if included
            if (e.data.title) {
                setScoreboardTitle(e.data.title);
                var titleSpan = document.getElementById('scoreboardTitleText');
                if (titleSpan && !titleSpan._editing) titleSpan.textContent = e.data.title;
            }
            // Save to localStorage so both windows stay in sync
            try {
                localStorage.setItem('customScoreboardData', JSON.stringify(scoreboardData));
                localStorage.setItem('scoreboardNextId', nextRowId.toString());
            } catch (ex) { }
            renderScoreboard();
            _sbSuppressBroadcast = false;
        }
    };
} catch (e) { }

// Format score for display (show ½ for .5 values)
function formatScore(score) {
    if (score % 1 === 0.5 || score % 1 === -0.5) {
        const wholePart = Math.floor(score);
        if (wholePart === 0 && score > 0) {
            return '½';
        }
        return wholePart + '½';
    }
    return score.toString();
}

// Get/set scoreboard title from localStorage
function getScoreboardTitle() {
    try { return localStorage.getItem('scoreboardTitle') || 'Custom Scoreboard'; }
    catch (e) { return 'Custom Scoreboard'; }
}

function setScoreboardTitle(title) {
    try { localStorage.setItem('scoreboardTitle', title); }
    catch (e) { }

    // Broadcast title change
    if (_scoreboardChannel && !_sbSuppressBroadcast) {
        try {
            _scoreboardChannel.postMessage({
                type: 'scoreboardSync',
                scoreboardData: scoreboardData,
                nextRowId: nextRowId,
                title: title
            });
        } catch (e) { }
    }
}

function renameScoreboard() {
    const span = document.getElementById('scoreboardTitleText');
    if (!span || span._editing) return;
    span._editing = true;

    const current = span.textContent;
    const input = document.createElement('input');
    input.type = 'text';
    input.value = current;
    input.className = 'form-control form-control-sm d-inline-block';
    input.style.cssText = 'width: auto; min-width: 120px; font-size: inherit; font-weight: inherit; padding: 0 4px; height: auto;';

    function commit() {
        var val = input.value.trim() || current;
        setScoreboardTitle(val);
        span.textContent = val;
        span.style.display = '';
        input.remove();
        span._editing = false;
    }

    input.addEventListener('blur', commit);
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
        if (e.key === 'Escape') { input.value = current; input.blur(); }
    });

    span.style.display = 'none';
    span.parentNode.insertBefore(input, span.nextSibling);
    input.focus();
    input.select();
}

// Initialize the custom scoreboard
function initCustomScoreboard() {
    createScoreboardUI();
    loadScoreboardData();
    renderScoreboard();
}

// Create the scoreboard UI structure
function createScoreboardUI() {
    const widgetContainer2 = document.getElementById('widgetContainer2');

    if (widgetContainer2) {
        const scoreboardDiv = document.createElement('div');
        scoreboardDiv.className = 'custom-scoreboard-container mt-4 p-3 border rounded bg-body-tertiary';
        scoreboardDiv.innerHTML = `
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0 scoreboard-title" style="cursor: pointer;" title="Click to rename">
                    <i class="fas fa-trophy"></i> <span id="scoreboardTitleText">${getScoreboardTitle()}</span>
                </h6>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-sm btn-outline-success" id="addScoreboardRow">
                        <i class="fas fa-plus"></i> Add Player
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-warning" id="resetScoreboard">
                        <i class="fas fa-undo"></i> Reset All
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-info" id="toggleScoreboard">
                        <i class="fas fa-eye-slash"></i> Hide
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="popoutScoreboardBtn" title="Pop out scoreboard (for OBS)" style="opacity: 0.6;">
                        <i class="fas fa-external-link-alt"></i>
                    </button>
                </div>
            </div>
            
            <div id="scoreboardRows" class="scoreboard-rows">
                <!-- Scoreboard rows will be dynamically added here -->
            </div>
            
            <div id="scoreboardEmpty" class="text-center text-muted py-3" style="display: none;">
                <i class="fas fa-users"></i><br>
                <small>No players added yet. Click "Add Player" to get started!</small>
            </div>
        `;

        widgetContainer2.appendChild(scoreboardDiv);
        setupScoreboardEventListeners();
    }
}

// Set up event listeners for scoreboard functionality
function setupScoreboardEventListeners() {
    // Add new row button
    const addRowBtn = document.getElementById('addScoreboardRow');
    if (addRowBtn) {
        addRowBtn.addEventListener('click', function() {
            addScoreboardRow('Player ' + (scoreboardData.length + 1));
        });
    }

    // Reset all scores button
    const resetBtn = document.getElementById('resetScoreboard');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetAllScores);
    }

    // Toggle visibility button
    const toggleBtn = document.getElementById('toggleScoreboard');
    if (toggleBtn) {
        toggleBtn.addEventListener('click', toggleScoreboardVisibility);
    }

    // Rename scoreboard title on click
    const titleEl = document.querySelector('.scoreboard-title');
    if (titleEl) {
        titleEl.addEventListener('click', renameScoreboard);
    }
}

// Add a new scoreboard row
function addScoreboardRow(name = '', score = 0) {
    const newRow = {
        id: nextRowId++,
        name: name,
        score: score
    };

    scoreboardData.push(newRow);
    saveScoreboardData();
    renderScoreboard();
}

// Delete a scoreboard row
function deleteScoreboardRow(rowId) {
    scoreboardData = scoreboardData.filter(row => row.id !== rowId);
    saveScoreboardData();
    renderScoreboard();
}

// Update participant name
function updateParticipantName(rowId, newName) {
    const row = scoreboardData.find(r => r.id === rowId);
    if (row) {
        row.name = newName;
        saveScoreboardData();
    }
}

// Update score
function updateScore(rowId, change) {
    const row = scoreboardData.find(r => r.id === rowId);
    if (row) {
        row.score = Math.max(0, row.score + change); // Prevent negative scores
        saveScoreboardData();
        renderScoreboard();
    }
}

// Reset all scores to zero
function resetAllScores() {
    if (scoreboardData.length === 0) return;

    if (confirm('Reset all scores to 0? This cannot be undone.')) {
        scoreboardData.forEach(row => {
            row.score = 0;
        });
        saveScoreboardData();
        renderScoreboard();
    }
}

// Render the entire scoreboard with FLIP animation for reordering
function renderScoreboard() {
    const container = document.getElementById('scoreboardRows');
    const emptyMessage = document.getElementById('scoreboardEmpty');

    if (!container) return;

    if (scoreboardData.length === 0) {
        container.innerHTML = '';
        if (emptyMessage) {
            emptyMessage.style.display = 'block';
        }
        return;
    }

    if (emptyMessage) {
        emptyMessage.style.display = 'none';
    }

    // Sort by score (highest first) for display
    const sortedData = [...scoreboardData].sort((a, b) => b.score - a.score);

    // FLIP Animation: First - capture current positions
    const existingRows = container.querySelectorAll('.scoreboard-row');
    const firstPositions = new Map();

    existingRows.forEach(row => {
        const rowId = parseInt(row.dataset.rowId);
        if (rowId) {
            const rect = row.getBoundingClientRect();
            firstPositions.set(rowId, { top: rect.top, left: rect.left });
        }
    });

    // Check if we have existing rows or need to create new ones
    const existingIds = new Set();
    existingRows.forEach(row => {
        const rowId = parseInt(row.dataset.rowId);
        if (rowId) existingIds.add(rowId);
    });

    // Update or create rows
    sortedData.forEach((rowData, index) => {
        let rowElement = container.querySelector(`.scoreboard-row[data-row-id="${rowData.id}"]`);

        if (rowElement) {
            // Update existing row content (position number and score)
            updateRowContent(rowElement, rowData, index + 1);
        } else {
            // Create new row
            rowElement = createScoreboardRowElement(rowData, index + 1);
            container.appendChild(rowElement);
        }
    });

    // Remove deleted rows
    existingRows.forEach(row => {
        const rowId = parseInt(row.dataset.rowId);
        if (!sortedData.find(r => r.id === rowId)) {
            row.remove();
        }
    });

    // Reorder DOM elements to match sorted order
    sortedData.forEach((rowData) => {
        const rowElement = container.querySelector(`.scoreboard-row[data-row-id="${rowData.id}"]`);
        if (rowElement) {
            container.appendChild(rowElement); // Moves to end in sorted order
        }
    });

    // FLIP Animation: Last - get new positions, Invert & Play
    if (firstPositions.size > 0 && !isAnimating) {
        const rowsToAnimate = container.querySelectorAll('.scoreboard-row');

        rowsToAnimate.forEach(row => {
            const rowId = parseInt(row.dataset.rowId);
            const firstPos = firstPositions.get(rowId);

            if (firstPos) {
                const lastRect = row.getBoundingClientRect();
                const deltaY = firstPos.top - lastRect.top;

                if (Math.abs(deltaY) > 1) {
                    // Apply inverse transform (Invert)
                    row.style.transform = `translateY(${deltaY}px)`;
                    row.style.transition = 'none';

                    // Force reflow
                    row.offsetHeight;

                    // Animate to final position (Play)
                    row.style.transition = `transform ${REORDER_ANIMATION_DURATION}ms ease-out`;
                    row.style.transform = 'translateY(0)';

                    // Clean up after animation
                    setTimeout(() => {
                        row.style.transition = '';
                        row.style.transform = '';
                    }, REORDER_ANIMATION_DURATION);
                }
            }
        });
    }
}

// Update existing row content without recreating
function updateRowContent(rowElement, rowData, position) {
    // Update position number
    const positionEl = rowElement.querySelector('.col-1 small');
    if (positionEl) {
        positionEl.textContent = `#${position}`;
    }

    // Update name input
    const nameInput = rowElement.querySelector('.participant-name');
    if (nameInput && !nameInput.matches(':focus')) {
        nameInput.value = rowData.name;
    }

    // Update score display
    const scoreDisplay = rowElement.querySelector('.score-display');
    if (scoreDisplay) {
        scoreDisplay.textContent = formatScore(rowData.score);
    }

    // Update delete button title
    const deleteBtn = rowElement.querySelector('.delete-row-btn');
    if (deleteBtn) {
        deleteBtn.title = `Delete ${rowData.name || 'this player'}`;
    }
}

// Create a single scoreboard row element
function createScoreboardRowElement(rowData, position) {
    const rowDiv = document.createElement('div');
    rowDiv.className = 'scoreboard-row mb-2 p-2 border rounded bg-body';
    rowDiv.dataset.rowId = rowData.id;

    // Entrance animation for new rows
    rowDiv.style.opacity = '0';
    rowDiv.style.transform = 'translateY(-10px)';
    requestAnimationFrame(() => {
        rowDiv.style.transition = `opacity ${REORDER_ANIMATION_DURATION}ms ease-out, transform ${REORDER_ANIMATION_DURATION}ms ease-out`;
        rowDiv.style.opacity = '1';
        rowDiv.style.transform = 'translateY(0)';
        setTimeout(() => {
            rowDiv.style.transition = '';
        }, REORDER_ANIMATION_DURATION);
    });

    rowDiv.innerHTML = `
        <div class="row align-items-center">
            <!-- Position & Delete -->
            <div class="col-1 text-center">
                <small class="text-muted">#${position}</small>
            </div>
            
            <!-- Name Input -->
            <div class="col-4">
                <input type="text" 
                       class="form-control form-control-sm participant-name" 
                       value="${rowData.name}" 
                       placeholder="Player Name"
                       data-row-id="${rowData.id}">
            </div>
            
            <!-- Score Controls -->
            <div class="col-5">
                <div class="input-group input-group-sm">
                    <button class="btn btn-outline-danger score-btn"
                            type="button"
                            data-row-id="${rowData.id}"
                            data-change="-1">
                        <i class="fas fa-minus"></i>
                    </button>
                    <button class="btn btn-outline-danger score-btn score-half"
                            type="button"
                            data-row-id="${rowData.id}"
                            data-change="-0.5">
                        -½
                    </button>

                    <span class="input-group-text score-display bg-primary text-white fw-bold text-center" style="min-width: 50px; justify-content: center;">
                        ${formatScore(rowData.score)}
                    </span>

                    <button class="btn btn-outline-success score-btn score-half"
                            type="button"
                            data-row-id="${rowData.id}"
                            data-change="0.5">
                        +½
                    </button>
                    <button class="btn btn-outline-success score-btn"
                            type="button"
                            data-row-id="${rowData.id}"
                            data-change="1">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
            </div>
            
            <!-- Delete Button -->
            <div class="col-2 text-end">
                <button class="btn btn-sm btn-outline-danger delete-row-btn" 
                        type="button" 
                        data-row-id="${rowData.id}"
                        title="Delete ${rowData.name || 'this player'}">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;

    // Add event listeners for this row
    setupRowEventListeners(rowDiv, rowData.id);

    return rowDiv;
}

// Set up event listeners for a specific row
function setupRowEventListeners(rowElement, rowId) {
    // Name input
    const nameInput = rowElement.querySelector('.participant-name');
    if (nameInput) {
        nameInput.addEventListener('change', function () {
            updateParticipantName(rowId, this.value);
        });

        nameInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                this.blur(); // Trigger change event
            }
        });
    }

    // Score buttons
    const scoreButtons = rowElement.querySelectorAll('.score-btn');
    scoreButtons.forEach(btn => {
        btn.addEventListener('click', function () {
            const change = parseFloat(this.dataset.change);
            updateScore(rowId, change);
        });
    });

    // Delete button
    const deleteBtn = rowElement.querySelector('.delete-row-btn');
    if (deleteBtn) {
        deleteBtn.addEventListener('click', function () {
            const row = scoreboardData.find(r => r.id === rowId);
            const playerName = row ? row.name || 'this player' : 'this player';

            if (confirm(`Delete ${playerName}? This cannot be undone.`)) {
                deleteScoreboardRow(rowId);
            }
        });
    }
}

// Toggle scoreboard visibility
function toggleScoreboardVisibility() {
    const scoreboardRows = document.getElementById('scoreboardRows');
    const emptyMessage = document.getElementById('scoreboardEmpty');
    const toggleBtn = document.getElementById('toggleScoreboard');

    if (!scoreboardRows || !toggleBtn) return;

    const isHidden = scoreboardRows.style.display === 'none';

    if (isHidden) {
        // Show
        scoreboardRows.style.display = 'block';
        if (emptyMessage) emptyMessage.style.display = scoreboardData.length === 0 ? 'block' : 'none';
        toggleBtn.innerHTML = '<i class="fas fa-eye-slash"></i> Hide';
    } else {
        // Hide
        scoreboardRows.style.display = 'none';
        if (emptyMessage) emptyMessage.style.display = 'none';
        toggleBtn.innerHTML = '<i class="fas fa-eye"></i> Show';
    }
}

// Save scoreboard data to localStorage
function saveScoreboardData() {
    try {
        localStorage.setItem('customScoreboardData', JSON.stringify(scoreboardData));
        localStorage.setItem('scoreboardNextId', nextRowId.toString());
    } catch (e) {
        console.error('Failed to save scoreboard data:', e);
    }

    // Broadcast to other windows
    if (_scoreboardChannel && !_sbSuppressBroadcast) {
        try {
            _scoreboardChannel.postMessage({
                type: 'scoreboardSync',
                scoreboardData: scoreboardData,
                nextRowId: nextRowId,
                title: getScoreboardTitle()
            });
        } catch (e) { }
    }
}

// Load scoreboard data from localStorage
function loadScoreboardData() {
    try {
        const saved = localStorage.getItem('customScoreboardData');
        const savedNextId = localStorage.getItem('scoreboardNextId');

        if (saved) {
            scoreboardData = JSON.parse(saved) || [];
        }

        if (savedNextId) {
            nextRowId = parseInt(savedNextId) || 1;
        }

        // Ensure all rows have valid IDs
        scoreboardData.forEach(row => {
            if (!row.id) {
                row.id = nextRowId++;
            }
        });

    } catch (e) {
        console.error('Failed to load scoreboard data:', e);
        scoreboardData = [];
        nextRowId = 1;
    }
}

// Clear all scoreboard data
function clearScoreboardData() {
    if (confirm('Delete all players and scores? This cannot be undone.')) {
        scoreboardData = [];
        nextRowId = 1;
        saveScoreboardData();
        renderScoreboard();
    }
}

// Export scoreboard data as text
function exportScoreboardText() {
    if (scoreboardData.length === 0) {
        alert('No players to export!');
        return;
    }

    const sortedData = [...scoreboardData].sort((a, b) => b.score - a.score);
    let exportText = 'SCOREBOARD\n==========\n\n';

    sortedData.forEach((row, index) => {
        const playerName = row.name || `Player ${row.id}`;
        exportText += `${index + 1}. ${playerName}: ${row.score} points\n`;
    });

    // Copy to clipboard if possible
    if (navigator.clipboard) {
        navigator.clipboard.writeText(exportText).then(() => {
            alert('Scoreboard copied to clipboard!');
        }).catch(() => {
            // Fallback: show in alert
            alert('Scoreboard:\n\n' + exportText);
        });
    } else {
        // Fallback: show in alert
        alert('Scoreboard:\n\n' + exportText);
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
    // Wait a bit for other scripts to load
    setTimeout(() => {
        initCustomScoreboard();
    }, 200);
});

// Export functions for external use
window.customScoreboard = {
    addPlayer: (name = '', score = 0) => addScoreboardRow(name, score),
    deletePlayer: deleteScoreboardRow,
    updateScore: updateScore,
    resetAll: resetAllScores,
    clearAll: clearScoreboardData,
    getData: () => [...scoreboardData],
    exportText: exportScoreboardText,
    show: () => {
        const container = document.querySelector('.custom-scoreboard-container');
        if (container) container.style.display = 'block';
    },
    hide: () => {
        const container = document.querySelector('.custom-scoreboard-container');
        if (container) container.style.display = 'none';
    }
};