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

// =============================================================================
// HISTORIA — Galería animada de archivo histórico
// =============================================================================

const historiaItems = [
{
  id: "h1",
  src: "assets/historia/01-revista-portada.jpeg",
  year: "2002",
  title: "QUIÉN LA LLEVA",
  body: "Los Reyes de la Calle en portada. 47 jóvenes de las poblaciones más marginales de Santiago reescribiendo lo que significa ser deportista en Chile.",
  tag: "Prensa",
  aspect: "portrait"
},
{
  id: "h2",
  src: "assets/historia/02-and1-mixtape-tour.jpeg",
  year: "2004",
  title: "AND1 MIXTAPE TOUR · CHILE",
  body: "El tour mundial de AND1 aterriza en Chile y nosotros somos parte. Mural, sneakers, crossover. La cultura street llega oficialmente al sur del mundo.",
  tag: "Tour",
  aspect: "wide"
},
{
  id: "h3",
  src: "assets/historia/03-sba-usa.jpeg",
  year: "2003",
  title: "VS. TEAM USA",
  body: "Los mejores jugadores chilenos exhibieron sus habilidades ante los estadounidenses del Team AND1. Una noche en la que el barrio se midió con el mundo.",
  tag: "Encuentro",
  aspect: "wide"
},
{
  id: "h4",
  src: "assets/historia/04-gimnasio-osorno.jpeg",
  year: "2003",
  title: "OSORNO RESPONDE",
  body: "Gimnasio lleno. El streetball cruzó la cordillera de norte a sur. Equipos de toda la región sur respondieron al llamado de la calle.",
  tag: "Tour Sur",
  aspect: "wide"
},
{
  id: "h5",
  src: "assets/historia/05-aca-tu-pones-reglas.jpeg",
  year: "2003",
  title: "ACÁ TÚ PONES LAS REGLAS",
  body: "Elvis Marte del Team AND1 lo dijo claro: en la calle no hay árbitros, hay códigos. Una herramienta de inserción social para los jóvenes lejos de los vicios.",
  tag: "Editorial",
  aspect: "portrait"
},
{
  id: "h6",
  src: "assets/historia/06-la-moneda.jpeg",
  year: "2003",
  title: "EL STREETBALL LLEGÓ A LA MONEDA",
  body: "Una invasión de ritmo y color interrumpió los tonos grises del centro cívico. El intendente Trivelli se animó a jugar un rato con los muchachos.",
  tag: "Hito",
  aspect: "portrait"
},
{
  id: "h7",
  src: "assets/historia/07-trivelli-plaza.jpeg",
  year: "2003",
  title: "PLAZA DE LA CONSTITUCIÓN",
  body: "El intendente Marcelo Trivelli fue el invitado de honor en la exhibición que el tour montó frente a La Moneda. Autoridades sentadas en el suelo, escuchando.",
  tag: "Hito",
  aspect: "wide"
},
{
  id: "h8",
  src: "assets/historia/08-tour-streetbolers.jpeg",
  year: "2004",
  title: "EL TOUR EN MARCHA",
  body: "Camión rotulado, equipo completo, próxima parada. Llevamos el streetball y el hip hop a cada comuna que abrió sus puertas.",
  tag: "Tour",
  aspect: "wide"
}];


