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

/* Animated counter: counts from `from` to `to` over `dur` ms when `play` flips true */
function Counter({ from = 0, to = 100, dur = 1400, play, prefix = '', suffix = '', sep = false }) {
  const [v, setV] = useState(from);
  useEffect(() => {
    if (!play) { setV(from); return; }
    const t0 = performance.now();
    let raf;
    const tick = (t) => {
      const k = Math.min(1, (t - t0) / dur);
      // ease-out cubic
      const e = 1 - Math.pow(1 - k, 3);
      setV(from + (to - from) * e);
      if (k < 1) raf = requestAnimationFrame(tick);
      else setV(to);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [play, from, to, dur]);
  const rounded = Math.round(v);
  const formatted = sep ? rounded.toLocaleString('pt-BR') : String(rounded);
  return <span>{prefix}{formatted}{suffix}</span>;
}

/* Decorative QR code — fake but visually structured */
function FakeQR({ size = 380, dark = '#101010', light = 'transparent', seed = 7 }) {
  // deterministic pattern: 25x25 modules with finder squares
  const n = 25;
  const cells = [];
  // LCG for repeatable noise
  let s = seed;
  const rnd = () => { s = (s * 1664525 + 1013904223) >>> 0; return (s & 0xffff) / 0xffff; };
  const isFinder = (x, y) => (
    (x < 7 && y < 7) ||
    (x >= n - 7 && y < 7) ||
    (x < 7 && y >= n - 7)
  );
  for (let y = 0; y < n; y++) {
    for (let x = 0; x < n; x++) {
      if (isFinder(x, y)) {
        const lx = x >= n - 7 ? x - (n - 7) : x;
        const ly = y >= n - 7 ? y - (n - 7) : y;
        const inOuter = lx === 0 || lx === 6 || ly === 0 || ly === 6;
        const inInner = (lx >= 2 && lx <= 4 && ly >= 2 && ly <= 4);
        if (inOuter || inInner) cells.push([x, y]);
      } else {
        if (rnd() > 0.52) cells.push([x, y]);
      }
    }
  }
  const cs = size / n;
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} role="img" aria-label="QR placeholder">
      <rect width={size} height={size} fill={light} />
      {cells.map(([x, y], i) => (
        <rect key={i} x={x * cs} y={y * cs} width={cs} height={cs} fill={dark} />
      ))}
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/* SLIDE 1 — Opening                                                   */
/* ------------------------------------------------------------------ */
function Slide1({ active, tweak }) {
  // generate stars + grid drift
  const stars = React.useMemo(() => {
    const arr = [];
    for (let i = 0; i < 60; i++) {
      arr.push({
        x: Math.random() * 100,
        y: Math.random() * 100,
        d: (Math.random() * 4).toFixed(2),
        s: (0.6 + Math.random() * 0.8).toFixed(2),
      });
    }
    return arr;
  }, []);

  return (
    <section className={"slide s1" + (active ? " active" : "")} data-screen-label="01 Abertura">
      <div className="bg-grid" />
      <div className="stars">
        {stars.map((s, i) => (
          <span key={i} className="star" style={{
            left: s.x + '%', top: s.y + '%',
            animationDelay: s.d + 's',
            transform: `scale(${s.s})`,
          }} />
        ))}
      </div>

      <div className="corner-mark">
        <div className="sym"><img src="brand/symbol-on-dark.svg" alt="" /></div>
        <div className="meta">NOVO DASH ⟶ TECH SHOWCASE 2026</div>
      </div>

      <div className="center">
        <div>
          <div className="logo-mark anim-rise d-1" style={{height: 100}}>
            <span className="nd-wordmark-mask" aria-label="novodash" />
          </div>

          <div className="title huge">
            <span className="lc anim-fade d-2">tecnologia brasileira,</span>
            <div className="anim-rise d-3">
              MOVENDO NEGÓCIOS
            </div>
            <div className="anim-rise d-4">
              NOS{' '}
              <span className="scribble-wrap">
                <span className="accent">EUA.</span>
                <img src="brand/motif-circle-scribble-red.svg" alt="" />
              </span>
            </div>
          </div>
        </div>
      </div>

      <div className="geo-arc anim-fade d-7">
        <div className="label-l">
          <span className="pin" /> BELO HORIZONTE · BR
        </div>
        <div className="line" />
        <div className="label-r">
          MIAMI · FLORIDA <span className="pin" />
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* SLIDE 2 — Quem somos                                                */
/* ------------------------------------------------------------------ */
function Slide2({ active }) {
  return (
    <section className={"slide s2" + (active ? " active" : "")} data-screen-label="02 Quem Somos">
      <div className="top">
        <div className="anim-fade d-1">
          <div className="eyebrow">⟶ QUEM SOMOS</div>
        </div>
        <div className="right-meta anim-fade d-1">
          Brasil → EUA
          <span className="big">Desde 2020</span>
        </div>
      </div>

      <div>
        <h1 className="headline">
          <span className="row anim-rise d-2">+5 ANOS</span>
          <span className="row anim-rise d-3">TRANSFORMANDO</span>
          <span className="row anim-rise d-4">
            NEGÓCIOS NOS{' '}
            <span className="scribble-wrap">
              EUA.
              <img src="brand/motif-underline.svg" alt="" />
            </span>
          </span>
        </h1>
        <div className="subline anim-fade d-6" style={{marginTop:24}}>
          Marketing digital, presença online e gestão de academias de jiu-jitsu para o mercado norte-americano.
        </div>
      </div>

      <div className="stats">
        <div className="stat anim-rise d-7">
          <div className="num">
            <Counter from={0} to={100} dur={1400} play={active} suffix="%" />
          </div>
          <div className="label">Clientes <span className="accent">nos EUA</span></div>
        </div>
        <div className="stat anim-rise d-8">
          <div className="num">
            <Counter from={0} to={100} dur={1600} play={active} prefix="+" />
          </div>
          <div className="label">Academias atendidas</div>
        </div>
        <div className="stat anim-rise d-9">
          <div className="num">
            <Counter from={0} to={12000} dur={1900} play={active} sep />
          </div>
          <div className="label">Novos alunos entregues</div>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* SLIDE 3 — Serviços                                                  */
/* ------------------------------------------------------------------ */
function Slide3({ active }) {
  const items = [
    { icon: 'ph-megaphone', num: '01', name: 'Marketing & Tráfego Pago', desc: 'Meta + Google direcionados ao mercado americano.' },
    { icon: 'ph-code', num: '02', name: 'Landing Pages & Sites', desc: 'Conversão e velocidade em código próprio.' },
    { icon: 'ph-trophy', num: '03', name: 'Gestão de Academias BJJ', desc: 'Presença digital, leads e retenção para o tatame americano.' },
    { icon: 'ph-shapes', num: '04', name: 'Branding & Identidade', desc: 'Sistemas visuais que escalam de feed a outdoor.' },
  ];
  return (
    <section className={"slide s3" + (active ? " active" : "")} data-screen-label="03 Serviços">
      <div className="top">
        <div>
          <div className="eyebrow anim-fade d-1">⟶ O QUE ENTREGAMOS HOJE</div>
          <h2 className="headline">
            <span className="row anim-rise d-2">QUATRO FRENTES.</span>
            <span className="row anim-rise d-3">UM <span className="accent">MERCADO.</span></span>
          </h2>
        </div>
        <div className="flag anim-fade d-3">
          <div className="flag-stripes">
            <div className="stripe" /><div className="stripe" /><div className="stripe" />
            <div className="stripe" /><div className="stripe" /><div className="stripe" />
            <div className="stripe" />
            <div className="canton" />
          </div>
          <div>100% MERCADO<br/>NORTE-AMERICANO</div>
        </div>
      </div>

      <div className="grid">
        {items.map((it, i) => (
          <div key={it.name} className={`card anim-rise d-${4 + i}`}>
            <div>
              <div className="num">{it.num}</div>
              <i className={`ph-duotone ${it.icon} icon`} />
            </div>
            <div>
              <div className="name">{it.name}</div>
              <div className="desc">{it.desc}</div>
              <div className="badge">USA market</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* SLIDE 4 — AI / Tech Era                                             */
/* ------------------------------------------------------------------ */
function Slide4({ active }) {
  // matrix rain columns
  const cols = React.useMemo(() => {
    const chars = '01アイウエオカキクケコサシスセソタチツテトabcdefHTTPGETPOST{}<>/=();[]→AI/ML';
    const arr = [];
    for (let i = 0; i < 38; i++) {
      const len = 18 + Math.floor(Math.random() * 22);
      let text = '';
      for (let j = 0; j < len; j++) {
        text += chars[Math.floor(Math.random() * chars.length)] + '\n';
      }
      arr.push({
        left: (i * (100 / 38)).toFixed(2),
        dur: (6 + Math.random() * 6).toFixed(2),
        delay: (-Math.random() * 8).toFixed(2),
        text,
        op: (0.3 + Math.random() * 0.7).toFixed(2),
      });
    }
    return arr;
  }, []);

  // neural network nodes/edges
  const net = React.useMemo(() => {
    const layers = [4, 6, 6, 3];
    const W = 760, H = 720;
    const nodes = [];
    const edges = [];
    const cols = layers.length;
    layers.forEach((count, li) => {
      for (let i = 0; i < count; i++) {
        const x = 80 + (W - 160) * (li / (cols - 1));
        const y = 80 + (H - 160) * ((i + 0.5) / count);
        nodes.push({ x, y, layer: li });
      }
    });
    nodes.forEach((a, ai) => {
      nodes.forEach((b, bi) => {
        if (b.layer === a.layer + 1) edges.push([ai, bi]);
      });
    });
    return { nodes, edges, W, H };
  }, []);

  return (
    <section className={"slide s4" + (active ? " active" : "")} data-screen-label="04 Nova Era IA">
      <div className="matrix" aria-hidden="true">
        {cols.map((c, i) => (
          <pre key={i} className="col" style={{
            left: c.left + '%',
            animationDuration: c.dur + 's',
            animationDelay: c.delay + 's',
            opacity: c.op,
          }}>{c.text}</pre>
        ))}
      </div>
      <div className="neon-glow" />

      <div className="corner-mark">
        <div className="sym"><img src="brand/symbol-on-dark.svg" alt="" /></div>
        <div className="meta">SISTEMA ⟶ AI ENGINE v1</div>
      </div>

      <div className="body">
        <div className="left">
          <div className="eyebrow anim-fade d-1">⟶ A NOVA ERA</div>
          <h2 className="headline">
            <span className="row anim-rise d-2">ENTRANDO NA ERA DA</span>
            <span className="row anim-rise d-4">
              <span className="accent">INTELIGÊNCIA<br/>ARTIFICIAL.</span>
            </span>
          </h2>
          <div className="sub anim-fade d-6">
            Sistemas, automações e produtos com IA, desenhados para o cliente americano, construídos do Brasil.
          </div>
          <div className="pills anim-fade d-7">
            <span className="pill solid">LLM AGENTS</span>
            <span className="pill">AUTOMAÇÕES</span>
            <span className="pill">SaaS</span>
            <span className="pill">DATA PIPELINES</span>
          </div>
        </div>

        <div className="net anim-fade d-5">
          <svg viewBox={`0 0 ${net.W} ${net.H}`} preserveAspectRatio="xMidYMid meet">
            {net.edges.map(([a, b], i) => {
              const A = net.nodes[a], B = net.nodes[b];
              return <line key={i} className="edge" x1={A.x} y1={A.y} x2={B.x} y2={B.y}
                style={{animationDelay: `${(i * 80) % 2000}ms`}} />;
            })}
            {net.nodes.map((n, i) => (
              <g key={i} style={{transformOrigin: `${n.x}px ${n.y}px`, animationDelay: `${(i * 160) % 1800}ms`}} className="node-g">
                <circle cx={n.x} cy={n.y} r={n.layer === 0 || n.layer === 3 ? 14 : 9}
                  className="node"
                  style={{animationDelay: `${(i * 160) % 1800}ms`}} />
              </g>
            ))}
          </svg>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* SLIDE 4B — IA em operação                                           */
/* ------------------------------------------------------------------ */
function SlideAIOps({ active }) {
  // Live "log" of AI activity that scrolls
  const logEntries = React.useMemo(() => ([
    { t: '14:02:17', tag: 'CALL', msg: 'Lead qualificado → academia em Tampa, FL' },
    { t: '14:02:09', tag: 'BOOK', msg: 'Aula experimental agendada · 18h local' },
    { t: '14:01:54', tag: 'CALL', msg: 'Follow-up automático · Houston, TX' },
    { t: '14:01:33', tag: 'PAGE', msg: 'Landing v3 publicada · Phoenix BJJ' },
    { t: '14:01:12', tag: 'SYS',  msg: 'Dashboard de retenção · build OK' },
    { t: '14:00:58', tag: 'BOOK', msg: '3 trials agendados · LA County' },
    { t: '14:00:41', tag: 'CALL', msg: 'Lead recuperado · Miami Beach' },
    { t: '14:00:22', tag: 'PAGE', msg: 'A/B test rodando · 4 variantes ativas' },
    { t: '14:00:05', tag: 'SYS',  msg: 'CRM sync · 412 leads atualizados' },
    { t: '13:59:48', tag: 'CALL', msg: 'Aluno reativado · Atlanta, GA' },
  ]), []);

  const blocks = [
    {
      side: 'PARA O CLIENTE',
      items: [
        { icon: 'ph-phone-call', name: 'Ligações com IA', desc: 'Prospecção e qualificação de leads em inglês, 24/7.' },
        { icon: 'ph-calendar-check', name: 'Agendamentos automáticos', desc: 'Aulas experimentais marcadas direto na agenda da academia.' },
      ]
    },
    {
      side: 'DENTRO DE CASA',
      items: [
        { icon: 'ph-browsers', name: 'Landing pages', desc: 'Páginas geradas, testadas e iteradas com IA.' },
        { icon: 'ph-code', name: 'Sistemas internos', desc: 'CRM, dashboards e automações construídas com IA.' },
      ]
    }
  ];

  return (
    <section className={"slide s4b" + (active ? " active" : "")} data-screen-label="05 IA em Operação">
      <div className="s4b-grid-bg" />
      <div className="neon-glow s4b-glow" />

      <div className="corner-mark">
        <div className="sym"><img src="brand/symbol-on-dark.svg" alt="" /></div>
        <div className="meta">IA ENGINE ⟶ PRODUÇÃO · v1.4</div>
      </div>

      <div className="s4b-live">
        <span className="live-dot" /> LIVE · NOW
      </div>

      <div className="s4b-body">
        <div className="s4b-head">
          <div className="eyebrow anim-fade d-1">⟶ IA EM OPERAÇÃO</div>
          <h2 className="s4b-headline">
            <span className="row anim-rise d-2">LITERALMENTE TUDO,</span>
            <span className="row anim-rise d-3"><span className="accent">COM IA.</span></span>
          </h2>
          <div className="s4b-sub anim-fade d-5">
            Não é roadmap. Já está rodando, para clientes americanos, todos os dias.
          </div>
        </div>

        <div className="s4b-cols">
          {blocks.map((b, ci) => (
            <div key={b.side} className={`s4b-col anim-rise d-${5 + ci}`}>
              <div className="s4b-col-label">⟶ {b.side}</div>
              <div className="s4b-cards">
                {b.items.map((it, ii) => (
                  <div key={it.name} className="s4b-card">
                    <i className={`ph-duotone ${it.icon} s4b-icon`} />
                    <div className="s4b-card-text">
                      <div className="s4b-card-name">{it.name}</div>
                      <div className="s4b-card-desc">{it.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        <div className="s4b-feed anim-fade d-8">
          <div className="s4b-feed-label">⟶ AI ENGINE · LOG</div>
          <div className="s4b-feed-stream">
            <div className="s4b-feed-track">
              {[...logEntries, ...logEntries].map((e, i) => (
                <div key={i} className="s4b-feed-row">
                  <span className="s4b-feed-time">{e.t}</span>
                  <span className={`s4b-feed-tag tag-${e.tag.toLowerCase()}`}>{e.tag}</span>
                  <span className="s4b-feed-msg">{e.msg}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.SlideAIOps = SlideAIOps;

/* ------------------------------------------------------------------ */
/* SLIDE 5 — Recrutamento                                              */
/* ------------------------------------------------------------------ */
function Slide5({ active }) {
  return (
    <section className={"slide s5" + (active ? " active" : "")} data-screen-label="06 Vem Com a Gente">
      <div className="left">
        <div className="eyebrow anim-fade d-1">⟶ ESTAMOS CONTRATANDO</div>
        <h1 className="headline">
          <span className="anim-rise d-2" style={{display:'block'}}>VEM</span>
          <span className="anim-rise d-3" style={{display:'block'}}>COM A</span>
          <span className="anim-rise d-4" style={{display:'block'}}>
            <span className="scribble-wrap">
              <span className="scribble-text">GENTE.</span>
              <img src="brand/motif-circle-scribble-red.svg" alt="" />
            </span>
          </span>
        </h1>
        <div className="sub anim-fade d-6">
          Procuramos <b>devs</b> e <b>entusiastas de IA</b> para construir produtos para clientes americanos, do Brasil, no nosso fuso, no nosso tatame.
        </div>
        <div className="stacks anim-fade d-7">
          <span className="chip"><i className="ph-duotone ph-browsers" /> Frontend</span>
          <span className="chip"><i className="ph-duotone ph-database" /> Backend</span>
          <span className="chip"><i className="ph-duotone ph-brain" /> IA / LLM</span>
          <span className="chip"><i className="ph-duotone ph-lightning" /> Automação</span>
          <span className="chip"><i className="ph-duotone ph-cloud" /> Cloud</span>
        </div>
      </div>
      <div className="right anim-scale d-5">
        <div className="qr-card">
          <div className="qr-wrap">
            <img src="brand/qr-evento-puc.svg" alt="QR Code candidatura" width={400} height={400} />
          </div>
          <div className="label">CANDIDATE-SE <span className="accent">⟶ aponte a câmera</span></div>
        </div>
      </div>
    </section>
  );
}

window.Slide1 = Slide1;
window.Slide2 = Slide2;
window.Slide3 = Slide3;
window.Slide4 = Slide4;
window.Slide5 = Slide5;
