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

// ============== Modal de contacto ==============
const WA_NUMBER = '5491141733139';

function ContactModal({ onClose }) {
  const [form, setForm] = useState({ nombre: '', empresa: '', rol: '', wa: '' });
  const [sent, setSent] = useState(false);
  const overlayRef = useRef(null);

  useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }

  function submit(e) {
    e.preventDefault();
    const msg = encodeURIComponent(
      `Hola! Me interesa el curso de IA Aplicada a Servicios.\n\n` +
      `Nombre: ${form.nombre}\n` +
      `Empresa: ${form.empresa}\n` +
      `Rol: ${form.rol}\n` +
      `Mi WhatsApp: ${form.wa}`
    );
    window.open(`https://wa.me/${WA_NUMBER}?text=${msg}`, '_blank');
    setSent(true);
  }

  return (
    <div
      ref={overlayRef}
      className="modal-overlay"
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div className="modal-box">
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">✕</button>
        {sent ? (
          <div className="modal-thanks">
            <div className="modal-thanks-icon">✓</div>
            <h3>¡Perfecto!</h3>
            <p>Se abrió WhatsApp con tu información. Si no se abrió, <a href={`https://wa.me/${WA_NUMBER}`} target="_blank" rel="noreferrer">hacé click acá</a>.</p>
            <button className="btn btn-primary" onClick={onClose}>Cerrar</button>
          </div>
        ) : (
          <>
            <span className="modal-eyebrow">Reservar lugar · 2026</span>
            <h3>Contanos un poco sobre vos</h3>
            <p className="modal-sub">Te contactamos por WhatsApp para coordinar los detalles.</p>
            <form onSubmit={submit} className="modal-form">
              <div className="mfield">
                <label>Nombre completo</label>
                <input required value={form.nombre} onChange={e => set('nombre', e.target.value)} placeholder="Ana García" />
              </div>
              <div className="mfield">
                <label>Empresa</label>
                <input required value={form.empresa} onChange={e => set('empresa', e.target.value)} placeholder="Acme S.A." />
              </div>
              <div className="mfield">
                <label>Rol / Puesto</label>
                <input required value={form.rol} onChange={e => set('rol', e.target.value)} placeholder="Head of Ops, CTO, PM…" />
              </div>
              <div className="mfield">
                <label>Tu WhatsApp</label>
                <input required type="tel" value={form.wa} onChange={e => set('wa', e.target.value)} placeholder="+54 9 11 xxxx-xxxx" />
              </div>
              <button type="submit" className="btn btn-primary modal-submit">
                Enviar por WhatsApp →
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

// ============== Helpers ==============
function useLang() {
  const [lang, setLang] = useState(() => window.__lang || 'es');
  useEffect(() => {
    window.__lang = lang;
    window.dispatchEvent(new CustomEvent('langchange', { detail: lang }));
  }, [lang]);
  useEffect(() => {
    const h = (e) => setLang(e.detail);
    window.addEventListener('langchange', h);
    return () => window.removeEventListener('langchange', h);
  }, []);
  return [lang, setLang];
}

function useScrollReveal() {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const o = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setShown(true); o.disconnect(); } },
      { threshold: 0.15, rootMargin: '0px 0px -10% 0px' }
    );
    o.observe(ref.current);
    return () => o.disconnect();
  }, []);
  return [ref, shown];
}

function Reveal({ children, delay = 0 }) {
  const [ref, shown] = useScrollReveal();
  return (
    <div ref={ref} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? 'translateY(0)' : 'translateY(18px)',
      transition: `opacity .8s cubic-bezier(.2,.8,.2,1) ${delay}ms, transform .9s cubic-bezier(.2,.8,.2,1) ${delay}ms`,
    }}>{children}</div>
  );
}

// ============== Nav ==============
const NAV_ANCHORS = ['#curso', '#stack', '#roadmap', '#modalidad', '#empresa'];

