// Optimal Trade — Screens 2: Suppliers, SupplierProfile, Contract, Logistics, PayConfirm
const { useState: useState2, useEffect: useEffect2 } = React;

/* ============================== SUPPLIER CATALOG ================================ */
function SupplierCatalog({ app }) {
  const [q, setQ] = useState2("");
  const [cat, setCat] = useState2("All");
  const cats = ["All", "Electronics", "Textiles", "Automotive", "Homeware", "Agriculture"];
  const list = SUPPLIERS.filter(s =>
    (cat === "All" || s.cat === cat) &&
    (s.name.toLowerCase().includes(q.toLowerCase()) || s.cat.toLowerCase().includes(q.toLowerCase())));
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Suppliers" right={<button className="ot-iconbtn"><Icon name="filter" /></button>} />
      <div style={{ padding: "0 20px 8px" }}>
        <div className="ot-input"><Icon name="search" /><input placeholder="Search authorized suppliers" value={q} onChange={e => setQ(e.target.value)} /></div>
      </div>
      <div style={{ display: "flex", gap: 8, overflowX: "auto", padding: "8px 20px 12px" }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)} style={{ flex: "none", padding: "7px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12.5, background: cat === c ? "var(--ot-navy)" : "var(--ot-gray-100)", color: cat === c ? "#fff" : "var(--ot-fg-2)" }}>{c}</button>
        ))}
      </div>
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 4, 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={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, 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, fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 13, color: "var(--ot-navy)" }}><Icon name="star" size={14} style={{ color: "var(--ot-orange)" }} />{s.rating}</span>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 11 }}>
                {s.tags.map(t => <span key={t} style={{ fontSize: 11, fontWeight: 600, color: "var(--ot-fg-2)", background: "var(--ot-gray-100)", padding: "4px 9px", borderRadius: 999 }}>{t}</span>)}
                {!s.authorized && <span style={{ marginLeft: "auto" }}><Badge kind="pending" dot>Not authorized</Badge></span>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================== SUPPLIER PROFILE =============================== */
function SupplierProfile({ app, params }) {
  const s = params.supplier;
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Supplier" onBack={app.back} right={<button className="ot-iconbtn"><Icon name="more-horizontal" /></button>} />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 2 }}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", padding: "10px 0 18px" }}>
            <Flag code={s.flag} size={68} />
            <h2 style={{ font: "var(--ot-h2)", margin: "12px 0 4px" }}>{s.name}</h2>
            <span style={{ fontSize: 13.5, color: "var(--ot-fg-2)", fontWeight: 500 }}>{s.country} · {s.cat}</span>
            <div style={{ marginTop: 10 }}>
              {s.authorized ? <Badge kind="solid" icon="shield-check">Authorized supplier</Badge> : <Badge kind="pending" dot>Awaiting authorization</Badge>}
            </div>
          </div>

          <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
            {[["star", s.rating, "Rating"], ["package", s.orders, "Orders"], ["clock", s.lead.split("–")[0] + "d", "Lead time"]].map(([ic, val, lab]) => (
              <div key={lab} className="ot-card flat" style={{ flex: 1, padding: "12px 8px", textAlign: "center" }}>
                <Icon name={ic} size={18} style={{ color: "var(--ot-orange)" }} />
                <div className="ot-num" style={{ fontSize: 17, color: "var(--ot-navy)", margin: "4px 0 1px" }}>{val}</div>
                <span style={{ fontSize: 11, color: "var(--ot-fg-2)", fontWeight: 600 }}>{lab}</span>
              </div>
            ))}
          </div>

          <p style={{ font: "var(--ot-body)", color: "var(--ot-fg)", margin: "0 0 16px" }}>{s.blurb}</p>

          <div className="ot-card flat" style={{ padding: 14, marginBottom: 16 }}>
            <KV k="Minimum order" v={money("$", s.min)} />
            <KV k="Lead time" v={s.lead} />
            <KV k="Settlement" v="USD · CNY · AED" last />
          </div>

          <span className="ot-eyebrow" style={{ display: "block", marginBottom: 10 }}>Product lines</span>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {s.tags.map(t => <span key={t} style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ot-navy)", background: "var(--ot-orange-50)", padding: "8px 13px", borderRadius: 999 }}>{t}</span>)}
          </div>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)", display: "flex", gap: 10 }}>
        {s.authorized
          ? <Button variant="primary" icon="file-text" onClick={() => app.navigate("contract", { supplier: s })}>Create contract</Button>
          : <Button variant="dark" icon="shield-check" onClick={() => app.navigate("contract", { supplier: s })}>Authorize &amp; contract</Button>}
      </div>
    </div>
  );
}

