// All page sections. Exported to window.
const { useState: useStateS } = React;

const LOGO = window.LOGO_SRC;
window.LOGO = LOGO;

/* ============ HEADER ============ */
function Header() {
  const [open, setOpen] = useStateS(false);
  const links = [
    { href: '#como-funciona', label: 'Cómo funciona' },
    { href: '#muestras', label: 'Muestras' },
    { href: '#ventajas', label: 'Ventajas' },
    { href: '#precios', label: 'Precios' },
    { href: '#faq', label: 'FAQ' },
  ];
  return (
    <header className="sticky top-0 z-50 backdrop-blur-md bg-fondo-principal/80 border-b border-marca-invisible/10">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 h-16 sm:h-[72px] flex items-center justify-between">
        <a href="#" className="flex items-center">
          <img src={LOGO} alt="Banda Invisible — producción musical para autores" className="h-6 sm:h-7 w-auto" />
        </a>
        <nav className="hidden md:flex items-center gap-8">
          {links.map(l => (
            <a key={l.href} href={l.href} className="text-[13px] font-medium text-texto-oscuro/75 hover:text-marca-invisible-dark transition-colors">
              {l.label}
            </a>
          ))}
        </nav>
        <div className="flex items-center gap-3">
          <a href="#contacto" className="hidden sm:inline-flex items-center gap-1.5 bg-marca-banda hover:bg-marca-banda-dark text-white text-[13px] font-semibold px-4 py-2.5 rounded-full transition-colors">
            Empezar
            <IconArrowRight size={14} />
          </a>
          <button onClick={() => setOpen(o => !o)} className="md:hidden w-9 h-9 flex flex-col items-center justify-center gap-1" aria-label="Menú">
            <span className={`block w-5 h-px bg-texto-oscuro transition-transform ${open ? 'translate-y-[3px] rotate-45' : ''}`}></span>
            <span className={`block w-5 h-px bg-texto-oscuro transition-transform ${open ? '-translate-y-[3px] -rotate-45' : ''}`}></span>
          </button>
        </div>
      </div>
      {open && (
        <div className="md:hidden border-t border-marca-invisible/10 px-5 py-4 space-y-3 bg-fondo-principal">
          {links.map(l => (
            <a key={l.href} href={l.href} onClick={() => setOpen(false)} className="block text-sm font-medium text-texto-oscuro/80">
              {l.label}
            </a>
          ))}
        </div>
      )}
    </header>
  );
}

