/* Hero — animated geometric operations diagram */

const useReveal = () => {
  React.useEffect(() => {
    // Defer to next frame so all sections have rendered
    const id = requestAnimationFrame(() => {
      const els = document.querySelectorAll(".reveal");
      const io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {
              e.target.classList.add("in");
              io.unobserve(e.target);
            }
          });
        },
        { threshold: 0.08, rootMargin: "0px 0px -40px 0px" }
      );
      els.forEach((el) => {
        // Force-reveal if already on screen at mount (above the fold)
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight && r.bottom > 0) {
          el.classList.add("in");
        } else {
          io.observe(el);
        }
      });
      window.__oqivaIO = io;
    });
    return () => {
      cancelAnimationFrame(id);
      if (window.__oqivaIO) window.__oqivaIO.disconnect();
    };
  }, []);
};

const t = (val, lang) => (typeof val === "string" ? val : (val?.[lang] ?? val?.en ?? ""));

/* Animated diagram: input channels (LINE, IG, web, email) → operations layer → outcomes */
const HeroDiagram = ({ lang }) => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((x) => (x + 1) % 4), 1800);
    return () => clearInterval(id);
  }, []);

  const channels = [
    { label: "LINE OA", x: 60, y: 90 },
    { label: "Instagram", x: 60, y: 170 },
    { label: "Email", x: 60, y: 250 },
    { label: "Webform", x: 60, y: 330 },
  ];
  const outcomes = [
    { label: { en: "Reply", th: "ตอบ" }, x: 720, y: 100 },
    { label: { en: "Booking", th: "จอง" }, x: 720, y: 170 },
    { label: { en: "Route", th: "ส่งต่อ" }, x: 720, y: 240 },
    { label: { en: "Insight", th: "ข้อมูล" }, x: 720, y: 310 },
  ];

  const corePath = (sx, sy) => {
    const cx = 400, cy = 210;
    return `M${sx + 18} ${sy} C ${sx + 100} ${sy}, ${cx - 120} ${cy}, ${cx - 60} ${cy}`;
  };
  const outPath = (ex, ey) => {
    const cx = 400, cy = 210;
    return `M${cx + 60} ${cy} C ${cx + 120} ${cy}, ${ex - 100} ${ey}, ${ex - 18} ${ey}`;
  };

  return (
    <div className="hero-diagram">
      <svg viewBox="0 0 800 420" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        <defs>
          <linearGradient id="lineFade" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="var(--ink-mute)" stopOpacity="0.25" />
            <stop offset="1" stopColor="var(--accent-deep)" stopOpacity="0.7" />
          </linearGradient>
          <radialGradient id="coreGlow" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0" stopColor="var(--accent)" stopOpacity="0.55" />
            <stop offset="1" stopColor="var(--accent)" stopOpacity="0" />
          </radialGradient>
          <pattern id="dotpat" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="1" fill="var(--line-strong)" />
          </pattern>
        </defs>

        {/* dotted backdrop */}
        <rect x="0" y="0" width="800" height="420" fill="url(#dotpat)" opacity="0.5" />

        {/* core glow */}
        <circle cx="400" cy="210" r="120" fill="url(#coreGlow)" />

        {/* core ring */}
        <circle cx="400" cy="210" r="62" fill="var(--bg)" stroke="var(--ink)" strokeWidth="1.25" />
        <circle cx="400" cy="210" r="46" fill="none" stroke="var(--accent-deep)" strokeWidth="1" strokeDasharray="2 4" opacity="0.7">
          <animateTransform attributeName="transform" type="rotate" from="0 400 210" to="360 400 210" dur="22s" repeatCount="indefinite" />
        </circle>
        <circle cx="400" cy="210" r="14" fill="var(--accent)" />
        <circle cx="400" cy="210" r="6" fill="var(--bg)" />

        {/* channel nodes */}
        {channels.map((c, i) => (
          <g key={c.label}>
            <rect
              x={c.x - 50}
              y={c.y - 16}
              width="100"
              height="32"
              rx="16"
              fill="var(--bg)"
              stroke={tick === i ? "var(--accent-deep)" : "var(--line-strong)"}
              strokeWidth={tick === i ? "1.4" : "1"}
              style={{ transition: "stroke 0.4s, stroke-width 0.4s" }}
            />
            <text
              x={c.x}
              y={c.y + 4}
              textAnchor="middle"
              fontFamily="var(--font-mono)"
              fontSize="11"
              fill="var(--ink-2)"
              letterSpacing="0.04em"
            >
              {c.label}
            </text>
            {/* path from channel to core */}
            <path
              d={corePath(c.x + 50, c.y)}
              fill="none"
              stroke="url(#lineFade)"
              strokeWidth={tick === i ? "1.5" : "0.8"}
              opacity={tick === i ? 1 : 0.45}
              style={{ transition: "all 0.4s" }}
            />
            {/* moving dot */}
            {tick === i && (
              <circle r="3" fill="var(--accent-deep)">
                <animateMotion dur="1.4s" repeatCount="1" path={corePath(c.x + 50, c.y)} />
              </circle>
            )}
          </g>
        ))}

        {/* outcome nodes */}
        {outcomes.map((o, i) => {
          const isActive = tick === i;
          return (
            <g key={"out-" + i}>
              <path
                d={outPath(o.x, o.y)}
                fill="none"
                stroke="url(#lineFade)"
                strokeWidth={isActive ? "1.5" : "0.8"}
                opacity={isActive ? 1 : 0.45}
                style={{ transition: "all 0.4s" }}
              />
              {isActive && (
                <circle r="3" fill="var(--accent-deep)">
                  <animateMotion dur="1.4s" begin="0.4s" repeatCount="1" path={outPath(o.x, o.y)} />
                </circle>
              )}
              <rect
                x={o.x - 50}
                y={o.y - 16}
                width="100"
                height="32"
                rx="16"
                fill={isActive ? "var(--accent)" : "var(--bg)"}
                stroke={isActive ? "var(--accent-deep)" : "var(--line-strong)"}
                strokeWidth="1"
                style={{ transition: "all 0.4s" }}
              />
              <text
                x={o.x}
                y={o.y + 4}
                textAnchor="middle"
                fontFamily="var(--font-mono)"
                fontSize="11"
                fill={isActive ? "#0E1208" : "var(--ink-2)"}
                letterSpacing="0.04em"
                style={{ transition: "all 0.4s" }}
              >
                {t(o.label, lang)}
              </text>
            </g>
          );
        })}

        {/* labels above */}
        <text x="60" y="58" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-mute)" letterSpacing="0.1em">
          {(lang === "th" ? "ช่องทาง" : "CHANNELS").toUpperCase()}
        </text>
        <text x="400" y="58" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-mute)" letterSpacing="0.1em">
          {(lang === "th" ? "ชั้นปฏิบัติการ AI" : "AI OPERATIONS LAYER").toUpperCase()}
        </text>
        <text x="720" y="58" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-mute)" letterSpacing="0.1em">
          {(lang === "th" ? "ผลลัพธ์" : "OUTCOMES").toUpperCase()}
        </text>

        {/* meta tag in core */}
        <text x="400" y="295" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-mute)" letterSpacing="0.1em">
          FlowAIOS · Jongtoh
        </text>
      </svg>
    </div>
  );
};