/* ============================== CONTRACT / INVOICE ============================= */
function ContractCreate({ app, params }) {
  const a = app.account;
  const sup = params && params.supplier;
  const [supplier, setSupplier] = useState2(sup || null);
  const [pickerOpen, setPickerOpen] = useState2(false);
  const [goods, setGoods] = useState2("");
  const [amount, setAmount] = useState2(8200);
  const [ccy, setCcy] = useState2("USD");
  const [incoterm, setIncoterm] = useState2("FOB");
  const valid = supplier && goods.trim() && amount > 0;
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="New contract" onBack={app.back} />
      <div className="ot-body">
        <div className="ot-pad" style={{ display: "flex", flexDirection: "column", gap: 16, paddingTop: 4 }}>
          <div className="ot-field">
            <label>Supplier</label>
            <button onClick={() => setPickerOpen(true)} className="ot-input" style={{ cursor: "pointer", justifyContent: "space-between" }}>
              {supplier ? <span style={{ display: "flex", alignItems: "center", gap: 10 }}><Flag code={supplier.flag} size={26} /><b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 14.5 }}>{supplier.name}</b></span>
                : <span style={{ color: "var(--ot-gray-400)" }}>Select authorized supplier</span>}
              <Icon name="chevron-down" size={18} />
            </button>
          </div>
          <div className="ot-field">
            <label>Goods description</label>
            <div className="ot-input"><Icon name="package" /><input placeholder="e.g. Camera modules ×400" value={goods} onChange={e => setGoods(e.target.value)} /></div>
          </div>
          <div className="ot-field">
            <label>Contract amount</label>
            <div className="ot-input">
              <span style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600 }}>{ccy === "USD" ? "$" : ccy === "CNY" ? "\u00A5" : "\u062F.\u0625"}</span>
              <input value={fmt(amount)} onChange={e => setAmount(+e.target.value.replace(/[^0-9]/g, "") || 0)} />
              <div className="ot-seg" style={{ flex: "none", padding: 3 }}>
                {["USD", "CNY", "AED"].map(c => <button key={c} className={ccy === c ? "active" : ""} onClick={() => setCcy(c)} style={{ padding: "5px 9px", fontSize: 11.5 }}>{c}</button>)}
              </div>
            </div>
          </div>
          <div className="ot-field">
            <label>Incoterm</label>
            <div className="ot-seg">
              {["FOB", "CIF", "EXW"].map(t => <button key={t} className={incoterm === t ? "active" : ""} onClick={() => setIncoterm(t)}>{t}</button>)}
            </div>
          </div>
          <div className="ot-card flat" style={{ padding: 14 }}>
            <KV k="Pay from" v={`${a.ccy} wallet`} />
            <KV k="Est. logistics" v={<span style={{ color: "var(--ot-orange-deep)", display: "inline-flex", gap: 4, alignItems: "center", cursor: "pointer" }} onClick={() => app.navigate("logistics")}><Icon name="calculator" size={13} />Calculate</span>} />
            <KV k="Platform fee" v="1.5%" last />
          </div>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        <Button variant="primary" disabled={!valid} onClick={() => app.navigate("payconfirm", { draft: { supplier, goods, amount, ccy, incoterm } })}>Review &amp; pay</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 12px" }}>Select supplier</h2>
            {SUPPLIERS.filter(s => s.authorized).map(s => (
              <Row key={s.id} iconEl={<Flag code={s.flag} size={40} />} title={s.name} sub={`${s.country} · ${s.cat}`} onClick={() => { setSupplier(s); setPickerOpen(false); }} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ============================== LOGISTICS CALCULATOR =========================== */
function LogisticsCalc({ app }) {
  const [origin, setOrigin] = useState2("Shenzhen, China");
  const [mode, setMode] = useState2("sea");
  const [weight, setWeight] = useState2(1200);
  const [volume, setVolume] = useState2(8);
  const modes = [
    { id: "sea", label: "Sea", icon: "ship", rate: 2.1, days: "18–24", base: 480 },
    { id: "air", label: "Air", icon: "plane", rate: 6.8, days: "4–7", base: 320 },
    { id: "road", label: "Road", icon: "truck", rate: 3.4, days: "10–16", base: 260 },
  ];
  const m = modes.find(x => x.id === mode);
  const cost = Math.round(m.base + weight * m.rate + volume * 95);
  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Logistics calculator" onBack={app.back} />
      <div className="ot-body">
        <div className="ot-pad" style={{ display: "flex", flexDirection: "column", gap: 16, paddingTop: 4 }}>
          <div className="ot-card flat" style={{ padding: 4 }}>
            <Row icon="warehouse" title={origin} sub="Origin" />
            <hr className="ot-divider" />
            <Row icon="map-pin" title={`${app.account.country} · ${app.account.country === "Nigeria" ? "Lagos (Apapa)" : app.account.country === "Kenya" ? "Mombasa" : "Durban"}`} sub="Destination" />
          </div>

          <div>
            <label style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12.5, color: "var(--ot-fg-2)", display: "block", marginBottom: 8 }}>Transport mode</label>
            <div style={{ display: "flex", gap: 10 }}>
              {modes.map(x => (
                <button key={x.id} onClick={() => setMode(x.id)} style={{ flex: 1, padding: "14px 4px", borderRadius: "var(--ot-r-md)", cursor: "pointer", border: `1.5px solid ${mode === x.id ? "var(--ot-orange)" : "var(--ot-gray-200)"}`, background: mode === x.id ? "var(--ot-orange-25)" : "#fff", display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
                  <Icon name={x.icon} size={22} style={{ color: mode === x.id ? "var(--ot-orange-deep)" : "var(--ot-navy)" }} />
                  <b style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 13 }}>{x.label}</b>
                  <span style={{ fontSize: 10.5, color: "var(--ot-fg-2)" }}>{x.days} days</span>
                </button>
              ))}
            </div>
          </div>

          <Slider label="Weight" value={weight} setValue={setWeight} min={100} max={5000} step={100} unit="kg" />
          <Slider label="Volume" value={volume} setValue={setVolume} min={1} max={40} step={1} unit="m³" />

          <div style={{ background: "var(--ot-navy)", borderRadius: "var(--ot-r-lg)", padding: 18, color: "#fff" }}>
            <span style={{ fontSize: 12, color: "rgba(255,255,255,.7)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".08em" }}>Estimated logistics cost</span>
            <div className="ot-num" style={{ fontSize: 34, color: "#fff", margin: "6px 0 4px" }}>{money("$", cost)}</div>
            <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.65)" }}>{m.label} freight · {m.days} days · customs included</span>
          </div>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        <Button variant="primary" icon="check" onClick={app.back}>Use this estimate</Button>
      </div>
    </div>
  );
}
function Slider({ label, value, setValue, min, max, step, unit }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
        <label style={{ fontFamily: "var(--ot-font-body)", fontWeight: 600, fontSize: 12.5, color: "var(--ot-fg-2)" }}>{label}</label>
        <span className="ot-num" style={{ fontSize: 14, color: "var(--ot-navy)" }}>{fmt(value)} {unit}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => setValue(+e.target.value)}
        style={{ width: "100%", accentColor: "var(--ot-orange)", background: `linear-gradient(90deg,var(--ot-orange) ${pct}%, var(--ot-gray-200) ${pct}%)`, height: 6, borderRadius: 999, appearance: "none", WebkitAppearance: "none", outline: "none" }} />
    </div>
  );
}

