// Optimal Trade — Screens 1: Login, Dashboard, Wallet, Convert, TopUp
const { useState, useEffect, useRef } = React;

/* ============================== LOGIN / DEMO SELECT ============================== */
function LoginScreen({ app }) {
  return (
    <div className="ot-screen" style={{ background: "var(--ot-navy)" }}>
      <StatusBar dark />
      <div style={{
        position: "absolute", inset: 0, opacity: 0.5,
        background: "radial-gradient(700px 420px at 80% -5%, rgba(255,92,0,.55), transparent 60%), radial-gradient(600px 400px at -10% 105%, rgba(72,66,200,.5), transparent 55%)"
      }} />
      <div className="ot-body" style={{ position: "relative", zIndex: 2 }}>
        <div className="ot-pad" style={{ display: "flex", flexDirection: "column", minHeight: "100%", paddingTop: 24 }}>
          <Logo height={30} variant="white" />
          <div style={{ marginTop: 56, marginBottom: 30 }}>
            <h1 style={{ font: "var(--ot-display)", fontSize: 38, lineHeight: 1.05, letterSpacing: "-.03em", color: "#fff", margin: 0, fontFamily: "var(--ot-font-display)", fontWeight: 700 }}>
              Move money,<br />move goods.
            </h1>
            <p style={{ font: "var(--ot-body-lg)", color: "rgba(255,255,255,.7)", marginTop: 14, maxWidth: 300 }}>
              Pay international suppliers in your local currency. Convert, contract and track — in one app.
            </p>
          </div>
          <span className="ot-eyebrow" style={{ color: "rgba(255,255,255,.5)", marginBottom: 12, display: "block" }}>Choose a demo account</span>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {DEMO_ACCOUNTS.map(a => (
              <button key={a.id} onClick={() => app.login(a)} style={{
                display: "flex", alignItems: "center", gap: 13, background: "rgba(255,255,255,.08)",
                border: "1px solid rgba(255,255,255,.14)", borderRadius: "var(--ot-r-lg)", padding: "13px 14px",
                cursor: "pointer", textAlign: "left", color: "#fff", backdropFilter: "blur(6px)"
              }}>
                <Flag code={a.flag} size={42} />
                <span style={{ flex: 1 }}>
                  <b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 15, display: "block" }}>{a.company}</b>
                  <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.65)" }}>{a.name} · {a.country}</span>
                </span>
                <span style={{ textAlign: "right" }}>
                  <span className="ot-num" style={{ color: "#fff", fontSize: 14, display: "block" }}>{money(a.sym, a.balance)}</span>
                  <Icon name="arrow-right-left" size={15} style={{ color: "var(--ot-orange-300)", marginTop: 3 }} />
                </span>
              </button>
            ))}
          </div>
          <div style={{ marginTop: "auto", paddingTop: 22, display: "flex", alignItems: "center", gap: 8, justifyContent: "center" }}>
            <Icon name="shield-check" size={15} style={{ color: "rgba(255,255,255,.5)" }} />
            <span style={{ fontSize: 12, color: "rgba(255,255,255,.5)" }}>Demo prototype · all data is mocked</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================== DASHBOARD ======================================== */
