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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "Every logo. Every frame. Every mention.",
  "showAmbient": true
}/*EDITMODE-END*/;

// ============================================================================
// LOGO
// ============================================================================
const Wordmark = ({ size = 22 }) => (
  <img src="assets/sponsoriq-logo.png" alt="SponsorIQ" style={{ height: size * 1.2, width: "auto", display: "block" }} />
);

// ============================================================================
// AMBIENT LIVE BACKGROUND — animated mesh of detection boxes scanning across
// ============================================================================
function AmbientBackground() {
  const ref = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    function resize() {
      canvas.width = window.innerWidth * dpr;
      canvas.height = window.innerHeight * dpr;
      canvas.style.width = window.innerWidth + "px";
      canvas.style.height = window.innerHeight + "px";
      ctx.scale(dpr, dpr);
    }
    resize();
    window.addEventListener("resize", resize);

    const N = 18;
    const parts = Array.from({ length: N }, () => ({
      x: Math.random(), y: Math.random(),
      vx: (Math.random() - 0.5) * 0.00012,
      vy: (Math.random() - 0.5) * 0.00012,
      w: 60 + Math.random() * 140,
      h: 30 + Math.random() * 60,
      phase: Math.random() * Math.PI * 2,
      speed: 0.3 + Math.random() * 0.7,
    }));

    function draw(t) {
      const W = window.innerWidth, H = window.innerHeight;
      ctx.clearRect(0, 0, W, H);

      // mesh dots
      const grid = 80;
      ctx.fillStyle = "rgba(167,139,250,0.05)";
      for (let x = 0; x < W; x += grid) {
        for (let y = 0; y < H; y += grid) {
          ctx.fillRect(x, y, 1, 1);
        }
      }

      // scanning sweep
      const sweep = ((t * 0.00008) % 1) * (W + 200) - 100;
      const grad = ctx.createLinearGradient(sweep - 200, 0, sweep + 200, 0);
      grad.addColorStop(0, "rgba(167,139,250,0)");
      grad.addColorStop(0.5, "rgba(167,139,250,0.04)");
      grad.addColorStop(1, "rgba(167,139,250,0)");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, W, H);

      // detection rectangles
      parts.forEach((p) => {
        p.x += p.vx;
        p.y += p.vy;
        if (p.x < -0.1 || p.x > 1.1) p.vx *= -1;
        if (p.y < -0.1 || p.y > 1.1) p.vy *= -1;
        const breath = (Math.sin(t * 0.001 * p.speed + p.phase) + 1) / 2;
        const op = 0.05 + breath * 0.14;
        const x = p.x * W, y = p.y * H;

        ctx.strokeStyle = `rgba(167,139,250,${op})`;
        ctx.lineWidth = 1;
        ctx.setLineDash([4, 4]);
        ctx.strokeRect(x, y, p.w, p.h);
        ctx.setLineDash([]);

        ctx.strokeStyle = `rgba(167,139,250,${op * 1.5})`;
        ctx.lineWidth = 1.5;
        const c = 7;
        ctx.beginPath();
        ctx.moveTo(x, y + c); ctx.lineTo(x, y); ctx.lineTo(x + c, y);
        ctx.moveTo(x + p.w - c, y); ctx.lineTo(x + p.w, y); ctx.lineTo(x + p.w, y + c);
        ctx.moveTo(x, y + p.h - c); ctx.lineTo(x, y + p.h); ctx.lineTo(x + c, y + p.h);
        ctx.moveTo(x + p.w - c, y + p.h); ctx.lineTo(x + p.w, y + p.h); ctx.lineTo(x + p.w, y + p.h - c);
        ctx.stroke();
      });

      raf = requestAnimationFrame(draw);
    }
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, []);
  return <canvas ref={ref} className="ambient" aria-hidden="true" />;
}

// ============================================================================
// NAV
// ============================================================================
function Nav() {
  return (
    <nav className="nav">
      <div className="nav__inner">
        <a href="#"><Wordmark size={20} /></a>
        <div className="nav__links">
          <a href="#demo">The benchmark</a>
          <a href="#beyond">Beyond broadcast</a>
          <a href="#how">How it works</a>
          <a href="#segments">For you</a>
          <a href="#documents">Reports</a>
          <a href="https://docs.sponsoriq.io">Docs ↗</a>
        </div>
        <div className="nav__cta">
          <a href="mailto:tim@sponsoriq.io" className="btn btn--primary">Request demo</a>
        </div>
      </div>
    </nav>
  );
}

// ============================================================================
// HERO — single unified section: copy + comparison demo + verdict table
// ============================================================================
const SIQ_DETECTIONS = [
  { brand: "Oppo",  asset: "Digital Overlay", t: 9.4, c: 99.8 },
  { brand: "Oppo",  asset: "Pitch Ring",      t: 3.2, c: 95.0 },
  { brand: "Puma",  asset: "Gloves",          t: 2.4, c: 92.0 },
  { brand: "Oppo",  asset: "Wicket",          t: 2.0, c: 90.0 },
  { brand: "Oppo",  asset: "Jersey Front",    t: 1.8, c: 98.0 },
  { brand: "Oppo",  asset: "Jersey Sleeve",   t: 0.8, c: 92.0 },
];
const HIVE_DETECTIONS = [
  { brand: "Oppo",       t: 8.0, c: 87, flag: null },
  { brand: "Puma",       t: 1.0, c: 78, flag: null },
  { brand: "Nike",       t: 1.0, c: 47, flag: "HALLUCINATED" },
  { brand: "On-Running", t: 1.0, c: 0,  flag: "HALLUCINATED" },
];

