// permission-flow.jsx — "Decide what every agent can touch".
// A looping, three-scene Framer Motion story for the Permissions tab of the
// governance section. Mirrors the AuditTrail pattern (timed scenes, reduced-
// motion fallback). Exports window.PermissionFlow.
//
//   Scene 1 — Permissions card: a cursor pans/zooms across a Gmail action
//             list, setting each action to Off / Review / On.
//   Scene 2 — Empty workspace: the list slides out, the space opens up.
//   Scene 3 — Prompt → WisAI run → approval required before sending email.
//
// React hooks (useState/useEffect/useRef) and Icon are already global,
// destructured upstream in landing-mockups.jsx.

(function () {
  const M = window.Motion || {};
  const motion = M.motion;
  const ease = [0.16, 1, 0.3, 1];

  const usePermT = () => {
    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;
  };

  // Per-action target access level: 0 = Off, 1 = Review, 2 = On.
  const STATES = ["off", "review", "on"];
  const ROWS = [
    { key: "read",    label: "Read messages",    target: 2 },
    { key: "search",  label: "Search messages",  target: 2 },
    { key: "draft",   label: "Draft message",    target: 1 },
    { key: "send",    label: "Send message",     target: 1 },
    { key: "archive", label: "Archive message",  target: 0 },
    { key: "forward", label: "Forward message",  target: 0 },
    { key: "label",   label: "Label messages",   target: 2 },
  ];

  /* ---------- Scene 1 — permissions card ---------- */
  const PermsScene = ({ states, cursor, clickKey, cameraRef, segRefs }) => {
    const t = usePermT();
    return (
      <div className="pf-scene">
        <div className="pf-perms">
          <div className="pf-perms-head">
            <img src="assets/gmail-icon.svg" alt="" />
            <h4>{t("perm.head.title", "Gmail · agent access")}</h4>
          </div>
          {ROWS.map((row, i) => (
            <div className="pf-perm-row" key={row.key}>
              <span className="pf-perm-label">{t(`perm.row.${row.key}`, row.label)}</span>
              <span className="pf-seg" role="group">
                {STATES.map((s, si) => (
                  <span
                    key={s}
                    ref={si === row.target ? (el) => { segRefs.current[i] = el; } : null}
                    className={`pf-seg-opt ${states[i] === si ? "is-on" : ""}`}
                    data-state={s}>
                    {t(`perm.seg.${s}`, s === "off" ? "Off" : s === "review" ? "Review" : "On")}
                  </span>
                ))}
              </span>
            </div>
          ))}
        </div>
        {motion && cursor && (
          <motion.div
            className="pf-cursor"
            initial={false}
            animate={{ x: cursor.x, y: cursor.y, scale: cursor.down ? 0.82 : 1 }}
            transition={{ x: { duration: 0.42, ease }, y: { duration: 0.42, ease }, scale: { duration: 0.12 } }}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M4 2l12 6.5-5 1.2-2.6 5.1z" fill="#0B1F3B" stroke="#fff" strokeWidth="1.2" strokeLinejoin="round" />
            </svg>
            {clickKey > 0 && <span className="pf-click-ring" key={clickKey} />}
          </motion.div>
        )}
      </div>
    );
  };

  /* ---------- Scene 2 — prompt, run, approval ---------- */
  const ChatScene = ({ step }) => {
    const t = usePermT();
    const Node = motion ? motion.div : "div";
    const appear = (delay) => motion ? {
      initial: { opacity: 0, y: 10 },
      animate: { opacity: 1, y: 0 },
      transition: { duration: 0.4, delay, ease },
    } : {};
    return (
      <div className="pf-scene">
        <div className="pf-chat">
          <Node className="pf-msg-user" {...appear(0)}>
            <div className="pf-msg-head">
              <span>{t("perm.chat.you", "You")}</span>
              <time>{t("perm.chat.time", "08:21")}</time>
            </div>
            <div className="pf-bubble">
              {t("perm.chat.prompt", "The aircon contractor is asking what's outstanding before tomorrow's visit. Pull their open work orders and draft a reply.")}
            </div>
          </Node>

          {step >= 1 && (
            <div className="pf-wai">
              <img className="pf-wai-av" src="assets/wisbid-icon.svg" alt="WisAI" />
              <div className="pf-wai-body">
                <div className="pf-wai-name">{t("perm.chat.wai", "WisAI")}</div>

                <Node className="pf-step" {...appear(0)}>
                  <span className="pf-step-check"><Icon name="check" size={10} /></span>
                  <img src="assets/gmail-icon.svg" alt="" />
                  {t("perm.chat.step1", "Read contractor email · site visit tomorrow")}
                </Node>

                {step >= 2 && (
                  <Node className="pf-step" {...appear(0)}>
                    <span className="pf-step-check"><Icon name="check" size={10} /></span>
                    <Icon name="layers" size={13} />
                    {t("perm.chat.step2", "Found 4 open work orders for this vendor")}
                  </Node>
                )}

                {step === 2 && (
                  <Node className="pf-step" {...appear(0.1)}>
                    <span className="pf-spin" />
                    {t("perm.chat.thinking", "Drafting reply with the job list…")}
                  </Node>
                )}

                {step >= 3 && motion && (
                  <motion.div
                    className="pf-approve"
                    initial={{ opacity: 0, y: 14, scale: 0.98 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    transition={{ duration: 0.45, ease }}>
                    <div className="pf-approve-head">
                      <Icon name="shield" size={14} />
                      {t("perm.approve.title", "Approval required before sending")}
                    </div>
                    <div className="pf-approve-prev">
                      <div className="pf-prev-row"><b>{t("perm.approve.to", "To")}</b><span>ops@aircon-vendor.sg</span></div>
                      <div className="pf-prev-row"><b>{t("perm.approve.subj", "Subject")}</b><span>{t("perm.approve.subjVal", "Re: Tomorrow's site visit, outstanding jobs")}</span></div>
                      <div className="pf-prev-snip">{t("perm.approve.snippet", "Thanks. Ahead of tomorrow there are 4 open work orders on your account, starting with the Blk C fan coil (WO-2026-0488). Please prioritise that unit; access details below.")}</div>
                    </div>
                    {step === 3 ? (
                      <div className="pf-approve-actions">
                        <span className="pf-btn pf-btn-primary"><Icon name="send" size={13} />{t("perm.approve.send", "Approve & send")}</span>
                        <span className="pf-btn pf-btn-ghost">{t("perm.approve.review", "Review draft")}</span>
                        <span className="pf-approve-foot">
                          <span className="pill"><Icon name="lock" size={10} />{t("perm.approve.policy", "Send · Review")}</span>
                        </span>
                      </div>
                    ) : (
                      <div className="pf-sent">
                        <span className="pf-sent-check"><Icon name="check" size={12} /></span>
                        {t("perm.approve.sent", "Approved & sent")}
                      </div>
                    )}
                  </motion.div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    );
  };

  /* ---------- main ---------- */
  const PermissionFlow = () => {
    const t = usePermT();
    const [scene, setScene] = useState(0);   // 0 = permissions, 1 = chat
    const [states, setStates] = useState(ROWS.map(() => -1)); // -1 = unset
    const [cursor, setCursor] = useState({ x: 70, y: 360, down: false });
    const [clickKey, setClickKey] = useState(0);
    const [slideOut, setSlideOut] = useState(false); // permissions card exits left
    const [step, setStep] = useState(0); // chat progress
    const cameraRef = useRef(null);
    const segRefs = useRef([]);

    useEffect(() => {
      const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      if (reduced) {
        setScene(1); setStep(4);
        setStates(ROWS.map((r) => r.target));
        return;
      }
      const timers = [];
      const at = (fn, ms) => timers.push(setTimeout(fn, ms));

      // Read a target segment's centre, relative to the (panning) camera.
      const segCenter = (i) => {
        const cam = cameraRef.current;
        const seg = segRefs.current[i];
        if (!cam || !seg) return null;
        const c = cam.getBoundingClientRect();
        const r = seg.getBoundingClientRect();
        return { x: r.left - c.left + r.width / 2, y: r.top - c.top + r.height / 2 };
      };

      const run = () => {
        setScene(0);
        setStates(ROWS.map(() => -1));
        setStep(0);
        setSlideOut(false);
        setCursor({ x: 70, y: 360, down: false });

        let e = 420; // let layout settle before the cursor moves

        // Scene 1 — cursor visits each row and sets its access level (brisk)
        ROWS.forEach((row, i) => {
          at(() => {
            const p = segCenter(i);
            if (p) setCursor({ x: p.x - 3, y: p.y - 2, down: false });
          }, e);
          e += 300;
          at(() => {
            setCursor((c) => ({ ...c, down: true }));
            setClickKey((k) => k + 1);
            setStates((prev) => { const n = prev.slice(); n[i] = row.target; return n; });
          }, e);
          e += 90;
          at(() => setCursor((c) => ({ ...c, down: false })), e);
          e += 60;
        });
        e += 360; // brief hold on the completed list

        // Transition — permissions card slides out to the left,
        // then (once fully off-screen) the chat scene pops in.
        at(() => setSlideOut(true), e);
        e += 720; // > slide duration, so the card is gone before we swap

        // Scene 2 — prompt → run → approval → sent (unhurried, so it reads)
        at(() => { setScene(1); setStep(0); }, e);
        e += 380;
        at(() => setStep(1), e);   // user prompt → WisAI starts reading
        e += 1150;
        at(() => setStep(2), e);   // work-order history pulled, drafting
        e += 1600;
        at(() => setStep(3), e);   // approval gate appears
        e += 2700;
        at(() => setStep(4), e);   // approved & sent
        e += 3600;                 // long idle on the resolved state to digest

        at(run, e);
      };
      run();
      return () => timers.forEach(clearTimeout);
    }, []);

    // Subtle camera pan while choosing access; settle once the card exits.
    const cameraAnim = motion && scene === 0 && !slideOut
      ? { y: [0, -7, 3, 0] }
      : { y: 0 };

    return (
      <div className="pf-wrap">
        <div className="pf-card">
          {motion ? (
            <div className="pf-stage">
              <motion.div
                className="pf-camera"
                ref={cameraRef}
                animate={cameraAnim}
                transition={scene === 0 && !slideOut ? { duration: 4.4, ease: "easeInOut" } : { duration: 0.5, ease }}>
                {scene === 0 && (
                  <motion.div
                    key="perms"
                    className="pf-scene-wrap"
                    initial={{ opacity: 0, scale: 0.92, y: 12 }}
                    animate={slideOut
                      ? { x: "-128%", opacity: 1, scale: 1, y: 0 }
                      : { x: 0, opacity: 1, scale: 1, y: 0 }}
                    transition={slideOut
                      ? { duration: 0.62, ease: [0.4, 0, 0.2, 1] }
                      : { duration: 0.5, ease }}>
                    <PermsScene
                      states={states} cursor={cursor} clickKey={clickKey}
                      cameraRef={cameraRef} segRefs={segRefs} />
                  </motion.div>
                )}
                {scene === 1 && (
                  <motion.div
                    key="chat"
                    className="pf-scene-wrap"
                    initial={{ opacity: 0, scale: 0.88, y: 16 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    transition={{ duration: 0.46, ease }}>
                    <ChatScene step={step} />
                  </motion.div>
                )}
              </motion.div>
            </div>
          ) : (
            <div className="pf-stage">
              <div className="pf-camera"><ChatScene step={4} /></div>
            </div>
          )}
        </div>
      </div>
    );
  };

  window.PermissionFlow = PermissionFlow;
})();
