// Optimal Trade — Screens 3: Tracking, Activity (history), Operator Console
const { useState: useState3 } = React;

/* ============================== SHIPMENT TRACKING ============================== */
function Tracking({ app, params }) {
  const w = app.world;
  const c = (params && params.contract) || w.contracts.find(x => x.status === "transit") || w.contracts[0];
  const stageIdx = w.shipStage;
  const stages = SHIPMENT_STAGES;
  const pct = Math.min(100, (stageIdx / (stages.length - 1)) * 100);
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Track shipment" onBack={app.fromTab ? null : app.back} right={<button className="ot-iconbtn"><Icon name="external-link" /></button>} />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 4 }}>
          {/* summary */}
          <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: -20, bottom: -28, opacity: .22 }}><Icon name="ship" size={130} strokeWidth={1.4} /></div>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Flag code={c.flag} size={36} />
              <div style={{ flex: 1 }}>
                <b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 15.5 }}>{c.id}</b>
                <span style={{ display: "block", fontSize: 12.5, color: "rgba(255,255,255,.8)" }}>{c.supplier}</span>
              </div>
            </div>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,.9)", marginTop: 12 }}>{c.goods}</div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 6 }}>
              <span className="ot-num" style={{ fontSize: 22 }}>{money(c.sym || "$", c.amount)}</span>
              <Badge kind="locked" icon={stages[stageIdx].icon}>{stages[stageIdx].label}</Badge>
            </div>
          </div>

          {/* progress bar */}
          <div style={{ height: 6, borderRadius: 999, background: "var(--ot-gray-200)", overflow: "hidden", marginBottom: 20 }}>
            <div style={{ width: pct + "%", height: "100%", background: "var(--ot-grad-hero)", transition: "width .5s cubic-bezier(.2,.8,.2,1)" }} />
          </div>

          {/* timeline */}
          <div style={{ position: "relative", paddingLeft: 4 }}>
            {stages.map((st, i) => {
              const done = i < stageIdx, active = i === stageIdx;
              return (
                <div key={st.key} style={{ display: "flex", gap: 14, position: "relative", paddingBottom: i === stages.length - 1 ? 0 : 22 }}>
                  {i < stages.length - 1 && <span style={{ position: "absolute", left: 17, top: 36, bottom: 0, width: 2, background: done ? "var(--ot-orange)" : "var(--ot-gray-200)" }} />}
                  <span style={{ width: 36, height: 36, borderRadius: "50%", flex: "none", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1,
                    background: done ? "var(--ot-orange)" : active ? "#fff" : "var(--ot-gray-100)",
                    border: active ? "2px solid var(--ot-orange)" : "none",
                    color: done ? "#fff" : active ? "var(--ot-orange-deep)" : "var(--ot-gray-400)",
                    boxShadow: active ? "0 0 0 5px var(--ot-orange-50)" : "none" }}>
                    <Icon name={done ? "check" : st.icon} size={17} strokeWidth={done ? 3 : 2} />
                  </span>
                  <div style={{ flex: 1, paddingTop: 2 }}>
                    <b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 14.5, color: done || active ? "var(--ot-navy)" : "var(--ot-fg-3)" }}>{st.label}</b>
                    <div style={{ display: "flex", justifyContent: "space-between", marginTop: 2 }}>
                      <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{st.place}</span>
                      <span style={{ fontSize: 12, color: active ? "var(--ot-orange-deep)" : "var(--ot-fg-3)", fontWeight: active ? 700 : 500 }}>{st.ts}</span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      {stageIdx < stages.length - 1 && (
        <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
          <button className="ot-btn ot-btn-outline" onClick={app.advanceShipment}><Icon name="refresh-cw" size={17} />Simulate next update</button>
        </div>
      )}
    </div>
  );
}

/* ============================== ACTIVITY / HISTORY ============================= */
function Activity({ app }) {
  const w = app.world;
  const [filter, setFilter] = useState3("all");
  const tabs = [["all", "All"], ["invoice", "Payments"], ["topup", "Top ups"], ["convert", "Conversions"]];
  const list = w.txs.filter(t => filter === "all" || t.type === filter);
  const iconFor = { invoice: "ship", topup: "arrow-down-left", convert: "arrow-right-left" };
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Activity" right={<button className="ot-iconbtn"><Icon name="filter" /></button>} />
      <div style={{ display: "flex", gap: 8, overflowX: "auto", padding: "4px 20px 12px" }}>
        {tabs.map(([id, label]) => (
          <button key={id} onClick={() => setFilter(id)} style={{ flex: "none", padding: "7px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12.5, background: filter === id ? "var(--ot-navy)" : "var(--ot-gray-100)", color: filter === id ? "#fff" : "var(--ot-fg-2)" }}>{label}</button>
        ))}
      </div>
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 0 }}>
          <div className="ot-card">
            {list.map(t => (
              <Row key={t.id} icon={iconFor[t.type]} title={t.title} sub={`${t.date} · ${t.sub}`}
                right={<div style={{ textAlign: "right", marginRight: 6 }}>
                  <div className="ot-num" style={{ fontSize: 14.5, color: t.amount < 0 ? "var(--ot-error)" : "var(--ot-success)" }}>
                    {t.amount < 0 ? "−" : "+"}{money(t.sym, Math.abs(t.amount), t.sym === "$" ? 0 : 0)}
                  </div>
                  <div style={{ marginTop: 3 }}><StatusPill status={t.status} /></div>
                </div>} />
            ))}
          </div>
          {list.length === 0 && <p style={{ textAlign: "center", color: "var(--ot-fg-3)", marginTop: 40, fontSize: 14 }}>No transactions yet.</p>}
        </div>
      </div>
    </div>
  );
}

