// Interactive Demo — playable Tinder-style triage

// Auto-playing reply modal — typing → AI optimize → send animation
const ReplyAutoModal = ({ email, onComplete }) => {
  const [phase, setPhase] = useState("opening"); // opening | typing-rough | wait-rough | optimizing | typing-new | wait-new | sending | sent | flying-out
  const [typed, setTyped] = useState("");
  const cancelRef = useRef(false);

  const rough = email.replyRough || "收到，會處理。";
  const optimized = email.replyOptimized || "感謝來信，已收到您的訊息，將盡快處理並回覆。";

  useEffect(() => {
    cancelRef.current = false;
    const timers = [];
    const intervals = [];

    const sched = (fn, ms) => {
      const t = setTimeout(() => { if (!cancelRef.current) fn(); }, ms);
      timers.push(t);
      return t;
    };

    const typeText = (full, durationMs, onDone) => {
      setTyped("");
      const start = performance.now();
      const iv = setInterval(() => {
        if (cancelRef.current) { clearInterval(iv); return; }
        const elapsed = performance.now() - start;
        const ratio = Math.min(1, elapsed / durationMs);
        // Ease-out for natural feel
        const eased = 1 - Math.pow(1 - ratio, 1.3);
        const len = Math.floor(full.length * eased);
        setTyped(full.slice(0, len));
        if (ratio >= 1) {
          clearInterval(iv);
          setTyped(full);
          onDone();
        }
      }, 24);
      intervals.push(iv);
    };

    // T+0: modal opens (CSS handles fade-in)
    // T+300: start typing rough draft
    sched(() => {
      setPhase("typing-rough");
      typeText(rough, 1500, () => {
        setPhase("wait-rough");
        // T+1800+300: AI optimize button "pressed"
        sched(() => {
          setPhase("optimizing");
          // T+2400: start typing optimized (rough fades out via CSS)
          sched(() => {
            setPhase("typing-new");
            typeText(optimized, 1500, () => {
              setPhase("wait-new");
              // T+3900+400: send button pressed
              sched(() => {
                setPhase("sending");
                // T+4400: sent
                sched(() => {
                  setPhase("sent");
                  // T+5100: card fly out
                  sched(() => {
                    setPhase("flying-out");
                    sched(() => onComplete && onComplete(), 700);
                  }, 700);
                }, 500);
              }, 400);
            });
          }, 600);
        }, 300);
      });
    }, 300);

    return () => {
      cancelRef.current = true;
      timers.forEach(clearTimeout);
      intervals.forEach(clearInterval);
    };
  }, []);

  const opened = phase !== "opening";
  const flyingOut = phase === "flying-out";
  const showRough = phase === "typing-rough" || phase === "wait-rough" || phase === "optimizing";
  const roughFading = phase === "optimizing";
  const showNew = phase === "typing-new" || phase === "wait-new" || phase === "sending" || phase === "sent";
  const aiButtonActive = phase === "optimizing";
  const sendPressed = phase === "sending" || phase === "sent";
  const sent = phase === "sent";

  const displayed = showNew ? typed : (showRough ? typed : "");

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: "rgba(10,10,15,0.78)",
      backdropFilter: "blur(8px)",
      WebkitBackdropFilter: "blur(8px)",
      borderRadius: 24,
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 24,
      zIndex: 100,
      opacity: opened ? 1 : 0,
      transition: "opacity .25s ease",
      pointerEvents: opened ? "auto" : "none",
    }}>
      <div style={{
        width: "min(640px, 100%)",
        maxHeight: "100%",
        background: "var(--panel)",
        border: "1px solid var(--border)",
        borderRadius: 18,
        boxShadow: "0 30px 80px -20px rgba(0,0,0,0.7), 0 0 0 1px rgba(59,130,246,0.15)",
        overflow: "hidden",
        display: "flex", flexDirection: "column",
        transform: flyingOut
          ? "translate(120px, -180px) scale(0.5) rotate(8deg)"
          : opened ? "scale(1)" : "scale(0.94)",
        opacity: flyingOut ? 0 : 1,
        transition: flyingOut
          ? "transform .7s cubic-bezier(.5,.05,.5,1), opacity .7s ease"
          : "transform .3s cubic-bezier(.2,.8,.2,1)",
        transformOrigin: "center center",
      }}>
        {/* Modal Header */}
        <div style={{
          padding: "14px 20px",
          borderBottom: "1px solid var(--border-soft)",
          display: "flex", alignItems: "center", gap: 12,
          background: "var(--bg-3)",
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 8,
            background: "linear-gradient(135deg, #3B82F6, #22D3EE)",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "white",
          }}><IconReply size={14}/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="mono" style={{ fontSize: 9.5, color: "var(--text-4)", letterSpacing: "0.15em", marginBottom: 2 }}>REPLY · 草擬中</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              Re: {email.subject}
            </div>
          </div>
        </div>

        {/* To / From row */}
        <div className="reply-modal-to-from" style={{
          padding: "10px 20px",
          display: "flex", flexDirection: "column", gap: 4,
          borderBottom: "1px solid var(--border-soft)",
        }}>
          <div style={{ display: "flex", gap: 10, fontSize: 11.5 }}>
            <span className="mono" style={{ color: "var(--text-4)", letterSpacing: "0.1em", width: 36 }}>TO</span>
            <span style={{ color: "var(--text-2)" }}>{email.senderName} &lt;{email.senderEmail}&gt;</span>
          </div>
          <div style={{ display: "flex", gap: 10, fontSize: 11.5 }}>
            <span className="mono" style={{ color: "var(--text-4)", letterSpacing: "0.1em", width: 36 }}>FROM</span>
            <span style={{ color: "var(--text-2)" }}>王志明 &lt;will.wang@formosa-components.com&gt;</span>
          </div>
        </div>

        {/* Body — typed text */}
        <div className="reply-modal-body" style={{
          padding: 24,
          minHeight: 220,
          background: "var(--bg-2)",
          position: "relative",
          fontSize: 13.5,
          lineHeight: 1.75,
          whiteSpace: "pre-wrap",
          fontFamily: "inherit",
          color: showNew ? "var(--accent-2)" : "var(--text)",
          transition: "color .3s ease",
        }}>
          {/* Rough draft (fades when optimizing) */}
          {showRough && (
            <div style={{
              position: "relative",
              color: roughFading ? "var(--text-4)" : "var(--text)",
              opacity: roughFading ? 0.35 : 1,
              transition: "color .5s ease, opacity .5s ease",
            }}>
              {displayed}
              {(phase === "typing-rough") && <span className="caret" />}
            </div>
          )}

          {/* Optimized draft */}
          {showNew && (
            <div style={{
              position: "relative",
              color: "var(--accent-2)",
              fontWeight: 500,
            }}>
              {displayed}
              {phase === "typing-new" && <span className="caret caret-blue" />}
            </div>
          )}

          {/* Initial blank placeholder */}
          {!showRough && !showNew && (
            <div style={{ color: "var(--text-4)" }}>
              <span className="caret" />
            </div>
          )}
        </div>

        {/* Toolbar */}
        <div className="reply-modal-toolbar" style={{
          padding: "14px 20px",
          borderTop: "1px solid var(--border-soft)",
          background: "var(--bg-3)",
        }}>
          {/* AI optimize button */}
          <button
            disabled
            style={{
              padding: "10px 14px",
              borderRadius: 10,
              border: `1px solid ${aiButtonActive ? "rgba(34,211,238,0.5)" : "var(--border)"}`,
              background: aiButtonActive ? "rgba(34,211,238,0.12)" : "var(--bg-2)",
              color: aiButtonActive ? "var(--cyan)" : "var(--text-2)",
              fontSize: 12,
              fontWeight: 700,
              fontFamily: "inherit",
              display: "inline-flex", alignItems: "center", gap: 8,
              cursor: "default",
              boxShadow: aiButtonActive ? "0 0 0 4px rgba(34,211,238,0.18), 0 8px 24px -6px rgba(34,211,238,0.4)" : "none",
              transform: aiButtonActive ? "scale(0.97)" : "scale(1)",
              transition: "all .2s ease",
            }}
          >
            <IconWand size={13}/>
            {aiButtonActive ? "AI 優化中..." : "AI 優化"}
          </button>

          {/* Spacer */}
          <div style={{ flex: 1 }} />

          {/* Status text */}
          <div className="mono reply-toolbar-status" style={{ fontSize: 10, color: "var(--text-4)", letterSpacing: "0.12em" }}>
            {phase === "typing-rough" && "草擬中..."}
            {phase === "wait-rough" && "草稿完成"}
            {phase === "optimizing" && "AI 優化中..."}
            {phase === "typing-new" && "AI 重寫中..."}
            {phase === "wait-new" && "已優化"}
            {phase === "sending" && "寄送中..."}
            {phase === "sent" && "已寄出 ✓"}
          </div>

          {/* Send button */}
          <button
            disabled
            style={{
              padding: "10px 18px",
              borderRadius: 10,
              border: "none",
              background: sent ? "var(--green)" : "var(--accent)",
              color: "white",
              fontSize: 13,
              fontWeight: 700,
              fontFamily: "inherit",
              display: "inline-flex", alignItems: "center", gap: 8,
              cursor: "default",
              boxShadow: sent
                ? "0 0 0 4px rgba(52,211,153,0.2), 0 8px 24px -6px rgba(52,211,153,0.5)"
                : sendPressed
                  ? "0 0 0 4px rgba(59,130,246,0.25), 0 8px 24px -6px rgba(59,130,246,0.55)"
                  : "0 4px 12px -2px rgba(59,130,246,0.4)",
              transform: sendPressed && !sent ? "scale(0.95)" : "scale(1)",
              transition: "all .25s cubic-bezier(.3,1.5,.5,1)",
            }}
          >
            {sent ? <IconCheck size={14}/> : <IconSend size={13}/>}
            {sent ? "已寄出" : "寄出回覆"}
          </button>
        </div>
      </div>
    </div>
  );
};

