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

/* Brand icon paths — keyed by the same `kind` strings used in
   PLATFORM_GROUPS below and in the Bento "execution moves" feed.
   Real brand SVGs live in design-system/assets/brand-icons/. */
const BRAND_ICON_PATHS = {
  // AI providers
  chatgpt: "/landing/design-system/assets/brand-icons/ai-providers/chatgpt.svg",
  claude: "/landing/design-system/assets/brand-icons/ai-providers/claude.svg",
  gemini: "/landing/design-system/assets/brand-icons/ai-providers/gemini.svg",
  perplexity: "/landing/design-system/assets/brand-icons/ai-providers/perplexity.svg",
  google: "/landing/design-system/assets/brand-icons/ai-providers/google-ai.svg",
  bing: "/landing/design-system/assets/brand-icons/ai-providers/bing.svg",
  // Social
  x: "/landing/design-system/assets/brand-icons/social/x.svg",
  instagram: "/landing/design-system/assets/brand-icons/social/instagram.svg",
  youtube: "/landing/design-system/assets/brand-icons/social/youtube.svg",
  tiktok: "/landing/design-system/assets/brand-icons/social/tiktok.svg",
  linkedin: "/landing/design-system/assets/brand-icons/social/linkedin.svg",
  facebook: "/landing/design-system/assets/brand-icons/social/facebook.svg",
  reddit: "/landing/design-system/assets/brand-icons/social/reddit.svg",
  pinterest: "/landing/design-system/assets/brand-icons/social/pinterest.svg",
  threads: "/landing/design-system/assets/brand-icons/social/threads.svg",
  bluesky: "/landing/design-system/assets/brand-icons/social/bluesky.svg",
  mastodon: "/landing/design-system/assets/brand-icons/social/mastodon.svg",
  // Publishing
  wordpress: "/landing/design-system/assets/brand-icons/publishing/wordpress.svg",
  webflow: "/landing/design-system/assets/brand-icons/publishing/webflow.svg",
  medium: "/landing/design-system/assets/brand-icons/publishing/medium.svg",
  // Demo competitors (used inside HowItWorks tile mocks)
  stripe: "/landing/design-system/assets/brand-icons/competitors-demo/stripe.svg",
  square: "/landing/design-system/assets/brand-icons/competitors-demo/square.svg",
  adyen: "/landing/design-system/assets/brand-icons/competitors-demo/adyen.svg",
};

const PlatformLogo = ({ kind, size = 28, alt }) => {
  const src = BRAND_ICON_PATHS[kind];
  if (!src) return null;
  return (
    <img
      className="brand-icon"
      src={src}
      alt={alt || kind}
      width={size}
      height={size}
      loading="lazy"
      decoding="async"
    />
  );
};

const PLATFORM_GROUPS = {
  "AI Models": [
    { id: "chatgpt", name: "ChatGPT", caption: "OpenAI" },
    { id: "claude", name: "Claude", caption: "Anthropic" },
    { id: "gemini", name: "Gemini", caption: "Google" },
    { id: "perplexity", name: "Perplexity", caption: "Perplexity AI" },
    { id: "google", name: "Google AI", caption: "AI Overviews" },
  ],
  Social: [
    { id: "x", name: "X", caption: "Twitter" },
    { id: "instagram", name: "Instagram", caption: "Meta" },
    { id: "youtube", name: "YouTube", caption: "Channels" },
    { id: "tiktok", name: "TikTok", caption: "Videos" },
    { id: "wordpress", name: "WordPress", caption: "Blogs" },
  ],
};

