/* MOB.tv — cinematic content sections */
const { useState, useEffect, useRef, useMemo } = React;

/* ─── Shared carousel hook ─────────────────────────────────────── */
function useCarouselTrack(count) {
  const ref = useRef(null);
  const [active, setActive] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const update = () => {
      const cardW = (el.firstElementChild?.offsetWidth ?? el.clientWidth) + 14;
      setActive(Math.max(0, Math.min(count - 1, Math.round(el.scrollLeft / cardW))));
    };
    el.addEventListener('scroll', update, { passive: true });
    return () => el.removeEventListener('scroll', update);
  }, [count]);
  const scrollTo = (i) => {
    const el = ref.current;
    if (!el) return;
    const cardW = (el.firstElementChild?.offsetWidth ?? el.clientWidth) + 14;
    el.scrollTo({ left: i * cardW, behavior: 'smooth' });
  };
  return { ref, active, scrollTo };
}

/* ─── Carousel dot indicator ────────────────────────────────────── */
function CarouselDots({ count, active, onSelect }) {
  return (
    <div className="carousel-dots" aria-hidden="true">
      {Array.from({ length: count }).map((_, i) => (
        <button key={i} className={`carousel-dot${i === active ? ' active' : ''}`} onClick={() => onSelect(i)} />
      ))}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   HERO with typing rotator
   ───────────────────────────────────────────────────────────────── */
const HERO_WORDS = [
  'COPA DO MUNDO',
  'UFC',
  'FUTEBOL',
  'FILMES',
  'SÉRIES',
  'CHAMPIONS',
  'NBA',
  'ANIMES',
];

function Typewriter({ words }) {
  const [wordIdx, setWordIdx] = useState(0);
  const [text, setText] = useState('');
  const [phase, setPhase] = useState('typing'); // typing | holding | erasing | swap
  const [swap, setSwap] = useState(false);

  useEffect(() => {
    const current = words[wordIdx];
    let timeout;

    if (phase === 'typing') {
      if (text.length < current.length) {
        timeout = setTimeout(() => {
          setText(current.slice(0, text.length + 1));
        }, 60 + Math.random() * 40);
      } else {
        timeout = setTimeout(() => setPhase('holding'), 1400);
      }
    } else if (phase === 'holding') {
      timeout = setTimeout(() => setPhase('erasing'), 1100);
    } else if (phase === 'erasing') {
      if (text.length > 0) {
        timeout = setTimeout(() => {
          setText(text.slice(0, -1));
        }, 28);
      } else {
        setSwap(true);
        timeout = setTimeout(() => {
          setWordIdx((wordIdx + 1) % words.length);
          setSwap(false);
          setPhase('typing');
        }, 220);
      }
    }

    return () => clearTimeout(timeout);
  }, [text, phase, wordIdx, words]);

  return (
    <h2 className="typewriter" aria-live="polite">
      <span className="static">Dê play em</span>{' '}
      <span className={`rotor${swap ? ' swapping' : ''}`}>
        {text}
        <span className="caret" aria-hidden="true"></span>
      </span>
    </h2>
  );
}

function HeroV2() {
  const ambientRef = useRef(null);
  // Subtle scroll parallax
  useEffect(() => {
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (!ambientRef.current) return;
        const y = window.scrollY;
        ambientRef.current.style.transform = `translateY(${y * 0.25}px)`;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  const onCTA = (e) => {
    e.preventDefault();
    window.tracker?.trackClick('hero_cta');
    window.smoothScrollTo('cta');
  };

  return (
    <section id="top" className="hero-v2" data-screen-label="01 Hero">
      <div className="ambient" ref={ambientRef} aria-hidden="true"></div>
      <div className="grid-overlay" aria-hidden="true"></div>

      <div className="inner">
        <div className="eyebrow" style={{ marginBottom: 28 }}>O seu player de entretenimento</div>

        <h1 className="hero-logo" aria-label="MOB.TV">
          <span className="word">MOB</span>
          <span className="dot">.</span>
          <span className="word b">TV</span>
        </h1>

        <Typewriter words={HERO_WORDS} />

        <p className="description">
          Qualidade 4K, estabilidade 24h e suporte humano dedicado.
        </p>

        <a href="#cta" className="cta-cinematic" onClick={onCTA}>
          <span className="label">Quero Realizar Meu Teste</span>
        </a>
      </div>

      <div className="hero-hint" aria-hidden="true">
        <span>2026 · 4K HDR</span>
        <span>Role para descobrir</span>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Streaming services marquee
   ───────────────────────────────────────────────────────────────── */
const SERVICES = [
  { name: 'Netflix', style: '' },
  { name: 'Prime Video', style: 'mono' },
  { name: 'HBO Max', style: 'serif' },
  { name: 'Disney+', style: '' },
  { name: 'Apple TV+', style: '' },
  { name: 'Paramount+', style: 'mono' },
  { name: 'ESPN', style: '' },
  { name: 'Telecine', style: 'serif' },
  { name: 'Crunchyroll', style: '' },
  { name: 'Globoplay', style: '' },
  { name: 'Premiere', style: 'mono' },
  { name: 'Discovery+', style: 'italic' },
];

/* ─────────────────────────────────────────────────────────────────
   Interactive Touch-Draggable Auto-Scrolling Track
   ───────────────────────────────────────────────────────────────── */
function InteractiveTrack({ children, speed = 0.08, className = "" }) {
  const containerRef = React.useRef(null);
  const isDragging = React.useRef(false);
  const startX = React.useRef(0);
  const scrollLeft = React.useRef(0);
  const animFrameId = React.useRef(null);
  const lastTime = React.useRef(0);

  React.useEffect(() => {
    const el = containerRef.current;
    if (!el) return;

    const scrollLoop = (time) => {
      if (!isDragging.current) {
        if (!lastTime.current) lastTime.current = time;
        const delta = time - lastTime.current;
        lastTime.current = time;

        // Auto scroll
        el.scrollLeft += speed * delta;

        // Infinite loop wrap
        const maxScroll = el.scrollWidth / 2;
        if (el.scrollLeft >= maxScroll) {
          el.scrollLeft -= maxScroll;
        }
      } else {
        lastTime.current = 0; // reset delta calculations while dragging
      }
      animFrameId.current = requestAnimationFrame(scrollLoop);
    };

    animFrameId.current = requestAnimationFrame(scrollLoop);

    return () => {
      if (animFrameId.current) {
        cancelAnimationFrame(animFrameId.current);
      }
    };
  }, [speed]);

  const onMouseDown = (e) => {
    isDragging.current = true;
    startX.current = e.pageX - containerRef.current.offsetLeft;
    scrollLeft.current = containerRef.current.scrollLeft;
    containerRef.current.style.cursor = 'grabbing';
  };

  const onMouseMove = (e) => {
    if (!isDragging.current) return;
    e.preventDefault();
    const x = e.pageX - containerRef.current.offsetLeft;
    const walk = (x - startX.current) * 1.5;
    containerRef.current.scrollLeft = scrollLeft.current - walk;
  };

  const onMouseUpOrLeave = () => {
    isDragging.current = false;
    if (containerRef.current) {
      containerRef.current.style.cursor = 'grab';
    }
  };

  const onTouchStart = (e) => {
    isDragging.current = true;
    startX.current = e.touches[0].pageX - containerRef.current.offsetLeft;
    scrollLeft.current = containerRef.current.scrollLeft;
  };

  const onTouchMove = (e) => {
    if (!isDragging.current) return;
    const x = e.touches[0].pageX - containerRef.current.offsetLeft;
    const walk = (x - startX.current) * 1.5;
    containerRef.current.scrollLeft = scrollLeft.current - walk;
  };

  return (
    <div
      ref={containerRef}
      className={className}
      style={{
        overflowX: 'hidden',
        whiteSpace: 'nowrap',
        cursor: 'grab',
        userSelect: 'none',
        width: '100%'
      }}
      onMouseDown={onMouseDown}
      onMouseMove={onMouseMove}
      onMouseUp={onMouseUpOrLeave}
      onMouseLeave={onMouseUpOrLeave}
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onMouseUpOrLeave}
    >
      {children}
    </div>
  );
}

function StreamingMarquee() {
  return (
    <section className="streaming-strip" data-screen-label="02 Streaming">
      <div className="label">Acesso a um ecossistema completo</div>
      <div className="streaming-track-wrap">
        <div className="streaming-track">
          {Array.from({ length: 2 }).map((_, k) => (
            <React.Fragment key={k}>
              {SERVICES.map((s, i) => (
                <span
                  key={`${k}-${i}`}
                  className={`svc ${s.style}${i % 5 === 2 ? ' glow' : ''}`}
                >
                  {s.name}
                </span>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div className="marquee-comparison">
        <div className="comp-side old">
          <p className="comp-desc">Para ter todos eles você gastaria</p>
          <div className="comp-price grey">R$ 400<small>/mês</small></div>
        </div>
        <div className="comp-side new">
          <p className="comp-desc highlight">Na MOB você tem tudo a partir de</p>
          <div className="comp-price gold">R$ 19,90<small>/mês</small></div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Benefits
   ───────────────────────────────────────────────────────────────── */
const BENEFITS = [
  { n: '01', t: 'Qualidade FHD e 4K', d: 'Imagem cristalina, cores vibrantes e máxima definição em cada conteúdo.' },
  { n: '02', t: 'Sem travamentos', d: 'Servidores de alta performance garantindo estabilidade 24 horas por dia.' },
  { n: '03', t: 'Compatível com tudo', d: 'Smart TVs, TV Box, Android, iPhone, tablet e computador.' },
  { n: '04', t: 'Esportes ao vivo', d: 'Futebol, UFC, Champions, Brasileirão, Libertadores e mais.' },
  { n: '05', t: 'Catálogo atualizado', d: 'Filmes, séries e lançamentos atualizados constantemente.' },
  { n: '06', t: 'App rápido', d: 'Interface leve, moderna e otimizada para a melhor experiência.' },
  { n: '07', t: 'Suporte humano', d: 'Atendimento rápido e humanizado direto pelo WhatsApp.' },
  { n: '08', t: 'Liberação imediata', d: 'Seu acesso liberado em poucos minutos para assistir agora.' },
];

const BENEFIT_GLYPHS = {
  '01': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="3" /><path d="M3 12c3-5 6-7 9-7s6 2 9 7c-3 5-6 7-9 7s-6-2-9-7z" /></svg>),
  '02': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 8l3 8 4-12 4 12 3-8" /></svg>),
  '03': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="6" width="13" height="9" rx="1" /><rect x="16" y="9" width="5" height="9" rx="1" /></svg>),
  '04': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9" /><path d="M12 3v18M3 12h18" /></svg>),
  '05': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16" rx="2" /><path d="M8 8h8M8 12h8M8 16h5" /></svg>),
  '06': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z" /></svg>),
  '07': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 17a4 4 0 014-4h2v8H7a4 4 0 01-4-4zM21 17a4 4 0 00-4-4h-2v8h2a4 4 0 004-4zM12 3a8 8 0 00-8 8v3M12 3a8 8 0 018 8v3" /></svg>),
  '08': (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 2v6M12 16v6M2 12h6M16 12h6M5 5l4 4M15 15l4 4M5 19l4-4M15 9l4-4" /></svg>),
};

function Benefits() {
  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    e.currentTarget.style.setProperty('--mouse-x', `${e.clientX - r.left}px`);
    e.currentTarget.style.setProperty('--mouse-y', `${e.clientY - r.top}px`);
  };
  const marqueeItems = useMemo(() => [...BENEFITS, ...BENEFITS], []);
  return (
    <section id="beneficios" className="benefits shell" data-screen-label="03 Benefits">
      <div className="section-head reveal">
        <div className="eyebrow">Por que escolher a MOB TV</div>
        <h2 className="display-m">
          Entretenimento completo,<br />
          com estabilidade de verdade.
        </h2>
      </div>

      {/* Grid for desktop */}
      <div className="benefits-grid reveal" data-delay="1">
        {BENEFITS.map((b) => (
          <div key={b.n} className="benefit" onMouseMove={onMove}>
            <div className="glyph">{BENEFIT_GLYPHS[b.n]}</div>
            <div className="num">{b.n}</div>
            <h4>{b.t}</h4>
            <p>{b.d}</p>
          </div>
        ))}
      </div>

      {/* Marquee for mobile */}
      <div className="benefits-marquee-outer reveal" data-delay="1">
        <div className="benefits-marquee">
          {marqueeItems.map((b, idx) => (
            <div key={`${b.n}-${idx}`} className="benefit" onMouseMove={onMove}>
              <div className="glyph">{BENEFIT_GLYPHS[b.n]}</div>
              <div className="num">{b.n}</div>
              <h4>{b.t}</h4>
              <p>{b.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}


/* ─────────────────────────────────────────────────────────────────
   Catalog
   ───────────────────────────────────────────────────────────────── */
const CATEGORIES = [
  { n: '01', t: 'Filmes', d: 'Lançamentos, clássicos e sucessos em FHD e 4K.', bg: 'cat-bg-films' },
  { n: '02', t: 'Séries', d: 'Temporadas completas e episódios atualizados constantemente.', bg: 'cat-bg-series' },
  { n: '03', t: 'Esportes Ao Vivo', d: 'A emoção dos maiores campeonatos em tempo real.', bg: 'cat-bg-sports' },
  { n: '04', t: 'UFC e Lutas', d: 'Eventos, cards principais e as maiores lutas do mundo.', bg: 'cat-bg-ufc' },
];

function Catalog() {
  const mobileItems = useMemo(() => [...CATEGORIES, ...CATEGORIES], []);
  return (
    <section id="catalogo" className="catalog shell" data-screen-label="04 Catalog">
      <div className="section-head reveal">
        <div className="eyebrow">Catálogo</div>
        <h2 className="display-l">
          Tudo o que você quer assistir.<br />
          Em um único lugar.
        </h2>
      </div>
      <div className="catalog-grid reveal" data-delay="1">
        {CATEGORIES.map((c) => (
          <article key={c.n} className="cat-card">
            <div className={`bg ${c.bg}`} aria-hidden="true"></div>
            <div className="grad" aria-hidden="true"></div>
            <span className="num">{c.n}</span>
            <div className="content">
              <h4>{c.t}</h4>
              <p>{c.d}</p>
              <span className="arrow-pill">Explorar</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Tech / Stability — animated signal waves
   ───────────────────────────────────────────────────────────────── */
function TechViz() {
  const canvasRef = useRef(null);
  const [bps, setBps] = useState(248);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, w, h, dpr;
    const resize = () => {
      dpr = Math.min(2, window.devicePixelRatio || 1);
      const rect = canvas.parentElement.getBoundingClientRect();
      w = canvas.width = rect.width * dpr;
      h = canvas.height = rect.height * dpr;
      canvas.style.width = rect.width + 'px';
      canvas.style.height = rect.height + 'px';
    };
    resize();
    window.addEventListener('resize', resize);

    const start = performance.now();
    const draw = (t) => {
      const time = (t - start) / 1000;
      ctx.clearRect(0, 0, w, h);

      // Layered sine waves
      const layers = [
        { amp: 30, freq: 0.012, speed: 1.2, color: 'rgba(250, 204, 21, 0.7)', width: 1.6, glow: 18 },
        { amp: 20, freq: 0.018, speed: -0.9, color: 'rgba(245, 158, 11, 0.45)', width: 1.2, glow: 12 },
        { amp: 14, freq: 0.026, speed: 1.6, color: 'rgba(250, 204, 21, 0.25)', width: 1, glow: 6 },
      ];
      const midY = h / 2;
      layers.forEach((L) => {
        ctx.beginPath();
        ctx.lineWidth = L.width * dpr;
        ctx.strokeStyle = L.color;
        ctx.shadowColor = L.color;
        ctx.shadowBlur = L.glow;
        for (let x = 0; x <= w; x += 2 * dpr) {
          const tt = time * L.speed;
          // Envelope so the wave swells in the middle
          const env = Math.sin((x / w) * Math.PI);
          const y = midY + Math.sin(x * L.freq + tt) * L.amp * dpr * env;
          if (x === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.stroke();
      });
      ctx.shadowBlur = 0;

      // Faint horizontal baseline
      ctx.strokeStyle = 'rgba(255, 255, 255, 0.04)';
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(0, midY);
      ctx.lineTo(w, midY);
      ctx.stroke();

      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
    };
  }, []);

  // Live "bandwidth" counter that idly oscillates
  useEffect(() => {
    const id = setInterval(() => {
      setBps(240 + Math.floor(Math.random() * 24));
    }, 1100);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="tech-viz">
      <canvas ref={canvasRef}></canvas>
      <div className="nodes" aria-hidden="true">
        <span className="node pulse" style={{ left: '12%', top: '50%' }}></span>
        <span className="node pulse" style={{ left: '38%', top: '50%', animationDelay: '0.7s' }}></span>
        <span className="node pulse" style={{ left: '62%', top: '50%', animationDelay: '1.3s' }}></span>
        <span className="node pulse" style={{ left: '88%', top: '50%', animationDelay: '1.9s' }}></span>
      </div>
      <div className="meta"><span className="dot"></span>Sinal estável · 24h</div>
      <div className="reading">
        <div>
          <div style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--fg-faint)', textTransform: 'uppercase', marginBottom: 4 }}>
            Throughput
          </div>
          <div className="num">{bps}<span style={{ fontSize: '0.5em', color: 'var(--fg-dim)', marginLeft: 2 }}>Mb/s</span></div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--fg-faint)', textTransform: 'uppercase', marginBottom: 4 }}>
            Latência
          </div>
          <div className="num">24<span style={{ fontSize: '0.5em', color: 'var(--fg-dim)', marginLeft: 2 }}>ms</span></div>
        </div>
      </div>
    </div>
  );
}

function TechStability() {
  return (
    <section className="tech shell" data-screen-label="05 Technology">
      <div className="tech-stage reveal">
        <div className="tech-copy">
          <div className="eyebrow" style={{ marginBottom: 24 }}>Tecnologia</div>
          <h2 className="display-m">
            Estabilidade real até nos horários de pico.
          </h2>
          <p>
            Sem travamentos, delays ou interrupções.
          </p>
          <dl className="tech-stats">
            <div>
              <dt>Uptime</dt>
              <dd>99,98%</dd>
            </div>
            <div>
              <dt>Latência</dt>
              <dd>&lt; 2s</dd>
            </div>
            <div>
              <dt>Nós Edge</dt>
              <dd>12</dd>
            </div>
          </dl>
        </div>
        <TechViz />
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Devices carousel
   ───────────────────────────────────────────────────────────────── */
const DEVICES = [
  { num: '01', name: 'Smart TV', os: 'Samsung · LG · Roku', kind: 'tv' },
  { num: '02', name: 'TV Box', os: 'Android TV · Chromecast', kind: 'box' },
  { num: '03', name: 'iPhone', os: 'Todos os iPhones', kind: 'phone' },
  { num: '04', name: 'Android', os: 'Todos os Androids', kind: 'phone' },
  { num: '05', name: 'Notebook', os: 'macOS · Windows · Linux', kind: 'laptop' },
  { num: '06', name: 'Tablet', os: 'iPad · Android Tablet', kind: 'tablet' },
];

function DeviceGlyph({ kind }) {
  const stroke = 'rgba(255,255,255,0.85)';
  const fill = 'rgba(255,255,255,0.02)';
  if (kind === 'tv') return (
    <svg viewBox="0 0 100 76" fill={fill} stroke={stroke} strokeWidth="1.4">
      <rect x="4" y="4" width="92" height="56" rx="3" />
      <rect x="9" y="9" width="82" height="46" rx="1.5" fill="rgba(250,204,21,0.04)" stroke="none" />
      <line x1="36" y1="70" x2="64" y2="70" />
      <line x1="42" y1="64" x2="58" y2="64" />
    </svg>
  );
  if (kind === 'box') return (
    <svg viewBox="0 0 100 76" fill={fill} stroke={stroke} strokeWidth="1.4">
      <rect x="14" y="26" width="72" height="32" rx="3" />
      <circle cx="74" cy="42" r="2.4" fill={stroke} stroke="none" />
      <line x1="22" y1="50" x2="44" y2="50" />
    </svg>
  );
  if (kind === 'phone') return (
    <svg viewBox="0 0 60 100" fill={fill} stroke={stroke} strokeWidth="1.4">
      <rect x="11" y="4" width="38" height="92" rx="6" />
      <rect x="14" y="9" width="32" height="78" rx="2" fill="rgba(250,204,21,0.04)" stroke="none" />
      <line x1="25" y1="90" x2="35" y2="90" />
    </svg>
  );
  if (kind === 'tablet') return (
    <svg viewBox="0 0 80 100" fill={fill} stroke={stroke} strokeWidth="1.4">
      <rect x="6" y="4" width="68" height="92" rx="5" />
      <rect x="10" y="9" width="60" height="82" rx="2" fill="rgba(250,204,21,0.04)" stroke="none" />
      <circle cx="40" cy="93" r="1.6" />
    </svg>
  );
  if (kind === 'laptop') return (
    <svg viewBox="0 0 110 80" fill={fill} stroke={stroke} strokeWidth="1.4">
      <rect x="16" y="8" width="78" height="50" rx="2.4" />
      <rect x="20" y="12" width="70" height="42" rx="1.2" fill="rgba(250,204,21,0.04)" stroke="none" />
      <line x1="4" y1="64" x2="106" y2="64" />
      <line x1="40" y1="68" x2="70" y2="68" />
    </svg>
  );
  return null;
}

function DevicesCarousel() {
  const items = React.useMemo(() => [...DEVICES, ...DEVICES, ...DEVICES, ...DEVICES], []);
  return (
    <section id="dispositivos" className="devices-v2" data-screen-label="06 Devices">
      <div className="shell">
        <div className="section-head reveal">
          <div className="eyebrow">Dispositivos</div>
          <h2 className="display-l">
            Seu entretenimento<br />em qualquer tela.
          </h2>
          <p className="lede">
            Smart TV, TV Box, celular, tablet ou computador — máxima qualidade
            e estabilidade.
          </p>
        </div>
      </div>
      <div className="devices-carousel reveal" data-delay="1">
        <InteractiveTrack speed={0.10} className="devices-track">
          {items.map((d, i) => (
            <div key={i} className="device-card" style={{ marginRight: 'clamp(14px, 2vw, 22px)', flexShrink: 0 }}>
              <div className="device-num">{d.num} / 06</div>
              <div className="device-render">
                <DeviceGlyph kind={d.kind} />
              </div>
              <div>
                <div className="device-name">{d.name}</div>
                <div className="device-os">{d.os}</div>
              </div>
            </div>
          ))}
        </InteractiveTrack>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Testimonials
   ───────────────────────────────────────────────────────────────── */
const QUOTES = [
  { q: 'Já testei vários aplicativos antes e quase todos travavam principalmente em horário de jogo. Na MOB TV foi totalmente diferente. A imagem fica estável, os canais carregam rápido e até os filmes em alta qualidade rodam muito bem.', n: 'Marcos V.', c: 'Rio de Janeiro · RJ', i: 'MV' },
  { q: 'O que mais gostei foi a organização da plataforma. Consegui encontrar séries, filmes e esportes muito rápido. Uso praticamente todos os dias e até agora a experiência foi muito acima do que eu esperava.', n: 'Juliana F.', c: 'Fortaleza · CE', i: 'JF' },
  { q: 'Assisto bastante futebol e UFC ao vivo, então estabilidade era o mais importante pra mim. Testei durante jogos grandes e funcionou sem travamentos. Dá pra perceber diferença comparado a outros serviços.', n: 'André L.', c: 'Goiânia · GO', i: 'AL' },
  { q: 'A qualidade da imagem me surpreendeu muito, principalmente nos canais esportivos. Além disso, o catálogo é enorme e sempre encontro alguma coisa nova para assistir com minha família.', n: 'Fernanda M.', c: 'Campinas · SP', i: 'FM' },
];

function Testimonials() {
  return (
    <section className="testimonials shell" data-screen-label="07 Testimonials">
      <div className="section-head reveal">
        <div className="eyebrow">Depoimentos</div>
        <h2 className="display-l">
          Quem procura estabilidade,<br />fica na MOB TV.
        </h2>
      </div>
      <div className="testimonial-grid">
        {QUOTES.map((q, i) => (
          <div key={i} className="testimonial reveal" data-delay={i + 1}>
            <div className="quote-mark" aria-hidden="true">"</div>
            <blockquote>{q.q}</blockquote>
            <div className="author">
              <div className="avatar">{q.i}</div>
              <div className="author-meta">
                <div className="name">{q.n}</div>
                <div className="city">{q.c}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   How it works
   ───────────────────────────────────────────────────────────────── */
const STEPS = [
  { n: '01', t: 'Escolha seu acesso', d: 'Selecione o plano ideal e finalize sua adesão em segundos.' },
  { n: '02', t: 'Receba sua liberação', d: 'Em poucos minutos seu acesso é ativado, com instruções claras.' },
  { n: '03', t: 'Comece a assistir', d: 'Conecte-se em qualquer dispositivo e mergulhe no catálogo.' },
];

function HowItWorks() {
  return (
    <section className="howto shell" data-screen-label="08 How it works">
      <div className="section-head reveal">
        <div className="eyebrow">Como funciona</div>
        <h2 className="display-l">Começar é simples.</h2>
      </div>
      <div className="howto-steps">
        {STEPS.map((s, i) => (
          <div key={s.n} className="howto-step reveal" data-delay={i + 1}>
            <div className="step-num">{s.n}</div>
            <h4>{s.t}</h4>
            <p>{s.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Pricing / Planos
   ───────────────────────────────────────────────────────────────── */
function PricingSection() {
  const [familyScreens, setFamilyScreens] = React.useState(1);
  const [fullScreens, setFullScreens] = React.useState(1);

  const familyPrices = {
    1: '19,90',
    2: '31,90',
    3: '42,90',
  };

  const fullPrices = {
    1: '23,99',
    2: '37,90',
    3: '49,90',
  };

  const onSelectPlan = (planName, screens) => {
    const prices = planName === 'Family' ? familyPrices : fullPrices;
    const price = prices[screens];
    const msg = `Olá! Gostaria de realizar meu teste grátis no plano ${planName} com ${screens} ${screens === 1 ? 'tela' : 'telas'} (R$ ${price}/mês).`;
    
    // Rastreamento do clique no plano e tela
    const eventName = `plan_${planName.toLowerCase()}_${screens}_screen${screens > 1 ? 's' : ''}`;
    window.tracker?.trackClick(eventName);

    window.open(`https://api.whatsapp.com/send?phone=5521959063337&text=${encodeURIComponent(msg)}`, '_blank');
  };

  return (
    <section id="planos" className="pricing shell" data-screen-label="09 Pricing">
      <div className="section-head reveal">
        <div className="eyebrow">Nossos Planos</div>
        <h2 className="display-m">
          Escolha o plano ideal para sua rotina<br />
          e dê play sem travamentos.
        </h2>
      </div>

      <div className="pricing-grid reveal" data-delay="1">
        {/* Features list */}
        <div className="pricing-features">
          <h3>O que está incluso</h3>
          <ul>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>Filmes, séries e lançamentos</span>
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>UFC, futebol ao vivo e esportes</span>
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>Canais abertos e fechados</span>
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>Compatível com TV, Celular e PC</span>
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>Suporte humano especializado</span>
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="check-icon"><polyline points="20 6 9 17 4 12"></polyline></svg>
              <span>Estabilidade premium sem travamentos</span>
            </li>
          </ul>
        </div>

        {/* Card Family */}
        <div className="pricing-card">
          <div className="card-head">
            <span className="plan-name">Family</span>
            <p className="plan-desc">Mais de 5.000 conteúdos, esportes ao vivo e lançamentos atualizados em tempo real.</p>
          </div>
          
          <div className="screens-selector">
            <span className="sel-label">Selecione as telas:</span>
            <div className="sel-pills">
              {[1, 2, 3].map((num) => (
                <button
                  key={num}
                  className={`sel-pill ${familyScreens === num ? 'active' : ''}`}
                  onClick={() => setFamilyScreens(num)}
                >
                  {num} {num === 1 ? 'Tela' : 'Telas'}
                </button>
              ))}
            </div>
          </div>

          <div className="card-price-wrap">
            <div className="price">
              <span className="currency">R$</span>
              <span className="amount">{familyPrices[familyScreens]}</span>
              <span className="period">/mês</span>
            </div>
          </div>

          <button
            className="pricing-btn"
            onClick={() => onSelectPlan('Family', familyScreens)}
          >
            Quero Realizar Meu Teste
          </button>
        </div>

        {/* Card Full */}
        <div className="pricing-card highlighted">
          <div className="card-badge">Mais vendido</div>
          <div className="card-head">
            <span className="plan-name">Full</span>
            <p className="plan-desc">Catálogo completo com mais de 10.000 conteúdos, esportes, <span className="hot-highlight">acesso hot liberado</span> e com senha para privacidade.</p>
          </div>
          
          <div className="screens-selector">
            <span className="sel-label">Selecione as telas:</span>
            <div className="sel-pills">
              {[1, 2, 3].map((num) => (
                <button
                  key={num}
                  className={`sel-pill ${fullScreens === num ? 'active' : ''}`}
                  onClick={() => setFullScreens(num)}
                >
                  {num} {num === 1 ? 'Tela' : 'Telas'}
                </button>
              ))}
            </div>
          </div>

          <div className="card-price-wrap">
            <div className="price gold">
              <span className="currency">R$</span>
              <span className="amount">{fullPrices[fullScreens]}</span>
              <span className="period">/mês</span>
            </div>
          </div>

          <button
            className="pricing-btn gold"
            onClick={() => onSelectPlan('Full', fullScreens)}
          >
            Quero Realizar Meu Teste
          </button>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Final CTA
   ───────────────────────────────────────────────────────────────── */
function FinalCTAV2() {
  const onCTA = (e) => {
    e.preventDefault();
    const msg = "Olá! Quero começar e realizar meu teste grátis na MOB TV.";
    window.tracker?.trackClick('final_cta');
    window.open(`https://api.whatsapp.com/send?phone=5521959063337&text=${encodeURIComponent(msg)}`, '_blank');
  };
  return (
    <section id="cta" className="final-cta-v2 shell" data-screen-label="09 Final CTA">
      <div className="inner">
        <div className="eyebrow reveal" style={{ marginBottom: 28, justifyContent: 'center' }}>
          Pronto para começar
        </div>
        <h2 className="display-xl reveal" data-delay="1">
          Dê play no que importa.
        </h2>
        <p className="lede reveal" data-delay="2" style={{ textAlign: 'center', maxWidth: '54ch', margin: '0 auto 48px' }}>
          Filmes, séries, futebol, UFC e muito mais tudo em um só lugar, com estabilidade de verdade.
        </p>
        <div className="reveal" data-delay="3">
          <a href="#" className="cta-cinematic" onClick={onCTA} style={{ animation: 'none', opacity: 1, transform: 'none' }}>
            <span className="label">Quero Realizar Meu Teste</span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* Export to window so app.jsx can use them */
Object.assign(window, {
  HeroV2,
  StreamingMarquee,
  Benefits,
  Catalog,
  TechStability,
  DevicesCarousel,
  Testimonials,
  HowItWorks,
  PricingSection,
  FinalCTAV2,
});
