// ─── SECTIONS A: Nav, Hero, Ticker, Diagnóstico ─────────────────────────

const { useEffect: useEffA, useState: useStA, useRef: useRefA } = React;

// ─── NAV ───────────────────────────────────────────────────────────────
function Nav() {
  const [scrolled, setScrolled] = useStA(false);
  const [active, setActive] = useStA("");
  const [drawerOpen, setDrawerOpen] = useStA(false);

  useEffA(() => {
    const ids = ["especialidades", "metodo", "resultados", "joel", "garantia", "contacto"];
    const onScroll = () => {
      setScrolled(window.scrollY > 32);
      const y = window.scrollY + window.innerHeight * 0.35;
      let found = "";
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        if (y >= el.offsetTop && y <= el.offsetTop + el.offsetHeight) { found = id; break; }
      }
      setActive(found);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffA(() => {
    document.body.style.overflow = drawerOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [drawerOpen]);

  const links = [
    { id: "especialidades", label: "Especialidades" },
    { id: "resultados", label: "Resultados" },
    { id: "testimonios", label: "Testimonios" },
    { id: "joel", label: "Quiénes somos" },
    { id: "garantia", label: "Garantía" },
  ];

  const go = (id) => {
    setDrawerOpen(false);
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 56, behavior: "smooth" });
    }, 80);
  };

  return (
    <>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button className="hamburger" aria-label="Abrir menú" onClick={() => setDrawerOpen(true)}>
            <span className="bars" aria-hidden="true"><span /><span /><span /></span>
          </button>
          <a className="nav-logo" href="#top" aria-label="Legalketing — Inicio">
            <LogoMark size={26} />
            <span>Legal<em style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontWeight: 400, color: "var(--terra)" }}>keting</em></span>
          </a>
        </div>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.id} href={`#${l.id}`} className={active === l.id ? "active" : ""}
               onClick={e => { e.preventDefault(); go(l.id); }}>{l.label}</a>
          ))}
        </div>
        <MagBtn href={WA_LINK} variant="terra" size="sm">
          <WaIcon size={14} /> Hablar ahora
        </MagBtn>
      </nav>

      {/* Mobile drawer */}
      <div className={`drawer ${drawerOpen ? "open" : ""}`} role="dialog" aria-modal="true">
        <div className="drawer-backdrop" onClick={() => setDrawerOpen(false)} />
        <div className="drawer-panel">
          <div className="drawer-head">
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <LogoMark size={24} />
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16 }}>
                Legal<em style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontWeight: 400, color: "var(--terra)" }}>keting</em>
              </span>
            </div>
            <button className="drawer-close" onClick={() => setDrawerOpen(false)} aria-label="Cerrar">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          {links.map(l => (
            <a key={l.id} className="drawer-link" href={`#${l.id}`} onClick={e => { e.preventDefault(); go(l.id); }}>
              {l.label}
              <span className="ico"><ArrowIcon size={16} /></span>
            </a>
          ))}
          <div className="drawer-foot">
            <span className="note">+50 despachos · Sin permanencia · Resultados sem. 1</span>
            <MagBtn href={WA_LINK} variant="terra" className="btn">
              <WaIcon size={16} /> Hablar ahora
            </MagBtn>
          </div>
        </div>
      </div>
    </>
  );
}