function Globe() {
  const ref = useRef(null);
  useEffect(() => {
    if (!window.THREE || !ref.current) return;
    const THREE = window.THREE;
    const w = ref.current.clientWidth,
      h = ref.current.clientHeight;
    const scene = new THREE.Scene();
    const cam = new THREE.PerspectiveCamera(45, w / h, 0.1, 100);
    cam.position.z = 3.0;
    const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(w, h);
    ref.current.appendChild(renderer.domElement);

    // wireframe sphere
    const geo = new THREE.SphereGeometry(1.2, 32, 24);
    const wire = new THREE.LineSegments(
      new THREE.EdgesGeometry(geo),
      new THREE.LineBasicMaterial({
        color: 0x68b4e6,
        transparent: true,
        opacity: 0.5,
      }),
    );
    scene.add(wire);

    // dot points layer
    const dotGeo = new THREE.SphereGeometry(1.22, 36, 28);
    const dotMat = new THREE.PointsMaterial({
      color: 0xfdda2f,
      size: 0.025,
      transparent: true,
      opacity: 0.78,
    });
    const points = new THREE.Points(dotGeo, dotMat);
    scene.add(points);

    let raf;
    const tick = () => {
      wire.rotation.y += 0.0035;
      points.rotation.y += 0.0035;
      wire.rotation.x = 0.2;
      points.rotation.x = 0.2;
      renderer.render(scene, cam);
      raf = requestAnimationFrame(tick);
    };
    tick();
    const onResize = () => {
      if (!ref.current) return;
      const w = ref.current.clientWidth,
        h = ref.current.clientHeight;
      cam.aspect = w / h;
      cam.updateProjectionMatrix();
      renderer.setSize(w, h);
    };
    window.addEventListener("resize", onResize);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", onResize);
      renderer.dispose();
      if (ref.current) ref.current.innerHTML = "";
    };
  }, []);
  return <div className="globe" ref={ref}></div>;
}

function Platforms({ t: tt }) {
  const [tab, setTab] = useState("AI Models");
  const [glow, setGlow] = useState(0);
  const tiles = PLATFORM_GROUPS[tab];
  useEffect(() => {
    const t = setInterval(() => setGlow((g) => (g + 1) % 12), 600);
    return () => clearInterval(t);
  }, []);
  return (
    <section className="platforms" id="platforms">
      <Reveal className="platforms-card">
        <div className="platforms-left">
          <span
            className="eyebrow frost"
            style={{
              background: "rgba(255,255,255,0.10)",
              borderColor: "rgba(255,255,255,0.18)",
              color: "rgba(255,255,255,0.78)",
            }}
          >
            {tt.platforms.eyebrow}
          </span>
          <TwoTone
            parts={[
              { tone: "navy", text: tt.platforms.ha + " " },
              { tone: "accent", text: tt.platforms.hbAccent },
            ]}
          />
          <div className="platforms-tabs">
            {Object.keys(PLATFORM_GROUPS).map((t) => (
              <button key={t} className={tab === t ? "is-active" : ""} onClick={() => setTab(t)}>
                {t}
              </button>
            ))}
          </div>
          <div className="platforms-foot">{tt.platforms.foot}</div>
        </div>
        <div className="platforms-right">
          <Globe />
          <div className={`platform-grid grid-${tab.replace(/\s/g, "")}`}>
            {tiles.map((t, i) => (
              <div
                key={`${tab}-${i}`}
                className={`platform-tile ${i === glow % tiles.length ? "glow" : ""}`}
              >
                <span className="logo">
                  <PlatformLogo kind={t.id} />
                </span>
                <span className="name">{t.name}</span>
                <span className="caption">{t.caption}</span>
              </div>
            ))}
          </div>
        </div>
      </Reveal>
    </section>
  );
}

