// ESCALA — Sections part 1: Hero, Ticker, Problema, Error, Nueva Creencia
const { useState, useEffect, useRef } = React;

/* ============================================
   HERO
   ============================================ */
function Hero() {
  return (
    <section className="section hero" id="hero">
      <div className="hero-grid container">
        <div className="hero-left fade-in">
          <span className="eyebrow">Sistema ESCALA · Tráfico · IA · Arquitectura de Ingresos</span>
          <h1 style={{ marginTop: 24 }}>
            Convierte tu negocio<br />
            en una <span className="hl">máquina<br />predecible</span> de ingresos<span className="underscore">_</span>
          </h1>
          <p className="lead" style={{ marginTop: 28 }}>
            Conectamos tráfico en Meta, Google, TikTok y YouTube con landing pages,
            automatizaciones con IA y un proceso de cierre consultivo — para que
            cada peso invertido tenga un destino, una métrica y un retorno claro.
          </p>
          <div className="hero-cta">
            <a href="#diagnostico" className="btn btn-primary">
              Agenda diagnóstico gratis
              <span className="arrow">→</span>
            </a>
            <a href="#sistema" className="btn btn-ghost">Ver el sistema</a>
          </div>
          <div className="hero-meta">
            <div className="stat">
              <span className="stat-num">+14 <span className="arrow-up">↗</span></span>
              <span className="stat-label">Negocios escalados</span>
            </div>
            <div className="stat">
              <span className="stat-num">3.2× <span className="arrow-up">↗</span></span>
              <span className="stat-label">ROAS promedio</span>
            </div>
            <div className="stat">
              <span className="stat-num">4</span>
              <span className="stat-label">Canales de tráfico</span>
            </div>
          </div>
        </div>

        <div className="hero-right fade-in" style={{ transitionDelay: "120ms" }}>
          <ArchitectureTerminal />
        </div>
      </div>
    </section>);

}