function Nav({ lang, setLang, copy, onCTA }) {
  function scrollTo(e, anchor) {
    e.preventDefault();
    if (anchor === '#empresa') { onCTA(); return; }
    const el = document.querySelector(anchor);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  return (
    <nav className="nav">
      <div className="nav-brand">
        <span className="mark"></span>
        <span>aplicada<span style={{ color: 'var(--ink-3)' }}>.ai</span></span>
      </div>
      <div className="nav-links">
        {copy.nav.links.map((l, i) => (
          <a key={i} href={NAV_ANCHORS[i]} onClick={(e) => scrollTo(e, NAV_ANCHORS[i])}>{l}</a>
        ))}
      </div>
      <div className="nav-right">
        <div className="lang-toggle">
          <button className={lang === 'es' ? 'on' : ''} onClick={() => setLang('es')}>ES</button>
          <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
        <button className="btn btn-primary" onClick={onCTA}>{copy.nav.cta} →</button>
      </div>
    </nav>
  );
}

// ============== Hero ==============
function Hero({ copy, onCTA }) {
  return (
    <section className="hero container">
      <div className="hero-grid">
        <div>
          <Reveal>
            <span className="eyebrow"><span className="dot"></span>{copy.hero.eyebrow}</span>
          </Reveal>
          <Reveal delay={80}>
            <h1>{copy.hero.title_1}<span className="accent">{copy.hero.title_accent}</span>{copy.hero.title_2}</h1>
          </Reveal>
          <Reveal delay={160}>
            <p className="hero-lede">{copy.hero.lede}</p>
          </Reveal>
          <Reveal delay={240}>
            <div className="hero-cta">
              <button className="btn btn-primary" onClick={onCTA}>{copy.hero.cta_primary} →</button>
              <button className="btn btn-ghost" onClick={onCTA}>{copy.hero.cta_secondary}</button>
            </div>
          </Reveal>
          <Reveal delay={320}>
            <div className="hero-meta">
              <span><span className="pulse"></span>{copy.hero.meta[0]}</span>
              <span>· {copy.hero.meta[1]}</span>
              <span>· {copy.hero.meta[2]}</span>
            </div>
          </Reveal>
        </div>
        <Reveal delay={200}>
          <ChatDemo copy={copy.chat} />
        </Reveal>
      </div>
    </section>
  );
}

// ============== Chat demo ==============
function ChatDemo({ copy }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const bodyRef = useRef(null);

  useEffect(() => {
    setMessages([]);
    let i = 0;
    let cancelled = false;
    const timers = [];
    const seed = (copy && copy.seed) || [];
    const tick = () => {
      if (cancelled || i >= seed.length) return;
      const item = seed[i];
      if (item && item.role) {
        setMessages((m) => [...m, item]);
      }
      i++;
      timers.push(setTimeout(tick, 900));
    };
    timers.push(setTimeout(tick, 400));
    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, [copy]);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages]);

  async function send(text) {
    if (!text.trim() || busy) return;
    setBusy(true);
    setMessages((m) => [...m, { role: 'user', text }]);
    setInput('');
    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: text }),
      });
      const data = await res.json();
      setMessages((m) => [...m, { role: 'bot', text: data.text || '...' }]);
    } catch (e) {
      setMessages((m) => [...m, { role: 'bot', text: 'Hubo un error. Intentá de nuevo.' }]);
    }
    setBusy(false);
  }

  return (
    <div className="chat-demo">
      <div className="chat-head">
        <div className="lights">
          <span className="light on"></span>
          <span className="light"></span>
          <span className="light"></span>
        </div>
        <span className="title">{copy.title}</span>
        <span style={{ width: 30 }}></span>
      </div>
      <div className="chat-body" ref={bodyRef}>
        {messages.filter(m => m && m.role).map((m, i) => (
          <div key={i} className={`bubble ${m.role}`}>
            {m.text}
            {m.tool && (
              <div className="tool-call">
                <span className="icon">⏵</span>
                <span>{m.tool}</span>
              </div>
            )}
          </div>
        ))}
        {busy && (
          <div className="bubble bot"><span className="typing"><span></span><span></span><span></span></span></div>
        )}
      </div>
      <div className="chat-input">
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && send(input)}
          placeholder={copy.placeholder}
        />
        <button className="send" onClick={() => send(input)}>↑</button>
      </div>
      <div className="chat-suggest">
        {copy.suggestions.map((s, i) => (
          <button key={i} onClick={() => send(s)}>{s}</button>
        ))}
      </div>
    </div>
  );
}

