// TV Overlay Control System JavaScript
class OverlayController {
    constructor() {
        this.state = {
            overlayType: 'lower-third',
            position: 'bottom-left',
            animation: 'slide',
            scale: 100,
            visible: false,
            eventId: null,
            currentParticipant: null,
            autoUpdate: 'off',
            displayDuration: 10
        };
        
        this.overlayFrame = document.getElementById('overlayFrame');
        this.participants = [];
        this.currentParticipantIndex = 0;
        
        this.init();
    }
    
    init() {
        // Load initial data
        this.loadParticipants();
        this.updateStatus();
        
        // Setup auto-update interval
        this.setupAutoUpdate();
        
        // Initialize scale slider
        this.updateScaleDisplay();
    }
    
    sendCommand(action, data = {}) {
        const command = { action, ...data };
        this.overlayFrame.contentWindow.postMessage(command, window.location.origin);
    }
    
    loadParticipants() {
        const eventId = document.getElementById('eventSelect').value;
        if (!eventId) return;
        
        // In real implementation, fetch from API
        // For demo, use sample data
        this.participants = [
            { id: 1, name: 'John Smith', country: 'USA', bib: '#42' },
            { id: 2, name: 'Jane Doe', country: 'CAN', bib: '#15' },
            { id: 3, name: 'Bob Wilson', country: 'NOR', bib: '#23' },
            { id: 4, name: 'Anna Lee', country: 'KOR', bib: '#8' },
            { id: 5, name: 'Max Weber', country: 'GER', bib: '#31' }
        ];
        
        this.updateParticipantDropdown();
    }
    
    updateParticipantDropdown() {
        const select = document.getElementById('participantSelect');
        select.innerHTML = '';
        
        this.participants.forEach((participant, index) => {
            const option = document.createElement('option');
            option.value = participant.id;
            option.textContent = `${participant.bib} ${participant.name} (${participant.country})`;
            if (index === this.currentParticipantIndex) {
                option.selected = true;
            }
            select.appendChild(option);
        });
    }
    
    updateStatus() {
        const typeNames = {
            'lower-third': 'Lower Third',
            'rankings': 'Live Rankings',
            'top5': 'Top 5 Results',
            'top3': 'Top 3 Podium',
            'startlist': 'Start List',
            'judges': 'Judge Scores',
            'none': 'Hidden'
        };
        
        const positionNames = {
            'top-left': 'Top Left',
            'top-center': 'Top Center',
            'top-right': 'Top Right',
            'center-left': 'Center Left',
            'center': 'Center',
            'center-right': 'Center Right',
            'bottom-left': 'Bottom Left',
            'bottom-center': 'Bottom Center',
            'bottom-right': 'Bottom Right'
        };
        
        document.getElementById('currentView').textContent = typeNames[this.state.overlayType] || 'Unknown';
        document.getElementById('currentPosition').textContent = positionNames[this.state.position] || 'Unknown';
        document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();
    }
    
    setupAutoUpdate() {
        const autoUpdateSelect = document.getElementById('autoUpdate');
        
        if (this.autoUpdateInterval) {
            clearInterval(this.autoUpdateInterval);
        }
        
        const interval = parseInt(autoUpdateSelect.value);
        if (interval > 0) {
            this.autoUpdateInterval = setInterval(() => {
                this.refreshData();
            }, interval * 1000);
        }
    }
    
    updateScaleDisplay() {
        const slider = document.getElementById('scaleSlider');
        const display = document.getElementById('scaleValue');
        const previewScale = document.getElementById('previewScale');
        
        display.textContent = slider.value + '%';
        previewScale.textContent = slider.value + '%';
        
        this.state.scale = parseInt(slider.value);
        this.sendCommand('setScale', { scale: this.state.scale });
    }
}

// Global controller instance
let overlayController;

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    overlayController = new OverlayController();
    
    // Load configurations for the initially selected event
    loadEventConfigurations();
    
    // Load saved panel order from local storage
    loadPanelOrder();
});

// Auto-save panel settings before page unloads
window.addEventListener('beforeunload', function() {
    savePanelOrder();
    savePanelSettings();
});

// Control Functions (called from HTML)
function setOverlayType(type) {
    // Update button states
    document.querySelectorAll('[id^="btn-"]').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById('btn-' + type).classList.add('active');
    
    // Send overlay type to display
    overlayController.sendCommand('setType', { type: type });
    
    overlayController.state.overlayType = type;
    overlayController.sendCommand('setType', { type });
    overlayController.updateStatus();
}

