<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/tracker.php';
track_visitor();

$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Lili Records Radio - La mejor música en vivo.';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? 'assets/pasted-20260215-164611-6d2aee42.png';

// WhatsApp info
$whatsapp_link = "https://chat.whatsapp.com/DkG96pTzAFO3hvLqmzwmTY";
$whatsapp_number = '+5359177041';
$facebook_link = "https://www.facebook.com/profile.php?id=61587890927489";
$instagram_link = "https://www.instagram.com/";
$youtube_link = "https://www.youtube.com/@lilirecords";
$twitter_link = "https://twitter.com/";
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lili Records Radio</title>
    
    <!-- Meta tags SEO -->
    <meta name="description" content="<?= htmlspecialchars($projectDescription) ?>" />
    <meta property="og:title" content="Lili Records Radio" />
    <meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
    <meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
    <meta property="twitter:card" content="summary_large_image" />

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <script type="module" src="https://cdn.jsdelivr.net/npm/emoji-picker-element@1/index.js"></script>

    <style>
        :root {
            --accent-color: #00e676; /* Vibrant Neon Green */
            --primary-color: #38bdf8; /* Deep Sky Blue */
            --secondary-color: #f472b6; /* Playful Pink */
            --bg-overlay: rgba(2, 6, 23, 0.35); /* Deep slate overlay for depth */
            --glass-bg: rgba(30, 41, 59, 0.3); /* Slate glass */
            --glass-border: rgba(255, 255, 255, 0.1);
            --text-color: #f8fafc;
            --card-shadow: rgba(0, 0, 0, 0.6);
        }

        [data-theme="light"] {
            --bg-overlay: rgba(255, 255, 255, 0.5);
            --glass-bg: rgba(255, 255, 255, 0.7);
            --glass-border: rgba(0, 0, 0, 0.05);
            --text-color: #0f172a;
            --card-shadow: rgba(0, 0, 0, 0.1);
        }

        body, html {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            font-family: 'Inter', sans-serif;
            color: var(--text-color);
            background-color: transparent;
            transition: color 0.3s ease;
        }

        .background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('assets/images/background.jpg') center/cover no-repeat;
            z-index: -1;
            transition: filter 0.05s ease-out, transform 0.05s ease-out, background-image 1.5s ease-in-out;
            will-change: filter, transform, background-image;
        }

        .background::after {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 50% 50%, transparent 0%, var(--bg-overlay) 100%);
            backdrop-filter: blur(2px);
        }

        .app-container {
            display: flex;
            flex-direction: column;
            width: 100%;
            min-height: 100vh;
            align-items: center;
            justify-content: center;
            padding: 2rem 1.5rem;
            box-sizing: border-box;
            gap: 1.5rem;
        }

        /* Center Section: Player */
        .player-section {
            width: 100%;
            max-width: 680px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            z-index: 10;
        }

        .interaction-center {
            width: 100%;
            max-width: 520px;
            z-index: 10;
        }

        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(3px);
            -webkit-backdrop-filter: blur(3px);
            border: 2px solid transparent;
            border-radius: 32px;
            padding: 2.5rem;
            box-shadow: 0 15px 45px rgba(0, 0, 0, 0.4);
            position: relative;
            background-clip: padding-box;
            overflow: hidden;
            transition: border-radius 0.5s ease, background 0.5s ease, box-shadow 0.1s ease;
        }

        /* Animated colorful border */
        .glass-card::before {
            content: "";
            position: absolute;
            inset: 0;
            border-radius: 32px;
            padding: 2px; /* thickness */
            background: var(--card-border-bg, linear-gradient(45deg, #00e676, #38bdf8, #facc15, #f472b6, #00e676));
            background-size: 400% 400%;
            -webkit-mask: 
                linear-gradient(#fff 0 0) content-box, 
                linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor; 
            mask-composite: exclude;
            pointer-events: none;
            animation: gradient-border 8s linear infinite;
            transition: background 0.05s ease;
        }

        @keyframes gradient-border {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .brand h1 {
            font-size: 2.8rem;
            font-weight: 800;
            margin: 0 0 0.5rem;
            background: linear-gradient(to right, var(--text-color), var(--primary-color), var(--accent-color));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: -1px;
            filter: drop-shadow(0 0 10px rgba(56, 189, 248, 0.3));
        }

        .brand-logo {
            width: 130px;
            height: 130px;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid var(--primary-color);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
            transition: transform 0.3s ease, border-color 0.1s ease, box-shadow 0.1s ease;
        }

        .logo-wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 2rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .brand-logo:hover {
            transform: scale(1.1) rotate(5deg);
        }

        .brand p {
            font-size: 1rem;
            opacity: 0.8;
            margin-bottom: 2rem;
        }

        /* Radio Player UI */
        .radio-player {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .now-playing {
            display: flex;
            align-items: center;
            gap: 1.2rem;
            background: rgba(255, 255, 255, 0.02);
            padding: 1.2rem;
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: inset 0 0 15px rgba(0,0,0,0.2);
            position: relative;
            overflow: hidden;
        }

        .track-cover-container {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            overflow: hidden;
            flex-shrink: 0;
            position: relative;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5), inset 0 0 10px rgba(0,0,0,0.8);
            border: 4px solid #111;
            transition: transform 0.3s ease, box-shadow 0.1s ease;
            animation: spin-vinyl 30s linear infinite;
            margin: 0 auto;
        }

        .track-cover-container::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 20px;
            height: 20px;
            background: #111;
            border-radius: 50%;
            border: 2px solid rgba(255,255,255,0.2);
            z-index: 10;
        }

        .track-cover-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: opacity 0.5s ease;
            border-radius: 50%;
        }

        @keyframes spin-vinyl {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .track-cover-container {
                width: 100px;
                height: 100px;
            }
        }

        .track-cover-container i {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 1.5rem;
            color: rgba(255,255,255,0.5);
            z-index: 1;
            display: none;
        }

        .now-playing i {
            font-size: 1.5rem;
            color: var(--primary-color);
        }

        .track-info {
            overflow: hidden;
            flex: 1;
        }

        .track-title {
            font-weight: 800;
            font-size: 1.5rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: color 0.05s ease, transform 0.05s ease, text-shadow 0.05s ease, opacity 0.5s ease;
            color: var(--text-color);
            text-shadow: 0 0 15px var(--primary-color);
            opacity: 0.9;
            display: block;
            margin-top: 0.2rem;
            will-change: color, transform, text-shadow;
            cursor: pointer;
            position: relative;
        }

        .track-title:hover {
            color: var(--primary-color);
        }

        .copy-toast {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--accent-color);
            color: white;
            padding: 12px 24px;
            border-radius: 50px;
            font-weight: 800;
            font-size: 0.9rem;
            z-index: 10000;
            box-shadow: 0 10px 30px rgba(0, 200, 83, 0.4);
            animation: toast-in-out 2s forwards;
            display: flex;
            align-items: center;
            gap: 10px;
            pointer-events: none;
        }

        @keyframes toast-in-out {
            0% { opacity: 0; transform: translate(-50%, 20px); }
            15% { opacity: 1; transform: translate(-50%, 0); }
            85% { opacity: 1; transform: translate(-50%, 0); }
            100% { opacity: 0; transform: translate(-50%, -20px); }
        }

        .track-label {
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 2px;
            color: var(--accent-color);
            margin-bottom: -5px;
            display: block;
        }

        @keyframes marquee {
            0% { transform: translateX(0); }
            100% { transform: translateX(-50%); }
        }

        .track-title.scrolling {
            text-overflow: clip;
        }

        .track-title.scrolling span {
            display: inline-block;
            animation: marquee 15s linear infinite;
            padding-right: 2rem;
        }

        .track-status {
            font-size: 0.85rem;
            opacity: 0.6;
        }

        .quality-selector-wrapper:hover {
            background: rgba(255,255,255,0.15) !important;
            border-color: rgba(255,255,255,0.2) !important;
        }

        .controls {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            margin-top: 1.5rem;
            justify-content: center;
            flex-wrap: wrap;
        }


        .play-btn {
            width: 72px;
            height: 72px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary-color), #0ea5e9);
            border: none;
            color: #fff;
            font-size: 2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 0 20px rgba(56, 189, 248, 0.4), inset 0 0 10px rgba(255,255,255,0.2);
            position: relative;
        }

        .play-btn::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 2px solid var(--primary-color);
            opacity: 0;
            transition: all 0.4s;
        }

        .play-btn:hover::after {
            opacity: 1;
            transform: scale(1.2);
        }

        .play-btn.playing {
            background: linear-gradient(135deg, #ff4444, #cc0000) !important;
            box-shadow: 0 0 25px rgba(255, 68, 68, 0.6);
            transform: scale(1.1);
        }

        @keyframes pulse-button {
            0% { box-shadow: 0 0 0 0 rgba(255, 68, 68, 0.7); }
            70% { box-shadow: 0 0 0 20px rgba(255, 68, 68, 0); }
            100% { box-shadow: 0 0 0 0 rgba(255, 68, 68, 0); }
        }

        .now-playing {
            display: flex;
            align-items: center;
            gap: 1rem;
            background: rgba(255, 255, 255, 0.05);
            padding: 1.2rem;
            border-radius: 16px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: inset 0 0 15px rgba(0,0,0,0.2);
        }

        .play-btn:hover {
            transform: scale(1.05);
            background: #0ea5e9;
        }

        .visualizer-container {
            width: 100%;
            height: 120px;
            margin-bottom: 1rem;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            gap: 4px;
            overflow: hidden;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            background: radial-gradient(circle at center, rgba(56, 189, 248, 0.05) 0%, transparent 70%);
            position: relative;
            padding: 0 10px;
        }

        .audio-visualizer {
            display: flex;
            align-items: flex-end;
            justify-content: center;
            gap: 4px;
            width: 100%;
            height: 100%;
        }

        .visualizer-bar {
            width: 18px;
            height: 5px;
            border-radius: 4px 4px 0 0;
            background: linear-gradient(to top, var(--primary-color), var(--accent-color));
            transition: height 0.05s ease;
            min-height: 5px;
            position: relative;
            box-shadow: 0 0 15px rgba(56, 189, 248, 0.3);
        }

        /* Visualizer Peak */
        .visualizer-peak {
            position: absolute;
            width: 18px;
            height: 12px;
            background: linear-gradient(to bottom, #fff, transparent);
            border-radius: 2px;
            bottom: 0;
            z-index: 2;
            box-shadow: 0 -2px 10px rgba(255, 255, 255, 0.8);
            pointer-events: none;
            transition: background 0.1s ease;
        }

        /* Removed strobe-peak animation */

        /* Playing Animations */
        body.is-playing .glass-card {
            border-color: rgba(56, 189, 248, 0.5);
            box-shadow: 0 15px 45px rgba(0, 0, 0, 0.4);
        }

        .featured-img-container {
            width: 100%;
            max-width: 900px;
            position: relative;
            border-radius: 32px;
            overflow: hidden;
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.7);
            aspect-ratio: 16 / 10;
            transition: all 0.5s ease;
        }

        /* Removed card-pulse and float-img animations */

        .volume-slider {
            flex: 1;
            height: 6px;
            -webkit-appearance: none;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 3px;
            outline: none;
        }

        .volume-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 16px;
            height: 16px;
            background: #fff;
            border-radius: 50%;
            cursor: pointer;
        }

        /* Interaction Form */
        .interaction-form {
            margin-top: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
            text-align: left;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;
        }

        .interaction-form label {
            font-size: 0.85rem;
            font-weight: 700;
            opacity: 0.9;
            letter-spacing: 0.5px;
        }

        .interaction-form input, 
        .interaction-form textarea {
            width: 100%;
            padding: 0.8rem;
            border-radius: 12px;
            border: 1px solid var(--glass-border);
            background-color: var(--glass-bg);
            color: var(--text-color); 
            font-family: inherit;
            font-size: 0.95rem;
            box-sizing: border-box;
            outline: none;
            transition: all 0.2s;
            backdrop-filter: blur(4px);
        }

        .interaction-form textarea {
            resize: none;
            height: 80px;
        }

        .interaction-form input::placeholder,
        .interaction-form textarea::placeholder {
            color: var(--text-color);
            opacity: 0.5;
        }

        .send-whatsapp-btn {
            background-color: var(--accent-color);
            color: #fff;
            border: none;
            padding: 0.8rem;
            border-radius: 12px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: transform 0.2s, background 0.2s;
        }

        .send-whatsapp-btn:hover {
            transform: translateY(-2px);
            background-color: #00c853;
        }

        /* Gallery Styles */
        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 10px;
            margin-top: 1rem;
        }

        .gallery-item {
            position: relative;
            aspect-ratio: 1/1;
            border-radius: 12px;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.3s ease;
            border: 1px solid rgba(255,255,255,0.1);
        }

        .gallery-item:hover {
            transform: scale(1.05);
            z-index: 2;
        }

        .gallery-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .gallery-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0,0,0,0.8));
            padding: 8px;
            font-size: 0.7rem;
            opacity: 0;
            transition: opacity 0.3s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .gallery-item:hover .gallery-overlay {
            opacity: 1;
        }

        .gallery-username {
            font-weight: bold;
            color: #fff;
        }

        .gallery-likes {
            color: #ff4081;
            display: flex;
            align-items: center;
            gap: 3px;
        }

        /* Lightbox */
        .lightbox {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.95);
            z-index: 2000;
            display: none;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            padding: 20px;
        }

        .lightbox-img {
            max-width: 100%;
            max-height: 80vh;
            border-radius: 12px;
            box-shadow: 0 0 30px rgba(0,0,0,0.5);
        }

        .lightbox-info {
            margin-top: 20px;
            text-align: center;
            color: white;
        }

        .lightbox-close {
            position: absolute;
            top: 20px;
            right: 20px;
            font-size: 2rem;
            color: white;
            cursor: pointer;
        }

        /* Center Section: Featured Image */
        .image-section {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 5;
        }

        .featured-img-container {
            width: 100%;
            max-width: 900px;
            position: relative;
            border-radius: 32px;
            overflow: hidden;
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.7);
            aspect-ratio: 16 / 10;
        }

        .featured-img-container img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: rgba(0,0,0,0.2);
            transition: transform 0.5s;
        }

        .featured-img-container:hover img {
            transform: scale(1.05);
        }

        /* Transfermovil QR Section */
        .payment-section {
            margin-top: 2rem;
            text-align: center;
        }

        .qr-placeholder {
            width: 220px;
            height: 220px;
            margin: 1rem auto;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #fff;
            padding: 10px;
            backdrop-filter: blur(4px);
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .qr-placeholder:hover {
            transform: scale(1.05);
            box-shadow: 0 0 20px var(--accent-color);
            background: rgba(255, 255, 255, 0.2);
        }

        /* Modal Styles */
        .qr-modal {
            display: none;
            position: fixed;
            z-index: 2000;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            backdrop-filter: blur(15px);
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .qr-modal.show {
            display: flex;
            opacity: 1;
        }

        .qr-modal-content {
            max-width: 90%;
            max-height: 90%;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            padding: 30px;
            border-radius: 32px;
            position: relative;
            transform: scale(0.7);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            overflow: hidden;
            box-shadow: 0 0 50px rgba(0, 230, 118, 0.4), 0 0 100px rgba(0, 0, 0, 0.5);
            animation: glow-color-change 8s infinite ease-in-out;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        @keyframes glow-color-change {
            0% { box-shadow: 0 0 50px rgba(0, 230, 118, 0.4), 0 0 100px rgba(0, 0, 0, 0.5); }
            33% { box-shadow: 0 0 50px rgba(56, 189, 248, 0.4), 0 0 100px rgba(0, 0, 0, 0.5); }
            66% { box-shadow: 0 0 50px rgba(244, 114, 182, 0.4), 0 0 100px rgba(0, 0, 0, 0.5); }
            100% { box-shadow: 0 0 50px rgba(0, 230, 118, 0.4), 0 0 100px rgba(0, 0, 0, 0.5); }
        }

        .qr-modal-content::after {
            content: "";
            position: absolute;
            top: -50%;
            left: -150%;
            width: 200%;
            height: 200%;
            background: linear-gradient(
                120deg,
                transparent,
                rgba(255, 255, 255, 0.1),
                transparent
            );
            transform: rotate(10deg);
            pointer-events: none;
        }

        .qr-modal.show .qr-modal-content::after {
            animation: modal-shine 4s infinite;
        }

        @keyframes modal-shine {
            0% { left: -150%; }
            20% { left: 150%; }
            100% { left: 150%; }
        }

        .qr-modal.show .qr-modal-content {
            transform: scale(1);
        }

        /* Sleep Timer Modal */
        .sleep-modal {
            display: none;
            position: fixed;
            z-index: 3000;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            backdrop-filter: blur(10px);
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .sleep-modal.show {
            display: flex;
            opacity: 1;
        }
        .sleep-modal-content {
            background: rgba(20, 20, 20, 0.8);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 2.5rem;
            border-radius: 32px;
            width: 90%;
            max-width: 400px;
            text-align: center;
            transform: scale(0.8);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        }
        .sleep-modal.show .sleep-modal-content {
            transform: scale(1);
        }
        .sleep-option {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
            padding: 1rem;
            margin: 0.8rem 0;
            border-radius: 16px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .sleep-option:hover {
            background: rgba(255, 255, 255, 0.15);
            transform: translateY(-2px);
            border-color: var(--primary-color);
        }
        .sleep-option.active {
            background: var(--primary-color);
            color: #000;
            border-color: #fff;
        }

        .qr-modal-close {
            position: absolute;
            top: 15px;
            right: 20px;
            color: #ffffff;
            font-size: 2.5rem;
            cursor: pointer;
            z-index: 10;
            text-shadow: 0 0 10px rgba(0,0,0,0.5);
        }

        .qr-placeholder i {
            font-size: 3rem;
            margin-bottom: 10px;
            color: #fff;
        }

        .qr-placeholder span {
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
        }

        /* Floating Social Buttons */
        .social-float-container {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            z-index: 100;
        }

        .social-float {
            width: 60px;
            height: 60px;
            color: #FFF;
            border-radius: 50%;
            text-align: center;
            font-size: 28px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            transition: all 0.05s ease-out; /* Super fast for vibration */
            position: relative;
            will-change: transform, background-color, box-shadow;
        }

        .social-float::before {
            content: "";
            position: absolute;
            inset: 0;
            border-radius: 50%;
            padding: 3px;
            background: linear-gradient(45deg, #00e676, #38bdf8, #facc15, #f472b6, #00e676);
            background-size: 400% 400%;
            -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor;
            mask-composite: exclude;
            pointer-events: none;
            animation: gradient-border 6s linear infinite;
        }

        .social-float:hover {
            transform: scale(1.1) rotate(8deg);
            color: #fff;
        }

        .social-float.whatsapp { 
            background-color: var(--accent-color); 
            box-shadow: 0 0 20px rgba(0, 230, 118, 0.5);
        }
        
        .social-float.youtube { 
            background-color: #ff0000; 
            box-shadow: 0 0 20px rgba(255, 0, 0, 0.5);
        }

        .social-float.facebook { 
            background-color: #1877F2; 
            box-shadow: 0 0 20px rgba(24, 119, 242, 0.5);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-5px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }

        @keyframes alert-pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.3); background: #facc15 !important; }
            100% { transform: scale(1); }
        }
        .counter-alert {
            animation: alert-pulse 1s infinite ease-in-out;
            box-shadow: 0 0 10px #facc15;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .app-container {
                flex-direction: column;
                height: auto;
                overflow-y: auto;
                padding: 2rem 1rem;
            }
            .player-section, .interaction-center {
                max-width: 100% !important;
                margin-bottom: 2rem;
            }
            .interaction-center {
                grid-template-columns: 1fr !important;
            }
            .chat-window {
                height: 500px !important;
            }
            .image-section {
                padding-left: 0;
                width: 100%;
            }
            .featured-img-container {
                aspect-ratio: 16 / 9;
            }
        }

        @media (max-width: 600px) {
            .app-container {
                padding: 1rem 0.8rem;
                gap: 1rem;
            }
            .form-row {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
            .glass-card {
                padding: 1.5rem 1.2rem;
                border-radius: 24px;
            }
            .glass-card::before {
                border-radius: 24px;
            }
            .brand h1 {
                font-size: 1.8rem;
            }
            .brand-logo {
                width: 100px;
                height: 100px;
            }
            .logo-wrapper {
                gap: 1rem;
                margin-bottom: 1rem;
            }
            .now-playing {
                padding: 1rem;
                gap: 0.8rem;
                flex-direction: column;
                text-align: center;
            }
            .track-cover-container {
                width: 120px;
                height: 120px;
                margin: 0 auto;
            }
            .track-title {
                font-size: 1.3rem;
                white-space: normal;
                word-break: break-word;
            }
            .controls {
                justify-content: center;
                gap: 1.2rem;
                flex-wrap: wrap;
            }
            .play-btn {
                width: 80px;
                height: 80px;
                font-size: 2.5rem;
            }
            .volume-slider {
                width: 100%;
                order: 4;
                margin-top: 10px;
            }
            .chat-window {
                height: 450px !important;
            }
            .social-float-container {
                bottom: 1rem;
                right: 1rem;
            }
            .social-float {
                width: 50px;
                height: 50px;
                font-size: 22px;
            }
            .chat-input-area button {
                padding: 0 0.8rem;
            }
            #chat-msg {
                font-size: 1rem; /* Prevent zoom on iOS */
            }
        }

        @media (max-width: 400px) {
            .brand h1 {
                font-size: 1.5rem;
            }
            .play-btn {
                width: 70px;
                height: 70px;
            }
            .track-title {
                font-size: 1.1rem;
            }
        }

        /* Song Requests Styles */
        .request-list {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;
            max-height: 300px;
            overflow-y: auto;
            padding-right: 5px;
        }
        .request-item {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 0.8rem;
            border-radius: 12px;
            animation: fadeIn 0.5s ease;
        }
        .request-item .artist {
            color: var(--primary-color);
            font-weight: 800;
            font-size: 0.8rem;
            text-transform: uppercase;
        }
        .request-item .song {
            font-weight: 600;
            font-size: 0.95rem;
            margin: 2px 0;
        }
        .request-item .requester {
            font-size: 0.7rem;
            opacity: 0.6;
            font-style: italic;
        }
        .request-badge {
            background: var(--primary-color);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.6rem;
            font-weight: bold;
            margin-right: 5px;
        }

        /* Social Media Widget Styles */
        .social-card {
            margin-top: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1.2rem;
        }
        .social-card-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }
        .social-card-item {
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 1rem;
            border-radius: 16px;
            text-decoration: none;
            color: white;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            position: relative;
            overflow: hidden;
        }
        .social-card-item:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.1);
            border-color: var(--primary-color);
            box-shadow: 0 10px 20px rgba(0,0,0,0.3);
        }
        .social-card-item i {
            font-size: 1.5rem;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            transition: transform 0.3s;
        }
        .social-card-item:hover i {
            transform: scale(1.1) rotate(5deg);
        }
        .social-card-item.fb i { background: #1877F2; }
        .social-card-item.ig i { background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%); }
        .social-card-item.yt i { background: #FF0000; }
        .social-card-item.tw i { background: #1DA1F2; }
        
        .social-card-info {
            display: flex;
            flex-direction: column;
        }
        .social-card-name {
            font-weight: 800;
            font-size: 0.9rem;
            letter-spacing: 0.5px;
        }
        .social-card-handle {
            font-size: 0.7rem;
            opacity: 0.6;
            text-transform: uppercase;
        }

        /* Leaderboard Styles */
        .leaderboard-list {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;
        }
        .leaderboard-item {
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 0.8rem;
            border-radius: 16px;
            transition: all 0.3s ease;
        }
        .leaderboard-item:hover {
            background: rgba(255, 255, 255, 0.1);
            transform: translateX(5px);
            border-color: var(--primary-color);
        }
        .leaderboard-rank {
            font-weight: 800;
            font-size: 1.1rem;
            width: 25px;
            text-align: center;
            color: var(--primary-color);
        }
        .leaderboard-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            border: 2px solid var(--glass-border);
            object-fit: cover;
        }
        .leaderboard-info {
            flex: 1;
        }
        .leaderboard-name {
            font-weight: 700;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .leaderboard-points {
            font-size: 0.75rem;
            opacity: 0.6;
        }
        .badge-icon {
            font-size: 0.8rem;
        }

        /* Level System Styles */
        .level-badge {
            font-size: 0.65rem;
            font-weight: 800;
            padding: 2px 8px;
            border-radius: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .level-progress-container {
            margin-top: 1rem;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 1rem;
            animation: fadeIn 0.5s ease;
        }
        .level-bar-bg {
            width: 100%;
            height: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            margin-top: 8px;
            overflow: hidden;
        }
        .level-bar-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
            width: 0%;
            transition: width 1s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 0 10px var(--primary-color);
        }
        .unlocked-reward {
            font-size: 0.7rem;
            color: var(--accent-color);
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 700;
        }

        /* Shop Styles */
        .shop-modal {
            display: none;
            position: fixed;
            z-index: 4000;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(10px);
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .shop-modal.show {
            display: flex;
            opacity: 1;
        }
        .shop-modal-content {
            background: rgba(20, 20, 20, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 2.5rem;
            border-radius: 32px;
            width: 90%;
            max-width: 500px;
            transform: scale(0.8);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        }
        .shop-modal.show .shop-modal-content {
            transform: scale(1);
        }
        .shop-item {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 1.2rem;
            border-radius: 20px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 15px;
            transition: all 0.2s;
        }
        .shop-item:hover {
            background: rgba(255, 255, 255, 0.1);
            border-color: var(--primary-color);
        }
        .shop-item-icon {
            width: 50px;
            height: 50px;
            background: rgba(56, 189, 248, 0.1);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: var(--primary-color);
        }
        .shop-item-info {
            flex: 1;
        }
        .shop-item-name {
            font-weight: 800;
            font-size: 1rem;
            color: white;
        }
    .shop-item-desc {
        font-size: 0.75rem;
        opacity: 0.7;
    }

    /* Celebration & Flowers */
    #celebration-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: 9999;
        overflow: hidden;
    }

    .flower-particle {
        position: absolute;
        font-size: 2rem;
        user-select: none;
        animation: fall-and-sway var(--duration) linear forwards;
        opacity: 0;
    }

    .donor-message {
        position: absolute;
        top: 40%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(15, 23, 42, 0.8);
        backdrop-filter: blur(12px);
        padding: 25px 50px;
        border-radius: 24px;
        border: 2px solid #f472b6;
        color: white;
        text-align: center;
        z-index: 2000;
        animation: toast-celebration 5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
        box-shadow: 0 20px 40px rgba(236, 72, 153, 0.4), 0 0 20px rgba(236, 72, 153, 0.2);
        pointer-events: auto;
        min-width: 300px;
    }

    .donor-message h4 {
        margin: 0;
        font-size: 1rem;
        text-transform: uppercase;
        letter-spacing: 2px;
        color: #f472b6;
        font-weight: 800;
    }

    .donor-message h2 {
        margin: 10px 0 0;
        font-size: 2.2rem;
        font-weight: 900;
        background: linear-gradient(to right, #ffffff, #f472b6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 0 20px rgba(244, 114, 182, 0.3);
    }

    .donor-message p {
        margin: 15px 0 0;
        font-size: 1.1rem;
        font-style: italic;
        color: rgba(255, 255, 255, 0.9);
        border-top: 1px solid rgba(244, 114, 182, 0.3);
        padding-top: 15px;
        max-width: 400px;
        line-height: 1.4;
    }

    @keyframes toast-celebration {
        0% { opacity: 0; transform: translate(-50%, -30%) scale(0.8); }
        10% { opacity: 1; transform: translate(-50%, -50%) scale(1.05); }
        15% { transform: translate(-50%, -50%) scale(1); }
        85% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        100% { opacity: 0; transform: translate(-50%, -70%) scale(0.9); }
    }

    @keyframes fall-and-sway {
        0% { transform: translateY(-10vh) translateX(0) rotate(0deg); opacity: 0; }
        10% { opacity: 1; }
        90% { opacity: 1; }
        100% { transform: translateY(110vh) translateX(var(--sway)) rotate(360deg); opacity: 0; }
    }

    .dj-badge {
        background: linear-gradient(135deg, #f472b6, #db2777);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.7rem;
        font-weight: 800;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        margin-bottom: 8px;
        box-shadow: 0 4px 12px rgba(236, 72, 153, 0.3);
        animation: pulse 2s infinite;
    }

    /* Shoutout Modal Styles */
    .shoutout-modal {
        display: none;
        position: fixed;
        z-index: 5000;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.85);
        backdrop-filter: blur(15px);
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: opacity 0.5s ease;
    }
    .shoutout-modal.show {
        display: flex;
        opacity: 1;
    }
    .shoutout-card {
        background: linear-gradient(145deg, rgba(30, 30, 30, 0.9), rgba(10, 10, 10, 0.95));
        border: 2px solid var(--primary-color);
        padding: 3rem;
        border-radius: 40px;
        text-align: center;
        max-width: 500px;
        width: 90%;
        position: relative;
        transform: scale(0.5) translateY(100px);
        transition: all 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        box-shadow: 0 0 50px rgba(56, 189, 248, 0.6);
    }
    .shoutout-modal.show .shoutout-card {
        transform: scale(1) translateY(0);
    }
    .shoutout-icon {
        font-size: 5rem;
        color: #facc15;
        margin-bottom: 1.5rem;
        filter: drop-shadow(0 0 20px rgba(250, 204, 21, 0.6));
        animation: bounce 2s infinite;
    }
    .shoutout-title {
        font-size: 2.2rem;
        font-weight: 900;
        background: linear-gradient(to right, #fff, var(--primary-color));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 1rem;
        text-transform: uppercase;
        letter-spacing: 2px;
    }
    .shoutout-msg {
        font-size: 1.2rem;
        line-height: 1.6;
        color: #fff;
        margin-bottom: 2rem;
        font-weight: 500;
    }
    .shoutout-dj {
        font-size: 0.8rem;
        color: var(--primary-color);
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: 3px;
    }
    @keyframes bounce {
        0%, 100% { transform: translateY(0); }
        50% { transform: translateY(-20px); }
    }
    .shoutout-confetti {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
    }
    
    /* Chat Message Styles */
    @keyframes messageBubble {
        0% { transform: scale(0.5); opacity: 0; transform-origin: left bottom; }
        70% { transform: scale(1.05); transform-origin: left bottom; }
        100% { transform: scale(1); opacity: 1; transform-origin: left bottom; }
    }

    @keyframes messageBubbleMe {
        0% { transform: scale(0.5); opacity: 0; transform-origin: right bottom; }
        70% { transform: scale(1.05); transform-origin: right bottom; }
        100% { transform: scale(1); opacity: 1; transform-origin: right bottom; }
    }

    .chat-msg-item {
        max-width: 85%;
        padding: 0.8rem;
        border-radius: 18px;
        transition: all 0.3s ease;
        position: relative;
        animation: messageBubble 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
        align-self: flex-start;
        background: rgba(255,255,255,0.05);
        border-bottom-left-radius: 4px;
        margin-bottom: 0.5rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    .chat-msg-item.is-me {
        align-self: flex-end;
        background: rgba(56, 189, 248, 0.15) !important;
        border-left: none !important;
        border-right: 4px solid var(--primary-color);
        text-align: right;
        border-bottom-left-radius: 18px;
        border-bottom-right-radius: 4px;
        animation: messageBubbleMe 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
    }
    
    .chat-msg-header {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 0.7rem;
        font-weight: bold;
        margin-bottom: 2px;
    }
    
    .chat-msg-item.is-me .chat-msg-header {
        flex-direction: row-reverse;
    }
    
    .chat-msg-time {
        font-size: 0.6rem;
        opacity: 0.4;
        margin-top: 4px;
        text-align: right;
    }
    
        .chat-msg-item.is-me .chat-msg-time {
        text-align: left;
    }

    /* Flying Emojis Animation */
    .flying-emoji {
        position: fixed;
        bottom: 20px;
        font-size: 2.5rem;
        user-select: none;
        pointer-events: none;
        z-index: 10000;
        animation: flyUp var(--duration) ease-out forwards;
        filter: drop-shadow(0 0 10px rgba(0,0,0,0.3));
    }

    @keyframes flyUp {
        0% { transform: translateY(0) translateX(0) rotate(0deg); opacity: 0; }
        10% { opacity: 1; }
        100% { transform: translateY(-80vh) translateX(var(--drift)) rotate(var(--rot)); opacity: 0; }
    }

    @keyframes floatUpFade {
        0% { transform: translate(-50%, -50%) scale(0.5); opacity: 0; }
        20% { opacity: 1; transform: translate(-50%, -80%) scale(1.2); }
        100% { transform: translate(-50%, -150%) scale(1); opacity: 0; }
    }

    /* Reaction Buttons Container */
    .reaction-buttons {
        display: flex;
        gap: 12px;
        margin-top: 15px;
        justify-content: center;
        padding: 10px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 50px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        animation: slideUpFade 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }

    /* Flash Poll Styles */
    #flash-poll-container {
        position: fixed;
        top: 20%;
        left: 50%;
        transform: translate(-50%, -50%) scale(0.8);
        z-index: 9995;
        width: 90%;
        max-width: 400px;
        background: linear-gradient(145deg, rgba(30, 41, 59, 0.95), rgba(15, 23, 42, 0.98));
        border: 2px solid #facc15;
        border-radius: 24px;
        padding: 20px;
        box-shadow: 0 0 50px rgba(250, 204, 21, 0.4), 0 20px 40px rgba(0,0,0,0.5);
        display: none;
        opacity: 0;
        transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        text-align: center;
    }
    #flash-poll-container.show {
        display: block;
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }
    .poll-question {
        font-size: 1.2rem;
        font-weight: 800;
        color: #fff;
        margin-bottom: 15px;
        line-height: 1.3;
    }
    .poll-options {
        display: flex;
        gap: 10px;
        justify-content: center;
    }
    .poll-btn {
        background: rgba(255,255,255,0.1);
        border: 1px solid rgba(255,255,255,0.2);
        color: white;
        padding: 10px 20px;
        border-radius: 12px;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.2s;
        flex: 1;
    }
    .poll-btn:hover {
        background: var(--primary-color);
        border-color: #fff;
        transform: translateY(-3px);
    }
    .poll-timer-bar {
        width: 100%;
        height: 4px;
        background: rgba(255,255,255,0.1);
        border-radius: 2px;
        margin-top: 15px;
        overflow: hidden;
    }
    .poll-timer-fill {
        height: 100%;
        background: #facc15;
        width: 100%;
        transition: width linear;
    }

    /* Energy Thermometer for DJ */
    .energy-thermometer-container {
        display: none;
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
        margin-left: 5px;
    }
    .energy-thermometer {
        width: 80px;
        height: 8px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        overflow: hidden;
        position: relative;
    }
    .energy-fill {
        height: 100%;
        width: 0%;
        background: linear-gradient(90deg, #38bdf8, #facc15, #f472b6, #38bdf8);
        background-size: 200% 100%;
        transition: width 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        animation: gradient-shift 2s linear infinite;
        box-shadow: 0 0 10px rgba(56, 189, 248, 0.5);
    }
    @keyframes gradient-shift {
        0% { background-position: 0% 50%; }
        100% { background-position: 200% 50%; }
    }
    .energy-status-label {
        font-size: 0.55rem;
        font-weight: 800;
        color: #facc15;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    @keyframes slideUpFade {
        0% { transform: translateY(20px); opacity: 0; }
        100% { transform: translateY(0); opacity: 1; }
    }

    .reaction-btn {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        width: 45px;
        height: 45px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        cursor: pointer;
        transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        backdrop-filter: blur(5px);
    }

    .reaction-btn:hover {
        transform: scale(1.2) translateY(-5px);
        background: rgba(255, 255, 255, 0.2);
        border-color: var(--primary-color);
        box-shadow: 0 0 15px var(--primary-color);
    }

    .reaction-btn:active {
        transform: scale(0.9);
    }

    .reaction-overlay-active {
        animation: pulse-reaction 1s infinite;
        border: 2px solid #facc15 !important;
    }

    @keyframes pulse-reaction {
        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(250, 204, 21, 0.7); }
        70% { transform: scale(1.1); box-shadow: 0 0 0 15px rgba(250, 204, 21, 0); }
        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(250, 204, 21, 0); }
    }

    /* Top Listener Banner */
    .top-listener-banner {
        background: linear-gradient(135deg, rgba(250, 204, 21, 0.2), rgba(245, 158, 11, 0.3));
        border: 1px solid rgba(250, 204, 21, 0.4);
        border-radius: 16px;
        padding: 10px 15px;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 12px;
        animation: fadeIn 0.8s ease;
        position: relative;
        overflow: hidden;
    }
    .top-listener-banner::after {
        content: "";
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(120deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transform: rotate(25deg);
        animation: modal-shine 6s infinite;
        pointer-events: none;
    }
    .top-listener-crown {
        font-size: 1.5rem;
        color: #facc15;
        filter: drop-shadow(0 0 5px rgba(250, 204, 21, 0.5));
    }
    .top-listener-name {
        font-weight: 800;
        color: #fff;
        font-size: 0.9rem;
    }
    .top-listener-label {
        font-size: 0.65rem;
        font-weight: 800;
        color: #facc15;
        letter-spacing: 1px;
        text-transform: uppercase;
        display: block;
    }
</style>
</head>
<body>
    <div class="background"></div>

    <!-- Sticky Top Marquee -->
    <div id="sticky-now-playing" style="position: fixed; top: 0; left: 0; width: 100%; background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(10px); z-index: 1000; padding: 10px 0; border-bottom: 1px solid rgba(56, 189, 248, 0.3); display: none; animation: slideDown 0.5s ease;">
        <div style="max-width: 1200px; margin: 0 auto; display: flex; align-items: center; justify-content: center; gap: 15px; padding: 0 20px;">
            <div style="width: 30px; height: 30px; border-radius: 50%; overflow: hidden; flex-shrink: 0; border: 2px solid var(--primary-color); animation: spin-vinyl 30s linear infinite;">
                <img id="sticky-track-cover" src="./assets/pasted-20260215-163754-def41f49.png" loading="lazy" style="width: 100%; height: 100%; object-fit: cover; border-radius: 50%;">
            </div>
            <div style="overflow: hidden; white-space: nowrap; flex: 1; text-align: center;">
                <span style="color: var(--primary-color); font-weight: 800; font-size: 0.75rem; text-transform: uppercase; margin-right: 10px;">SONANDO:</span>
                <span id="sticky-track-info" style="font-weight: 700; font-size: 0.9rem; color: #fff;">Lili Records Radio</span>
            </div>
        </div>
    </div>
    <style>
        @keyframes slideDown { from { transform: translateY(-100%); } to { transform: translateY(0); } }
        @keyframes shake {
            10%, 90% { transform: translate3d(-1px, 0, 0); }
            20%, 80% { transform: translate3d(2px, 0, 0); }
            30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
            40%, 60% { transform: translate3d(4px, 0, 0); }
        }
        @keyframes vip-flash {
            0% { background: #facc15; box-shadow: 0 0 10px #facc15; color: #000; }
            50% { background: #ff4444; box-shadow: 0 0 30px #ff4444; color: #fff; }
            100% { background: #facc15; box-shadow: 0 0 10px #facc15; color: #000; }
        }
        .vip-alert-banner {
            display: none;
            background: #facc15;
            color: #000;
            padding: 12px 20px;
            border-radius: 16px;
            font-weight: 900;
            font-size: 0.9rem;
            margin-bottom: 15px;
            text-align: center;
            animation: vip-flash 0.8s infinite ease-in-out;
            border: 2px solid rgba(255,255,255,0.5);
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(0,0,0,0.3);
            text-transform: uppercase;
            letter-spacing: 1px;
        }
    </style>

    <div class="app-container">
        <!-- Left Section: Player -->
        <section class="player-section">
            <div class="glass-card">
                <header class="brand">
                    <div style="position: absolute; top: 1rem; right: 1rem; display: flex; gap: 0.5rem; z-index: 100;">
                        <button onclick="openShopModal()" style="background: linear-gradient(135deg, #facc15, #fbbf24); border: none; color: #000; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 0 15px rgba(250, 204, 21, 0.4); transition: all 0.3s; z-index: 101;" title="Tienda de la Radio">
                            <i class="bi bi-shop"></i>
                        </button>
                        <button onclick="toggleTheme()" id="theme-toggle" style="background: var(--glass-bg); border: 1px solid var(--glass-border); color: var(--text-color); width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; backdrop-filter: blur(5px); transition: all 0.3s;" title="Cambiar modo claro/oscuro">
                            <i class="bi bi-moon-fill"></i>
                        </button>
                        <a href="history.php" style="background: var(--glass-bg); border: 1px solid var(--glass-border); color: var(--text-color); width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; backdrop-filter: blur(5px); transition: all 0.3s; text-decoration: none;" title="Historial de canciones">
                            <i class="bi bi-clock-history"></i>
                        </a>
                    </div>
                    <div class="logo-wrapper">
                        <img src="./assets/pasted-20260215-163754-def41f49.png" alt="Lili Records Logo" class="brand-logo" loading="lazy">
                        <img src="./assets/pasted-20260215-171328-d90df4ce.jpg" alt="Logo Secundario" class="brand-logo" loading="lazy">
                    </div>
                    <h1>Lili Records</h1>
                    <p>Siente la música, vive el ritmo.</p>
                    <div style="display: flex; justify-content: center; margin-top: 1rem;">
                        <div class="theme-switch-wrapper" onclick="toggleTheme()" style="display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,0.05); padding: 5px 15px; border-radius: 20px; cursor: pointer; border: 1px solid var(--glass-border); transition: all 0.3s;">
                            <i class="bi bi-sun-fill" style="font-size: 0.9rem; color: #facc15;"></i>
                            <div style="width: 40px; height: 20px; background: rgba(255,255,255,0.2); border-radius: 10px; position: relative;">
                                <div id="theme-switch-dot" style="position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; background: white; border-radius: 50%; transition: all 0.3s;"></div>
                            </div>
                            <i class="bi bi-moon-fill" style="font-size: 0.9rem; color: #94a3b8;"></i>
                            <span style="font-size: 0.7rem; font-weight: 700; text-transform: uppercase; margin-left: 5px;">Modo Oscuro</span>
                        </div>
                    </div>
                </header>

                <div class="radio-player">
                    <!-- Top Listener of the Week Banner -->
                    <div id="top-listener-section" style="display: none;">
                        <div class="top-listener-banner">
                            <div class="top-listener-crown">
                                <i class="bi bi-crown-fill"></i>
                            </div>
                            <div style="flex: 1;">
                                <span class="top-listener-label">Oyente de la Semana</span>
                                <div id="top-listener-display" class="top-listener-name">Cargando...</div>
                            </div>
                            <div style="font-size: 0.7rem; opacity: 0.6; font-weight: 700; text-transform: uppercase;">
                                <i class="bi bi-graph-up-arrow"></i> #1 Ranking
                            </div>
                        </div>
                    </div>

                    <div class="visualizer-container">
                        <div id="audio-visualizer" class="audio-visualizer"></div>
                    </div>
                    <div class="now-playing">
                        <div class="track-cover-container">
                            <i id="cover-placeholder" class="bi bi-broadcast"></i>
                            <img id="track-cover" src="./assets/pasted-20260215-163754-def41f49.png" alt="Cover" crossorigin="anonymous" loading="lazy" onerror="this.style.display='none'; document.getElementById('cover-placeholder').style.display='block';">
                        </div>
                        <div class="track-info">
                        <div id="dj-vip-alert" class="vip-alert-banner" onclick="scrollToRequests()">
                            <i class="bi bi-lightning-charge-fill"></i> ¡SALTO VIP PENDIENTE! PONLO AHORA 🎧
                        </div>
                        <div id="dj-host-container" style="display: flex; align-items: center; gap: 8px;">
                                <div class="dj-badge" onclick="adminOpenShoutout()" style="cursor: pointer;" title="DJ Panel (Admin)"><i class="bi bi-mic-fill"></i> <span id="current-dj-name">LILI</span></div>
                                <button id="test-tictac-btn" onclick="testTicTac()" style="display: none; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); color: white; font-size: 0.6rem; padding: 2px 8px; border-radius: 10px; font-weight: 800; cursor: pointer; transition: all 0.3s;" title="Probar sonido Tic-Tac">
                                    <i class="bi bi-clock"></i> TEST TIC-TAC
                                </button>
                                <button id="test-applause-btn" onclick="testApplause()" style="display: none; background: rgba(244, 114, 182, 0.2); border: 1px solid #f472b6; color: #f472b6; font-size: 0.6rem; padding: 2px 8px; border-radius: 10px; font-weight: 800; cursor: pointer; transition: all 0.3s; margin-left: 5px;" title="Probar sonido Aplausos">
                                    <i class="bi bi-megaphone"></i> TEST APPLAUSE
                                </button>
                                <div id="dj-flash-poll-control" style="display: none; margin-bottom: 8px;">
                                    <button onclick="promptFlashPoll()" style="background: rgba(250, 204, 21, 0.2); border: 1px solid #facc15; color: #facc15; font-size: 0.6rem; padding: 2px 8px; border-radius: 10px; font-weight: 800; cursor: pointer; transition: all 0.3s;" title="Lanzar Encuesta Flash">
                                        <i class="bi bi-lightning-fill"></i> PREGUNTA FLASH
                                    </button>
                                </div>
                                <div id="dj-energy-thermometer" class="energy-thermometer-container" title="Energía para la Fiesta Total">
                                    <span id="energy-text" class="energy-status-label">Cargando hype...</span>
                                    <div class="energy-thermometer">
                                        <div id="energy-fill" class="energy-fill"></div>
                                    </div>
                                </div>
                            </div>
                            <span class="track-label">ESTÁS ESCUCHANDO:</span>
                            <div id="track-title" class="track-title" onclick="copyTrackTitle()" title="Toca para copiar">Cargando stream...</div>
                            <div id="track-artist" class="track-artist" style="font-size: 0.95rem; font-weight: 600; opacity: 0.8; color: var(--primary-color); text-transform: uppercase; letter-spacing: 1px; margin-top: 2px;">Lili Records Radio</div>
                            <div id="track-album" style="font-size: 0.8rem; opacity: 0.6; color: #fff; margin-top: 2px; display: none; font-style: italic;"></div>
                            <div class="track-status" style="margin-top: 5px; display: flex; align-items: center; gap: 5px; font-size: 0.75rem;">
                                <span style="width: 8px; height: 8px; background: #ff4444; border-radius: 50%; display: inline-block; animation: pulse 1.5s infinite;"></span>
                                EN VIVO
                            </div>
                            <div id="track-progress-container" style="width: 100%; height: 4px; background: rgba(255,255,255,0.1); border-radius: 2px; margin-top: 10px; display: none; overflow: hidden; box-shadow: inset 0 1px 2px rgba(0,0,0,0.2);">
                                <div id="track-progress-bar" style="height: 100%; background: linear-gradient(90deg, var(--primary-color), var(--accent-color)); width: 0%; transition: width 1s linear;"></div>
                            </div>
                            <a id="lyrics-link" href="lyrics.php" style="font-size: 0.7rem; color: var(--primary-color); text-decoration: none; margin-top: 8px; display: none; align-items: center; gap: 4px; opacity: 0.8; transition: opacity 0.2s;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0.8'">
                                <i class="bi bi-music-note-list"></i> VER LETRA
                            </a>
                            <div id="share-links-container" style="display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px;">
                                <a id="whatsapp-share-track" href="#" target="_blank" style="font-size: 0.65rem; background: rgba(37, 211, 102, 0.1); border: 1px solid rgba(37, 211, 102, 0.3); color: #25D366; text-decoration: none; display: none; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-weight: 700; transition: all 0.3s;" onmouseover="this.style.background='rgba(37, 211, 102, 0.2)';" onmouseout="this.style.background='rgba(37, 211, 102, 0.1)';">
                                    <i class="bi bi-whatsapp"></i> COMPARTIR
                                </a>
                                <a id="facebook-share-track" href="#" target="_blank" style="font-size: 0.65rem; background: rgba(24, 119, 242, 0.1); border: 1px solid rgba(24, 119, 242, 0.3); color: #1877F2; text-decoration: none; display: none; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-weight: 700; transition: all 0.3s;" onmouseover="this.style.background='rgba(24, 119, 242, 0.2)';" onmouseout="this.style.background='rgba(24, 119, 242, 0.1)';">
                                    <i class="bi bi-facebook"></i> FACEBOOK
                                </a>
                                <a id="twitter-share-track" href="#" target="_blank" style="font-size: 0.65rem; background: rgba(29, 161, 242, 0.1); border: 1px solid rgba(29, 161, 242, 0.3); color: #1DA1F2; text-decoration: none; display: none; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-weight: 700; transition: all 0.3s;" onmouseover="this.style.background='rgba(29, 161, 242, 0.2)';" onmouseout="this.style.background='rgba(29, 161, 242, 0.1)';">
                                    <i class="bi bi-twitter-x"></i> POSTEAR
                                </a>
                                <a id="instagram-share-track" href="https://www.instagram.com/" target="_blank" style="font-size: 0.65rem; background: rgba(225, 48, 108, 0.1); border: 1px solid rgba(225, 48, 108, 0.3); color: #E1306C; text-decoration: none; display: none; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-weight: 700; transition: all 0.3s;" onmouseover="this.style.background='rgba(225, 48, 108, 0.2)';" onmouseout="this.style.background='rgba(225, 48, 108, 0.1)';">
                                    <i class="bi bi-instagram"></i> INSTAGRAM
                                </a>
                            </div>
                        </div>
                        <button id="like-song-btn" onclick="likeSong()" style="background: none; border: none; color: #ff4444; font-size: 1.8rem; cursor: pointer; transition: transform 0.2s; display: flex; align-items: center; gap: 5px;">
                            <i class="bi bi-heart"></i>
                            <span id="like-count" style="font-size: 0.9rem; color: white; opacity: 0.8; font-weight: bold;"></span>
                        </button>
                        <button id="send-flowers-btn" onclick="sendFlowersToDJ()" style="background: none; border: none; color: #f472b6; font-size: 1.8rem; cursor: pointer; transition: transform 0.2s; display: flex; flex-direction: column; align-items: center; justify-content: center; margin-left: 10px;" title="Regalar flores al DJ">
                            <i class="bi bi-flower1"></i>
                            <span style="font-size: 0.6rem; color: white; opacity: 0.8; font-weight: bold; margin-top: -5px;">FLORES</span>
                        </button>
                    </div>

                    <div class="controls">
                        <button id="play-pause" class="play-btn" onclick="togglePlay()">
                            <i id="play-icon" class="bi bi-play-fill"></i>
                        </button>
                        <button id="dj-skip-btn" onclick="djSkipSong()" style="display: none; background: rgba(250, 204, 21, 0.2); border: 1px solid #facc15; color: #facc15; width: 45px; height: 45px; border-radius: 50%; align-items: center; justify-content: center; cursor: pointer; margin-left: 10px; transition: all 0.3s;" title="Saltar Canción (Poder DJ)">
                            <i class="bi bi-skip-forward-fill"></i>
                        </button>
                                                <i class="bi bi-volume-up"></i>
                        <input type="range" class="volume-slider" min="0" max="1" step="0.01" value="1" oninput="changeVolume(this.value)">
                        
                        <!-- Quality Selector -->
                        <div class="quality-selector-wrapper" style="display: flex; align-items: center; gap: 6px; background: rgba(255,255,255,0.08); padding: 6px 14px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.1); margin: 0 10px; transition: all 0.3s;">
                            <i class="bi bi-broadcast" style="font-size: 0.8rem; color: var(--primary-color);"></i>
                            <select id="audio-quality" onchange="changeQuality(this.value)" style="background: none; border: none; color: white; font-size: 0.75rem; font-weight: 700; cursor: pointer; outline: none; padding: 0; appearance: none; -webkit-appearance: none; text-align: center;">
                                <option value="high" style="background: #1a1a1a; color: white;">Alta (HD)</option>
                                <option value="low" style="background: #1a1a1a; color: white;">Ahorro (SD)</option>
                            </select>
                        </div>

                        <button id="sleep-timer-btn" onclick="openSleepModal()" 
 style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: white; width: 45px; height: 45px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s;" title="Temporizador de apagado">
                            <i class="bi bi-clock"></i>
                        </button>
                        <button id="report-issue-btn" onclick="openReportModal()" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #ff4444; width: 45px; height: 45px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s;" title="Reportar un problema">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                        </button>
                    </div>

                    <div id="sleep-countdown" style="display: none; text-align: center; margin-top: -0.5rem; font-size: 0.8rem; color: var(--accent-color); font-weight: bold; animation: fadeIn 0.5s;">
                        Apagado en: <span id="sleep-time-left">00:00</span>
                    </div>

                    <div id="upcoming-tracks-container" style="margin-top: 1.5rem; display: none; background: rgba(255, 255, 255, 0.02); padding: 1rem; border-radius: 16px; border: 1px solid rgba(255, 255, 255, 0.05);">
                        <span class="track-label" style="font-size: 0.65rem; margin-bottom: 0.8rem; color: var(--primary-color);">
                            <i class="bi bi-fast-forward-fill"></i> PRÓXIMAMENTE
                        </span>
                        <div id="upcoming-tracks-list" style="display: flex; flex-direction: column; gap: 0.6rem;"></div>
                    </div>

                    <div id="recent-tracks-container" style="margin-top: 1rem; display: none;">
                        <span class="track-label" style="font-size: 0.65rem; margin-bottom: 0.5rem;">CANCIONES ANTERIORES:</span>
                        <div id="recent-tracks-list" style="display: flex; flex-direction: column; gap: 0.5rem;"></div>
                    </div>

                    <div id="top-songs-container" style="margin-top: 1.5rem; background: rgba(255, 255, 255, 0.03); padding: 1rem; border-radius: 16px; border: 1px solid rgba(255, 255, 255, 0.05);">
                        <span class="track-label" style="font-size: 0.65rem; margin-bottom: 0.8rem; color: #facc15;">
                            <i class="bi bi-trophy-fill"></i> TOP CANCIONES DE LA SEMANA
                        </span>
                        <div id="top-songs-list" style="display: flex; flex-direction: column; gap: 0.6rem;">
                            <div style="font-size: 0.8rem; opacity: 0.5; text-align: center;">Cargando ranking...</div>
                        </div>
                    </div>

                    <div class="interaction-form">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="user-name">NOMBRE</label>
                                <input type="text" id="user-name" placeholder="Tu nombre..." oninput="this.style.borderColor='rgba(255, 255, 255, 0.2)'; if(this.value.length >= 3) { fetchLeaderboard(); saveUserInfo(); }">
                            </div>
                            
                            <div class="form-group">
                                <label for="user-phone">MOVIL</label>
                                <input type="tel" id="user-phone" placeholder="Tu número..." oninput="this.style.borderColor='rgba(255, 255, 255, 0.2)'" onchange="saveUserInfo()">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="user-message">MENSAJE</label>
                            <textarea id="user-message" placeholder="¿Qué quieres escuchar?"></textarea>
                        </div>
                        
                        <button onclick="sendToWhatsApp()" class="send-whatsapp-btn" style="width: 100%; border: none; text-decoration: none;">
                            <i class="bi bi-whatsapp"></i> PEDIR POR WHATSAPP
                        </button>
                    </div>

                    <!-- Fan of the Month Section -->
                    <div id="fan-of-the-month" style="margin-top: 2rem; background: linear-gradient(135deg, rgba(56, 189, 248, 0.1), rgba(0, 200, 83, 0.1)); padding: 1.5rem; border-radius: 24px; border: 1px solid var(--glass-border); display: flex; align-items: center; gap: 1rem; position: relative; overflow: hidden;">
                        <div style="position: absolute; top: -10px; right: -10px; font-size: 4rem; opacity: 0.05; transform: rotate(15deg); color: var(--accent-color);">
                            <i class="bi bi-star-fill"></i>
                        </div>
                        <?php
                        require_once __DIR__ . '/db/config.php';
                        try {
                            $fan = db()->query("SELECT * FROM fans WHERE is_fan_of_month = 1 LIMIT 1")->fetch();
                        } catch (Exception $e) {
                            $fan = null;
                        }
                        ?>
                        <div style="width: 60px; height: 60px; border-radius: 50%; border: 3px solid var(--accent-color); padding: 2px; background: var(--glass-bg);">
                            <img src="<?= $fan['photo'] ?? 'assets/pasted-20260215-163754-def41f49.png' ?>" alt="Fan of the Month" loading="lazy" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">
                        </div>
                        <div style="flex: 1;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="font-size: 0.65rem; font-weight: 800; color: var(--accent-color); letter-spacing: 2px; text-transform: uppercase;">Fan del Mes</span>
                                <a href="ranking.php" style="font-size: 0.6rem; color: var(--primary-color); text-decoration: none; font-weight: 700;">VER RANKING <i class="bi bi-chevron-right"></i></a>
                            </div>
                            <div style="font-size: 1.1rem; font-weight: 800; color: var(--text-color);"><?= htmlspecialchars($fan['name'] ?? 'Tú puedes ser el próximo') ?></div>
                            <div style="font-size: 0.75rem; opacity: 0.6;"><?= $fan['points'] ?? 0 ?> puntos de actividad</div>
                        </div>
                        <i class="bi bi-trophy-fill" style="font-size: 1.5rem; color: #facc15;"></i>
                    </div>

                    <!-- User Level Progress Section -->
                    <div id="user-progress-container" class="level-progress-container" style="display: none; margin-bottom: 1rem;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <span id="user-level-badge" class="level-badge">Nivel 1</span>
                                <span id="user-level-name" style="font-size: 0.85rem; font-weight: 700;">Novato</span>
                            </div>
                            <span id="user-points-display" style="font-size: 0.75rem; opacity: 0.7;">0 / 100 pts</span>
                        </div>
                        <div class="level-bar-bg">
                            <div id="user-level-bar" class="level-bar-fill"></div>
                        </div>
                        
                        <!-- Loyalty Wallet & Store -->
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 1rem; padding-top: 0.8rem; border-top: 1px solid rgba(255,255,255,0.05);">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="width: 35px; height: 35px; background: rgba(0, 230, 118, 0.1); border: 1px solid rgba(0, 230, 118, 0.3); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #00e676; font-size: 1.2rem;">
                                    <i class="bi bi-coin"></i>
                                </div>
                                <div>
                                    <div style="font-size: 0.6rem; opacity: 0.6; text-transform: uppercase; font-weight: 700; letter-spacing: 1px;">Loyalty Points</div>
                                    <div id="loyalty-points-display" style="font-size: 1.1rem; font-weight: 800; color: #00e676;">0 LP</div>
                                </div>
                            </div>
                            <button onclick="openShopModal()" style="background: linear-gradient(135deg, #00e676, #00c853); color: white; border: none; padding: 6px 15px; border-radius: 50px; font-size: 0.7rem; font-weight: 800; display: flex; align-items: center; gap: 5px; cursor: pointer; box-shadow: 0 4px 15px rgba(0, 230, 118, 0.3);">
                                <i class="bi bi-cart-fill"></i> TIENDA
                            </button>
                        </div>

                        <div id="unlocked-rewards-msg" class="unlocked-reward">
                            <i class="bi bi-unlock-fill"></i> Siguiente: Color de chat azul
                        </div>
                    </div>

                    <!-- Espacio para Código QR -->
                    <div class="payment-section">
                        <div class="qr-placeholder" style="padding: 0; overflow: hidden; background: rgba(255,255,255,0.1);" onclick="openQRModal()">
                            <img src="./assets/pasted-20260216-203652-f5645ae9.jpg" alt="Código QR" loading="lazy" style="width: 100%; height: 100%; object-fit: contain; border-radius: 12px;">
                        </div>
                        <p style="color: var(--accent-color); font-size: 0.9rem; font-weight: 600; margin-top: 0.5rem; text-transform: uppercase;">
                            Contribuye con tu ayuda a nuestra Web App
                        </p>
                    </div>
                </div>
            </div>

            <?php if (isset($_GET['admin']) && $_GET['admin'] === '1'): ?>
            <!-- Admin Real-Time Stats (Only visible with ?admin=1) -->
            <div class="glass-card mt-4" style="margin-top: 2rem;">
                <h3 style="font-size: 1.2rem; margin-bottom: 1rem; color: var(--accent-color);">
                    <i class="bi bi-shield-lock"></i> Panel Admin Real-Time
                </h3>
                
                <!-- On-Air Announcement Section -->
                <div style="background: rgba(37, 211, 102, 0.1); border: 1px solid rgba(37, 211, 102, 0.3); padding: 1.5rem; border-radius: 20px; margin-bottom: 1.5rem; text-align: center;">
                    <h4 style="color: #25D366; font-size: 1rem; margin-top: 0;"><i class="bi bi-broadcast"></i> Anunciar "Al Aire"</h4>
                    <p style="font-size: 0.8rem; opacity: 0.8; margin-bottom: 1rem;">Envía un mensaje a tus contactos de WhatsApp para invitarlos a la emisora.</p>
                    <button onclick="announceOnAir()" style="background: #25D366; color: white; border: none; padding: 12px 24px; border-radius: 50px; font-weight: 800; cursor: pointer; display: flex; align-items: center; gap: 10px; margin: 0 auto; transition: all 0.3s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
                        <i class="bi bi-whatsapp"></i> ANUNCIAR POR WHATSAPP
                    </button>
                </div>

                <iframe src="admin.php?token=lili_admin_2026" style="width: 100%; height: 400px; border: none; border-radius: 12px; background: rgba(0,0,0,0.2);"></iframe>
            </div>
            <?php endif; ?>
        </section>

        <!-- Interaction Center: Live Chat -->
        <section class="interaction-center">
            <!-- New Dedicated Request Section -->
            <div class="glass-card mb-4" style="margin-bottom: 1.5rem; background: linear-gradient(135deg, rgba(56, 189, 248, 0.1), rgba(0, 200, 83, 0.1)); border-color: var(--primary-color);">
                <h3 style="font-size: 1.3rem; margin-bottom: 1rem; color: #fff; display: flex; align-items: center; gap: 10px;">
                    <i class="bi bi-music-note-beamed" style="color: var(--primary-color);"></i> ¿QUÉ QUIERES ESCUCHAR?
                </h3>
                <p style="font-size: 0.8rem; opacity: 0.8; margin-bottom: 1.2rem;">Envía tu petición o saludo. ¡Te leeremos en vivo y te notificaremos por email!</p>
                <div class="interaction-form" style="margin-top: 0;">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="req-artist-new">ARTISTA</label>
                            <input type="text" id="req-artist-new" placeholder="Ej: Bad Bunny">
                        </div>
                        <div class="form-group">
                            <label for="req-song-new">CANCIÓN / SALUDO</label>
                            <input type="text" id="req-song-new" placeholder="Ej: Tití Me Preguntó">
                        </div>
                    </div>
                    <div style="display: flex; gap: 1rem; margin-top: 1rem;">
                        <button onclick="submitSongRequestNew()" id="submit-req-btn-new" style="flex: 2; background: var(--primary-color); color: white; border: none; padding: 1rem; border-radius: 12px; font-weight: 800; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 0.8rem; transition: all 0.3s; box-shadow: 0 4px 15px rgba(56, 189, 248, 0.3);">
                            <i class="bi bi-send-check-fill"></i> ENVIAR PETICIÓN
                        </button>
                        <button onclick="submitVipJump()" id="vip-jump-btn" style="flex: 1; background: linear-gradient(135deg, #00e676, #00c853); color: white; border: none; padding: 1rem; border-radius: 12px; font-weight: 800; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 0.5rem; transition: all 0.3s; box-shadow: 0 4px 15px rgba(0, 230, 118, 0.3);" title="Paga 500 LP para sonar ya">
                            <i class="bi bi-lightning-charge-fill"></i> VIP JUMP
                        </button>
                    </div>
                </div>
            </div>

            <!-- Live Web Chat -->
            <div class="glass-card chat-window" style="height: 500px; display: flex; flex-direction: column;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                    <h3 style="font-size: 1.2rem; margin: 0; color: var(--primary-color);">
                        <i class="bi bi-chat-dots-fill"></i> CHAT EN VIVO
                    </h3>
                    <button id="mute-chat-btn" onclick="toggleChatSound()" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s;" title="Silenciar/Activar sonido del chat">
                        <i class="bi bi-volume-up-fill"></i>
                    </button>
                </div>
                <div id="pinned-message" class="pinned-message-container">
                    <div class="pinned-label"><i class="bi bi-pin-angle-fill"></i> MENSAJE FIJADO</div>
                    <div id="pinned-content" style="font-size: 0.85rem; font-weight: 600;"></div>
                    <div id="pinned-author" style="font-size: 0.65rem; opacity: 0.7; margin-top: 4px;"></div>
                </div>
                <div id="chat-messages" style="flex: 1; overflow-y: auto; margin-bottom: 1rem; padding-right: 5px; display: flex; flex-direction: column; gap: 0.8rem;">
                    <!-- Mensajes se cargarán aquí -->
                    <div style="opacity: 0.5; font-size: 0.9rem; text-align: center; margin-top: 2rem;">Cargando mensajes...</div>
                </div>
                <div id="dj-reaction-area" class="reaction-buttons" style="display: none; flex-direction: column; align-items: center; margin-bottom: 15px; border-radius: 20px; padding: 12px;">
                    <span style="font-size: 0.65rem; font-weight: 800; color: #facc15; text-transform: uppercase; margin-bottom: 8px; letter-spacing: 1px; opacity: 0.9;">¡Celebra con el DJ! 👇</span>
                    <div style="display: flex; gap: 12px;">
                        <button class="reaction-btn" onclick="sendReaction('❤️')" title="¡Me encanta!">❤️</button>
                        <button class="reaction-btn" onclick="sendReaction('🔥')" title="¡Fuego!">🔥</button>
                        <button class="reaction-btn" onclick="sendReaction('🎉')" title="¡Celebrar!">🎉</button>
                        <button class="reaction-btn" onclick="sendReaction('🎧')" title="¡Ese DJ!">🎧</button>
                        <button class="reaction-btn" onclick="sendReaction('🙌')" title="¡Subidón!">🙌</button>
                    </div>
                </div>
                <div class="chat-input-area" style="display: flex; gap: 0.5rem; position: relative;">
                    <input type="hidden" id="chat-user">
                    <button onclick="toggleEmojiPicker()" style="background: rgba(255,255,255,0.1); border: none; border-radius: 8px; color: white; padding: 0 0.5rem; cursor: pointer;">
                        <i class="bi bi-emoji-smile"></i>
                    </button>
                    <button id="camera-btn" onclick="document.getElementById('chat-file').click()" title="Subir foto" style="background: rgba(255,255,255,0.1); border: none; border-radius: 8px; color: white; padding: 0 0.5rem; cursor: pointer; position: relative; transition: all 0.3s;">
                        <i class="bi bi-camera-fill"></i>
                        <span id="photo-counter" style="position: absolute; top: -10px; right: -5px; background: var(--primary-color); color: white; font-size: 0.6rem; padding: 1px 4px; border-radius: 10px; font-weight: bold; border: 1px solid rgba(255,255,255,0.3); display: none;">0/5</span>
                    </button>
                    <div id="photo-limit-msg" style="display: none; position: absolute; bottom: -20px; left: 0; width: 100%; text-align: center; font-size: 0.65rem; color: #ff4444; font-weight: bold; animation: fadeIn 0.3s;"></div>
                    <input type="file" id="chat-file" style="display: none;" accept="image/*" onchange="uploadImage(this)">
                    <input type="text" id="chat-msg" placeholder="Escribe un mensaje..." style="flex: 1; font-size: 0.8rem; padding: 0.5rem; border-radius: 8px; border: none; background: rgba(255,255,255,0.05); color: white;">
                    <button onclick="sendChatMessage()" style="background: var(--primary-color); border: none; border-radius: 8px; color: white; padding: 0 1rem; cursor: pointer;">
                        <i class="bi bi-send-fill"></i>
                    </button>

                    <emoji-picker id="emoji-picker" style="display: none; position: absolute; bottom: 50px; left: 0; z-index: 1000; --num-columns: 6; --category-button-size: 1.5rem; width: 300px; height: 350px;"></emoji-picker>
                </div>
            </div>

            <!-- Song Requests Live List -->
            <div class="glass-card mt-4" style="margin-top: 1.5rem;">
                <h3 style="font-size: 1.2rem; margin-bottom: 1rem; color: var(--accent-color);">
                    <i class="bi bi-music-note-beamed"></i> PETICIONES EN VIVO
                </h3>
                <div id="song-requests-list" class="request-list">
                    <div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 2rem;">No hay peticiones recientes.</div>
                </div>
            </div>

            <!-- Online Users Widget -->
            <div class="glass-card mt-4" style="margin-top: 1.5rem; background: linear-gradient(135deg, rgba(37, 211, 102, 0.05), rgba(0, 0, 0, 0.1)); border: 1px solid rgba(37, 211, 102, 0.2);">
                <h3 style="font-size: 1.2rem; margin-bottom: 0.5rem; color: #25D366;">
                    <i class="bi bi-people-fill"></i> CLIENTES CONECTADOS
                </h3>
                <p style="font-size: 0.75rem; opacity: 0.7; margin-bottom: 1rem;">Habla directamente con otros oyentes por WhatsApp.</p>
                <div id="online-users-list" style="display: flex; flex-direction: column; gap: 0.8rem;">
                    <div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 1rem;">Cargando usuarios...</div>
                </div>
            </div>

            <!-- Gallery Widget -->
            <div class="glass-card mt-4" style="margin-top: 1.5rem;">
                <h3 style="font-size: 1.2rem; margin-bottom: 0.5rem; color: #ffca28;">
                    <i class="bi bi-images"></i> GALERÍA COMUNIDAD
                </h3>
                <p style="font-size: 0.75rem; opacity: 0.7; margin-bottom: 1rem;">Fotos compartidas por nuestros oyentes.</p>
                <div id="gallery-container" class="gallery-grid">
                    <div style="grid-column: 1/-1; text-align: center; padding: 2rem; opacity: 0.5; font-size: 0.85rem;">Cargando galería...</div>
                </div>
            </div>

            <!-- Social Media Feed Widget -->
            <div class="glass-card mt-4" style="margin-top: 1.5rem;">
                <h3 style="font-size: 1.2rem; margin-bottom: 1rem; color: #f472b6;">
                    <i class="bi bi-share-fill"></i> SÍGUENOS EN REDES
                </h3>
                <div class="social-card">
                    <div class="social-card-grid">
                        <a href="<?= $facebook_link ?>" target="_blank" class="social-card-item fb">
                            <i class="bi bi-facebook"></i>
                            <div class="social-card-info">
                                <span class="social-card-name">Facebook</span>
                                <span class="social-card-handle">Lili Records</span>
                            </div>
                        </a>
                        <a href="<?= $instagram_link ?>" target="_blank" class="social-card-item ig">
                            <i class="bi bi-instagram"></i>
                            <div class="social-card-info">
                                <span class="social-card-name">Instagram</span>
                                <span class="social-card-handle">@lilirecords</span>
                            </div>
                        </a>
                        <a href="<?= $youtube_link ?>" target="_blank" class="social-card-item yt">
                            <i class="bi bi-youtube"></i>
                            <div class="social-card-info">
                                <span class="social-card-name">YouTube</span>
                                <span class="social-card-handle">Lili Records TV</span>
                            </div>
                        </a>
                        <a href="<?= $twitter_link ?>" target="_blank" class="social-card-item tw">
                            <i class="bi bi-twitter-x"></i>
                            <div class="social-card-info">
                                <span class="social-card-name">X (Twitter)</span>
                                <span class="social-card-handle">@lilirecords</span>
                            </div>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Fan Leaderboard Widget -->
            <div class="glass-card mt-4" style="margin-top: 1.5rem;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                    <h3 style="font-size: 1.2rem; margin: 0; color: var(--primary-color);">
                        <i class="bi bi-trophy-fill"></i> TOP FANS
                    </h3>
                    <a href="ranking.php" style="font-size: 0.75rem; color: var(--accent-color); text-decoration: none; font-weight: 700;">VER TODO <i class="bi bi-arrow-right"></i></a>
                </div>
                <div id="leaderboard-list" class="leaderboard-list">
                    <div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 1rem;">Cargando ranking...</div>
                </div>
                <div style="margin-top: 1rem; font-size: 0.65rem; opacity: 0.5; text-align: center; font-style: italic;">
                    Suma puntos participando en el chat y pidiendo canciones.
                </div>
            </div>
        </section>

    </div>

    <!-- Sleep Timer Modal -->
    <div id="sleep-modal" class="sleep-modal" onclick="closeSleepModal()">
        <div class="sleep-modal-content" onclick="event.stopPropagation()">
            <h3 style="margin-top: 0; color: var(--primary-color);">Temporizador</h3>
            <p style="opacity: 0.7; font-size: 0.9rem; margin-bottom: 1.5rem;">La radio se detendrá automáticamente.</p>
            
            <div class="sleep-option" onclick="setSleepTimer(15)">
                <span>15 Minutos</span>
                <i class="bi bi-chevron-right"></i>
            </div>
            <div class="sleep-option" onclick="setSleepTimer(30)">
                <span>30 Minutos</span>
                <i class="bi bi-chevron-right"></i>
            </div>
            <div class="sleep-option" onclick="setSleepTimer(60)">
                <span>60 Minutos</span>
                <i class="bi bi-chevron-right"></i>
            </div>
            <div id="cancel-sleep-option" class="sleep-option" onclick="setSleepTimer(0)" style="margin-top: 2rem; border-color: #ff4444; color: #ff4444; display: none;">
                <span>Desactivar</span>
                <i class="bi bi-x-circle"></i>
            </div>
            
            <button onclick="closeSleepModal()" style="margin-top: 1.5rem; background: none; border: none; color: white; opacity: 0.5; cursor: pointer;">Cerrar</button>
        </div>
    </div>

    <!-- Report Issue Modal -->
    <div id="report-modal" class="sleep-modal" onclick="closeReportModal()">
        <div class="sleep-modal-content" onclick="event.stopPropagation()" style="max-width: 450px;">
            <h3 style="margin-top: 0; color: #ff4444;">Reportar un Problema</h3>
            <p style="opacity: 0.7; font-size: 0.9rem; margin-bottom: 1.5rem;">Cuéntanos qué está fallando para poder arreglarlo.</p>
            
            <div class="interaction-form" style="margin-top: 0;">
                <div class="form-group" style="margin-bottom: 1rem;">
                    <label for="report-issue-type">TIPO DE PROBLEMA</label>
                    <select id="report-issue-type" style="width: 100%; padding: 0.8rem; border-radius: 12px; border: 1px solid var(--glass-border); background-color: var(--glass-bg); color: var(--text-color); font-family: inherit; font-size: 0.95rem; outline: none; backdrop-filter: blur(4px);">
                        <option value="Audio cortado">Audio se corta</option>
                        <option value="No carga el stream">No carga el stream</option>
                        <option value="Metadata incorrecta">Canción/Artista incorrecto</option>
                        <option value="Problema en el chat">Problema en el chat</option>
                        <option value="Otro">Otro problema</option>
                    </select>
                </div>
                <div class="form-group" style="margin-bottom: 1.5rem;">
                    <label for="report-description">DESCRIPCIÓN</label>
                    <textarea id="report-description" placeholder="Describe brevemente el problema..." style="height: 100px;"></textarea>
                </div>
                <button onclick="submitReport()" id="submit-report-btn" class="send-whatsapp-btn" style="background-color: #ff4444; width: 100%;">
                    <i class="bi bi-megaphone-fill"></i> ENVIAR REPORTE
                </button>
            </div>
            
            <button onclick="closeReportModal()" style="margin-top: 1.5rem; background: none; border: none; color: white; opacity: 0.5; cursor: pointer;">Cancelar</button>
        </div>
    </div>

    <!-- Flowers Modal -->
    <div id="flowers-modal" class="sleep-modal" onclick="closeFlowersModal()">
        <div class="sleep-modal-content" onclick="event.stopPropagation()" style="max-width: 450px;">
            <h3 style="margin-top: 0; color: #f472b6;"><i class="bi bi-flower1"></i> Regalar Flores</h3>
            <p style="opacity: 0.7; font-size: 0.9rem; margin-bottom: 1.5rem;">Envía un ramo de flores al DJ y personaliza tu mensaje.</p>
            
            <div class="interaction-form" style="margin-top: 0;">
                <div class="form-group" style="margin-bottom: 1.5rem;">
                    <label for="flower-message">MENSAJE PERSONALIZADO</label>
                    <textarea id="flower-message" placeholder="Escribe algo bonito para el DJ..." style="height: 80px;"></textarea>
                </div>
                <button onclick="confirmSendFlowers()" id="confirm-flowers-btn" class="send-whatsapp-btn" style="background-color: #f472b6; width: 100%;">
                    <i class="bi bi-send-fill"></i> ENVIAR POR 100 PTS
                </button>
            </div>
            
            <button onclick="closeFlowersModal()" style="margin-top: 1.5rem; background: none; border: none; color: white; opacity: 0.5; cursor: pointer;">Cancelar</button>
        </div>
    </div>

    <!-- Floating Social Links -->
    <div class="social-float-container">
        <a href="<?= $facebook_link ?>" class="social-float facebook" target="_blank" title="Facebook">
            <i class="bi bi-facebook"></i>
        </a>
        <a href="<?= $youtube_link ?>" class="social-float youtube" target="_blank" title="YouTube">
            <i class="bi bi-youtube"></i>
        </a>
        <a href="<?= $whatsapp_link ?>" class="social-float whatsapp" target="_blank" title="WhatsApp">
            <i class="bi bi-whatsapp"></i>
        </a>
    </div>

    <!-- QR Modal -->
    <div id="qr-modal" class="qr-modal" onclick="closeQRModal()">
        <div class="qr-modal-content" onclick="event.stopPropagation()">
            <span class="qr-modal-close" onclick="closeQRModal()">&times;</span>
            <img src="./assets/pasted-20260216-203652-f5645ae9.jpg" alt="QR Ampliado" loading="lazy" style="width: 100%; max-width: 400px; height: auto; border-radius: 12px; display: block; margin: 0 auto;">
            <p style="color: #333; text-align: center; margin-top: 1rem; font-weight: 700; font-size: 1.1rem;">¡ÚNETE A NUESTRO WHATSAPP!</p>
        </div>
    </div>

    <!-- Lightbox for Gallery -->
    <div id="lightbox" class="lightbox" onclick="closeLightbox()">
        <span class="lightbox-close" onclick="closeLightbox()">&times;</span>
        <img id="lightbox-img" class="lightbox-img" src="" alt="Full view">
        <div class="lightbox-info">
            <h4 id="lightbox-username" style="margin: 0; color: var(--primary-color);"></h4>
            <p id="lightbox-caption" style="margin: 5px 0 0; opacity: 0.8;"></p>
        </div>
    </div>

    <!-- Shop Modal -->
    <div id="shop-modal" class="shop-modal" onclick="closeShopModal()">
        <div class="shop-modal-content" onclick="event.stopPropagation()">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 style="margin: 0; color: #facc15;"><i class="bi bi-shop"></i> Tienda Radio</h2>
                <div style="text-align: right;">
                    <div id="shop-user-points" style="background: rgba(56, 189, 248, 0.2); color: #38bdf8; padding: 2px 12px; border-radius: 20px; font-weight: 800; font-size: 0.8rem; margin-bottom: 5px;">
                        0 PTS
                    </div>
                    <div id="shop-user-loyalty" style="background: rgba(0, 230, 118, 0.2); color: #00e676; padding: 2px 12px; border-radius: 20px; font-weight: 800; font-size: 0.8rem;">
                        0 LP
                    </div>
                </div>
            </div>
            
            <p style="opacity: 0.7; font-size: 0.9rem; margin-bottom: 2rem;">Gasta tus puntos en perks globales para todos los oyentes.</p>

            <div class="shop-item" onclick="promptBuyPinnedMessage()">
                <div class="shop-item-icon"><i class="bi bi-pin-angle-fill"></i></div>
                <div class="shop-item-info">
                    <div class="shop-item-name">Mensaje Fijado</div>
                    <div class="shop-item-desc">Tu mensaje al inicio del chat por 1 hora.</div>
                </div>
                <div class="shop-item-price">500 <i class="bi bi-lightning-fill"></i></div>
            </div>

            <div class="shop-item" onclick="promptBuyBackground()">
                <div class="shop-item-icon"><i class="bi bi-image-fill"></i></div>
                <div class="shop-item-info">
                    <div class="shop-item-name">Cambiar Fondo</div>
                    <div class="shop-item-desc">Cambia el fondo de la radio por 30 min.</div>
                </div>
                <div class="shop-item-price">1000 <i class="bi bi-lightning-fill"></i></div>
            </div>

            <div class="shop-item" onclick="promptBuyGodMode()">
                <div class="shop-item-icon" style="color: #facc15;"><i class="bi bi-stars"></i></div>
                <div class="shop-item-info">
                    <div class="shop-item-name">Modo Dios</div>
                    <div class="shop-item-desc">Colores personalizados para tu nombre en el chat.</div>
                </div>
                <div class="shop-item-price">500 <i class="bi bi-heart-fill" style="color: #00e676;"></i></div>
            </div>

            <div class="shop-item" onclick="promptBuyDjDay()">
                <div class="shop-item-icon" style="color: #f472b6;"><i class="bi bi-headphones"></i></div>
                <div class="shop-item-info">
                    <div class="shop-item-name">DJ por un día</div>
                    <div class="shop-item-desc">Nombre dorado y estatus de DJ Invitado.</div>
                </div>
                <div class="shop-item-price">2000 <i class="bi bi-heart-fill" style="color: #00e676;"></i></div>
            </div>

            <div class="shop-item" onclick="promptBuyVipJump()">
                <div class="shop-item-icon" style="color: #00e676;"><i class="bi bi-lightning-charge-fill"></i></div>
                <div class="shop-item-info">
                    <div class="shop-item-name">Salto VIP</div>
                    <div class="shop-item-desc">Tu canción suena inmediatamente saltando la cola.</div>
                </div>
                <div class="shop-item-price">500 <i class="bi bi-heart-fill" style="color: #00e676;"></i></div>
            </div>

            <button onclick="closeShopModal()" style="width: 100%; margin-top: 1.5rem; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: white; padding: 0.8rem; border-radius: 12px; cursor: pointer; font-weight: 700;">Cerrar Tienda</button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
    <!-- Celebration Overlay -->
    <div id="celebration-overlay"></div>

    <!-- Flash Poll Overlay -->
    <div id="flash-poll-container">
        <div style="font-size: 0.7rem; color: #facc15; font-weight: 800; text-transform: uppercase; margin-bottom: 5px; letter-spacing: 2px;">
            <i class="bi bi-lightning-fill"></i> Pregunta Flash del DJ
        </div>
        <div id="poll-question" class="poll-question">¿Qué canción prefieren para cerrar el set?</div>
        <div style="font-size: 0.65rem; color: #00e676; margin-bottom: 10px; font-weight: 700;">🎁 ¡RESPONDE Y GANA +10 LOYALTY POINTS!</div>
        <div class="poll-options">
            <button class="poll-btn" onclick="answerFlashPoll('SÍ')">¡SÍ! 🔥</button>
            <button class="poll-btn" onclick="answerFlashPoll('NO')">¡NO! 🎧</button>
        </div>
        <div class="poll-timer-bar">
            <div id="poll-timer-fill" class="poll-timer-fill"></div>
        </div>
    </div>

    <!-- Shoutout Modal -->
    <div id="shoutout-modal" class="shoutout-modal" onclick="this.classList.remove('show'); setTimeout(() => this.style.display = 'none', 500)">
        <div class="shoutout-card" onclick="event.stopPropagation()">
            <div class="shoutout-icon"><i class="bi bi-megaphone-fill"></i></div>
            <div class="shoutout-title">¡Mención Especial!</div>
            <div id="shoutout-target" style="font-size: 1.5rem; color: #facc15; font-weight: 800; margin-bottom: 1rem;"></div>
            <div id="shoutout-message" class="shoutout-msg"></div>
            <div class="shoutout-dj">— Con cariño, <span id="shoutout-dj-name">Lili</span> —</div>
            <button onclick="document.getElementById('shoutout-modal').classList.remove('show'); setTimeout(() => document.getElementById('shoutout-modal').style.display = 'none', 500)" style="margin-top: 2rem; background: var(--primary-color); border: none; color: black; padding: 10px 30px; border-radius: 20px; font-weight: 800; cursor: pointer; transition: all 0.3s;">
                ¡GRACIAS!
            </button>
        </div>
    </div>

    <audio id="radio-audio" src="https://play.radioking.io/classic-rock-radio92" preload="none" crossorigin="anonymous"></audio>
    <audio id="welcome-sound" src="https://assets.mixkit.co/active_storage/sfx/2013/2013-preview.mp3" preload="none"></audio>
    <audio id="pop-sound" src="https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3" preload="none"></audio>
    <audio id="dj-power-sound" src="https://assets.mixkit.co/active_storage/sfx/2862/2862-preview.mp3" preload="none"></audio>

    <script>
        const isAdmin = <?php echo isset($_GET['admin']) && $_GET['admin'] === '1' ? 'true' : 'false'; ?>;
        const audio = document.getElementById('radio-audio');
        const playBtn = document.getElementById('play-pause');
        const playIcon = document.getElementById('play-icon');
        const trackTitle = document.getElementById('track-title');
        const trackArtist = document.getElementById('track-artist');
        const trackAlbum = document.getElementById('track-album');
        const lyricsLink = document.getElementById('lyrics-link');
        const trackCover = document.getElementById('track-cover');
        const coverPlaceholder = document.getElementById('cover-placeholder');
        const visualizerContainer = document.getElementById('audio-visualizer');
        const glassCard = document.querySelector('.glass-card');
        const trackLabel = document.querySelector('.track-label');
        const socialIcons = document.querySelectorAll('.social-float');

        let audioCtx;
        let analyzer;
        let source;
        let animationId;
        const BAR_COUNT = 16;
        let visualizerBars = [];
        let visualizerPeaks = [];
        let barHeights = new Array(BAR_COUNT).fill(5);
        let peakHeights = new Array(BAR_COUNT).fill(5);
        const bg = document.querySelector('.background');

        let colorOffset = 0;
        function draw() {
            if (audio.paused || audio.ended) {
                animationId = null;
                visualizerBars.forEach(bar => bar.style.height = '5px');
                visualizerPeaks.forEach(peak => {
                    peak.style.bottom = '5%';
                    peak.style.background = 'linear-gradient(to bottom, #fff, transparent)';
                    peak.style.boxShadow = '0 -2px 10px rgba(255, 255, 255, 0.8)';
                });
                if (bg) {
                    bg.style.filter = 'brightness(1)';
                    bg.style.transform = 'scale(1)';
                }
                return;
            }
            
            animationId = requestAnimationFrame(draw);
            const bufferLength = analyzer.frequencyBinCount;
            const dataArray = new Uint8Array(bufferLength);
            analyzer.getByteFrequencyData(dataArray);

            colorOffset += 1;

            // Removed bass detection for background flicker
            if (bg) {
                bg.style.filter = '';
                bg.style.transform = '';
            }

            for (let i = 0; i < BAR_COUNT; i++) {
                // Map frequency data to bars (skipping very low and very high)
                const freqIndex = Math.floor((i / BAR_COUNT) * (dataArray.length * 0.7)) + 1;
                const val = dataArray[freqIndex];
                const targetHeight = (val / 255) * 100 + 5;
                
                // Retro "slow fall" logic
                if (targetHeight > barHeights[i]) {
                    barHeights[i] = targetHeight; 
                } else {
                    barHeights[i] -= 2; 
                    if (barHeights[i] < 5) barHeights[i] = 5;
                }
                
                if (visualizerBars[i]) {
                    visualizerBars[i].style.height = `${barHeights[i]}%`;
                }

                // Peak logic
                if (barHeights[i] > peakHeights[i]) {
                    peakHeights[i] = barHeights[i];
                } else {
                    peakHeights[i] -= 1.2; 
                    if (peakHeights[i] < 5) peakHeights[i] = 5;
                }

                if (visualizerPeaks[i]) {
                    visualizerPeaks[i].style.bottom = `${peakHeights[i]}%`;
                    
                    const hue = 190 + (peakHeights[i] * 0.5); // 190 to 240 range (Cyan to Blue)
                    const color = `hsla(${hue}, 100%, 90%, 1)`;
                    const glow = `hsla(${hue}, 100%, 60%, 0.7)`;
                    
                    visualizerPeaks[i].style.background = `linear-gradient(to bottom, ${color}, transparent)`;
                    visualizerPeaks[i].style.boxShadow = `0 -2px 10px ${glow}`;
                }
            }

            // Dynamic glow effect based on average volume
            let sum = 0;
            for (let i = 0; i < dataArray.length; i++) sum += dataArray[i];
            const avg = sum / dataArray.length;
            const intensity = (avg / 255);

            if (glassCard) {
                const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
                glassCard.style.boxShadow = `0 20px 50px rgba(0, 0, 0, 0.5), 0 0 ${intensity * 40}px ${primaryColor}44`;
                glassCard.style.transform = `scale(${1 + intensity * 0.005})`;
            }

            // Subtle color shift for border
            const hueShift = intensity * 30;
            document.documentElement.style.setProperty('--card-border-bg', `linear-gradient(${45 + hueShift}deg, var(--primary-color), var(--accent-color), var(--secondary-color), var(--primary-color))`);

            if (trackTitle) {
                trackTitle.style.transform = `scale(${1 + intensity * 0.01})`;
                trackTitle.style.textShadow = `0 0 ${15 + intensity * 15}px var(--primary-color)`;
            }

            // Pulse social icons slightly with bass
            const bass = dataArray[0] / 255;
            socialIcons.forEach(icon => {
                icon.style.transform = `scale(${1 + bass * 0.05})`;
            });
        }

        function initVisualizer() {
            // Create bars and peaks if not already created
            if (visualizerBars.length === 0) {
                visualizerContainer.innerHTML = '';
                for (let i = 0; i < BAR_COUNT; i++) {
                    const barWrapper = document.createElement('div');
                    barWrapper.style.position = 'relative';
                    barWrapper.style.height = '100%';
                    barWrapper.style.display = 'flex';
                    barWrapper.style.alignItems = 'flex-end';
                    barWrapper.style.width = '18px';

                    const bar = document.createElement('div');
                    bar.className = 'visualizer-bar';
                    
                    const peak = document.createElement('div');
                    peak.className = 'visualizer-peak';
                    
                    barWrapper.appendChild(bar);
                    barWrapper.appendChild(peak);
                    visualizerContainer.appendChild(barWrapper);
                    
                    visualizerBars.push(bar);
                    visualizerPeaks.push(peak);
                }
            }

            if (!audioCtx) {
                try {
                    audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                    analyzer = audioCtx.createAnalyser();
                    source = audioCtx.createMediaElementSource(audio);
                    source.connect(analyzer);
                    analyzer.connect(audioCtx.destination);
                    analyzer.fftSize = 128;
                } catch (e) {
                    console.error("AudioContext error:", e);
                }
            }
            
            if (audioCtx && audioCtx.state === 'suspended') {
                audioCtx.resume();
            }

            if (!animationId && !audio.paused) {
                draw();
            }
        }

        audio.addEventListener('play', () => {
            initVisualizer();
        });

        function togglePlay() {
            if (audio.paused) {
                audio.play().then(() => {
                    initVisualizer();
                }).catch(err => {
                    console.error("Error playing audio:", err);
                });
                playIcon.classList.remove('bi-play-fill');
                playIcon.classList.add('bi-pause-fill');
                playBtn.classList.add('playing');
                document.body.classList.add('is-playing');
            } else {
                audio.pause();
                playIcon.classList.remove('bi-pause-fill');
                playIcon.classList.add('bi-play-fill');
                playBtn.classList.remove('playing');
                document.body.classList.remove('is-playing');
            }
        }

        function changeVolume(val) {
            audio.volume = val;
        }

        function changeQuality(quality) {
            const isPlaying = !audio.paused;
            
            // NOTE: Replace the 'low' URL with your actual low-quality/mobile stream if available.
            const streams = {
                high: 'https://play.radioking.io/classic-rock-radio92',
                low: 'https://play.radioking.io/classic-rock-radio92'
            };
            
            const newSrc = streams[quality];
            
            // Visual feedback
            const wrapper = document.querySelector('.quality-selector-wrapper');
            wrapper.style.borderColor = 'var(--primary-color)';
            wrapper.style.transform = 'scale(1.05)';
            
            setTimeout(() => {
                wrapper.style.borderColor = 'rgba(255,255,255,0.1)';
                wrapper.style.transform = 'scale(1)';
            }, 300);

            audio.src = newSrc;
            audio.load();
            if (isPlaying) {
                audio.play().catch(e => console.error("Error al reproducir el stream:", e));
            }
        }

        function copyTrackTitle() {
            const title = document.getElementById('track-title').innerText.replace(/\s{2,}/g, ' ').trim();
            const artist = document.getElementById('track-artist').innerText.trim();
            const textToCopy = `${artist} - ${title}`;

            navigator.clipboard.writeText(textToCopy).then(() => {
                const toast = document.createElement('div');
                toast.className = 'copy-toast';
                toast.innerHTML = `<i class="bi bi-check-circle-fill"></i> ¡Copiado al portapapeles!`;
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 2000);
            }).catch(err => {
                console.error('Error copying text: ', err);
            });
        }

        function saveUserInfo() {
            const nameInput = document.getElementById('user-name');
            const phoneInput = document.getElementById('user-phone');
            const name = nameInput.value.trim();
            const phone = phoneInput.value.trim();
            
            if (!name && !phone) return;

            const isNewUser = !localStorage.getItem('userName') && name.length >= 3;

            localStorage.setItem('userName', name);
            localStorage.setItem('userPhone', phone);

            fetch('api/save_user_info.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username: name, phone: phone })
            });

            if (isNewUser) {
                // Special welcome for first-time identification
                showWelcomeToast(name);
                
                // Send a welcome message to the chat automatically
                setTimeout(() => {
                    sendChatMessage(`¡Hola a todos! Acabo de conectarme a Lili Records Radio. 👋📻`, 'text');
                    
                    // Radio Station welcome response
                    setTimeout(() => {
                        sendChatMessage(`¡Bienvenido ${name} a la familia de Lili Records! 🎉 Disfruta de la mejor programación.`, 'text', 'Lili Records Radio');
                    }, 1500);
                }, 1000);

                confetti({
                    particleCount: 150,
                    spread: 100,
                    origin: { y: 0.7 }
                });
            }
        }

        function getUserColor(str) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                hash = str.charCodeAt(i) + ((hash << 5) - hash);
            }
            const h = Math.abs(hash) % 360;
            // Usamos colores vibrantes con buena saturación y luminosidad media
            return `hsl(${h}, 65%, 55%)`;
        }

        function timeAgo(dateString) {
            const now = new Date();
            const past = new Date(dateString);
            const diffInSeconds = Math.floor((now - past) / 1000);
            
            if (diffInSeconds < 60) return 'Hace un momento';
            if (diffInSeconds < 3600) return `Hace ${Math.floor(diffInSeconds / 60)} min`;
            return 'Hace más de 1 hora';
        }

        async function fetchOnlineUsers() {
            try {
                const response = await fetch('api/get_online_users.php');
                const data = await response.json();
                if (data.success) {
                    const list = document.getElementById('online-users-list');
                    const widgetTitle = document.querySelector('#online-users-list').previousElementSibling.previousElementSibling;
                    
                    if (widgetTitle && data.total_active !== undefined) {
                        widgetTitle.innerHTML = `<i class="bi bi-people-fill"></i> CLIENTES CONECTADOS <span style="font-size: 0.7rem; background: rgba(37, 211, 102, 0.2); padding: 2px 8px; border-radius: 20px; vertical-align: middle; margin-left: 5px;">${data.total_active} OYENTES</span>`;
                    }

                    if (data.users.length === 0) {
                        list.innerHTML = '<div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 1rem;">No hay otros usuarios con móvil registrado ahora.</div>';
                        return;
                    }
                    
                    list.innerHTML = data.users.map(user => {
                        const isVeryActive = (new Date() - new Date(user.last_activity)) < 60000;
                        const flagUrl = user.country_code ? `https://flagcdn.com/w20/${user.country_code.toLowerCase()}.png` : null;
                        const isTopFan = user.points > 10 || user.is_fan_of_month == 1;
                        const isLoyal = user.loyalty_points > 0;
                        const isGuestDj = user.dj_day_until && (new Date(user.dj_day_until) > new Date());
                        
                        let userColor = user.chat_color || (isLoyal ? "#00e676" : getUserColor(user.username));
                        if (isGuestDj) userColor = "#facc15";
                        
                        return `
                        <div style="display: flex; align-items: center; justify-content: space-between; background: rgba(255,255,255,0.03); padding: 10px 15px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); transition: all 0.3s; position: relative; ${isLoyal ? "box-shadow: 0 0 10px rgba(0, 230, 118, 0.1);" : ""} ${isGuestDj ? "border-color: #facc15; background: rgba(250, 204, 21, 0.05);" : ""}">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="width: 38px; height: 38px; background: ${userColor}; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 1rem; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,0.3); position: relative; ${isVeryActive ? `box-shadow: 0 0 0 2px rgba(255,255,255,0.1), 0 0 12px ${userColor};` : ''} ${isLoyal || isGuestDj ? "animation: pulse 2s infinite;" : ""}">
                                    ${isGuestDj ? '<i class="bi bi-headphones"></i>' : user.username.charAt(0).toUpperCase()}
                                    ${isVeryActive ? '<span style="position: absolute; bottom: 0; right: 0; width: 10px; height: 10px; background: #25D366; border: 2px solid #000; border-radius: 50%;"></span>' : ''}
                                </div>
                                <div>
                                    <div style="font-weight: 700; font-size: 0.95rem; display: flex; align-items: center; gap: 6px;">
                                        <span style="color: ${userColor};">${user.username}</span>
                                        ${flagUrl ? `<img src="${flagUrl}" style="width: 16px; height: auto; border-radius: 2px; vertical-align: middle;" title="${user.country_code}">` : ''}
                                        ${isGuestDj ? `<span style="background: #facc15; color: black; font-size: 0.55rem; padding: 2px 6px; border-radius: 10px; font-weight: 800; text-transform: uppercase;">DJ INVITADO</span>` : ""}
                                        ${isLoyal && !isGuestDj ? `<span style="background: #00e676; color: white; font-size: 0.55rem; padding: 2px 6px; border-radius: 10px; font-weight: 800; text-transform: uppercase;"><i class="bi bi-shield-fill-check"></i> LEAL</span>` : ""}
                                        ${isTopFan && !isLoyal && !isGuestDj ? `<span style="background: #FFD700; color: #000; font-size: 0.6rem; padding: 2px 6px; border-radius: 10px; font-weight: 800; text-transform: uppercase;">TOP</span>` : ''}
                                    </div>
                                    <div style="font-size: 0.7rem; opacity: 0.6;">
                                        <i class="bi bi-clock"></i> ${timeAgo(user.last_activity)}
                                    </div>
                                </div>
                            </div>
                            <a href="https://wa.me/${user.phone_number.replace(/\D/g, '')}?text=Hola,%20te%20vi%20en%20Lili%20Records" target="_blank" style="background: #25D366; color: white; width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; text-decoration: none; box-shadow: 0 4px 10px rgba(37, 211, 102, 0.3); transition: all 0.2s;" onmouseover="this.style.transform='scale(1.15)'" onmouseout="this.style.transform='scale(1)'">
                                <i class="bi bi-whatsapp"></i>
                            </a>
                        </div>
                        `;
                    }).join('');
                }
            } catch (error) {
                console.error('Error fetching online users:', error);
            }
        }

        // Fetch online users every 30 seconds
        setInterval(fetchOnlineUsers, 30000);
        setTimeout(fetchOnlineUsers, 2000); // Initial fetch

        function savePhone(phone) {
            const phoneInput = document.getElementById('user-phone');
            const phoneRegex = /^\+?[0-9]{7,15}$/;
            const cleanPhone = phone.replace(/\s/g, '');
            
            if (cleanPhone && !phoneRegex.test(cleanPhone)) {
                phoneInput.style.borderColor = '#ff4444';
                return;
            }
            
            phoneInput.style.borderColor = 'rgba(255, 255, 255, 0.2)';
            
            const formData = new FormData();
            formData.append('phone', cleanPhone);
            fetch('api/save_phone.php', {
                method: 'POST',
                body: formData
            });
        }

        async function sendToWhatsApp() {
            const name = document.getElementById('user-name').value.trim();
            const phone = document.getElementById('user-phone').value.trim();
            const message = document.getElementById('user-message').value.trim();
            
            const reqArtist = document.getElementById('req-artist').value.trim();
            const reqSong = document.getElementById('req-song').value.trim();
            
            const phoneRegex = /^\+?[0-9]{7,15}$/;

            if (name.length < 3) {
                alert('Por favor, ingresa un nombre válido (mínimo 3 caracteres).');
                document.getElementById('user-name').style.borderColor = '#ff4444';
                return;
            }

            if (!phone) {
                alert('Por favor, ingresa tu número de móvil para continuar.');
                document.getElementById('user-phone').style.borderColor = '#ff4444';
                return;
            }

            if (!phoneRegex.test(phone.replace(/\s/g, ''))) {
                alert('Por favor, ingresa un número de móvil válido (ej: +5359177041).');
                document.getElementById('user-phone').style.borderColor = '#ff4444';
                return;
            }

            const now = new Date();
            const dateTime = now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
            const refId = Math.floor(1000 + Math.random() * 9000);
            const currentSong = document.getElementById('track-title').innerText.replace(/\s{2,}/g, ' ').trim();
            
            let requestDetails = "";
            if (reqArtist && reqSong) {
                requestDetails = `*Petición:* ${reqArtist} - ${reqSong}\n`;
            }

            const text = `*PETICIÓN RADIO* (Ref: #${refId})\n\n` +
                         `*Nombre:* ${name}\n` +
                         `*Móvil:* ${phone}\n` +
                         `*Fecha:* ${dateTime}\n` +
                         requestDetails +
                         `*Sonando ahora:* ${currentSong}\n\n` +
                         `*Mensaje:* ${message || 'Sin mensaje específico'}`;
            
            // Register in database
            try {
                const formData = new FormData();
                formData.append('artist', reqArtist || 'WhatsApp');
                formData.append('song', reqSong || message || 'Petición Directa');
                formData.append('requester', name);
                formData.append('source', 'whatsapp');

                await fetch('api/song_requests.php', {
                    method: 'POST',
                    body: formData
                });
                
                if (typeof fetchSongRequests === 'function') fetchSongRequests();
                if (typeof fetchLeaderboard === 'function') fetchLeaderboard();
            } catch (e) {
                console.error("Error registering WhatsApp request:", e);
            }

            const url = `https://wa.me/<?= str_replace('+', '', $whatsapp_number) ?>?text=${encodeURIComponent(text)}`;
            window.open(url, '_blank');
        }

        // --- Chat Functionality ---
        const chatMessages = document.getElementById('chat-messages');
        const chatUser = document.getElementById('chat-user');
        const chatMsg = document.getElementById('chat-msg');
        const emojiPicker = document.getElementById('emoji-picker');
        let lastMessageCount = 0;
        let chatSoundMuted = localStorage.getItem('chatSoundMuted') === 'true';

        function updateMuteButton() {
            const btn = document.getElementById('mute-chat-btn');
            if (!btn) return;
            const icon = btn.querySelector('i');
            if (chatSoundMuted) {
                icon.classList.remove('bi-volume-up-fill');
                icon.classList.add('bi-volume-mute-fill');
                btn.style.color = '#ff4444';
            } else {
                icon.classList.remove('bi-volume-mute-fill');
                icon.classList.add('bi-volume-up-fill');
                btn.style.color = 'white';
            }
        }

        function toggleChatSound() {
            chatSoundMuted = !chatSoundMuted;
            localStorage.setItem('chatSoundMuted', chatSoundMuted);
            updateMuteButton();
        }

        // Initialize button state
        setTimeout(updateMuteButton, 500);

        function toggleEmojiPicker() {
            emojiPicker.style.display = emojiPicker.style.display === 'none' ? 'block' : 'none';
        }

        emojiPicker.addEventListener('emoji-click', event => {
            chatMsg.value += event.detail.unicode;
            emojiPicker.style.display = 'none';
            chatMsg.focus();
        });

        // Close emoji picker when clicking outside
        document.addEventListener('click', (e) => {
            if (!emojiPicker.contains(e.target) && !e.target.closest('button[onclick="toggleEmojiPicker()"]')) {
                emojiPicker.style.display = 'none';
            }
        });

        async function uploadImage(input) {
            if (!input.files || !input.files[0]) return;
            
            const file = input.files[0];
            const formData = new FormData();
            formData.append('image', file);

            try {
                const response = await fetch('api/upload.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                if (result.success) {
                    sendChatMessage(result.url, 'image');
                    updatePhotoCounter();
                } else {
                    alert(result.error || 'Error al subir la imagen');
                }
            } catch (error) {
                console.error('Upload error:', error);
                alert('Error de conexión al subir la imagen');
            }
            input.value = ''; // Reset input
        }

        async function fetchMessages() {
            try {
                const response = await fetch('api/chat.php');
                const messages = await response.json();
                
                if (messages.length === lastMessageCount) return;
                
                // Play pop sound for new messages (not on initial load)
                if (!chatSoundMuted && messages.length > lastMessageCount && lastMessageCount > 0) {
                    const popSound = document.getElementById('pop-sound');
                    if (popSound) {
                        popSound.currentTime = 0;
                        popSound.volume = 0.4; // Soft volume
                        popSound.play().catch(e => console.log('Pop sound blocked:', e));
                    }
                }
                
                const currentUserName = document.getElementById('user-name').value.trim() || 'Anónimo';
                chatMessages.innerHTML = '';
                messages.forEach((msg, index) => {
                    // Play DJ Power sound for new dj_power messages
                    if (msg.type === 'dj_power' && index >= lastMessageCount && lastMessageCount > 0) {
                        const powerSound = document.getElementById('dj-power-sound');
                        if (powerSound) {
                            powerSound.currentTime = 0;
                            powerSound.volume = 0.5;
                            powerSound.play().catch(e => console.log('DJ Power sound blocked:', e));
                        }
                        
                        // Also trigger a small shake on the whole app for impact
                        document.body.style.animation = 'none';
                        setTimeout(() => {
                            document.body.style.animation = 'shake 0.5s cubic-bezier(.36,.07,.19,.97) both';
                        }, 10);

                        // Trigger reaction buttons visibility
                        showReactionButtons();
                    }
                    
                    // Trigger flash poll UI
                    if (msg.type === 'flash_poll' && index >= lastMessageCount && lastMessageCount > 0) {
                        showFlashPoll(msg.message);
                    }

                    // Trigger flying emoji for reaction messages
                    if (msg.type === 'reaction' && index >= lastMessageCount && lastMessageCount > 0) {
                        spawnReactionEmoji(msg.message);
                    }

                    if (msg.type === 'reaction' || msg.type === 'flash_poll') return;

                    const div = document.createElement('div');
                    const isLike = msg.message.includes('❤️');
                    const isMe = msg.username.toLowerCase() === currentUserName.toLowerCase();
                    
                    div.className = 'chat-msg-item' + (isMe ? ' is-me' : '');
                    
                    // Only animate truly new messages to avoid visual fatigue
                    if (index < lastMessageCount && lastMessageCount > 0) {
                        div.style.animation = 'none';
                        div.style.opacity = '1';
                    }
                    
                    // Si el color es el gris por defecto (#94a3b8) o no tiene, usamos el color dinámico por nombre
                    let nameColor = (msg.level_color && msg.level_color !== '#94a3b8') ? msg.level_color : getUserColor(msg.username);
                    const levelEmoji = msg.level_emoji || '';
                    
                    if (msg.is_loyal) {
                        div.style.borderLeft = "4px solid #00e676";
                        div.style.background = "rgba(0, 230, 118, 0.05)";
                    }

                    if (msg.type === 'dj_power') {
                        div.style.background = "linear-gradient(135deg, rgba(250, 204, 21, 0.2), rgba(245, 158, 11, 0.1))";
                        div.style.border = "1px solid #facc15";
                        div.style.boxShadow = "0 0 15px rgba(250, 204, 21, 0.3)";
                        div.style.animation = "toast-in-out 0.5s forwards, pulse 2s infinite";
                    }

                    if (isLike) {
                        div.style.background = isMe ? 'rgba(255, 68, 68, 0.25)' : 'rgba(255, 68, 68, 0.15)';
                        div.style.borderLeft = isMe ? 'none' : '4px solid #ff4444';
                        if (isMe) div.style.borderRight = '4px solid #ff4444';
                    } else if (!isMe) {
                        div.style.borderLeft = `4px solid ${msg.username === currentUserName ? 'var(--primary-color)' : 'rgba(255,255,255,0.2)'}`;
                    }
                    
                    let content = '';
                    if (msg.type === 'image') {
                        content = `
                            <div style="position: relative; display: inline-block;">
                                <img src="${msg.message}" style="max-width: 100%; border-radius: 8px; margin-top: 5px; cursor: pointer;" onclick="window.open('${msg.message}', '_blank')">
                                <div style="position: absolute; top: 10px; right: 10px; background: rgba(255,0,0,0.7); color: white; font-size: 0.5rem; padding: 2px 5px; border-radius: 4px; font-weight: 800; border: 1px solid rgba(255,255,255,0.3);"><i class="bi bi-clock-history"></i> 5s</div>
                            </div>
                        `;
                    } else {
                        content = `<div style="font-size: 0.85rem; line-height: 1.4; ${isLike ? 'font-weight: 600;' : ''}">${msg.message}</div>`;
                    }

                    div.innerHTML = `
                        <div class="chat-msg-header" style="color: ${nameColor};">
                            ${msg.username} ${levelEmoji ? `<span style="font-size: 0.8rem;">${levelEmoji}</span>` : ''}
                        </div>
                        ${content}
                        <div class="chat-msg-time">${new Date(msg.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
                    `;
                    chatMessages.appendChild(div);
                });
                chatMessages.scrollTop = chatMessages.scrollHeight;
                lastMessageCount = messages.length;
            } catch (error) {
                console.error('Chat error:', error);
            }
        }

        async function sendChatMessage(msgContent = null, type = 'text', customUser = null) {
            const userNameInput = document.getElementById('user-name');
            const userPhoneInput = document.getElementById('user-phone');
            const user = customUser || userNameInput.value.trim();
            const phone = userPhoneInput.value.trim();
            const message = msgContent || chatMsg.value.trim();
            const phoneRegex = /^\+?[0-9]{7,15}$/;

            if (!customUser && user.length < 3) {
                alert('Por favor, ingresa un nombre válido arriba (mínimo 3 caracteres).');
                userNameInput.style.borderColor = '#ff4444';
                return;
            }

            if (!customUser && !phone) {
                alert('Por favor, regístrate con tu móvil arriba para poder chatear.');
                userPhoneInput.style.borderColor = '#ff4444';
                return;
            }

            if (!customUser && !phoneRegex.test(phone.replace(/\s/g, ''))) {
                alert('Por favor, ingresa un número de móvil válido arriba.');
                userPhoneInput.style.borderColor = '#ff4444';
                return;
            }

            if (!message) return;

            try {
                const response = await fetch('api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: user, message: message, type: type })
                });
                const result = await response.json();
                if (result.success) {
                    if (!msgContent) chatMsg.value = '';
                    fetchMessages();
                }
            } catch (error) {
                console.error('Error sending message:', error);
            }
        }

        let globalReactionCount = 0;
        let lastMassiveCelebration = 0;
        let reactionTimer = null;

        function triggerMassiveCelebration() {
            const duration = 10 * 1000;
            const animationEnd = Date.now() + duration;
            const defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 10001 };

            // Reset thermometer
            const energyFill = document.getElementById('energy-fill');
            const energyText = document.getElementById('energy-text');
            if (energyFill) {
                energyFill.style.width = '0%';
                energyFill.parentElement.classList.remove('counter-alert');
                if (energyText) energyText.innerText = "¡REINICIANDO!";
            }

            function randomInRange(min, max) {
                return Math.random() * (max - min) + min;
            }

            const interval = setInterval(function() {
                const timeLeft = animationEnd - Date.now();

                if (timeLeft <= 0) {
                    return clearInterval(interval);
                }

                const particleCount = 40 * (timeLeft / duration);
                confetti(Object.assign({}, defaults, { particleCount, origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 } }));
                confetti(Object.assign({}, defaults, { particleCount, origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 } }));
            }, 250);
            
            // Visual feedback text
            const banner = document.createElement('div');
            banner.style.position = 'fixed';
            banner.style.top = '50%';
            banner.style.left = '50%';
            banner.style.transform = 'translate(-50%, -50%)';
            banner.style.zIndex = '10002';
            banner.style.textAlign = 'center';
            banner.style.pointerEvents = 'none';
            banner.style.animation = 'fadeIn 0.5s forwards';
            banner.innerHTML = `
                <h1 style="font-size: clamp(2rem, 8vw, 5rem); font-weight: 900; color: #facc15; text-shadow: 0 0 30px rgba(250, 204, 21, 0.8); margin: 0; animation: bounce 1s infinite;">¡FIESTA TOTAL!</h1>
                <p style="font-size: clamp(1rem, 3vw, 1.5rem); font-weight: 800; color: #fff; text-shadow: 0 0 10px rgba(0,0,0,0.5); text-transform: uppercase; letter-spacing: 2px;">¡LA RADIO ESTÁ EXPLOTANDO! 🔥🎉</p>
            `;
            document.body.appendChild(banner);
            
            // Play a sound if possible (recycling the DJ power sound)
            const powerSound = document.getElementById('dj-power-sound');
            if (powerSound) {
                powerSound.currentTime = 0;
                powerSound.play().catch(() => {});
            }

            setTimeout(() => {
                banner.style.transition = 'opacity 1s ease';
                banner.style.opacity = '0';
                setTimeout(() => banner.remove(), 1000);
            }, 5000);
        }

        function spawnReactionEmoji(emoji) {
            const container = document.body;
            const emojiEl = document.createElement('div');
            emojiEl.className = 'flying-emoji';
            emojiEl.innerText = emoji;
            
            const startX = Math.random() * 80 + 10;
            const drift = (Math.random() - 0.5) * 200;
            const rotation = (Math.random() - 0.5) * 90;
            const duration = 2 + Math.random() * 2;
            
            emojiEl.style.left = `${startX}%`;
            emojiEl.style.setProperty('--drift', `${drift}px`);
            emojiEl.style.setProperty('--rot', `${rotation}deg`);
            emojiEl.style.setProperty('--duration', `${duration}s`);
            
            container.appendChild(emojiEl);
            setTimeout(() => { emojiEl.remove(); }, duration * 1000);

            // Massive Celebration Logic
            const boost = window.isPollActive ? 10 : 1;
            globalReactionCount += boost;
            
            // Update Energy Thermometer for DJ
            const energyFill = document.getElementById('energy-fill');
            const energyText = document.getElementById('energy-text');
            if (energyFill) {
                const threshold = 50;
                const percentage = (globalReactionCount / threshold) * 100;
                energyFill.style.width = `${Math.min(percentage, 100)}%`;
                
                if (energyText) {
                    if (percentage < 30) energyText.innerText = "Cargando hype...";
                    else if (percentage < 70) energyText.innerText = "¡Hype subiendo!";
                    else if (percentage < 100) {
                        energyText.innerText = "¡Casi explota!";
                        energyFill.parentElement.classList.add('counter-alert');
                    } else {
                        energyText.innerText = "¡EXPLOSIÓN!";
                        energyFill.parentElement.classList.add('counter-alert');
                    }
                    
                    if (percentage < 70) energyFill.parentElement.classList.remove('counter-alert');
                }
            }
            
            if (!reactionTimer) {
                reactionTimer = setTimeout(() => {
                    globalReactionCount = 0;
                    reactionTimer = null;
                }, 10000); // 10 second window
            }
            
            if (globalReactionCount >= 50 && (Date.now() - lastMassiveCelebration > 30000)) {
                triggerMassiveCelebration();
                globalReactionCount = 0;
                lastMassiveCelebration = Date.now();
                if (reactionTimer) {
                    clearTimeout(reactionTimer);
                    reactionTimer = null;
                }
            }
        }

        async function promptFlashPoll() {
            const question = prompt("Ingresa la Pregunta Flash para la audiencia:");
            if (!question) return;
            const userName = document.getElementById('user-name').value.trim() || 'Lili';
            await sendChatMessage(question, 'flash_poll', userName);
        }

        function showFlashPoll(question) {
            const container = document.getElementById('flash-poll-container');
            const qEl = document.getElementById('poll-question');
            const timerFill = document.getElementById('poll-timer-fill');
            
            qEl.innerText = question;
            container.style.display = 'block';
            setTimeout(() => container.classList.add('show'), 10);
            
            timerFill.style.transition = 'none';
            timerFill.style.width = '100%';
            
            setTimeout(() => {
                timerFill.style.transition = 'width 30s linear';
                timerFill.style.width = '0%';
            }, 100);
            
            window.isPollActive = true;
            showReactionButtons(); // Activar botones de reacción para el combo
            
            setTimeout(() => {
                container.classList.remove('show');
                window.isPollActive = false;
                setTimeout(() => { container.style.display = 'none'; }, 500);
            }, 30000);
        }

        async function answerFlashPoll(answer) {
            const emoji = answer === 'SÍ' ? '🔥' : '🎧';
            const userName = document.getElementById('user-name').value.trim() || 'Anónimo';
            
            try {
                await fetch('api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        username: userName, 
                        message: emoji, 
                        type: 'flash_poll_response' 
                    })
                });
                
                // Show floating +10 LP animation
                showFloatingPoints('+10 LP', '#00e676');
                
                spawnReactionEmoji(emoji);
            } catch (error) {
                console.error('Error sending poll response:', error);
            }
            
            document.getElementById('flash-poll-container').classList.remove('show');
            window.isPollActive = false;
        }

        function showFloatingPoints(text, color) {
            const container = document.getElementById('flash-poll-container');
            const floating = document.createElement('div');
            floating.innerText = text;
            floating.style.position = 'absolute';
            floating.style.top = '50%';
            floating.style.left = '50%';
            floating.style.transform = 'translate(-50%, -50%)';
            floating.style.color = color;
            floating.style.fontWeight = '900';
            floating.style.fontSize = '2rem';
            floating.style.zIndex = '10005';
            floating.style.pointerEvents = 'none';
            floating.style.animation = 'floatUpFade 1.5s forwards';
            floating.style.textShadow = '0 0 10px rgba(0,0,0,0.5)';
            
            container.appendChild(floating);
            setTimeout(() => floating.remove(), 1500);
        }

        async function sendReaction(emoji) {
            const userName = document.getElementById('user-name').value.trim() || 'Anónimo';
            try {
                await fetch('api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        username: userName, 
                        message: emoji, 
                        type: 'reaction' 
                    })
                });
                // Optimistic UI
                spawnReactionEmoji(emoji);
            } catch (error) {
                console.error('Error sending reaction:', error);
            }
        }

        function showReactionButtons() {
            const container = document.getElementById('dj-reaction-area');
            if (container) {
                container.style.display = 'flex';
                container.style.opacity = '1';
                container.classList.add('reaction-overlay-active');
                
                if (window.reactionTimeout) clearTimeout(window.reactionTimeout);
                
                window.reactionTimeout = setTimeout(() => {
                    container.classList.remove('reaction-overlay-active');
                    container.style.transition = 'opacity 1s ease';
                    container.style.opacity = '0';
                    setTimeout(() => {
                        if (container.style.opacity === '0') container.style.display = 'none';
                    }, 1000);
                }, 20000);
            }
        }

        chatMsg.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendChatMessage();
        });

        async function updatePhotoCounter() {
            try {
                const response = await fetch('api/photo_status.php');
                const data = await response.json();
                const counter = document.getElementById('photo-counter');
                const cameraBtn = document.getElementById('camera-btn');
                const fileInput = document.getElementById('chat-file');
                const limitMsg = document.getElementById('photo-limit-msg');

                if (data && typeof data.count !== 'undefined') {
                    counter.innerText = `${data.count}/${data.limit}`;
                    counter.style.display = 'block';
                    
                    // Alerta cuando solo queda 1 foto (4 de 5)
                    if (data.count === data.limit - 1) {
                        counter.classList.add('counter-alert');
                    } else {
                        counter.classList.remove('counter-alert');
                    }
                    
                    if (data.count >= data.limit) {
                        counter.style.background = '#ff4444';
                        // Bloquear visualmente el botón
                        cameraBtn.style.opacity = '0.4';
                        cameraBtn.style.filter = 'grayscale(1)';
                        cameraBtn.style.pointerEvents = 'none';
                        cameraBtn.title = 'Límite de fotos alcanzado';
                        fileInput.disabled = true;

                        // Mostrar tiempo restante
                        if (data.reset_in_seconds > 0) {
                            const hours = Math.floor(data.reset_in_seconds / 3600);
                            const minutes = Math.floor((data.reset_in_seconds % 3600) / 60);
                            const timeStr = hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
                            limitMsg.innerText = `Disponible en ${timeStr}`;
                            limitMsg.style.display = 'block';
                        }
                    } else {
                        counter.style.background = 'var(--primary-color)';
                        // Restaurar el botón
                        cameraBtn.style.opacity = '1';
                        cameraBtn.style.filter = 'none';
                        cameraBtn.style.pointerEvents = 'auto';
                        cameraBtn.title = 'Subir foto';
                        fileInput.disabled = false;
                        limitMsg.style.display = 'none';
                    }
                }
            } catch (error) {
                console.error('Error updating photo counter:', error);
            }
        }

        async function checkAutomation() {
            try {
                const response = await fetch('api/automation.php');
                const data = await response.json();
                if (data.success && data.action === 'executed') {
                    // Force metadata update if something was executed
                    updateMetadata();
                    if (typeof fetchSongRequests === 'function') fetchSongRequests();
                }
            } catch (error) {
                console.error('Automation error:', error);
            }
        }

        // Run automation check every 15 seconds
        setInterval(checkAutomation, 15000);
        setTimeout(checkAutomation, 2000); // Initial check
        // --- End Chat Functionality ---

        // --- Song Request Functionality ---
        async function submitSongRequestNew() {
            const artistInput = document.getElementById('req-artist-new');
            const songInput = document.getElementById('req-song-new');
            const artist = artistInput.value.trim();
            const song = songInput.value.trim();
            const requester = document.getElementById('user-name').value.trim() || 'Anónimo';

            if (!artist || !song) {
                alert('Por favor, ingresa el artista y el nombre de la canción o saludo.');
                if (!artist) artistInput.style.borderColor = '#ff4444';
                if (!song) songInput.style.borderColor = '#ff4444';
                return;
            }

            const btn = document.getElementById('submit-req-btn-new');
            const originalContent = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> PROCESANDO...';

            try {
                const formData = new FormData();
                formData.append('artist', artist);
                formData.append('song', song);
                formData.append('requester', requester);
                formData.append('source', 'web_dedicated');

                const response = await fetch('api/song_requests.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                if (result.success) {
                    artistInput.value = '';
                    songInput.value = '';
                    artistInput.style.borderColor = '';
                    songInput.style.borderColor = '';
                    
                    if (typeof fetchSongRequests === 'function') fetchSongRequests();
                    
                    btn.innerHTML = '<i class="bi bi-check-circle-fill"></i> ¡ENVIADO CON ÉXITO!';
                    btn.style.backgroundColor = 'var(--accent-color)';
                    
                    confetti({
                        particleCount: 150,
                        spread: 70,
                        origin: { y: 0.6 }
                    });

                    setTimeout(() => {
                        btn.disabled = false;
                        btn.innerHTML = originalContent;
                        btn.style.backgroundColor = '';
                    }, 3000);
                } else {
                    alert('Error: ' + (result.error || 'No se pudo enviar la petición'));
                    btn.disabled = false;
                    btn.innerHTML = originalContent;
                }
            } catch (error) {
                console.error('Error submitting request:', error);
                btn.disabled = false;
                btn.innerHTML = originalContent;
            }
        }

        function scrollToRequests() {
            const list = document.getElementById('song-requests-list');
            if (list) {
                list.scrollIntoView({ behavior: 'smooth', block: 'center' });
                list.style.animation = 'shake 0.5s ease-in-out';
                setTimeout(() => list.style.animation = '', 600);
            }
        }

        async function fetchSongRequests() {
            try {
                const response = await fetch('api/song_requests.php');
                const result = await response.json();
                
                // Check if there are priority requests
                const hasPriority = result.success && result.requests.some(req => req.is_priority == 1);
                
                // Check if current user is Guest DJ
                const currentUserName = document.getElementById('user-name').value.trim();
                let isGuestDj = false;
                
                // We can check if the current user has the Guest DJ status from the online users data or another check
                // For simplicity, let's do a quick local check if we've already fetched online users
                const onlineUsersResponse = await fetch('api/get_online_users.php');
                const onlineData = await onlineUsersResponse.json();
                if (onlineData.success && currentUserName) {
                    const me = onlineData.users.find(u => u.username.toLowerCase() === currentUserName.toLowerCase());
                    if (me && me.dj_day_until && (new Date(me.dj_day_until) > new Date())) {
                        isGuestDj = true;
                    }
                }

                // Show/hide Skip button
                const skipBtn = document.getElementById('dj-skip-btn');
                if (skipBtn) skipBtn.style.display = (isGuestDj || isAdmin) ? 'flex' : 'none';

                // Show/hide Energy Thermometer
                const thermometer = document.getElementById('dj-energy-thermometer');
                if (thermometer) thermometer.style.display = (isGuestDj || isAdmin) ? 'flex' : 'none';

                // Show/hide Flash Poll control
                const pollControl = document.getElementById('dj-flash-poll-control');
                if (pollControl) pollControl.style.display = (isGuestDj || isAdmin) ? 'block' : 'none';

                // Show/hide VIP Alert
                const vipAlert = document.getElementById('dj-vip-alert');
                if (vipAlert) {
                    vipAlert.style.display = ((isGuestDj || isAdmin) && hasPriority) ? 'block' : 'none';
                }

                // Show/hide Test buttons
                const tictacBtn = document.getElementById('test-tictac-btn');
                if (tictacBtn) tictacBtn.style.display = (isGuestDj || isAdmin) ? 'block' : 'none';
                const applauseBtn = document.getElementById('test-applause-btn');
                if (applauseBtn) applauseBtn.style.display = (isGuestDj || isAdmin) ? 'block' : 'none';

                if (result.success) {
                    const list = document.getElementById('song-requests-list');
                    if (result.requests.length === 0) {
                        list.innerHTML = '<div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 2rem;">No hay peticiones recientes.</div>';
                        return;
                    }
                    list.innerHTML = result.requests.map(req => {
                        const isPriority = req.is_priority == 1;
                        return `
                        <div class="request-item" style="${isPriority ? 'border-left: 4px solid #facc15; background: rgba(250, 204, 21, 0.05);' : ''}">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span class="artist" style="${isPriority ? 'color: #facc15;' : ''}">${isPriority ? '⭐ ' : ''}${req.artist}</span>
                                    ${isPriority && isGuestDj ? `
                                        <div class="vip-timer" data-start="${req.created_at}" style="font-size: 0.7rem; font-weight: 800; background: rgba(0,0,0,0.3); padding: 2px 8px; border-radius: 20px; color: #facc15; display: inline-flex; align-items: center; gap: 4px; border: 1px solid rgba(255,255,255,0.1);">
                                            <i class="bi bi-stopwatch"></i> <span class="timer-value">--:--</span>
                                        </div>
                                    ` : ''}
                                </div>
                                <span style="font-size: 0.6rem; opacity: 0.4;">${new Date(req.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                            </div>
                            <div class="song">${req.song}</div>
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 5px;">
                                <div class="requester"><i class="bi bi-person-fill"></i> ${req.requester}</div>
                                <div style="display: flex; gap: 5px; align-items: center;">
                                    ${isGuestDj ? `
                                        <button onclick="djMarkPlayed(${req.id})" style="background: #22c55e; color: white; border: none; font-size: 0.6rem; padding: 2px 8px; border-radius: 4px; font-weight: 800; cursor: pointer;">
                                            <i class="bi bi-play-fill"></i> SONAR
                                        </button>
                                    ` : ''}
                                    ${isGuestDj && !isPriority ? `
                                        <button onclick="djPrioritizeSong(${req.id})" style="background: #facc15; color: black; border: none; font-size: 0.6rem; padding: 2px 8px; border-radius: 4px; font-weight: 800; cursor: pointer;">
                                            <i class="bi bi-star-fill"></i> PRIORIZAR
                                        </button>
                                    ` : ''}
                                    ${isPriority ? '<span style="color: #facc15; font-size: 0.6rem; font-weight: 800;"><i class="bi bi-lightning-fill"></i> PRIORIDAD DJ</span>' : ''}
                                </div>
                            </div>
                        </div>
                        `;
                    }).join('');
                }
            } catch (error) {
                console.error('Error fetching requests:', error);
            }
        }

        async function djSkipSong() {
            const username = document.getElementById('user-name').value.trim();
            if (!username) return;

            if (!confirm('¿Estás seguro de que quieres usar tu poder de DJ para SALTAR esta canción?')) return;

            try {
                const response = await fetch('api/dj_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: username, action: 'skip' })
                });
                const result = await response.json();
                if (result.success) {
                    alert('¡Canción saltada! Se ha anunciado en el chat.');
                    fetchMessages();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Error skipping song:', error);
            }
        }

        async function djMarkPlayed(requestId) {
            const username = document.getElementById('user-name').value.trim();
            if (!username) {
                alert('⚠️ Por favor, ingresa tu NOMBRE en el formulario para identificarte como DJ.');
                document.getElementById('user-name').focus();
                document.getElementById('user-name').style.borderColor = '#facc15';
                return;
            }

            try {
                const formData = new FormData();
                formData.append('action', 'mark_played');
                formData.append('id', requestId);
                formData.append('username', username);

                const response = await fetch('api/song_requests.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                if (result.success) {
                    if (result.was_priority) {
                        applauseAudio.volume = 0.5;
                        applauseAudio.play();
                    }
                    if (result.bonus_awarded) {
                        confetti({
                            particleCount: 150,
                            spread: 70,
                            origin: { y: 0.6 },
                            colors: ['#22c55e', '#ffffff', '#facc15']
                        });
                        // Show quick toast if bonus
                        const toast = document.createElement('div');
                        toast.style = 'position: fixed; top: 20px; right: 20px; background: #22c55e; color: white; padding: 15px 25px; border-radius: 10px; z-index: 10000; font-weight: bold; animation: slideIn 0.3s ease-out;';
                        toast.innerHTML = '⚡ ¡BONO DE RAPIDEZ! +100 LP 🎧';
                        document.body.appendChild(toast);
                        setTimeout(() => {
                            toast.style.animation = 'fadeOut 0.5s ease-in';
                            setTimeout(() => toast.remove(), 500);
                        }, 4000);
                        
                        fetchTopFans();
                    }
                    fetchSongRequests();
                    fetchMessages();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Error marking song as played:', error);
            }
        }

        async function djPrioritizeSong(requestId) {
            const username = document.getElementById('user-name').value.trim();
            if (!username) {
                alert('⚠️ Por favor, ingresa tu NOMBRE en el formulario para identificarte como DJ.');
                document.getElementById('user-name').focus();
                document.getElementById('user-name').style.borderColor = '#facc15';
                return;
            }

            try {
                const response = await fetch('api/dj_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: username, action: 'prioritize', request_id: requestId })
                });
                const result = await response.json();
                if (result.success) {
                    alert('¡Petición priorizada! Sonará pronto.');
                    fetchSongRequests();
                    fetchMessages();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Error prioritizing song:', error);
            }
        }

        async function submitSongRequest() {
            const artistInput = document.getElementById('req-artist');
            const songInput = document.getElementById('req-song');
            const artist = artistInput.value.trim();
            const song = songInput.value.trim();
            const requester = document.getElementById('user-name').value.trim() || 'Anónimo';

            if (!artist || !song) {
                alert('Por favor, ingresa el artista y el nombre de la canción.');
                if (!artist) artistInput.style.borderColor = '#ff4444';
                if (!song) songInput.style.borderColor = '#ff4444';
                return;
            }

            const btn = document.getElementById('submit-req-btn');
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> ENVIANDO...';

            try {
                const formData = new FormData();
                formData.append('artist', artist);
                formData.append('song', song);
                formData.append('requester', requester);

                const response = await fetch('api/song_requests.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                if (result.success) {
                    artistInput.value = '';
                    songInput.value = '';
                    artistInput.style.borderColor = '';
                    songInput.style.borderColor = '';
                    fetchSongRequests();
                    
                    // Small visual feedback
                    btn.innerHTML = '<i class="bi bi-check-circle-fill"></i> ¡PEDIDA!';
                    btn.style.backgroundColor = 'var(--accent-color)';
                    
                    // Celebration if the user is #1
                    if (result.is_top) {
                        confetti({
                            particleCount: 200,
                            spread: 90,
                            origin: { y: 0.7 },
                            colors: ['#facc15', '#ffffff', '#38bdf8']
                        });
                        
                        // Show special shoutout
                        const shoutoutModal = document.getElementById('shoutout-modal');
                        const shoutoutTarget = document.getElementById('shoutout-target');
                        const shoutoutMsg = document.getElementById('shoutout-message');
                        
                        shoutoutTarget.innerText = `¡FELICIDADES ${result.top_name.toUpperCase()}!`;
                        shoutoutMsg.innerText = `¡Te has convertido en el Oyente #1 de la Semana! Gracias por tu increíble apoyo a Lili Records Radio. 👑📻`;
                        
                        shoutoutModal.style.display = 'flex';
                        setTimeout(() => shoutoutModal.classList.add('show'), 10);
                        
                        fetchTopListener(); // Update banner
                    } else {
                        confetti({
                            particleCount: 50,
                            spread: 60,
                            origin: { y: 0.8 },
                            colors: ['#38bdf8', '#00e676']
                        });
                    }

                    setTimeout(() => {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="bi bi-plus-circle-fill"></i> PEDIR CANCIÓN';
                        btn.style.backgroundColor = '';
                    }, 3000);
                } else {
                    alert('Error: ' + (result.error || 'No se pudo enviar la petición'));
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-plus-circle-fill"></i> PEDIR CANCIÓN';
                }
            } catch (error) {
                console.error('Error submitting request:', error);
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-plus-circle-fill"></i> PEDIR CANCIÓN';
            }
        }

        // Initial fetch and poll for requests
        fetchSongRequests();
        setInterval(fetchSongRequests, 10000); // Update requests every 10s
        // --- End Song Request Functionality ---

        function openQRModal() {
            const modal = document.getElementById('qr-modal');
            modal.style.display = 'flex';
            setTimeout(() => {
                modal.classList.add('show');
            }, 10);
        }

        function closeQRModal() {
            const modal = document.getElementById('qr-modal');
            modal.classList.remove('show');
            setTimeout(() => {
                modal.style.display = 'none';
            }, 300);
        }

        // Close modal on Esc key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeQRModal();
        });

        async function likeSong() {
            const nameInput = document.getElementById('user-name');
            const name = nameInput.value.trim();
            const song = document.getElementById('track-title').innerText.replace(/\s{2,}/g, ' ').trim();
            
            if (name.length < 3) {
                alert('Por favor, ingresa tu nombre arriba para dar Like.');
                nameInput.style.borderColor = '#ff4444';
                return;
            }

            const btn = document.getElementById('like-song-btn');
            const icon = btn.querySelector('i');
            
            icon.classList.remove('bi-heart');
            icon.classList.add('bi-heart-fill');
            btn.style.transform = 'scale(1.3)';
            
            try {
                const response = await fetch('api/like_song.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: name, song_title: song })
                });
                const result = await response.json();
                if (result.success) {
                    // Confetti explosion!
                    confetti({
                        particleCount: 100,
                        spread: 70,
                        origin: { y: 0.6 },
                        colors: ['#ff4444', '#00e676', '#38bdf8', '#facc15']
                    });

                    document.getElementById('like-count').innerText = result.likes_count;
                    setTimeout(() => {
                        btn.style.transform = 'scale(1)';
                    }, 200);
                    fetchMessages(); 
                    fetchTopFans(); // Update ranking
                }
            } catch (error) {
                console.error('Error liking song:', error);
            }
        }

        let recentTracks = JSON.parse(localStorage.getItem('recentTracks') || '[]');

        function renderRecentTracks() {
            const container = document.getElementById('recent-tracks-container');
            const list = document.getElementById('recent-tracks-list');
            if (!list || recentTracks.length === 0) {
                if (container) container.style.display = 'none';
                return;
            }
            if (container) container.style.display = 'block';
            list.innerHTML = '';
            recentTracks.forEach(track => {
                const item = document.createElement('div');
                item.style.display = 'flex';
                item.style.alignItems = 'center';
                item.style.gap = '10px';
                item.style.background = 'rgba(255,255,255,0.03)';
                item.style.padding = '5px 10px';
                item.style.borderRadius = '8px';
                item.style.fontSize = '0.75rem';
                item.style.border = '1px solid rgba(255,255,255,0.05)';
                
                const likesCount = track.likes || '0';
                
                item.innerHTML = `
                    <img src="${track.cover}" style="width: 35px; height: 35px; border-radius: 50%; object-fit: cover; border: 2px solid rgba(255,255,255,0.1); animation: spin-vinyl 45s linear infinite;">
                    <div style="flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; opacity: 0.9; font-weight: 600;">
                        ${track.title}
                    </div>
                    <div style="display: flex; align-items: center; gap: 3px; color: #ff4444; font-weight: bold; opacity: 0.9;">
                        <i class="bi bi-heart-fill" style="font-size: 0.65rem;"></i>
                        <span>${likesCount}</span>
                    </div>
                `;
                list.appendChild(item);
            });
        }

        // Initial render
        renderRecentTracks();

        async function fetchTopSongs() {
            try {
                const response = await fetch('api/top-songs.php');
                const result = await response.json();
                if (result.success && result.data) {
                    const list = document.getElementById('top-songs-list');
                    if (result.data.length === 0) {
                        list.innerHTML = '<div style="font-size: 0.8rem; opacity: 0.5; text-align: center;">Aún no hay votos esta semana.</div>';
                        return;
                    }
                    list.innerHTML = result.data.map((song, index) => `
                        <div style="display: flex; align-items: center; justify-content: space-between; background: rgba(255,255,255,0.05); padding: 0.6rem 0.8rem; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05); transition: transform 0.2s; cursor: default;" onmouseover="this.style.transform='translateX(5px)'" onmouseout="this.style.transform='translateX(0)'">
                            <div style="display: flex; align-items: center; gap: 10px; overflow: hidden;">
                                <span style="font-weight: 800; color: #facc15; font-size: 0.9rem; min-width: 20px;">#${index + 1}</span>
                                <span style="font-size: 0.85rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${song.song_title}</span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 4px; color: #ff4444; font-weight: bold; font-size: 0.8rem;">
                                <i class="bi bi-heart-fill"></i>
                                <span>${song.likes_count}</span>
                            </div>
                        </div>
                    `).join('');
                }
            } catch (error) {
                console.error('Error fetching top songs:', error);
            }
        }

        async function fetchTopListener() {
            try {
                const response = await fetch('api/get_top_requesters.php');
                const result = await response.json();
                if (result.success && result.data && result.data.length > 0) {
                    const top = result.data[0];
                    const section = document.getElementById('top-listener-section');
                    const display = document.getElementById('top-listener-display');
                    
                    display.innerHTML = `${top.requester} <span style="opacity: 0.7; font-size: 0.7rem; font-weight: 400;">(${top.total_requests} peticiones)</span>`;
                    section.style.display = 'block';
                }
            } catch (error) {
                console.error('Error fetching top listener:', error);
            }
        }

        // --- Sleep Timer & Upcoming Tracks ---
        let sleepTimeout = null;
        let sleepInterval = null;

        function openSleepModal() {
            const modal = document.getElementById('sleep-modal');
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
            
            // Show cancel option if active
            document.getElementById('cancel-sleep-option').style.display = sleepTimeout ? 'flex' : 'none';
        }

        function closeSleepModal() {
            const modal = document.getElementById('sleep-modal');
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }

        function setSleepTimer(minutes) {
            // Clear existing
            if (sleepTimeout) clearTimeout(sleepTimeout);
            if (sleepInterval) clearInterval(sleepInterval);
            
            if (minutes === 0) {
                document.getElementById('sleep-countdown').style.display = 'none';
                sleepTimeout = null;
                alert('Temporizador desactivado');
                closeSleepModal();
                return;
            }

            const ms = minutes * 60 * 1000;
            const endTime = Date.now() + ms;

            document.getElementById('sleep-countdown').style.display = 'block';
            
            function updateCountdown() {
                const now = Date.now();
                const diff = endTime - now;
                if (diff <= 0) {
                    clearInterval(sleepInterval);
                    if (!audio.paused) togglePlay();
                    document.getElementById('sleep-countdown').style.display = 'none';
                    sleepTimeout = null;
                    return;
                }
                const m = Math.floor(diff / 60000);
                const s = Math.floor((diff % 60000) / 1000);
                document.getElementById('sleep-time-left').innerText = `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
            }

            updateCountdown();
            sleepInterval = setInterval(updateCountdown, 1000);
            
            sleepTimeout = setTimeout(() => {
                // Done
            }, ms);

            alert(`La radio se apagará en ${minutes} minutos`);
            closeSleepModal();
        }

        async function fetchUpcomingTracks() {
            try {
                // RadioKing API for next tracks
                const response = await fetch('https://www.radioking.com/widgets/api/v1/radio/828046/track/next?limit=3');
                const tracks = await response.json();
                
                const container = document.getElementById('upcoming-tracks-container');
                const list = document.getElementById('upcoming-tracks-list');
                
                if (tracks && tracks.length > 0) {
                    container.style.display = 'block';
                    list.innerHTML = tracks.map(track => `
                        <div style="display: flex; align-items: center; gap: 12px; background: rgba(255,255,255,0.03); padding: 10px 15px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); transition: opacity 0.3s;">
                            <img src="${track.cover || './assets/pasted-20260215-163754-def41f49.png'}" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 2px solid rgba(255,255,255,0.1); animation: spin-vinyl 60s linear infinite;">
                            <div style="flex: 1; overflow: hidden;">
                                <div style="font-size: 0.9rem; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #fff;">${track.title}</div>
                                <div style="font-size: 0.75rem; opacity: 0.7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--primary-color);">${track.artist || 'Lili Records'}</div>
                            </div>
                        </div>
                    `).join('');
                } else {
                    container.style.display = 'none';
                }
            } catch (error) {
                console.error('Error fetching upcoming tracks:', error);
            }
        }

        // --- End Sleep Timer & Upcoming Tracks ---

        function openReportModal() {
            const modal = document.getElementById('report-modal');
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }

        function closeReportModal() {
            const modal = document.getElementById('report-modal');
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }

        async function submitReport() {
            const btn = document.getElementById('submit-report-btn');
            const type = document.getElementById('report-issue-type').value;
            const description = document.getElementById('report-description').value.trim();
            const name = document.getElementById('user-name').value.trim() || 'Anónimo';
            const phone = document.getElementById('user-phone').value.trim() || 'No proporcionado';
            const currentSong = document.getElementById('track-title').innerText;

            if (!description) {
                alert('Por favor, describe el problema.');
                return;
            }

            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> ENVIANDO...';

            try {
                const response = await fetch('api/report.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name: name,
                        email: phone, // Using phone as contact email since it's the identifier we have
                        issue_type: type,
                        description: description,
                        current_song: currentSong
                    })
                });
                const result = await response.json();
                if (result.success) {
                    alert('Gracias por tu reporte. Lo revisaremos pronto.');
                    document.getElementById('report-description').value = '';
                    closeReportModal();
                } else {
                    alert('Error: ' + (result.error || 'No se pudo enviar el reporte.'));
                }
            } catch (error) {
                console.error('Report error:', error);
                alert('Error de conexión al enviar el reporte.');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-megaphone-fill"></i> ENVIAR REPORTE';
            }
        }

        async function fetchLeaderboard() {
            const container = document.getElementById('leaderboard-list');
            const currentUserName = document.getElementById('user-name').value.trim();
            try {
                const response = await fetch(`api/get_top_fans.php?username=${encodeURIComponent(currentUserName)}`);
                const data = await response.json();
                
                if (data.success) {
                    if (data.fans.length === 0) {
                        container.innerHTML = '<div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 1rem;">No hay fans destacados aún.</div>';
                        return;
                    }
                    
                    // Filter out extra user if they are not in top 5 for the list display, 
                    // but we use them for the progress bar.
                    const topFans = data.fans.filter(f => !f.is_extra);
                    
                    container.innerHTML = topFans.map((fan, index) => `
                        <div class="leaderboard-item">
                            <div class="leaderboard-rank">${index + 1}</div>
                            ${fan.photo ? 
                                `<img src="${fan.photo}" alt="${fan.username}" class="leaderboard-avatar">` : 
                                `<div class="leaderboard-avatar" style="display: flex; align-items: center; justify-content: center; background: ${getUserColor(fan.username)}; color: #fff; font-weight: 800; border: none; font-size: 1.2rem; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">
                                    ${fan.username.charAt(0).toUpperCase()}
                                </div>`
                            }
                            <div class="leaderboard-info">
                                <div class="leaderboard-name">
                                    <span style="color: ${fan.level_color};">${fan.username}</span>
                                    ${fan.unlocked_emoji ? `<span style="font-size: 0.8rem;">${fan.unlocked_emoji}</span>` : ''}
                                    ${fan.badges.map(b => `<i class="bi ${b.icon}" style="color: ${b.color};" title="${b.label}"></i>`).join('')}
                                </div>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span class="level-badge" style="background: ${fan.level_color}; font-size: 0.55rem;">Nivel ${fan.level}</span>
                                    <div class="leaderboard-points">${parseInt(fan.total_likes).toLocaleString()} pts</div>
                                </div>
                            </div>
                        </div>
                    `).join('');

                    // Update current user's progress
                    if (currentUserName) {
                        const currentUserData = data.fans.find(f => f.username.toLowerCase() === currentUserName.toLowerCase());
                        if (currentUserData) {
                            showUserProgress(currentUserData);
                        } else {
                            document.getElementById('user-progress-container').style.display = 'none';
                        }
                    } else {
                        document.getElementById('user-progress-container').style.display = 'none';
                    }
                }
            } catch (error) {
                container.innerHTML = '<div style="opacity: 0.5; font-size: 0.85rem; text-align: center; padding: 1rem; color: #ff4444;">Error al cargar el ranking.</div>';
            }
        }

        let lastUserLevel = localStorage.getItem('lastUserLevel');

        function showUserProgress(fan) {
            const container = document.getElementById('user-progress-container');
            const badge = document.getElementById('user-level-badge');
            const name = document.getElementById('user-level-name');
            const pointsDisplay = document.getElementById('user-points-display');
            const bar = document.getElementById('user-level-bar');
            const rewards = document.getElementById('unlocked-rewards-msg');

            // Check for level up
            if (lastUserLevel && parseInt(fan.level) > parseInt(lastUserLevel)) {
                confetti({
                    particleCount: 200,
                    spread: 100,
                    origin: { y: 0.6 },
                    colors: ['#38bdf8', '#facc15', '#00e676', '#ffffff']
                });
                // Small delay to let the points update before showing the level up toast
                setTimeout(() => {
                    const toast = document.createElement('div');
                    toast.className = 'copy-toast';
                    toast.style.background = 'linear-gradient(135deg, #facc15, #fbbf24)';
                    toast.style.color = '#000';
                    toast.innerHTML = `<i class="bi bi-arrow-up-circle-fill"></i> ¡NIVEL SUBIDO! Ahora eres <b>${fan.level_name}</b>`;
                    document.body.appendChild(toast);
                    setTimeout(() => toast.remove(), 5000);
                }, 500);
            }
            lastUserLevel = fan.level;
            localStorage.setItem('lastUserLevel', fan.level);

            // Update shop points display
            const shopPoints = document.getElementById('shop-user-points');
            const shopLoyalty = document.getElementById('shop-user-loyalty');
            const mainLoyalty = document.getElementById('loyalty-points-display');
            if (shopPoints) shopPoints.innerText = `${parseInt(fan.total_likes).toLocaleString()} PTS`;
            if (shopLoyalty) shopLoyalty.innerText = `${parseInt(fan.loyalty_points || 0).toLocaleString()} LP`;
            if (mainLoyalty) mainLoyalty.innerText = `${parseInt(fan.loyalty_points || 0).toLocaleString()} LP`;

            container.style.display = 'block';
            badge.innerText = `Nivel ${fan.level}`;
            badge.style.background = fan.level_color;
            name.innerText = fan.level_name;
            name.style.color = fan.level_color;
            
            pointsDisplay.innerText = `${parseInt(fan.total_likes).toLocaleString()} / ${fan.next_level_points || 'MAX'} pts`;
            bar.style.width = `${fan.level_progress}%`;
            bar.style.boxShadow = `0 0 10px ${fan.level_color}`;

            let nextReward = '';
            switch(fan.level) {
                case 1: nextReward = 'Siguiente: Color de chat azul (100 pts)'; break;
                case 2: nextReward = 'Siguiente: Color verde + ⭐ Emoji (500 pts)'; break;
                case 3: nextReward = 'Siguiente: Color naranja + 🔥 Emoji (1000 pts)'; break;
                case 4: nextReward = 'Siguiente: Color púrpura + 👑 Emoji (2500 pts)'; break;
                default: nextReward = '¡Nivel Máximo alcanzado! Eres una Leyenda.'; break;
            }
            rewards.innerHTML = `<i class="bi bi-unlock-fill"></i> ${nextReward}`;
        }

        async function fetchGallery() {
            const container = document.getElementById('gallery-container');
            try {
                const response = await fetch('api/gallery.php');
                const data = await response.json();
                
                if (data.success) {
                    if (data.images.length === 0) {
                        container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 2rem; opacity: 0.5; font-size: 0.85rem;">Aún no hay fotos en la galería.</div>';
                        return;
                    }
                    
                    container.innerHTML = data.images.map(img => `
                        <div class="gallery-item" onclick="openLightbox('${img.image_url}', '${img.username}', '${img.caption || ''}')">
                            <img src="${img.image_url}" alt="Foto de ${img.username}">
                            <div style="position: absolute; top: 5px; right: 5px; background: rgba(255,0,0,0.8); color: white; font-size: 0.5rem; padding: 2px 4px; border-radius: 4px; font-weight: 800; z-index: 5;">5s</div>
                            <div class="gallery-overlay">
                                <span class="gallery-username">@${img.username}</span>
                                <span class="gallery-likes"><i class="bi bi-heart-fill"></i> ${img.likes}</span>
                            </div>
                        </div>
                    `).join('');
                }
            } catch (error) {
                container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 2rem; opacity: 0.5; font-size: 0.85rem; color: #ff4444;">Error al cargar la galería.</div>';
            }
        }

        function openLightbox(url, username, caption) {
            const lightbox = document.getElementById('lightbox');
            const img = document.getElementById('lightbox-img');
            const userText = document.getElementById('lightbox-username');
            const captionText = document.getElementById('lightbox-caption');
            
            img.src = url;
            userText.innerText = '@' + username;
            captionText.innerText = caption;
            
            lightbox.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function closeLightbox() {
            document.getElementById('lightbox').style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        // Fetch Now Playing Metadata
        let progressInterval = null;
        let currentTrackId = '';

        async function updateMetadata() {
            try {
                const response = await fetch('api/current_song.php');
                const data = await response.json();
                
                if (data && data.title) {
                    const title = data.title;
                    const artist = data.artist;
                    const album = data.album || '';
                    const coverUrl = data.cover || './assets/pasted-20260215-163754-def41f49.png';
                    const fullDisplay = `${artist} - ${title}`;
                    const source = data.source || 'radioking';
                    const requester = data.requester || '';

                    if (trackTitle.textContent !== title) {
                        currentTrackId = fullDisplay;
                        // If it's a local request, show special label
                        const label = document.querySelector('.track-label');
                        if (source === 'local_request') {
                            label.innerHTML = `PETICIÓN DE <span style="color: #facc15;">${requester.toUpperCase()}</span>:`;
                            label.style.animation = 'pulse 1s infinite';
                            if (data.youtube_url) {
                                const youtubeBtn = document.createElement('a');
                                youtubeBtn.href = data.youtube_url;
                                youtubeBtn.target = '_blank';
                                youtubeBtn.style.background = '#ff0000';
                                youtubeBtn.style.color = '#fff';
                                youtubeBtn.style.padding = '4px 10px';
                                youtubeBtn.style.borderRadius = '12px';
                                youtubeBtn.style.fontSize = '0.65rem';
                                youtubeBtn.style.fontWeight = '800';
                                youtubeBtn.style.textDecoration = 'none';
                                youtubeBtn.style.marginLeft = '10px';
                                youtubeBtn.innerHTML = '<i class="bi bi-youtube"></i> VER VIDEO';
                                label.appendChild(youtubeBtn);
                            }
                        } else {
                            label.innerText = 'ESTÁS ESCUCHANDO:';
                            label.style.animation = 'none';
                        }
                        trackTitle.style.opacity = '0';
                        if (trackArtist) trackArtist.style.opacity = '0';
                        if (trackAlbum) trackAlbum.style.opacity = '0';
                        if (trackCover) trackCover.style.opacity = '0';
                        
                        const likeIcon = document.querySelector('#like-song-btn i');
                        if (likeIcon) {
                            likeIcon.classList.remove('bi-heart-fill');
                            likeIcon.classList.add('bi-heart');
                        }
                        const likeCount = document.getElementById('like-count');
                        if (likeCount) likeCount.innerText = '';

                        trackTitle.classList.remove('scrolling');
                        setTimeout(async () => {
                            trackTitle.textContent = title;
                            if (trackArtist) trackArtist.textContent = artist;
                            
                            if (trackAlbum) {
                                if (album) {
                                    trackAlbum.textContent = album;
                                    trackAlbum.style.display = 'block';
                                    trackAlbum.style.opacity = '0.6';
                                } else {
                                    trackAlbum.style.display = 'none';
                                }
                            }

                            if (lyricsLink) {
                                lyricsLink.href = `lyrics.php?track=${encodeURIComponent(title)}&artist=${encodeURIComponent(artist)}`;
                                lyricsLink.style.display = 'flex';
                            }

                            const whatsappShareBtn = document.getElementById('whatsapp-share-track');
                            const facebookShareBtn = document.getElementById('facebook-share-track');
                            const twitterShareBtn = document.getElementById('twitter-share-track');
                            const instagramShareBtn = document.getElementById('instagram-share-track');
                            
                            const shareText = `¡Estoy escuchando "${title}" de ${artist} en Lili Records Radio! 🎶📻`;
                            const shareUrl = window.location.href;

                            if (whatsappShareBtn) {
                                whatsappShareBtn.href = `https://wa.me/?text=${encodeURIComponent(shareText + " Escúchala aquí: " + shareUrl)}`;
                                whatsappShareBtn.style.display = 'flex';
                            }
                            if (facebookShareBtn) {
                                facebookShareBtn.href = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}&quote=${encodeURIComponent(shareText)}`;
                                facebookShareBtn.style.display = 'flex';
                            }
                            if (twitterShareBtn) {
                                twitterShareBtn.href = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(shareUrl)}`;
                                twitterShareBtn.style.display = 'flex';
                            }
                            if (instagramShareBtn) {
                                instagramShareBtn.style.display = 'flex';
                                instagramShareBtn.onclick = (e) => {
                                    e.preventDefault();
                                    navigator.clipboard.writeText(shareText + " " + shareUrl).then(() => {
                                        const toast = document.createElement('div');
                                        toast.className = 'copy-toast';
                                        toast.style.background = 'linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%)';
                                        toast.innerHTML = `<i class="bi bi-instagram"></i> ¡Texto copiado! Pégalo en Instagram`;
                                        document.body.appendChild(toast);
                                        setTimeout(() => {
                                            toast.remove();
                                            window.open('https://www.instagram.com/', '_blank');
                                        }, 1500);
                                    });
                                };
                            }
                            
                            trackTitle.style.opacity = '1';
                            if (trackArtist) trackArtist.style.opacity = '0.8';
                            
                            if (trackCover) {
                                trackCover.src = coverUrl;
                                trackCover.style.display = 'block';
                                if (coverPlaceholder) coverPlaceholder.style.display = 'none';
                                trackCover.style.opacity = '1';
                                
                                // Save to recent tracks if changed
                                const currentTrackFull = `${artist} - ${title}`;
                                if (recentTracks.length === 0 || recentTracks[0].title !== currentTrackFull) {
                                    const newTrack = { 
                                        title: currentTrackFull, 
                                        cover: coverUrl, 
                                        likes: 0 
                                    };
                                    recentTracks.unshift(newTrack);
                                    if (recentTracks.length > 6) recentTracks.pop();
                                    localStorage.setItem('recentTracks', JSON.stringify(recentTracks));
                                    renderRecentTracks();
                                }

                                fetch('api/record_history.php', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({ title: title, artist: artist, cover: coverUrl })
                                }).catch(err => console.error("Error recording history:", err));

                                trackCover.onload = function() {
                                    try {
                                        const canvas = document.createElement('canvas');
                                        const ctx = canvas.getContext('2d');
                                        canvas.width = 1;
                                        canvas.height = 1;
                                        ctx.drawImage(trackCover, 0, 0, 1, 1);
                                        const rgb = ctx.getImageData(0, 0, 1, 1).data;
                                        if (rgb[0] + rgb[1] + rgb[2] > 30) {
                                            const color = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
                                            document.documentElement.style.setProperty('--primary-color', color);
                                        }
                                    } catch(e) {}
                                };
                            }

                            fetch(`api/pexels.php?query=${encodeURIComponent(artist + " " + title + " music background")}`)
                                .then(res => res.json())
                                .then(pData => {
                                    if (pData.success && pData.url && bg) {
                                        bg.style.backgroundImage = `url('${pData.url}')`;
                                    }
                                }).catch(() => {});

                            const progContainer = document.getElementById('track-progress-container');
                            const progBar = document.getElementById('track-progress-bar');
                            
                            if (data.started_at && data.end_at && progContainer && progBar) {
                                progContainer.style.display = 'block';
                                const start = new Date(data.started_at).getTime();
                                const end = new Date(data.end_at).getTime();
                                const duration = end - start;

                                function updateProgressBar() {
                                    const now = new Date().getTime();
                                    const elapsed = now - start;
                                    
                                    let percent = (elapsed / duration) * 100;
                                    if (percent > 100) percent = 100;
                                    if (percent < 0) percent = 0;
                                    progBar.style.width = percent + '%';
                                    if (percent >= 100) {
                                        clearInterval(progressInterval);
                                        // Play transition sound
                                        transitionAudio.volume = 0.5;
                                        transitionAudio.play().catch(e => console.log('Transition sound blocked:', e));
                                        
                                        // Trigger automation check and metadata refresh immediately
                                        fetch('api/automation.php').finally(() => {
                                            setTimeout(updateMetadata, 1000);
                                        });
                                    }
                                }
                                
                                updateProgressBar();
                                if (progressInterval) clearInterval(progressInterval);
                                progressInterval = setInterval(updateProgressBar, 1000);
                            } else if (progContainer) {
                                progContainer.style.display = 'none';
                            }

                            try {
                                const lResp = await fetch(`api/get_likes.php?song_title=${encodeURIComponent(fullDisplay)}`);
                                const lData = await lResp.json();
                                if (lData.likes_count > 0 && likeCount) {
                                    likeCount.innerText = lData.likes_count;
                                }
                            } catch (e) {}

                            if (trackTitle.scrollWidth > trackTitle.clientWidth) {
                                trackTitle.classList.add('scrolling');
                                trackTitle.innerHTML = `<span>${title} &nbsp;&nbsp;&nbsp;&nbsp; ${title} &nbsp;&nbsp;&nbsp;&nbsp;</span>`;
                            }

                            const stickyBar = document.getElementById('sticky-now-playing');
                            const stickyCover = document.getElementById('sticky-track-cover');
                            const stickyInfo = document.getElementById('sticky-track-info');
                            if (stickyBar && stickyCover && stickyInfo) {
                                stickyCover.src = coverUrl;
                                stickyInfo.textContent = `${artist} - ${title}`;
                                stickyBar.style.display = 'block';
                            }
                        }, 500);
                    }
                    
                    document.title = `▶ ${fullDisplay} | Lili Records Radio`;

                    if ('mediaSession' in navigator) {
                        navigator.mediaSession.metadata = new MediaMetadata({
                            title: title,
                            artist: artist,
                            album: 'Lili Records Radio',
                            artwork: [{ src: coverUrl, sizes: '512x512', type: 'image/png' }]
                        });
                    }
                } else {
                    trackTitle.textContent = "Lili Records Radio - En Vivo";
                }
            } catch (error) {
                console.error('Error fetching metadata:', error);
                if (trackTitle.textContent === "Cargando stream...") {
                    trackTitle.textContent = "Lili Records Radio - En Vivo";
                }
            }
        }

        // Update cycles
        setInterval(updateMetadata, 30000);
        setInterval(fetchTopSongs, 60000);
        setInterval(fetchTopListener, 60000);
        setInterval(fetchGallery, 3000); // Frecuencia aumentada para fotos efímeras (5s)
        setInterval(fetchLeaderboard, 60000);
        setInterval(fetchUpcomingTracks, 30000);
        setInterval(fetchActivePerks, 30000);
        setInterval(updateVipTimers, 1000);
        
        const ticTacAudio = new Audio('https://assets.mixkit.co/active_storage/sfx/560/560-preview.mp3');
        const applauseAudio = new Audio('https://assets.mixkit.co/active_storage/sfx/467/467-preview.mp3'); // Crowd Cheer
        const transitionAudio = new Audio('https://assets.mixkit.co/active_storage/sfx/2013/2013-preview.mp3'); // Ding
        
        function testTicTac() {
            const btn = document.getElementById('test-tictac-btn');
            ticTacAudio.volume = 0.5;
            ticTacAudio.play();
            btn.style.background = '#facc15';
            btn.style.color = '#000';
            setTimeout(() => {
                btn.style.background = '';
                btn.style.color = '';
            }, 2000);
        }

        function testApplause() {
            const btn = document.getElementById('test-applause-btn');
            applauseAudio.volume = 0.4;
            applauseAudio.play();
            btn.style.background = '#f472b6';
            btn.style.color = '#fff';
            setTimeout(() => {
                btn.style.background = '';
                btn.style.color = '';
            }, 3000);
        }

        function updateVipTimers() {
            let shouldPlayTicTac = false;
            document.querySelectorAll('.vip-timer').forEach(timer => {
                const startStr = timer.dataset.start;
                if (!startStr) return;

                const start = new Date(startStr.replace(' ', 'T')).getTime();
                const now = new Date().getTime();
                const diff = 300 - Math.floor((now - start) / 1000); // 300 seconds = 5 min
                
                const valueSpan = timer.querySelector('.timer-value');
                if (diff <= 0) {
                    timer.innerHTML = '<i class="bi bi-clock-history"></i> BONO EXPIRADO';
                    timer.style.color = '#94a3b8';
                    timer.style.background = 'rgba(0,0,0,0.5)';
                } else {
                    const m = Math.floor(diff / 60);
                    const s = diff % 60;
                    valueSpan.innerText = `${m}:${s.toString().padStart(2, '0')}`;
                    
                    // Color logic
                    if (diff < 60) {
                        timer.style.color = '#ff4444';
                        timer.classList.add('counter-alert');
                        
                        // Tic-tac logic (last 10 seconds)
                        if (diff <= 10) {
                            shouldPlayTicTac = true;
                        }
                    } else if (diff < 180) {
                        timer.style.color = '#facc15';
                        timer.classList.remove('counter-alert');
                    } else {
                        timer.style.color = '#22c55e';
                        timer.classList.remove('counter-alert');
                    }
                }
            });

            if (shouldPlayTicTac) {
                ticTacAudio.currentTime = 0;
                ticTacAudio.play().catch(() => {});
            }
        }

        // Initial fetch
        updateMetadata();
        fetchTopSongs();
        fetchTopListener();
        fetchGallery();
        fetchLeaderboard();
        fetchUpcomingTracks();
        fetchActivePerks();

        // Theme Toggle Functionality
        function toggleTheme() {
            const body = document.body;
            const currentTheme = body.getAttribute('data-theme');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            const themeBtn = document.getElementById('theme-toggle').querySelector('i');
            const switchDot = document.getElementById('theme-switch-dot');
            
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            
            if (newTheme === 'light') {
                themeBtn.classList.remove('bi-moon-fill');
                themeBtn.classList.add('bi-sun-fill');
                if (switchDot) switchDot.style.left = '2px';
            } else {
                themeBtn.classList.remove('bi-sun-fill');
                themeBtn.classList.add('bi-moon-fill');
                if (switchDot) switchDot.style.left = '22px';
            }
        }

        // Initialize Theme
        (function() {
            const savedTheme = localStorage.getItem('theme') || 'dark';
            const switchDot = document.getElementById('theme-switch-dot');
            if (savedTheme === 'light') {
                document.body.setAttribute('data-theme', 'light');
                const themeBtn = document.getElementById('theme-toggle').querySelector('i');
                themeBtn.classList.remove('bi-moon-fill');
                themeBtn.classList.add('bi-sun-fill');
                if (switchDot) switchDot.style.left = '2px';
            } else {
                if (switchDot) switchDot.style.left = '22px';
            }
            
            // Welcome logic for new users
            setTimeout(() => {
                const welcomeName = localStorage.getItem('userName');
                if (welcomeName) {
                    showWelcomeToast(welcomeName);
                }
            }, 2000);
        })();

        function showWelcomeToast(name) {
            const welcomeSound = document.getElementById('welcome-sound');
            if (welcomeSound) {
                welcomeSound.volume = 0.5;
                welcomeSound.play().catch(e => console.log('Welcome sound blocked:', e));
            }

            const toast = document.createElement('div');
            toast.className = 'copy-toast';
            toast.style.background = 'linear-gradient(135deg, var(--primary-color), var(--accent-color))';
            toast.style.bottom = 'auto';
            toast.style.top = '30px';
            toast.innerHTML = `<i class="bi bi-stars"></i> ¡Bienvenido de nuevo, ${name}! Disfruta de la mejor música.`;
            document.body.appendChild(toast);
            
            confetti({
                particleCount: 100,
                spread: 70,
                origin: { y: 0.3 },
                colors: ['#38bdf8', '#00c853', '#ffffff']
            });

            setTimeout(() => toast.remove(), 4000);
        }

        function announceOnAir() {
            const currentSong = document.getElementById('track-title').innerText.trim();
            const shareUrl = window.location.origin + window.location.pathname;
            const text = `🔴 *¡ESTAMOS AL AIRE!* 🎙️📻\n\nSintoniza ahora *Lili Records Radio* para escuchar la mejor música en vivo.\n\n🎵 *Sonando:* ${currentSong}\n\n👉 *Escúchanos aquí:* ${shareUrl}\n\n¡Te esperamos! 💃🕺\n\n#LiliRecords #RadioEnVivo #LaQueTeGusta`;
            
            const url = `https://wa.me/?text=${encodeURIComponent(text)}`;
            window.open(url, '_blank');
        }

        // Handle possible audio interruptions
        audio.addEventListener('error', function(e) {
            console.error('Audio error:', e);
            trackTitle.textContent = "Error de conexión. Reintentando...";
            setTimeout(() => {
                audio.load();
                if (!audio.paused) audio.play();
            }, 5000);
        });

        // --- Radio Shop Functionality ---
        function openShopModal() {
            const modal = document.getElementById('shop-modal');
            const userName = document.getElementById('user-name').value.trim();
            
            if (!userName) {
                alert('Por favor, ingresa tu nombre arriba para acceder a la tienda.');
                document.getElementById('user-name').focus();
                document.getElementById('user-name').style.borderColor = '#facc15';
                return;
            }

            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
            fetchLeaderboard(); // This updates user points
        }

        function closeShopModal() {
            const modal = document.getElementById('shop-modal');
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }

        async function fetchActivePerks() {
            try {
                const response = await fetch('api/get_active_perks.php');
                const data = await response.json();
                
                if (data.success) {
                    // Pinned Message
                    const pinned = data.perks.pinned_message;
                    const pinnedEl = document.getElementById('pinned-message');
                    if (pinned) {
                        document.getElementById('pinned-content').innerText = pinned.perk_value;
                        document.getElementById('pinned-author').innerText = `Por: ${pinned.user_name}`;
                        pinnedEl.style.display = 'block';
                    } else {
                        pinnedEl.style.display = 'none';
                    }

                    // Background
                    const background = data.perks.background;
                    if (background && bg) {
                        bg.style.backgroundImage = `url('${background.perk_value}')`;
                    }
                }
            } catch (error) {
                console.error('Error fetching perks:', error);
            }
        }

        async function buyPerk(action, value) {
            const userName = document.getElementById('user-name').value.trim();
            try {
                const formData = new FormData();
                formData.append('action', action);
                formData.append('username', userName);
                formData.append('value', value);

                const response = await fetch('api/shop.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                
                if (result.success) {
                    confetti({
                        particleCount: 150,
                        spread: 70,
                        origin: { y: 0.6 },
                        colors: ['#facc15', '#fbbf24', '#ffffff']
                    });
                    alert(result.message);
                    closeShopModal();
                    fetchActivePerks();
                    fetchLeaderboard();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Buy error:', error);
                alert('Error de conexión al realizar la compra.');
            }
        }

        function promptBuyPinnedMessage() {
            const msg = prompt('Escribe el mensaje que quieres fijar (máx 100 carac.):');
            if (msg && msg.trim()) {
                if (msg.length > 100) {
                    alert('El mensaje es demasiado largo.');
                    return;
                }
                buyPerk('pinned_message', msg.trim());
            }
        }

        function promptBuyBackground() {
            const query = prompt('¿De qué quieres que sea el nuevo fondo? (ej: cyberpunk, ocean, tropical):');
            if (query && query.trim()) {
                // Fetch image from pexels first
                fetch(`api/pexels.php?query=${encodeURIComponent(query.trim())}`)
                    .then(res => res.json())
                    .then(data => {
                        if (data.success && data.url) {
                            if (confirm('¿Te gusta este fondo? Lo activaremos para todos por 1000 pts.')) {
                                buyPerk('background', data.url);
                            }
                        } else {
                            alert('No encontramos una imagen para esa búsqueda.');
                        }
                    });
            }
        }

        async function redeemItem(item, color = null) {
            const userName = document.getElementById('user-name').value.trim();
            if (!userName) return;

            try {
                const response = await fetch('api/redeem.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: userName, item: item, color: color })
                });
                const result = await response.json();
                
                if (result.success) {
                    confetti({
                        particleCount: 200,
                        spread: 100,
                        origin: { y: 0.6 },
                        colors: ['#facc15', '#f472b6', '#38bdf8', '#ffffff']
                    });
                    alert(result.message);
                    closeShopModal();
                    fetchLeaderboard();
                    if (typeof fetchMessages === 'function') fetchMessages();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Redeem error:', error);
                alert('Error de conexión al realizar el canje.');
            }
        }

        function promptBuyGodMode() {
            const color = prompt('MODO DIOS: Elige un color hexadecimal para tu nombre (ej: #FFD700 para Oro, #00FFFF para Cian):', '#FFD700');
            if (color) {
                if (!/^#[0-9A-F]{6}$/i.test(color)) {
                    alert('Por favor, ingresa un código hexadecimal válido (ej: #FFD700).');
                    return;
                }
                redeemItem('god_mode', color);
            }
        }

        function promptBuyDjDay() {
            if (confirm('¿Quieres convertirte en DJ INVITADO por 2000 pts? Tu nombre destacará en toda la sala por 24 horas.')) {
                redeemItem('dj_day');
            }
        }

        function promptBuyVipJump() {
            const artist = prompt('Ingresa el ARTISTA para tu Salto VIP:');
            if (!artist) return;
            const song = prompt(`Ingresa la CANCIÓN de ${artist} para tu Salto VIP:`);
            if (!song) return;

            if (confirm(`¿Confirmas gastar 500 LP para que "${artist} - ${song}" suene inmediatamente?`)) {
                redeemItem('vip_jump', null, artist, song);
            }
        }

        async function submitVipJump() {
            const artistInput = document.getElementById('req-artist-new');
            const songInput = document.getElementById('req-song-new');
            const artist = artistInput.value.trim();
            const song = songInput.value.trim();
            const requester = document.getElementById('user-name').value.trim();

            if (!requester) {
                alert('Por favor, ingresa tu nombre arriba para usar el Salto VIP.');
                document.getElementById('user-name').focus();
                return;
            }

            if (!artist || !song) {
                alert('Por favor, ingresa el artista y la canción que quieres priorizar.');
                return;
            }

            if (confirm(`¿Quieres usar 500 LP para que "${artist} - ${song}" suene ahora mismo?`)) {
                const btn = document.getElementById('vip-jump-btn');
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass-split"></i>...';

                try {
                    const response = await fetch('api/redeem.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            username: requester, 
                            item: 'vip_jump',
                            artist: artist,
                            song: song
                        })
                    });
                    const result = await response.json();
                    
                    if (result.success) {
                        confetti({
                            particleCount: 300,
                            spread: 120,
                            origin: { y: 0.6 },
                            colors: ['#00e676', '#facc15', '#ffffff']
                        });
                        alert(result.message);
                        artistInput.value = '';
                        songInput.value = '';
                        fetchSongRequests();
                        fetchLeaderboard();
                    } else {
                        alert('Error: ' + result.error);
                    }
                } catch (error) {
                    console.error('VIP Jump error:', error);
                    alert('Error de conexión.');
                } finally {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-lightning-charge-fill"></i> VIP JUMP';
                }
            }
        }

        async function redeemItem(item, color = null, artist = null, song = null) {
            const userName = document.getElementById('user-name').value.trim();
            if (!userName) return;

            try {
                const response = await fetch('api/redeem.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        username: userName, 
                        item: item, 
                        color: color,
                        artist: artist,
                        song: song
                    })
                });
                const result = await response.json();
                
                if (result.success) {
                    confetti({
                        particleCount: 200,
                        spread: 100,
                        origin: { y: 0.6 },
                        colors: ['#facc15', '#f472b6', '#38bdf8', '#ffffff']
                    });
                    alert(result.message);
                    closeShopModal();
                    fetchLeaderboard();
                    if (typeof fetchMessages === 'function') fetchMessages();
                    if (item === 'vip_jump') fetchSongRequests();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Redeem error:', error);
                alert('Error de conexión al realizar el canje.');
            }
        }

        setInterval(fetchActivePerks, 10000);
        fetchActivePerks();
        // --- End Radio Shop Functionality ---

        // --- DJ Flores Functionality ---
        let lastCelebrationId = 0;
        const shownTips = new Set();

        function openFlowersModal() {
            const userName = document.getElementById('user-name').value.trim();
            if (!userName) {
                alert('Por favor, ingresa tu nombre arriba para regalar flores.');
                document.getElementById('user-name').focus();
                return;
            }
            document.getElementById('flowers-modal').classList.add('show');
        }

        function closeFlowersModal() {
            document.getElementById('flowers-modal').classList.remove('show');
        }

        async function sendFlowersToDJ() {
            openFlowersModal();
        }

        async function confirmSendFlowers() {
            const userName = document.getElementById('user-name').value.trim();
            const message = document.getElementById('flower-message').value.trim();
            const btn = document.getElementById('confirm-flowers-btn');
            
            try {
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass-split"></i> ENVIANDO...';
                
                const formData = new FormData();
                formData.append('username', userName);
                formData.append('amount', 100);
                formData.append('message', message);

                const response = await fetch('api/send_tip.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (data.success) {
                    closeFlowersModal();
                    document.getElementById('flower-message').value = '';
                    launchFlowerCelebration(userName, message); // Local trigger with message
                    fetchLeaderboard(); // Update points
                } else {
                    alert(data.error);
                }
            } catch (e) {
                console.error('Error sending flowers:', e);
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-send-fill"></i> ENVIAR POR 100 PTS';
            }
        }

        async function pollCelebrations() {
            try {
                const response = await fetch('api/get_latest_tips.php');
                const data = await response.json();

                if (data.success) {
                    // Update DJ Name
                    if (data.current_dj) {
                        document.getElementById('current-dj-name').innerText = data.current_dj.toUpperCase();
                    }

                    // Check for new tips
                    data.tips.forEach(tip => {
                        if (!shownTips.has(tip.id)) {
                            shownTips.add(tip.id);
                            launchFlowerCelebration(tip.sender_name, tip.message, tip.id);
                            console.log(`Celebration for tip from ${tip.sender_name}`);
                        }
                    });

                    // Check for new thanks
                    if (data.thanks) {
                        data.thanks.forEach(thank => {
                            const thankKey = `thank_${thank.id}`;
                            if (!shownTips.has(thankKey)) {
                                shownTips.add(thankKey);
                                launchDJThanksCelebration(thank.sender_name);
                            }
                        });
                    }
                    
                    // Cleanup set to keep it small
                    if (shownTips.size > 100) {
                        const it = shownTips.values();
                        shownTips.delete(it.next().value);
                    }
                }
            } catch (e) {
                console.error('Error polling celebrations:', e);
            }
        }

        function launchFlowerCelebration(senderName = "", donorMessage = "", tipId = null) {
            // Celebration confetti burst
            confetti({
                particleCount: 150,
                spread: 70,
                origin: { y: 0.6 },
                colors: ['#f472b6', '#fb7185', '#ec4899', '#ffffff', '#ffd700'],
                shapes: ['circle', 'square'],
                scalar: 1.2
            });

            const container = document.getElementById('celebration-overlay');
            
            // Floating Name Message
            if (senderName) {
                const message = document.createElement('div');
                message.className = 'donor-message';
                message.innerHTML = `
                    <h4>¡DONACIÓN DE FLORES!</h4>
                    <h2>${senderName}</h2>
                    ${donorMessage ? `<p>"${donorMessage}"</p>` : ''}
                `;

                if (isAdmin && tipId) {
                    const thankBtn = document.createElement('div');
                    thankBtn.style.marginTop = '15px';
                    thankBtn.style.pointerEvents = 'auto';
                    thankBtn.innerHTML = `
                        <button onclick="thankDonor(${tipId}, this)" style="background: var(--accent-color); color: white; border: none; padding: 10px 20px; border-radius: 50px; font-weight: 800; cursor: pointer; display: flex; align-items: center; gap: 8px; margin: 0 auto; box-shadow: 0 4px 10px rgba(0, 230, 118, 0.3); transition: transform 0.2s;">
                            <i class="bi bi-heart-fill"></i> Agradecer
                        </button>
                    `;
                    message.appendChild(thankBtn);
                }

                container.appendChild(message);
                setTimeout(() => {
                    if (message.parentNode) message.remove();
                }, 8000); 
            }

            const emojis = ['🌸', '🌹', '🌺', '🌻', '🌼', '🌷', '✨', '💖'];
            const count = 30;

            for (let i = 0; i < count; i++) {
                setTimeout(() => {
                    const flower = document.createElement('div');
                    flower.className = 'flower-particle';
                    flower.innerText = emojis[Math.floor(Math.random() * emojis.length)];
                    
                    const left = Math.random() * 100;
                    const sway = (Math.random() - 0.5) * 200;
                    const duration = 3 + Math.random() * 4;
                    
                    flower.style.left = `${left}%`;
                    flower.style.setProperty('--sway', `${sway}px`);
                    flower.style.setProperty('--duration', `${duration}s`);
                    flower.style.fontSize = `${1.5 + Math.random() * 2}rem`;
                    
                    container.appendChild(flower);
                    
                    setTimeout(() => {
                        if (flower.parentNode) flower.remove();
                    }, duration * 1000);
                }, i * 100);
            }
        }

        async function thankDonor(tipId, btn) {
            if (btn) {
                btn.disabled = true;
                btn.style.opacity = "0.7";
                btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Enviando...';
            }
            try {
                const response = await fetch('api/thank_tip.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ tip_id: tipId })
                });
                const data = await response.json();
                if (data.success) {
                    if (btn) btn.innerHTML = '<i class="bi bi-check-circle-fill"></i> ¡Agradecido!';
                } else {
                    if (btn) {
                        btn.disabled = false;
                        btn.style.opacity = "1";
                        btn.innerHTML = '<i class="bi bi-heart-fill"></i> Agradecer';
                        alert("Error: " + data.error);
                    }
                }
            } catch (e) {
                console.error("Error thanking donor:", e);
                if (btn) {
                    btn.disabled = false;
                    btn.style.opacity = "1";
                    btn.innerHTML = '<i class="bi bi-heart-fill"></i> Agradecer';
                }
            }
        }

        function launchDJThanksCelebration(donorName) {
            const container = document.getElementById('celebration-overlay');
            const message = document.createElement('div');
            message.className = 'donor-message';
            message.style.borderColor = '#00e676';
            message.style.boxShadow = '0 20px 40px rgba(0, 230, 118, 0.4)';
            message.innerHTML = `
                <h4 style="color: #00e676;">¡EL DJ TE AGRADECE!</h4>
                <h2 style="background: linear-gradient(to right, #ffffff, #00e676); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">${donorName}</h2>
                <p>"¡Muchas gracias por tu regalo! ❤️"</p>
            `;
            container.appendChild(message);
            setTimeout(() => {
                if (message.parentNode) message.remove();
            }, 6000);

            // Heart confetti
            const duration = 3 * 1000;
            const end = Date.now() + duration;

            (function frame() {
                confetti({
                    particleCount: 3,
                    angle: 60,
                    spread: 55,
                    origin: { x: 0 },
                    colors: ['#ff0000', '#ff69b4', '#00e676'],
                    shapes: ['circle']
                });
                confetti({
                    particleCount: 3,
                    angle: 120,
                    spread: 55,
                    origin: { x: 1 },
                    colors: ['#ff0000', '#ff69b4', '#00e676'],
                    shapes: ['circle']
                });

                if (Date.now() < end) {
                    requestAnimationFrame(frame);
                }
            }());
        }

        // Initialize polling
        // --- DJ Shoutout Functionality ---
        async function adminOpenShoutout() {
            const target = prompt("¿A quién quieres mandarle un saludo?");
            if (!target) return;
            const message = prompt(`¿Qué mensaje quieres decirle a ${target}?`, "¡Gracias por estar en sintonía con Lili Records!");
            if (!message) return;

            try {
                const response = await fetch('api/send_shoutout.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ target_name: target, message: message })
                });
                const data = await response.json();
                if (data.success) {
                    alert("¡Mención enviada con éxito!");
                } else {
                    alert("Error: " + data.error);
                }
            } catch (e) {
                console.error("Error sending shoutout:", e);
            }
        }

        async function pollShoutouts() {
            const userName = document.getElementById('user-name').value.trim();
            if (!userName) return;

            try {
                const response = await fetch(`api/get_shoutouts.php?user_name=${encodeURIComponent(userName)}`);
                const data = await response.json();

                if (data.success && data.shoutout) {
                    showShoutoutModal(data.shoutout);
                }
            } catch (e) {
                console.error("Error polling shoutouts:", e);
            }
        }

        function showShoutoutModal(shoutout) {
            const modal = document.getElementById('shoutout-modal');
            const targetEl = document.getElementById('shoutout-target');
            const msgEl = document.getElementById('shoutout-message');
            const djEl = document.getElementById('shoutout-dj-name');
            const userName = document.getElementById('user-name').value.trim();

            targetEl.innerText = `¡Para ${userName}!`;
            msgEl.innerText = shoutout.message;
            djEl.innerText = shoutout.dj_name;

            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
            
            // Celebration confetti
            confetti({
                particleCount: 250,
                spread: 160,
                origin: { y: 0.6 },
                colors: ['#facc15', '#38bdf8', '#ff4444', '#00e676', '#ffffff']
            });

            // Audio cue if possible
            try {
                const audio = new Audio('https://www.soundjay.com/buttons/sounds/button-3.mp3');
                audio.volume = 0.5;
                audio.play();
            } catch(e) {}
        }

        setInterval(pollShoutouts, 5000);
        setInterval(pollCelebrations, 5000);
        pollCelebrations();
        // --- End DJ Shoutout Functionality ---

        audio.addEventListener('error', function(e) {
            console.error('Audio error:', e);
            trackTitle.textContent = "Error de conexión. Reintentando...";
            setTimeout(() => {
                audio.load();
                if (!audio.paused) audio.play();
            }, 5000);
        });
    </script>
</body>
</html>