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

// ============================================================
// NAV
// ============================================================
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`np-nav ${scrolled ? 'is-scrolled' : ''}`}>
      <div className="wrap np-nav__inner">
        <a className="np-nav__logo" href="#">
          <img src="assets/natipay-logo.png" alt="Natipay" />
        </a>
        <div className="np-nav__links">
          <a href="#produtos">Produtos</a>
          <a href="#segmentos">Para quem é</a>
          <a href="#api">Integrações</a>
          <a href="#seguranca">Segurança</a>
          <a href="#">Tarifas</a>
        </div>
        <div className="np-nav__cta">
          <a className="np-nav__login" href="#">Entrar</a>
          <a className="btn btn-primary np-nav__signup" href="#">
            Criar conta <span className="arr">→</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ============================================================
// HERO — Totem PDV with animated PIX QR Code flow
// ============================================================
function Hero({ heroVariant }) {
  return (
    <section className="np-hero">
      <div className="np-hero__bg" />
      <HeroGridPattern />
      <div className="wrap np-hero__inner">
        <div className="np-hero__left">
          <div className="tag on-dark">
            <span className="dot" /> PIX em tempo real · 99,99% uptime
          </div>
          <h1>
            Pagamentos<br/>
            <span className="np-hero__accent">na frente do caixa.</span>
          </h1>
          <p className="np-hero__lede">
            A infraestrutura de PIX, checkout e API que move totens,
            PDVs e frentes de loja em todo o Brasil. Recebimento
            instantâneo, conciliação automática, zero fricção.
          </p>
          <div className="np-hero__ctas">
            <a className="btn btn-blue" href="#">
              Começar grátis <span className="arr">→</span>
            </a>
            <a className="btn btn-ghost-light" href="#api">
              Ver documentação
            </a>
          </div>
          <div className="np-hero__metrics">
            <Metric value="< 800ms" label="liquidação PIX" />
            <Metric value="R$ 14B" label="processados em 2025" />
            <Metric value="12k+" label="terminais ativos" />
          </div>
        </div>
        <div className="np-hero__right">
          {heroVariant === 'totem' && <TotemMockup />}
          {heroVariant === 'phone' && <PhoneCheckoutMockup />}
          {heroVariant === 'flow' && <PaymentFlowMockup />}
        </div>
      </div>
      <HeroBottomBar />
    </section>
  );
}

function HeroGridPattern() {
  return (
    <svg className="np-hero__grid" viewBox="0 0 1440 800" preserveAspectRatio="none" aria-hidden>
      <defs>
        <pattern id="np-grid" width="56" height="56" patternUnits="userSpaceOnUse">
          <path d="M 56 0 L 0 0 0 56" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1"/>
        </pattern>
        <radialGradient id="np-glow" cx="80%" cy="30%" r="60%">
          <stop offset="0%" stopColor="rgba(63,184,238,0.45)" />
          <stop offset="100%" stopColor="rgba(63,184,238,0)" />
        </radialGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#np-grid)" />
      <rect width="100%" height="100%" fill="url(#np-glow)" />
    </svg>
  );
}

function Metric({ value, label }) {
  return (
    <div className="np-metric">
      <div className="np-metric__value mono">{value}</div>
      <div className="np-metric__label">{label}</div>
    </div>
  );
}