// ─── HERO ──────────────────────────────────────────────────────────────
function Hero() {
  return (
    <section className="hero section shell" id="top">
      <div className="noise" aria-hidden="true" />
      <div className="hero-main">
        {/* Left col */}
        <div>
          <div className="hero-eyebrow-row reveal">
            <span className="hero-pulse">
              <span className="blip" />
              Marketing jurídico especializado
            </span>
          </div>

          <h1 className="hero-display reveal reveal-delay-1">
            Más casos.<br />
            Mayor facturación.<br />
            <em>Garantizado.</em>
          </h1>

          <p className="hero-sub reveal reveal-delay-2">
            Generamos clientes cualificados para tu despacho. Filtrados, exclusivos y con caso real.
            Desde la primera semana, o te devolvemos los honorarios.
          </p>
          <p className="hero-sub-2 reveal reveal-delay-3">
            Especialistas en <strong>LSO, bancario, hipotecas, revolving, micropréstamos, cobro de deudas y accidentes.</strong>
          </p>

          <div className="hero-cta-row reveal reveal-delay-4">
            <MagBtn href={WA_LINK} variant="terra">
              <WaIcon size={16} /> Hablar ahora gratis
            </MagBtn>
            <span className="small-note">Sin compromiso · Respuesta en &lt;2h</span>
          </div>
        </div>

        {/* Right col — portrait + live feed */}
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {/* Live feed */}
          <div className="hero-live reveal reveal-delay-3">
            <div className="hero-live-head">
              <span className="label">Pipeline en vivo</span>
              <span className="live-blip"><span className="b" />En directo</span>
            </div>
            <div className="hero-live-feed" aria-hidden="true">
              <div className="hero-live-feed-inner">
                {[...LIVE_FEED, ...LIVE_FEED].map((item, i) => (
                  <div key={i} className="hero-live-item">
                    <span className="time">{item.time}</span>
                    <span className="what"><span className="marker" />{item.what}</span>
                    <span className="who">{item.who}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="hero-live-foot">
              <div><span className="v"><AnimatedNumber to={59} suffix="%" /></span></div>
              <span className="l">Tasa cierre media</span>
            </div>
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div className="hero-stat-row reveal">
        {[
          { v: "+50", l: "Despachos activos" },
          { v: "6M€", l: "Gestionados en ads" },
          { v: "59%", l: "Tasa cierre media" },
          { v: "Sem. 1", l: "Primeros leads" },
        ].map(s => (
          <div key={s.l} className="hero-stat">
            <span className="v">{s.v}</span>
            <span className="l">{s.l}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── REVIEWS STRIP ─────────────────────────────────────────────────────
function ReviewsStrip() {
  return (
    <div className="reviews-strip">
      <a href={WA_LINK} target="_blank" rel="noopener noreferrer">
        <span className="stars" aria-label="5 estrellas">
          {Array(5).fill(0).map((_, i) => (
            <svg key={i} width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
            </svg>
          ))}
        </span>
        <span className="rate">4.9<em>/5</em></span>
        <span className="sep" />
        <span className="who"><strong>+50 despachos</strong> confían en Legalketing</span>
        <span className="sep" />
        <span className="who"><strong>59% tasa de cierre</strong> media. El doble que el sector.</span>
        <span className="cta">Ver casos de éxito <ArrowIcon size={13} /></span>
      </a>
    </div>
  );
}

// ─── TICKER ────────────────────────────────────────────────────────────
function Ticker() {
  return (
    <div className="ticker" aria-hidden="true">
      <Marquee
        items={TICKER_ITEMS}
        gap={48}
        duration={55}
        renderItem={(item) => (
          <span className="ticker-item">
            <span className="dot" />
            {item}
          </span>
        )}
      />
    </div>
  );
}

// ─── DIAGNÓSTICO ───────────────────────────────────────────────────────
function Diagnostico() {
  const problems = [
    {
      num: "01",
      scene: "Pipeline irregular",
      body: "Meses de 1.900€ y meses de 18.500€ sin saber por qué. Dependes del boca a boca, que no escala y que no puedes controlar.",
      fix: "Generamos demanda constante, todos los meses.",
    },
    {
      num: "02",
      scene: "Leads de mala calidad",
      body: "Las consultas que llegan son de personas sin caso viable, sin capacidad de pago, o que ya han llamado a 5 despachos antes que a ti.",
      fix: "Nuestros formularios filtran antes de que te lleguen.",
    },
    {
      num: "03",
      scene: "El boca a boca no escala",
      body: "Cada año depende de que alguien te recomiende. Tu crecimiento está limitado por algo que no puedes controlar ni acelerar.",
      fix: "Captación digital: un grifo de clientes que tú controlas.",
    },
  ];

  return (
    <section className="section shell" id="diagnostico">
      <div className="section-label-row reveal">
        <span className="section-label">
          <span className="rule" />
          El diagnóstico
        </span>
      </div>
      <h2 className="section-title reveal reveal-delay-1" style={{ marginBottom: 64 }}>
        3 problemas que frenan a la mayoría de <em>despachos.</em>
      </h2>

      <div className="problem-list">
        {problems.map((p, i) => (
          <div key={i} className="problem-item reveal">
            <span className="num">{p.num}</span>
            <div>
              <div className="scene">{p.scene}</div>
            </div>
            <div className="body">
              <p style={{ marginBottom: 16 }}>{p.body}</p>
              <div className="fix-label">La solución</div>
              <p style={{ color: "var(--ink)", fontWeight: 600 }}>{p.fix}</p>
            </div>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: 32,
        padding: "18px 24px",
        background: "oklch(54% 0.14 42 / 0.06)",
        border: "1px solid var(--terra-line)",
        borderRadius: 12,
        fontFamily: "var(--font-display)",
        fontWeight: 600,
        fontSize: 15,
        color: "var(--terra)",
        textAlign: "center",
      }} className="reveal">
        +50 despachos ya han resuelto estos tres problemas con Legalketing
      </div>
    </section>
  );
}