// Load ranking configurations for the current event
function loadEventConfigurations() {
    const eventId = document.getElementById('eventSelect').value;
    const configList = document.getElementById('configurationList');
    
    if (!eventId) {
        configList.innerHTML = '<div class="text-muted text-center"><i class="fas fa-info-circle me-1"></i>Select an event to load configurations</div>';
        return;
    }
    
    configList.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin me-2"></i>Loading configurations...</div>';
    
    // Use YOUR StyleScore API directly
    fetch(`../api/result_configurations_api.php?action=list&event_id=${eventId}&format=json`)
        .then(response => response.json())
        .then(data => {
            console.log('Configuration API Response:', data); // Debug log
            if (data.success && data.data && data.data.length > 0) {
                let html = '';
                data.data.forEach(config => {
                    html += `
                        <div class="configuration-item border rounded p-3 mb-2 bg-secondary bg-opacity-10">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">${config.name || `Configuration ${config.id}`}</h6>
                                    <small class="text-muted">Config ID: ${config.id} | Type: ${config.view_type || 'summary'}</small>
                                </div>
                                <div class="d-grid gap-1">
                                    <button type="button" class="btn btn-sm btn-primary" onclick="loadConfiguration(${config.id})">
                                        <i class="fas fa-download me-1"></i>Load
                                    </button>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=${config.id}&format=pdf', '_blank')" class="btn btn-outline-danger" title="Export PDF">
                                            <i class="fas fa-file-pdf"></i>
                                        </button>
                                        <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=${config.id}&format=html', '_blank')" class="btn btn-outline-secondary" title="Export HTML">
                                            <i class="fas fa-table"></i>
                                        </button>
                                        <button type="button" onclick="window.location.href='../api/summary_table_api.php?config_id=${config.id}&format=csv'" class="btn btn-outline-success" title="Export CSV">
                                            <i class="fas fa-file-csv"></i>
                                        </button>
                                        <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=${config.id}&format=json', '_blank')" class="btn btn-outline-info" title="View JSON">
                                            <i class="fas fa-code"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                configList.innerHTML = html;
            } else {
                const message = data.message || 'No configurations found for this event';
                configList.innerHTML = `<div class="text-muted text-center"><i class="fas fa-exclamation-circle me-1"></i>${message}</div>`;
            }
        })
        .catch(error => {
            console.error('Error loading configurations:', error);
            configList.innerHTML = `<div class="text-danger text-center"><i class="fas fa-exclamation-triangle me-1"></i>Error loading configurations: ${error.message}</div>`;
        });
}

// Load a specific configuration for TV overlay
function loadConfiguration(configId) {
    console.log('Loading configuration:', configId);
    
    // Set the overlay type to rankings
    setOverlayType('rankings');
    
    // Store the selected config ID
    window.selectedConfigId = configId;
    
    // Send message to overlay iframe to update with this configuration
    const overlayFrame = document.getElementById('overlayFrame');
    if (overlayFrame && overlayFrame.contentWindow) {
        overlayFrame.contentWindow.postMessage({
            action: 'loadConfiguration',
            configId: configId
        }, '*');
    }
    
    // Update overlay with this configuration
    overlayController.sendCommand('updateRankings', {
        configId: configId
    });
}

function setPosition(position) {
    // Update position button states
    document.querySelectorAll('.position-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-pos="${position}"]`).classList.add('active');
    
    overlayController.state.position = position;
    overlayController.sendCommand('setPosition', { position });
    overlayController.updateStatus();
}

function showOverlay() {
    overlayController.state.visible = true;
    overlayController.sendCommand('show');
    overlayController.updateStatus();
    
    // Auto-hide after duration if set
    const duration = parseInt(document.getElementById('displayDuration').value);
    if (duration > 0) {
        setTimeout(() => {
            hideOverlay();
        }, duration * 1000);
    }
}

function hideOverlay() {
    overlayController.state.visible = false;
    overlayController.sendCommand('hide');
    overlayController.updateStatus();
}

function updateScale() {
    overlayController.updateScaleDisplay();
}

function changeEvent() {
    const eventId = document.getElementById('eventSelect').value;
    overlayController.state.eventId = eventId;
    overlayController.loadParticipants();
    
    // Reload overlay frame with new event
    const currentSrc = overlayController.overlayFrame.src;
    const url = new URL(currentSrc);
    url.searchParams.set('event_id', eventId);
    overlayController.overlayFrame.src = url.toString();
}

function nextParticipant() {
    if (overlayController.participants.length === 0) return;
    
    overlayController.currentParticipantIndex = 
        (overlayController.currentParticipantIndex + 1) % overlayController.participants.length;
    
    selectCurrentParticipant();
}

function previousParticipant() {
    if (overlayController.participants.length === 0) return;
    
    overlayController.currentParticipantIndex = 
        overlayController.currentParticipantIndex === 0 
        ? overlayController.participants.length - 1 
        : overlayController.currentParticipantIndex - 1;
    
    selectCurrentParticipant();
}

function selectCurrentParticipant() {
    const participant = overlayController.participants[overlayController.currentParticipantIndex];
    if (!participant) return;
    
    overlayController.state.currentParticipant = participant.id;
    overlayController.sendCommand('setParticipant', { participantId: participant.id });
    overlayController.updateParticipantDropdown();
}

function selectParticipant(direction) {
    if (direction === 'next') {
        nextParticipant();
    } else if (direction === 'prev') {
        previousParticipant();
    } else {
        // Direct selection from dropdown
        const participantId = parseInt(document.getElementById('participantSelect').value);
        const index = overlayController.participants.findIndex(p => p.id === participantId);
        if (index !== -1) {
            overlayController.currentParticipantIndex = index;
            selectCurrentParticipant();
        }
    }
}

function refreshData() {
    overlayController.sendCommand('updateData');
    overlayController.updateStatus();
}

function openFullscreen() {
    const overlayWindow = window.open(
        overlayController.overlayFrame.src,
        'overlay_fullscreen',
        'fullscreen=yes,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes'
    );
    
    if (overlayWindow) {
        overlayWindow.focus();
    }
}

// Auto-update setup change
document.getElementById('autoUpdate').addEventListener('change', function() {
    overlayController.state.autoUpdate = this.value;
    overlayController.setupAutoUpdate();
});

// Animation type change
document.getElementById('animationType').addEventListener('change', function() {
    overlayController.state.animation = this.value;
    overlayController.sendCommand('setAnimation', { animation: this.value });
});

// Participant dropdown change
document.getElementById('participantSelect').addEventListener('change', function() {
    selectParticipant();
});

// Status indicators
function updateStatusIndicator(status) {
    const indicator = document.querySelector('.status-indicator');
    indicator.className = 'status-indicator';
    
    switch(status) {
        case 'live':
            indicator.classList.add('status-live');
            break;
        case 'ready':
            indicator.classList.add('status-ready');
            break;
        case 'loading':
            indicator.classList.add('status-loading');
            break;
    }
}

// Initialize status as ready
updateStatusIndicator('ready');

// Styling Control Functions
function updateStyling() {
    const styling = {
        rankFontSize: document.getElementById('rankFontSize').value,
        nameFontSize: document.getElementById('nameFontSize').value,
        scoreFontSize: document.getElementById('scoreFontSize').value,
        countryFontSize: document.getElementById('countryFontSize').value,
        rowHeight: document.getElementById('rowHeight').value,
        rowSpacing: document.getElementById('rowSpacing').value,
        rankingPadding: document.getElementById('rankingPadding').value,
        borderRadius: document.getElementById('borderRadius').value,
        bgOpacity: document.getElementById('bgOpacity').value,
        shadowIntensity: document.getElementById('shadowIntensity').value,
        enableGlow: document.getElementById('enableGlow').checked,
        
        // Width Controls
        lowerThirdWidth: document.getElementById('lowerThirdWidth') ? document.getElementById('lowerThirdWidth').value : 600,
        rankingsWidth: document.getElementById('rankingsWidth') ? document.getElementById('rankingsWidth').value : 480,
        resultColumnWidth: document.getElementById('resultColumnWidth') ? document.getElementById('resultColumnWidth').value : 100,
        rankColumnWidth: document.getElementById('rankColumnWidth') ? document.getElementById('rankColumnWidth').value : 60,
        bibColumnWidth: document.getElementById('bibColumnWidth') ? document.getElementById('bibColumnWidth').value : 60,
        judgesColumnWidth: document.getElementById('judgesColumnWidth') ? document.getElementById('judgesColumnWidth').value : 120,
        startlistColumnWidth: document.getElementById('startlistColumnWidth') ? document.getElementById('startlistColumnWidth').value : 80,
        
        // Panel Position Controls
        panelOffsetXOffscreen: document.getElementById('panelOffsetXOffscreen') ? document.getElementById('panelOffsetXOffscreen').value : -100,
        panelOffsetYOffscreen: document.getElementById('panelOffsetYOffscreen') ? document.getElementById('panelOffsetYOffscreen').value : 0,
        panelOffsetXOnscreen: document.getElementById('panelOffsetXOnscreen') ? document.getElementById('panelOffsetXOnscreen').value : 0,
        panelOffsetYOnscreen: document.getElementById('panelOffsetYOnscreen') ? document.getElementById('panelOffsetYOnscreen').value : 0,
        
        // Column Controls
        nameAlign: document.getElementById('nameAlign').value,
        nameOffsetX: document.getElementById('nameOffsetX').value,
        nameOffsetY: document.getElementById('nameOffsetY').value,
        showName: document.getElementById('showName').checked,
        clubAlign: document.getElementById('clubAlign').value,
        clubOffsetX: document.getElementById('clubOffsetX').value,
        clubOffsetY: document.getElementById('clubOffsetY').value,
        showClub: document.getElementById('showClub').checked,
        countryAlign: document.getElementById('countryAlign').value,
        countryOffsetX: document.getElementById('countryOffsetX').value,
        countryOffsetY: document.getElementById('countryOffsetY').value,
        showCountry: document.getElementById('showCountry').checked,
        
        // New column controls
        rankAlign: document.getElementById('rankAlign') ? document.getElementById('rankAlign').value : 'center',
        rankOffsetX: document.getElementById('rankOffsetX') ? document.getElementById('rankOffsetX').value : 0,
        rankOffsetY: document.getElementById('rankOffsetY') ? document.getElementById('rankOffsetY').value : 0,
        showRank: document.getElementById('showRank') ? document.getElementById('showRank').checked : true,
        scoreAlign: document.getElementById('scoreAlign') ? document.getElementById('scoreAlign').value : 'center',
        scoreOffsetX: document.getElementById('scoreOffsetX') ? document.getElementById('scoreOffsetX').value : 0,
        scoreOffsetY: document.getElementById('scoreOffsetY') ? document.getElementById('scoreOffsetY').value : 0,
        showScore: document.getElementById('showScore') ? document.getElementById('showScore').checked : true,
        bibAlign: document.getElementById('bibAlign') ? document.getElementById('bibAlign').value : 'center',
        bibOffsetX: document.getElementById('bibOffsetX') ? document.getElementById('bibOffsetX').value : 0,
        bibOffsetY: document.getElementById('bibOffsetY') ? document.getElementById('bibOffsetY').value : 0,
        showBib: document.getElementById('showBib') ? document.getElementById('showBib').checked : true,
        judgesAlign: document.getElementById('judgesAlign') ? document.getElementById('judgesAlign').value : 'center',
        judgesOffsetX: document.getElementById('judgesOffsetX') ? document.getElementById('judgesOffsetX').value : 0,
        judgesOffsetY: document.getElementById('judgesOffsetY') ? document.getElementById('judgesOffsetY').value : 0,
        showJudges: document.getElementById('showJudges') ? document.getElementById('showJudges').checked : true,
        startlistAlign: document.getElementById('startlistAlign') ? document.getElementById('startlistAlign').value : 'center',
        startlistOffsetX: document.getElementById('startlistOffsetX') ? document.getElementById('startlistOffsetX').value : 0,
        startlistOffsetY: document.getElementById('startlistOffsetY') ? document.getElementById('startlistOffsetY').value : 0,
        showStartlist: document.getElementById('showStartlist') ? document.getElementById('showStartlist').checked : true
    };
    
    // Update display values
    document.getElementById('rankFontSizeValue').textContent = styling.rankFontSize + 'px';
    document.getElementById('nameFontSizeValue').textContent = styling.nameFontSize + 'px';
    document.getElementById('scoreFontSizeValue').textContent = styling.scoreFontSize + 'px';
    document.getElementById('countryFontSizeValue').textContent = styling.countryFontSize + 'px';
    document.getElementById('rowHeightValue').textContent = styling.rowHeight + 'px';
    document.getElementById('rowSpacingValue').textContent = styling.rowSpacing + 'px';
    document.getElementById('rankingPaddingValue').textContent = styling.rankingPadding + 'px';
    document.getElementById('borderRadiusValue').textContent = styling.borderRadius + 'px';
    document.getElementById('bgOpacityValue').textContent = styling.bgOpacity + '%';
    document.getElementById('shadowIntensityValue').textContent = styling.shadowIntensity + '%';
    
    // Update width control display values
    if (document.getElementById('lowerThirdWidthValue')) {
        document.getElementById('lowerThirdWidthValue').textContent = styling.lowerThirdWidth + 'px';
    }
    if (document.getElementById('rankingsWidthValue')) {
        document.getElementById('rankingsWidthValue').textContent = styling.rankingsWidth + 'px';
    }
    if (document.getElementById('resultColumnWidthValue')) {
        document.getElementById('resultColumnWidthValue').textContent = styling.resultColumnWidth + 'px';
    }
    if (document.getElementById('rankColumnWidthValue')) {
        document.getElementById('rankColumnWidthValue').textContent = styling.rankColumnWidth + 'px';
    }
    if (document.getElementById('bibColumnWidthValue')) {
        document.getElementById('bibColumnWidthValue').textContent = styling.bibColumnWidth + 'px';
    }
    if (document.getElementById('judgesColumnWidthValue')) {
        document.getElementById('judgesColumnWidthValue').textContent = styling.judgesColumnWidth + 'px';
    }
    if (document.getElementById('startlistColumnWidthValue')) {
        document.getElementById('startlistColumnWidthValue').textContent = styling.startlistColumnWidth + 'px';
    }
    
    // Update panel position control display values
    if (document.getElementById('panelOffsetXOffscreenValue')) {
        document.getElementById('panelOffsetXOffscreenValue').textContent = styling.panelOffsetXOffscreen + '%';
    }
    if (document.getElementById('panelOffsetYOffscreenValue')) {
        document.getElementById('panelOffsetYOffscreenValue').textContent = styling.panelOffsetYOffscreen + 'px';
    }
    if (document.getElementById('panelOffsetXOnscreenValue')) {
        document.getElementById('panelOffsetXOnscreenValue').textContent = styling.panelOffsetXOnscreen + 'px';
    }
    if (document.getElementById('panelOffsetYOnscreenValue')) {
        document.getElementById('panelOffsetYOnscreenValue').textContent = styling.panelOffsetYOnscreen + 'px';
    }
    
    // Update column offset display values
    document.getElementById('nameOffsetXValue').textContent = styling.nameOffsetX + 'px';
    document.getElementById('nameOffsetYValue').textContent = styling.nameOffsetY + 'px';
    document.getElementById('clubOffsetXValue').textContent = styling.clubOffsetX + 'px';
    document.getElementById('clubOffsetYValue').textContent = styling.clubOffsetY + 'px';
    document.getElementById('countryOffsetXValue').textContent = styling.countryOffsetX + 'px';
    document.getElementById('countryOffsetYValue').textContent = styling.countryOffsetY + 'px';
    
    // Update new column offset display values
    if (document.getElementById('rankOffsetXValue')) {
        document.getElementById('rankOffsetXValue').textContent = styling.rankOffsetX + 'px';
    }
    if (document.getElementById('rankOffsetYValue')) {
        document.getElementById('rankOffsetYValue').textContent = styling.rankOffsetY + 'px';
    }
    if (document.getElementById('scoreOffsetXValue')) {
        document.getElementById('scoreOffsetXValue').textContent = styling.scoreOffsetX + 'px';
    }
    if (document.getElementById('scoreOffsetYValue')) {
        document.getElementById('scoreOffsetYValue').textContent = styling.scoreOffsetY + 'px';
    }
    if (document.getElementById('bibOffsetXValue')) {
        document.getElementById('bibOffsetXValue').textContent = styling.bibOffsetX + 'px';
    }
    if (document.getElementById('bibOffsetYValue')) {
        document.getElementById('bibOffsetYValue').textContent = styling.bibOffsetY + 'px';
    }
    if (document.getElementById('judgesOffsetXValue')) {
        document.getElementById('judgesOffsetXValue').textContent = styling.judgesOffsetX + 'px';
    }
    if (document.getElementById('judgesOffsetYValue')) {
        document.getElementById('judgesOffsetYValue').textContent = styling.judgesOffsetY + 'px';
    }
    if (document.getElementById('startlistOffsetXValue')) {
        document.getElementById('startlistOffsetXValue').textContent = styling.startlistOffsetX + 'px';
    }
    if (document.getElementById('startlistOffsetYValue')) {
        document.getElementById('startlistOffsetYValue').textContent = styling.startlistOffsetY + 'px';
    }
    
    // Send styling update to overlay
    overlayController.sendCommand('updateStyling', { styling });
}

function resetStyling() {
    // Reset all controls to default values
    document.getElementById('rankFontSize').value = 32;
    document.getElementById('nameFontSize').value = 24;
    document.getElementById('scoreFontSize').value = 20;
    document.getElementById('countryFontSize').value = 14;
    document.getElementById('rowHeight').value = 70;
    document.getElementById('rowSpacing').value = 8;
    document.getElementById('rankingPadding').value = 20;
    document.getElementById('borderRadius').value = 10;
    document.getElementById('bgOpacity').value = 90;
    document.getElementById('shadowIntensity').value = 50;
    document.getElementById('enableGlow').checked = true;
    
    // Reset width controls
    if (document.getElementById('lowerThirdWidth')) {
        document.getElementById('lowerThirdWidth').value = 600;
    }
    if (document.getElementById('rankingsWidth')) {
        document.getElementById('rankingsWidth').value = 480;
    }
    if (document.getElementById('resultColumnWidth')) {
        document.getElementById('resultColumnWidth').value = 100;
    }
    if (document.getElementById('rankColumnWidth')) {
        document.getElementById('rankColumnWidth').value = 60;
    }
    if (document.getElementById('bibColumnWidth')) {
        document.getElementById('bibColumnWidth').value = 60;
    }
    if (document.getElementById('judgesColumnWidth')) {
        document.getElementById('judgesColumnWidth').value = 120;
    }
    if (document.getElementById('startlistColumnWidth')) {
        document.getElementById('startlistColumnWidth').value = 80;
    }
    
    // Reset panel position controls
    if (document.getElementById('panelOffsetXOffscreen')) {
        document.getElementById('panelOffsetXOffscreen').value = -100;
    }
    if (document.getElementById('panelOffsetYOffscreen')) {
        document.getElementById('panelOffsetYOffscreen').value = 0;
    }
    if (document.getElementById('panelOffsetXOnscreen')) {
        document.getElementById('panelOffsetXOnscreen').value = 0;
    }
    if (document.getElementById('panelOffsetYOnscreen')) {
        document.getElementById('panelOffsetYOnscreen').value = 0;
    }
    
    // Reset column controls
    document.getElementById('nameAlign').value = 'left';
    document.getElementById('nameOffsetX').value = 0;
    document.getElementById('nameOffsetY').value = 0;
    document.getElementById('showName').checked = true;
    document.getElementById('clubAlign').value = 'left';
    document.getElementById('clubOffsetX').value = 0;
    document.getElementById('clubOffsetY').value = 0;
    document.getElementById('showClub').checked = true;
    document.getElementById('countryAlign').value = 'left';
    document.getElementById('countryOffsetX').value = 0;
    document.getElementById('countryOffsetY').value = 0;
    document.getElementById('showCountry').checked = true;
    
    // Reset new column controls
    if (document.getElementById('rankAlign')) {
        document.getElementById('rankAlign').value = 'center';
    }
    if (document.getElementById('rankOffsetX')) {
        document.getElementById('rankOffsetX').value = 0;
    }
    if (document.getElementById('rankOffsetY')) {
        document.getElementById('rankOffsetY').value = 0;
    }
    if (document.getElementById('showRank')) {
        document.getElementById('showRank').checked = true;
    }
    if (document.getElementById('scoreAlign')) {
        document.getElementById('scoreAlign').value = 'center';
    }
    if (document.getElementById('scoreOffsetX')) {
        document.getElementById('scoreOffsetX').value = 0;
    }
    if (document.getElementById('scoreOffsetY')) {
        document.getElementById('scoreOffsetY').value = 0;
    }
    if (document.getElementById('showScore')) {
        document.getElementById('showScore').checked = true;
    }
    if (document.getElementById('bibAlign')) {
        document.getElementById('bibAlign').value = 'center';
    }
    if (document.getElementById('bibOffsetX')) {
        document.getElementById('bibOffsetX').value = 0;
    }
    if (document.getElementById('bibOffsetY')) {
        document.getElementById('bibOffsetY').value = 0;
    }
    if (document.getElementById('showBib')) {
        document.getElementById('showBib').checked = true;
    }
    if (document.getElementById('judgesAlign')) {
        document.getElementById('judgesAlign').value = 'center';
    }
    if (document.getElementById('judgesOffsetX')) {
        document.getElementById('judgesOffsetX').value = 0;
    }
    if (document.getElementById('judgesOffsetY')) {
        document.getElementById('judgesOffsetY').value = 0;
    }
    if (document.getElementById('showJudges')) {
        document.getElementById('showJudges').checked = true;
    }
    if (document.getElementById('startlistAlign')) {
        document.getElementById('startlistAlign').value = 'center';
    }
    if (document.getElementById('startlistOffsetX')) {
        document.getElementById('startlistOffsetX').value = 0;
    }
    if (document.getElementById('startlistOffsetY')) {
        document.getElementById('startlistOffsetY').value = 0;
    }
    if (document.getElementById('showStartlist')) {
        document.getElementById('showStartlist').checked = true;
    }
    
    // Update styling
    updateStyling();
}

function applyStylingPreset(preset) {
    const presets = {
        compact: {
            rankFontSize: 24,
            nameFontSize: 18,
            scoreFontSize: 16,
            countryFontSize: 12,
            rowHeight: 50,
            rowSpacing: 4,
            rankingPadding: 15,
            borderRadius: 5,
            bgOpacity: 85,
            shadowIntensity: 30,
            enableGlow: true,
            nameAlign: 'left',
            nameOffsetX: 0,
            nameOffsetY: 0,
            showName: true,
            clubAlign: 'left',
            clubOffsetX: 0,
            clubOffsetY: 0,
            showClub: true,
            countryAlign: 'center',
            countryOffsetX: 0,
            countryOffsetY: 0,
            showCountry: true
        },
        large: {
            rankFontSize: 42,
            nameFontSize: 32,
            scoreFontSize: 26,
            countryFontSize: 18,
            rowHeight: 90,
            rowSpacing: 12,
            rankingPadding: 30,
            borderRadius: 15,
            bgOpacity: 95,
            shadowIntensity: 70,
            enableGlow: true,
            nameAlign: 'left',
            nameOffsetX: 5,
            nameOffsetY: 0,
            showName: true,
            clubAlign: 'left',
            clubOffsetX: 5,
            clubOffsetY: 0,
            showClub: true,
            countryAlign: 'center',
            countryOffsetX: 0,
            countryOffsetY: 0,
            showCountry: true
        },
        minimal: {
            rankFontSize: 28,
            nameFontSize: 20,
            scoreFontSize: 18,
            countryFontSize: 12,
            rowHeight: 60,
            rowSpacing: 2,
            rankingPadding: 10,
            borderRadius: 0,
            bgOpacity: 60,
            shadowIntensity: 20,
            enableGlow: false,
            nameAlign: 'left',
            nameOffsetX: 0,
            nameOffsetY: 0,
            showName: true,
            clubAlign: 'left',
            clubOffsetX: 0,
            clubOffsetY: 0,
            showClub: false,
            countryAlign: 'center',
            countryOffsetX: 0,
            countryOffsetY: 0,
            showCountry: true
        },
        broadcast: {
            rankFontSize: 36,
            nameFontSize: 26,
            scoreFontSize: 22,
            countryFontSize: 16,
            rowHeight: 75,
            rowSpacing: 10,
            rankingPadding: 25,
            borderRadius: 12,
            bgOpacity: 92,
            shadowIntensity: 60,
            enableGlow: true,
            nameAlign: 'left',
            nameOffsetX: 8,
            nameOffsetY: 0,
            showName: true,
            clubAlign: 'left',
            clubOffsetX: 8,
            clubOffsetY: 0,
            showClub: true,
            countryAlign: 'center',
            countryOffsetX: 0,
            countryOffsetY: -2,
            showCountry: true
        }
    };
    
    const presetValues = presets[preset];
    if (!presetValues) return;
    
    // Apply preset values to controls
    Object.keys(presetValues).forEach(key => {
        const element = document.getElementById(key);
        if (element) {
            if (element.type === 'checkbox') {
                element.checked = presetValues[key];
            } else {
                element.value = presetValues[key];
            }
        }
    });
    
    // Update styling
    updateStyling();
}

// Initialize styling controls when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Set initial styling values
    updateStyling();
    
    // Initialize draggable panels
    initializeDraggablePanels();
    
    // Load saved panel settings from local storage
    loadPanelSettings();
});

// Draggable Panel System
let dragState = {
    isDragging: false,
    currentPanel: null,
    startX: 0,
    startY: 0,
    offsetX: 0,
    offsetY: 0
};

// Z-index management for bringing panels to front
let highestZIndex = 1000;

function bringToFront(panel) {
    if (panel.classList.contains('floating')) {
        highestZIndex++;
        panel.style.zIndex = highestZIndex;
    }
}

function initializeDraggablePanels() {
    // Find all panels that can be made draggable (they have panel-header and panel-content)
    const panels = document.querySelectorAll('[id$="Panel"]:not(#controlPanel)');
    
    console.log('Initializing panels in docked state:', panels.length);
    
    panels.forEach(panel => {
        const header = panel.querySelector('.panel-header');
        
        console.log('Processing panel:', panel.id, 'Current classes:', panel.className);
        
        // Ensure panels start as normal docked panels (no draggable-panel class)
        panel.classList.remove('draggable-panel', 'floating', 'minimized');
        
        // Add a class to identify these as potential draggable panels
        panel.classList.add('panel');
        
        // Force docked positioning and remove any floating styles
        panel.style.position = '';
        panel.style.left = '';
        panel.style.top = '';
        panel.style.transform = '';
        panel.style.zIndex = '';
        
        // Ensure panel stays in the layout (not moved to body)
        if (panel.parentElement.tagName.toLowerCase() === 'body') {
            // If panel was moved to body, move it back to the left column
            const leftColumn = document.querySelector('.col-lg-4');
            const mainControlPanel = leftColumn.querySelector('.control-panel');
            if (mainControlPanel.nextElementSibling) {
                leftColumn.insertBefore(panel, mainControlPanel.nextElementSibling);
            } else {
                leftColumn.appendChild(panel);
            }
        }
        
        // Initialize all panels as minimized
        panel.classList.add('minimized');
        const content = panel.querySelector('.panel-content');
        const btn = panel.querySelector('.panel-btn.minimize i');
        
        if (content) {
            content.style.display = 'none';
        }
        if (btn) {
            btn.className = 'fas fa-plus';
        }
        panel.style.height = '50px';
        
        // Ensure float button shows correct state for docked panels
        const floatBtn = panel.querySelector('.panel-btn.float i');
        if (floatBtn) {
            floatBtn.className = 'fas fa-external-link-alt';
            floatBtn.parentElement.title = 'Float';
        }
        
        // Ensure move buttons are visible for docked panels
        const moveButtons = panel.querySelectorAll('.panel-btn.move-up, .panel-btn.move-down');
        moveButtons.forEach(btn => btn.style.display = 'flex');
        
        console.log('Panel after processing:', panel.id, 'Classes:', panel.className);
        
        // Note: We don't add drag event listeners here anymore
        // They will be added when the panel is floated
    });
}

function startDrag(panel, e) {
    dragState.isDragging = true;
    dragState.currentPanel = panel;
    
    // Bring panel to front when starting to drag
    bringToFront(panel);
    
    // Get the panel's actual position on screen, accounting for any transforms or margins
    const rect = panel.getBoundingClientRect();
    const computedStyle = window.getComputedStyle(panel);
    
    dragState.startX = e.clientX;
    dragState.startY = e.clientY;
    
    // Calculate offset from cursor to panel's actual top-left corner
    // Account for any CSS transforms or margins
    dragState.offsetX = e.clientX - rect.left;
    dragState.offsetY = e.clientY - rect.top;
    
    panel.style.transition = 'none';
    document.body.style.cursor = 'move';
    document.body.style.userSelect = 'none';
    
    // Ensure panel is in floating mode for dragging
    if (!panel.classList.contains('floating')) {
        panel.classList.add('floating');
        
        // When switching to floating, preserve current visual position
        panel.style.left = rect.left + 'px';
        panel.style.top = rect.top + 'px';
        
        const floatBtn = panel.querySelector('.panel-btn.float i');
        if (floatBtn) {
            floatBtn.className = 'fas fa-compress';
            floatBtn.parentElement.title = 'Dock';
        }
    }
}

function handleDrag(e) {
    if (!dragState.isDragging || !dragState.currentPanel) return;
    
    // Prevent default to avoid any browser drag behaviors
    e.preventDefault();
    
    // Calculate new position based on cursor position minus the initial offset
    const newLeft = e.clientX - dragState.offsetX;
    const newTop = e.clientY - dragState.offsetY;
    
    // Keep panel within viewport bounds with some padding
    const padding = 10;
    const maxLeft = window.innerWidth - dragState.currentPanel.offsetWidth - padding;
    const maxTop = window.innerHeight - dragState.currentPanel.offsetHeight - padding;
    
    const constrainedLeft = Math.max(padding, Math.min(newLeft, maxLeft));
    const constrainedTop = Math.max(padding, Math.min(newTop, maxTop));
    
    dragState.currentPanel.style.left = constrainedLeft + 'px';
    dragState.currentPanel.style.top = constrainedTop + 'px';
}

function stopDrag() {
    if (dragState.isDragging && dragState.currentPanel) {
        dragState.currentPanel.style.transition = 'all 0.3s ease';
        document.body.style.cursor = '';
        document.body.style.userSelect = '';
        
        // Save panel settings after dragging
        savePanelSettings();
    }
    
    dragState.isDragging = false;
    dragState.currentPanel = null;
}

function toggleMinimize(panelId) {
    const panel = document.getElementById(panelId);
    const content = panel.querySelector('.panel-content');
    const btn = panel.querySelector('.panel-btn.minimize i');
    
    panel.classList.toggle('minimized');
    
    if (panel.classList.contains('minimized')) {
        content.style.display = 'none';
        btn.className = 'fas fa-plus';
        panel.style.height = '50px';
    } else {
        content.style.display = 'block';
        btn.className = 'fas fa-minus';
        panel.style.height = 'auto';
    }
    
    // Save panel settings after state change
    savePanelSettings();
}

function toggleFloat(panelId) {
    const panel = document.getElementById(panelId);
    const btn = panel.querySelector('.panel-btn.float i');
    
    if (panel.classList.contains('floating')) {
        // Dock panel - remove draggable functionality
        panel.classList.remove('floating', 'draggable-panel');
        
        // Find the appropriate parent container in the left column
        const leftColumn = document.querySelector('.col-lg-4');
        const mainControlPanel = leftColumn.querySelector('.control-panel');
        
        // Insert after the main control panel
        if (mainControlPanel.nextElementSibling) {
            leftColumn.insertBefore(panel, mainControlPanel.nextElementSibling);
        } else {
            leftColumn.appendChild(panel);
        }
        
        // Reset inline positioning
        panel.style.left = '';
        panel.style.top = '';
        panel.style.position = '';
        panel.style.zIndex = '';
        
        // Remove drag event listeners
        const header = panel.querySelector('.panel-header');
        if (header) {
            header.replaceWith(header.cloneNode(true)); // Remove all event listeners
        }
        
        // Show move buttons for docked panels
        const moveButtons = panel.querySelectorAll('.panel-btn.move-up, .panel-btn.move-down');
        moveButtons.forEach(btn => btn.style.display = 'flex');
        
        btn.className = 'fas fa-external-link-alt';
        btn.parentElement.title = 'Float';
    } else {
        // Float panel - add draggable functionality
        panel.classList.add('draggable-panel', 'floating');
        
        // Move to body and position it
        document.body.appendChild(panel);
        
        // Position panel in center of viewport
        const rect = panel.getBoundingClientRect();
        panel.style.left = (window.innerWidth / 2 - rect.width / 2) + 'px';
        panel.style.top = (window.innerHeight / 2 - rect.height / 2) + 'px';
        
        // Set z-index for proper layering
        highestZIndex++;
        panel.style.zIndex = highestZIndex;
        
        // Add drag event listeners
        const header = panel.querySelector('.panel-header');
        if (header) {
            header.addEventListener('mousedown', function(e) {
                if (e.target.closest('.panel-controls')) return; // Don't drag if clicking controls
                
                // Prevent text selection during drag
                e.preventDefault();
                
                startDrag(panel, e);
            });
        }
        
        // Also bring to front on any click within the panel
        panel.addEventListener('mousedown', function(e) {
            bringToFront(panel);
        });
        
        // Make sure drag event listeners are set up globally (only once)
        if (!window.dragEventListenersAdded) {
            document.addEventListener('mousemove', handleDrag);
            document.addEventListener('mouseup', stopDrag);
            window.dragEventListenersAdded = true;
        }
        
        // Hide move buttons for floating panels
        const moveButtons = panel.querySelectorAll('.panel-btn.move-up, .panel-btn.move-down');
        moveButtons.forEach(btn => btn.style.display = 'none');
        
        btn.className = 'fas fa-compress';
        btn.parentElement.title = 'Dock';
    }
    
    // Save panel settings after state change
    savePanelOrder();
    savePanelSettings();
}

function closePanel(panelId) {
    const panel = document.getElementById(panelId);
    panel.style.opacity = '0';
    panel.style.transform = 'scale(0.8)';
    
    setTimeout(() => {
        panel.style.display = 'none';
        // Add button to reopen panel
        addReopenButton(panelId, panel);
        
        // Save panel settings after state change
        savePanelSettings();
    }, 300);
}

function addReopenButton(panelId, panel) {
    // Check if reopen button already exists
    if (document.getElementById(`reopen-${panelId}`)) return;
    
    const reopenBtn = document.createElement('button');
    reopenBtn.id = `reopen-${panelId}`;
    reopenBtn.className = 'btn btn-outline-info btn-sm mb-2';
    reopenBtn.innerHTML = `<i class="fas fa-plus me-1"></i>Show ${panel.querySelector('.panel-header h5').textContent}`;
    reopenBtn.onclick = () => reopenPanel(panelId);
    
    // Add to the first control panel
    const firstPanel = document.querySelector('.control-panel');
    firstPanel.insertBefore(reopenBtn, firstPanel.firstChild);
}

function reopenPanel(panelId) {
    const panel = document.getElementById(panelId);
    const reopenBtn = document.getElementById(`reopen-${panelId}`);
    
    if (reopenBtn) {
        reopenBtn.remove();
    }
    
    panel.style.display = 'block';
    setTimeout(() => {
        panel.style.opacity = '1';
        panel.style.transform = 'scale(1)';
        
        // Save panel settings after state change
        savePanelSettings();
    }, 10);
}

// Keyboard shortcuts for panel management
document.addEventListener('keydown', function(event) {
    if (event.ctrlKey || event.metaKey) {
        switch(event.key) {
            case '1':
                setOverlayType('lower-third');
                event.preventDefault();
                break;
            case '2':
                setOverlayType('rankings');
                event.preventDefault();
                break;
            case '3':
                setOverlayType('top3');
                event.preventDefault();
                break;
            case 'h':
                hideOverlay();
                event.preventDefault();
                break;
            case 's':
                showOverlay();
                event.preventDefault();
                break;
            case 'm':
                // Toggle minimize styling panel
                toggleMinimize('stylingPanel');
                event.preventDefault();
                break;
            case 'f':
                // Toggle float styling panel
                toggleFloat('stylingPanel');
                event.preventDefault();
                break;
            case 'ArrowRight':
                nextParticipant();
                event.preventDefault();
                break;
            case 'ArrowLeft':
                previousParticipant();
                event.preventDefault();
                break;
        }
    }
});

// Panel Manager Functions
function toggleAllPanels() {
    const panels = document.querySelectorAll('.panel[id$="Panel"]:not(#controlPanel)');
    const allHidden = Array.from(panels).every(panel => panel.style.display === 'none');
    
    panels.forEach(panel => {
        if (allHidden) {
            reopenPanel(panel.id);
        } else {
            closePanel(panel.id);
        }
    });
}

function floatAllPanels() {
    const panels = document.querySelectorAll('.panel[id$="Panel"]:not(#controlPanel)');
    panels.forEach((panel, index) => {
        if (!panel.classList.contains('floating')) {
            toggleFloat(panel.id);
            
            // Cascade panels with slight offset
            const offset = index * 30;
            panel.style.left = (50 + offset) + 'px';
            panel.style.top = (50 + offset) + 'px';
        }
    });
}

function dockAllPanels() {
    const panels = document.querySelectorAll('.panel[id$="Panel"]:not(#controlPanel)');
    
    panels.forEach(panel => {
        if (panel.classList.contains('floating')) {
            toggleFloat(panel.id);
        }
    });
}

function minimizeAllPanels() {
    const panels = document.querySelectorAll('.panel[id$="Panel"]:not(#controlPanel)');
    const allMinimized = Array.from(panels).every(panel => panel.classList.contains('minimized'));
    
    panels.forEach(panel => {
        if (allMinimized) {
            // Expand all
            if (panel.classList.contains('minimized')) {
                toggleMinimize(panel.id);
            }
        } else {
            // Minimize all
            if (!panel.classList.contains('minimized')) {
                toggleMinimize(panel.id);
            }
        }
    });
}

function resetPanelLayout() {
    const panels = document.querySelectorAll('.panel[id$="Panel"]:not(#controlPanel)');
    panels.forEach(panel => {
        // Remove floating
        if (panel.classList.contains('floating')) {
            toggleFloat(panel.id);
        }
        
        // Expand if minimized
        if (panel.classList.contains('minimized')) {
            toggleMinimize(panel.id);
        }
        
        // Show if hidden
        if (panel.style.display === 'none') {
            reopenPanel(panel.id);
        }
    });
}

// Panel reordering functions
function movePanelUp(panelId) {
    const panel = document.getElementById(panelId);
    
    // Only allow moving docked panels
    if (panel.classList.contains('floating')) {
        return;
    }
    
    const parentContainer = panel.parentElement;
    const previousSibling = panel.previousElementSibling;
    
    // Don't move above the main control panel
    if (previousSibling && !previousSibling.classList.contains('control-panel')) {
        parentContainer.insertBefore(panel, previousSibling);
        
        // Add visual feedback
        addMoveAnimation(panel, 'up');
        
        // Save the new panel order
        savePanelOrder();
        savePanelSettings();
    }
}

function movePanelDown(panelId) {
    const panel = document.getElementById(panelId);
    
    // Only allow moving docked panels
    if (panel.classList.contains('floating')) {
        return;
    }
    
    const parentContainer = panel.parentElement;
    const nextSibling = panel.nextElementSibling;
    
    if (nextSibling) {
        parentContainer.insertBefore(nextSibling, panel);
        
        // Add visual feedback
        addMoveAnimation(panel, 'down');
        
        // Save the new panel order
        savePanelOrder();
        savePanelSettings();
    }
}

function addMoveAnimation(panel, direction) {
    // Add a subtle animation to show the panel moved
    panel.style.transition = 'transform 0.3s ease';
    const offset = direction === 'up' ? '-10px' : '10px';
    panel.style.transform = `translateY(${offset})`;
    
    setTimeout(() => {
        panel.style.transform = '';
        setTimeout(() => {
            panel.style.transition = '';
        }, 300);
    }, 150);
}

// Local Storage Functions for Panel Management

function savePanelOrder() {
    const controlPanel = document.querySelector('.col-lg-4');
    const panels = controlPanel.querySelectorAll('[id$="Panel"]:not(#controlPanel)');
    
    const panelOrder = Array.from(panels).map(panel => panel.id);
    
    try {
        localStorage.setItem('tvOverlayPanelOrder', JSON.stringify(panelOrder));
        console.log('Panel order saved:', panelOrder);
        showSaveNotification('Panel order saved');
    } catch (error) {
        console.error('Failed to save panel order:', error);
        showSaveNotification('Failed to save panel order', 'danger');
    }
}

function loadPanelOrder() {
    try {
        const savedOrder = localStorage.getItem('tvOverlayPanelOrder');
        if (!savedOrder) {
            console.log('No saved panel order found');
            return;
        }
        
        const panelOrder = JSON.parse(savedOrder);
        console.log('Loading panel order:', panelOrder);
        
        const controlPanel = document.querySelector('.col-lg-4');
        const mainControlPanel = controlPanel.querySelector('.control-panel');
        
        // Get all existing panels
        const existingPanels = {};
        const panels = controlPanel.querySelectorAll('[id$="Panel"]:not(#controlPanel)');
        panels.forEach(panel => {
            existingPanels[panel.id] = panel;
        });
        
        // Create a document fragment to hold the reordered panels
        const fragment = document.createDocumentFragment();
        
        // Add panels to fragment in the saved order
        panelOrder.forEach(panelId => {
            if (existingPanels[panelId]) {
                fragment.appendChild(existingPanels[panelId]);
                // Mark as processed
                delete existingPanels[panelId];
            }
        });
        
        // Add any remaining panels that weren't in the saved order
        Object.values(existingPanels).forEach(panel => {
            fragment.appendChild(panel);
        });
        
        // Insert all panels after the main control panel
        const nextSibling = mainControlPanel.nextSibling;
        if (nextSibling) {
            controlPanel.insertBefore(fragment, nextSibling);
        } else {
            controlPanel.appendChild(fragment);
        }
        
        console.log('Panel order restored successfully');
    } catch (error) {
        console.error('Failed to load panel order:', error);
    }
}

function savePanelSettings() {
    const panels = document.querySelectorAll('[id$="Panel"]:not(#controlPanel)');
    const panelSettings = {};
    
    panels.forEach(panel => {
        panelSettings[panel.id] = {
            minimized: panel.classList.contains('minimized'),
            floating: panel.classList.contains('floating'),
            hidden: panel.style.display === 'none',
            position: {
                left: panel.style.left,
                top: panel.style.top,
                zIndex: panel.style.zIndex
            }
        };
    });
    
    try {
        localStorage.setItem('tvOverlayPanelSettings', JSON.stringify(panelSettings));
        console.log('Panel settings saved:', panelSettings);
        showSaveNotification('Panel settings saved');
    } catch (error) {
        console.error('Failed to save panel settings:', error);
        showSaveNotification('Failed to save panel settings', 'danger');
    }
}

function loadPanelSettings() {
    try {
        const savedSettings = localStorage.getItem('tvOverlayPanelSettings');
        if (!savedSettings) {
            console.log('No saved panel settings found');
            return;
        }
        
        const panelSettings = JSON.parse(savedSettings);
        console.log('Loading panel settings:', panelSettings);
        
        Object.keys(panelSettings).forEach(panelId => {
            const panel = document.getElementById(panelId);
            if (!panel) return;
            
            const settings = panelSettings[panelId];
            
            // Apply floating state first
            if (settings.floating) {
                if (!panel.classList.contains('floating')) {
                    toggleFloat(panelId);
                }
                
                // Apply saved position for floating panels
                if (settings.position.left) {
                    panel.style.left = settings.position.left;
                }
                if (settings.position.top) {
                    panel.style.top = settings.position.top;
                }
                if (settings.position.zIndex) {
                    panel.style.zIndex = settings.position.zIndex;
                    // Update highest z-index to prevent conflicts
                    const zIndex = parseInt(settings.position.zIndex);
                    if (zIndex > highestZIndex) {
                        highestZIndex = zIndex;
                    }
                }
            }
            
            // Apply minimized state
            const isCurrentlyMinimized = panel.classList.contains('minimized');
            if (settings.minimized !== isCurrentlyMinimized) {
                toggleMinimize(panelId);
            }
            
            // Apply hidden state
            if (settings.hidden) {
                closePanel(panelId);
            }
        });
        
        console.log('Panel settings restored successfully');
    } catch (error) {
        console.error('Failed to load panel settings:', error);
    }
}

function clearPanelSettings() {
    try {
        localStorage.removeItem('tvOverlayPanelOrder');
        localStorage.removeItem('tvOverlayPanelSettings');
        console.log('Panel settings cleared from local storage');
        
        // Show confirmation
        const notification = document.createElement('div');
        notification.className = 'alert alert-success position-fixed';
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            <i class="fas fa-check-circle me-2"></i>
            Panel settings cleared successfully
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(notification);
        
        // Auto-remove after 3 seconds
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 3000);
    } catch (error) {
        console.error('Failed to clear panel settings:', error);
    }
}

function showSaveNotification(message, type = 'success') {
    // Only show notifications when called manually (not during auto-save)
    const isManualSave = new Error().stack.includes('onclick');
    if (!isManualSave) return;
    
    const alertClass = type === 'danger' ? 'alert-danger' : 'alert-success';
    const iconClass = type === 'danger' ? 'fas fa-exclamation-triangle' : 'fas fa-check-circle';
    
    const notification = document.createElement('div');
    notification.className = `alert ${alertClass} position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px; opacity: 0; transition: opacity 0.3s ease;';
    notification.innerHTML = `
        <i class="${iconClass} me-2"></i>
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;
    document.body.appendChild(notification);
    
    // Fade in
    setTimeout(() => {
        notification.style.opacity = '1';
    }, 10);
    
    // Auto-remove after 2 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.style.opacity = '0';
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 300);
        }
    }, 2000);
}
