/* simple/arriving.jsx — the arriving-funds experience.
   Money you moved in that hasn't landed yet is spendable: the trade/move
   "available" is settled cash + in-transit funds, and an order that dips into
   the in-transit part becomes a ONE-TIME AUTOMATION — identical to an
   after-hours trade, just with a different trigger. It's placed through the
   same `placeOrder` pipeline into the one In-motion list (tagged `fundedBy`
   the transfer), so it gets the standard row, the standard pending detail
   (TxnDetailSheet), and the standard cancel. This file is only the pre-confirm
   review where you pick all-at-once vs split before the passkey. */

const FundingOption = ({ on, title, sub, onPick }) => (
  <button className="press" onClick={onPick} style={{ width: "100%", textAlign: "left", display: "flex", gap: 11, alignItems: "flex-start", padding: "12px 13px", background: on ? "color-mix(in srgb, var(--accent) 7%, var(--bg-card))" : "var(--bg-card)", border: `1px solid ${on ? "var(--accent)" : "var(--rule-2)"}`, borderRadius: 12, cursor: "pointer" }}>
    <span style={{ width: 16, height: 16, flex: "none", marginTop: 1, borderRadius: 999, border: `1.5px solid ${on ? "var(--accent)" : "var(--rule-2)"}`, display: "grid", placeItems: "center", boxSizing: "border-box" }}>
      {on && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--accent)" }} />}
    </span>
    <span style={{ minWidth: 0 }}>
      <span style={{ display: "block", fontFamily: "var(--f-display)", fontSize: typeSize(13), fontWeight: 600 }}>{title}</span>
      <span style={{ display: "block", fontFamily: "var(--f-display)", fontSize: typeSize(11), color: "var(--ink-3)", marginTop: 2, lineHeight: 1.45 }}>{sub}</span>
    </span>
  </button>
);

/* place a queued order as a one-time automation into the ONE In-motion list —
   same bridge (`placeOrder`) the after-hours trade uses. Tagged `fundedBy` the
   transfer + `funds` (the in-transit slice it consumes) so the ceiling can
   read what's committed. Trades wait for the funds and then the next market
   open; transfers just wait for the funds. */
const placeQueued = (item) => { if (window.yoshiTrack && window.yoshiTrack.placed) window.yoshiTrack.placed(item); };

/* ============================================================
   QueuedTradeReview · the pre-confirm review for a BUY that
   needs money still in flight. Timing is the headline; the
   all-at-once vs split funding split is the one decision here.
   ============================================================ */