function HeroBottomBar() {
  const items = ['Visa', 'Mastercard', 'PIX', 'Banco Central', 'Elo', 'American Express', 'Hipercard'];
  return (
    <div className="np-hero__bar">
      <div className="wrap np-hero__bar-inner">
        <span className="np-hero__bar-label mono">Aceitamos</span>
        <div className="np-hero__bar-track">
          {[...items, ...items].map((i, idx) => (
            <span key={idx} className="np-hero__bar-item">{i}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

// ============================================================
// TOTEM MOCKUP — animated PIX checkout
// ============================================================
function TotemMockup() {
  const [stage, setStage] = useState(0); // 0 idle, 1 qr, 2 scanning, 3 paid
  useEffect(() => {
    const seq = [
      { s: 1, t: 1400 },
      { s: 2, t: 2400 },
      { s: 3, t: 4200 },
      { s: 0, t: 6800 },
    ];
    let timer;
    let i = 0;
    const tick = () => {
      setStage(seq[i].s);
      timer = setTimeout(() => {
        i = (i + 1) % seq.length;
        tick();
      }, seq[i].t - (i > 0 ? seq[i-1].t : 0));
    };
    timer = setTimeout(tick, 500);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div className="totem">
      <div className="totem__shadow" />
      <div className="totem__body">
        <div className="totem__bezel">
          <div className="totem__screen">
            <div className="totem__topbar">
              <img src="assets/natipay-logo.png" alt="" className="totem__logo" />
              <span className="totem__time mono">14:32</span>
            </div>

            <div className={`totem__stage stage-${stage}`}>
              {/* Stage 0: idle / amount */}
              <div className="totem__panel idle">
                <div className="totem__label mono">Total a pagar</div>
                <div className="totem__amount">
                  <span className="cur">R$</span>
                  <span className="val">127,<small>40</small></span>
                </div>
                <div className="totem__cta">
                  <div className="totem__cta-btn">Pagar com PIX</div>
                </div>
              </div>

              {/* Stage 1: QR */}
              <div className="totem__panel qr">
                <div className="totem__label mono">Aponte a câmera</div>
                <div className="totem__qr-wrap">
                  <QRCode />
                  <div className="totem__scan" />
                </div>
                <div className="totem__amount sm">
                  <span className="cur">R$</span>
                  <span className="val">127,<small>40</small></span>
                </div>
              </div>

              {/* Stage 2: scanning / pending */}
              <div className="totem__panel pending">
                <div className="totem__spinner" />
                <div className="totem__pending-text">Processando pagamento…</div>
                <div className="totem__amount sm">
                  <span className="cur">R$</span>
                  <span className="val">127,<small>40</small></span>
                </div>
              </div>

              {/* Stage 3: paid */}
              <div className="totem__panel paid">
                <div className="totem__check">
                  <svg viewBox="0 0 64 64" width="64" height="64">
                    <circle cx="32" cy="32" r="30" fill="#00C29B" />
                    <path d="M18 33 L28 43 L46 23" fill="none" stroke="white" strokeWidth="5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
                <div className="totem__paid-title">Pago!</div>
                <div className="totem__paid-sub mono">Comprovante #84921 · liquidado em 612ms</div>
              </div>
            </div>

            <div className="totem__footer mono">
              <span>natipay.com.br</span>
              <span>·</span>
              <span>terminal #PDV-014</span>
            </div>
          </div>
        </div>
        <div className="totem__base">
          <div className="totem__stem" />
          <div className="totem__foot" />
        </div>
      </div>

      {/* Floating event chip */}
      <FloatingChip stage={stage} />
    </div>
  );
}

function FloatingChip({ stage }) {
  const messages = [
    { icon: '○', text: 'aguardando cliente', cls: 'idle' },
    { icon: '◇', text: 'QR Code gerado · 30s', cls: 'qr' },
    { icon: '↻', text: 'callback /webhook enviado', cls: 'pending' },
    { icon: '✓', text: 'pix.received · R$ 127,40', cls: 'paid' },
  ];
  const m = messages[stage];
  return (
    <div key={stage} className={`totem__chip chip-${m.cls}`}>
      <span className="chip__icon mono">{m.icon}</span>
      <span className="chip__text mono">{m.text}</span>
    </div>
  );
}

function QRCode() {
  // procedural QR-like grid (not a real QR)
  const cells = 25;
  const seed = [];
  let s = 7;
  for (let i = 0; i < cells * cells; i++) {
    s = (s * 9301 + 49297) % 233280;
    seed.push(s / 233280 > 0.5);
  }
  return (
    <div className="totem__qr">
      <svg viewBox="0 0 25 25" width="100%" height="100%">
        {/* finder patterns */}
        {[[0,0],[18,0],[0,18]].map(([x,y],i) => (
          <g key={i}>
            <rect x={x} y={y} width="7" height="7" fill="#0B1E37" />
            <rect x={x+1} y={y+1} width="5" height="5" fill="white" />
            <rect x={x+2} y={y+2} width="3" height="3" fill="#0B1E37" />
          </g>
        ))}
        {/* random data cells */}
        {seed.map((on, i) => {
          if (!on) return null;
          const x = i % cells;
          const y = Math.floor(i / cells);
          // skip finder regions
          if ((x < 8 && y < 8) || (x > 16 && y < 8) || (x < 8 && y > 16)) return null;
          return <rect key={i} x={x} y={y} width="1" height="1" fill="#0B1E37" />;
        })}
        {/* center logo dot */}
        <rect x="10" y="10" width="5" height="5" fill="white" />
        <rect x="11" y="11" width="3" height="3" fill="#3FB8EE" rx="0.5" />
      </svg>
    </div>
  );
}

// ============================================================
// Alternative hero variants
// ============================================================
function PhoneCheckoutMockup() {
  return (
    <div className="phone">
      <div className="phone__body">
        <div className="phone__notch" />
        <div className="phone__screen">
          <div className="phone__app-bar">
            <span className="mono">9:41</span>
            <div className="phone__dots"><span/><span/><span/></div>
          </div>
          <div className="phone__merchant">Padaria Bom Pão</div>
          <div className="phone__amount">R$ 42,<small>90</small></div>
          <div className="phone__qr"><QRCode /></div>
          <div className="phone__paybtn">Confirmar pagamento</div>
          <div className="phone__note mono">PIX · expira em 04:58</div>
        </div>
      </div>
    </div>
  );
}

function PaymentFlowMockup() {
  return (
    <div className="flowm">
      <div className="flowm__step">
        <div className="flowm__num mono">01</div>
        <div className="flowm__title">Cliente abre o checkout</div>
        <div className="flowm__bar"><div className="flowm__fill" style={{width:'100%'}} /></div>
      </div>
      <div className="flowm__step">
        <div className="flowm__num mono">02</div>
        <div className="flowm__title">QR Code PIX gerado pela API</div>
        <div className="flowm__bar"><div className="flowm__fill" style={{width:'72%'}} /></div>
      </div>
      <div className="flowm__step active">
        <div className="flowm__num mono">03</div>
        <div className="flowm__title">Pagamento confirmado</div>
        <div className="flowm__bar"><div className="flowm__fill" style={{width:'100%', background:'var(--pix-green)'}} /></div>
      </div>
      <div className="flowm__step">
        <div className="flowm__num mono">04</div>
        <div className="flowm__title">Webhook entregue ao lojista</div>
        <div className="flowm__bar"><div className="flowm__fill" style={{width:'48%'}} /></div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Nav, Hero, TotemMockup, PhoneCheckoutMockup, PaymentFlowMockup, QRCode, Metric
});