/* ============================== OPERATOR CONSOLE (desktop side panel) ========== */
function OperatorConsole({ app }) {
  const w = app.world;
  const stage = SHIPMENT_STAGES[w.shipStage];
  const pending = w.contracts.filter(c => c.status === "pending");
  return (
    <div style={{ width: 320, flex: "none", background: "#13161d", borderRadius: 22, padding: 20, color: "#fff", boxShadow: "0 30px 80px rgba(0,0,0,.5)", border: "1px solid rgba(255,255,255,.08)", alignSelf: "flex-start" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
        <span style={{ width: 34, height: 34, borderRadius: 10, background: "rgba(255,92,0,.16)", color: "var(--ot-orange)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="monitor" size={18} /></span>
        <div>
          <b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 15 }}>Operator Console</b>
          <span style={{ display: "block", fontSize: 11, color: "rgba(255,255,255,.45)" }}>Demo payment &amp; status control</span>
        </div>
      </div>
      <p style={{ fontSize: 11.5, color: "rgba(255,255,255,.4)", lineHeight: 1.5, margin: "10px 0 16px" }}>
        Mock back-office. Actions here drive the live app on the left — advance shipments, approve or decline payments.
      </p>

      <div className="ocard">
        <span className="oeyebrow">Active shipment</span>
        <div style={{ display: "flex", alignItems: "center", gap: 9, margin: "8px 0 12px" }}>
          <span style={{ width: 30, height: 30, borderRadius: 9, background: "rgba(255,92,0,.16)", color: "var(--ot-orange)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={stage.icon} size={16} /></span>
          <div style={{ flex: 1 }}><b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 13 }}>{stage.label}</b><span style={{ display: "block", fontSize: 11, color: "rgba(255,255,255,.45)" }}>Stage {w.shipStage + 1} / {SHIPMENT_STAGES.length}</span></div>
        </div>
        <button className="obtn primary" onClick={app.advanceShipment} disabled={w.shipStage >= SHIPMENT_STAGES.length - 1}>
          <Icon name="arrow-up-right" size={15} />{w.shipStage >= SHIPMENT_STAGES.length - 1 ? "Delivered" : "Advance stage"}
        </button>
      </div>

      <div className="ocard">
        <span className="oeyebrow">Pending payments ({pending.length})</span>
        {pending.length === 0 && <p style={{ fontSize: 12, color: "rgba(255,255,255,.4)", margin: "10px 0 2px" }}>No payments awaiting action.</p>}
        {pending.map(c => (
          <div key={c.id} style={{ marginTop: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Flag code={c.flag} size={26} />
              <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12.5, display: "block", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.supplier}</b><span style={{ fontSize: 11, color: "rgba(255,255,255,.45)" }}>{c.id} · {money(c.sym || "$", c.amount)}</span></div>
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 9 }}>
              <button className="obtn primary" style={{ flex: 1 }} onClick={() => app.setContractStatus(c.id, "transit")}><Icon name="check" size={14} />Approve</button>
              <button className="obtn ghost" style={{ flex: 1 }} onClick={() => app.setContractStatus(c.id, "declined")}><Icon name="x" size={14} />Decline</button>
            </div>
          </div>
        ))}
      </div>

      <button className="obtn outline" style={{ width: "100%", marginTop: 4 }} onClick={app.resetDemo}><Icon name="refresh-cw" size={14} />Reset demo</button>

      <style dangerouslySetInnerHTML={{ __html: `
        .ocard{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:14px;padding:14px;margin-bottom:12px;}
        .oeyebrow{font-family:var(--ot-font-body);font-weight:600;font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.5);}
        .obtn{display:inline-flex;align-items:center;justify-content:center;gap:6px;font-family:var(--ot-font-body);font-weight:600;font-size:12.5px;border-radius:10px;border:none;cursor:pointer;padding:10px 12px;transition:transform .1s,opacity .15s;}
        .obtn:active{transform:scale(.97);}
        .obtn:disabled{opacity:.4;cursor:not-allowed;}
        .obtn.primary{background:var(--ot-orange);color:#fff;}
        .obtn.ghost{background:rgba(255,255,255,.1);color:#fff;}
        .obtn.outline{background:transparent;color:rgba(255,255,255,.7);border:1px solid rgba(255,255,255,.18);}
      ` }} />
    </div>
  );
}

Object.assign(window, { Tracking, Activity, OperatorConsole });
