// ============================================
// SECTIONS 3 — QR Scanner, Features, Final CTA
// ============================================
const { useState: useS3, useEffect: useE3, useRef: useR3 } = React;

// ---------- QR SCANNER ----------
function QRScanner() {
  const [active, setActive] = useS3(false);
  const [result, setResult] = useS3(null);
  const [error, setError] = useS3(null);
  const videoRef = useR3(null);
  const streamRef = useR3(null);
  const rafRef = useR3(null);

  const stop = () => {
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(t => t.stop());
      streamRef.current = null;
    }
    setActive(false);
  };

  const start = async () => {
    setError(null);
    setResult(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        await videoRef.current.play();
      }
      setActive(true);
      scanLoop();
    } catch (e) {
      setError('No se pudo acceder a la cámara. Permití el acceso y probá de nuevo.');
    }
  };

  const scanLoop = () => {
    const tick = () => {
      if (!videoRef.current || !streamRef.current) return;
      if (videoRef.current.readyState === videoRef.current.HAVE_ENOUGH_DATA && window.jsQR) {
        const canvas = document.createElement('canvas');
        canvas.width = videoRef.current.videoWidth;
        canvas.height = videoRef.current.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
        const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const code = window.jsQR(imgData.data, canvas.width, canvas.height);
        if (code) {
          setResult(code.data);
          stop();
          return;
        }
      }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
  };

  useE3(() => () => stop(), []);

  return (
    <section className="block" id="qr">
      <div className="container">
        <div className="qrs-wrap reveal">
          <div>
            <div className="eyebrow violet"><span className="dot"></span><span>ESCÁNER QR · LIVE</span></div>
            <h2 className="section-h">Escaneá un <span className="glow">QR real</span></h2>
            <p className="section-sub">
              Imprimí una etiqueta con el código único de cada activo. El operador lo escanea
              desde su celular y accede al instante a la ficha: hoja de vida, mantenimientos,
              responsable y ubicación.
            </p>
            <div className="qrs-actions">
              {!active ? (
                <button className="btn btn-primary hover-target" onClick={start}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h3v3h-3zM18 18h3M14 21v-3"/></svg>
                  Activar cámara
                </button>
              ) : (
                <button className="btn btn-ghost hover-target" onClick={stop}>Detener</button>
              )}
              <a className="btn btn-ghost hover-target" href="#modulos">Ver todos los módulos →</a>
            </div>
            {error && (
              <div style={{marginTop: 18, padding: 14, background: 'rgba(251,113,133,0.08)', border: '1px solid rgba(251,113,133,0.3)', borderRadius: 10, fontSize: 13, color: 'var(--red)'}}>
                {error}
              </div>
            )}
            {result && (
              <div className="qrs-result">
                <b>ACTIVO DETECTADO</b>
                <div style={{color: 'var(--ink-0)', fontSize: 14, wordBreak: 'break-all'}}>{result}</div>
              </div>
            )}
          </div>

          <div className="qrs-screen">
            <video ref={videoRef} className="qrs-video" playsInline muted/>
            {!active && (
              <div className="qrs-placeholder">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" strokeWidth="1" style={{filter:'drop-shadow(0 0 8px var(--cyan))'}}>
                  <path d="M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h3v3h-3zM18 18h3M14 21v-3"/>
                </svg>
                <div className="mono">CÁMARA INACTIVA</div>
                <div style={{fontSize: 12, color: 'var(--ink-2)', maxWidth: 260}}>Hacé clic en "Activar cámara" y apuntá a cualquier código QR.</div>
              </div>
            )}
            {active && (
              <div className="qrs-overlay">
                <div className="qrs-box">
                  <div className="qrs-corners">
                    <span></span><span></span><span></span><span></span>
                  </div>
                  <div className="qrs-scanline-live"></div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- FEATURES ----------
function Features() {
  const feats = [
    { i: '☁', t: '100% en la nube', d: 'Accedé desde cualquier dispositivo. Sin instalaciones ni mantenimiento de servidores.' },
    { i: '🔒', t: 'Seguridad nivel bancario', d: 'Cifrado SSL, backups automáticos y control de acceso granular por rol.' },
    { i: '📱', t: 'Optimizado para móvil', d: 'Escaneá QR, aprobá solicitudes y registrá novedades desde el campo.' },

    { i: '🤝', t: 'Soporte humano', d: 'Asesores por WhatsApp, videollamada y capacitación incluida.' },
  ];
  return (
    <section className="block" id="por-que">
      <div className="container">
        <div className="feat-wrap">
          <div className="reveal">
            <div className="eyebrow amber"><span className="dot"></span><span>POR QUÉ ELEGIRNOS</span></div>
            <h2 className="section-h">Tecnología que <span className="glow">trabaja</span> para ti</h2>
            <p className="section-sub">
              Sin servidores. Sin instalaciones. Sin Excel. Todo centralizado, seguro y
              en tiempo real.
            </p>
            <div className="feat-list">
              {feats.map(f => (
                <div key={f.t} className="feat-item hover-target">
                  <div className="feat-ico">{f.i}</div>
                  <div>
                    <div className="feat-t">{f.t}</div>
                    <div className="feat-d">{f.d}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="feat-viz reveal-stagger reveal">
            <div className="feat-vc hl">
              <div className="feat-vc-ic">◆</div>
              
              <div className="feat-vc-l">COP en activos gestionados este mes</div>
            </div>
            <div className="feat-vc">
              <div className="feat-vc-ic">⚡</div>
              <div className="feat-vc-v">2 min</div>
              <div className="feat-vc-l">activación promedio</div>
            </div>
            <div className="feat-vc">
              <div className="feat-vc-ic">↓</div>
              <div className="feat-vc-v">-68%</div>
              <div className="feat-vc-l">activos perdidos</div>
            </div>
            <div className="feat-vc">
              <div className="feat-vc-ic">🌎</div>
              <div className="feat-vc-v">12</div>
              <div className="feat-vc-l">países LATAM</div>
            </div>
            <div className="feat-vc">
              <div className="feat-vc-ic">★</div>
              <div className="feat-vc-v">4.9<span style={{fontSize:'0.5em', color:'var(--ink-3)'}}>/5</span></div>
              <div className="feat-vc-l">satisfacción</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function CountUp3({ value }) {
  const [d, setD] = useS3(0);
  const ref = useR3(null);
  useE3(() => {
    const el = ref.current;
    let done = false;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !done) {
        done = true;
        const t0 = performance.now();
        const dur = 1200;
        const tick = t => {
          const p = Math.min(1, (t - t0) / dur);
          const eased = 1 - Math.pow(1-p, 3);
          setD(Math.round(value * eased));
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    });
    if (el) obs.observe(el);
    return () => obs.disconnect();
  }, [value]);
  return <span ref={ref}>{d.toLocaleString('es-CO')}</span>;
}

// ---------- FINAL CTA ----------
function FinalCTA() {
  return (
    <section className="cta-final">
      <div className="container">
        <div className="cta-box reveal">
          <div className="eyebrow" style={{margin: '0 auto 16px'}}><span className="dot"></span><span>EMPEZÁ EN 2 MINUTOS</span></div>
          <h2>¿Listo para tomar <span className="glow">el control</span><br/>de tus activos?</h2>
     
          <div className="cta-actions">
            <a className="btn btn-primary" href="https://wa.me/573017287922?text=Estoy%20interesado%20en%20Mi%20Activo%20360...">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 00-8.5 15.2L2 22l4.9-1.4A10 10 0 1012 2zm5.5 13.5c-.2.6-1.2 1.1-1.7 1.1-.4 0-1 .1-3.5-1-2.1-.9-3.5-3.1-3.6-3.2-.1-.1-.9-1.2-.9-2.3 0-1.1.6-1.7.8-1.9.2-.2.4-.2.6-.2h.4c.1 0 .3 0 .5.4.2.5.6 1.6.7 1.7 0 .1.1.2 0 .4-.1.2-.1.3-.3.4-.1.1-.3.3-.4.4-.1.1-.3.3-.1.5.1.2.6.9 1.3 1.5.9.8 1.6 1 1.8 1.1.2.1.4.1.5-.1.1-.1.6-.7.8-.9.2-.2.3-.2.5-.1.2.1 1.3.6 1.5.7.2.1.4.2.5.3.1.2.1.8-.1 1.4z"/></svg>
              Contactar por WhatsApp
            </a>
            <a className="btn btn-ghost" href="#roi">Calcular mi ROI →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="foot-grid">
          <div>
            <div className="foot-brand">
              <div className="nav-logo-mark">
                <svg viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" strokeWidth="2"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="1" fill="var(--cyan)"/></svg>
              </div>
              <div style={{fontFamily: 'var(--display)', fontSize: 18, fontWeight: 700, color: 'var(--ink-0)'}}>
                Mi Activo <span style={{color: 'var(--cyan)'}}>360</span>
              </div>
            </div>
            <div className="foot-tag">
              La plataforma más completa para gestión de activos fijos, depreciación
              automática, mantenimientos y consumibles en Latinoamérica.
            </div>
          </div>
          <div>
            <div className="foot-col-t">Producto</div>
            <div className="foot-links">
              <a href="#modulos">Módulos</a>
              <a href="#depreciacion">Depreciación</a>
              <a href="#roles">Roles</a>
              <a href="#sistema">El Sistema</a>
            </div>
          </div>
          <div>
            <div className="foot-col-t">Recursos</div>
            <div className="foot-links">
              <a href="#roi">Calculadora ROI</a>
              <a href="#depreciacion">Lab depreciación</a>
              <a href="#qr">Demo QR</a>
              <a href="#comparador">Comparador</a>
            </div>
          </div>
          <div>
            <div className="foot-col-t">Contacto</div>
            <div className="foot-links">
              <a href="https://wa.me/573017287922">WhatsApp</a>
              <a href="#testimonios">Clientes</a>
              <a href="#por-que">Por qué elegirnos</a>
            </div>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 MI ACTIVO 360 · TODOS LOS DERECHOS RESERVADOS</span>
          <span>HECHO EN COLOMBIA 🇨🇴</span>
        </div>
      </div>
    </footer>
  );
}

window.QRScanner = QRScanner;
window.Features = Features;
window.FinalCTA = FinalCTA;
window.Footer = Footer;