/* ---------- Architecture Terminal (right side of hero) ---------- */
function ArchitectureTerminal() {
  const [active, setActive] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setActive((a) => (a + 1) % 6), 1400);
    return () => clearInterval(id);
  }, []);

  const nodes = [
  { id: 0, x: "4%",  y: "6%",  w: 185, label: "TRÁFICO MULTI-CANAL", dotMoney: false },
  { id: 1, x: "56%", y: "6%",  w: 175, label: "LANDING · OFERTA",    dotMoney: false },
  { id: 2, x: "28%", y: "40%", w: 180, label: "IA · WHATSAPP · CRM", dotMoney: false },
  { id: 3, x: "4%",  y: "72%", w: 175, label: "SEGUIMIENTO AUTO",    dotMoney: false },
  { id: 4, x: "56%", y: "72%", w: 160, label: "VENTA · CIERRE",      dotMoney: true  },
  { id: 5, x: "28%", y: "86%", w: 165, label: "MÉTRICAS · ROAS",     dotMoney: false }];


  return (
    <div className="terminal">
      <div className="terminal-bar">
        <div className="lights"><span /><span /><span /></div>
        <span className="title">escala.system / arquitectura.flow</span>
      </div>
      <div className="terminal-body">
        <div className="arch">
          <svg viewBox="0 0 600 440" preserveAspectRatio="none">
            <defs>
              <linearGradient id="line-grad" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#2E6BFF" stopOpacity="0.1" />
                <stop offset="50%" stopColor="#5C8DFF" stopOpacity="0.7" />
                <stop offset="100%" stopColor="#2E6BFF" stopOpacity="0.1" />
              </linearGradient>
              <linearGradient id="line-money" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#2DD498" stopOpacity="0.1" />
                <stop offset="50%" stopColor="#2DD498" stopOpacity="0.8" />
                <stop offset="100%" stopColor="#2DD498" stopOpacity="0.1" />
              </linearGradient>
            </defs>
            {/* Static lines */}
            <g stroke="rgba(120,160,255,0.18)" strokeWidth="1" fill="none">
              <path d="M 200 44 C 260 44, 300 44, 356 44" />
              <path d="M 455 66 C 455 125, 375 160, 315 185" />
              <path d="M 205 210 C 175 260, 130 295, 120 325" />
              <path d="M 310 210 C 365 268, 400 295, 410 325" />
              <path d="M 410 355 C 390 375, 340 388, 300 400" />
            </g>
            {/* Animated active line */}
            <g fill="none" strokeWidth="1.6" strokeDasharray="6 4">
              <path d="M 200 44 C 260 44, 300 44, 356 44"
              stroke="url(#line-grad)"
              strokeOpacity={active >= 1 ? 1 : 0.2}>
                <animate attributeName="stroke-dashoffset" from="20" to="0" dur="1.2s" repeatCount="indefinite" />
              </path>
              <path d="M 455 66 C 455 125, 375 160, 315 185"
              stroke="url(#line-grad)"
              strokeOpacity={active >= 2 ? 1 : 0.2}>
                <animate attributeName="stroke-dashoffset" from="20" to="0" dur="1.2s" repeatCount="indefinite" />
              </path>
              <path d="M 205 210 C 175 260, 130 295, 120 325"
              stroke="url(#line-grad)"
              strokeOpacity={active >= 3 ? 1 : 0.2}>
                <animate attributeName="stroke-dashoffset" from="20" to="0" dur="1.2s" repeatCount="indefinite" />
              </path>
              <path d="M 310 210 C 365 268, 400 295, 410 325"
              stroke="url(#line-money)"
              strokeOpacity={active >= 4 ? 1 : 0.2}>
                <animate attributeName="stroke-dashoffset" from="20" to="0" dur="1.2s" repeatCount="indefinite" />
              </path>
              <path d="M 410 355 C 390 375, 340 388, 300 400"
              stroke="url(#line-money)"
              strokeOpacity={active >= 5 ? 1 : 0.2}>
                <animate attributeName="stroke-dashoffset" from="20" to="0" dur="1.2s" repeatCount="indefinite" />
              </path>
            </g>
          </svg>
          {nodes.map((n) =>
          <div
            key={n.id}
            className={`node ${active === n.id ? "active" : ""} ${n.dotMoney ? "money" : ""}`}
            style={{
              left: n.x, top: n.y, width: n.w
            }}>
            
              <span className="dot" />
              {n.label}
            </div>
          )}
        </div>
        <div style={{
          marginTop: 16, paddingTop: 16, borderTop: "1px solid var(--line)",
          display: "flex", justifyContent: "space-between",
          fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.08em"
        }}>
          <span>SYS · 6 PILLARS ACTIVE</span>
          <span style={{ color: "var(--money)" }}>● LIVE</span>
        </div>
      </div>
    </div>);

}

/* ============================================
   TICKER (logos / metrics bar)
   ============================================ */
function Ticker() {
  const items = [
  ["LEAD/COSTO", "$24.80", "▲ 18.4%"],
  ["CTR META", "3.92%", "▲ 0.7pp"],
  ["GOOGLE ADS CTR", "4.1%", "▲ 0.9pp"],
  ["CONV LEAD→VTA", "22.6%", "▲ 5.1pp"],
  ["ROAS BLENDED", "3.2×", "▲ 0.4×"],
  ["TIKTOK CPL", "$18.40", "▼ 24%"],
  ["MRR PIPELINE", "$184K", "▲ 12.6%"],
  ["FOLLOW-UP RATE", "97%", "▲ 6.0pp"]];

  const all = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {all.map((it, i) =>
        <div className="item" key={i}>
            <span>{it[0]}</span>
            <span className="val">{it[1]}</span>
            <span className="delta">{it[2]}</span>
          </div>
        )}
      </div>
    </div>);

}

/* ============================================
   PROBLEMA (síntomas)
   ============================================ */