function Bento({ ctaLabel, t: tt, urls, onDemoClick }) {
  const c = tt.bento.cards;
  const [b2, b2ref] = useCountUp(58.4, {
    duration: 1500,
    decimals: 1,
    start: 32,
  });
  const [b3, b3ref] = useCountUp(241, { duration: 1400, decimals: 0 });
  const [b5, b5ref] = useCountUp(94, { duration: 1700, decimals: 0 });
  const [tog, setTog] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setTog(true), 1800);
    const loop = setInterval(() => setTog((v) => !v), 4000);
    return () => {
      clearTimeout(t);
      clearInterval(loop);
    };
  }, []);

  return (
    <section className="bento-section" id="features">
      <div className="wrap">
        <Reveal className="bento-head">
          <div className="bento-head-left">
            <span className="eyebrow">
              <span className="dot"></span>
              {tt.bento.eyebrow}
            </span>
            <TwoTone
              parts={[
                { tone: "navy", text: tt.bento.ha + " " },
                { tone: "accent", text: tt.bento.hbAccent },
              ]}
            />
            <p className="bento-sub">{tt.bento.sub}</p>
          </div>
          <button type="button" className="btn btn-primary" onClick={onDemoClick}>
            <LogoBadge size={36} />
            {ctaLabel}
          </button>
        </Reveal>
        <div className="bento-grid">
          <div className="bcard softblue">
            <span className="bcard-num">01</span>
            <h3 className="bcard-title">{c.c1.title}</h3>
            <p className="bcard-cap">{c.c1.cap}</p>
            <div className="bcard-art">
              <div className={`toggle-pill ${tog ? "done" : ""}`}>
                {tog ? (
                  <>
                    <span className="check">✓</span>
                    {c.c1.live}
                  </>
                ) : (
                  <>
                    <span className="spinner"></span>
                    {c.c1.connecting}
                  </>
                )}
              </div>
            </div>
          </div>
          <div className="bcard blue" ref={b2ref}>
            <span className="bcard-num">02</span>
            <h3 className="bcard-title">{c.c2.title}</h3>
            <p className="bcard-cap">{c.c2.cap}</p>
            <div className="bcard-art">
              <div className="b2-v">
                {b2}
                <span className="b2-pct">%</span>
              </div>
              <div className="b2-d">{c.c2.delta}</div>
              <svg viewBox="0 0 280 60" style={{ width: "100%", height: 50, marginTop: 10 }}>
                <path
                  d="M0 48 C30 44, 50 40, 80 32 S130 22, 160 24 S220 14, 280 8"
                  fill="none"
                  stroke="#fff"
                  strokeWidth="2"
                  strokeLinecap="round"
                />
                <circle cx="280" cy="8" r="4" fill="#fff" />
              </svg>
            </div>
          </div>
          <div className="bcard frost" ref={b3ref}>
            <span className="bcard-num">03</span>
            <h3 className="bcard-title">{c.c3.title}</h3>
            <p className="bcard-cap">{c.c3.cap}</p>
            <div className="bcard-art">
              <div className="b3-l">{c.c3.label}</div>
              <div className="b3-v">{b3}</div>
              <div className="b3-meta">{c.c3.meta}</div>
              <div className="b3-bar">
                <div></div>
              </div>
            </div>
          </div>
          <div className="bcard wide58">
            <span className="bcard-num">04</span>
            <h3 className="bcard-title">{c.c4.title}</h3>
            <p className="bcard-cap">{c.c4.cap}</p>
            <div className="bcard-art b4-feed">
              {c.c4.rows.map((r, i) => (
                <div key={i} className="b4-row">
                  <div className="l">
                    <span className="logo-chip">
                      <PlatformLogo kind={r.id} />
                    </span>
                    {r.n}
                  </div>
                  <span className="v">{r.v}</span>
                </div>
              ))}
              <div className="b4-more">{c.c4.more}</div>
            </div>
          </div>
          <div className="bcard wide42 shadow" ref={b5ref}>
            <span className="bcard-num">05</span>
            <h3 className="bcard-title">{c.c5.title}</h3>
            <p className="bcard-cap">{c.c5.cap}</p>
            <div
              className="bcard-art"
              style={{
                position: "relative",
                display: "flex",
                justifyContent: "center",
              }}
            >
              <div className="b5-spot"></div>
              <div className="b5-tag">
                <div className="l">{c.c5.label}</div>
                <div className="v">
                  {Math.round(b5)}
                  <span className="b5-pct">%</span>
                </div>
                <div className="d">{c.c5.delta}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Platforms, Bento, PlatformLogo });
