// zdr-flow.jsx — Framer Motion animation for the Zero Data Retention tab.
// After Effects-style product animation: focused UI fragments transitioning
// through five scenes. Sharp 3-6px corners, no decorative dots, no AI slop.
// Loops infinitely; respects prefers-reduced-motion. Exports window.ZdrFlow.

(function () {
  const M = window.Motion || {};
  const motion = M.motion || null;
  const AnimatePresence = M.AnimatePresence || null;
  const useZdrT = () => {
    const i18n = (typeof window !== "undefined" && window.Wisbid && window.Wisbid.i18n) || null;
    const [, force] = useState(0);
    useEffect(() => {
      if (!i18n) return;
      return i18n.subscribe(() => force((v) => v + 1));
    }, [i18n]);
    return (k, fb) => i18n ? i18n.t(k, fb) : fb;
  };

  /* ---------- scene timing (ms) ----------
     1 data appears     0.0 - 1.6
     2 secure ingest    1.6 - 3.2
     3 provider call    3.2 - 5.0
     4 response returns 5.0 - 6.4
     5 nothing retained 6.4 - 8.4
     hold + loop        8.4 - 9.4
  */
  const TOTAL_MS = 9400;

  const DATA = [
    { k: "prompt",   label: "Prompt",          meta: "User query · 1.2 KB" },
    { k: "sop",      label: "SOP document",    meta: "SOP-FA-204 · 14 steps" },
    { k: "vendor",   label: "Vendor record",   meta: "VND-318 · DLP active" },
    { k: "ops",      label: "Operational data",meta: "Asset PB-A02 · history" },
  ];

  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

  /* ---------- sub-components ---------- */
  const DataCard = ({ d, index, phase, t }) => {
    // phase: "enter" (0→1), "into-wisai", "held", "out-to-provider"
    // t is global ms elapsed
    const appear = clamp((t - index * 220) / 600, 0, 1);
    const gathered = t > 1500 ? clamp((t - 1500) / 700, 0, 1) : 0;
    // when gathered, all cards slide toward the WisAI container in a stack
    const targetY = gathered * (-index * 6 + 8);   // tight stack
    const targetX = gathered * 86;                 // shift right toward container
    const cardScale = 1 - gathered * 0.06;
    const cardOpacity = appear * (t > 3100 ? clamp(1 - (t - 3100) / 400, 0, 1) : 1);

    if (motion) {
      return (
        <motion.div
          className="zdr-data-card"
          initial={false}
          animate={{
            opacity: cardOpacity,
            y: (1 - appear) * 16 + targetY,
            x: targetX,
            scale: cardScale,
          }}
          transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
        >
          <span className={`zdr-data-ico zdr-data-ico--${d.k}`}>
            {iconFor(d.k)}
          </span>
          <span className="zdr-data-body">
            <span className="lbl">{d.label}</span>
            <span className="meta">{d.meta}</span>
          </span>
        </motion.div>
      );
    }
    return (
      <div className="zdr-data-card">
        <span className={`zdr-data-ico zdr-data-ico--${d.k}`}>{iconFor(d.k)}</span>
        <span className="zdr-data-body">
          <span className="lbl">{d.label}</span>
          <span className="meta">{d.meta}</span>
        </span>
      </div>
    );
  };

  function iconFor(k) {
    switch (k) {
      case "prompt":
        return (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a8 8 0 1 1-3-6.2L21 3v6h-6" /></svg>);
      case "sop":
        return (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /><path d="M14 3v5h5M9 13h6M9 17h4" /></svg>);
      case "vendor":
        return (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 21V8l8-5 8 5v13" /><path d="M9 21v-7h6v7" /></svg>);
      case "ops":
        return (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8l9-4 9 4v8l-9 4-9-4z" /><path d="M3 8l9 4 9-4M12 12v8" /></svg>);
      default:
        return null;
    }
  }

  /* ---------- main flow ---------- */
  const ZdrFlow = () => {
    const tt = useZdrT();
    const [t, setT] = useState(0); // ms within loop
    const data = DATA.map((d) => ({
      ...d,
      label: tt(`zdr.data.${d.k}.label`, d.label),
      meta: tt(`zdr.data.${d.k}.meta`, d.meta),
    }));
    const chips = [
      tt("zdr.chip.retained", "0 retained"),
      tt("zdr.chip.training", "Not used for training"),
      tt("zdr.chip.taskOnly", "Task-only processing"),
      tt("zdr.chip.knowledge", "Knowledge stays yours"),
    ];

    useEffect(() => {
      const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      if (reduced) { setT(TOTAL_MS - 1000); return; }
      let raf, start;
      const tick = (now) => {
        if (!start) start = now;
        setT(((now - start) % TOTAL_MS));
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => cancelAnimationFrame(raf);
    }, []);

    // derived flags
    const showSecure  = t > 1500;
    const wisaiGlow   = clamp((t - 1700) / 600, 0, 1) * (t < 6500 ? 1 : clamp(1 - (t - 6500) / 600, 0, 1));
    const packetsOut  = t > 2900 && t < 5200;
    const showResult  = t > 4900;
    const resultHide  = clamp((t - 6300) / 400, 0, 1);
    const showChips   = t > 6400;
    const chipsResolved = t > 8000;

    // packet positions (3 packets staggered)
    const packetT = (offset) => {
      const local = (t - 2900 - offset * 240) / 1100;
      return clamp(local, 0, 1);
    };

    return (
      <div className="zdr-stage">
        {/* faint blueprint backdrop is inherited from page; stage stays minimal */}

        {/* SCENE 1 — proprietary data cards */}
        <div className="zdr-data-col">
          {data.map((d, i) => (
            <DataCard key={d.k} d={d} index={i} t={t} />
          ))}
        </div>

        {/* SCENE 2 — WisAI secure processing layer */}
        <div className={`zdr-wisai ${showSecure ? "is-in" : ""}`} style={{ '--glow': wisaiGlow }}>
          <div className="zdr-wisai-head">
            <span className="zdr-lock">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="4" y="11" width="16" height="10" rx="1.5" />
                <path d="M8 11V8a4 4 0 1 1 8 0v3" />
              </svg>
            </span>
            <span className="zdr-wisai-title">{tt("zdr.secureLayer", "WisAI · Secure processing layer")}</span>
          </div>
          <div className="zdr-wisai-rows">
            <div className="row"><span>{tt("zdr.encryption", "Encryption")}</span><span className="v">TLS 1.3 + AES-256</span></div>
            <div className="row"><span>{tt("zdr.residency", "Residency")}</span><span className="v">{tt("zdr.singapore", "Singapore")}</span></div>
            <div className="row"><span>{tt("zdr.scope", "Scope")}</span><span className="v">{tt("zdr.taskOnly", "Task-only")}</span></div>
          </div>
          <div className="zdr-wisai-flash" />
        </div>

        {/* SCENE 3 — ZDR-supported model provider */}
        <div className={`zdr-provider ${t > 2700 ? "is-in" : ""}`}>
          <div className="zdr-provider-head">
            <span className="zdr-badge">ZDR</span>
            <span className="zdr-provider-title">{tt("zdr.modelProvider", "Model provider")}</span>
          </div>
          <div className="zdr-provider-meta">
            <div className="row"><span>{tt("zdr.retention", "Retention")}</span><span className="v ok">{tt("zdr.zeroDays", "0 days")}</span></div>
            <div className="row"><span>{tt("zdr.training", "Training")}</span><span className="v ok">{tt("zdr.excluded", "Excluded")}</span></div>
          </div>
        </div>

        {/* connecting channel */}
        <svg className="zdr-channel" viewBox="0 0 100 24" preserveAspectRatio="none">
          <line x1="0" y1="12" x2="100" y2="12" stroke="rgba(22,69,122,0.18)" strokeDasharray="4 4" />
        </svg>

        {/* SCENE 3 — temporary data packets flowing to provider */}
        {packetsOut && [0, 1, 2].map((i) => {
          const p = packetT(i);
          return (
            <div
              key={i}
              className="zdr-packet"
              style={{
                left: `calc(48% + ${p * 18}%)`,
                opacity: p > 0 && p < 1 ? 1 : 0,
                transform: `translateY(-50%) scale(${0.9 + p * 0.1})`,
              }}
            >
              <span>{i === 0 ? tt("zdr.packet.prompt", "Prompt") : i === 1 ? tt("zdr.packet.context", "Context") : tt("zdr.packet.refs", "Refs")}</span>
            </div>
          );
        })}

        {/* SCENE 4 — response card returning */}
        {showResult && (
          <div
            className="zdr-result"
            style={{
              opacity: clamp((t - 4900) / 400, 0, 1) * (1 - resultHide),
              transform: `translateY(-50%) translateX(${clamp((6300 - t) / 900, 0, 1) * 60}px)`,
            }}
          >
            <div className="zdr-result-head">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l4 4 10-10" /></svg>
              {tt("zdr.result.head", "Task response")}
            </div>
            <div className="zdr-result-body">{tt("zdr.result.body", "Recommendation ready")}</div>
            <div className="zdr-result-meta">{tt("zdr.result.meta", "processed · not stored")}</div>
          </div>
        )}

        {/* SCENE 5 — nothing retained chips */}
        <div className={`zdr-chips ${showChips ? "is-in" : ""}`}>
          {chips.map((c, i) => {
            const cAppear = clamp((t - 6400 - i * 220) / 500, 0, 1);
            return (
              <span
                key={c}
                className="zdr-chip"
                style={{
                  opacity: cAppear,
                  transform: `translateY(${(1 - cAppear) * 10}px)`,
                }}
              >
                <span className="tick">
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l4 4 10-10" /></svg>
                </span>
                {c}
              </span>
            );
          })}
        </div>

        {/* end-state quiet caption */}
        <div className="zdr-caption" style={{ opacity: chipsResolved ? 1 : 0 }}>
          {tt("zdr.caption", "Processed · not retained · not trained on")}
        </div>
      </div>
    );
  };

  window.ZdrFlow = ZdrFlow;
})();