function Problema() {
  const symptoms = [
  "Inviertes en anuncios pero no sabes cuáles venden",
  "Llegan mensajes pero la mayoría no compran",
  "WhatsApp lleno de conversaciones sin cerrar",
  "Vendes mes con mes pero nunca el mismo número",
  "Dependes de referidos y temporadas altas",
  "No tienes idea de tu CAC ni tu LTV",
  "Tu marketing y tus ventas viven en planetas distintos",
  "Pruebas tácticas sueltas que no se sostienen"];

  return (
    <section className="section" id="problema">
      <div className="container">
        <div className="section-head fade-in">
          <span className="eyebrow">01 · Diagnóstico</span>
          <h2>Tu negocio no tiene un problema de marketing.<br />
          Tiene un problema de <span style={{ color: "var(--blue-300)" }}>arquitectura</span>.</h2>
          <p className="lead">
            La mayoría de PYMEs no fallan por falta de esfuerzo — fallan porque
            cada parte del sistema (anuncios, mensajes, seguimiento, venta) opera
            por separado. El resultado: mucho movimiento, pocos ingresos predecibles.
          </p>
        </div>

        <div className="symptoms fade-in">
          {symptoms.map((s, i) =>
          <div className="symptom" key={i} style={{ "--i": i }}>
              <span className="x">✕</span>
              <span>{s}</span>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ============================================
   ERROR — el error costoso
   ============================================ */
function ErrorSection() {
  return (
    <section className="section" id="error">
      <div className="container">
        <div className="split">
          <div className="fade-in">
            <span className="eyebrow">02 · El error costoso</span>
            <h2 style={{ marginTop: 18 }}>
              Pagas por <em style={{ fontStyle: "normal", color: "var(--blue-300)" }}>tráfico</em>,<br />
              cuando deberías pagar por <em style={{ fontStyle: "normal", color: "var(--money)" }}>ventas que cierran</em>.
            </h2>
            <p className="lead" style={{ marginTop: 24 }}>
              El error no es invertir en Meta Ads. Es invertir sin un sistema detrás
              que convierta cada clic en una conversación con intención, y cada
              conversación en una venta documentada. Sin arquitectura, los anuncios
              son fuga, no inversión.
            </p>
          </div>

          <div className="fade-in">
            <ErrorDiagram />
          </div>
        </div>
      </div>
    </section>);

}

function ErrorDiagram() {
  return (
    <div className="terminal">
      <div className="terminal-bar">
        <div className="lights"><span /><span /><span /></div>
        <span className="title">presupuesto.flow / leak.audit</span>
      </div>
      <div className="terminal-body" style={{ padding: 28 }}>
        <FunnelChart />
      </div>
    </div>);

}

function FunnelChart() {
  const stages = [
  { label: "Inversión publicitaria", val: "$30,000", w: 100, leak: 0, color: "var(--blue-400)" },
  { label: "Clics al sitio", val: "1,240", w: 78, leak: 22, color: "var(--blue-300)" },
  { label: "Mensajes recibidos", val: "318", w: 52, leak: 26, color: "var(--blue-200)" },
  { label: "Conversaciones reales", val: "94", w: 28, leak: 24, color: "#9CC0FF" },
  { label: "Ventas cerradas", val: "12", w: 12, leak: 16, color: "var(--money)" }];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {stages.map((s, i) =>
      <div key={i} style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.08em" }}>
            <span>{s.label.toUpperCase()}</span>
            <span style={{ color: "var(--ink-1)" }}>{s.val}</span>
          </div>
          <div style={{ height: 14, background: "rgba(255,255,255,0.03)", borderRadius: 4, overflow: "hidden", position: "relative" }}>
            <div style={{
            width: `${s.w}%`, height: "100%",
            background: `linear-gradient(90deg, ${s.color}, ${s.color === 'var(--money)' ? '#2DD498' : 'var(--blue-500)'})`,
            opacity: 0.85,
            boxShadow: `0 0 12px ${s.color}`
          }} />
            {s.leak > 0 &&
          <div style={{
            position: "absolute", left: `${s.w}%`, top: 0, bottom: 0,
            width: `${s.leak}%`, background: "repeating-linear-gradient(45deg, rgba(255,95,109,0.18) 0 4px, transparent 4px 8px)"
          }} />
          }
          </div>
        </div>
      )}
      <div style={{
        marginTop: 8, paddingTop: 14, borderTop: "1px solid var(--line)",
        display: "flex", justifyContent: "space-between", flexWrap: "wrap", rowGap: "4px",
        fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-2)"
      }}>
        <span>FUGAS DETECTADAS</span>
        <span style={{ color: "#ff8089" }}>~88% sin retorno</span>
      </div>
    </div>);

}

/* ============================================
   NUEVA CREENCIA
   ============================================ */
function NuevaCreencia() {
  const beliefs = [
  {
    label: "ANTES",
    title: "Marketing por intuición",
    desc: "Publicar, esperar, rezar. Decisiones basadas en lo que “sí jaló la semana pasada”.",
    kind: "old"
  },
  {
    label: "AHORA",
    title: "Arquitectura por sistema",
    desc: "Cada decisión apoyada en datos: CAC, conversación cerrada, retorno por canal.",
    kind: "new"
  }];

  return (
    <section className="section" id="creencia">
      <div className="container">
        <div className="section-head center fade-in">
          <span className="eyebrow">03 · Nueva creencia</span>
          <h2 style={{ textAlign: "center" }}>Vender más no es trabajar más.<br />Es <span style={{ color: "var(--blue-300)" }}>arquitecturar</span> mejor.</h2>
          <p className="lead" style={{ textAlign: "center", margin: "0 auto" }}>
            Las PYMEs que escalan dejan de pensar en “tácticas” y empiezan a pensar
            en <strong style={{ color: "var(--ink-1)" }}>infraestructura comercial</strong> — un sistema
            que produce ingresos con o sin tu intervención diaria.
          </p>
        </div>

        <div className="cards cols-2 fade-in">
          {beliefs.map((b, i) =>
          <div className="card" key={i} style={{ padding: "40px 32px" }}>
              <div style={{
              fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.16em",
              color: b.kind === "old" ? "#ff8089" : "var(--blue-200)",
              textTransform: "uppercase"
            }}>{b.label}</div>
              <h3 style={{ fontSize: 28, marginTop: 4 }}>{b.title}</h3>
              <p style={{ fontSize: 15 }}>{b.desc}</p>
              <div style={{
              marginTop: 24, height: 60,
              opacity: 0.9
            }}>
                {b.kind === "old" ?
              <ChaosLine /> :
              <UpLine />}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

function ChaosLine() {
  return (
    <svg viewBox="0 0 400 60" style={{ width: "100%", height: "100%" }}>
      <path d="M0 30 L 30 12 L 60 44 L 90 18 L 120 50 L 150 22 L 180 38 L 210 14 L 240 46 L 270 24 L 300 40 L 330 18 L 360 36 L 400 28"
      fill="none" stroke="#ff8089" strokeWidth="1.5" strokeOpacity="0.7" />
    </svg>);

}
function UpLine() {
  return (
    <svg viewBox="0 0 400 60" style={{ width: "100%", height: "100%" }}>
      <defs>
        <linearGradient id="up-grad" x1="0" y1="1" x2="1" y2="0">
          <stop offset="0%" stopColor="#2E6BFF" stopOpacity="0.4" />
          <stop offset="100%" stopColor="#2DD498" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d="M0 50 L 50 46 L 100 42 L 150 36 L 200 30 L 250 24 L 300 16 L 350 10 L 400 4 L 400 60 L 0 60 Z"
      fill="url(#up-grad)" />
      <path d="M0 50 L 50 46 L 100 42 L 150 36 L 200 30 L 250 24 L 300 16 L 350 10 L 400 4"
      fill="none" stroke="#2DD498" strokeWidth="1.8" />
      <circle cx="400" cy="4" r="3" fill="#2DD498" />
    </svg>);

}

window.Hero = Hero;
window.Ticker = Ticker;
window.Problema = Problema;
window.ErrorSection = ErrorSection;
window.NuevaCreencia = NuevaCreencia;