/* ============================== PAYMENT CONFIRMATION =========================== */
function PayConfirm({ app, params }) {
  const a = app.account;
  // paying: a To-pay invoice, a new draft, or an existing pending contract
  const src = params.invoice || params.draft || params.contract;
  const draft = params.draft;
  const supplierName = draft ? draft.supplier.name : src.supplier;
  const flag = draft ? draft.supplier.flag : src.flag;
  const amount = src.amount;
  const ccy = src.ccy || "USD";
  const sym = ccy === "USD" ? "$" : ccy === "CNY" ? "\u00A5" : ccy === "AED" ? "\u062F.\u0625" : "$";
  const goods = src.goods;
  const incoterm = src.incoterm || (draft && draft.incoterm) || "FOB";
  const id = src.id || ("OT-" + (2050 + Math.floor(Math.random() * 40)));
  const rate = ccy === "USD" ? 1512.4 : ccy === "CNY" ? 208.65 : 411.78;
  const fee = Math.round(amount * 0.015);
  const localCost = Math.round((amount + fee) * rate);
  const [stage, setStage] = useState2("review"); // review | processing | done
  const [authed, setAuthed] = useState2(false);
  const [openFee, setOpenFee] = useState2(false);

  const pay = () => {
    setStage("processing");
    setTimeout(() => { app.payContract({ id, supplier: supplierName, flag, amount, ccy, sym, goods, incoterm, localCost, fromInvoice: !!params.invoice }); setStage("done"); }, 1900);
  };

  if (stage === "processing") 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" }}>
      <div className="ot-pill" style={{ width: "100%", maxWidth: 280 }}><span className="dots"><i /><i /><i /></span>Settling payment</div>
      <p style={{ font: "var(--ot-body)", color: "var(--ot-fg-2)", maxWidth: 250, marginTop: 18 }}>Converting {a.ccy} and routing {money(sym, amount)} to {supplierName} via the finance center.</p>
    </div></div></div>
  );

  if (stage === "done") return (
    <div className="ot-screen"><StatusBar />
      <Confetti />
      <div className="ot-body"><div className="ot-pad" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "100%", textAlign: "center" }}>
      <span className="ot-ceremony-check"><Icon name="check" size={48} strokeWidth={2.4} /></span>
      <h1 style={{ font: "var(--ot-h2)", margin: "20px 0 6px" }}>Payment sent</h1>
      <p style={{ font: "var(--ot-body)", color: "var(--ot-fg-2)", margin: 0 }}>{id} · {supplierName}</p>
      <Odometer value={amount} from={0} sym={sym} dur={900} style={{ fontSize: 32, color: "var(--ot-navy)", display: "block", margin: "12px 0" }} />
      <Badge kind="transit" icon="ship">Shipment created</Badge>
      <div className="ot-card flat" style={{ width: "100%", padding: 12, margin: "18px 0 22px", textAlign: "left", display: "flex", alignItems: "center", gap: 10 }}>
        <Icon name="shield" size={18} style={{ color: "var(--ot-success)", flex: "none" }} />
        <span style={{ fontSize: 12, color: "var(--ot-fg-2)" }}>Receipt saved · protected by mandate contract №{id}</span>
      </div>
      <Button variant="primary" icon="ship" onClick={() => app.navigate("tracking", { contract: { id, supplier: supplierName, flag, amount, sym, goods, status: "transit", incoterm } })}>Track shipment</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 home</button>
    </div></div></div>
  );

  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="Confirm payment" onBack={app.back} />
      <div className="ot-body">
        <div className="ot-pad" style={{ paddingTop: 4 }}>
          {/* total on top */}
          <div className="ot-card" style={{ padding: 18, textAlign: "center", marginBottom: 16 }}>
            <Flag code={flag} size={54} style={{ margin: "0 auto" }} />
            <span style={{ display: "block", fontSize: 13, color: "var(--ot-fg-2)", marginTop: 10, fontWeight: 600 }}>Supplier gets</span>
            <b style={{ fontWeight: 700, fontSize: 17, color: "var(--ot-navy)", display: "block" }}>{supplierName}</b>
            <div className="ot-num" style={{ fontSize: 34, color: "var(--ot-navy)", margin: "10px 0 2px" }}>{money(sym, amount)}</div>
            <span style={{ fontSize: 12.5, color: "var(--ot-fg-3)" }}>You pay ≈ {money(a.sym, localCost)} from {a.ccy}</span>
          </div>
          {/* fee accordion (transparency before confirm) */}
          <div className="ot-card flat" style={{ padding: "4px 14px", marginBottom: 16 }}>
            <button onClick={() => setOpenFee(v => !v)} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", background: "none", border: "none", padding: "12px 0", cursor: "pointer" }}>
              <span style={{ fontWeight: 700, fontSize: 13.5, color: "var(--ot-navy)" }}>Total breakdown</span>
              <span style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--ot-fg-2)" }}><span className="ot-num" style={{ fontSize: 13.5 }}>{money(a.sym, localCost)}</span><Icon name={openFee ? "chevron-up" : "chevron-down"} size={16} /></span>
            </button>
            {openFee && <div className="ot-page-anim" style={{ paddingBottom: 8 }}>
              <KV k="Supplier amount" v={money(sym, amount)} />
              <KV k="FX rate" v={`1 ${ccy} = ${fmt(rate, 2)} ${a.ccy}`} />
              <KV k="Platform fee (1.5%)" v={money(sym, fee)} />
              <KV k="Finance route" v="UAE non-resident a/c" last />
            </div>}
          </div>
          <div className="ot-card flat" style={{ padding: 14, marginBottom: 18 }}>
            <KV k="Contract" v={id} />
            <KV k="Goods" v={goods} />
            <KV k="Incoterm" v={incoterm} last />
          </div>
          <label style={{ display: "flex", gap: 11, alignItems: "flex-start", cursor: "pointer", padding: "2px 2px 4px" }} onClick={() => setAuthed(v => !v)}>
            <span style={{ width: 22, height: 22, borderRadius: 7, flex: "none", marginTop: 1, border: `2px solid ${authed ? "var(--ot-orange)" : "var(--ot-gray-300)"}`, background: authed ? "var(--ot-orange)" : "#fff", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", transition: "background .15s" }}>{authed && <Icon name="check" size={14} strokeWidth={3} />}</span>
            <span style={{ fontSize: 13, color: "var(--ot-fg)", lineHeight: 1.45 }}>I authorize Optimal Trade to convert and settle this payment on my behalf. Documentary obligations apply.</span>
          </label>
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        <SwipeToPay label={authed ? `Slide to pay ${money(sym, amount)}` : "Authorize to continue"} disabled={!authed} onConfirm={pay} />
      </div>
    </div>
  );
}

Object.assign(window, { SupplierCatalog, SupplierProfile, ContractCreate, LogisticsCalc, Slider, PayConfirm });