const QueuedTradeReview = ({ sel, amtNum, avail, t, onBack }) => {
  const [mode, setMode] = useState("together"); // together · one order when it lands / split · settled part now
  const part = +(amtNum - avail).toFixed(2); // the slice that rides on the transfer
  // current price + today's move, colored — same as the trade ticket / other legs
  const dayAbs = sel.last - sel.last / (1 + (sel.dch || 0) / 100);
  const secChange = sel.dch != null ? `${sel.dch >= 0 ? "+" : "−"}${usd(Math.abs(dayAbs), 2)} (${sel.dch >= 0 ? "+" : "−"}${Math.abs(sel.dch).toFixed(2)}%) today` : null;
  const secTone = sel.dch >= 0 ? "pos" : "neg";
  const orderAmt = mode === "split" ? part : amtNum; // the amount that rides the transfer

  // "Confirm with passkey" places it straight into In motion (→ Activity),
  // like every other confirm in the app — no second passkey modal.
  const confirm = () => {
    placeQueued({
      icon: "trade", title: `Buy ${usd(orderAmt)} of ${sel.ticker}`,
      category: "Investment", kind: "once", state: "queued", agent: false,
      net: -orderAmt, scope: "yoshi", acct: "One-time order · Yoshi",
      fundedBy: t.id, funds: part, trigger: `${t.fromShort || "Chase"} transfer lands${!MARKET_OPEN ? " · then market open" : ""}`,
      cancelNote: `Prepped and waiting — Yoshi buys ${sel.ticker} the moment your ${usd(t.amount)} ${t.fromShort || "Chase"} transfer lands${!MARKET_OPEN ? ", at the next market open" : ""}. Cancel any time before then.`,
      steps: [["Prepared", "Just now"], [`Waiting on your ${t.fromShort || "Chase"} transfer`, "You are here"], [`Buys at ${!MARKET_OPEN ? "the next market open" : "the live price"}`, "after the funds land"]], stepAt: 1,
      settle: { icon: "trade", title: `Bought ${sel.ticker}`, detail: "Notional order · funds landed", category: "Investment", accountScope: "yoshi", net: -orderAmt },
    });
  };

  return (
    <div className="push-enter" data-screen-label="Queued order review" style={{ position: "absolute", inset: 0, zIndex: 60, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", justifyContent: "flex-end", padding: "10px 20px 0", flex: "none" }}>
        <button className="press" onClick={onBack} aria-label="Close" style={{ background: "none", border: "none", padding: 0, color: "var(--ink-3)", display: "flex", cursor: "pointer" }}><Icon name="close" size={19} /></button>
      </div>
      <div style={{ padding: "2px 20px 0", flex: "none" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, flex: "none", border: "1.5px solid var(--ink-3)" }} />
          <span style={{ fontFamily: "var(--f-display)", fontSize: typeSize(10), fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)" }}>One-time automation</span>
        </div>
      </div>

      <div className="scroll" style={{ padding: "0 20px" }}>
        <div style={{ fontFamily: "var(--f-display)", fontSize: typeSize(22), fontWeight: 600, letterSpacing: "-0.025em", marginTop: 8 }}>Runs when your transfer lands</div>
        <div style={{ fontFamily: "var(--f-display)", fontSize: typeSize(13.5), color: "var(--ink-2)", marginTop: 7, lineHeight: 1.55 }}>
          Yoshi places this the moment your {usd(t.amount)} pending transfer from Chase lands{!MARKET_OPEN ? ", at the next market open" : ""}, and notifies you when it runs. There's no set date — it runs whenever the funds arrive.
        </div>

        <Eyebrow style={{ margin: "16px 0 7px" }}>Order</Eyebrow>
        <div style={{ border: "1px solid var(--rule-2)", borderRadius: 12, overflow: "hidden" }}>
          <LegRow leg={["BUY", { ticker: sel.ticker, price: usd(sel.last, 2), change: secChange, changeTone: secTone, name: sel.name, valueLabel: `Notional order · final shares at execution price` }, "", usd(amtNum)]} />
          <LegRow leg={["FROM", "Yoshi Cash ••8841", `${usd(avail)} available now`, "−" + usd(avail)]} />
          <LegRow leg={["FROM", "Pending transfer · Chase", `Lands when received`, "−" + usd(part)]} last />
        </div>

        <Eyebrow style={{ margin: "16px 0 7px" }}>Funding</Eyebrow>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <FundingOption on={mode === "together"} onPick={() => setMode("together")}
            title="Run everything when it lands"
            sub={`${usd(avail)} available + ${usd(part)} pending execute as one order — one price, one fill.`} />
          <FundingOption on={mode === "split"} onPick={() => setMode("split")}
            title={`Invest ${usd(avail)} now`}
            sub={`Executes immediately. The remaining ${usd(part)} runs when the transfer lands.`} />
        </div>

        <div style={{ display: "flex", alignItems: "flex-start", gap: 8, marginTop: 12, marginBottom: 8, padding: "10px 12px", background: "var(--bg-2)" }}>
          <Icon name="shield" size={16} color="var(--ink-3)" stroke={1.5} style={{ flex: "none", marginTop: 1 }} />
          <span style={{ fontFamily: "var(--f-display)", fontSize: typeSize(11), color: "var(--ink-3)", lineHeight: 1.45 }}>
            Sits in In motion as a one-time automation you can cancel any time. If the transfer doesn't land, the order is cancelled and you're alerted — nothing runs silently.
          </span>
        </div>
      </div>

      <div style={{ flex: "none", padding: "0 20px" }}><Seam style={{ margin: "12px 0 0", background: "var(--rule-2)", opacity: 1 }} /></div>
      <div style={{ flex: "none", padding: "12px 20px 20px" }}>
        <Btn full onClick={confirm}>Confirm with passkey</Btn>
        <Btn kind="ghost" full onClick={onBack} style={{ marginTop: 8 }}>Back</Btn>
      </div>
    </div>
  );
};

/* ============================================================
   QueuedTransferReview · the transfer twin of QueuedTradeReview.
   A Move out of Yoshi Cash that dips into still-pending funds gets
   the SAME one-time-automation treatment; transfers only wait on
   the funds (no market-open leg).
   ============================================================ */
const QueuedTransferReview = ({ fromName, toName, amtNum, avail, t, onBack }) => {
  const [mode, setMode] = useState("together");
  const part = +(amtNum - avail).toFixed(2);
  const moveAmt = mode === "split" ? part : amtNum;

  // "Confirm with passkey" places it straight into In motion (→ Activity),
  // like every other confirm in the app — no second passkey modal.
  const confirm = () => {
    placeQueued({
      icon: "swap", title: `Move ${usd(moveAmt)} to ${toName}`,
      category: "Transfer", kind: "once", state: "queued", agent: false,
      trigger: `${t.fromShort || "Chase"} transfer lands`,
      net: -moveAmt, scope: "yoshi", acct: `${fromName} → ${toName}`, rail: "Standard ACH",
      fundedBy: t.id, funds: part,
      cancelNote: `Prepped and waiting — Yoshi sends this the moment your ${usd(t.amount)} ${t.fromShort || "Chase"} transfer lands. Cancel any time before then.`,
      steps: [["Prepared", "Just now"], [`Waiting on your ${t.fromShort || "Chase"} transfer`, "You are here"], ["Sends · Standard ACH", "after the funds land"]], stepAt: 1,
      settle: { icon: "swap", title: toName, detail: "Standard ACH · funds landed", category: "Transfer", accountScope: "yoshi", net: -moveAmt },
    });
  };

  return (
    <div className="push-enter" data-screen-label="Queued transfer review" style={{ position: "absolute", inset: 0, zIndex: 60, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      {window.StatusBar && <window.StatusBar />}
      <div style={{ display: "flex", justifyContent: "flex-end", padding: "10px 20px 0", flex: "none" }}>
        <button className="press" onClick={onBack} aria-label="Close" style={{ background: "none", border: "none", padding: 0, color: "var(--ink-3)", display: "flex", cursor: "pointer" }}><Icon name="close" size={19} /></button>
      </div>
      <div style={{ padding: "2px 20px 0", flex: "none" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, flex: "none", border: "1.5px solid var(--ink-3)" }} />
          <span style={{ fontFamily: "var(--f-display)", fontSize: typeSize(10), fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)" }}>One-time automation</span>
        </div>
      </div>

      <div className="scroll" style={{ padding: "0 20px" }}>
        <div style={{ fontFamily: "var(--f-display)", fontSize: typeSize(22), fontWeight: 600, letterSpacing: "-0.025em", marginTop: 8 }}>Runs when your transfer lands</div>
        <div style={{ fontFamily: "var(--f-display)", fontSize: typeSize(13.5), color: "var(--ink-2)", marginTop: 7, lineHeight: 1.55 }}>
          Yoshi sends this the moment your {usd(t.amount)} pending transfer from Chase lands, and notifies you when it runs. There's no set date — it runs whenever the funds arrive.
        </div>

        <Eyebrow style={{ margin: "16px 0 7px" }}>Transfer</Eyebrow>
        <div style={{ border: "1px solid var(--rule-2)", borderRadius: 12, overflow: "hidden" }}>
          <LegRow leg={["TO", toName, "Standard ACH · no fee", usd(amtNum)]} />
          <LegRow leg={["FROM", `${fromName} ••8841`, `${usd(avail)} available now`, "−" + usd(avail)]} />
          <LegRow leg={["FROM", "Pending transfer · Chase", `Lands when received`, "−" + usd(part)]} last />
        </div>

        <Eyebrow style={{ margin: "16px 0 7px" }}>Funding</Eyebrow>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <FundingOption on={mode === "together"} onPick={() => setMode("together")}
            title="Send everything when it lands"
            sub={`${usd(avail)} available + ${usd(part)} pending move as one transfer when the funds land.`} />
          <FundingOption on={mode === "split"} onPick={() => setMode("split")}
            title={`Move ${usd(avail)} now`}
            sub={`Sends immediately. The remaining ${usd(part)} moves when the transfer lands.`} />
        </div>

        <div style={{ display: "flex", alignItems: "flex-start", gap: 8, marginTop: 12, marginBottom: 8, padding: "10px 12px", background: "var(--bg-2)" }}>
          <Icon name="shield" size={16} color="var(--ink-3)" stroke={1.5} style={{ flex: "none", marginTop: 1 }} />
          <span style={{ fontFamily: "var(--f-display)", fontSize: typeSize(11), color: "var(--ink-3)", lineHeight: 1.45 }}>
            Sits in In motion as a one-time automation you can cancel any time. If the incoming transfer doesn't land, this is cancelled and you're alerted — nothing runs silently.
          </span>
        </div>
      </div>

      <div style={{ flex: "none", padding: "0 20px" }}><Seam style={{ margin: "12px 0 0", background: "var(--rule-2)", opacity: 1 }} /></div>
      <div style={{ flex: "none", padding: "12px 20px 20px" }}>
        <Btn full onClick={confirm}>Confirm with passkey</Btn>
        <Btn kind="ghost" full onClick={onBack} style={{ marginTop: 8 }}>Back</Btn>
      </div>
    </div>
  );
};

Object.assign(window, { FundingOption, QueuedTradeReview, QueuedTransferReview });
