// Optimal Trade — Home (bento), Orders feed, Finance, Profile, Counterparties
const { useState: useStateH, useEffect: useEffectH } = React;

/* status vocab for orders (colour + icon + text — always all three) */
const ORDER_STATUS = {
  offers:    { kind: "transit", icon: "sparkles", label: "offers ready" },
  waiting:   { kind: "pending", dot: true, label: "Awaiting offers" },
  topay:     { kind: "locked",  icon: "wallet", label: "Awaiting payment" },
  transit:   { kind: "transit", icon: "ship",  label: "In transit" },
  delivered: { kind: "paid",    icon: "check-check", label: "Delivered" },
  declined:  { kind: "error",   icon: "x", label: "Declined" },
};
function OrderChip({ status, text }) {
  const m = ORDER_STATUS[status] || ORDER_STATUS.waiting;
  return <Badge kind={m.kind} icon={m.icon} dot={m.dot}>{text || m.label}</Badge>;
}

/* ============================== HOME (bento) ==================================== */
function Home({ app }) {
  const a = app.account, w = app.world;
  const [glow, setGlow] = useStateH(false);
  useEffectH(() => { if (w.justPaid) { setGlow(true); const t = setTimeout(() => { setGlow(false); app.clearJustPaid(); }, 1400); return () => clearTimeout(t); } }, [w.justPaid]);
  const rate = RATE_PAIRS[0];
  const active = w.orders.filter(o => o.kind === "order" && o.status !== "delivered");
  return (
    <div className="ot-screen">
      <StatusBar />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 2 }}>
          {/* greeting */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "6px 0 14px" }}>
            <Flag code={a.flag} size={38} />
            <div style={{ flex: 1 }}>
              <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)", fontWeight: 600 }}>Welcome back</span>
              <b style={{ display: "block", fontWeight: 700, fontSize: 16, color: "var(--ot-navy)" }}>{a.company}</b>
            </div>
            <button className="ot-iconbtn" style={{ position: "relative" }} onClick={() => app.setTab("orders")}>
              <Icon name="bell" /><span style={{ position: "absolute", top: 7, right: 8, width: 8, height: 8, borderRadius: "50%", background: "var(--ot-orange)", border: "2px solid #fff" }} />
            </button>
          </div>

          {/* BENTO 1 — balance + rate (large, door to Finance) */}
          <div className={"ot-card" + (glow ? " ot-glow" : "")} onClick={() => app.setTab("finance")}
            style={{ background: "var(--ot-grad-hero)", borderRadius: "var(--ot-r-xl)", padding: 20, color: "#fff", boxShadow: "var(--ot-shadow-orange)", position: "relative", overflow: "hidden", cursor: "pointer" }}>
            <div style={{ position: "absolute", right: -28, top: -28, width: 140, height: 140, borderRadius: "50%", background: "rgba(255,255,255,.10)" }} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <span style={{ fontSize: 12, color: "rgba(255,255,255,.85)", fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase" }}>Balance · {a.ccy}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "rgba(255,255,255,.2)", borderRadius: 999, padding: "4px 9px", fontSize: 11.5, fontWeight: 700 }}>
                <Icon name="trending-up" size={12} />{rate.pair} {fmt(rate.rate, 2)}
              </span>
            </div>
            <Odometer value={w.balance} from={w.justPaid ? w.prevBalance : undefined} sym={a.sym} style={{ fontSize: 38, color: "#fff", display: "block", margin: "8px 0 16px" }} />
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={(e) => { e.stopPropagation(); app.openTopup(); }} style={glassBtn}><Icon name="plus" size={16} />Top up</button>
              <button onClick={(e) => { e.stopPropagation(); app.navigate("convert"); }} style={glassBtn}><Icon name="arrow-right-left" size={16} />Convert</button>
            </div>
          </div>

          {/* BENTO 2 — To-pay (money finds the user) */}
          {w.toPay && (
            <div className="ot-card" style={{ marginTop: 14, padding: 16, border: "1.5px solid var(--ot-orange)", display: "flex", alignItems: "center", gap: 13, cursor: "pointer" }}
              onClick={() => app.navigate("payconfirm", { invoice: w.toPay })}>
              <span style={{ width: 46, height: 46, borderRadius: 13, background: "var(--ot-orange-50)", color: "var(--ot-orange-deep)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="wallet" size={22} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}><b style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ot-navy)" }}>To pay · {w.toPay.supplier}</b></div>
                <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{w.toPay.id} · {w.toPay.due}</span>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="ot-num" style={{ fontSize: 15, color: "var(--ot-navy)" }}>{money(w.toPay.sym, w.toPay.amount)}</div>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ot-orange-deep)" }}>Pay now ›</span>
              </div>
            </div>
          )}

          {/* BENTO 3 — active orders lane */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "22px 0 10px" }}>
            <span className="ot-eyebrow" style={{ font: "var(--ot-caption)", fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ot-fg-3)" }}>Active orders</span>
            <span onClick={() => app.setTab("orders")} style={{ fontSize: 12.5, color: "var(--ot-orange-deep)", fontWeight: 700, cursor: "pointer" }}>See all</span>
          </div>
          <div style={{ display: "flex", gap: 12, overflowX: "auto", margin: "0 -20px", padding: "0 20px 6px" }}>
            {active.map(o => (
              <div key={o.id} className="ot-card" style={{ flex: "none", width: 230, padding: 15, cursor: "pointer" }} onClick={() => app.openOrder(o)}>
                <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}>
                  <Flag code={o.flag} size={28} />
                  <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)", fontWeight: 600, flex: 1 }}>{o.id}</span>
                  <OrderChip status={o.status} />
                </div>
                <b style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ot-navy)", display: "block" }}>{o.title}</b>
                <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{o.supplier}</span>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 11, color: "var(--ot-orange-deep)" }}>
                  <Icon name="arrow-up-right" size={14} /><span style={{ fontSize: 12, fontWeight: 700 }}>{o.next}</span>
                </div>
              </div>
            ))}
          </div>

          {/* primary intent — the single accent button */}
          <button className="ot-btn ot-btn-primary" style={{ marginTop: 22, height: 56, fontSize: 16 }} onClick={() => app.navigate("wizard")}>
            <Icon name="plus" size={20} />New purchase
          </button>
          <p style={{ textAlign: "center", fontSize: 12, color: "var(--ot-fg-3)", marginTop: 12 }}>Request a price from verified suppliers in 4 steps.</p>
        </div>
      </div>
    </div>
  );
}