// ============== Signal row ==============
function SignalRow({ items }) {
  return (
    <div className="container">
      <div className="signal-row">
        {items.map((s, i) => <span key={i}>· {s}</span>)}
      </div>
    </div>
  );
}

// ============== Antes vs Después ==============
function Compare({ copy }) {
  const [split, setSplit] = useState(0.7407407407407408);
  const ref = useRef(null);
  const dragging = useRef(false);

  function onDown(e) { dragging.current = true; e.preventDefault(); }

  useEffect(() => {
    function move(e) {
      if (!dragging.current || !ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const x = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
      setSplit(Math.max(0, Math.min(100, (x / r.width) * 100)));
    }
    function up() { dragging.current = false; }
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move);
    window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', up);
    };
  }, []);

  return (
    <section className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <Reveal delay={180}>
        <div className="compare" ref={ref} style={{ '--split': `${split}%` }}>
          <div className="compare-side before">
            <div>
              <span className="compare-tag"><span className="num">→</span>{copy.before.tag}</span>
              <h3>{copy.before.title}</h3>
            </div>
            <ul className="compare-list">
              {copy.before.items.map((it, i) => <li key={i}><span className="marker">0{i + 1}</span>{it}</li>)}
            </ul>
          </div>
          <div className="compare-side after">
            <div>
              <span className="compare-tag"><span className="num">→</span>{copy.after.tag}</span>
              <h3>{copy.after.title}</h3>
            </div>
            <ul className="compare-list">
              {copy.after.items.map((it, i) => <li key={i}><span className="marker">0{i + 1}</span>{it}</li>)}
            </ul>
          </div>
          <div className="compare-handle" onMouseDown={onDown} onTouchStart={onDown}></div>
        </div>
      </Reveal>
    </section>
  );
}

