/* global React */
const t = window.t || ((s) => s);
// Shared reveal controller (IntersectionObserver is unreliable in some
// preview frames, so we use a rAF-throttled scroll/rect check instead).
(function () {
  if (window.__cueWatch) return;
  const watchers = [];
  let scheduled = false;
  function check() {
    scheduled = false;
    const vh = window.innerHeight || document.documentElement.clientHeight;
    for (let i = watchers.length - 1; i >= 0; i--) {
      const w = watchers[i];
      if (!w.el || !w.el.isConnected) {watchers.splice(i, 1);continue;}
      const r = w.el.getBoundingClientRect();
      if (r.top < vh * w.ratio && r.bottom > 0) {
        w.cb();
        if (w.once) watchers.splice(i, 1);
      }
    }
  }
  function onScroll() {
    if (!scheduled) {scheduled = true;requestAnimationFrame(check);}
    setTimeout(check, 60);
  }
  window.addEventListener("scroll", onScroll, { passive: true });
  window.addEventListener("resize", onScroll);
  window.__cueWatch = function (el, cb, ratio, once) {
    watchers.push({ el, cb, ratio: ratio == null ? 0.9 : ratio, once: once !== false });
    requestAnimationFrame(check);
    setTimeout(check, 60);
  };
})();

// "How Cue works" — horizontal pipeline diagram.
// Sources (left) flow through the Cue Index core (center); the Tuner shapes it
// from above; the Index fans out to the ways you use Cue (right).
const DG = function () {
  const { useRef, useEffect, useState } = React;

  // ---- Design-space geometry (stage is 1300 x 720) ----
  const zones = [
  { x: 190, label: "Sources" },
  { x: 650, label: "Foundation" },
  { x: 1095, label: "Ways to use it" }];

  const sources = [
  { ico: "folder_open", title: "Project files", sub: "Specs · contracts · RFIs", top: 225 },
  { ico: "dns", title: "Other sources", sub: "ERP · CRM · external", top: 385 },
  { ico: "mail", title: "Silos", sub: "Email · PDFs · sheets", top: 545 }];

  const outputs = [
  { ico: "smart_toy", title: "Cue Agent", sub: "AEC & real-estate specialist", top: 200, badge: "Soon" },
  { ico: "dashboard", title: "Cue Studio", sub: "Ready-made & custom apps", top: 375 },
  { ico: "bolt", title: "Connect your AI", sub: "Claude · ChatGPT · Gemini", top: 550 }];

  // Connectors (verbatim from the source pipeline geometry).
  const links = [
  { id: "s1", d: "M320,290 C420,290 410,400 525,400" },
  { id: "s2", d: "M320,450 C420,450 440,450 525,450" },
  { id: "s3", d: "M320,610 C420,610 410,500 525,500" },
  { id: "tn", d: "M650,236 L650,325" },
  { id: "u1", d: "M775,400 C900,400 880,275 960,275" },
  { id: "u2", d: "M775,450 C900,450 880,450 960,450" },
  { id: "u3", d: "M775,500 C900,500 880,625 960,625" }];

  const flows = [
  { d: "M320,290 C420,290 410,400 525,400", dur: 2.8, begin: 0, halo: "rgba(40,89,225,.16)", dot: "#2859e1" },
  { d: "M320,450 C420,450 440,450 525,450", dur: 2.6, begin: -1.2, halo: "rgba(0,202,204,.18)", dot: "#00cacc" },
  { d: "M320,610 C420,610 410,500 525,500", dur: 3.0, begin: -0.6, halo: "rgba(40,89,225,.16)", dot: "#2859e1" },
  { d: "M650,236 L650,325", dur: 2.2, begin: -0.3, halo: "rgba(40,89,225,.16)", dot: "#2859e1", r: 5.5, rd: 2.6 },
  { d: "M775,400 C900,400 880,275 960,275", dur: 2.7, begin: -0.9, halo: "rgba(40,89,225,.16)", dot: "#2859e1" },
  { d: "M775,450 C900,450 880,450 960,450", dur: 2.5, begin: -1.5, halo: "rgba(226,245,82,.55)", dot: "#2859e1" },
  { d: "M775,500 C900,500 880,625 960,625", dur: 2.9, begin: -0.4, halo: "rgba(40,89,225,.16)", dot: "#2859e1" }];

  const pins = [
  [525, 400], [525, 450], [525, 500],
  [775, 400], [775, 450], [775, 500], [650, 325]];

  function Diagram() {
    const wrapRef = useRef(null);
    const scalerRef = useRef(null);
    const stageRef = useRef(null);
    const [run, setRun] = useState(false);

    // fit-to-width scaling
    useEffect(() => {
      const fit = () => {
        const wrap = wrapRef.current, scaler = scalerRef.current;
        if (!wrap || !scaler) return;
        const w = wrap.clientWidth;
        const scale = Math.min(1, w / 1300);
        scaler.style.transformOrigin = "top left";
        scaler.style.transform = `scale(${scale})`;
        scaler.style.width = "1300px";
        scaler.style.marginLeft = `${Math.max(0, (w - 1300 * scale) / 2)}px`;
        wrap.style.height = `${720 * scale}px`;
      };
      fit();
      window.addEventListener("resize", fit);
      const ro = new ResizeObserver(fit);
      if (wrapRef.current) ro.observe(wrapRef.current);
      return () => {window.removeEventListener("resize", fit);ro.disconnect();};
    }, []);

    // run on scroll into view
    useEffect(() => {
      if (stageRef.current) window.__cueWatch(stageRef.current, () => setRun(true), 0.82);
    }, []);

    // lock the final state shortly after intro so it renders even if CSS
    // transitions are throttled (tooling/background frames)
    useEffect(() => {
      if (!run) return;
      const t = setTimeout(() => {if (stageRef.current) stageRef.current.classList.add("run-final");}, 2200);
      return () => clearTimeout(t);
    }, [run]);

    return (
      <div>
        <div className="pl-wrap" ref={wrapRef}>
          <div className="pl-scaler" ref={scalerRef}>
            <div className={`pl-stage ${run ? "run" : ""}`} ref={stageRef}>
              <svg className="pl-links" viewBox="0 0 1300 720" preserveAspectRatio="none">
                {links.map((l, i) =>
                <path key={l.id} className="pl-link" d={l.d} pathLength="1" style={{ transitionDelay: `${0.2 + i * 0.06}s` }} />
                )}
                {flows.map((f, i) =>
                <g key={`f${i}`} className="pl-flow">
                    <circle r={f.r || 6} fill={f.halo} />
                    <circle r={f.rd || 3} fill={f.dot} />
                    <animateMotion dur={`${f.dur}s`} repeatCount="indefinite" begin={`${f.begin}s`}>
                      <mpath href={`#pl-path-${i}`} />
                    </animateMotion>
                  </g>
                )}
                {/* hidden path refs for the flow dots */}
                {flows.map((f, i) => <path key={`p${i}`} id={`pl-path-${i}`} d={f.d} fill="none" stroke="none" />)}
                {pins.map((p, i) => <circle key={`pin${i}`} className="pl-pin" cx={p[0]} cy={p[1]} r="3.2" />)}
              </svg>

              {/* zone labels */}
              {zones.map((z, i) =>
              <div key={z.label} className="pl-zone" style={{ left: z.x, top: 104, transitionDelay: `${i * 0.08}s` }}>{t(z.label)}</div>
              )}

              {/* sources */}
              {sources.map((s, i) =>
              <div key={s.title} className="pl-node pl-src" style={{ left: 60, top: s.top, width: 260, transitionDelay: `${0.15 + i * 0.09}s` }}>
                  <div className="pl-tile"><span className="cue-icon">{s.ico}</span></div>
                  <div className="pl-ntext"><div className="pl-ntitle">{t(s.title)}</div><div className="pl-nsub">{t(s.sub)}</div></div>
                </div>
              )}

              {/* tuner */}
              <div className="pl-tuner" style={{ left: 545, top: 144, width: 210, transitionDelay: ".33s" }}>
                <div className="pl-tile"><span className="cue-icon">tune</span></div>
                <div className="pl-ntext"><div className="pl-ntitle">{t("Cue Tuner")}</div></div>
                <span className="pl-tchip">{t("Optional")}</span>
              </div>

              {/* core */}
              <div className="pl-core" style={{ left: 525, top: 325, width: 250, height: 250, transitionDelay: ".45s" }}>
                <div className="pl-tile"><span className="cue-icon">hub</span></div>
                <div className="pl-ctitle">{t("Cue Index")}</div>
                <div className="pl-csub">{t("The connected foundation under everything")}</div>
              </div>
              <div className="pl-caption" style={{ left: 650, top: 595, transitionDelay: ".9s" }}>{t("Read & connected — no tagging, no folders")}</div>

              {/* outputs */}
              {outputs.map((o, i) =>
              <div key={o.title} className="pl-node pl-out" style={{ left: 960, top: o.top, width: 270, transitionDelay: `${0.6 + i * 0.1}s` }}>
                  <div className="pl-tile">{o.title === "Cue Agent" ? <window.CueAgentIcon size={26} /> : <span className="cue-icon">{o.ico}</span>}</div>
                  <div className="pl-ntext"><div className="pl-ntitle">{t(o.title)}</div><div className="pl-nsub">{t(o.sub)}</div></div>
                  {o.badge ? <span className="pl-badge">{t(o.badge)}</span> : null}
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="dg-legend">
          <div className="dg-legend__item">
            <span className="dg-legend__num">01</span>
            <div><p className="dg-legend__t">{t("Connect your documents")}</p><p className="dg-legend__d">{t("Point Cue at your project files, silos and other systems — in whatever shape they're in.")}</p></div>
          </div>
          <div className="dg-legend__item">
            <span className="dg-legend__num">02</span>
            <div><p className="dg-legend__t">{t("Cue builds the Index")}</p><p className="dg-legend__d">{t("Everything is read and connected into one searchable foundation. Shape it with the Tuner if you need to.")}</p></div>
          </div>
          <div className="dg-legend__item">
            <span className="dg-legend__num">03</span>
            <div><p className="dg-legend__t">{t("Put it to work")}</p><p className="dg-legend__d">{t("Connect the AI you already use, build on it with Cue Studio, or bring in the Cue Agent.")}</p></div>
          </div>
        </div>
      </div>);

  }

  return { Diagram };
}();

window.CueDiagram = DG.Diagram;
