{% extends "base.html" %}
{% load static %}

{% block content %}
<div class="container py-5">
    <div class="row align-items-center justify-content-center">
        <!-- Vinyl Player Visual -->
        <div class="col-lg-6 mb-5 mb-lg-0 text-center d-flex justify-content-center">
            <div class="player-container">
                <div id="vinyl" class="vinyl-disk">
                    <div class="vinyl-label" id="vinyl-label">
                        <img src="/assets/pasted-20260130-141153-87077408.jpg" alt="Logo" class="img-fluid rounded-circle" style="width: 100%; height: 100%; object-fit: cover; opacity: 0.9;">
                    </div>
                </div>
                <div class="tonearm" id="tonearm"></div>
            </div>
        </div>

        <!-- Player Controls & Info -->
        <div class="col-lg-6">
            <div class="glass-card p-4 rounded-4 shadow-lg border-neon">
                <div class="d-flex align-items-center mb-3">
                    <img src="/assets/pasted-20260130-141153-87077408.jpg" alt="Logo" height="60" class="me-3 rounded-2 shadow-sm">
                    <div>
                        <h1 class="h2 mb-0 fw-bold" id="current-station-name" style="font-family: 'Righteous', cursive; color: var(--secondary-neon);">Lili Records Radio</h1>
                        <p class="text-secondary mb-0" id="current-track-info">Virtual Broadcast</p>
                    </div>
                </div>

                <!-- Visualizer Waves -->
                <div class="visualizer-container my-4 d-flex align-items-end justify-content-center gap-1" id="visualizer">
                    <div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div>
                    <div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div>
                    <div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div>
                    <div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div><div class="v-bar"></div>
                </div>

                <div class="audio-controls mb-4 p-3 rounded-3 bg-dark bg-opacity-50 border border-secondary">
                    <audio id="audio-player"></audio>
                    <div class="d-flex align-items-center gap-3">
                        <button id="play-btn" class="btn btn-primary btn-lg rounded-circle d-flex align-items-center justify-content-center" style="width: 70px; height: 70px;">
                            <i class="fas fa-play fs-4"></i>
                        </button>
                        <div class="flex-grow-1">
                            <label for="volume-control" class="form-label small text-secondary mb-1">Volume</label>
                            <input type="range" class="form-range" id="volume-control" min="0" max="1" step="0.01" value="0.5">
                        </div>
                        <span class="badge bg-dark border border-secondary mt-3" id="volume-indicator">50%</span>
                    </div>
                </div>

                <div class="station-list">
                    <h5 class="mb-3 text-uppercase small ls-wide fw-bold text-secondary">Available Stations</h5>
                    <div class="list-group list-group-flush bg-transparent custom-scrollbar" style="max-height: 250px; overflow-y: auto;">
                        {% for station in stations %}
                        <button class="list-group-item list-group-item-action bg-transparent text-white border-0 py-3 rounded-3 mb-2 station-item"
                                data-url="{{ station.stream_url }}"
                                data-name="{{ station.name }}"
                                data-color="{{ station.color }}"
                                data-metadata-url="{{ station.metadata_api_url|default:'' }}">
                            <div class="d-flex align-items-center">
                                <div class="station-dot me-3" style="background-color: {{ station.color }}; box-shadow: 0 0 15px {{ station.color }};"></div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0 fw-bold">{{ station.name }}</h6>
                                    <small class="text-secondary">Click to tune in</small>
                                </div>
                                <i class="fas fa-chevron-right text-muted small"></i>
                            </div>
                        </button>
                        {% empty %}
                        <div class="text-center py-4">
                            <i class="fas fa-search mb-2 text-muted fs-1"></i>
                            <p class="text-muted small">No stations added yet.<br><a href="/admin/" class="text-decoration-none text-primary">Add some in Admin!</a></p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- QR Payment Section -->
    <div class="row justify-content-center mt-5">
        <div class="col-lg-8">
            <div class="glass-card p-4 rounded-4 shadow-lg border-neon text-center">
                <div class="d-flex align-items-center justify-content-center mb-4">
                    <i class="fas fa-qrcode fs-2 me-3 text-primary"></i>
                    <h2 class="h4 mb-0 fw-bold" style="font-family: 'Righteous', cursive;">Solicita tu Canción</h2>
                </div>
                
                <p class="text-secondary mb-4">Escanea el código con <strong>Transfermóvil</strong> para realizar una transferencia y solicitar tu tema favorito.</p>
                
                <div class="qr-container-wrapper p-3 bg-white d-inline-block rounded-4 shadow-sm mb-4">
                    <img src="/assets/pasted-20260130-182834-0516740b.jpg" alt="QR Transferencia" class="img-fluid rounded-2" style="max-width: 250px;">
                </div>

                <div class="mt-2 mb-4">
                    <span class="badge bg-primary px-3 py-2 rounded-pill fs-6" style="cursor: pointer;" onclick="navigator.clipboard.writeText('9227959879036585'); alert('Copiado al portapapeles');">
                        <i class="fas fa-credit-card me-2"></i>9227 9598 7903 6585
                    </span>
                    <p class="small text-muted mt-2">Haz clic arriba para copiar el número de tarjeta</p>
                </div>

                <div class="info-steps text-start mx-auto" style="max-width: 400px;">
                    <div class="d-flex align-items-start mb-3">
                        <div class="step-num me-3">1</div>
                        <p class="small text-secondary mb-0">Escanea el código desde la opción <strong>Transferencia</strong> en Transfermóvil.</p>
                    </div>
                    <div class="d-flex align-items-start">
                        <div class="step-num me-3">2</div>
                        <p class="small text-secondary mb-0">Envía el comprobante por WhatsApp con el nombre de la canción y artista.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .border-neon {
        border-color: rgba(0, 242, 255, 0.3) !important;
        box-shadow: 0 0 20px rgba(0, 242, 255, 0.1);
    }
    .glass-card {
        background: rgba(15, 15, 15, 0.8);
        backdrop-filter: blur(15px);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }
    .ls-wide { letter-spacing: 0.1em; }
    .station-dot {
        width: 14px;
        height: 14px;
        border-radius: 50%;
    }
    .station-item {
        background: rgba(255, 255, 255, 0.03) !important;
        transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        border: 1px solid transparent !important;
    }
    .station-item:hover {
        background: rgba(255, 255, 255, 0.08) !important;
        transform: translateX(10px);
        border-color: rgba(255, 0, 127, 0.3) !important;
    }
    .station-item.active {
        background: linear-gradient(90deg, rgba(255, 0, 127, 0.1), transparent) !important;
        border-left: 4px solid var(--primary-neon) !important;
        border-color: rgba(255, 0, 127, 0.2) !important;
    }
    .custom-scrollbar::-webkit-scrollbar {
        width: 4px;
    }
    .custom-scrollbar::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.1);
    }
    .custom-scrollbar::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
    }
    #current-track-info {
        transition: opacity 0.5s ease-in-out;
        font-weight: 500;
        text-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
    }

    /* QR Styles */
    .qr-container-wrapper {
        border: 8px solid #f8f9fa;
        transition: transform 0.3s ease;
    }
    .qr-container-wrapper:hover {
        transform: scale(1.05);
    }
    .step-num {
        background: var(--primary-neon);
        color: white;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.75rem;
        font-weight: bold;
        flex-shrink: 0;
    }
