const { useState, useEffect, useRef, useMemo } = React;

// ——————————————————————————————————————————————————
//  Top bar
// ——————————————————————————————————————————————————
const TopBar = ({ theme, onToggleTheme }) => {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const fmt = time.toLocaleTimeString("es-VE", { hour: "2-digit", minute: "2-digit" });
  return (
    <header className="topbar">
      <div className="topbar-inner container">
        <div className="topbar-left">
          <div className="mark">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
              <circle cx="12" cy="12" r="10" />
              <path d="M2 12 Q 12 4 22 12 Q 12 20 2 12 Z" />
              <circle cx="12" cy="12" r="2.5" fill="currentColor" />
            </svg>
          </div>
          <div className="mark-text">
            <span className="mark-title">Venezuela de Ayer</span>
            <span className="mark-sub">Archivo Visual · est. 2026</span>
          </div>
        </div>
        <nav className="topbar-nav">
          <a href="#mapa">Mapa</a>
          <a href="#archivo">Archivo</a>
          <a href="#decadas">Décadas</a>
          <a href="#sobre">Sobre</a>
        </nav>
        <div className="topbar-right">
          <span className="topbar-time">{fmt} · CCS</span>
          <button className="theme-btn" onClick={onToggleTheme} aria-label="Cambiar tema">
            {theme === "dark" ? "☀ Día" : "☾ Noche"}
          </button>
        </div>
      </div>
    </header>
  );
};