/* ============ HERO ============ */
function Hero() {
  return (
    <section className="relative overflow-hidden pt-12 sm:pt-20 pb-16 sm:pb-24">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 relative">
        <div className="grid lg:grid-cols-12 gap-12 lg:gap-16 items-center">
          {/* LEFT — copy */}
          <div className="lg:col-span-7">
            <div className="inline-flex items-center gap-2 bg-marca-invisible/15 text-marca-invisible-dark px-3.5 py-1.5 rounded-full text-[11px] sm:text-xs font-semibold tracking-wide">
              <span className="w-1.5 h-1.5 bg-marca-invisible rounded-full pulse-dot"></span>
              100% Derechos Comerciales — La obra es tuya
            </div>
            <h1 className="mt-6 sm:mt-8 text-3xl sm:text-4xl lg:text-5xl leading-[1.05] text-marca-invisible-dark uppercase" style={{textWrap: 'balance'}}>
              Convierte tus letras en <span className="text-marca-banda">canciones profesionales.</span>
            </h1>
            <p className="mt-5 sm:mt-6 text-base sm:text-lg text-texto-oscuro/75 max-w-xl leading-relaxed">
              Transformamos textos, poemas y composiciones en canciones con calidad de estudio. La herramienta definitiva para autores que buscan musicalizar su obra de forma ágil y accesible.
            </p>
            <div className="mt-8 flex flex-col sm:flex-row sm:items-center gap-4">
              <a href="#contacto" className="inline-flex items-center justify-center gap-2 bg-marca-banda hover:bg-marca-banda-dark text-white text-base font-semibold px-7 py-4 rounded-full shadow-lift transition-colors">
                Empezar mi producción
                <IconArrowRight size={18} />
              </a>
              <span className="text-sm text-texto-oscuro/60 max-w-xs">
                Producción ágil en <strong className="text-marca-invisible-dark">tiempo récord</strong>. Sin estudios ni músicos de sesión.
              </span>
            </div>

            {/* Trust strip */}
            <div className="mt-12 sm:mt-16 grid grid-cols-2 sm:grid-cols-3 gap-y-6 gap-x-6 pt-8 border-t border-marca-invisible/15">
              {[
                ['100%', 'Derechos cedidos'],
                ['Récord', 'Tiempos de entrega'],
                ['Máster', 'Calidad de estudio'],
              ].map(([n, l]) => (
                <div key={l}>
                  <div className="text-xl sm:text-2xl font-display text-marca-invisible-dark">{n}</div>
                  <div className="text-[10px] sm:text-[11px] uppercase tracking-[0.14em] text-texto-oscuro/55 mt-1">{l}</div>
                </div>
              ))}
            </div>
          </div>

          {/* RIGHT — visual */}
          <div className="lg:col-span-5 relative flex items-center justify-center lg:justify-end">
            <HeroVisual />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ HERO VISUAL ============ */
function HeroVisual() {
  return (
    <div className="relative w-full max-w-[420px] aspect-square">
      {/* Back tile — blue */}
      <div
        className="absolute left-0 top-6 w-[68%] aspect-square rounded-2xl shadow-card overflow-hidden"
        style={{ background: 'linear-gradient(140deg, #2C4B60 0%, #4F81A1 100%)', transform: 'rotate(-6deg)' }}
      >
        <div className="cover-stripes absolute inset-0 opacity-35"></div>
        <div className="absolute inset-0 flex items-center justify-center">
          <CoverGlyph variant="a" />
        </div>
        <div className="absolute top-3 left-3 text-[9px] font-mono uppercase tracking-[0.16em] text-white/80">
          A1 · Indie
        </div>
      </div>

      {/* Vinyl behind front tile */}
      <div
        aria-hidden
        className="absolute right-[6%] top-[4%] w-[58%] aspect-square rounded-full spin-slow"
        style={{
          background: 'radial-gradient(circle at center, #2D3134 0 18%, #1a1d20 18.5% 100%)',
          boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.04), 0 12px 32px rgba(44,75,96,0.25)',
        }}
      >
        {/* grooves */}
        <div className="absolute inset-[6%] rounded-full border border-white/5"></div>
        <div className="absolute inset-[14%] rounded-full border border-white/5"></div>
        <div className="absolute inset-[22%] rounded-full border border-white/5"></div>
        <div className="absolute inset-[30%] rounded-full border border-white/5"></div>
        {/* label */}
        <div className="absolute inset-[36%] rounded-full bg-marca-banda flex items-center justify-center">
          <div className="w-2 h-2 rounded-full bg-fondo-principal"></div>
        </div>
      </div>

      {/* Front tile — red */}
      <div
        className="absolute right-0 bottom-0 w-[62%] aspect-square rounded-2xl shadow-lift overflow-hidden"
        style={{ background: 'linear-gradient(140deg, #C53338 0%, #E23E44 100%)', transform: 'rotate(4deg)' }}
      >
        <div className="cover-stripes absolute inset-0 opacity-30"></div>
        <div className="absolute inset-0 flex items-center justify-center">
          <CoverGlyph variant="b" />
        </div>
        <div className="absolute top-3 left-3 text-[9px] font-mono uppercase tracking-[0.16em] text-white/85">
          B2 · Balada
        </div>
        {/* tiny play badge */}
        <div className="absolute bottom-3 right-3 w-9 h-9 rounded-full bg-white text-marca-banda flex items-center justify-center shadow-md">
          <IconPlay size={12} className="ml-0.5" />
        </div>
      </div>

      {/* Floating waveform chip */}
      <div className="absolute -left-2 bottom-8 bg-white shadow-lift rounded-full pl-2 pr-3 py-1.5 flex items-center gap-2 border border-marca-invisible/10">
        <span className="w-7 h-7 rounded-full bg-marca-banda text-white flex items-center justify-center">
          <WaveformAnim size={11} color="white" />
        </span>
        <span className="text-[10px] font-mono uppercase tracking-[0.16em] text-marca-invisible-dark">
          Sonando
        </span>
      </div>
    </div>
  );
}

/* ============ HOW IT WORKS ============ */
function HowItWorks() {
  const steps = [
    {
      n: '01',
      icon: <IconText />,
      title: 'Envía tu texto',
      desc: 'Pega tu letra, poema o guion. Puedes detallar la estructura (versos, puente, estribillo) o dejarnos total libertad creativa para la adaptación.',
    },
    {
      n: '02',
      icon: <IconSliders />,
      title: 'Define la identidad sonora',
      desc: 'Elige el género musical, la instrumentación y el perfil vocal. Desde un piano íntimo hasta una producción de rock o música urbana.',
    },
    {
      n: '03',
      icon: <IconDownload />,
      title: 'Recibe tu canción final',
      desc: 'Entregamos el archivo de audio en alta fidelidad, ecualizado y masterizado. Listo para usar como maqueta o para distribuir en plataformas digitales.',
    },
  ];
  return (
    <section id="como-funciona" className="py-20 sm:py-28">
      <div className="max-w-7xl mx-auto px-5 sm:px-8">
        <div className="max-w-3xl">
          <div className="text-[11px] uppercase tracking-[0.18em] text-marca-banda font-semibold">Metodología</div>
          <h2 className="mt-3 text-3xl sm:text-5xl text-marca-invisible-dark font-bold leading-tight" style={{textWrap: 'balance'}}>
            Del papel al máster final en tres pasos.
          </h2>
        </div>
        <div className="mt-12 sm:mt-16 grid md:grid-cols-3 gap-5 sm:gap-6">
          {steps.map((s, i) => (
            <div key={s.n} className="relative bg-fondo-tarjeta rounded-2xl p-7 sm:p-8 group hover:shadow-soft transition-shadow">
              <div className="flex items-start justify-between">
                <div className="w-12 h-12 rounded-xl bg-white text-marca-invisible-dark flex items-center justify-center shadow-sm">
                  {s.icon}
                </div>
                <span className="font-mono text-[11px] tracking-wider text-marca-invisible/70">{s.n} / 03</span>
              </div>
              <h3 className="mt-7 text-xl sm:text-2xl font-bold text-marca-invisible-dark leading-snug">{s.title}</h3>
              <p className="mt-3 text-[15px] leading-relaxed text-texto-oscuro/75">{s.desc}</p>
              {i < 2 && (
                <div aria-hidden className="hidden md:block absolute -right-3 top-1/2 -translate-y-1/2 text-marca-invisible/30">
                  <IconArrowRight size={22} />
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ SAMPLE TRACKS ============ */
const SAMPLE_TRACKS = [
  { id: 't1', title: 'Causas Perdidas', genre: 'Poesía Indie Rock', author: 'Santiago Navarra', note: 'Escritor polifacético que vive para el arte.', src: window.AUDIO_SRC.t1, coverBg: 'linear-gradient(135deg, #2C4B60 0%, #4F81A1 100%)', coverVariant: 'a' },
  { id: 't2', title: 'Anhelos', genre: 'Balada Acústica', author: 'Claudia Contreras', note: 'Un don y una sensibilidad para la escritura que siempre estuvieron ahí.', src: window.AUDIO_SRC.t2, coverBg: 'linear-gradient(135deg, #C53338 0%, #E23E44 100%)', coverVariant: 'b' },
  { id: 't3', title: 'Codo a Codo', genre: 'Urbano Poético', author: 'Lucía Parissi', note: 'Eligió el urbano para llevar su mensaje a los jóvenes.', src: window.AUDIO_SRC.t3, coverBg: 'linear-gradient(135deg, #2D3134 0%, #4F81A1 100%)', coverVariant: 'c' },
];

function ProductDemo({ playerState, setPlayerState }) {
  const playTrack = (track) => {
    const isSame = playerState.track?.id === track.id;
    setPlayerState({
      track,
      isPlaying: isSame ? !playerState.isPlaying : true,
      expanded: true,
    });
  };

  return (
    <section id="muestras" className="py-20 sm:py-28 bg-gradient-to-b from-fondo-principal to-fondo-tarjeta/40">
      <div className="max-w-7xl mx-auto px-5 sm:px-8">
        <div className="max-w-3xl">
          <div className="text-[11px] uppercase tracking-[0.18em] text-marca-banda font-semibold">Prueba de producto</div>
          <h2 className="mt-3 text-3xl sm:text-5xl text-marca-invisible-dark font-bold leading-tight" style={{textWrap: 'balance'}}>
            Calidad de industria, lista para publicar.
          </h2>
          <p className="mt-5 text-lg text-texto-oscuro/75 max-w-2xl">
            Tres autores, tres universos distintos. Escucha cómo adaptamos cada estilo narrativo al género que le corresponde.
          </p>
        </div>

        <div className="mt-12 grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {SAMPLE_TRACKS.map((t) => {
            const isCurrent = playerState.track?.id === t.id;
            const isThisPlaying = isCurrent && playerState.isPlaying;
            return (
              <div key={t.id} className="group">
                <div className="relative aspect-square rounded-2xl overflow-hidden shadow-soft" style={{ background: t.coverBg }}>
                  <div className="cover-stripes absolute inset-0 opacity-30"></div>
                  {/* Centerpiece glyph */}
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className={isThisPlaying ? 'spin-slow' : ''}>
                      <CoverGlyph variant={t.coverVariant} />
                    </div>
                  </div>
                  {/* Genre tag */}
                  <div className="absolute top-4 left-4 text-[10px] font-mono uppercase tracking-[0.16em] text-white/85 bg-black/25 backdrop-blur-sm px-2 py-1 rounded">
                    {t.genre}
                  </div>
                  {/* Play button floating */}
                  <button
                    onClick={() => playTrack(t)}
                    className="absolute bottom-4 right-4 w-14 h-14 rounded-full bg-white text-marca-invisible-dark hover:bg-marca-banda hover:text-white flex items-center justify-center shadow-lift transition-all group-hover:scale-105"
                    aria-label={isThisPlaying ? 'Pausar' : 'Reproducir'}
                  >
                    {isThisPlaying ? <IconPause size={18} /> : <IconPlay size={18} className="ml-0.5" />}
                  </button>
                  {/* Now playing overlay */}
                  {isThisPlaying && (
                    <div className="absolute bottom-5 left-4 text-white flex items-center gap-2">
                      <WaveformAnim size={12} color="white" />
                      <span className="text-[11px] font-mono tracking-wider uppercase">Sonando</span>
                    </div>
                  )}
                </div>
                <div className="mt-4 px-1">
                  <div className="font-display text-lg font-semibold text-marca-invisible-dark leading-snug">{t.title}</div>
                  <div className="text-xs text-marca-invisible mt-1 font-mono uppercase tracking-[0.14em]">Letra de {t.author}</div>
                  <p className="text-[13px] text-texto-oscuro/65 mt-2 leading-snug">{t.note}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============ ADVANTAGES ============ */
function Advantages() {
  const items = [
    { icon: <IconCoin />, title: 'Reducción drástica de costes', desc: 'Obtén un sonido de banda completa sin la necesidad de alquilar estudios de grabación, ingenieros de sonido o contratar músicos de sesión.' },
    { icon: <IconShield />, title: 'Propiedad Intelectual Total', desc: 'Con el plan comercial, mantienes el 100% de los derechos de explotación. Puedes subir la canción a Spotify, Apple Music o venderla a terceros.' },
    { icon: <IconBolt />, title: 'Velocidad de vértigo', desc: 'Optimiza tu flujo de trabajo. Pasa de la hoja en blanco al audio completamente finalizado en tiempo récord, evitando semanas de espera.' },
    { icon: <IconLayers />, title: 'Versatilidad creativa', desc: 'Apoyados en producción digital avanzada, exploramos cualquier frontera musical para encontrar el tono exacto que requiere tu narrativa.' },
  ];
  return (
    <section id="ventajas" className="relative py-20 sm:py-28 overflow-hidden bg-marca-invisible-dark">
      {/* Surco de vinilo muy tenue como textura de fondo */}
      <div aria-hidden className="hidden lg:block absolute" style={{ left: '-10rem', bottom: '-14rem', width: '560px', height: '560px', borderRadius: '9999px', border: '52px solid rgba(255,255,255,0.04)' }}></div>
      <div className="max-w-7xl mx-auto px-5 sm:px-8 relative">
        <div className="grid lg:grid-cols-12 gap-10 lg:gap-16">
          <div className="lg:col-span-5">
            <div className="inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-white/55 font-semibold">
              <span className="w-1.5 h-1.5 bg-marca-banda rounded-full"></span>
              Ventajas competitivas
            </div>
            <h2 className="mt-4 text-3xl sm:text-5xl text-white font-bold leading-tight" style={{textWrap: 'balance'}}>
              Una banda invisible al servicio de tu obra.
            </h2>
            <p className="mt-6 text-lg text-white/65 leading-relaxed">
              Producción digital avanzada que sustituye al estudio tradicional sin renunciar a la calidad. Tú escribes; nosotros encontramos el sonido.
            </p>
          </div>
          <div className="lg:col-span-7 grid sm:grid-cols-2 gap-px rounded-2xl overflow-hidden" style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.12)' }}>
            {items.map((it) => (
              <div key={it.title} className="p-7 sm:p-8" style={{ background: '#2C4B60' }}>
                <div className="w-11 h-11 rounded-lg text-white flex items-center justify-center" style={{ background: 'rgba(255,255,255,0.10)' }}>
                  {it.icon}
                </div>
                <h3 className="mt-5 text-lg font-bold text-white leading-snug">{it.title}</h3>
                <p className="mt-2 text-sm leading-relaxed text-white/65">{it.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, HeroVisual, HowItWorks, ProductDemo, Advantages, SAMPLE_TRACKS });