function Hero({ headline }) {
  const videoRef = useRef(null);
  const [time, setTime] = useState(0);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const onTime = () => setTime(v.currentTime);
    v.addEventListener("timeupdate", onTime);
    return () => v.removeEventListener("timeupdate", onTime);
  }, []);

  const togglePlay = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) { v.play(); setPaused(false); } else { v.pause(); setPaused(true); }
  };

  // Split headline into words to stylize the last 2 words with gradient
  const words = headline.trim().split(" ");
  const lead = words.slice(0, -2).join(" ");
  const tail = words.slice(-2).join(" ");

  return (
    <section className="hero" id="demo">
      <div className="hero__top">
        <div className="eyebrow">
          <span className="eyebrow__dot" />
          COMPUTER VISION × VLM × SOCIAL LISTENING
        </div>
        <h1 className="hero__h1">
          {lead} <span className="hero__h1-tail">{tail}</span>
        </h1>
        <p className="hero__sub">
          SponsorIQ measures sponsorship across broadcast, digital, and social — pairing a vision pipeline that detects
          every on-screen surface with a listening engine that tracks every conversation. Built on cutting-edge computer
          vision and vision-language models. Trusted by Two Circles.
        </p>
        <div className="hero__cta-row">
          <a href="mailto:tim@sponsoriq.io" className="btn btn--primary btn--lg">
            Request demo <span className="btn__arrow">→</span>
          </a>
          <a href="#beyond" className="btn btn--ghost btn--lg">See it work</a>
        </div>
      </div>

      <div className="hero__demo">
        <div className="hero__demo-caption">
          <span className="eyebrow"><span className="eyebrow__dot" /> THE BENCHMARK · 9-SECOND SEGMENT</span>
          <h3 className="hero__demo-h3">Same footage. Two systems. <em>Wildly different ledgers.</em></h3>
        </div>

        <div className="dvr">
          <div className="dvr__chrome">
            <span className="dvr__rec"><span className="dvr__rec-dot" /> LIVE COMPARISON</span>
            <span className="dvr__chrome-label">SPONSORIQ vs. INDUSTRY LEADER</span>
            <span className="dvr__chrome-time">{formatTC(time)}</span>
          </div>

          <div className="dvr__frame">
            <video ref={videoRef} src="assets/comparison.mp4" autoPlay loop muted playsInline className="dvr__video" />
            <div className="dvr__vs-line" />
            <div className="dvr__side-tag dvr__side-tag--l">
              <span className="dvr__side-dot" /> SPONSORIQ
            </div>
            <div className="dvr__side-tag dvr__side-tag--r">
              INDUSTRY LEADER <span className="dvr__side-dot dvr__side-dot--red" />
            </div>
          </div>

          <div className="dvr__scrubber">
            <button className="dvr__btn" onClick={togglePlay} aria-label="play/pause">
              {paused ? "▶" : "❚❚"}
            </button>
            <div className="dvr__track">
              <div className="dvr__progress" style={{ width: `${Math.min(100, (time / 9) * 100)}%` }} />
            </div>
            <span className="dvr__tc">9-second segment · live</span>
          </div>
        </div>

        <div className="vs-grid">
          <div className="vs-card vs-card--us">
            <div className="vs-card__head">
              <span className="vs-card__title"><span className="vs-card__check">✓</span> SPONSORIQ DETECTIONS</span>
              <span className="vs-card__pill vs-card__pill--ok">6 ASSETS · 0 ERRORS</span>
            </div>
            <div className="vs-table">
              <div className="vs-table__head">
                <span>BRAND</span><span>ASSET</span><span>EXPOSURE</span><span>CLARITY</span>
              </div>
              {SIQ_DETECTIONS.map((d, i) => (
                <div key={i} className="vs-table__row">
                  <span className="vs-table__brand">{d.brand}</span>
                  <span className="vs-table__asset">{d.asset}</span>
                  <span className="vs-table__t">{d.t.toFixed(1)}s</span>
                  <span className="vs-table__c vs-table__c--ok">{d.c.toFixed(1)}%</span>
                </div>
              ))}
            </div>
          </div>

          <div className="vs-card vs-card--them">
            <div className="vs-card__head">
              <span className="vs-card__title"><span className="vs-card__warn">⚠</span> GENERIC DETECTIONS</span>
              <span className="vs-card__pill vs-card__pill--bad">2 HALLUCINATIONS</span>
            </div>
            <div className="vs-table">
              <div className="vs-table__head">
                <span>BRAND</span><span></span><span>EXPOSURE</span><span>CLARITY</span>
              </div>
              {HIVE_DETECTIONS.map((d, i) => (
                <div key={i} className="vs-table__row">
                  <span className="vs-table__brand">
                    {d.brand}
                  </span>
                  <span className="vs-table__asset">
                    {d.flag && <span className="vs-table__flag">{d.flag}</span>}
                  </span>
                  <span className="vs-table__t">{d.t.toFixed(1)}s</span>
                  <span className={"vs-table__c vs-table__c--bad" + (d.c < 50 ? " vs-table__c--worst" : "")}>{d.c}%</span>
                </div>
              ))}
            </div>
            <div className="vs-card__missing">
              <strong>Missed:</strong> Puma gloves, jersey front, jersey sleeve, pitch ring — five revenue-bearing exposures generic systems can't see.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function formatTC(t) {
  const s = Math.floor(t);
  const ms = Math.floor((t - s) * 100);
  return `00:${String(s).padStart(2, "0")}.${String(ms).padStart(2, "0")}`;
}

window.AmbientBackground = AmbientBackground;
window.Hero = Hero;
window.Nav = Nav;
window.Wordmark = Wordmark;
window.TWEAK_DEFAULTS = TWEAK_DEFAULTS;
