<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TV Overlay Display - StyleScore</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        html, body {
            width: 100vw;
            height: 100vh;
            background: transparent;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            overflow: hidden;
        }
        
        :root {
            --lime: #39FF14;
            --blue: #4B7BFF;
            --violet: #AD26FF;
            --white: #FFFFFF;
            --dark: #0B1220;
            --grad: linear-gradient(135deg, var(--lime), var(--blue) 45%, var(--violet));
            
            /* Styling Variables */
            --rank-font-size: 32px;
            --name-font-size: 24px;
            --score-font-size: 20px;
            --country-font-size: 14px;
            --row-height: 70px;
            --row-spacing: 8px;
            --ranking-padding: 20px;
            --border-radius: 10px;
            --bg-opacity: 0.9;
            --shadow-intensity: 0.5;
            --glow-enabled: 1;
            
            /* Column Controls */
            --name-align: left;
            --name-offset-x: 0px;
            --name-offset-y: 0px;
            --show-name: block;
            --club-align: left;
            --club-offset-x: 0px;
            --club-offset-y: 0px;
            --show-club: block;
            --country-align: left;
            --country-offset-x: 0px;
            --country-offset-y: 0px;
            --show-country: block;
            --rank-align: center;
            --rank-offset-x: 0px;
            --rank-offset-y: 0px;
            --show-rank: block;
            --score-align: center;
            --score-offset-x: 0px;
            --score-offset-y: 0px;
            --show-score: block;
            --bib-align: center;
            --bib-offset-x: 0px;
            --bib-offset-y: 0px;
            --show-bib: block;
            --judges-align: center;
            --judges-offset-x: 0px;
            --judges-offset-y: 0px;
            --show-judges: flex;
            --startlist-align: center;
            --startlist-offset-x: 0px;
            --startlist-offset-y: 0px;
            --show-startlist: flex;
            
            /* Width Controls */
            --lowerthird-width: 600px;
            --rankings-width: 480px;
            --podium-width: auto;
            --result-column-width: 100px;
            --name-column-width: auto;
            --club-column-width: auto;
            --rank-column-width: 60px;
            --judges-column-width: 120px;
            --startlist-column-width: 80px;
            --bib-column-width: 60px;
            
            /* Panel Position Controls */
            --panel-offset-x-offscreen: -100%;
            --panel-offset-y-offscreen: 0px;
            --panel-offset-x-onscreen: 0px;
            --panel-offset-y-onscreen: 0px;
        }
        
        .overlay-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 1000;
            background: #009933;
        }
        
        /* Lower Third Graphics */
        .lower-third {
            position: absolute;
            bottom: 60px;
            left: 40px;
            background: linear-gradient(90deg, rgba(11,18,32,0.95), rgba(11,18,32,0.85));
            backdrop-filter: blur(10px);
            border-radius: 16px;
            border: 2px solid rgba(255,255,255,0.1);
            padding: 20px 30px;
            min-width: 400px;
            max-width: var(--lowerthird-width);
            width: var(--lowerthird-width);
            color: white;
            box-shadow: 0 20px 40px rgba(0,0,0,0.5);
            transform: translateX(-100%);
            transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .lower-third.show {
            transform: translateX(0);
        }
        
        .lower-third.position-top-left { top: 40px; left: 40px; bottom: auto; }
        .lower-third.position-top-center { top: 40px; left: 50%; bottom: auto; transform: translateX(-50%); }
        .lower-third.position-top-right { top: 40px; right: 40px; bottom: auto; left: auto; }
        .lower-third.position-center-left { top: 50%; left: 40px; bottom: auto; transform: translateY(-50%); }
        .lower-third.position-center { top: 50%; left: 50%; bottom: auto; transform: translate(-50%, -50%); }
        .lower-third.position-center-right { top: 50%; right: 40px; bottom: auto; left: auto; transform: translateY(-50%); }
        .lower-third.position-bottom-center { bottom: 60px; left: 50%; transform: translateX(-50%); }
        .lower-third.position-bottom-right { bottom: 60px; right: 40px; left: auto; }
        
        .participant-name {
            font-size: 24px;
            font-weight: 700;
            background: var(--grad);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-bottom: 8px;
        }
        
        .participant-info {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 12px;
        }
        
        .country-flag {
            width: 32px;
            height: 24px;
            border-radius: 4px;
            background: #ccc;
        }
        
        .bib-number {
            background: var(--grad);
            color: var(--dark);
            padding: 4px 12px;
            border-radius: 8px;
            font-weight: 700;
            font-size: 18px;
            text-align: var(--bib-align);
            transform: translate(var(--bib-offset-x), var(--bib-offset-y));
            display: var(--show-bib);
        }
        
        .scores-container {
            display: flex;
            gap: 15px;
            align-items: center;
        }
        
        .score-item {
            text-align: center;
        }
        
        .score-label {
            font-size: 12px;
            color: rgba(255,255,255,0.7);
            margin-bottom: 2px;
        }
        
        .score-value {
            font-size: 20px;
            font-weight: 700;
            color: var(--lime);
        }
        
        .current-score {
            font-size: 28px;
            color: white;
        }
        
        /* Rankings Table */
        .rankings-table {
            position: absolute;
            top: 40px;
            right: 40px;
            background: linear-gradient(180deg, 
                rgba(11,18,32,0.95) 0%, 
                rgba(15,23,48,0.9) 50%, 
                rgba(11,18,32,0.95) 100%);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            border: 2px solid rgba(57,255,20,0.3);
            padding: 25px;
            min-width: 380px;
            max-width: var(--rankings-width);
            width: var(--rankings-width);
            color: white;
            box-shadow: 
                0 25px 50px rgba(0,0,0,0.6),
                0 0 0 1px rgba(255,255,255,0.1),
                inset 0 1px 0 rgba(255,255,255,0.1);
            transform: translate(var(--panel-offset-x-offscreen), var(--panel-offset-y-offscreen));
            transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .rankings-table.show {
            transform: translate(var(--panel-offset-x-onscreen), var(--panel-offset-y-onscreen));
        }
        
        .ranking-container {
            position: relative;
            width: 100%;
        }
        
        .ranking-row {
            position: relative;
            display: block;
            width: 100%;
            height: var(--row-height);
            margin-bottom: var(--row-spacing);
            border-bottom: 1px solid rgba(57,255,20,0.2);
            opacity: 0;
            transform: translateX(50px);
            transition: all 0.3s ease;
            background: rgba(11,18,32, var(--bg-opacity));
            border-radius: var(--border-radius);
            box-shadow: 0 4px 8px rgba(0,0,0, calc(var(--shadow-intensity) * 0.01));
        }
        
        .ranking-row:last-child {
            border-bottom: none;
        }
        
        .ranking-cell {
            position: absolute;
            top: 0;
            height: 100%;
            display: flex;
            align-items: center;
            padding: 8px;
        }
        
        .ranking-cell.rank-cell {
            left: 0;
            width: var(--rank-column-width);
            justify-content: center;
        }
        
        .ranking-cell.bib-cell {
            left: var(--rank-column-width);
            width: 60px;
            justify-content: center;
        }
        
        .ranking-cell.name-cell {
            left: calc(var(--rank-column-width) + 60px);
            right: calc(var(--result-column-width) + var(--judges-column-width, 120px) + var(--startlist-column-width, 80px));
            flex-direction: column;
            justify-content: center;
            align-items: flex-start;
            text-align: left;
        }
        
        .ranking-cell.judges-cell {
            right: calc(var(--result-column-width) + var(--startlist-column-width, 80px));
            width: var(--judges-column-width, 120px);
            justify-content: center;
            flex-direction: column;
            text-align: var(--judges-align);
            transform: translate(var(--judges-offset-x), var(--judges-offset-y));
            display: var(--show-judges);
        }
        
        .ranking-cell.startlist-cell {
            right: var(--result-column-width);
            width: var(--startlist-column-width, 80px);
            justify-content: center;
            text-align: var(--startlist-align);
            transform: translate(var(--startlist-offset-x), var(--startlist-offset-y));
            display: var(--show-startlist);
        }
        
        .ranking-cell.score-cell {
            right: 0;
            width: var(--result-column-width);
            justify-content: center;
        }
        
        .judge-scores {
            display: flex;
            flex-direction: column;
            gap: 2px;
            font-size: 11px;
            width: 100%;
        }
        
        .judge-score {
            background: rgba(255,255,255,0.1);
            padding: 1px 4px;
            border-radius: 3px;
            font-weight: 500;
            text-align: center;
            color: rgba(255,255,255,0.9);
        }
        
        .start-order {
            font-weight: 600;
            color: rgba(255,255,255,0.8);
            font-size: 14px;
        }
        
        .table-header {
            background: var(--grad);
            color: var(--dark);
            padding: 16px 20px;
            border-radius: 12px;
            font-weight: 800;
            text-align: center;
            margin-bottom: 20px;
            font-size: 18px;
            text-transform: uppercase;
            letter-spacing: 1px;
            box-shadow: 
                0 8px 16px rgba(0,0,0,0.3),
                inset 0 1px 0 rgba(255,255,255,0.2);
        }
        
        .ranking-row {
            position: relative;
            display: block;
            width: 100%;
            height: var(--row-height);
            margin-bottom: var(--row-spacing);
            border-bottom: 1px solid rgba(57,255,20,0.2);
            opacity: 0;
            transform: translateX(50px);
            transition: all 0.3s ease;
            background: rgba(11,18,32, var(--bg-opacity));
            border-radius: var(--border-radius);
            box-shadow: 0 4px 8px rgba(0,0,0, calc(var(--shadow-intensity) * 0.01));
        }
        
        .ranking-row:last-child {
            border-bottom: none;
        }
        
        .ranking-row:nth-child(even) {
            animation-delay: 0.1s;
        }
        
        .ranking-row:nth-child(odd) {
            animation-delay: 0.05s;
        }
        
        .rank {
            font-size: var(--rank-font-size);
            font-weight: 800;
            width: calc(var(--rank-font-size) + 13px);
            height: calc(var(--rank-font-size) + 13px);
            border-radius: 50%;
            display: var(--show-rank);
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, rgba(57,255,20,0.2), rgba(75,123,255,0.2));
            border: 2px solid rgba(255,255,255,0.3);
            color: white;
            text-align: var(--rank-align);
            transform: translate(var(--rank-offset-x), var(--rank-offset-y));
        }
        
        .rank.first { 
            background: linear-gradient(135deg, #FFD700, #FFA500);
            color: #000;
            border-color: #FFD700;
            box-shadow: 0 0 20px rgba(255,215,0, calc(var(--glow-enabled) * 0.5));
            animation: glowPulse 2s ease-in-out infinite;
            animation-play-state: calc(var(--glow-enabled) == 1 ? running : paused);
        }
        
        .rank.second { 
            background: linear-gradient(135deg, #C0C0C0, #A8A8A8);
            color: #000;
            border-color: #C0C0C0;
            box-shadow: 0 0 15px rgba(192,192,192, calc(var(--glow-enabled) * 0.4));
        }
        
        .rank.third { 
            background: linear-gradient(135deg, #CD7F32, #B8860B);
            color: #000;
            border-color: #CD7F32;
            box-shadow: 0 0 15px rgba(205,127,50, calc(var(--glow-enabled) * 0.4));
        }
        
        .participant-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: var(--name-column-width);
        }
        
        .name {
            font-weight: 700;
            font-size: var(--name-font-size);
            color: white;
            margin-bottom: 2px;
            text-shadow: 0 1px 2px rgba(0,0,0,0.5);
            text-align: var(--name-align);
            transform: translate(var(--name-offset-x), var(--name-offset-y));
            display: var(--show-name);
        }
        
        .club {
            font-size: var(--country-font-size);
            color: rgba(173,38,255,0.8);
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            text-align: var(--club-align);
            transform: translate(var(--club-offset-x), var(--club-offset-y));
            display: var(--show-club);
        }
        
        .country {
            font-size: var(--country-font-size);
            color: rgba(57,255,20,0.8);
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            text-align: var(--country-align);
            transform: translate(var(--country-offset-x), var(--country-offset-y));
            display: var(--show-country);
        }
        
        .score {
            font-size: var(--score-font-size);
            font-weight: 800;
            color: var(--lime);
            background: rgba(57,255,20,0.1);
            padding: 8px 12px;
            border-radius: var(--border-radius);
            border: 1px solid rgba(57,255,20,0.3);
            width: var(--result-column-width);
            text-align: var(--score-align);
            text-shadow: 0 0 10px rgba(57,255,20,0.5);
            transform: translate(var(--score-offset-x), var(--score-offset-y));
            display: var(--show-score);
        }
        }
        
        .rank-country {
            font-size: 12px;
            color: rgba(255,255,255,0.7);
        }
        
        .rank-score {
            font-size: 18px;
            font-weight: 700;
            color: var(--lime);
        }
        
        /* Animations */
        @keyframes slideInRow {
            from {
                opacity: 0;
                transform: translateX(50px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @keyframes glowPulse {
            0%, 100% { 
                box-shadow: 0 0 20px rgba(255,215,0,0.4);
            }
            50% { 
                box-shadow: 0 0 30px rgba(255,215,0,0.6);
            }
        }
        
        @keyframes flipIn {
            0% {
                transform: perspective(400px) rotateY(-90deg);
                opacity: 0;
            }
            100% {
                transform: perspective(400px) rotateY(0deg);
                opacity: 1;
            }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes zoomIn {
            0% {
                transform: scale(0.3);
                opacity: 0;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }
        
        /* Animation Classes */
        .anim-slide { transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1); }
        .anim-fade { animation: fadeIn 0.5s ease forwards; }
        .anim-flip { animation: flipIn 0.6s ease forwards; }
        .anim-zoom { animation: zoomIn 0.4s ease forwards; }
        
        /* Responsive Scaling */
        @media (max-width: 1920px) {
            .lower-third { font-size: 0.9em; }
            .rankings-table { font-size: 0.9em; }
        }
        
        @media (max-width: 1366px) {
            .lower-third { font-size: 0.8em; }
            .rankings-table { font-size: 0.8em; }
        }
        
        @media (max-width: 1024px) {
            .lower-third { font-size: 0.7em; }
            .rankings-table { font-size: 0.7em; }
        }
        
        /* Custom scaling */
        .scale-50 { transform: scale(0.5); transform-origin: top left; }
        .scale-75 { transform: scale(0.75); transform-origin: top left; }
        .scale-125 { transform: scale(1.25); transform-origin: top left; }
        .scale-150 { transform: scale(1.5); transform-origin: top left; }
        
        /* Top 3 Podium */
        .podium-container {
            position: absolute;
            bottom: 40px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 20px;
            align-items: end;
            width: var(--podium-width);
        }
        
        .podium-step {
            background: linear-gradient(180deg, rgba(11,18,32,0.95), rgba(11,18,32,0.85));
            backdrop-filter: blur(10px);
            border-radius: 16px;
            border: 2px solid rgba(255,255,255,0.1);
            padding: 20px;
            text-align: center;
            color: white;
            min-width: 180px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.5);
        }
        
        .podium-step.first { height: 200px; order: 2; }
        .podium-step.second { height: 160px; order: 1; }
        .podium-step.third { height: 120px; order: 3; }
        
        .podium-number {
            font-size: 36px;
            font-weight: 700;
            margin-bottom: 8px;
        }
        
        .podium-number.first { color: #FFD700; }
        .podium-number.second { color: #C0C0C0; }
        .podium-number.third { color: #CD7F32; }
        
        .podium-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .podium-score {
            font-size: 20px;
            font-weight: 700;
            color: var(--lime);
        }
    </style>
</head>
<body>
    <div class="overlay-container" id="overlayContainer">
        <!-- Lower Third -->
        <div class="lower-third anim-slide" id="lowerThird">
            <div class="participant-name" id="participantName">John Smith</div>
            <div class="participant-info">
                <div class="country-flag" id="countryFlag"></div>
                <div class="bib-number" id="bibNumber">#42</div>
                <div style="flex: 1;">
                    <div style="font-size: 14px; color: rgba(255,255,255,0.7);">Snowboard Slopestyle - Finals</div>
                    <div style="font-size: 12px; color: rgba(255,255,255,0.5);">Run 2 of 3</div>
                </div>
            </div>
            <div class="scores-container">
                <div class="score-item">
                    <div class="score-label">CURRENT</div>
                    <div class="score-value current-score" id="currentScore">87.50</div>
                </div>
                <div class="score-item">
                    <div class="score-label">BEST</div>
                    <div class="score-value" id="bestScore">89.25</div>
                </div>
                <div class="score-item">
                    <div class="score-label">RANK</div>
                    <div class="score-value" id="currentRank">2nd</div>
                </div>
            </div>
        </div>
        
        <!-- Rankings Table -->
        <div class="rankings-table anim-slide" id="rankingsTable" style="display: none;">
            <div class="table-header">LIVE RANKINGS</div>
            <div id="rankingRows">
                <!-- Dynamic ranking rows will be inserted here -->
            </div>
        </div>
        
        <!-- Podium (Top 3) -->
        <div class="podium-container" id="podiumContainer" style="display: none;">
            <div class="podium-step second">
                <div class="podium-number second">2</div>
                <div class="podium-name">Jane Doe</div>
                <div class="podium-score">85.75</div>
            </div>
            <div class="podium-step first">
                <div class="podium-number first">1</div>
                <div class="podium-name">John Smith</div>
                <div class="podium-score">89.25</div>
            </div>
            <div class="podium-step third">
                <div class="podium-number third">3</div>
                <div class="podium-name">Bob Wilson</div>
                <div class="podium-score">82.50</div>
            </div>
        </div>
       
    </div>

    <script>
        // Global overlay state
        let overlayState = {
            type: 'lower-third',
            position: 'bottom-left',
            animation: 'slide',
            scale: 100,
            visible: true,
            eventId: <?= isset($_GET['event_id']) ? (int)$_GET['event_id'] : 'null' ?>,
            currentParticipant: null
        };
        
        // Listen for messages from parent control panel
        window.addEventListener('message', function(event) {
            if (event.origin !== window.location.origin) return;
            
            const command = event.data;
            handleCommand(command);
        });
        
        function handleCommand(command) {
            switch(command.action) {
                case 'setType':
                    setOverlayType(command.type);
                    break;
                case 'setPosition':
                    setPosition(command.position);
                    break;
                case 'setAnimation':
                    setAnimation(command.animation);
                    break;
                case 'setScale':
                    setScale(command.scale);
                    break;
                case 'show':
                    showOverlay();
                    break;
                case 'hide':
                    hideOverlay();
                    break;
                case 'updateData':
                    updateData(command.data);
                    break;
                case 'setParticipant':
                    setCurrentParticipant(command.participantId);
                    break;
            }
        }
        
        function setOverlayType(type) {
            overlayState.type = type;
            
            // First hide all overlays
            hideOverlay();
            
            // Hide all overlay elements
            document.getElementById('lowerThird').style.display = 'none';
            document.getElementById('rankingsTable').style.display = 'none';
            document.getElementById('podiumContainer').style.display = 'none';
            
            // Show selected overlay after a short delay to ensure smooth transition
            setTimeout(() => {
                switch(type) {
                    case 'lower-third':
                        document.getElementById('lowerThird').style.display = 'block';
                        break;
                    case 'rankings':
                    case 'top5':
                        document.getElementById('rankingsTable').style.display = 'block';
                        // Load data after showing the element
                        setTimeout(() => {
                            updateRankingsTable(type === 'top5' ? 5 : 10);
                        }, 100);
                        break;
                    case 'top3':
                        document.getElementById('podiumContainer').style.display = 'flex';
                        // Load podium data
                        setTimeout(() => {
                            updatePodiumData();
                        }, 100);
                        break;
                    case 'none':
                        // All hidden
                        return;
                }
                
                // Show overlay after data is loaded
                setTimeout(() => {
                    showOverlay();
                }, 200);
            }, 300);
        }
        
        function setPosition(position) {
            overlayState.position = position;
            const lowerThird = document.getElementById('lowerThird');
            
            // Remove all position classes
            lowerThird.className = lowerThird.className.replace(/position-\S+/g, '');
            
            // Add new position class
            lowerThird.classList.add('position-' + position);
        }
        
        function setAnimation(animation) {
            overlayState.animation = animation;
            const elements = document.querySelectorAll('.lower-third, .rankings-table');
            
            elements.forEach(el => {
                el.className = el.className.replace(/anim-\S+/g, '');
                el.classList.add('anim-' + animation);
            });
        }
        
        function setScale(scale) {
            overlayState.scale = scale;
            const container = document.getElementById('overlayContainer');
            
            if (scale === 100) {
                container.style.transform = '';
            } else {
                container.style.transform = `scale(${scale / 100})`;
                container.style.transformOrigin = 'top left';
            }
        }
        
        function showOverlay() {
            overlayState.visible = true;
            const activeElements = getActiveElements();
            
            activeElements.forEach(el => {
                el.classList.add('show');
            });
        }
        
        function hideOverlay() {
            overlayState.visible = false;
            const activeElements = getActiveElements();
            
            activeElements.forEach(el => {
                el.classList.remove('show');
            });
        }
        
        function getActiveElements() {
            const elements = [];
            switch(overlayState.type) {
                case 'lower-third':
                    elements.push(document.getElementById('lowerThird'));
                    break;
                case 'rankings':
                case 'top5':
                    elements.push(document.getElementById('rankingsTable'));
                    break;
                case 'top3':
                    elements.push(document.getElementById('podiumContainer'));
                    break;
            }
            return elements;
        }
        
        // Helper function to get URL parameters
        function getUrlParameter(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        function parseTableBodyToParticipants(tableBodyHtml) {
            // Create a temporary element to parse the HTML
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = tableBodyHtml;
            
            const participants = [];
            
            // Try to find participant rows - they might be .group-participant-row or just regular tr elements
            let rows = tempDiv.querySelectorAll('tr.group-participant-row');
            if (rows.length === 0) {
                // If no group-participant-row, try regular tr elements with data-approved_at
                rows = tempDiv.querySelectorAll('tr[data-approved_at]');
            }
            if (rows.length === 0) {
                // Last resort: all tr elements
                rows = tempDiv.querySelectorAll('tr');
            }
            
            console.log('Found rows:', rows.length); // Debug log
            
            rows.forEach((row, index) => {
                const cells = row.querySelectorAll('td');
                console.log('Row', index, 'has', cells.length, 'cells'); // Debug log
                
                if (cells.length >= 5) {
                    // Extract data from table cells - adjust for single category format
                    const rankCell = cells[0].querySelector('.group-rank') || cells[0];
                    const bibCell = cells[1].querySelector('.badge') || cells[1];
                    const nameCell = cells[2].querySelector('strong') || cells[2];
                    const clubCell = cells[3].querySelector('.badge') || cells[3];
                    const scoreCell = cells[cells.length - 1]; // Last cell is usually the best score
                    
                    const rankText = rankCell ? rankCell.textContent.trim() : (index + 1).toString();
                    const rank = parseInt(rankText) || index + 1;
                    const bib = bibCell ? bibCell.textContent.trim() : '';
                    const name = nameCell ? nameCell.textContent.trim() : 'Unknown';
                    const club = clubCell ? clubCell.textContent.trim() : '';
                    const scoreText = scoreCell ? scoreCell.textContent.trim() : '0.00';
                    const score = parseFloat(scoreText) || 0.00;
                    
                    console.log('Parsed participant:', { rank, bib, name, club, score }); // Debug log
                    
                    participants.push({
                        rank: rank,
                        bib: bib,
                        name: name,
                        club: club,
                        score: score.toFixed(2)
                    });
                }
            });
            
            console.log('Total participants parsed:', participants.length); // Debug log
            return participants;
        }
        
        function updatePodiumData() {
            // Get event ID from URL parameter
            const eventId = getUrlParameter('event_id') || '3';
            
            // Use the selected config ID or default API call
            let selectedConfigId;
            try {
                selectedConfigId = parent.window.selectedConfigId;
            } catch (e) {
                // Can't access parent window
            }
            
            let apiUrl;
            if (selectedConfigId) {
                apiUrl = `../api/summary_table_api.php?config_id=${selectedConfigId}&format=json&limit=3&tv_overlay=1`;
            } else {
                apiUrl = `../api/summary_table_api.php?event_id=${eventId}&format=json&limit=3&sort=OverallAverage&sort_direction=desc&tv_overlay=1`;
            }
            
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.participants && data.participants.length > 0) {
                        const participants = data.participants.slice(0, 3);
                        const podiumSteps = document.querySelectorAll('.podium-step');
                        
                        participants.forEach((participant, index) => {
                            if (podiumSteps[index]) {
                                const step = podiumSteps[index];
                                step.querySelector('.podium-name').textContent = participant.name;
                                step.querySelector('.podium-score').textContent = participant.formatted_score;
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading podium data:', error);
                });
        }
        
        function updateRankingsTable(limit = 10, configId = null) {
            // Get event ID from URL parameter
            const eventId = getUrlParameter('event_id') || '3'; // Default for testing
            
            // Use the provided configId or try to get from parent window
            let selectedConfigId = configId;
            if (!selectedConfigId) {
                try {
                    selectedConfigId = parent.window.selectedConfigId;
                } catch (e) {
                    // Can't access parent window
                }
            }
            
            // Build URL to call YOUR StyleScore API directly with TV overlay parameter
            let apiUrl;
            if (selectedConfigId) {
                apiUrl = `../api/summary_table_api.php?config_id=${selectedConfigId}&format=json&limit=${limit}&tv_overlay=1`;
            } else {
                apiUrl = `../api/summary_table_api.php?event_id=${eventId}&format=json&limit=${limit}&sort=OverallAverage&sort_direction=desc&tv_overlay=1`;
            }
            
            console.log('Calling YOUR API directly:', apiUrl);
            
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    console.log('YOUR API Response:', data); // Debug log
                    const container = document.getElementById('rankingRows');
                    container.innerHTML = '';
                    
                    if (data.success && data.participants && data.participants.length > 0) {
                        // Use clean participant data from your API
                        const participants = data.participants;
                        
                        participants.slice(0, limit).forEach((participant, index) => {
                            setTimeout(() => {
                                const row = document.createElement('div');
                                row.className = 'ranking-row';
                                
                                const rank = participant.rank || index + 1;
                                let rankClass = '';
                                if (rank === 1) rankClass = 'first';
                                else if (rank === 2) rankClass = 'second';
                                else if (rank === 3) rankClass = 'third';
                                
                                row.innerHTML = `
                                    <div class="ranking-cell rank-cell">
                                        <div class="rank ${rankClass}">${rank}</div>
                                    </div>
                                    <div class="ranking-cell bib-cell">
                                        <div class="bib">${participant.bib || index + 1}</div>
                                    </div>
                                    <div class="ranking-cell name-cell">
                                        <div class="participant-info">
                                            <div class="name">${participant.name}</div>
                                            <div class="country">${participant.club || 'Club'}</div>
                                        </div>
                                    </div>
                                    <div class="ranking-cell judges-cell">
                                        <div class="judge-scores">
                                            ${(participant.judge_scores || ['8.5', '8.3', '8.7']).map(score => 
                                                `<span class="judge-score">${score}</span>`
                                            ).join('')}
                                        </div>
                                    </div>
                                    <div class="ranking-cell startlist-cell">
                                        <div class="start-order">${participant.start_order || Math.floor(Math.random() * 20) + 1}</div>
                                    </div>
                                    <div class="ranking-cell score-cell">
                                        <div class="score">${participant.formatted_score}</div>
                                    </div>
                                `;
                                
                                container.appendChild(row);
                                
                                // Add animation
                                setTimeout(() => {
                                    row.style.opacity = '1';
                                    row.style.transform = 'translateX(0)';
                                }, 50);
                            }, index * 100);
                        });
                    } else if (data.success && data.table_body) {
                        // Fallback: parse HTML if clean data not available
                        console.log('Falling back to HTML parsing');
                        const participants = parseTableBodyToParticipants(data.table_body);
                        
                        participants.slice(0, limit).forEach((participant, index) => {
                            setTimeout(() => {
                                const row = document.createElement('div');
                                row.className = 'ranking-row';
                                
                                const rank = participant.rank || index + 1;
                                let rankClass = '';
                                if (rank === 1) rankClass = 'first';
                                else if (rank === 2) rankClass = 'second';
                                else if (rank === 3) rankClass = 'third';
                                
                                row.innerHTML = `
                                    <div class="ranking-cell rank-cell">
                                        <div class="rank ${rankClass}">${rank}</div>
                                    </div>
                                    <div class="ranking-cell bib-cell">
                                        <div class="bib">${participant.bib || index + 1}</div>
                                    </div>
                                    <div class="ranking-cell name-cell">
                                        <div class="participant-info">
                                            <div class="name">${participant.name}</div>
                                            <div class="country">${participant.club || 'Club'}</div>
                                        </div>
                                    </div>
                                    <div class="ranking-cell judges-cell">
                                        <div class="judge-scores">
                                            <span class="judge-score">8.${Math.floor(Math.random() * 9)}</span>
                                            <span class="judge-score">8.${Math.floor(Math.random() * 9)}</span>
                                            <span class="judge-score">8.${Math.floor(Math.random() * 9)}</span>
                                        </div>
                                    </div>
                                    <div class="ranking-cell startlist-cell">
                                        <div class="start-order">${Math.floor(Math.random() * 20) + 1}</div>
                                    </div>
                                    <div class="ranking-cell score-cell">
                                        <div class="score">${participant.score}</div>
                                    </div>
                                `;
                                
                                container.appendChild(row);
                                
                                // Add animation
                                setTimeout(() => {
                                    row.style.opacity = '1';
                                    row.style.transform = 'translateX(0)';
                                }, 50);
                            }, index * 100);
                        });
                    } else {
                        const message = data.message || 'No ranking data available';
                        container.innerHTML = `
                            <div class="ranking-row">
                                <div class="ranking-cell rank-cell">
                                    <div class="rank">-</div>
                                </div>
                                <div class="ranking-cell bib-cell">
                                    <div class="bib">-</div>
                                </div>
                                <div class="ranking-cell name-cell">
                                    <div class="participant-info">
                                        <div class="name">${message}</div>
                                        <div class="country">Check configuration</div>
                                    </div>
                                </div>
                                <div class="ranking-cell judges-cell">
                                    <div class="judge-scores">
                                        <span class="judge-score">-</span>
                                    </div>
                                </div>
                                <div class="ranking-cell startlist-cell">
                                    <div class="start-order">-</div>
                                </div>
                                <div class="ranking-cell score-cell">
                                    <div class="score">0.00</div>
                                </div>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error loading rankings:', error);
                    const container = document.getElementById('rankingRows');
                    container.innerHTML = `
                        <div class="ranking-row">
                            <div class="ranking-cell rank-cell">
                                <div class="rank">!</div>
                            </div>
                            <div class="ranking-cell bib-cell">
                                <div class="bib">!</div>
                            </div>
                            <div class="ranking-cell name-cell">
                                <div class="participant-info">
                                    <div class="name">API Connection Error</div>
                                    <div class="country">${error.message}</div>
                                </div>
                            </div>
                            <div class="ranking-cell judges-cell">
                                <div class="judge-scores">
                                    <span class="judge-score">!</span>
                                </div>
                            </div>
                            <div class="ranking-cell startlist-cell">
                                <div class="start-order">!</div>
                            </div>
                            <div class="ranking-cell score-cell">
                                <div class="score">--</div>
                            </div>
                        </div>
                    `;
                });
        }
        
        function setCurrentParticipant(participantId) {
            overlayState.currentParticipant = participantId;
            // Fetch participant data and update lower third
            updateParticipantData(participantId);
        }
        
        function updateParticipantData(participantId) {
            // In real implementation, fetch from API
            // For demo, use sample data
            const sampleData = {
                name: 'Sarah Johnson',
                country: 'USA',
                bib: '#15',
                currentScore: 92.75,
                bestScore: 92.75,
                rank: '1st'
            };
            
            document.getElementById('participantName').textContent = sampleData.name;
            document.getElementById('bibNumber').textContent = sampleData.bib;
            document.getElementById('currentScore').textContent = sampleData.currentScore;
            document.getElementById('bestScore').textContent = sampleData.bestScore;
            document.getElementById('currentRank').textContent = sampleData.rank;
        }
        
        // Auto-refresh data every 5 seconds
        setInterval(() => {
            if (overlayState.visible && overlayState.eventId) {
                // Refresh data based on current overlay type
                switch(overlayState.type) {
                    case 'rankings':
                    case 'top5':
                        updateRankingsTable(overlayState.type === 'top5' ? 5 : 10);
                        break;
                    case 'lower-third':
                        if (overlayState.currentParticipant) {
                            updateParticipantData(overlayState.currentParticipant);
                        }
                        break;
                }
            }
        }, 5000);
        
        // Initialize
        setTimeout(() => {
            setOverlayType('lower-third');
            setPosition('bottom-left');
            showOverlay();
        }, 500);
        
        // Update overlay styling with CSS variables
        function updateOverlayStyling(styling) {
            const root = document.documentElement;
            
            // Update CSS variables
            if (styling.rankFontSize) {
                root.style.setProperty('--rank-font-size', styling.rankFontSize + 'px');
            }
            if (styling.nameFontSize) {
                root.style.setProperty('--name-font-size', styling.nameFontSize + 'px');
            }
            if (styling.scoreFontSize) {
                root.style.setProperty('--score-font-size', styling.scoreFontSize + 'px');
            }
            if (styling.countryFontSize) {
                root.style.setProperty('--country-font-size', styling.countryFontSize + 'px');
            }
            if (styling.rowHeight) {
                root.style.setProperty('--row-height', styling.rowHeight + 'px');
            }
            if (styling.rowSpacing) {
                root.style.setProperty('--row-spacing', styling.rowSpacing + 'px');
            }
            if (styling.rankingPadding) {
                root.style.setProperty('--ranking-padding', styling.rankingPadding + 'px');
            }
            if (styling.borderRadius) {
                root.style.setProperty('--border-radius', styling.borderRadius + 'px');
            }
            if (styling.bgOpacity) {
                root.style.setProperty('--bg-opacity', styling.bgOpacity / 100);
            }
            if (styling.shadowIntensity) {
                root.style.setProperty('--shadow-intensity', styling.shadowIntensity);
            }
            if (styling.enableGlow !== undefined) {
                root.style.setProperty('--glow-enabled', styling.enableGlow ? 1 : 0);
            }
            
            // Width Controls
            if (styling.lowerThirdWidth) {
                root.style.setProperty('--lowerthird-width', styling.lowerThirdWidth + 'px');
            }
            if (styling.rankingsWidth) {
                root.style.setProperty('--rankings-width', styling.rankingsWidth + 'px');
            }
            if (styling.podiumWidth) {
                root.style.setProperty('--podium-width', styling.podiumWidth === 'auto' ? 'auto' : styling.podiumWidth + 'px');
            }
            if (styling.resultColumnWidth) {
                root.style.setProperty('--result-column-width', styling.resultColumnWidth + 'px');
            }
            if (styling.nameColumnWidth) {
                root.style.setProperty('--name-column-width', styling.nameColumnWidth === 'auto' ? 'auto' : styling.nameColumnWidth + 'px');
            }
            if (styling.clubColumnWidth) {
                root.style.setProperty('--club-column-width', styling.clubColumnWidth === 'auto' ? 'auto' : styling.clubColumnWidth + 'px');
            }
            if (styling.rankColumnWidth) {
                root.style.setProperty('--rank-column-width', styling.rankColumnWidth + 'px');
            }
            if (styling.bibColumnWidth) {
                root.style.setProperty('--bib-column-width', styling.bibColumnWidth + 'px');
            }
            if (styling.judgesColumnWidth) {
                root.style.setProperty('--judges-column-width', styling.judgesColumnWidth + 'px');
            }
            if (styling.startlistColumnWidth) {
                root.style.setProperty('--startlist-column-width', styling.startlistColumnWidth + 'px');
            }
            
            // Panel Position Controls
            if (styling.panelOffsetXOffscreen !== undefined) {
                root.style.setProperty('--panel-offset-x-offscreen', styling.panelOffsetXOffscreen + '%');
            }
            if (styling.panelOffsetYOffscreen !== undefined) {
                root.style.setProperty('--panel-offset-y-offscreen', styling.panelOffsetYOffscreen + 'px');
            }
            if (styling.panelOffsetXOnscreen !== undefined) {
                root.style.setProperty('--panel-offset-x-onscreen', styling.panelOffsetXOnscreen + 'px');
            }
            if (styling.panelOffsetYOnscreen !== undefined) {
                root.style.setProperty('--panel-offset-y-onscreen', styling.panelOffsetYOnscreen + 'px');
            }
            
            // Update column controls for name
            if (styling.nameAlign) {
                root.style.setProperty('--name-align', styling.nameAlign);
            }
            if (styling.nameOffsetX !== undefined) {
                root.style.setProperty('--name-offset-x', styling.nameOffsetX + 'px');
            }
            if (styling.nameOffsetY !== undefined) {
                root.style.setProperty('--name-offset-y', styling.nameOffsetY + 'px');
            }
            if (styling.showName !== undefined) {
                root.style.setProperty('--show-name', styling.showName ? 'block' : 'none');
            }
            
            // Update column controls for club
            if (styling.clubAlign) {
                root.style.setProperty('--club-align', styling.clubAlign);
            }
            if (styling.clubOffsetX !== undefined) {
                root.style.setProperty('--club-offset-x', styling.clubOffsetX + 'px');
            }
            if (styling.clubOffsetY !== undefined) {
                root.style.setProperty('--club-offset-y', styling.clubOffsetY + 'px');
            }
            if (styling.showClub !== undefined) {
                root.style.setProperty('--show-club', styling.showClub ? 'block' : 'none');
            }
            
            // Update column controls for country
            if (styling.countryAlign) {
                root.style.setProperty('--country-align', styling.countryAlign);
            }
            if (styling.countryOffsetX !== undefined) {
                root.style.setProperty('--country-offset-x', styling.countryOffsetX + 'px');
            }
            if (styling.countryOffsetY !== undefined) {
                root.style.setProperty('--country-offset-y', styling.countryOffsetY + 'px');
            }
            if (styling.showCountry !== undefined) {
                root.style.setProperty('--show-country', styling.showCountry ? 'block' : 'none');
            }
            
            // Update column controls for rank
            if (styling.rankAlign) {
                root.style.setProperty('--rank-align', styling.rankAlign);
            }
            if (styling.rankOffsetX !== undefined) {
                root.style.setProperty('--rank-offset-x', styling.rankOffsetX + 'px');
            }
            if (styling.rankOffsetY !== undefined) {
                root.style.setProperty('--rank-offset-y', styling.rankOffsetY + 'px');
            }
            if (styling.showRank !== undefined) {
                root.style.setProperty('--show-rank', styling.showRank ? 'flex' : 'none');
            }
            
            // Update column controls for score
            if (styling.scoreAlign) {
                root.style.setProperty('--score-align', styling.scoreAlign);
            }
            if (styling.scoreOffsetX !== undefined) {
                root.style.setProperty('--score-offset-x', styling.scoreOffsetX + 'px');
            }
            if (styling.scoreOffsetY !== undefined) {
                root.style.setProperty('--score-offset-y', styling.scoreOffsetY + 'px');
            }
            if (styling.showScore !== undefined) {
                root.style.setProperty('--show-score', styling.showScore ? 'block' : 'none');
            }
            
            // Update column controls for bib
            if (styling.bibAlign) {
                root.style.setProperty('--bib-align', styling.bibAlign);
            }
            if (styling.bibOffsetX !== undefined) {
                root.style.setProperty('--bib-offset-x', styling.bibOffsetX + 'px');
            }
            if (styling.bibOffsetY !== undefined) {
                root.style.setProperty('--bib-offset-y', styling.bibOffsetY + 'px');
            }
            if (styling.showBib !== undefined) {
                root.style.setProperty('--show-bib', styling.showBib ? 'block' : 'none');
            }
            
            // Update column controls for judges
            if (styling.judgesAlign) {
                root.style.setProperty('--judges-align', styling.judgesAlign);
            }
            if (styling.judgesOffsetX !== undefined) {
                root.style.setProperty('--judges-offset-x', styling.judgesOffsetX + 'px');
            }
            if (styling.judgesOffsetY !== undefined) {
                root.style.setProperty('--judges-offset-y', styling.judgesOffsetY + 'px');
            }
            if (styling.showJudges !== undefined) {
                root.style.setProperty('--show-judges', styling.showJudges ? 'flex' : 'none');
            }
            
            // Update column controls for startlist
            if (styling.startlistAlign) {
                root.style.setProperty('--startlist-align', styling.startlistAlign);
            }
            if (styling.startlistOffsetX !== undefined) {
                root.style.setProperty('--startlist-offset-x', styling.startlistOffsetX + 'px');
            }
            if (styling.startlistOffsetY !== undefined) {
                root.style.setProperty('--startlist-offset-y', styling.startlistOffsetY + 'px');
            }
            if (styling.showStartlist !== undefined) {
                root.style.setProperty('--show-startlist', styling.showStartlist ? 'flex' : 'none');
            }
            
            console.log('Styling updated:', styling);
        }
        
        // Listen for messages from parent window
        window.addEventListener('message', function(event) {
            if (event.origin !== window.location.origin) return;
            
            const command = event.data;
            if (!command.action) return;
            
            switch(command.action) {
                case 'setType':
                    setOverlayType(command.type);
                    break;
                case 'setPosition':
                    setPosition(command.position);
                    break;
                case 'setAnimation':
                    setAnimation(command.animation);
                    break;
                case 'setScale':
                    setScale(command.scale);
                    break;
                case 'show':
                    showOverlay();
                    break;
                case 'hide':
                    hideOverlay();
                    break;
                case 'updateParticipant':
                    updateParticipantData(command.participant);
                    break;
                case 'loadConfiguration':
                    updateRankingsTable(10, command.configId);
                    break;
                case 'updateRankings':
                    updateRankingsTable(10, command.configId);
                    break;
                case 'updateStyling':
                    updateOverlayStyling(command.styling);
                    break;
            }
        });
    </script>
</body>
</html>
