// Optimal Trade — AI Agent Mission (cinematic multi-phase sourcing experience)
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

const A_PHASES = [
  { key: "understand", label: "Brief", icon: "sparkles" },
  { key: "scan", label: "Scan", icon: "radar" },
  { key: "reach", label: "Reach out", icon: "send" },
  { key: "negotiate", label: "Negotiate", icon: "handshake" },
  { key: "verdict", label: "Verdict", icon: "badge-check" },
];

/* The scripted mission timeline. Each beat renders into the live feed. */
const BEATS = [
  { phase: "understand", t: "agent", typing: true, wait: 1500, text: "Got it. I'll source 50 industrial water pumps — 2.2 kW, CE-certified — within 4 weeks, target $8,000." },
  { phase: "understand", t: "think", wait: 1300, text: "Building a search profile from your reference model…" },

  { phase: "scan", t: "phasediv", wait: 500, label: "Scanning the market", icon: "radar" },
  { phase: "scan", t: "scan", wait: 2900 },
  { phase: "scan", t: "agent", typing: true, wait: 1500, text: "Matched your spec against 38 product lines. Found 1 exact match and 2 close analogs." },
  { phase: "scan", t: "candidates", wait: 2000 },

  { phase: "reach", t: "phasediv", wait: 500, label: "Reaching out", icon: "send" },
  { phase: "reach", t: "agent", typing: true, wait: 1400, text: "Contacting all three supplier agents on your behalf." },
  { phase: "reach", t: "roster", wait: 1600 },

  { phase: "negotiate", t: "phasediv", wait: 500, label: "Live negotiation · Ningbo", icon: "message-square" },
  { phase: "negotiate", t: "supplier", id: "a1", typing: true, wait: 1700, cn: "您好！我们生产 2.2kW 工业水泵，CE 认证齐全，可供 50 台。", text: "Hello! We make 2.2 kW industrial water pumps, fully CE-certified — 50 units available." },
  { phase: "negotiate", t: "doc", id: "a1", wait: 1500, cnName: "产品规格书.pdf", name: "Product spec sheet" },
  { phase: "negotiate", t: "translate", wait: 3000 },
  { phase: "negotiate", t: "agent", typing: true, wait: 1700, text: "Your reference uses a stainless-steel impeller — theirs is cast iron. Can they match it?" },
  { phase: "negotiate", t: "supplier", id: "a1", typing: true, wait: 1500, cn: "不锈钢叶轮可以做，每台加 6 美元，交期 +3 天。", text: "Stainless impeller is possible: +$6 per unit, +3 days lead." },
  { phase: "negotiate", t: "agent", typing: true, wait: 1700, text: "Counter: hold the unit price if we commit to all 50 units and ship within 21 days?" },
  { phase: "negotiate", t: "supplier", id: "a1", typing: true, wait: 1600, cn: "成交！不锈钢叶轮包含在内，168 美元/台，21 天交货。", text: "Deal — stainless impeller included, $168/unit, 21-day lead." },
  { phase: "negotiate", t: "win", wait: 1600, text: "Negotiated the stainless upgrade at no extra cost — saved you ~$300." },
  { phase: "negotiate", t: "think", wait: 1800, text: "Jebel Ali confirmed an exact 1:1 match in stock; Bursa offered a higher-efficiency EU analog." },

  { phase: "verdict", t: "phasediv", wait: 500, label: "Verdict", icon: "badge-check" },
  { phase: "verdict", t: "agent", typing: true, wait: 1500, text: "Done. I negotiated with all three and read every datasheet. Here's my honest take." },
  { phase: "verdict", t: "done", wait: 300 },
];

/* ---------- small pieces ---------- */
function MatchRing({ pct, size = 40 }) {
  const r = (size - 5) / 2, c = 2 * Math.PI * r;
  const col = pct >= 97 ? "var(--ot-success)" : pct >= 92 ? "var(--ot-orange)" : "var(--ot-route-purple)";
  return (
    <span className="ot-match" style={{ width: size, height: size }}>
      <svg width={size} height={size} style={{ position: "absolute", transform: "rotate(-90deg)" }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--ot-gray-200)" strokeWidth="3" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={col} strokeWidth="3" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - pct / 100)} style={{ transition: "stroke-dashoffset 1s var(--ot-ease-move)" }} />
      </svg>
      <span className="pct">{pct}</span>
    </span>
  );
}