const Hero = ({ lang, c }) => {
  return (
    <section className="hero" id="top">
      <div className="hero-bg">
        <div className="hero-grid"></div>
      </div>
      <div className="shell hero-shell">
        <div className="hero-meta">
          <span className="pill">
            <span className="dot"></span>
            {t(c.hero.statusLeft, lang)}
          </span>
          <span className="mono-tag hero-coords">14.5995° N · 100.5018° E</span>
        </div>

        <h1 className="display-xl hero-title reveal">
          {t(c.hero.title, lang)}
        </h1>

        <div className="hero-body reveal" style={{ "--reveal-delay": "120ms" }}>
          <p className="body-lg">{t(c.hero.body, lang)}</p>
          <p className="body-md hero-body2">{t(c.hero.body2, lang)}</p>

          <div className="hero-ctas">
            <a href="#products" className="btn btn-primary">
              {t(c.hero.cta1, lang)}
              <ArrowRight />
            </a>
            <a href="#partners" className="btn btn-ghost">
              {t(c.hero.cta2, lang)}
              <ArrowUpRight />
            </a>
          </div>
        </div>

        <div className="hero-products mono-tag reveal" style={{ "--reveal-delay": "240ms" }}>
          <span>{t(c.hero.firstProducts, lang)}</span>
          <span className="hero-prod-tag">Jongtoh</span>
          <span className="sep">·</span>
          <span className="hero-prod-tag">FlowAIOS</span>
        </div>

        <div className="hero-diagram-wrap reveal" style={{ "--reveal-delay": "320ms" }}>
          <HeroDiagram lang={lang} />
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Hero, HeroDiagram, useReveal, t });
