<?php
/**
 * Test Heat Bracket API
 * Quick test to verify the bracket generation API works
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Heat Bracket API</title>
      <?php include_once 'includes/stylesheets.php'; ?>  <style>
        body {
            padding: 20px;
            background: #f8f9fa;
        }
        .test-container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .test-controls {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 6px;
        }
        .bracket-preview {
            min-height: 400px;
            border: 2px dashed #dee2e6;
            border-radius: 6px;
            padding: 20px;
        }
        .loading {
            text-align: center;
            padding: 60px;
            color: #6c757d;
        }
        /* Include bracket styles from score.php */
        .bracket-flow-container {
            display: flex;
            gap: 40px;
            position: relative;
            padding: 20px;
            overflow-x: auto;
        }
        .bracket-column {
            display: flex;
            flex-direction: column;
            gap: 15px;
            min-width: 180px;
        }
        .bracket-column-header {
            font-weight: 600;
            font-size: 11px;
            color: #6c757d;
            text-align: center;
            padding: 8px 0;
            border-bottom: 2px solid #dee2e6;
            margin-bottom: 10px;
        }
        .bracket-heat-compact {
            position: relative;
        }
        .bracket-heat-card-mini {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            padding: 10px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .bracket-heat-card-mini:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #0d6efd;
        }
        .bracket-heat-card-mini.active {
            border-color: #0d6efd;
            background: linear-gradient(135deg, #e7f3ff 0%, #ffffff 100%);
        }
        .bracket-heat-card-mini.completed {
            border-color: #28a745;
            opacity: 0.7;
        }
        .bracket-heat-header-mini {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        .bracket-heat-number-mini {
            background: #0d6efd;
            color: white;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 13px;
        }
        .bracket-heat-card-mini.completed .bracket-heat-number-mini {
            background: #28a745;
        }
        .bracket-heat-status-icon {
            font-size: 16px;
        }
        .bracket-heat-name-mini {
            font-weight: 600;
            font-size: 13px;
            margin-bottom: 6px;
            color: #212529;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .bracket-heat-info-mini {
            display: flex;
            gap: 12px;
            font-size: 11px;
            color: #6c757d;
        }
        .bracket-heat-info-mini i {
            margin-right: 4px;
        }
        .bracket-heat-live-badge {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #dc3545;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 4px;
            box-shadow: 0 2px 8px rgba(220, 53, 69, 0.4);
        }
        .bracket-connections {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 0;
        }
        .connection-path {
            fill: none;
            stroke: #adb5bd;
            stroke-width: 2;
        }
        
        /* Aropupu bracket custom styles */
        #aropupu-bracket {
            min-height: 500px;
            background: white;
            padding: 20px;
        }
        
        /* Angular tournament bracket styles */
        #angular-bracket {
            min-height: 500px;
            background: white;
            padding: 20px;
        }
        .tournament-bracket {
            display: flex;
            flex-direction: row;
            gap: 20px;
        }
        .tournament-round {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
        }
        .tournament-match {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            margin: 10px 0;
            padding: 10px;
            min-width: 200px;
        }
        .tournament-participant {
            padding: 8px;
            border-bottom: 1px solid #f0f0f0;
        }
        .tournament-participant:last-child {
            border-bottom: none;
        }
        .tournament-participant.winner {
            background: #d4edda;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="test-container">
        <h2 class="mb-4">
            <i class="fas fa-vial me-2"></i>
            Heat Bracket API Test
        </h2>

        <div class="test-controls">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Event ID</label>
                    <input type="number" id="eventId" class="form-control" value="6" min="1">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Bracket Style</label>
                    <select id="bracketStyle" class="form-select">
                        <option value="custom-compact">1. Custom Compact (Judge)</option>
                        <option value="custom-full">2. Custom Full (Admin)</option>
                        <option value="aropupu">3. Aropupu SVG Bracket</option>
                        <option value="angular-tournament">4. Angular Tournament Bracket</option>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button class="btn btn-primary w-100" onclick="loadBracket()">
                        <i class="fas fa-sync-alt me-2"></i>Load Bracket
                    </button>
                </div>
            </div>
        </div>

        <div class="bracket-preview" id="bracketPreview">
            <div class="loading">
                <i class="fas fa-info-circle fa-2x mb-3"></i>
                <p>Click "Load Bracket" to test the API</p>
            </div>
        </div>

        <div class="mt-4">
            <h5>API Response Log</h5>
            <pre id="responseLog" class="bg-light p-3 rounded" style="max-height: 300px; overflow-y: auto; font-size: 12px;"></pre>
        </div>
    </div>

    <!-- jQuery and jQuery Bracket Library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/js/jquery-bracket/jquery.bracket.min.js"></script>
    
    <script>
        async function loadBracket() {
            const eventId = document.getElementById('eventId').value;
            const bracketStyle = document.getElementById('bracketStyle').value;
            const preview = document.getElementById('bracketPreview');
            const log = document.getElementById('responseLog');

            if (!eventId) {
                alert('Please enter an Event ID');
                return;
            }

            preview.innerHTML = '<div class="loading"><div class="spinner-border text-primary" role="status"></div><p class="mt-3">Loading bracket data...</p></div>';
            log.textContent = 'Fetching data...\n';

            try {
                // Determine API call based on bracket style
                let url, compact;
                
                if (bracketStyle === 'custom-compact') {
                    compact = '1';
                    url = `api/heat_bracket_view_api.php?event_id=${eventId}&compact=${compact}`;
                } else if (bracketStyle === 'custom-full') {
                    compact = '0';
                    url = `api/heat_bracket_view_api.php?event_id=${eventId}&compact=${compact}`;
                } else {
                    // For Aropupu and Angular, get raw data
                    url = `api/heat_bracket_data_api.php?event_id=${eventId}`;
                }
                
                log.textContent += `GET ${url}\n`;

                const response = await fetch(url);
                const data = await response.json();

                log.textContent += `\nResponse Status: ${response.status}\n`;
                log.textContent += `Response Data:\n${JSON.stringify(data, null, 2)}`;

                if (!data.success) {
                    preview.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Error:</strong> ${data.error || 'Unknown error'}
                        </div>
                    `;
                    return;
                }

                // Render based on selected style
                if (bracketStyle === 'custom-compact' || bracketStyle === 'custom-full') {
                    renderCustomBracket(data, preview);
                } else if (bracketStyle === 'aropupu') {
                    renderAropupuBracket(data, preview);
                } else if (bracketStyle === 'angular-tournament') {
                    renderAngularBracket(data, preview);
                }

            } catch (error) {
                console.error('Error loading bracket:', error);
                preview.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Error:</strong> ${error.message}
                    </div>
                `;
                log.textContent += `\nError: ${error.message}`;
            }
        }

        function renderCustomBracket(data, preview) {
            if (!data.html) {
                preview.innerHTML = `
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle me-2"></i>
                        No heats configured for this event
                    </div>
                `;
                return;
            }

            // Insert the HTML
            preview.innerHTML = data.html;

            // Draw connections if available
            if (data.connections && data.connections.length > 0) {
                setTimeout(() => {
                    drawConnections(data.connections);
                    
                    // Initialize tooltips
                    const tooltipTriggerList = document.querySelectorAll('.bracket-preview [data-bs-toggle="tooltip"]');
                    tooltipTriggerList.forEach(tooltipTriggerEl => {
                        new bootstrap.Tooltip(tooltipTriggerEl, {
                            html: true,
                            trigger: 'hover',
                            delay: { show: 300, hide: 100 }
                        });
                    });
                }, 100);
            }
        }

        function renderAropupuBracket(data, preview) {
            if (!data.heats || data.heats.length === 0) {
                preview.innerHTML = `
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle me-2"></i>
                        No heats configured for this event
                    </div>
                `;
                return;
            }

            // Create container for jQuery Bracket
            preview.innerHTML = '<div id="jquery-bracket"></div>';

            // Convert heat data to jQuery Bracket format
            const bracketData = convertToJQueryBracketFormat(data.heats);
            
            // Initialize jQuery bracket
            $('#jquery-bracket').bracket({
                init: bracketData,
                teamWidth: 200,
                scoreWidth: 50,
                matchMargin: 40,
                roundMargin: 60
            });
        }

        function convertToJQueryBracketFormat(heats) {
            // Group heats by level
            const levels = {};
            heats.forEach(heat => {
                const level = heat.level || 1;
                if (!levels[level]) levels[level] = [];
                levels[level].push(heat);
            });

            // Build teams array (matchups from first round)
            const teams = [];
            const firstRound = levels[1] || [];
            firstRound.forEach(heat => {
                const matchup = [];
                if (heat.participants && heat.participants.length >= 2) {
                    matchup.push(heat.participants[0].name + ' (#' + heat.participants[0].bib + ')');
                    matchup.push(heat.participants[1].name + ' (#' + heat.participants[1].bib + ')');
                } else if (heat.participants && heat.participants.length === 1) {
                    matchup.push(heat.participants[0].name + ' (#' + heat.participants[0].bib + ')');
                    matchup.push(null); // BYE
                } else {
                    matchup.push(null);
                    matchup.push(null);
                }
                teams.push(matchup);
            });

            // Build results array (scores per round)
            const results = [[]]; // Single elimination bracket
            
            // Sort levels by number
            const sortedLevels = Object.keys(levels).sort((a, b) => parseInt(a) - parseInt(b));
            
            sortedLevels.forEach(level => {
                const round = [];
                levels[level].forEach(heat => {
                    const match = [];
                    if (heat.participants && heat.participants.length >= 2) {
                        match.push(heat.participants[0].best_score || null);
                        match.push(heat.participants[1].best_score || null);
                    } else if (heat.participants && heat.participants.length === 1) {
                        match.push(heat.participants[0].best_score || null);
                        match.push(null);
                    } else {
                        match.push(null);
                        match.push(null);
                    }
                    round.push(match);
                });
                results[0].push(round);
            });

            return {
                teams: teams,
                results: results
            };
        }

        function renderAngularBracket(data, preview) {
            if (!data.heats || data.heats.length === 0) {
                preview.innerHTML = `
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle me-2"></i>
                        No heats configured for this event
                    </div>
                `;
                return;
            }

            // Group heats by level (round)
            const rounds = {};
            data.heats.forEach(heat => {
                const level = heat.level || 1;
                if (!rounds[level]) rounds[level] = [];
                rounds[level].push(heat);
            });

            // Build tournament bracket HTML
            let html = '<div class="tournament-bracket">';
            
            Object.keys(rounds).sort().forEach(level => {
                html += `<div class="tournament-round">`;
                html += `<h5 class="text-center mb-3">Round ${level}</h5>`;
                
                rounds[level].forEach(heat => {
                    html += `<div class="tournament-match">`;
                    html += `<div class="text-center mb-2"><strong>${heat.heat_name}</strong></div>`;
                    
                    if (heat.participants && heat.participants.length > 0) {
                        heat.participants.forEach((p, index) => {
                            const isWinner = index === 0; // First participant is winner
                            html += `
                                <div class="tournament-participant ${isWinner ? 'winner' : ''}">
                                    <div class="d-flex justify-content-between">
                                        <span>${p.name}</span>
                                        <span class="badge bg-primary">${p.best_score || '-'}</span>
                                    </div>
                                </div>
                            `;
                        });
                    } else {
                        html += '<div class="tournament-participant text-muted">TBD</div>';
                        html += '<div class="tournament-participant text-muted">TBD</div>';
                    }
                    
                    html += `</div>`;
                });
                
                html += `</div>`;
            });
            
            html += '</div>';
            preview.innerHTML = html;
        }

        function drawConnections(connections) {
            const svg = document.querySelector('.bracket-connections');
            if (!svg) return;

            const container = svg.closest('.bracket-flow-container');
            if (!container) return;

            const containerRect = container.getBoundingClientRect();

            connections.forEach(conn => {
                const fromCard = document.querySelector(`[data-heat-id="${conn.from}"]`);
                const toCard = document.querySelector(`[data-heat-id="${conn.to}"]`);

                if (!fromCard || !toCard) return;

                const fromRect = fromCard.getBoundingClientRect();
                const toRect = toCard.getBoundingClientRect();

                const fromX = fromRect.right - containerRect.left;
                const fromY = fromRect.top + fromRect.height / 2 - containerRect.top;
                const toX = toRect.left - containerRect.left;
                const toY = toRect.top + toRect.height / 2 - containerRect.top;

                const midX = fromX + (toX - fromX) / 2;
                const pathData = `M ${fromX} ${fromY} L ${midX} ${fromY} L ${midX} ${toY} L ${toX} ${toY}`;

                const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                path.setAttribute('d', pathData);
                path.setAttribute('class', 'connection-path');
                path.setAttribute('marker-end', 'url(#arrowhead)');

                svg.appendChild(path);
            });
        }

        function showHeatDetail(heatNumber) {
            alert('Heat detail clicked: ' + heatNumber);
        }
    </script>
</body>
</html>
