// Interactive Live Demo — employee chat (left) + audit panel (right).
// Pure React. No backend; all logic runs in-page.

const { useState, useEffect, useRef, useMemo } = React;

function nowHHMMSS() {
  const d = new Date();
  const pad = (n) => String(n).padStart(2, "0");
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

function LiveDemo({ t, lang }) {
  // chat: [{from: "user"|"ai"|"system", text: string | jsx, id}]
  const [chat, setChat] = useState([]);
  const [logs, setLogs] = useState([]); // {time, type, raw, token}
  const [input, setInput] = useState("");
  const [thinking, setThinking] = useState(false);
  const [tab, setTab] = useState("log"); // 'log' | 'stats' | 'learn'
  const [tokenSaved, setTokenSaved] = useState(42.5);
  const [vramPct, setVramPct] = useState(90); // 7.2/8.0 GB
  const [reload, setReload] = useState("idle"); // idle | running | done
  const chatBodyRef = useRef(null);

  // Reset state when language changes so canned strings re-render
  useEffect(() => {
    setChat([]);
    setLogs([]);
  }, [lang]);

  // Allow other parts of the page (hero CTA) to trigger the canned scenario
  // via a window-level custom event.
  useEffect(() => {
    const onPlay = () => playScenario();
    window.addEventListener("secuagent:play", onPlay);
    return () => window.removeEventListener("secuagent:play", onPlay);
  });

  // Auto-scroll chat to bottom on new message
  useEffect(() => {
    if (chatBodyRef.current) {
      chatBodyRef.current.scrollTop = chatBodyRef.current.scrollHeight;
    }
  }, [chat, thinking]);

  const playScenario = () => {
    setChat([]);
    setLogs([]);
    // 1) User message
    setTimeout(() => {
      setChat((c) => [
        ...c,
        { id: "u1", from: "user", text: t.msg_user_demo },
      ]);
    }, 200);

    // 2) Drop in logs one-by-one
    t.mock_logs.forEach((l, i) => {
      setTimeout(() => {
        setLogs((cur) => [
          { time: nowHHMMSS(), ...l, status: t.log_status_ok },
          ...cur,
        ]);
      }, 700 + i * 350);
    });

    // 3) Thinking indicator
    setTimeout(() => setThinking(true), 700 + t.mock_logs.length * 350 + 200);

    // 4) AI reply with restored highlights
    setTimeout(() => {
      setThinking(false);
      setChat((c) => [
        ...c,
        {
          id: "a1",
          from: "ai",
          text: (
            <>
              <span className="label">{t.ai_reply_lead}</span>
              <span className="restored">
                {lang === "zh"
                  ? "南科三廠 A1 區"
                  : "Tainan Fab 3 Building A1"}
              </span>
              {t.msg_ai_demo[0].replace(
                lang === "zh"
                  ? "南科三廠 A1 區艾司摩爾 DUV 光阻塗佈機（ASML-2026-X1）"
                  : "ASML DUV photoresist coater at Tainan Fab 3 Building A1 (ASML-2026-X1)",
                ""
              )}
              <span className="restored">{t.msg_ai_demo[1]}</span>
              {t.msg_ai_demo[2]}
            </>
          ),
        },
      ]);
      setTokenSaved((v) => +(v + 0.8).toFixed(1));
    }, 700 + t.mock_logs.length * 350 + 1600);
  };

  const resetDemo = () => {
    setChat([]);
    setLogs([]);
    setTokenSaved(42.5);
  };

  const sendInput = () => {
    const text = input.trim();
    if (!text) return;
    const id = "u" + Date.now();
    setChat((c) => [...c, { id, from: "user", text }]);
    setInput("");
    // Generate one dynamic log
    const raw = text.slice(0, Math.min(text.length, 14));
    setLogs((cur) => [
      {
        time: nowHHMMSS(),
        type: lang === "zh" ? "動態偵測" : "Dynamic",
        raw,
        token:
          lang === "zh"
            ? `[使用者輸入_${cur.length + 1}]`
            : `[User input_${cur.length + 1}]`,
        status: t.log_status_ok,
      },
      ...cur,
    ]);
    setThinking(true);
    setTimeout(() => {
      setThinking(false);
      setChat((c) => [
        ...c,
        { id: "a" + Date.now(), from: "ai", text: t.ai_canned },
      ]);
      setTokenSaved((v) => +(v + 0.3).toFixed(1));
    }, 1100);
  };

  const onKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendInput();
    }
  };

  // Risk-distribution percentages (mocked + slight drift from log count)
  const statsData = useMemo(() => {
    const base = [38, 28, 16, 12, 6];
    return t.stats_cats.map((c, i) => ({
      label: c,
      pct: base[i] + (logs.length % 3 === i ? 2 : 0),
    }));
  }, [t.stats_cats, logs.length]);

  return (
    <>
      <div className="demo__topbar">
        <button className="btn btn--primary" onClick={playScenario}>
          {t.btn_play}
        </button>
        <button className="btn btn--ghost-dark" onClick={resetDemo}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 12a9 9 0 1 0 3-6.7L3 8" />
            <path d="M3 3v5h5" />
          </svg>
          {t.btn_reset}
        </button>
        <div style={{
          marginLeft: "auto",
          fontFamily: "var(--ff-mono)",
          fontSize: 16,
          color: "var(--sa-night-fg-3)",
          letterSpacing: "0.1em",
          textTransform: "uppercase",
          display: "flex", gap: 8, alignItems: "center",
        }}>
          <span style={{
            width: 8, height: 8, borderRadius: "50%",
            background: "var(--ok)",
            boxShadow: "0 0 0 4px rgba(61,169,90,.18)",
          }}></span>
          GATEWAY · ONLINE
        </div>
      </div>
      <div className="demo__layout">
      {/* === Employee panel (LEFT) === */}
      <div className="demo-panel chat">
        <div className="demo-panel__head">
          <h3>
            <span className="role">USER</span>
            👤 {t.employee_title}
          </h3>
          <p>{t.employee_sub}</p>
        </div>
        <div className="chat__body" ref={chatBodyRef}>
          {chat.length === 0 && !thinking && (
            <div className="demo__empty">
              {lang === "zh"
                ? "尚未開始對話。點上方按鈕，或直接在下方輸入訊息。"
                : "No conversation yet. Press play, or type below to start."}
            </div>
          )}
          {chat.map((m) => (
            <div key={m.id} className={`chat__msg chat__msg--${m.from}`}>
              {m.text}
            </div>
          ))}
          {thinking && (
            <div className="chat__typing">
              <span></span>
              <span></span>
              <span></span>
            </div>
          )}
        </div>
        <div className="chat__input">
          <textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={onKey}
            placeholder={thinking ? t.sending : t.input_ph}
            disabled={thinking}
          />
          <button
            className="chat__send"
            onClick={sendInput}
            disabled={!input.trim() || thinking}
            aria-label="Send"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M22 2L11 13" />
              <path d="M22 2l-7 20-4-9-9-4 20-7z" />
            </svg>
          </button>
        </div>
      </div>

      {/* === Audit panel (RIGHT) === */}
      <div className="demo-panel">
        <div className="demo-panel__head">
          <h3>
            <span className="role">ADMIN</span>
            🕵️ {t.audit_title}
          </h3>
          <p>{t.audit_sub}</p>
        </div>
        <div className="audit__metrics">
          <div className="audit__metric">
            <div className="audit__metric-l">🛡️ {t.metric_blocked}</div>
            <div className="audit__metric-n">
              {logs.length}
              <span style={{ fontSize: 16, marginLeft: 4 }}>
                {t.metric_blocked_u}
              </span>
            </div>
          </div>
          <div className="audit__metric">
            <div className="audit__metric-l">💰 {t.metric_saved}</div>
            <div className="audit__metric-n">${tokenSaved}</div>
            <div className="audit__metric-d">USD ↑</div>
          </div>
          <div className="audit__metric">
            <div className="audit__metric-l">⚡ {t.metric_latency}</div>
            <div className="audit__metric-n">14 ms</div>
            <div className="audit__metric-d">{t.metric_latency_d}</div>
          </div>
          <div className="audit__metric">
            <div className="audit__metric-l">🧠 {t.metric_vram}</div>
            <div className="audit__metric-n">{t.metric_vram_n}</div>
            <div className="vram-bar">
              <div className="vram-bar__fill" style={{ width: `${vramPct}%` }} />
            </div>
            <div className="audit__metric-d" style={{ color: "var(--sa-night-fg-3)" }}>{t.metric_vram_d}</div>
          </div>
        </div>
        <div className="audit__tabs">
          <button
            className={`audit__tab ${tab === "log" ? "is-active" : ""}`}
            onClick={() => setTab("log")}
          >
            👁️ {t.tab_log}
          </button>
          <button
            className={`audit__tab ${tab === "stats" ? "is-active" : ""}`}
            onClick={() => setTab("stats")}
          >
            📊 {t.tab_stats}
          </button>
          <button
            className={`audit__tab ${tab === "learn" ? "is-active" : ""}`}
            onClick={() => setTab("learn")}
          >
            🔄 {t.tab_learn}
          </button>
        </div>
        <div className="audit__body">
          {tab === "log" && (
            <table className="audit__table">
              <thead>
                <tr>
                  {t.log_cols.map((c) => (
                    <th key={c}>{c}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {logs.length === 0 && (
                  <tr>
                    <td colSpan={5} className="demo__empty" style={{ padding: 60 }}>
                      {lang === "zh"
                        ? "尚無攔截紀錄。"
                        : "No interception logs yet."}
                    </td>
                  </tr>
                )}
                {logs.map((l, i) => (
                  <tr key={i}>
                    <td><span className="time">{l.time}</span></td>
                    <td><span className="type">{l.type}</span></td>
                    <td><span className="raw">{l.raw}</span></td>
                    <td><span className="tok">{l.token}</span></td>
                    <td><span className="status">{l.status}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {tab === "stats" && (
            <div className="audit__chart">
              {statsData.map((s) => (
                <div className="bar" key={s.label}>
                  <div className="bar__label">
                    <span>{s.label}</span>
                    <span className="n">{s.pct}%</span>
                  </div>
                  <div className="bar__track">
                    <div className="bar__fill" style={{ width: `${s.pct * 2.2}%` }} />
                  </div>
                </div>
              ))}
            </div>
          )}
          {tab === "learn" && (
            <LearnTab
              t={t}
              reload={reload}
              setReload={setReload}
              setVramPct={setVramPct}
            />
          )}
        </div>
      </div>
      </div>
    </>
  );
}

// Expose to other Babel scripts
Object.assign(window, { LiveDemo });

/* ===== LearnTab — Continuous Learning panel ===== */
function LearnTab({ t, reload, setReload, setVramPct }) {
  // QLoRA loss curve — synthetic but plausible
  const points = [
    [0, 2.85], [40, 2.42], [80, 2.10], [120, 1.83], [160, 1.62],
    [200, 1.45], [240, 1.31], [280, 1.20], [320, 1.11], [360, 1.04],
    [400, 0.98], [440, 0.93], [480, 0.89], [520, 0.86],
  ];
  const w = 460, h = 110, padL = 32, padR = 8, padT = 10, padB = 24;
  const xs = (x) => padL + (x / 520) * (w - padL - padR);
  const ys = (y) => padT + (1 - (y - 0.6) / (3.0 - 0.6)) * (h - padT - padB);
  const path = points.map(([x, y], i) => `${i === 0 ? "M" : "L"}${xs(x).toFixed(1)},${ys(y).toFixed(1)}`).join(" ");
  const fillPath = path + ` L${xs(520)},${h - padB} L${xs(0)},${h - padB} Z`;
  const last = points[points.length - 1];

  const fireReload = () => {
    if (reload !== "idle") return;
    setReload("running");
    // Simulate background load — temporarily nudge VRAM up to ~94% then back
    setVramPct(94);
    setTimeout(() => setVramPct(91), 1200);
    setTimeout(() => {
      setReload("done");
      setVramPct(90);
    }, 2400);
    setTimeout(() => setReload("idle"), 6000);
  };

  return (
    <div className="learn">
      {/* Data cleansing */}
      <div className="learn__block">
        <div className="learn__head">
          <span>{t.learn_data_t}</span>
          <span className="learn__pct">{t.learn_data_pct}%</span>
        </div>
        <div className="bar__track">
          <div className="bar__fill" style={{ width: `${t.learn_data_pct}%` }} />
        </div>
        <div className="learn__meta">{t.learn_data_meta}</div>
      </div>

      {/* QLoRA loss curve */}
      <div className="learn__block">
        <div className="learn__head">
          <span>{t.learn_loss_t}</span>
          <span className="learn__pct" style={{ color: "var(--ok)" }}>loss {last[1]}</span>
        </div>
        <svg className="learn__chart" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
          <defs>
            <linearGradient id="lossGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="var(--sa-accent)" stopOpacity="0.45" />
              <stop offset="100%" stopColor="var(--sa-accent)" stopOpacity="0" />
            </linearGradient>
          </defs>
          {/* Grid */}
          {[0.5, 1.0, 1.5, 2.0, 2.5, 3.0].map((v) => (
            <g key={v}>
              <line x1={padL} x2={w - padR} y1={ys(v)} y2={ys(v)}
                stroke="rgba(255,255,255,.06)" strokeDasharray="2 4" />
              <text x={padL - 6} y={ys(v) + 3} fontSize="9"
                fill="var(--sa-night-fg-3)" textAnchor="end"
                fontFamily="var(--ff-mono)">{v.toFixed(1)}</text>
            </g>
          ))}
          {/* Fill + line */}
          <path d={fillPath} fill="url(#lossGrad)" />
          <path d={path} fill="none" stroke="var(--sa-accent)" strokeWidth="2"
            strokeLinecap="round" strokeLinejoin="round" />
          {/* Final dot */}
          <circle cx={xs(last[0])} cy={ys(last[1])} r="3.5"
            fill="var(--sa-accent)" stroke="#fff" strokeWidth="1.5" />
          {/* X-axis labels */}
          <text x={padL} y={h - 6} fontSize="9" fill="var(--sa-night-fg-3)"
            fontFamily="var(--ff-mono)">step 0</text>
          <text x={w - padR} y={h - 6} fontSize="9" fill="var(--sa-night-fg-3)"
            fontFamily="var(--ff-mono)" textAnchor="end">step 1,420</text>
        </svg>
        <div className="learn__meta">{t.learn_loss_meta}</div>
      </div>

      {/* Hot reload */}
      <div className="learn__block learn__reload">
        <button
          className={`btn btn--primary learn__reload-btn ${reload === "running" ? "is-running" : ""}`}
          onClick={fireReload}
          disabled={reload !== "idle"}
        >
          {reload === "done" ? t.learn_reload_done : t.learn_reload_btn}
        </button>
        <div className="learn__meta">
          {reload === "running" ? t.learn_reload_running : t.learn_reload_meta}
        </div>
        {reload === "running" && (
          <div className="learn__progress"><div className="learn__progress-fill"></div></div>
        )}
      </div>
    </div>
  );
}
