/* global React */
const { useState, useEffect, useRef } = React;

// =============================================================================
// AUDIO PLAYER — Banda sonora del Reino
// =============================================================================

const AudioPlayer = () => {
  const audioRef = useRef(null);
  const [playing, setPlaying] = useState(false);
  const [current, setCurrent] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(0.8);
  const [muted, setMuted] = useState(false);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    const onTime = () => setCurrent(a.currentTime);
    const onMeta = () => {setDuration(a.duration);setLoaded(true);};
    const onEnd = () => setPlaying(false);
    a.addEventListener("timeupdate", onTime);
    a.addEventListener("loadedmetadata", onMeta);
    a.addEventListener("ended", onEnd);
    return () => {
      a.removeEventListener("timeupdate", onTime);
      a.removeEventListener("loadedmetadata", onMeta);
      a.removeEventListener("ended", onEnd);
    };
  }, []);

  const toggle = async () => {
    const a = audioRef.current;
    if (!a) return;
    if (playing) {
      a.pause();
      setPlaying(false);
    } else {
      try {await a.play();setPlaying(true);} catch (e) {console.warn(e);}
    }
  };

  const seek = (e) => {
    const a = audioRef.current;
    if (!a || !duration) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const pct = (e.clientX - rect.left) / rect.width;
    a.currentTime = Math.max(0, Math.min(duration, pct * duration));
  };

  const changeVolume = (v) => {
    setVolume(v);
    if (audioRef.current) audioRef.current.volume = v;
    if (v > 0 && muted) {
      setMuted(false);
      if (audioRef.current) audioRef.current.muted = false;
    }
  };

  const toggleMute = () => {
    const m = !muted;
    setMuted(m);
    if (audioRef.current) audioRef.current.muted = m;
  };

  const fmt = (s) => {
    if (!s || isNaN(s)) return "0:00";
    const m = Math.floor(s / 60);
    const ss = Math.floor(s % 60);
    return `${m}:${ss.toString().padStart(2, "0")}`;
  };

  const progress = duration ? current / duration * 100 : 0;

  return (
    <section
      id="banda-sonora"
      data-screen-label="Banda Sonora"
      className="relative py-14 md:py-20 bg-[#020100] overflow-hidden border-y border-white/5">
      
      {/* Background art */}
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute -left-32 top-1/2 -translate-y-1/2 w-[600px] h-[600px] rounded-full bg-[#FF6D0D]/10 blur-[160px]" />
        <div className="absolute -right-20 bottom-0 w-[400px] h-[400px] rounded-full bg-[#FF6D0D]/8 blur-[140px]" />
        <div
          className="absolute inset-0 opacity-[0.05]"
          style={{ backgroundImage: "url('assets/camo-pattern.jpeg')", backgroundSize: "600px", mixBlendMode: "screen" }} />
        
      </div>

      <div className="relative max-w-[1440px] mx-auto px-6 md:px-10">
        <div className="grid lg:grid-cols-12 gap-8 lg:gap-12 items-center">
          {/* Left — section copy */}
          <div className="lg:col-span-4">
            <div className="text-[#FF6D0D] uppercase tracking-[0.3em] text-xs mb-4" style={{ fontFamily: "Inter, sans-serif" }}>
              ·  Banda sonora del Reino
            </div>
            <h2
              className="text-white mb-4"
              style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(36px, 5vw, 72px)", lineHeight: 0.95 }}>
              
              LA CALLE<br /><span className="text-[#FF6D0D]">SUENA ASÍ.</span>
            </h2>
            <p className="text-white/65 text-base leading-relaxed" style={{ fontFamily: "Inter, sans-serif" }}>
              Cada cancha tiene su soundtrack. El nuestro lo escribe el barrio.
              Hip-hop chileno hecho por uno de los nuestros, para sonar fuerte cuando el balón pica.
            </p>

            <div className="mt-6 flex items-center gap-3 text-white/45 text-[10px] uppercase tracking-[0.3em]" style={{ fontFamily: "Inter, sans-serif" }}>
              <span>Track 01</span>
              <span className="w-1 h-1 rounded-full bg-[#FF6D0D]" />
              <span>2026</span>
            </div>
          </div>

          {/* Right — player */}
          <div className="lg:col-span-8">
            <div className="relative bg-gradient-to-br from-[#0F0C0A] to-[#070504] border border-white/10 p-5 md:p-8 shadow-[0_20px_60px_-20px_rgba(0,0,0,0.8)]">
              {/* Top brand strip */}
              <div className="flex items-center justify-between mb-6 pb-4 border-b border-white/5">
                <div className="flex items-center gap-2 text-white/40 text-[10px] uppercase tracking-[0.3em]" style={{ fontFamily: "Inter, sans-serif" }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3v10.55A4 4 0 1014 17V7h4V3h-6z" /></svg>
                  Reyes Records · 01
                </div>
                <div className="text-white/30 text-[10px] uppercase tracking-[0.3em] hidden md:block" style={{ fontFamily: "Inter, sans-serif" }}>
                  Hip-Hop · Chile
                </div>
              </div>

              <div className="flex flex-col md:flex-row gap-6 md:gap-8 items-center md:items-start">
                {/* Cover art — vinyl */}
                <div className="relative shrink-0">
                  <div className="relative w-44 h-44 md:w-48 md:h-48">
                    {/* Vinyl behind */}
                    <div
                      className="absolute inset-0 rounded-full bg-gradient-to-br from-[#1a1614] via-black to-[#0a0807] border border-white/10"
                      style={{
                        transform: `translateX(${playing ? '30%' : '0%'}) rotate(${playing ? 'var(--spin)' : '0deg'})`,
                        animation: playing ? "audioVinyl 4s linear infinite" : "none",
                        transition: "transform 0.7s cubic-bezier(.4,.1,.2,1)"
                      }}>
                      
                      {/* Vinyl grooves */}
                      <div className="absolute inset-3 rounded-full border border-white/5" />
                      <div className="absolute inset-6 rounded-full border border-white/5" />
                      <div className="absolute inset-10 rounded-full border border-white/5" />
                      <div className="absolute inset-14 rounded-full border border-white/5" />
                      {/* Center label */}
                      <div className="absolute inset-0 m-auto w-12 h-12 rounded-full bg-[#FF6D0D] flex items-center justify-center">
                        <div className="w-2 h-2 rounded-full bg-black" />
                      </div>
                    </div>
                    {/* Album art on top of vinyl */}
                    <div className="absolute inset-0 overflow-hidden border-2 border-[#FF6D0D]/30 shadow-[0_10px_30px_-10px_rgba(255,109,13,0.4)]">
                      <img src="assets/king-painting.jpeg" alt="DARWIN album art" className="w-full h-full object-cover" />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
                      <div className="absolute bottom-2 left-2 right-2">
                        <div className="text-white text-[10px] uppercase tracking-[0.25em]" style={{ fontFamily: "Inter, sans-serif" }}>aka Atomic10</div>
                        <div className="text-[#FF6D0D]" style={{ fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.04em" }}>2026</div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Player controls */}
                <div className="flex-1 w-full">
                  <div className="mb-1 flex items-center gap-2">
                    <span className="bg-[#FF6D0D] text-black text-[9px] uppercase tracking-[0.3em] font-bold px-2 py-0.5" style={{ fontFamily: "'Anton', sans-serif" }}>
                      Single
                    </span>
                    <span className="text-white/30 text-[10px] uppercase tracking-[0.25em]" style={{ fontFamily: "Inter, sans-serif" }}>
                      2026
                    </span>
                  </div>
                  <h3 className="text-white mb-1" style={{ fontFamily: "'Anton', sans-serif", fontSize: 44, lineHeight: 0.95, letterSpacing: "0.01em" }}>AKA ATOMIC10

                  </h3>
                  <div className="text-white/55 text-sm uppercase tracking-[0.2em]" style={{ fontFamily: "Inter, sans-serif" }}>
                    aka <span className="text-[#FF6D0D] font-semibold">ORIGINAL</span>
                  </div>

                  {/* Equalizer */}
                  <div className="mt-5 flex items-end gap-0.5 h-8 opacity-90">
                    {Array.from({ length: 48 }).map((_, i) =>
                    <span
                      key={i}
                      className="w-1 bg-[#FF6D0D] rounded-sm"
                      style={{
                        height: playing ?
                        `${20 + Math.abs(Math.sin(Date.now() / 200 + i)) * 80}%` :
                        `${8 + i * 7 % 5 * 4}%`,
                        opacity: playing ? 0.6 + i % 3 * 0.15 : 0.25,
                        animation: playing ? `audioBar 0.${4 + i % 6}s ease-in-out infinite alternate` : "none",
                        animationDelay: `${i * 0.03}s`
                      }} />

                    )}
                  </div>

                  {/* Scrubber */}
                  <div
                    className="mt-5 group cursor-pointer"
                    onClick={seek}>
                    
                    <div className="relative h-1.5 bg-white/10 overflow-hidden">
                      <div
                        className="absolute inset-y-0 left-0 bg-[#FF6D0D] transition-[width] duration-100"
                        style={{ width: `${progress}%` }} />
                      
                      <div
                        className="absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                        style={{ left: `calc(${progress}% - 6px)` }} />
                      
                    </div>
                    <div className="flex justify-between text-[10px] mt-2 text-white/45 font-mono uppercase tracking-wider">
                      <span>{fmt(current)}</span>
                      <span>{fmt(duration)}</span>
                    </div>
                  </div>

                  {/* Controls row */}
                  <div className="mt-5 flex items-center gap-4">
                    <button
                      onClick={toggle}
                      className="group relative w-14 h-14 rounded-full bg-[#FF6D0D] hover:bg-[#ff8530] text-black flex items-center justify-center transition-all hover:scale-105 shadow-[0_8px_24px_-6px_rgba(255,109,13,0.6)]"
                      aria-label={playing ? "Pausar" : "Reproducir"}>
                      
                      {playing ?
                      <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" /><rect x="14" y="5" width="4" height="14" /></svg> :

                      <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" style={{ marginLeft: 2 }}><path d="M8 5v14l11-7z" /></svg>
                      }
                    </button>

                    <div className="flex items-center gap-2 flex-1">
                      <button onClick={toggleMute} className="text-white/60 hover:text-[#FF6D0D] transition-colors" aria-label="Silenciar">
                        {muted || volume === 0 ?
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 5L6 9H2v6h4l5 4V5zM23 9l-6 6M17 9l6 6" /></svg> :
                        volume > 0.5 ?
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 5L6 9H2v6h4l5 4V5zM15.54 8.46a5 5 0 010 7.07M19.07 4.93a10 10 0 010 14.14" /></svg> :

                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 5L6 9H2v6h4l5 4V5zM15.54 8.46a5 5 0 010 7.07" /></svg>
                        }
                      </button>
                      <input
                        type="range" min="0" max="1" step="0.01" value={muted ? 0 : volume}
                        onChange={(e) => changeVolume(parseFloat(e.target.value))}
                        className="audio-volume max-w-[120px]" />
                      
                    </div>

                    <div className="text-white/30 text-[10px] uppercase tracking-[0.25em] hidden sm:block" style={{ fontFamily: "Inter, sans-serif" }}>
                      {loaded ? "♪ 320 kbps" : "Cargando..."}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Hidden audio element */}
      <audio
        ref={audioRef}
        src="assets/darwin.mp3"
        preload="metadata" />
      

      <style>{`
        @keyframes audioVinyl {
          from { transform: translateX(30%) rotate(0deg); }
          to { transform: translateX(30%) rotate(360deg); }
        }
        @keyframes audioBar {
          0%, 100% { transform: scaleY(0.4); }
          50% { transform: scaleY(1); }
        }
        .audio-volume {
          -webkit-appearance: none;
          appearance: none;
          width: 100%;
          height: 3px;
          background: rgba(255,255,255,0.12);
          outline: none;
          cursor: pointer;
        }
        .audio-volume::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background: #FF6D0D;
          cursor: pointer;
        }
        .audio-volume::-moz-range-thumb {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background: #FF6D0D;
          border: none;
          cursor: pointer;
        }
      `}</style>
    </section>);

};

window.AudioPlayer = AudioPlayer;