/* ============================== ORDERS FEED ==================================== */
function Orders({ app }) {
  const w = app.world;
  const [f, setF] = useStateH("all");
  const chips = [["all", "All"], ["quote", "Quotes"], ["topay", "To pay"], ["transit", "In transit"], ["delivered", "Delivered"]];
  const list = w.orders.filter(o => f === "all" || o.status === f || (f === "quote" && o.kind === "quote"));
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Orders" right={<button className="ot-iconbtn"><Icon name="search" /></button>} />
      <div style={{ display: "flex", gap: 8, overflowX: "auto", padding: "2px 20px 12px" }}>
        {chips.map(([id, label]) => <button key={id} className={"ot-chip" + (f === id ? " active" : "")} onClick={() => setF(id)}>{label}</button>)}
      </div>
      <div className="ot-body">
        <div className="ot-pad ot-stagger" style={{ paddingTop: 2, display: "flex", flexDirection: "column", gap: 12 }}>
          {list.map(o => (
            <div key={o.id} className="ot-card" style={{ padding: 15, cursor: "pointer" }} onClick={() => app.openOrder(o)}>
              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <Flag code={o.flag} size={40} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <b style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ot-navy)", display: "block" }}>{o.title}</b>
                  <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{o.id} · {o.kind === "quote" ? "Quote" : o.supplier}</span>
                </div>
                {o.amount && <span className="ot-num" style={{ fontSize: 14.5, color: "var(--ot-navy)" }}>{money(o.sym, o.amount)}</span>}
              </div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--ot-gray-100)" }}>
                <OrderChip status={o.status} text={o.statusLabel} />
                <span style={{ fontSize: 12, color: "var(--ot-fg-2)", fontWeight: 500 }}>{o.sub}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================== FINANCE ======================================== */
function Finance({ app }) {
  const a = app.account, w = app.world;
  const pockets = [{ 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="Finance" right={<button className="ot-iconbtn"><Icon name="scan-line" /></button>} />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 2 }}>
          <div style={{ background: "var(--ot-navy)", borderRadius: "var(--ot-r-xl)", padding: 20, color: "#fff" }}>
            <TMark size={26} />
            <span style={{ display: "block", fontSize: 12, color: "rgba(255,255,255,.7)", fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase", marginTop: 14 }}>Balance · {a.ccy}</span>
            <Odometer value={w.balance} sym={a.sym} style={{ fontSize: 36, color: "#fff", display: "block", margin: "6px 0 14px" }} />
            <div style={{ display: "flex", gap: 10 }}>
              <button className="ot-btn ot-btn-primary" onClick={() => app.openTopup()}><Icon name="plus" size={18} />Top up</button>
              <button className="ot-btn ot-btn-outline" style={{ background: "rgba(255,255,255,.1)", color: "#fff", border: "1px solid rgba(255,255,255,.2)" }} onClick={() => app.navigate("convert")}><Icon name="arrow-right-left" size={18} />Convert</button>
            </div>
          </div>

          <span className="ot-eyebrow" style={{ display: "block", margin: "22px 0 10px", font: "var(--ot-caption)", fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ot-fg-3)" }}>Currency pockets</span>
          <div className="ot-card">
            {pockets.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>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "22px 0 10px" }}>
            <span className="ot-eyebrow" style={{ font: "var(--ot-caption)", fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ot-fg-3)" }}>Recent operations</span>
            <span onClick={() => app.setTab("orders")} style={{ fontSize: 12.5, color: "var(--ot-orange-deep)", fontWeight: 700, cursor: "pointer" }}>All</span>
          </div>
          <div className="ot-card">
            {w.txs.slice(0, 4).map(t => {
              const ic = { invoice: "ship", topup: "arrow-down-left", convert: "arrow-right-left" }[t.type];
              return <Row key={t.id} icon={ic} title={t.title} sub={`${t.date} · ${t.sub}`}
                right={<span className="ot-num" style={{ fontSize: 14, color: t.amount < 0 ? "var(--ot-error)" : "var(--ot-success)", marginRight: 4 }}>{t.amount < 0 ? "−" : "+"}{money(t.sym, Math.abs(t.amount))}</span>} />;
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================== PROFILE & COUNTERPARTIES ======================= */
function Profile({ app }) {
  const a = app.account;
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Profile" />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 2 }}>
          <div className="ot-card" style={{ padding: 18, display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
            <Flag code={a.flag} size={54} />
            <div style={{ flex: 1 }}>
              <b style={{ fontWeight: 700, fontSize: 16, color: "var(--ot-navy)", display: "block" }}>{a.company}</b>
              <span style={{ fontSize: 13, color: "var(--ot-fg-2)" }}>{a.name} · {a.country}</span>
              <div style={{ marginTop: 7 }}><Badge kind="paid" icon="badge-check">Verified business</Badge></div>
            </div>
          </div>
          <div className="ot-card">
            {PROFILE_MENU.map(m => (
              <Row key={m.label} icon={m.icon} title={m.label} sub={m.sub} chevron
                onClick={() => m.to && app.navigate(m.to)}
                right={m.badge ? <Badge kind="paid">{m.badge}</Badge> : null} />
            ))}
          </div>
          <button className="ot-btn ot-btn-outline" style={{ marginTop: 18, color: "var(--ot-error)", borderColor: "var(--ot-gray-200)" }} onClick={app.logout}><Icon name="log-out" size={18} />Log out</button>
          <p style={{ textAlign: "center", fontSize: 11.5, color: "var(--ot-fg-3)", marginTop: 16 }}>Optimal Trade · Demo prototype · v3.0</p>
        </div>
      </div>
    </div>
  );
}

function Counterparties({ app }) {
  const [q, setQ] = useStateH("");
  const list = SUPPLIERS.filter(s => s.name.toLowerCase().includes(q.toLowerCase()) || s.cat.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Counterparties" onBack={app.back} />
      <div style={{ padding: "0 20px 8px" }}><div className="ot-input"><Icon name="search" /><input placeholder="Search suppliers" value={q} onChange={e => setQ(e.target.value)} /></div></div>
      <div className="ot-body">
        <div className="ot-pad ot-stagger" style={{ paddingTop: 6, display: "flex", flexDirection: "column", gap: 12 }}>
          {list.map(s => (
            <div key={s.id} className="ot-card" style={{ padding: 14, cursor: "pointer" }} onClick={() => app.navigate("supplier", { supplier: s })}>
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <span style={{ position: "relative" }}><Flag code={s.flag} size={46} />
                  {s.authorized && <span style={{ position: "absolute", right: -3, bottom: -3, width: 19, height: 19, borderRadius: "50%", background: "var(--ot-success)", border: "2px solid #fff", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff" }}><Icon name="check" size={11} strokeWidth={3} /></span>}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <b style={{ fontWeight: 700, fontSize: 15, color: "var(--ot-navy)", display: "block" }}>{s.name}</b>
                  <span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>{s.country} · {s.cat}</span>
                </div>
                <span style={{ display: "flex", alignItems: "center", gap: 3, fontWeight: 700, fontSize: 13, color: "var(--ot-navy)" }}><Icon name="star" size={14} style={{ color: "var(--ot-orange)" }} />{s.rating}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Home, Orders, Finance, Profile, Counterparties, OrderChip, ORDER_STATUS });