</style>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const audio = document.getElementById('audio-player');
    const playBtn = document.getElementById('play-btn');
    const vinyl = document.getElementById('vinyl');
    const vinylLabel = document.getElementById('vinyl-label');
    const tonearm = document.getElementById('tonearm');
    const visualizer = document.getElementById('visualizer');
    const stationItems = document.querySelectorAll('.station-item');
    const stationNameDisplay = document.getElementById('current-station-name');
    const trackInfoDisplay = document.getElementById('current-track-info');
    const volumeControl = document.getElementById('volume-control');
    const volumeIndicator = document.getElementById('volume-indicator');

    let isPlaying = false;
    let currentMetadataUrl = '';
    let metadataInterval = null;

    function fetchMetadata() {
        if (!currentMetadataUrl) return;
        
        fetch(currentMetadataUrl)
            .then(response => response.json())
            .then(data => {
                let trackText = 'Virtual Broadcast';
                if (data.artist && data.title) {
                    trackText = `${data.artist} - ${data.title}`;
                } else if (data.title) {
                    trackText = data.title;
                }
                
                if (trackInfoDisplay.textContent !== trackText) {
                    trackInfoDisplay.style.opacity = 0;
                    setTimeout(() => {
                        trackInfoDisplay.textContent = trackText;
                        trackInfoDisplay.style.opacity = 1;
                    }, 500);
                }
            })
            .catch(err => console.error('Error fetching metadata:', err));
    }

    function togglePlay() {
        if (isPlaying) {
            audio.pause();
            playBtn.innerHTML = '<i class="fas fa-play fs-4"></i>';
            vinyl.classList.remove('spinning');
            tonearm.classList.remove('active');
            visualizer.classList.remove('playing');
            if (metadataInterval) clearInterval(metadataInterval);
        } else {
            if (audio.src && audio.src !== window.location.href) {
                audio.play().catch(e => {
                    console.error("Playback failed", e);
                    alert("Unable to play stream. It might be offline.");
                });
                playBtn.innerHTML = '<i class="fas fa-pause fs-4"></i>';
                vinyl.classList.add('spinning');
                tonearm.classList.add('active');
                visualizer.classList.add('playing');
                
                // Start fetching metadata
                fetchMetadata();
                metadataInterval = setInterval(fetchMetadata, 15000); // Every 15 seconds
            } else {
                alert('Please select a station first!');
                return;
            }
        }
        isPlaying = !isPlaying;
    }

    playBtn.addEventListener('click', togglePlay);

    stationItems.forEach(item => {
        item.addEventListener('click', function() {
            const url = this.dataset.url;
            const name = this.dataset.name;
            const color = this.dataset.color;
            currentMetadataUrl = this.dataset.metadataUrl;

            // Update UI
            stationItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');
            stationNameDisplay.textContent = name;
            vinylLabel.style.boxShadow = `0 0 30px ${color}`;

            // Reset track info
            trackInfoDisplay.textContent = 'Connecting...';
            if (metadataInterval) clearInterval(metadataInterval);

            // Set source and play
            audio.src = url;
            isPlaying = false; // Reset state for toggle
            togglePlay();
        });
    });

    volumeControl.addEventListener('input', function() {
        audio.volume = this.value;
        volumeIndicator.textContent = Math.round(this.value * 100) + '%';
    });
});
</script>
{% endblock %}