function ScanCard() {
  const [n, setN] = useStateA(0);
  useEffectA(() => {
    const target = AGENT_MARKET.scanned, t0 = performance.now(), dur = 2200; let raf;
    const tick = (t) => { const k = Math.min(1, (t - t0) / dur); setN(Math.round(target * (1 - Math.pow(1 - k, 3)))); if (k < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div className="ot-scan">
      <span className="radar"><Icon name="radar" size={92} strokeWidth={1.2} /></span>
      <span style={{ fontSize: 12, color: "rgba(255,255,255,.7)", fontWeight: 600 }}>Verified suppliers analysed</span>
      <div className="num">{fmt(n)}</div>
      <div className="ot-scanbar"><i /></div>
      <div style={{ display: "flex", gap: 6, marginTop: 12, flexWrap: "wrap" }}>
        {AGENT_MARKET.regions.map(r => <span key={r} className="ot-region"><Icon name="map-pin" size={11} />{r}</span>)}
      </div>
    </div>
  );
}

function DocTranslate() {
  const [done, setDone] = useStateA(false);
  useEffectA(() => { const t = setTimeout(() => setDone(true), 1500); return () => clearTimeout(t); }, []);
  if (!done) return (
    <div className="ot-translate">
      <div className="ot-xlate-head"><span className="ot-think sp" style={{ display: "inline-block" }} /><b style={{ fontSize: 13, color: "var(--ot-navy)", fontWeight: 700 }}>Translating documentation</b><span className="ot-cn" style={{ marginLeft: "auto" }}>中文 → EN</span></div>
      <Skeleton h={11} style={{ marginBottom: 7 }} /><Skeleton w="80%" h={11} style={{ marginBottom: 7 }} /><Skeleton w="60%" h={11} />
    </div>
  );
  return (
    <div className="ot-translate">
      <div className="ot-xlate-head"><Icon name="languages" size={16} style={{ color: "var(--ot-orange-deep)" }} /><b style={{ fontSize: 13, color: "var(--ot-navy)", fontWeight: 700 }}>Datasheet translated &amp; analysed</b><span className="ot-anchip ok" style={{ marginLeft: "auto" }}><Icon name="check" size={11} />EN</span></div>
      <KV k="Power" v="2.2 kW · 380V 3-phase" />
      <KV k="Flow rate" v="50 m³/h · head 32 m" />
      <KV k="Certification" v="CE · ISO 9001" />
      <KV k="Impeller" v="Cast iron (orig: stainless)" last />
      <div className="ot-chiprow">
        <span className="ot-anchip ok"><Icon name="check" size={11} />2.2 kW match</span>
        <span className="ot-anchip ok"><Icon name="check" size={11} />CE valid</span>
        <span className="ot-anchip warn"><Icon name="info" size={11} />Impeller differs</span>
      </div>
    </div>
  );
}

function FeedBubble({ side, name, flag, cn, text, agent }) {
  return (
    <div className="ot-bubble" style={{ display: "flex", gap: 9, alignItems: "flex-end", flexDirection: side === "right" ? "row-reverse" : "row" }}>
      {agent
        ? <span style={{ width: 26, height: 26, borderRadius: 8, background: "var(--ot-navy)", color: "var(--ot-orange-300)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="sparkles" size={14} /></span>
        : <Flag code={flag} size={26} />}
      <div style={{ maxWidth: "80%" }}>
        <span style={{ fontSize: 11, color: agent ? "var(--ot-orange-deep)" : "var(--ot-fg-3)", fontWeight: 700, margin: side === "right" ? "0 4px 0 0" : "0 0 0 4px", display: "block", textAlign: side === "right" ? "right" : "left" }}>{name}</span>
        <div style={{ background: agent ? "var(--ot-orange-25)" : "#fff", border: `1px solid ${agent ? "var(--ot-orange-100)" : "var(--ot-gray-200)"}`, borderRadius: side === "right" ? "16px 4px 16px 16px" : "4px 16px 16px 16px", padding: "10px 13px", marginTop: 3 }}>
          {cn && <>
            <div className="ot-cnline">{cn}</div>
            <span className="ot-xtag"><Icon name="languages" size={11} />Auto-translated by agent</span>
          </>}
          <div style={{ fontSize: 13.5, color: "var(--ot-navy)", lineHeight: 1.45 }}>{text}</div>
        </div>
      </div>
    </div>
  );
}

/* ============================== AGENT SCENE ==================================== */
function AgentScene({ app }) {
  const sups = AGENT_SUPPLIERS;
  const supById = id => sups.find(s => s.id === id);
  const [idx, setIdx] = useStateA(0);
  const [stage, setStage] = useStateA("live"); // live | report
  const [elapsed, setElapsed] = useStateA(0);
  const bodyRef = useRefA(null);
  const done = idx >= BEATS.length;

  // drive the timeline
  useEffectA(() => {
    if (done) return;
    const b = BEATS[idx];
    const t = setTimeout(() => setIdx(i => i + 1), b.wait || 1200);
    return () => clearTimeout(t);
  }, [idx]);
  // elapsed timer
  useEffectA(() => { if (done) return; const t = setInterval(() => setElapsed(e => e + 1), 1000); return () => clearInterval(t); }, [done]);
  // auto-scroll
  useEffectA(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [idx]);

  const revealed = BEATS.slice(0, idx);
  const curPhase = (revealed.length ? revealed[revealed.length - 1].phase : "understand");
  const curPhaseIdx = A_PHASES.findIndex(p => p.key === curPhase);
  const nextBeat = !done ? BEATS[idx] : null;
  const showTyping = nextBeat && nextBeat.typing;
  const typingIsAgent = showTyping && nextBeat.t === "agent";
  const typingFlag = showTyping && nextBeat.t === "supplier" ? supById(nextBeat.id).flag : null;
  const best = sups.find(s => s.offer.best);
  const mm = Math.floor(elapsed / 60), ss = String(elapsed % 60).padStart(2, "0");

  if (stage === "report") return <AgentReport app={app} sups={sups} best={best} onBack={() => setStage("live")} />;

  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Optimal Agent" onBack={app.back} right={
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, fontWeight: 700, color: "var(--ot-fg-2)", fontVariantNumeric: "tabular-nums" }}>
          <Icon name="clock" size={14} />{mm}:{ss}
        </span>} />

      {/* live header */}
      <div style={{ padding: "0 20px 12px" }}>
        <div style={{ background: "var(--ot-navy)", borderRadius: "var(--ot-r-lg)", padding: 14, display: "flex", alignItems: "center", gap: 12 }}>
          <span className={"ot-agent-orb" + (done ? "" : " live")}><Icon name="sparkles" size={22} /></span>
          <div style={{ flex: 1 }}>
            <b style={{ fontWeight: 700, fontSize: 14.5, color: "#fff", display: "block" }}>Optimal Agent</b>
            <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.7)" }}>{done ? "Mission complete · 3 offers secured" : (A_PHASES[curPhaseIdx] && A_PHASES[curPhaseIdx].label) + " · working for you…"}</span>
          </div>
        </div>
        {/* phase rail */}
        <div className="ot-rail" style={{ marginTop: 12 }}>
          {A_PHASES.map((p, i) => (
            <div key={p.key} className={"ph" + (i === curPhaseIdx ? " active" : i < curPhaseIdx ? " done" : "")}>
              <span className="pdot"><Icon name={i < curPhaseIdx ? "check" : p.icon} size={14} strokeWidth={i < curPhaseIdx ? 3 : 2} /></span>
              <span className="plabel">{p.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* feed */}
      <div ref={bodyRef} className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 4, display: "flex", flexDirection: "column", gap: 12 }}>
          {revealed.map((b, i) => {
            if (b.t === "agent") return <FeedBubble key={i} agent name="Optimal Agent" text={b.text} />;
            if (b.t === "supplier") { const s = supById(b.id); return <FeedBubble key={i} flag={s.flag} name={s.short + " · agent"} cn={b.cn} text={b.text} />; }
            if (b.t === "think") return <div key={i} className="ot-think"><span className="sp" /><span>{b.text}</span></div>;
            if (b.t === "phasediv") return <div key={i} className="ot-phase-div"><span className="l" /><span className="t"><Icon name={b.icon} size={12} />{b.label}</span><span className="l" /></div>;
            if (b.t === "scan") return <ScanCard key={i} />;
            if (b.t === "candidates") return (
              <div key={i} style={{ display: "flex", flexDirection: "column", gap: 8 }} className="ot-stagger">
                {sups.map(s => (
                  <div key={s.id} className="ot-cand">
                    <MatchRing pct={s.match} />
                    <Flag code={s.flag} size={30} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <b style={{ fontWeight: 700, fontSize: 13.5, color: "var(--ot-navy)", display: "block" }}>{s.name}</b>
                      <span style={{ fontSize: 11.5, color: "var(--ot-fg-2)" }}>{s.verdictKind === "exact" ? "Exact match" : "Close analog"} · ★ {s.rating}</span>
                    </div>
                  </div>
                ))}
              </div>
            );
            if (b.t === "roster") return (
              <div key={i} className="ot-stagger" style={{ display: "flex", gap: 8 }}>
                {sups.map(s => (
                  <div key={s.id} style={{ flex: 1, textAlign: "center", padding: "11px 6px", borderRadius: "var(--ot-r-md)", background: "var(--ot-gray-50)", border: "1px solid var(--ot-gray-200)" }}>
                    <span style={{ position: "relative", display: "inline-block" }}><Flag code={s.flag} size={32} /><span style={{ position: "absolute", right: -2, bottom: -1, width: 11, height: 11, borderRadius: "50%", background: "var(--ot-success)", border: "2px solid #fff" }} /></span>
                    <span style={{ display: "block", fontSize: 10.5, fontWeight: 700, color: "var(--ot-navy)", marginTop: 5 }}>{s.short}</span>
                    <span style={{ fontSize: 9.5, color: "var(--ot-success)", fontWeight: 700 }}>online</span>
                  </div>
                ))}
              </div>
            );
            if (b.t === "doc") { const s = supById(b.id); return (
              <div key={i} className="ot-bubble" style={{ display: "flex", gap: 9 }}>
                <Flag code={s.flag} size={26} style={{ alignSelf: "flex-end" }} />
                <div className="ot-doc" style={{ flex: 1 }}>
                  <span className="fic"><Icon name="file-text" size={18} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <b style={{ fontWeight: 700, fontSize: 13, color: "var(--ot-navy)", display: "block" }}>{b.cnName}</b>
                    <span style={{ fontSize: 11.5, color: "var(--ot-fg-2)" }}>{b.name} · PDF · 1.2 MB</span>
                  </div>
                  <span className="ot-cn">中文</span>
                </div>
              </div>
            ); }
            if (b.t === "translate") return <DocTranslate key={i} />;
            if (b.t === "win") return <div key={i} className="ot-win"><span className="wic"><Icon name="handshake" size={18} /></span><span style={{ fontSize: 13, color: "var(--ot-navy)", fontWeight: 600, lineHeight: 1.4 }}>{b.text}</span></div>;
            return null;
          })}

          {/* typing indicator */}
          {showTyping && (
            <div className="ot-bubble" style={{ display: "flex", gap: 9, alignItems: "flex-end" }}>
              {typingIsAgent
                ? <span style={{ width: 26, height: 26, borderRadius: 8, background: "var(--ot-navy)", color: "var(--ot-orange-300)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="sparkles" size={14} /></span>
                : <Flag code={typingFlag} size={26} />}
              <div className="ot-typing" style={{ display: "flex", gap: 4, padding: "11px 14px", background: "#fff", border: "1px solid var(--ot-gray-200)", borderRadius: "4px 16px 16px 16px" }}><i /><i /><i /></div>
            </div>
          )}
        </div>
      </div>

      {/* footer CTA */}
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        {done
          ? <Button variant="primary" icon="git-compare" onClick={() => setStage("report")}>See the agent's verdict</Button>
          : <button onClick={() => setIdx(BEATS.length)} style={{ width: "100%", background: "none", border: "none", color: "var(--ot-fg-2)", fontWeight: 700, fontSize: 14, cursor: "pointer", fontFamily: "var(--ot-font-body)", padding: "6px" }}>Skip to results ›</button>}
      </div>
    </div>
  );
}

/* ============================== AGENT REPORT (verdict) ========================= */
function AgentReport({ app, sups, best, onBack }) {
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Agent verdict" onBack={onBack} />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 2 }}>
          {/* summary banner */}
          <div style={{ background: "var(--ot-grad-hero)", borderRadius: "var(--ot-r-xl)", padding: 18, color: "#fff", marginBottom: 18, position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", right: -18, bottom: -22, opacity: .2 }}><Icon name="badge-check" size={120} strokeWidth={1.3} /></div>
            <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase", color: "rgba(255,255,255,.85)" }}>Mission complete</span>
            <p style={{ fontSize: 14.5, lineHeight: 1.5, margin: "8px 0 0", fontWeight: 500, maxWidth: 290 }}>
              I reached 3 verified suppliers, translated their datasheets from Chinese, and negotiated terms. One is a true 1:1 match; two are close analogs. My pick balances price, lead time and spec.
            </p>
          </div>

          <span className="ot-eyebrow" style={{ font: "var(--ot-caption)", fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ot-fg-3)", display: "block", marginBottom: 10 }}>3 offers ranked</span>

          <div className="ot-stagger" style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            {sups.map(s => (
              <div key={s.id} className="ot-card" style={{ padding: 15, border: s.offer.best ? "1.5px solid var(--ot-orange)" : "1px solid var(--ot-gray-200)", boxShadow: s.offer.best ? "var(--ot-shadow-md)" : "var(--ot-shadow-sm)", position: "relative" }}>
                {s.offer.best && <span style={{ position: "absolute", top: -10, left: 15, background: "var(--ot-orange)", color: "#fff", fontWeight: 700, fontSize: 11, padding: "3px 10px", borderRadius: 999, display: "inline-flex", gap: 4, alignItems: "center" }}><Icon name="sparkles" size={11} />Agent pick</span>}
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <MatchRing pct={s.match} size={42} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <b style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ot-navy)", display: "block" }}>{s.name}</b>
                    <span style={{ fontSize: 12, color: "var(--ot-fg-2)", display: "inline-flex", alignItems: "center", gap: 3 }}><Flag code={s.flag} size={13} /> {s.offer.terms} · ★ {s.rating}</span>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    {s.offer.was > s.offer.total && <div style={{ fontSize: 11, color: "var(--ot-fg-3)", textDecoration: "line-through" }}>{money("$", s.offer.was)}</div>}
                    <div className="ot-num" style={{ fontSize: 18, color: "var(--ot-navy)" }}>{money("$", s.offer.total)}</div>
                  </div>
                </div>

                {/* verdict label */}
                <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 12 }}>
                  {s.verdictKind === "exact"
                    ? <Badge kind="paid" icon="check-check">1:1 match to reference</Badge>
                    : <Badge kind="locked" icon="git-compare">{s.verdict}</Badge>}
                </div>
                <p style={{ fontSize: 12.5, color: "var(--ot-fg-2)", margin: "9px 0 0", lineHeight: 1.45 }}>{s.nuance}</p>

                <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                  <Metric label="Per unit" value={"$" + s.offer.unit} />
                  <Metric label="Lead time" value={s.offer.lead + "d"} good={s.offer.best} />
                  <Metric label="MOQ" value={s.offer.moq} />
                </div>
                {s.id === "a1" && <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 11, fontSize: 11.5, color: "var(--ot-orange-deep)", fontWeight: 700 }}><Icon name="file-check" size={13} />Datasheet translated &amp; verified by agent</div>}
              </div>
            ))}
          </div>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        <Button variant="primary" icon="badge-check" onClick={() => app.acceptOffer(best)}>Accept {best.short} · {money("$", best.offer.total)}</Button>
        <p style={{ textAlign: "center", fontSize: 11.5, color: "var(--ot-fg-3)", marginTop: 10, display: "flex", alignItems: "center", justifyContent: "center", gap: 5 }}><Icon name="shield" size={13} style={{ color: "var(--ot-success)" }} />No payment until you accept · protected by mandate</p>
      </div>
    </div>
  );
}
function Metric({ label, value, good }) {
  return <div style={{ flex: 1, background: good ? "var(--ot-success-bg)" : "var(--ot-gray-50)", borderRadius: 10, padding: "9px 6px", textAlign: "center" }}>
    <div className="ot-num" style={{ fontSize: 15, color: good ? "var(--ot-success)" : "var(--ot-navy)" }}>{value}</div>
    <span style={{ fontSize: 10.5, color: "var(--ot-fg-2)", fontWeight: 600 }}>{label}</span>
  </div>;
}

Object.assign(window, { AgentScene, AgentReport, Metric, MatchRing });