// ——————————————————————————————————————————————————
//  Hero
// ——————————————————————————————————————————————————
const Hero = () => {
  const video = useMemo(() => (typeof pickHeroVideo === "function" ? pickHeroVideo() : null), []);
  return (
    <section className="hero">
      <div className="container hero-inner">
        <div className="hero-meta">
          <div className="hero-meta-row">
            <span className="eyebrow">Vol. 01 · Caracas</span>
            <span className="eyebrow">№ 001 — 167</span>
          </div>
          <hr className="rule" />
        </div>

        <div className="hero-grid">
          <div className="hero-left">
            <p className="eyebrow hero-kicker">un archivo vivo</p>
            <h1 className="hero-title">
              <span className="ht-line ht-1">Venezuela</span>
              <span className="ht-line ht-2"><em>de&nbsp;</em>ayer<span className="hero-dot">.</span></span>
            </h1>
            <p className="hero-lede">
              Un atlas afectivo de comerciales, avisos y postales. La memoria de un país contada
              cuadro por cuadro, jingle por jingle, esquina por esquina.
            </p>
            <div className="hero-ctas">
              <a href="#mapa" className="btn btn--primary">
                Entrar al archivo
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 12h14M13 6l6 6-6 6"/>
                </svg>
              </a>
              <a href="#decadas" className="btn">Explorar por década</a>
            </div>
          </div>

          <div className="hero-right">
            <div className="hero-card">
              <div className="hero-card-head">
                <span className="eyebrow">Pieza del día</span>
                {video?.duration && <span className="eyebrow hero-card-dur">{video.duration}</span>}
              </div>
              {video ? (
                <RetroTV channel="02" title={video.title} year={video.year} mode="hero">
                  <iframe
                    src={`https://www.youtube-nocookie.com/embed/${video.id}?autoplay=1&mute=1&loop=1&playlist=${video.id}&controls=1&rel=0&modestbranding=1&playsinline=1`}
                    title={video.title}
                    frameBorder="0"
                    allow="autoplay; encrypted-media; picture-in-picture"
                    allowFullScreen
                    style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
                  />
                </RetroTV>
              ) : (
                <RetroTV channel="02" title="«Sabor de Venezuela»" year="MCMLXV" showBars />
              )}
              <div className="hero-card-foot">
                <p className="hero-card-blurb">
                  {video?.blurb || "“Un instante de dulzura para los venezolanos.” Comercial de Savoy, recuperado de una cinta VHS familiar donada en 2024."}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Pillar strip */}
        <div className="hero-pillars">
          {PILLARS.map((p, i) => (
            <div className="pillar" key={p.id}>
              <div className="pillar-num">{String(i+1).padStart(2,"0")}</div>
              <div className="pillar-body">
                <div className="pillar-kind">{p.kind}</div>
                <div className="pillar-label">{p.label}</div>
              </div>
              <div className="pillar-count">{p.count}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Marquee */}
      <div className="marquee">
        <div className="marquee-track">
          {[...MARQUEE_ITEMS, ...MARQUEE_ITEMS, ...MARQUEE_ITEMS].map((t, i) => (
            <span key={i} className="marquee-item">{t}</span>
          ))}
        </div>
      </div>
    </section>
  );
};

// ——————————————————————————————————————————————————
//  Interactive Map (illustration + hotspots + caption cards)
// ——————————————————————————————————————————————————
const MapSection = ({ onOpenVideo }) => {
  const [hoveredId, setHoveredId] = useState(null);
  const [activeId, setActiveId] = useState(null);
  const wrapRef = useRef(null);

  const hovered = HOTSPOTS.find(h => h.id === hoveredId);

  // Parallax tilt based on mouse
  const [tilt, setTilt] = useState({ x: 0, y: 0 });
  const handleMove = (e) => {
    if (!wrapRef.current) return;
    const r = wrapRef.current.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    setTilt({ x: px * 14, y: py * 8 });
  };
  const resetTilt = () => setTilt({ x: 0, y: 0 });

  return (
    <section id="mapa" className="map-section">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">Cap. I · El Mapa</span>
            <h2 className="section-title">Una ciudad hecha de recuerdos.</h2>
          </div>
          <p className="section-dek">
            Cada punto rojo es una memoria recuperada. Haz click sobre cualquier edificio,
            esquina o letrero para reproducir el comercial, el aviso o la fotografía que
            lo habita.
          </p>
        </div>

        <div className="map-wrap" ref={wrapRef} onMouseMove={handleMove} onMouseLeave={resetTilt}>
          {/* Corner ticks */}
          <span className="tick t-tl" /><span className="tick t-tr" />
          <span className="tick t-bl" /><span className="tick t-br" />

          {/* Folio numbers */}
          <div className="folio folio-l">
            <span>N°</span><span>002</span>
          </div>
          <div className="folio folio-r">
            <span>LÁMINA</span><span>I</span>
          </div>

          <h3 className="map-heading">
            <span className="map-heading-kicker">LÁMINA I —</span>
            Caracas
            <span className="map-heading-year">ca. 1950 — 1989</span>
          </h3>

          <div className="illo-scale" style={{
            transform: `perspective(1400px) rotateY(${tilt.x * 0.15}deg) rotateX(${-tilt.y * 0.15}deg) translate3d(${tilt.x * 0.4}px, ${tilt.y * 0.4}px, 0)`,
          }}>
            <CityIllustration
              onHotspotClick={onOpenVideo}
              activeId={activeId}
              hoveredId={hoveredId}
              setHoveredId={setHoveredId}
            />
          </div>

          {/* Floating caption card */}
          {hovered && (
            <HoverCaption hot={hovered} />
          )}

          {/* Legend */}
          <div className="map-legend">
            <div className="legend-row">
              <span className="legend-dot" /> punto clickeable
            </div>
            <div className="legend-row">
              <span className="eyebrow">{HOTSPOTS.length} memorias en esta lámina</span>
            </div>
          </div>
        </div>

        {/* Hotspot index */}
        <div className="hotspot-index">
          {HOTSPOTS.map((h, i) => (
            <button
              key={h.id}
              className={"hidx " + (hoveredId===h.id ? "is-hover" : "")}
              onMouseEnter={() => setHoveredId(h.id)}
              onMouseLeave={() => setHoveredId(null)}
              onClick={() => onOpenVideo(h)}
            >
              <span className="hidx-num">{String(i+1).padStart(2,"0")}</span>
              <span className="hidx-title">{h.title}</span>
              <span className="hidx-kind">{h.kind}</span>
              <span className="hidx-year">{h.year}</span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
};

const HoverCaption = ({ hot }) => {
  return (
    <div className="hover-cap" style={{
      left: `${hot.x}%`,
      top: `${hot.y}%`,
    }}>
      <div className="hover-cap-inner">
        <div className="hc-num">№ {String(HOTSPOTS.indexOf(hot)+1).padStart(3,"0")}</div>
        <div className="hc-title">{hot.title}</div>
        <div className="hc-meta">{hot.kind} · {hot.year}</div>
        <div className="hc-blurb">{hot.blurb}</div>
        <div className="hc-cta">
          <span className="hc-play">▶</span>
          <span>Click para reproducir</span>
        </div>
      </div>
    </div>
  );
};

// ——————————————————————————————————————————————————
//  Archive grid
// ——————————————————————————————————————————————————
const ArchiveSection = ({ onOpenVideo }) => {
  const [decade, setDecade] = useState("all");
  const [category, setCategory] = useState("all");

  const items = useMemo(() => {
    return ARCHIVE.filter(a =>
      (decade === "all" || a.era === decade) &&
      (category === "all" || a.category === category)
    );
  }, [decade, category]);

  const cats = [
    { id: "all", label: "Todo" },
    { id: "tv", label: "Televisión" },
    { id: "print", label: "Impresos" },
    { id: "places", label: "Lugares" },
  ];

  return (
    <section id="archivo" className="archive-section">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">Cap. II · El Archivo</span>
            <h2 className="section-title">
              <em>Todo</em> lo que sobrevivió.
            </h2>
          </div>
          <p className="section-dek">
            Un índice abierto de comerciales, avisos impresos y fotografías rescatadas de
            cintas familiares, revistas y archivos personales. Filtra por década o por medio.
          </p>
        </div>

        <div className="filters">
          <div className="filter-group">
            <span className="filter-label">Década</span>
            <div className="filter-chips">
              <button className={"chip " + (decade==="all" ? "on":"")} onClick={()=>setDecade("all")}>Todas</button>
              {DECADES.map(d => (
                <button key={d} className={"chip " + (decade===d ? "on":"")} onClick={()=>setDecade(d)}>{d}</button>
              ))}
            </div>
          </div>
          <div className="filter-group">
            <span className="filter-label">Medio</span>
            <div className="filter-chips">
              {cats.map(c => (
                <button key={c.id} className={"chip " + (category===c.id ? "on":"")} onClick={()=>setCategory(c.id)}>
                  {c.label}
                </button>
              ))}
            </div>
          </div>
          <div className="filter-count eyebrow">
            {items.length} piezas
          </div>
        </div>

        <div className="archive-grid">
          {items.map((a, i) => (
            <ArchiveCard key={a.id} item={a} index={i} onOpen={() => onOpenVideo({
              id: a.id,
              title: a.title,
              kind: a.source,
              year: a.era,
              place: a.source,
              blurb: "Del archivo " + a.source + ".",
              youtube: a.youtube,
            })} />
          ))}
        </div>
      </div>
    </section>
  );
};

const ArchiveCard = ({ item, index, onOpen }) => {
  const isPrint = item.category === "print" || item.duration === "Impreso" || item.duration === "Foto";
  return (
    <button className={"acard acard--" + item.tone + (isPrint ? " acard--print" : " acard--tv")}
            onClick={onOpen}>
      <div className="acard-thumb">
        <div className={"acard-fill acard-fill--" + item.tone}>
          {/* Abstract thumb: stripes for TV, halftone for print */}
          {isPrint ? (
            <PrintThumb tone={item.tone} title={item.title} />
          ) : (
            <TvThumb tone={item.tone} />
          )}
        </div>
        <div className="acard-badge">
          {isPrint ? "IMPRESO" : "▶ VIDEO"}
        </div>
      </div>
      <div className="acard-body">
        <div className="acard-meta">
          <span className="acard-num">№ {String(index+1).padStart(3,"0")}</span>
          <span className="acard-era">{item.era}</span>
        </div>
        <div className="acard-title">{item.title}</div>
        <div className="acard-source">{item.source} · {item.duration}</div>
      </div>
    </button>
  );
};

const TvThumb = ({ tone }) => (
  <svg viewBox="0 0 200 120" className="thumb-svg" preserveAspectRatio="none">
    <rect x="0" y="0" width="200" height="120" fill="#1a140e" />
    {/* scanlines */}
    {Array.from({length: 30}).map((_, i) => (
      <rect key={i} x="0" y={i*4} width="200" height="1" fill="rgba(255,255,255,0.06)" />
    ))}
    {/* abstract frame */}
    <rect x="20" y="30" width="70" height="60" fill={`var(--${tone})`} opacity="0.7" />
    <rect x="100" y="40" width="80" height="40" fill="#f5e8d0" opacity="0.2" />
    <circle cx="140" cy="60" r="14" fill="#f5e8d0" opacity="0.3" />
    {/* vignette */}
    <rect x="0" y="0" width="200" height="120" fill="url(#vign)" />
    <defs>
      <radialGradient id="vign">
        <stop offset="60%" stopColor="#000" stopOpacity="0"/>
        <stop offset="100%" stopColor="#000" stopOpacity="0.7"/>
      </radialGradient>
    </defs>
  </svg>
);

const PrintThumb = ({ tone, title }) => (
  <svg viewBox="0 0 200 120" className="thumb-svg" preserveAspectRatio="none">
    <rect x="0" y="0" width="200" height="120" fill="#ecdfc7" />
    {/* Halftone dots */}
    <defs>
      <pattern id={"ht-"+tone} width="5" height="5" patternUnits="userSpaceOnUse">
        <circle cx="2.5" cy="2.5" r="1.2" fill={`var(--${tone})`} opacity="0.55"/>
      </pattern>
    </defs>
    <rect x="0" y="0" width="200" height="120" fill={`url(#ht-${tone})`} opacity="0.5" />
    {/* Frame + banner */}
    <rect x="10" y="10" width="180" height="100" fill="none" stroke="#2a241b" strokeWidth="1" />
    <rect x="20" y="22" width="80" height="14" fill={`var(--${tone})`} opacity="0.9" />
    <rect x="20" y="46" width="140" height="3" fill="#2a241b" opacity="0.6" />
    <rect x="20" y="54" width="120" height="3" fill="#2a241b" opacity="0.5" />
    <rect x="20" y="62" width="130" height="3" fill="#2a241b" opacity="0.5" />
    <rect x="130" y="80" width="50" height="20" fill="#2a241b" />
    <text x="155" y="93" textAnchor="middle" fontFamily="serif" fontSize="9" fill="#ecdfc7">Bs. 4,50</text>
  </svg>
);

// ——————————————————————————————————————————————————
//  Decades timeline
// ——————————————————————————————————————————————————
const DecadesSection = () => {
  const decadeMeta = {
    "1950s": { title: "Concreto y modernidad",   note: "Pérez Jiménez · Ciudad Universitaria · Teleférico" },
    "1960s": { title: "La televisión llega a todos", note: "RCTV · Canal 4 · primeros jingles" },
    "1970s": { title: "El boom petrolero",        note: "Saudita Venezuela · Concorde · prosperidad" },
    "1980s": { title: "Cultura a toda pantalla",  note: "Teresa Carreño · telenovelas · Miss Venezuela" },
    "1990s": { title: "Fin de una era",           note: "CANTV · cable · primeros celulares" },
  };
  return (
    <section id="decadas" className="decades-section">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">Cap. III · La Línea</span>
            <h2 className="section-title">Cinco décadas, una memoria.</h2>
          </div>
        </div>

        <div className="timeline">
          <div className="timeline-line" />
          {DECADES.map((d, i) => {
            const m = decadeMeta[d];
            const count = ARCHIVE.filter(a => a.era === d).length;
            return (
              <div className="tl-item" key={d} style={{ animationDelay: `${i*80}ms` }}>
                <div className="tl-dot" />
                <div className="tl-decade">{d}</div>
                <div className="tl-title">{m.title}</div>
                <div className="tl-note">{m.note}</div>
                <div className="tl-count eyebrow">{count} piezas</div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

// ——————————————————————————————————————————————————
//  About / CTA
// ——————————————————————————————————————————————————
const AboutSection = () => (
  <section id="sobre" className="about-section">
    <div className="container about-inner">
      <div className="about-left">
        <span className="eyebrow">Colofón</span>
        <h2 className="section-title">
          Si tu familia guardó una cinta,<br/>
          <em>aquí tiene lugar</em>.
        </h2>
        <p className="about-lede">
          Venezuela de Ayer es un archivo colaborativo. Recibimos VHS, Betamax, diapositivas
          y recortes de prensa. Los digitalizamos, los catalogamos y los devolvemos al
          dominio público del recuerdo.
        </p>
        <div className="about-ctas">
          <a href="https://www.instagram.com/venezueladeayer" target="_blank" rel="noreferrer" className="btn btn--primary">
            @venezueladeayer
          </a>
          <a href="mailto:archivo@venezueladeayer.com" className="btn">Donar un material</a>
        </div>
      </div>
      <div className="about-right">
        <div className="stamp">
          <div className="stamp-inner">
            <div className="stamp-ring">
              <svg viewBox="0 0 200 200" width="200" height="200">
                <defs>
                  <path id="circ" d="M 100 100 m -78, 0 a 78,78 0 1,1 156,0 a 78,78 0 1,1 -156,0" />
                </defs>
                <text fontFamily="var(--font-mono)" fontSize="11" letterSpacing="4" fill="currentColor">
                  <textPath href="#circ">
                    ARCHIVO VISUAL · VENEZUELA DE AYER · CARACAS · MMXXVI · 
                  </textPath>
                </text>
              </svg>
            </div>
            <div className="stamp-core">
              <div className="stamp-star">★</div>
              <div className="stamp-text">VDA</div>
              <div className="stamp-sub">vol. I</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ——————————————————————————————————————————————————
//  Footer
// ——————————————————————————————————————————————————
const Footer = () => (
  <footer className="footer">
    <div className="container footer-inner">
      <div className="footer-col">
        <div className="footer-mark">Venezuela de Ayer</div>
        <div className="footer-sub">Un archivo ciudadano de la memoria visual venezolana.</div>
      </div>
      <div className="footer-col">
        <div className="eyebrow">Secciones</div>
        <a href="#mapa">Mapa</a>
        <a href="#archivo">Archivo</a>
        <a href="#decadas">Décadas</a>
      </div>
      <div className="footer-col">
        <div className="eyebrow">Síguenos</div>
        <a href="https://www.instagram.com/venezueladeayer" target="_blank" rel="noreferrer">Instagram ↗</a>
        <a href="#">YouTube ↗</a>
        <a href="#">RSS ↗</a>
      </div>
      <div className="footer-col">
        <div className="eyebrow">Colofón</div>
        <div className="footer-note">
          Hecho en Caracas.<br/>
          Fraunces + JetBrains Mono.<br/>
          © MMXXVI Guayoyo LLC
        </div>
      </div>
    </div>
    <div className="container footer-bottom">
      <span className="eyebrow">001 — 167 · vol. I</span>
      <span className="eyebrow">
        Website diseñado por{" "}
        <a href="https://www.onbranded.com" target="_blank" rel="noreferrer"
           style={{ color: "var(--accent)", textDecoration: "none", borderBottom: "1px solid var(--accent)" }}>
          Onbranded
        </a>
      </span>
    </div>
  </footer>
);

// ——————————————————————————————————————————————————
//  RetroTV — a real retro television frame (wood + chrome + dials + legs)
// ——————————————————————————————————————————————————
const RetroTV = ({ children, channel = "02", title, year, showBars = false, mode = "hero" }) => {
  return (
    <div className={"rtv rtv--" + mode}>
      <div className="rtv-body">
        {/* Wood-grain cabinet is drawn in CSS on rtv-body */}
        <div className="rtv-brand">
          <span className="rtv-brand-dot" />
          <span className="rtv-brand-text">VENEZOLANA · CH {channel}</span>
        </div>

        <div className="rtv-screen-wrap">
          <div className="rtv-bezel">
            <div className="rtv-screen">
              {showBars && <div className="rtv-bars" />}
              {children}
              {showBars && (
                <div className="rtv-label">
                  <span className="rtv-ch">CH · {channel}</span>
                  {title && <span className="rtv-title">{title}</span>}
                  {year && <span className="rtv-year">{year}</span>}
                </div>
              )}
              <div className="rtv-overlay" />
              <div className="rtv-curve" />
            </div>
          </div>
        </div>

        <div className="rtv-controls">
          <div className="rtv-speaker">
            {Array.from({length: 7}).map((_,i) => <span key={i}/>)}
          </div>
          <div className="rtv-dials">
            <div className="rtv-dial"><span /></div>
            <div className="rtv-dial rtv-dial--sm"><span /></div>
            <div className="rtv-led" />
            <div className="rtv-label-chip">VHF</div>
          </div>
        </div>
      </div>
      <div className="rtv-legs">
        <span className="rtv-leg rtv-leg--l" />
        <span className="rtv-leg rtv-leg--r" />
      </div>
    </div>
  );
};

// ——————————————————————————————————————————————————
//  Video modal (CRT-style)
// ——————————————————————————————————————————————————
const VideoModal = ({ hot, onClose }) => {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div className="modal-head-left">
            <span className="eyebrow">Expediente № {hot.id.toUpperCase()}</span>
            <h3 className="modal-title">{hot.title}</h3>
            <div className="modal-meta">
              <span>{hot.kind}</span><span className="mdot">·</span>
              <span>{hot.year}</span><span className="mdot">·</span>
              <span>{hot.place}</span>
            </div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
              <path d="M6 6l12 12M18 6L6 18"/>
            </svg>
          </button>
        </div>

        <RetroTV
          channel={String(Math.abs(hot.id.charCodeAt(0)) % 13 + 2).padStart(2,"0")}
          mode="modal"
        >
          <iframe
            src={`https://www.youtube.com/embed/${hot.youtube}?autoplay=1&rel=0&modestbranding=1`}
            title={hot.title}
            frameBorder="0"
            allow="autoplay; encrypted-media; picture-in-picture"
            allowFullScreen
          />
        </RetroTV>

        <div className="modal-blurb">
          <p>{hot.blurb}</p>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  TopBar, Hero, MapSection, ArchiveSection, DecadesSection,
  AboutSection, Footer, VideoModal, RetroTV,
});