function Dashboard({ app }) {
  const a = app.account, w = app.world;
  const quick = [
    { icon: "arrow-right-left", label: "Convert", go: () => app.navigate("convert") },
    { icon: "file-text", label: "Pay invoice", go: () => app.navigate("contract") },
    { icon: "store", label: "Suppliers", go: () => app.setTab("suppliers") },
    { icon: "calculator", label: "Logistics", go: () => app.navigate("logistics") },
  ];
  return (
    <div className="ot-screen">
      <StatusBar />
      <div className="ot-body">
        <div className="ot-pad">
          {/* header */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "6px 0 16px" }}>
            <Flag code={a.flag} size={40} />
            <div style={{ flex: 1 }}>
              <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)", fontWeight: 600 }}>Welcome back</span>
              <b style={{ display: "block", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 16, color: "var(--ot-navy)", letterSpacing: "-.01em" }}>{a.company}</b>
            </div>
            <button className="ot-iconbtn"><Icon name="bell" /></button>
          </div>

          {/* balance card */}
          <div style={{ background: "var(--ot-grad-hero)", borderRadius: "var(--ot-r-xl)", padding: 20, color: "#fff", boxShadow: "var(--ot-shadow-orange)", position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", right: -30, top: -30, width: 150, height: 150, borderRadius: "50%", background: "rgba(255,255,255,.10)" }} />
            <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.85)", fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase" }}>Wallet · {a.ccy}</span>
            <div className="ot-num" style={{ fontSize: 38, color: "#fff", margin: "8px 0 16px" }}>{money(a.sym, w.balance)}</div>
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={() => app.openTopup()} style={glassBtn}><Icon name="plus" size={16} />Top up</button>
              <button onClick={() => app.navigate("convert")} style={glassBtn}><Icon name="arrow-right-left" size={16} />Convert</button>
            </div>
          </div>

          {/* FX rates */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "22px 0 10px" }}>
            <span className="ot-eyebrow">Live rates</span>
            <span style={{ fontSize: 11.5, color: "var(--ot-fg-3)", display: "flex", alignItems: "center", gap: 4 }}><Icon name="refresh-cw" size={12} />2 min ago</span>
          </div>
          <div style={{ display: "flex", gap: 10, overflowX: "auto", margin: "0 -20px", padding: "0 20px 4px" }}>
            {RATE_PAIRS.map(r => (
              <div key={r.pair} className="ot-card flat" style={{ flex: "none", width: 124, padding: 13 }}>
                <span style={{ fontSize: 11.5, color: "var(--ot-fg-2)", fontWeight: 600 }}>{r.pair}</span>
                <div className="ot-num" style={{ fontSize: 18, color: "var(--ot-navy)", margin: "5px 0 3px" }}>{fmt(r.rate, 2)}</div>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: r.trend >= 0 ? "var(--ot-success)" : "var(--ot-error)" }}>
                  {r.trend >= 0 ? "▲" : "▼"} {Math.abs(r.trend)}%
                </span>
              </div>
            ))}
          </div>

          {/* quick actions */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 8, marginTop: 18 }}>
            {quick.map(q => (
              <button key={q.label} onClick={q.go} style={{ background: "#fff", border: "1px solid var(--ot-gray-200)", borderRadius: "var(--ot-r-md)", padding: "14px 4px", display: "flex", flexDirection: "column", alignItems: "center", gap: 7, cursor: "pointer" }}>
                <span style={{ width: 38, height: 38, borderRadius: 11, background: "var(--ot-orange-50)", color: "var(--ot-orange-deep)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={q.icon} size={19} /></span>
                <span style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 11, color: "var(--ot-navy)" }}>{q.label}</span>
              </button>
            ))}
          </div>

          {/* active contracts */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "24px 0 10px" }}>
            <span className="ot-eyebrow">Active contracts</span>
            <span onClick={() => app.setTab("activity")} style={{ fontSize: 12.5, color: "var(--ot-orange-deep)", fontWeight: 700, cursor: "pointer" }}>See all</span>
          </div>
          <div className="ot-card">
            {w.contracts.map((c, i) => (
              <Row key={c.id}
                iconEl={<Flag code={c.flag} size={42} />}
                title={c.supplier}
                sub={`${c.id} · ${c.goods}`}
                right={<div style={{ textAlign: "right", marginRight: 6 }}>
                  <div className="ot-num" style={{ fontSize: 14, color: "var(--ot-navy)" }}>{money(c.sym || "$", c.amount)}</div>
                  <div style={{ marginTop: 4 }}><StatusPill status={c.status} /></div>
                </div>}
                onClick={() => app.navigate(c.status === "pending" ? "payconfirm" : "tracking", { contract: c })}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
const glassBtn = { flex: 1, background: "rgba(255,255,255,.2)", border: "none", color: "#fff", borderRadius: "var(--ot-r-sm)", padding: "11px", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 13.5, display: "flex", alignItems: "center", justifyContent: "center", gap: 6, cursor: "pointer" };

function StatusPill({ status }) {
  const map = {
    paid: { kind: "paid", icon: "check", label: "Paid" },
    pending: { kind: "pending", dot: true, label: "Pending" },
    transit: { kind: "transit", icon: "ship", label: "In transit" },
    delivered: { kind: "paid", icon: "check-check", label: "Delivered" },
    declined: { kind: "error", icon: "x", label: "Declined" },
  };
  const m = map[status] || map.pending;
  return <Badge kind={m.kind} icon={m.icon} dot={m.dot}>{m.label}</Badge>;
}

/* ============================== WALLET ========================================== */
function Wallet({ app }) {
  const a = app.account, w = app.world;
  const otherCcy = [
    { ccy: "USD", sym: "$", flag: "us", bal: w.usdBalance },
    { ccy: "CNY", sym: "\u00A5", flag: "cn", bal: w.cnyBalance },
  ];
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Wallet" right={<button className="ot-iconbtn"><Icon name="scan-line" /></button>} />
      <div className="ot-body">
        <div className="ot-pad">
          <div style={{ background: "var(--ot-navy)", borderRadius: "var(--ot-r-xl)", padding: 20, color: "#fff", position: "relative", overflow: "hidden" }}>
            <TMark size={26} />
            <span style={{ display: "block", fontSize: 12, color: "rgba(255,255,255,.7)", fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase", marginTop: 14 }}>Local balance · {a.ccy}</span>
            <div className="ot-num" style={{ fontSize: 36, color: "#fff", margin: "6px 0 14px" }}>{money(a.sym, w.balance)}</div>
            <Button variant="primary" icon="plus" onClick={() => app.openTopup()}>Top up wallet</Button>
          </div>

          <span className="ot-eyebrow" style={{ display: "block", margin: "22px 0 10px" }}>Foreign currency pockets</span>
          <div className="ot-card">
            {otherCcy.map(c => (
              <Row key={c.ccy} iconEl={<Flag code={c.flag} size={42} />}
                title={`${c.ccy} pocket`} sub="For supplier payments"
                right={<span className="ot-num" style={{ fontSize: 15, color: "var(--ot-navy)", marginRight: 4 }}>{money(c.sym, c.bal, c.ccy === "USD" ? 2 : 0)}</span>} />
            ))}
          </div>

          <span className="ot-eyebrow" style={{ display: "block", margin: "22px 0 10px" }}>Add money</span>
          <div className="ot-card">
            {TOPUP_METHODS.map(m => (
              <Row key={m.id} icon={m.icon} title={m.label} sub={m.sub} chevron onClick={() => app.openTopup(m.id)} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================== TOP UP (sheet) =================================== */
function TopupSheet({ app, initial }) {
  const a = app.account;
  const [method, setMethod] = useState(initial || "momo");
  const [amount, setAmount] = useState(2000000);
  const [stage, setStage] = useState("form"); // form | done
  const presets = [500000, 1000000, 2000000, 5000000];
  const confirm = () => {
    app.deposit(amount, TOPUP_METHODS.find(m => m.id === method).label);
    setStage("done");
  };
  return (
    <div className="ot-sheet-scrim" onClick={app.closeTopup}>
      <div className="ot-sheet" onClick={e => e.stopPropagation()}>
        <div className="grab" />
        {stage === "form" ? <>
          <h2 style={{ font: "var(--ot-h3)", margin: "0 0 4px" }}>Top up wallet</h2>
          <p style={{ font: "var(--ot-body-sm)", color: "var(--ot-fg-2)", margin: "0 0 16px" }}>Add {a.ccy} via your preferred method.</p>
          <div style={{ display: "flex", flexDirection: "column", gap: 9, marginBottom: 18 }}>
            {TOPUP_METHODS.map(m => (
              <button key={m.id} onClick={() => setMethod(m.id)} style={{
                display: "flex", alignItems: "center", gap: 12, padding: "13px 14px", cursor: "pointer", textAlign: "left",
                borderRadius: "var(--ot-r-md)", border: `1.5px solid ${method === m.id ? "var(--ot-orange)" : "var(--ot-gray-200)"}`,
                background: method === m.id ? "var(--ot-orange-25)" : "#fff"
              }}>
                <span style={{ width: 40, height: 40, borderRadius: 12, background: method === m.id ? "var(--ot-orange)" : "var(--ot-gray-100)", color: method === m.id ? "#fff" : "var(--ot-navy)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={m.icon} size={20} /></span>
                <span style={{ flex: 1 }}><b style={{ display: "block", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 14.5 }}>{m.label}</b><span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{m.sub}</span></span>
                <span style={{ width: 20, height: 20, borderRadius: "50%", border: `2px solid ${method === m.id ? "var(--ot-orange)" : "var(--ot-gray-300)"}`, display: "flex", alignItems: "center", justifyContent: "center" }}>{method === m.id && <span style={{ width: 10, height: 10, borderRadius: "50%", background: "var(--ot-orange)" }} />}</span>
              </button>
            ))}
          </div>
          <div className="ot-field" style={{ marginBottom: 12 }}>
            <label>Amount ({a.ccy})</label>
            <div className="ot-input"><span style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600 }}>{a.sym}</span><input value={fmt(amount)} onChange={e => setAmount(+e.target.value.replace(/[^0-9]/g, "") || 0)} /></div>
          </div>
          <div style={{ display: "flex", gap: 8, marginBottom: 20 }}>
            {presets.map(p => <button key={p} onClick={() => setAmount(p)} style={{ flex: 1, padding: "8px 0", borderRadius: 999, border: "1px solid var(--ot-gray-200)", background: amount === p ? "var(--ot-navy)" : "#fff", color: amount === p ? "#fff" : "var(--ot-navy)", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12, cursor: "pointer" }}>{p >= 1e6 ? (p / 1e6) + "M" : (p / 1e3) + "k"}</button>)}
          </div>
          <Button variant="primary" onClick={confirm}>Add {money(a.sym, amount)}</Button>
        </> : (
          <div style={{ textAlign: "center", padding: "10px 0 6px" }}>
            <SuccessMark />
            <h2 style={{ font: "var(--ot-h3)", margin: "16px 0 6px" }}>Top up complete</h2>
            <p style={{ font: "var(--ot-body)", color: "var(--ot-fg-2)", margin: "0 0 20px" }}>{money(a.sym, amount)} added to your {a.ccy} wallet.</p>
            <Button variant="dark" onClick={app.closeTopup}>Done</Button>
          </div>
        )}
      </div>
    </div>
  );
}

function SuccessMark() {
  return <span style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--ot-success-bg)", color: "var(--ot-success)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="circle-check" size={40} strokeWidth={2.2} /></span>;
}

/* ============================== CONVERT ========================================= */
function Convert({ app }) {
  const a = app.account, w = app.world;
  const [target, setTarget] = useState(CONVERT_TARGETS[0]);
  const [amount, setAmount] = useState(2000000);
  const [stage, setStage] = useState("form"); // form | done
  const [pickerOpen, setPickerOpen] = useState(false);

  const feeAmt = amount * (target.fee / 100);
  const net = amount - feeAmt;
  const out = net / target.rate;
  const confirm = () => { app.convert(amount, target, out); setStage("done"); };

  if (stage === "done") return (
    <div className="ot-screen">
      <StatusBar />
      <div className="ot-body"><div className="ot-pad" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "100%", textAlign: "center" }}>
        <SuccessMark />
        <h1 style={{ font: "var(--ot-h2)", margin: "18px 0 6px" }}>Converted</h1>
        <p style={{ font: "var(--ot-body)", color: "var(--ot-fg-2)", margin: 0 }}>You exchanged</p>
        <div className="ot-num" style={{ fontSize: 30, color: "var(--ot-navy)", margin: "10px 0" }}>{money(a.sym, amount)} → {money(target.sym, out, 2)}</div>
        <div className="ot-card flat" style={{ width: "100%", padding: 14, margin: "12px 0 22px", textAlign: "left" }}>
          <KV k="Rate" v={`1 ${target.ccy} = ${fmt(target.rate, 2)} ${a.ccy}`} />
          <KV k="Fee" v={`${target.fee}% · ${money(a.sym, feeAmt)}`} />
          <KV k={`${target.ccy} pocket`} v={money(target.sym, out, 2)} last />
        </div>
        <Button variant="primary" onClick={() => app.navigate("contract")}>Pay a supplier with {target.ccy}</Button>
        <button onClick={() => app.setTab("home")} style={{ marginTop: 12, background: "none", border: "none", color: "var(--ot-fg-2)", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 14, cursor: "pointer" }}>Back to dashboard</button>
      </div></div>
    </div>
  );

  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Convert" onBack={app.back} />
      <div className="ot-body">
        <div className="ot-pad">
          {/* from */}
          <div className="ot-card flat" style={{ padding: 16 }}>
            <span style={{ fontSize: 12, color: "var(--ot-fg-2)", fontWeight: 600 }}>You pay · from {a.ccy} wallet</span>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
              <Flag code={a.flag} size={34} />
              <input className="ot-num" value={fmt(amount)} onChange={e => setAmount(+e.target.value.replace(/[^0-9]/g, "") || 0)}
                style={{ border: "none", outline: "none", fontSize: 28, color: "var(--ot-navy)", width: "100%", background: "none" }} />
              <span style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, color: "var(--ot-fg-2)" }}>{a.ccy}</span>
            </div>
            <span style={{ fontSize: 12, color: "var(--ot-fg-3)", marginTop: 6, display: "block" }}>Balance {money(a.sym, w.balance)}</span>
          </div>

          {/* swap chip */}
          <div style={{ display: "flex", justifyContent: "center", margin: "-12px 0", position: "relative", zIndex: 2 }}>
            <span style={{ width: 40, height: 40, borderRadius: "50%", background: "var(--ot-orange)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "var(--ot-shadow-orange)", border: "3px solid var(--ot-bg)" }}><Icon name="arrow-up-down" size={18} /></span>
          </div>

          {/* to */}
          <div className="ot-card flat" style={{ padding: 16 }}>
            <span style={{ fontSize: 12, color: "var(--ot-fg-2)", fontWeight: 600 }}>You get · {target.ccy} pocket</span>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
              <button onClick={() => setPickerOpen(true)} style={{ display: "flex", alignItems: "center", gap: 7, background: "var(--ot-gray-100)", border: "none", borderRadius: 999, padding: "6px 10px 6px 6px", cursor: "pointer", flex: "none" }}>
                <Flag code={target.flag} size={26} /><b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 14 }}>{target.ccy}</b><Icon name="chevron-down" size={15} />
              </button>
              <Odometer value={out} dp={2} style={{ fontSize: 28, color: "var(--ot-navy)", marginLeft: "auto" }} />
            </div>
          </div>

          {/* rate lock */}
          <div className="ot-card flat" style={{ padding: 14, marginTop: 14 }}>
            <KV k="Rate" v={`1 ${target.ccy} = ${fmt(target.rate, 2)} ${a.ccy}`} />
            <KV k="Conversion fee" v={`${target.fee}% · ${money(a.sym, feeAmt)}`} />
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 8, marginTop: 4, borderTop: "1px solid var(--ot-gray-100)" }}>
              <Badge kind="locked" icon="lock">Rate locked for 60s</Badge>
              <RateRing seconds={60} size={46} />
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        <Button variant="primary" icon="arrow-right-left" onClick={confirm} disabled={amount <= 0 || amount > w.balance}>
          {amount > w.balance ? "Insufficient balance" : `Convert ${money(a.sym, amount)}`}
        </Button>
      </div>

      {pickerOpen && (
        <div className="ot-sheet-scrim" onClick={() => setPickerOpen(false)}>
          <div className="ot-sheet" onClick={e => e.stopPropagation()}>
            <div className="grab" />
            <h2 style={{ font: "var(--ot-h3)", margin: "0 0 14px" }}>Convert to</h2>
            {CONVERT_TARGETS.map(t => (
              <Row key={t.ccy} iconEl={<Flag code={t.flag} size={40} />} title={t.ccy} sub={`1 ${t.ccy} = ${fmt(t.rate, 2)} ${a.ccy} · fee ${t.fee}%`}
                onClick={() => { setTarget(t); setPickerOpen(false); }}
                right={target.ccy === t.ccy ? <Icon name="check" size={18} style={{ color: "var(--ot-orange)" }} /> : null} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
function KV({ k, v, last }) {
  return <div style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: last ? "none" : "1px solid var(--ot-gray-100)" }}>
    <span style={{ fontSize: 13, color: "var(--ot-fg-2)", fontWeight: 500 }}>{k}</span>
    <span style={{ fontSize: 13, color: "var(--ot-navy)", fontWeight: 700, fontFamily: "var(--ot-font-body)" }}>{v}</span>
  </div>;
}

Object.assign(window, { LoginScreen, Dashboard, Wallet, TopupSheet, Convert, StatusPill, SuccessMark, KV, glassBtn });