const InteractiveDemo = () => {
  const isPhone = useIsMobile(600);
  const swipeThreshold = isPhone ? 72 : 120;
  const exitDistance = isPhone ? 320 : 600;
  const [deck, setDeck] = useState(SAMPLE_EMAILS);
  const [completed, setCompleted] = useState([]); // {email, action}
  const [drag, setDrag] = useState({ x: 0, y: 0, active: false });
  const [exiting, setExiting] = useState(null); // "left" | "right"
  const [replyEmail, setReplyEmail] = useState(null);
  const startRef = useRef({ x: 0, y: 0 });
  const cardRef = useRef(null);
  const [hintSeen, setHintSeen] = useState(false);

  const current = deck[0];
  const next = deck[1];
  const next2 = deck[2];

  const total = SAMPLE_EMAILS.length;
  const done = completed.length;

  const onPointerDown = (e) => {
    if (!current || exiting || replyEmail) return;
    setHintSeen(true);
    startRef.current = { x: e.clientX, y: e.clientY };
    setDrag({ x: 0, y: 0, active: true });
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    if (!drag.active) return;
    setDrag({
      x: e.clientX - startRef.current.x,
      y: e.clientY - startRef.current.y,
      active: true,
    });
  };
  const finishLeft = () => {
    setExiting("left");
    const target = current;
    setTimeout(() => {
      setCompleted((c) => [...c, { email: target, action: "left" }]);
      setDeck((d) => d.slice(1));
      setDrag({ x: 0, y: 0, active: false });
      setExiting(null);
    }, 360);
  };
  const startReply = () => {
    if (!current) return;
    setExiting("right");
    const target = current;
    // Quick exit, then open modal
    setTimeout(() => {
      setReplyEmail(target);
      setDrag({ x: 0, y: 0, active: false });
      setExiting(null);
    }, 280);
  };
  const completeReply = () => {
    if (!replyEmail) return;
    setCompleted((c) => [...c, { email: replyEmail, action: "right" }]);
    setDeck((d) => d.filter((e) => e.id !== replyEmail.id));
    setReplyEmail(null);
  };
  const finish = (action) => {
    if (action === "right") startReply();
    else finishLeft();
  };
  const onPointerUp = () => {
    if (!drag.active) return;
    if (drag.x > swipeThreshold) startReply();
    else if (drag.x < -swipeThreshold) finishLeft();
    else setDrag({ x: 0, y: 0, active: false });
  };

  const reset = () => {
    setDeck(SAMPLE_EMAILS);
    setCompleted([]);
    setHintSeen(false);
    setReplyEmail(null);
  };

  const rotation = drag.active ? drag.x / 18 : 0;
  const swipeHint = isPhone ? 40 : 60;
  const swipeDir = drag.x > swipeHint ? "right" : drag.x < -swipeHint ? "left" : null;
  const exitX = exiting === "right" ? exitDistance : exiting === "left" ? -exitDistance : drag.x;
  const exitRot = exiting === "right" ? 25 : exiting === "left" ? -25 : rotation;

  const allDone = deck.length === 0;

  return (
    <section id="demo" style={{ position: "relative", overflow: "hidden" }} className="section-pad">
      <div className="hide-mobile-decor glow-blue" style={{
        position: "absolute", top: "20%", left: "50%", transform: "translateX(-50%)",
        width: "min(900px, 120vw)", height: 600, pointerEvents: "none", opacity: 0.7,
      }} />

      <div className="container" style={{ position: "relative" }}>
        <div style={{ textAlign: "center", marginBottom: 60 }}>
          <SectionHeader
            tag="03 / 互動 DEMO · 親手試試"
            title="不用註冊，現在就試玩。"
            sub={isPhone ? "左滑稍後 · 右滑回覆 · 或點下方按鈕。" : "左滑稍後處理 · 右滑立即回覆 · 或直接點下方按鈕。"}
            align="center"
            maxWidth={620}
          />
        </div>

        {/* Demo stage */}
        <div className="demo-stage-panel" style={{
          position: "relative",
          background: "var(--bg-2)",
          border: "1px solid var(--border)",
          borderRadius: 24,
          overflow: "hidden",
        }}>
          {/* Grid backdrop */}
          <div className="grid-bg-fine" style={{ position: "absolute", inset: 0, opacity: 0.6, pointerEvents: "none" }} />

          {/* Progress bar */}
          <div className="demo-progress-row" style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 32 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.15em" }}>QLIVO TRIAGE</div>
              <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--green)" }} className="pulse-dot" />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <div className="mono" style={{ fontSize: 11, color: "var(--text-2)", letterSpacing: "0.1em" }}>
                {done} / {total} 已處理
              </div>
              <button onClick={reset} className="mono" style={{
                background: "transparent", border: "1px solid var(--border-soft)",
                color: "var(--text-3)", padding: "6px 12px", borderRadius: 8,
                fontSize: 10, letterSpacing: "0.12em", cursor: "pointer", fontFamily: "var(--font-mono)",
                display: "inline-flex", alignItems: "center", gap: 6,
              }}><IconRotateLeft size={11}/> 重設 DEMO</button>
            </div>
          </div>

          {/* Progress bar visual */}
          <div style={{ position: "relative", height: 3, background: "var(--border-soft)", borderRadius: 2, overflow: "hidden", marginBottom: 48 }}>
            <div style={{
              position: "absolute", left: 0, top: 0, bottom: 0,
              width: `${(done / total) * 100}%`,
              background: "linear-gradient(90deg, var(--accent), var(--cyan))",
              transition: "width .4s ease",
            }} />
          </div>

          {/* Card area */}
          <div className="grid-demo-stage">
            {/* Left rail: instructions */}
            <div className="demo-rail-hints" style={{ paddingTop: 24 }}>
              <div style={{
                padding: "18px 20px",
                border: "1px solid var(--border-soft)",
                borderRadius: 14,
                background: "rgba(249,115,22,0.04)",
              }}>
                <div className="mono" style={{ fontSize: 10, color: "var(--orange)", letterSpacing: "0.12em", marginBottom: 10, display: "flex", alignItems: "center", gap: 6 }}>
                  <IconRotateLeft size={12}/> 向左滑
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>稍後處理</div>
                <div style={{ fontSize: 13, color: "var(--text-3)", lineHeight: 1.5 }}>非緊急、可暫緩的信件。收進右下角的「待處理」提醒徽章。</div>
              </div>

              <div style={{
                marginTop: 14, padding: "18px 20px",
                border: "1px solid var(--border-soft)", borderRadius: 14,
                background: "var(--bg-3)",
              }}>
                <div className="mono" style={{ fontSize: 10, color: "var(--cyan)", letterSpacing: "0.12em", marginBottom: 10, display: "flex", alignItems: "center", gap: 6 }}>
                  <IconSpark size={12}/> AI 已預先分析
                </div>
                <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.55 }}>
                  Qlivo 處理時，每張卡都已有<br/>
                  <span style={{ color: "var(--text)" }}>類型、優先級、摘要與下一步</span>，<br/>
                  幫你縮短判斷時間。
                </div>
              </div>
            </div>

            {/* Center: card stack */}
            <div className="demo-card-col">
              {/* Background stack cards */}
              {next2 && (
                <div style={{
                  position: "absolute", inset: 0,
                  transform: "rotate(3deg) scale(0.93) translateY(14px)",
                  opacity: 0.4,
                }}>
                  <EmailCard email={next2} dim />
                </div>
              )}
              {next && (
                <div style={{
                  position: "absolute", inset: 0,
                  transform: "rotate(-2deg) scale(0.96) translateY(6px)",
                  opacity: 0.7,
                }}>
                  <EmailCard email={next} dim />
                </div>
              )}

              {/* Top card (active) */}
              {current && (
                <div
                  ref={cardRef}
                  onPointerDown={onPointerDown}
                  onPointerMove={onPointerMove}
                  onPointerUp={onPointerUp}
                  onPointerCancel={onPointerUp}
                  style={{
                    position: "absolute", inset: 0, zIndex: 10,
                    transform: `translate(${exiting ? exitX : drag.x}px, ${drag.y * 0.4}px) rotate(${exitRot}deg)`,
                    transition: drag.active ? "none" : (exiting ? "transform .35s cubic-bezier(.5,0,.2,1), opacity .35s ease" : "transform .25s cubic-bezier(.2,.8,.2,1)"),
                    cursor: drag.active ? "grabbing" : "grab",
                    opacity: exiting ? 0 : 1,
                  }}
                  className="stack-shadow"
                >
                  <EmailCard email={current} />
                  {/* Direction overlay */}
                  {swipeDir && !exiting && (
                    <div style={{
                      position: "absolute", top: 28,
                      [swipeDir === "right" ? "right" : "left"]: 28,
                      padding: "10px 16px", borderRadius: 12,
                      border: `2px solid ${swipeDir === "right" ? "var(--green)" : "var(--orange)"}`,
                      color: swipeDir === "right" ? "var(--green)" : "var(--orange)",
                      fontWeight: 800, fontSize: 16, letterSpacing: "0.05em",
                      transform: `rotate(${swipeDir === "right" ? -8 : 8}deg)`,
                      background: "rgba(0,0,0,0.5)",
                      pointerEvents: "none",
                    }}>
                      {swipeDir === "right" ? "立即回覆 →" : "← 稍後處理"}
                    </div>
                  )}
                </div>
              )}

              {/* Done state */}
              {allDone && (
                <div style={{
                  position: "absolute", inset: 0,
                  display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center",
                  padding: 24,
                }}>
                  <div style={{
                    width: 80, height: 80, borderRadius: 40,
                    background: "linear-gradient(135deg, rgba(59,130,246,0.2), rgba(34,211,238,0.2))",
                    border: "1px solid rgba(59,130,246,0.4)",
                    color: "var(--cyan)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    marginBottom: 24,
                  }}><IconCheck size={40}/></div>
                  <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em", marginBottom: 12, lineHeight: 1.3 }}>
                    收件匣已清空 🎯
                  </div>
                  <p style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.6, maxWidth: 280, marginBottom: 28 }}>
                    你剛剛在 {Math.max(3, Math.round(done * 4))} 秒內處理了 {total} 封信，<br/>
                    相當於傳統收件匣的 12 分鐘。
                  </p>
                  <a href="#cta" className="btn btn-primary" style={{ padding: "12px 22px", fontSize: 14 }}>
                    預約完整版 Demo <IconArrowRight size={15}/>
                  </a>
                </div>
              )}

              {/* Hint on first card */}
              {!hintSeen && current && !exiting && (
                <div style={{
                  position: "absolute", top: -36, left: 0, right: 0,
                  display: "flex", justifyContent: "center", gap: 8,
                  pointerEvents: "none",
                }}>
                  <div className="mono" style={{
                    fontSize: 11, letterSpacing: "0.12em", color: "var(--text-3)",
                    display: "inline-flex", alignItems: "center", gap: 10,
                    padding: "8px 14px", borderRadius: 999,
                    background: "var(--bg)", border: "1px solid var(--border-soft)",
                  }}>
                    <span>拖曳卡片 ← / →，或點下方按鈕</span>
                  </div>
                </div>
              )}
            </div>

            {/* Right rail: live processed log */}
            <div className="demo-rail-log" style={{ paddingTop: 24 }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--text-3)", letterSpacing: "0.15em", marginBottom: 14 }}>LIVE LOG</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, minHeight: 200 }}>
                {completed.length === 0 ? (
                  <div style={{
                    padding: "16px 18px", border: "1px dashed var(--border-soft)", borderRadius: 12,
                    color: "var(--text-4)", fontSize: 12, lineHeight: 1.6,
                  }}>
                    處理過的郵件會即時出現在這裡。
                  </div>
                ) : completed.map((c, i) => (
                  <div key={i} style={{
                    padding: "10px 14px", borderRadius: 10,
                    background: "var(--bg-3)", border: "1px solid var(--border-soft)",
                    display: "flex", flexDirection: "column", gap: 4,
                  }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                      <span style={{
                        fontSize: 10, padding: "2px 7px", borderRadius: 999,
                        background: c.action === "right" ? "rgba(52,211,153,0.15)" : "rgba(249,115,22,0.15)",
                        color: c.action === "right" ? "var(--green)" : "var(--orange)",
                        fontWeight: 700, letterSpacing: "0.05em", fontFamily: "var(--font-mono)",
                      }}>
                        {c.action === "right" ? "✓ 已回覆" : "← 稍後處理"}
                      </span>
                      <span className="mono" style={{ fontSize: 9, color: "var(--text-4)" }}>{c.email.time}</span>
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {c.email.subject}
                    </div>
                    <div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {c.email.senderName}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Action buttons */}
          {!allDone && !replyEmail && (
            <div className="demo-action-btns" style={{
              position: "relative",
              display: "flex", justifyContent: "center", gap: 24,
              marginTop: 36,
            }}>
              <button
                onClick={() => current && finish("left")}
                style={{
                  width: 56, height: 56, borderRadius: 28,
                  background: "var(--bg-3)", border: "1px solid rgba(249,115,22,0.4)",
                  color: "var(--orange)", cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  boxShadow: "0 8px 24px -8px rgba(249,115,22,0.4)",
                  transition: "all .15s",
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = "rgba(249,115,22,0.1)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "var(--bg-3)"}
              ><IconRotateLeft size={22}/></button>
              <button
                onClick={() => current && finish("right")}
                style={{
                  width: 56, height: 56, borderRadius: 28,
                  background: "var(--bg-3)", border: "1px solid rgba(52,211,153,0.4)",
                  color: "var(--green)", cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  boxShadow: "0 8px 24px -8px rgba(52,211,153,0.4)",
                  transition: "all .15s",
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = "rgba(52,211,153,0.1)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "var(--bg-3)"}
              ><IconReply size={22}/></button>
            </div>
          )}

          {/* Reply Auto Modal — overlays the demo stage */}
          {replyEmail && (
            <ReplyAutoModal
              key={replyEmail.id}
              email={replyEmail}
              onComplete={completeReply}
            />
          )}
        </div>

        {/* Sub-note */}
        <div style={{ marginTop: 36, display: "flex", justifyContent: "center", gap: 24, flexWrap: "wrap", color: "var(--text-3)" }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", display: "flex", alignItems: "center", gap: 8 }}>
            <IconBot size={12}/> AI 摘要為真實模型輸出（已預錄）
          </div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", display: "flex", alignItems: "center", gap: 8 }}>
            <IconShield size={12}/> 此 Demo 不會傳送任何資料到伺服器
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { InteractiveDemo });