// ============== Stack ==============
function Stack({ copy }) {
  const [active, setActive] = useState('mcp');
  const detail = copy.details[active];

  function highlight(line) {
    return line
      .replace(/("[^"]*")/g, '<span class="str">$1</span>')
      .replace(/\b(rule|skill|on|when|then|owner|inputs|steps|audit)\b/g, '<span class="key">$1</span>')
      .replace(/(\/\/.*)/g, '<span class="com">$1</span>');
  }

  return (
    <section id="stack" className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <Reveal delay={180}>
        <div className="stack">
          {copy.caps.map((c) => (
            <div
              key={c.id}
              className={`cap ${active === c.id ? 'active' : ''}`}
              onMouseEnter={() => setActive(c.id)}
              onClick={() => setActive(c.id)}
            >
              <div className="glyph">{c.glyph}</div>
              <div>
                <div className="name">{c.name}</div>
                <div className="blurb">{c.blurb}</div>
              </div>
            </div>
          ))}
        </div>
      </Reveal>
      <Reveal delay={240}>
        <div className="stack-detail" key={active}>
          <div>
            <span className="label">{detail.label}</span>
            <h3>{detail.title}</h3>
            <p>{detail.body}</p>
          </div>
          <div className="example" dangerouslySetInnerHTML={{ __html: highlight(detail.example) }}></div>
        </div>
      </Reveal>
    </section>
  );
}

// ============== Roadmap ==============
function Roadmap({ copy }) {
  const [active, setActive] = useState(0);
  const lvl = copy.levels[active];
  return (
    <section id="roadmap" className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <Reveal delay={180}>
        <div className="roadmap">
          <div className="road-levels">
            {copy.levels.map((l, i) => (
              <div
                key={i}
                className={`road-level ${active === i ? 'active' : ''}`}
                onClick={() => setActive(i)}
                onMouseEnter={() => setActive(i)}
              >
                <span className="dot"></span>
                <span className="num">{l.num}</span>
                <span>{l.name}</span>
              </div>
            ))}
          </div>
          <div className="road-panel" key={active}>
            <span className="stage-tag">{lvl.tag}</span>
            <h3>{lvl.h}</h3>
            <p>{lvl.p}</p>
            <ul className="road-bullets">
              {lvl.bullets.map((b, i) => <li key={i}><span className="check">✓</span>{b}</li>)}
            </ul>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

// ============== Audience ==============
function Audience({ copy }) {
  return (
    <section id="curso" className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <div className="audience">
        {copy.personas.map((p, i) => (
          <Reveal key={i} delay={i * 100}>
            <div className="persona">
              <div className="role">{p.role}</div>
              <h3>{p.h}</h3>
              <p>{p.p}</p>
              <div className="tags">
                {p.tags.map((t, j) => <span key={j} className="tag">{t}</span>)}
              </div>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ============== Modes ==============
function Modes({ copy, onCTA }) {
  return (
    <section id="modalidad" className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <div className="modes">
        {copy.items.map((m, i) => (
          <Reveal key={i} delay={i * 80}>
            <div className={`mode ${m.featured ? 'featured' : ''}`}>
              {m.ribbon && <span className="ribbon">{m.ribbon}</span>}
              <span className="mode-name">{m.name}</span>
              <h3>{m.h}</h3>
              <div className="price">
                <span className="amount ph" style={{ color: 'var(--ink-4)' }}>{m.price}</span>
                <span className="unit">{m.unit}</span>
              </div>
              <p className="desc">{m.desc}</p>
              <ul>{m.features.map((f, j) => <li key={j}>{f}</li>)}</ul>
              <button className={`btn ${m.featured ? 'btn-primary' : 'btn-ghost'}`} onClick={onCTA}>{m.cta} →</button>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ============== ROI ==============
function ROI({ copy }) {
  const [vals, setVals] = useState(() => Object.fromEntries(copy.controls.map(c => [c.id, c.default])));
  useEffect(() => {
    setVals(Object.fromEntries(copy.controls.map(c => [c.id, c.default])));
  }, [copy]);

  const { tickets = 3000, minutes = 12, cost = 22, auto = 45 } = vals;
  const monthlyHours = (tickets * minutes) / 60;
  const fullCost = monthlyHours * cost;
  const savings = Math.round(fullCost * (auto / 100));

  function fmt(v, type) {
    if (type === '$') return '$' + v;
    if (type === '%') return v + '%';
    if (type === 'min') return v + ' min';
    return v.toLocaleString();
  }

  return (
    <section className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
        <Reveal delay={120}><p className="lede">{copy.lede}</p></Reveal>
      </div>
      <Reveal delay={180}>
        <div className="roi">
          <div className="roi-controls">
            {copy.controls.map((c) => (
              <div key={c.id} className="roi-control">
                <div className="label-row">
                  <span className="label">{c.label}</span>
                  <span className="value">{fmt(vals[c.id], c.fmt)}</span>
                </div>
                <input
                  type="range"
                  min={c.min} max={c.max} step={c.step}
                  value={vals[c.id]}
                  onChange={(e) => setVals(v => ({ ...v, [c.id]: Number(e.target.value) }))}
                />
              </div>
            ))}
          </div>
          <div className="roi-result">
            <span className="result-label">{copy.result_label}</span>
            <div className="result-num">${savings.toLocaleString()}</div>
            <span className="result-sub">{copy.result_sub}</span>
            <div className="breakdown">
              <div><span style={{ color: 'var(--ink-3)' }}>Horas/mes</span><span>{monthlyHours.toFixed(0)}</span></div>
              <div><span style={{ color: 'var(--ink-3)' }}>Costo total</span><span>${fullCost.toFixed(0).toLocaleString()}</span></div>
              <div><span style={{ color: 'var(--ink-3)' }}>% automatizado</span><span>{auto}%</span></div>
            </div>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

// ============== Instructor ==============
function Instructor({ copy }) {
  return (
    <section className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
      </div>
      <div className="instructor">
        <Reveal>
          <div className="photo">
            <img src="lucas-toffolon.jpg" alt="Lucas Daniel Toffolon" />
          </div>
        </Reveal>
        <Reveal delay={120}>
          <div>
            <span className="role">{copy.role}</span>
            <h3>{copy.name}</h3>
            <p>{copy.bio}</p>
            <div className="bio-stats">
              {copy.stats.map((s, i) => (
                <div key={i} className="bio-stat">
                  <div className="num">{s.num}</div>
                  <div className="lbl">{s.lbl}</div>
                </div>
              ))}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ============== Testimonials ==============
function Testimonials({ copy }) {
  return (
    <section className="section container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"></span>{copy.eyebrow}</span>
        <Reveal><h2>{copy.title}</h2></Reveal>
      </div>
      <div className="testimonials">
        {copy.items.map((t, i) => (
          <Reveal key={i} delay={i * 80}>
            <div className="testi">
              <div className="quote">"{t.quote}"</div>
              <div className="who">
                <div className="avatar">{t.name.charAt(0)}</div>
                <div className="who-meta">
                  <span className="name">{t.name}</span>
                  <span className="role">{t.role}</span>
                </div>
              </div>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ============== CTA Final ==============
function CTAFinal({ copy, onCTA }) {
  return (
    <section className="cta-final">
      <Reveal>
        <h2>{copy.title_1}<span className="accent">{copy.title_accent}</span>{copy.title_2}</h2>
      </Reveal>
      <Reveal delay={120}>
        <p>{copy.lede}</p>
      </Reveal>
      <Reveal delay={200}>
        <div className="row">
          <button className="btn btn-primary" onClick={onCTA}>{copy.primary} →</button>
          <button className="btn btn-ghost" onClick={onCTA}>{copy.secondary}</button>
        </div>
      </Reveal>
    </section>
  );
}

// ============== Cursor glow ==============
function CursorGlow() {
  const ref = useRef(null);
  useEffect(() => {
    function move(e) {
      if (!ref.current) return;
      // need position relative to the artboard
      const root = ref.current.closest('.site');
      if (!root) return;
      const r = root.getBoundingClientRect();
      ref.current.style.left = (e.clientX - r.left) + 'px';
      ref.current.style.top = (e.clientY - r.top) + 'px';
    }
    document.addEventListener('mousemove', move);
    return () => document.removeEventListener('mousemove', move);
  }, []);
  return <div ref={ref} className="cursor-glow" style={{ position: 'absolute' }}></div>;
}

// ============== Main Site ==============
function Site({ variant = 'main' }) {
  const [lang, setLang] = useLang();
  const [showModal, setShowModal] = useState(false);
  const copy = window.SITE_COPY[lang];
  const openModal = () => setShowModal(true);
  const closeModal = () => setShowModal(false);

  return (
    <div className="site" data-variant={variant}>
      <div className="aurora"></div>
      <div className="grain"></div>
      <CursorGlow />
      <Nav lang={lang} setLang={setLang} copy={copy} onCTA={openModal} />
      <Hero copy={copy} onCTA={openModal} />
      <SignalRow items={copy.signal} />
      <Compare copy={copy.why} />
      <Stack copy={copy.stack} />
      <Roadmap copy={copy.roadmap} />
      <Audience copy={copy.audience} />
      <Modes copy={copy.modes} onCTA={openModal} />
      <ROI copy={copy.roi} />
      <Instructor copy={copy.instructor} />
      {/* <Testimonials copy={copy.testi} /> */}
      <CTAFinal copy={copy.cta} onCTA={openModal} />
      <div className="foot">
        {copy.foot.map((f, i) => <span key={i}>{f}</span>)}
      </div>
      {showModal && <ContactModal onClose={closeModal} />}
    </div>
  );
}

window.Site = Site;