const Historia = () => {
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const [lightbox, setLightbox] = useState(null);
  const scrollerRef = useRef(null);
  const total = historiaItems.length;

  // Auto-advance
  useEffect(() => {
    if (paused || lightbox) return;
    const t = setInterval(() => setActive((a) => (a + 1) % total), 5500);
    return () => clearInterval(t);
  }, [paused, lightbox, total]);

  // Sync thumbnail strip scroll position (solo dentro del scroller horizontal, sin tocar el scroll de la página)
  useEffect(() => {
    if (!scrollerRef.current) return;
    const scroller = scrollerRef.current;
    const el = scroller.querySelector(`[data-thumb="${active}"]`);
    if (el) {
      const left = el.offsetLeft - scroller.clientWidth / 2 + el.clientWidth / 2;
      scroller.scrollTo({ left, behavior: "smooth" });
    }
  }, [active]);

  const next = () => setActive((a) => (a + 1) % total);
  const prev = () => setActive((a) => (a - 1 + total) % total);

  const current = historiaItems[active];

  return (
    <section
      id="archivo-historico"
      data-screen-label="Historia"
      className="relative py-12 md:py-16 bg-[#0A0807] overflow-hidden"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}>
      
      {/* Texture overlay */}
      <div
        className="absolute inset-0 opacity-[0.04] pointer-events-none"
        style={{
          backgroundImage:
          "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence baseFrequency='0.85' numOctaves='2'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>\")"
        }} />
      

      <div className="relative max-w-[1440px] mx-auto px-6 md:px-10">
        {/* Header */}
        <div className="grid lg:grid-cols-12 gap-8 items-end mb-10">
          <div className="lg:col-span-7">
            <div className="text-[#FF6D0D] uppercase tracking-[0.3em] text-xs mb-4" style={{ fontFamily: "Inter, sans-serif" }}>
              ·  Archivo Histórico · 2003 → Hoy
            </div>
            <h2
              className="text-white"
              style={{
                fontFamily: "'Anton', sans-serif",
                fontSize: "clamp(40px, 6vw, 96px)",
                lineHeight: 0.92
              }}>
              
              ASÍ <span className="text-[#FF6D0D]">FUE.</span><br />
              ASÍ <span className="text-[#FF6D0D]">SIGUE.</span>
            </h2>
          </div>
          <div className="lg:col-span-5 text-white/70 text-base md:text-lg leading-relaxed" style={{ fontFamily: "Inter, sans-serif" }}>
            <p className="mb-3">
              Recorrimos comunas, gimnasios y espacios públicos llevando el streetball a la gente.
              Eventos masivos, prensa, La Moneda, Osorno, partidos contra la SBA de Estados Unidos.
            </p>
            <p className="text-white/55 text-sm">
              Detrás de cada evento hubo jugadores, DJ, animadores, entrenadores, amistades, familias y público.
              El movimiento generó lazos, experiencias e identidad — más de 20 años después, todavía late.
            </p>
          </div>
        </div>

        {/* Main stage */}
        <div className="grid lg:grid-cols-12 gap-6 lg:gap-10">
          {/* Image stage */}
          <div className="lg:col-span-8 relative">
            <div
              className="relative aspect-[4/3] md:aspect-[16/10] overflow-hidden bg-black border border-white/10"
              onClick={() => setLightbox(current)}
              role="button"
              tabIndex={0}>
              
              {historiaItems.map((it, i) =>
              <div
                key={it.id}
                className="absolute inset-0 transition-all duration-1000 ease-out"
                style={{
                  opacity: i === active ? 1 : 0,
                  transform: i === active ? "scale(1)" : "scale(1.06)",
                  pointerEvents: i === active ? "auto" : "none"
                }}>
                
                  <img
                  src={it.src}
                  alt={it.title}
                  className="w-full h-full object-cover"
                  style={{ filter: "contrast(1.05) saturate(0.85)" }} />
                
                  {/* Vintage paper grain on photo */}
                  <div className="absolute inset-0 bg-gradient-to-tr from-[#FF6D0D]/10 via-transparent to-amber-200/5 mix-blend-overlay pointer-events-none" />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/10 to-transparent" />

                  {/* Year sticker */}
                  <div
                  className="absolute top-5 left-5 bg-[#FF6D0D] text-black px-3 py-1.5 rotate-[-4deg] shadow-lg"
                  style={{ fontFamily: "'Anton', sans-serif", letterSpacing: "0.08em" }}>
                  
                    <span className="text-base md:text-lg">{it.year}</span>
                  </div>

                  {/* Tag */}
                  <div className="absolute top-5 right-5 bg-black/70 backdrop-blur-sm border border-white/15 px-3 py-1.5">
                    <span className="text-white text-[10px] uppercase tracking-[0.25em]" style={{ fontFamily: "Inter, sans-serif" }}>
                      {it.tag}
                    </span>
                  </div>

                  {/* Zoom hint */}
                  <div className="absolute bottom-5 right-5 w-10 h-10 rounded-full bg-white/10 backdrop-blur-sm border border-white/20 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity group-hover:opacity-100">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2"><circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35M8 11h6M11 8v6" /></svg>
                  </div>
                </div>
              )}

              {/* Prev / Next */}
              <button
                type="button"
                onClick={(e) => {e.stopPropagation();prev();}}
                className="absolute top-1/2 -translate-y-1/2 left-3 w-10 h-10 md:w-12 md:h-12 rounded-full bg-black/60 backdrop-blur-sm border border-white/15 text-white hover:bg-[#FF6D0D] hover:text-black hover:border-[#FF6D0D] flex items-center justify-center transition-all"
                aria-label="Anterior">
                
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M15 18l-6-6 6-6" /></svg>
              </button>
              <button
                type="button"
                onClick={(e) => {e.stopPropagation();next();}}
                className="absolute top-1/2 -translate-y-1/2 right-3 w-10 h-10 md:w-12 md:h-12 rounded-full bg-black/60 backdrop-blur-sm border border-white/15 text-white hover:bg-[#FF6D0D] hover:text-black hover:border-[#FF6D0D] flex items-center justify-center transition-all"
                aria-label="Siguiente">
                
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M9 18l6-6-6-6" /></svg>
              </button>

              {/* Progress bar */}
              <div className="absolute bottom-0 left-0 right-0 h-1 bg-white/10">
                <div
                  key={active + (paused ? "-p" : "")}
                  className="h-full bg-[#FF6D0D]"
                  style={{
                    animation: paused || lightbox ? "none" : "historiaProgress 5500ms linear forwards"
                  }} />
                
              </div>
            </div>

            {/* Counter */}
            <div className="mt-3 flex items-center justify-between text-white/50 text-xs uppercase tracking-[0.25em]" style={{ fontFamily: "Inter, sans-serif" }}>
              <span>{String(active + 1).padStart(2, "0")} <span className="text-white/30">/ {String(total).padStart(2, "0")}</span></span>
              <button
                onClick={() => setPaused((p) => !p)}
                className="hover:text-[#FF6D0D] transition-colors flex items-center gap-2">
                
                {paused ?
                <><svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg> Reanudar</> :

                <><svg width="10" height="10" 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> Pausar</>
                }
              </button>
            </div>
          </div>

          {/* Caption + thumbnail rail */}
          <div className="lg:col-span-4 flex flex-col">
            <div className="flex-1 mb-6">
              <div
                key={"cap-" + active}
                style={{ animation: "historiaFadeUp 0.6s ease forwards" }}>
                
                <div className="text-[#FF6D0D] text-[10px] uppercase tracking-[0.3em] mb-2" style={{ fontFamily: "Inter, sans-serif" }}>
                  {current.tag} · {current.year}
                </div>
                <h3
                  className="text-white mb-4"
                  style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(28px, 3.2vw, 42px)", lineHeight: 0.95 }}>
                  
                  {current.title}
                </h3>
                <p className="text-white/70 text-base leading-relaxed" style={{ fontFamily: "Inter, sans-serif" }}>
                  {current.body}
                </p>
              </div>
            </div>

            {/* Thumbnails */}
            <div className="border-t border-white/10 pt-5">
              <div className="text-white/40 text-[10px] uppercase tracking-[0.3em] mb-3" style={{ fontFamily: "Inter, sans-serif" }}>
                Línea de tiempo
              </div>
              <div
                ref={scrollerRef}
                className="flex gap-2 overflow-x-auto pb-2 historia-scroller"
                style={{ scrollSnapType: "x mandatory" }}>
                
                {historiaItems.map((it, i) =>
                <button
                  key={it.id}
                  data-thumb={i}
                  onClick={() => setActive(i)}
                  className={
                  "shrink-0 relative w-20 h-14 md:w-24 md:h-16 border-2 overflow-hidden transition-all " + (
                  i === active ? "border-[#FF6D0D] scale-105" : "border-white/10 opacity-60 hover:opacity-100")
                  }
                  style={{ scrollSnapAlign: "center" }}
                  aria-label={it.title}>
                  
                    <img src={it.src} alt="" className="w-full h-full object-cover" />
                    <div className={"absolute inset-0 " + (i === active ? "bg-transparent" : "bg-black/30 hover:bg-transparent")} />
                    <div className="absolute bottom-0.5 left-0.5 right-0.5 text-[8px] text-white bg-black/60 px-1 text-center" style={{ fontFamily: "Inter, sans-serif" }}>
                      {it.year}
                    </div>
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Quote band */}
        <div className="mt-12 md:mt-16 border-l-4 border-[#FF6D0D] pl-6 md:pl-10 max-w-3xl">
          <p className="text-white/90 text-xl md:text-2xl leading-relaxed" style={{ fontFamily: "'Anton', sans-serif", letterSpacing: "0.01em" }}>
            "ACÁ TÚ PONES LAS REGLAS."
          </p>
          <p className="text-white/40 text-xs uppercase tracking-[0.25em] mt-2" style={{ fontFamily: "Inter, sans-serif" }}>— TEAM AND1, OCTUBRE 2003

          </p>
        </div>
      </div>

      <style>{`
        @keyframes historiaProgress {
          from { width: 0%; }
          to { width: 100%; }
        }
        @keyframes historiaFadeUp {
          from { opacity: 0; transform: translateY(12px); }
          to { opacity: 1; transform: none; }
        }
        .historia-scroller::-webkit-scrollbar { height: 4px; }
        .historia-scroller::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); }
        .historia-scroller::-webkit-scrollbar-thumb { background: #FF6D0D; }
      `}</style>

      {/* Lightbox */}
      {lightbox &&
      <div
        onClick={() => setLightbox(null)}
        className="fixed inset-0 z-[150] bg-black/95 backdrop-blur-md flex items-center justify-center p-4 md:p-10 cursor-pointer"
        style={{ animation: "fadeIn 0.25s ease" }}>
        
          <button
          type="button"
          onClick={() => setLightbox(null)}
          className="fixed top-4 right-4 md:top-6 md:right-6 w-12 h-12 rounded-full bg-[#FF6D0D] hover:bg-[#ff8530] text-black flex items-center justify-center transition-all hover:scale-110 z-[160] shadow-[0_6px_24px_rgba(0,0,0,0.6)]"
          aria-label="Cerrar">
          
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>
          <div className="max-w-6xl w-full max-h-full flex flex-col" onClick={(e) => e.stopPropagation()}>
            <img src={lightbox.src} alt={lightbox.title} className="max-w-full max-h-[78vh] mx-auto object-contain" />
            <div className="mt-4 text-center">
              <div className="text-[#FF6D0D] text-xs uppercase tracking-[0.3em] mb-1" style={{ fontFamily: "Inter, sans-serif" }}>
                {lightbox.tag} · {lightbox.year}
              </div>
              <h3 className="text-white text-2xl md:text-3xl" style={{ fontFamily: "'Anton', sans-serif" }}>
                {lightbox.title}
              </h3>
              <p className="text-white/70 text-sm md:text-base max-w-2xl mx-auto mt-3" style={{ fontFamily: "Inter, sans-serif" }}>
                {lightbox.body}
              </p>
            </div>
          </div>
        </div>
      }
    </section>);

};

window.Historia = Historia;