// Sections 1–4: Nav, Hero, Trust marquee, Damaging admission

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0,
      zIndex: 80,
      transition: 'background .25s ease, border-color .25s ease, backdrop-filter .25s ease',
      background: scrolled ? 'rgba(10, 9, 8, 0.7)' : 'transparent',
      backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: 68,
      }}>
        {/* Brand */}
        <a href="#top" style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <img src="assets/medux-logo.png" alt="Medux" style={{ height: 28, width: 'auto', display: 'block' }} />
        </a>

        {/* Center links */}
        <div className="nav-links" style={{
          display: 'flex', alignItems: 'center', gap: 30,
          fontSize: 14, color: 'var(--fg-dim)',
        }}>
          <a href="#kit" style={{ transition: 'color .2s' }} onMouseEnter={e=>e.currentTarget.style.color='var(--fg)'} onMouseLeave={e=>e.currentTarget.style.color='var(--fg-dim)'}>O que está incluso</a>
          <a href="#dashboard" onMouseEnter={e=>e.currentTarget.style.color='var(--fg)'} onMouseLeave={e=>e.currentTarget.style.color='var(--fg-dim)'}>Como funciona</a>
          <a href="#oferta" onMouseEnter={e=>e.currentTarget.style.color='var(--fg)'} onMouseLeave={e=>e.currentTarget.style.color='var(--fg-dim)'}>Garantia</a>
          <a href="#faq" onMouseEnter={e=>e.currentTarget.style.color='var(--fg)'} onMouseLeave={e=>e.currentTarget.style.color='var(--fg-dim)'}>FAQ</a>
        </div>

        {/* Right side */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <a href="https://www.instagram.com/meduxpro/" target="_blank" rel="noopener noreferrer" aria-label="Instagram @meduxpro" style={{ color: 'var(--fg-dim)', display: 'grid', placeItems: 'center', width: 36, height: 36, borderRadius: 8, border: '1px solid var(--line)' }}>
            <Icon.Instagram />
          </a>
          <a href="https://pay.kiwify.com.br/iIkOFg8" target="_blank" rel="noopener noreferrer" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 14 }}>
            Acessar o Kit
            <Icon.ArrowRight size={14} />
          </a>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .nav-links { display: none !important; }
        }
      `}</style>
    </nav>
  );
}

function NeuralBackground({ color = '#FF5B2C', trailOpacity = 0.04, particleCount = 380, speed = 0.7 }) {
  const canvasRef = React.useRef(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const container = containerRef.current;
    if (!canvas || !container) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    let width = container.clientWidth;
    let height = container.clientHeight;
    let particles = [];
    let raf;
    let t = 0;
    const mouse = { x: -1000, y: -1000 };

    // Pseudo-Perlin via layered sine — smoother & cheaper than real Perlin
    const fieldAngle = (x, y, time) => {
      const s = 0.0022;
      const n =
        Math.sin(x * s + time * 0.0006) +
        Math.cos(y * s * 1.3 - time * 0.0005) +
        Math.sin((x + y) * s * 0.7 + time * 0.0004);
      return n * Math.PI; // 0..~3π — multiple full rotations across screen
    };

    class Particle {
      constructor() { this.reset(true); }
      reset(initial) {
        this.x = Math.random() * width;
        this.y = Math.random() * height;
        this.px = this.x;
        this.py = this.y;
        this.life = 0;
        this.maxLife = 200 + Math.random() * 300;
        this.speed = (0.6 + Math.random() * 0.9) * speed;
        this.thickness = Math.random() < 0.15 ? 2.4 : 1.6;
      }
      step() {
        this.px = this.x;
        this.py = this.y;

        const a = fieldAngle(this.x, this.y, t);
        this.x += Math.cos(a) * this.speed;
        this.y += Math.sin(a) * this.speed;

        // soft mouse repulsion — gentle nudge, not a kick
        const dx = this.x - mouse.x, dy = this.y - mouse.y;
        const d2 = dx * dx + dy * dy;
        const r = 140;
        if (d2 < r * r && d2 > 0.01) {
          const d = Math.sqrt(d2);
          const f = (r - d) / r;
          this.x += (dx / d) * f * 1.4;
          this.y += (dy / d) * f * 1.4;
        }

        this.life++;
        // wrap edges — and reset px/py so we don't draw a line across the screen
        let wrapped = false;
        if (this.x < 0) { this.x += width; wrapped = true; }
        else if (this.x > width) { this.x -= width; wrapped = true; }
        if (this.y < 0) { this.y += height; wrapped = true; }
        else if (this.y > height) { this.y -= height; wrapped = true; }
        if (wrapped) { this.px = this.x; this.py = this.y; }

        if (this.life > this.maxLife) this.reset(false);
      }
      draw(c) {
        // alpha fades in/out across life for organic feel
        const lifeFrac = this.life / this.maxLife;
        const a = Math.sin(lifeFrac * Math.PI) * 0.85;
        c.globalAlpha = a;
        c.lineWidth = this.thickness;
        c.beginPath();
        c.moveTo(this.px, this.py);
        c.lineTo(this.x, this.y);
        c.stroke();
      }
    }

    const init = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = width * dpr;
      canvas.height = height * dpr;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.scale(dpr, dpr);
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      ctx.lineCap = 'round';
      ctx.strokeStyle = color;
      particles = [];
      for (let i = 0; i < particleCount; i++) particles.push(new Particle());
    };

    const animate = () => {
      // Trail fade — low alpha black overlay = long, smooth streamlines
      ctx.globalAlpha = 1;
      ctx.fillStyle = `rgba(10, 9, 8, ${trailOpacity})`;
      ctx.fillRect(0, 0, width, height);

      ctx.strokeStyle = color;
      for (const p of particles) { p.step(); p.draw(ctx); }
      t += 1;
      raf = requestAnimationFrame(animate);
    };

    const onResize = () => {
      width = container.clientWidth;
      height = container.clientHeight;
      init();
    };
    const onMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouse.x = e.clientX - rect.left;
      mouse.y = e.clientY - rect.top;
    };
    const onLeave = () => { mouse.x = -1000; mouse.y = -1000; };

    init(); animate();
    window.addEventListener('resize', onResize);
    container.addEventListener('mousemove', onMove);
    container.addEventListener('mouseleave', onLeave);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', onResize);
      container.removeEventListener('mousemove', onMove);
      container.removeEventListener('mouseleave', onLeave);
    };
  }, [color, trailOpacity, particleCount, speed]);

  return (
    <div ref={containerRef} aria-hidden="true" style={{
      position: 'absolute', inset: 0, overflow: 'hidden',
      background: '#0A0908', zIndex: 0,
    }}>
      <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
      {/* soft coral glow + bottom vignette so text stays readable */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 70% 55% at 50% 38%, rgba(255,91,44,0.16), rgba(10,9,8,0) 72%)',
      }} />
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(180deg, rgba(10,9,8,0) 55%, rgba(10,9,8,0.9) 100%)',
      }} />
    </div>
  );
}

function Hero() {
  return (
    <section id="top" className="section" style={{ paddingTop: 140, paddingBottom: 0, overflow: 'hidden', position: 'relative' }}>
      <NeuralBackground color="#FF5B2C" trailOpacity={0.35} particleCount={380} speed={0.7} />
      <div className="container" style={{ position: 'relative', zIndex: 1, textAlign: 'center' }}>
        <div className="fade-up">
          <div className="pill" style={{ margin: '0 auto' }}>
            <span className="dot" />
            ENQUANTO VOCÊ LÊ ISTO, MÉDICOS ESTÃO ECONOMIZANDO DE 8 A 20 MIN POR CONSULTA COM ESTE KIT IA
          </div>
        </div>

        <h1 className="h-display fade-up d1" style={{ marginTop: 28, fontSize: 'clamp(38px, 6.4vw, 88px)' }}>
          A IA não vai te substituir.<br />
          <span className="coral-grad">O médico que sabe usar IA<br />provavelmente vai.</span>
        </h1>

        <p className="lede fade-up d2" style={{
          margin: '28px auto 0',
          fontSize: 'clamp(16px, 1.3vw, 19px)',
          maxWidth: '62ch',
        }}>
          Não é palestra de futuro. É 2026. ChatGPT, Claude e Gemini já fazem evolução SOAP em 40 segundos, montam laudo estruturado em minutos e respondem a paciente no WhatsApp sem você precisar pensar. A pergunta é: <span style={{ color: 'var(--fg)' }}>você sabe usar?</span>
        </p>

        <div className="fade-up d3" style={{
          display: 'flex', justifyContent: 'center', gap: 12, marginTop: 36,
          flexWrap: 'wrap',
        }}>
          <a href="https://pay.kiwify.com.br/iIkOFg8" target="_blank" rel="noopener noreferrer" className="btn btn-primary lg glow">
            200 prompts por R$147
            <Icon.ArrowRight />
          </a>
          <a href="#kit" className="btn btn-ghost lg">
            Quero ver antes
            <Icon.ArrowDown />
          </a>
        </div>

        <div className="mono fade-up d4 meta-row" style={{
          marginTop: 26, fontSize: 12, letterSpacing: '0.16em',
          color: 'var(--fg-mute)', textTransform: 'uppercase',
        }}>
          <span style={{ textDecoration: 'line-through' }}>R$197</span>
          <span style={{ color: 'var(--fg)' }}>R$147 NO PIX</span>
          <span>OU 6X R$27,58</span>
          <span>7 DIAS DE GARANTIA</span>
        </div>

        {/* Dashboard mockup with Aceternity-style scroll tilt */}
        <ContainerScroll>
          <DashboardMock />
        </ContainerScroll>
      </div>
    </section>
  );
}

/* Aceternity-style scroll-driven container tilt */
function ContainerScroll({ children }) {
  const wrapRef = React.useRef(null);
  const cardRef = React.useRef(null);
  const titleRef = React.useRef(null);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    const card = cardRef.current;
    const title = titleRef.current;
    if (!wrap || !card) return;

    let raf = 0;
    const isMobile = () => window.matchMedia('(max-width: 760px)').matches;

    const update = () => {
      raf = 0;
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      // progress: 0 when wrap top hits viewport bottom, 1 when wrap top hits viewport top
      const total = r.height + vh;
      const passed = vh - r.top;
      let p = passed / total;
      p = Math.max(0, Math.min(1, p));
      // Ease-out so the unfold feels organic
      const eased = 1 - Math.pow(1 - p, 2.2);

      const startRot = isMobile() ? 18 : 22;
      const startScale = isMobile() ? 0.78 : 0.82;
      const endScale = 1;
      const startTitleScale = 0.92;
      const endTitleScale = 1.04;

      const rot = startRot * (1 - eased);
      const scale = startScale + (endScale - startScale) * eased;
      const ty = (1 - eased) * 30;

      card.style.transform = `translateY(${ty}px) rotateX(${rot}deg) scale(${scale})`;

      if (title) {
        const ts = startTitleScale + (endTitleScale - startTitleScale) * eased;
        title.style.transform = `translateY(${(1 - eased) * -10}px) scale(${ts})`;
        title.style.opacity = String(0.65 + 0.35 * eased);
      }
    };

    const onScroll = () => {
      if (!raf) raf = requestAnimationFrame(update);
    };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div ref={wrapRef} className="container-scroll" style={{
      perspective: '1200px',
      perspectiveOrigin: '50% 0%',
      marginTop: 80,
      paddingBottom: 0,
    }}>
      <div ref={titleRef} style={{
        textAlign: 'center',
        marginBottom: 28,
        transformOrigin: '50% 100%',
        willChange: 'transform, opacity',
        transition: 'opacity .2s linear',
      }}>
        <div className="mono meta-row" style={{
          fontSize: 11, letterSpacing: '0.18em',
          color: 'var(--fg-mute)',
        }}>
          <span>PRODUTO REAL</span>
          <span>ACESSO IMEDIATO APÓS A COMPRA</span>
        </div>
        <h3 style={{
          fontSize: 'clamp(22px, 2.6vw, 34px)',
          letterSpacing: '-0.02em',
          margin: '8px 0 0',
          fontWeight: 600,
        }}>
          O Dashboard MEDUX, por dentro
        </h3>
      </div>
      <div ref={cardRef} className="container-scroll-card" style={{
        transformOrigin: '50% 0%',
        transformStyle: 'preserve-3d',
        willChange: 'transform',
        borderRadius: 18,
        boxShadow: '0 60px 120px -40px rgba(0,0,0,0.7), 0 30px 60px -30px rgba(255,91,44,0.18), 0 0 0 1px rgba(255,255,255,0.04) inset',
        background: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0))',
        padding: 6,
      }}>
        {children}
      </div>
    </div>
  );
}

function TrustedBy() {
  const items = [
    'Cardiologia · Hospital Albert Einstein',
    'Clínica Médica · HCor',
    'Pediatria · Hospital Sírio-Libanês',
    'Radiologia · InCor',
    'Ginecologia · Hospital das Clínicas USP',
    'Psiquiatria · Hospital Israelita',
    'Dermatologia · Beneficência Portuguesa',
    'Ortopedia · Sancta Maggiore',
    'Oftalmologia · Hospital Samaritano',
    'Anestesiologia · BP Mirante',
  ];
  const doubled = [...items, ...items];

  return (
    <section className="section tight" style={{ paddingTop: 80, paddingBottom: 80 }}>
      <div className="container" style={{ textAlign: 'center', marginBottom: 32 }}>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.18em',
          color: 'var(--fg-mute)', textTransform: 'uppercase',
        }}>
          MÉDICOS QUE TESTARAM EM ROTINA REAL
        </div>
      </div>
      <div className="marquee">
        <div className="marquee-track">
          {doubled.map((label, i) => (
            <div key={i} className="marquee-item">
              <span>{label}</span>
              <span className="sep" />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function DamagingAdmission() {
  const cards = [
    { h: 'Isto não é mágica.', b: 'São 200 prompts num arquivo. Você ainda vai ler o que a IA gera. Vai revisar. Vai ajustar. A IA é assistente, não médico.' },
    { h: 'Isto não é curso.',   b: 'Não tem aula obrigatória, não tem módulo. É copia, cola e usa. Se você sabe abrir ChatGPT, sabe usar o Kit.' },
    { h: 'Isto não vai te fazer melhor médico.', b: 'Vai te fazer terminar mais rápido. São coisas diferentes. Sua medicina depende de você. Sua agenda depende de método.' },
  ];
  return (
    <section className="section" id="honestidade">
      <div className="container">
        <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 18, maxWidth: 760 }}>
          <div className="pill"><span className="dot" />ANTES DE COMPRAR</div>
          <h2 className="h-1">Vamos dizer o que isto não é.</h2>
          <p className="lede">Médico cético merece honestidade na cara. Aqui está.</p>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 18,
          marginTop: 56,
        }} className="grid-3">
          {cards.map((c, i) => (
            <div key={i} className={`card fade-up d${i+1}`}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', color: 'var(--fg-mute)' }}>0{i+1} / NÃO É</div>
              <h3 style={{ fontSize: 22, letterSpacing: '-0.02em', margin: '14px 0 12px', fontWeight: 600 }}>{c.h}</h3>
              <p style={{ color: 'var(--fg-dim)', margin: 0, fontSize: 15, lineHeight: 1.55 }}>{c.b}</p>
            </div>
          ))}
        </div>

        <div className="coral-block fade-up" style={{
          marginTop: 24, textAlign: 'center',
          padding: '34px 28px',
          fontSize: 'clamp(20px, 2.2vw, 28px)',
          fontWeight: 600,
          letterSpacing: '-0.025em',
        }}>
          Se o produto fosse mais do que isso, custaria mais que R$147.
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) { .grid-3 { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

window.Nav = Nav;
window.Hero = Hero;
window.TrustedBy = TrustedBy;
window.DamagingAdmission = DamagingAdmission;
