// Split Crew — settle up & confirmation screens (v2 with perspective + merge)

function computeTransfers(expenses, members) {
  // Each expense splits evenly across ALL current crew members,
  // not just whoever was in the original splitWith. Keeps balances correct
  // even when a member joined after the first expenses were logged.
  //
  // Math is done in the trip's HOME currency. We prefer `e.home` (the
  // canonical home-currency snapshot saved at expense-create time using
  // the trip's frozen FX rates). For legacy expenses without `home`, we
  // fall back to `e.sek` so old data keeps working.
  const balances = {};
  members.forEach(p => balances[p] = 0);
  if (!members.length) return { transfers: [] };
  for (const e of expenses) {
    const amt = (e.home != null ? Number(e.home) : Number(e.sek)) || 0;
    const share = amt / members.length;
    for (const p of members) balances[p] -= share;
    if (balances[e.paidBy] !== undefined) balances[e.paidBy] += amt;
  }
  const d = Object.entries(balances).filter(([_,v]) => v < -1).sort((a,b) => a[1] - b[1])
    .map(x => ({ name: x[0], amt: -x[1] }));
  const cr = Object.entries(balances).filter(([_,v]) => v > 1).sort((a,b) => b[1] - a[1])
    .map(x => ({ name: x[0], amt: x[1] }));
  const transfers = [];
  let di = 0, ci = 0;
  while (di < d.length && ci < cr.length) {
    const t = Math.min(d[di].amt, cr[ci].amt);
    transfers.push({ id: `${d[di].name}-${cr[ci].name}`, from: d[di].name, to: cr[ci].name, amt: Math.round(t) });
    d[di].amt -= t; cr[ci].amt -= t;
    if (d[di].amt < 1) di++;
    if (cr[ci].amt < 1) ci++;
  }
  return { transfers, balances };
}

const CREW_4 = {
  Du: PEOPLE_COLORS.Y, Elin: PEOPLE_COLORS.E, Max: PEOPLE_COLORS.M, Nils: PEOPLE_COLORS.S,
};
const initOf = (n) => n === 'Du' ? 'Y' : n[0];
const colorOf = (n) => CREW_4[n] || PEOPLE_COLORS.Y;

function rerouteOnce(transfers, inc, out, perspective) {
  const m = Math.min(inc.amt, out.amt);
  const next = [];
  for (const t of transfers) {
    if (t.id === inc.id) {
      if (t.amt - m > 1) next.push({ ...t, amt: t.amt - m });
    } else if (t.id === out.id) {
      if (t.amt - m > 1) next.push({ ...t, amt: t.amt - m });
    } else {
      next.push(t);
    }
  }
  // Reroute: inc.from now owes out.to directly
  const existing = next.find(t => t.from === inc.from && t.to === out.to);
  if (existing) { existing.amt += m; existing.rerouted = true; }
  else next.push({ id: `${inc.from}-${out.to}-m-${Date.now()}`, from: inc.from, to: out.to, amt: m, rerouted: true });
  return next;
}

function SettleScreen({ ctx }) {
  // Members come from the pot (the real crew), not hardcoded friends.
  const MEMBERS = (ctx.pot && ctx.pot.members && ctx.pot.members.length) ? ctx.pot.members : ['Du'];
  // Use only the crew's real expenses — no demo injections.
  const demoExpenses = ctx.expenses;

  // Trip's home currency (set at create-name) and the FX snapshot taken
  // when the trip was created. Used to (a) label all amounts, and (b) show
  // a SEK reference next to non-SEK home amounts.
  const homeCurrency = (ctx.pot && ctx.pot.homeCurrency) || 'SEK';
  const fxRates = (ctx.pot && ctx.pot.fxRates) || null;

  const { transfers: initial } = computeTransfers(demoExpenses, MEMBERS);
  const [transfers, setTransfers] = React.useState(initial);
  const [paid, setPaid] = React.useState({});
  const myName = ctx.myName || 'Du';
  const [perspective, setPerspective] = React.useState(myName); // viewer sees all from their POV

  const isCreator = perspective === myName;
  const visible = isCreator
    ? transfers
    : transfers.filter(t => t.from === perspective || t.to === perspective);

  // Merge candidates for CURRENT perspective: I receive X from A, and I owe Y to B → reroute min(X,Y) from A to B
  const myIncoming = transfers.filter(t => t.to === perspective);
  const myOutgoing = transfers.filter(t => t.from === perspective);
  const canMerge = myIncoming.length > 0 && myOutgoing.length > 0;

  // Single-pair reroute (one tap)
  const doMerge = () => {
    const inc = [...myIncoming].sort((a,b) => b.amt - a.amt)[0];
    const out = [...myOutgoing].sort((a,b) => b.amt - a.amt)[0];
    if (!inc || !out) return;
    setTransfers(rerouteOnce(transfers, inc, out, perspective));
  };

  // Fully optimize: keep rerouting until I have no incoming OR no outgoing
  const doOptimize = () => {
    let next = transfers;
    for (let i = 0; i < 20; i++) {
      const inc = next.filter(t => t.to === perspective).sort((a,b) => b.amt - a.amt)[0];
      const out = next.filter(t => t.from === perspective).sort((a,b) => b.amt - a.amt)[0];
      if (!inc || !out) break;
      next = rerouteOnce(next, inc, out, perspective);
    }
    setTransfers(next);
  };

  return (
    <div>
      <AppHeader back={() => ctx.go('dashboard')} title="SETTLE UP" right={
        <button onClick={() => setPerspective(p => MEMBERS[(MEMBERS.indexOf(p) + 1) % MEMBERS.length])} style={{
          background: 'transparent', border: '1px solid var(--line)', color: 'var(--cyan-500)',
          fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.18em',
          padding: '4px 6px', cursor: 'pointer', fontWeight: 600,
        }}>{perspective.toUpperCase()} ↓</button>
      } />
      <div style={{ padding: '0 24px 80px' }}>
        <h1 className="display" style={{ fontSize: 26, lineHeight: 1.05, marginBottom: 8 }}>
          {isCreator ? 'Full trip settlement' : 'Your transfers'}
        </h1>
        <p style={{ fontSize: 11, color: 'var(--text-mu)', lineHeight: 1.5, marginBottom: 14 }}>
          {isCreator
            ? <>As the creator you see all {transfers.length} transfers for the crew.</>
            : <>You only see what concerns you. Check off when you've paid — the recipient confirms.</>
          }
        </p>

        {/* Personal summary banner */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8,
        }}>
          <div style={{ flex: 1, height: 1, background: 'var(--cyan-500)', opacity: 0.4 }} />
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.28em', color: 'var(--cyan-500)' }}>◆ YOUR LEDGER</div>
          <div style={{ flex: 1, height: 1, background: 'var(--cyan-500)', opacity: 0.4 }} />
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-mu)', lineHeight: 1.5, marginBottom: 10, textAlign: 'center' }}>
          Your debts are maximized and netted against everyone else's — you'll only ever pay the minimum.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 18 }}>
          <SummaryCard label={`${perspective.toUpperCase()} GETS`} amount={myIncoming.reduce((s,t) => s + t.amt, 0)} tint="#7DE08B" homeCurrency={homeCurrency} fxRates={fxRates} />
          <SummaryCard label={`${perspective.toUpperCase()} PAYS`} amount={myOutgoing.reduce((s,t) => s + t.amt, 0)} tint="#E86B3B" homeCurrency={homeCurrency} fxRates={fxRates} />
        </div>

        {/* Optimize / settle */}
        {canMerge && (
          <div style={{
            border: '1px dashed var(--cyan-500)',
            background: 'rgba(59,180,232,0.04)',
            padding: '12px 14px', marginBottom: 14,
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 10 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.2em', color: 'var(--cyan-500)', marginBottom: 3 }}>◆ MINIMIZE {perspective.toUpperCase()}'S TRANSFERS</div>
                <div style={{ fontSize: 11, color: 'var(--text)', lineHeight: 1.45 }}>
                  Your debts are netted against everyone else's — money owed to <b style={{color:'var(--text-hi)'}}>{perspective}</b> flows directly to the people <b style={{color:'var(--text-hi)'}}>{perspective}</b> owes. Creates new direct transfers between others.
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button onClick={doOptimize} style={{
                flex: 1, padding: '10px 12px', background: 'var(--cyan-500)',
                border: 'none', color: '#000', cursor: 'pointer',
                fontFamily: 'var(--font-display)', letterSpacing: '0.14em', fontSize: 11, fontWeight: 700,
              }}>⇄ SETTLE ALL</button>
              <button onClick={doMerge} style={{
                padding: '10px 12px', background: 'transparent',
                border: '1px solid var(--line)', color: 'var(--cyan-100)', cursor: 'pointer',
                fontFamily: 'var(--font-display)', letterSpacing: '0.14em', fontSize: 10, fontWeight: 600,
              }}>STEP</button>
            </div>
          </div>
        )}

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, marginTop: 4,
        }}>
          <div style={{ flex: 1, height: 1, background: 'var(--line)', opacity: 0.6 }} />
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.28em', color: 'var(--text-mu)' }}>◆ TRANSFERS</div>
          <div style={{ flex: 1, height: 1, background: 'var(--line)', opacity: 0.6 }} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {visible.map((t, i) => {
            const state = paid[t.id];
            const direction = t.from === perspective ? 'out' : t.to === perspective ? 'in' : 'other';
            return (
              <TransferRow
                key={t.id + i}
                transfer={t}
                perspective={perspective}
                direction={direction}
                state={state}
                onSent={() => setPaid({ ...paid, [t.id]: 'sent' })}
                onConfirm={() => ctx.go('settle-confirm')}
                isCreatorView={isCreator}
                homeCurrency={homeCurrency}
                fxRates={fxRates}
              />
            );
          })}
          {visible.length === 0 && (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-mu)', fontSize: 12, border: '1px dashed var(--line-subtle)' }}>
              You're even. No transfers to make. ✓
            </div>
          )}
        </div>

        {/* Danger zone — delete trip */}
        <div style={{ marginTop: 40 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12,
          }}>
            <div style={{ flex: 1, height: 1, background: 'rgba(232,107,59,0.3)' }} />
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.28em', color: '#E86B3B' }}>◆ DANGER ZONE</div>
            <div style={{ flex: 1, height: 1, background: 'rgba(232,107,59,0.3)' }} />
          </div>
          <DeleteTripBlock ctx={ctx} />
        </div>
      </div>
    </div>
  );
}

function DeleteTripBlock({ ctx }) {
  const [confirming, setConfirming] = React.useState(false);
  const tripName = (ctx.pot && ctx.pot.name) ? ctx.pot.name : 'this trip';
  const hasSettlements = !!ctx.hasSettlements;
  const isAdmin = !!ctx.isAdmin;

  // Per the flow rules: only the creator can delete the trip,
  // and only before any debt has been settled.
  if (!isAdmin) {
    return (
      <div style={{
        padding: '12px 14px',
        border: '1px dashed var(--line-subtle)',
        background: 'rgba(10,20,32,0.4)',
        fontSize: 11, color: 'var(--text-mu)', lineHeight: 1.5, textAlign: 'center',
        fontFamily: 'var(--font-display)', letterSpacing: '0.14em',
      }}>
        ONLY THE TRIP CREATOR CAN DELETE THIS TRIP
      </div>
    );
  }

  if (hasSettlements) {
    return (
      <div style={{
        padding: '14px 16px',
        border: '1px solid var(--line-subtle)',
        background: 'rgba(10,20,32,0.4)',
        opacity: 0.7,
      }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--text-mu)', marginBottom: 6 }}>◆ DELETE LOCKED</div>
        <div style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.5 }}>
          Settlements have already been recorded in <b style={{ color: 'var(--text-hi)' }}>{tripName}</b>. The trip can no longer be deleted — the ledger has to stay intact for the crew.
        </div>
      </div>
    );
  }

  if (!confirming) {
    return (
      <button onClick={() => setConfirming(true)} style={{
        width: '100%', padding: '14px 16px',
        background: 'transparent', border: '1px solid rgba(232,107,59,0.4)',
        color: '#E86B3B', cursor: 'pointer',
        fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6M5 6l1 14a2 2 0 002 2h8a2 2 0 002-2l1-14"/></svg>
        Delete trip
      </button>
    );
  }

  return (
    <div className="bracket" style={{
      padding: 16, border: '1px solid #E86B3B',
      background: 'rgba(232,107,59,0.06)',
    }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.2em', color: '#E86B3B', marginBottom: 6 }}>◆ CONFIRM DELETE</div>
      <div style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.5, marginBottom: 14 }}>
        Permanently delete <b style={{ color: 'var(--text-hi)' }}>{tripName}</b> and all its expenses. Allowed only because no debt has been settled yet.
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={() => setConfirming(false)} style={{
          flex: 1, padding: '11px 12px', background: 'transparent',
          border: '1px solid var(--line)', color: 'var(--text)', cursor: 'pointer',
          fontFamily: 'var(--font-display)', letterSpacing: '0.16em', fontSize: 11, fontWeight: 600,
        }}>CANCEL</button>
        <button onClick={() => {
          if (ctx.deleteTrip) ctx.deleteTrip();
          else if (ctx.setPot) ctx.setPot({ name: '', members: [ctx.myName || 'Du'], code: '' });
          ctx.go('home');
        }} style={{
          flex: 1, padding: '11px 12px', background: '#E86B3B',
          border: '1px solid #E86B3B', color: '#000', cursor: 'pointer',
          fontFamily: 'var(--font-display)', letterSpacing: '0.16em', fontSize: 11, fontWeight: 700,
        }}>DELETE</button>
      </div>
    </div>
  );
}

function SummaryCard({ label, amount, tint, homeCurrency, fxRates }) {
  const home = homeCurrency || 'SEK';
  // Use the trip's frozen FX snapshot to compute the SEK reference. The
  // amount is in HOME currency (computeTransfers works in home currency).
  const sekRef = (window.convertFx
    ? window.convertFx(amount, home, 'SEK', fxRates, home)
    : amount);
  const showSek = home !== 'SEK';
  return (
    <div className="bracket" style={{
      background: `rgba(${tint === '#7DE08B' ? '125,224,139' : '232,107,59'},0.06)`,
      border: `1px solid ${tint}55`,
      padding: '12px 14px',
    }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.22em', color: tint }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: tint, marginTop: 4 }}>
        {amount > 0 && (label.includes('GETS') ? '+' : '−')}{Math.round(amount).toLocaleString('sv-SE').replace(/,/g,' ')} <span style={{ fontSize: 11, opacity: 0.7 }}>{home}</span>
      </div>
      {showSek && (
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, color: 'var(--text-mu)', marginTop: 2, letterSpacing: '0.08em' }}>
          ≈ {Math.round(sekRef).toLocaleString('sv-SE').replace(/,/g,' ')} SEK
        </div>
      )}
    </div>
  );
}

function TransferRow({ transfer: t, perspective, direction, state, onSent, onConfirm, isCreatorView, homeCurrency, fxRates }) {
  const home = homeCurrency || 'SEK';
  // Amount is in HOME currency. SEK reference is derived from the trip's
  // frozen FX snapshot. Falls through gracefully if rates aren't ready.
  const sekRef = (window.convertFx
    ? window.convertFx(t.amt, home, 'SEK', fxRates, home)
    : t.amt);
  const showSek = home !== 'SEK';
  const tint = direction === 'in' ? '#7DE08B' : direction === 'out' ? '#E86B3B' : 'var(--line)';
  const bg = state === 'confirmed' ? 'rgba(125,224,139,0.06)'
    : state === 'sent' ? 'rgba(245,198,74,0.06)'
    : direction === 'in' ? 'rgba(125,224,139,0.04)'
    : direction === 'out' ? 'rgba(232,107,59,0.04)'
    : 'rgba(10,20,32,0.5)';
  const border = state === 'confirmed' ? 'rgba(125,224,139,0.5)'
    : state === 'sent' ? 'rgba(245,198,74,0.5)'
    : direction !== 'other' ? tint + '66' : 'var(--line)';

  return (
    <div className="bracket" style={{
      background: bg, border: '1px solid ' + border,
      padding: '14px 14px', position: 'relative',
    }}>
      {t.rerouted && (
        <div style={{
          position: 'absolute', top: -7, left: 12,
          background: '#000', padding: '0 6px',
          fontFamily: 'var(--font-display)', fontSize: 9, color: 'var(--cyan-500)', letterSpacing: '0.18em',
        }}>◆ NETTED</div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: direction !== 'other' ? 10 : 0 }}>
        <CrewAvatar color={colorOf(t.from)} initial={initOf(t.from)} size={30} />
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 13, color: 'var(--text-hi)', fontWeight: 500 }}>{t.from}</span>
            <svg width="18" height="10" viewBox="0 0 20 10" fill="none" stroke="var(--cyan-500)" strokeWidth="1.5"><path d="M0 5h18M14 1l4 4-4 4"/></svg>
            <span style={{ fontSize: 13, color: 'var(--text-hi)', fontWeight: 500 }}>{t.to}</span>
            {direction === 'in' && <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-display)', fontSize: 9, color: '#7DE08B', letterSpacing: '0.18em' }}>YOU GET</span>}
            {direction === 'out' && <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-display)', fontSize: 9, color: '#E86B3B', letterSpacing: '0.18em' }}>YOU PAY</span>}
          </div>
          <div style={{ fontSize: 10, color: 'var(--text-mu)', fontFamily: 'var(--font-display)', letterSpacing: '0.14em', marginTop: 2 }}>
            {state === 'confirmed' ? 'CONFIRMED ✓' : state === 'sent' ? 'AWAITING CONFIRMATION' : 'UNPAID'}
          </div>
        </div>
        <CrewAvatar color={colorOf(t.to)} initial={initOf(t.to)} size={30} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22,
            color: direction === 'in' ? '#7DE08B' : direction === 'out' ? '#E86B3B' : 'var(--text-hi)',
            lineHeight: 1.1,
          }}>
            {direction === 'in' ? '+' : direction === 'out' ? '−' : ''}{t.amt.toLocaleString('sv-SE').replace(/,/g,' ')}
            <span style={{ fontSize: 12, color: 'var(--text-mu)', fontWeight: 500 }}> {home}</span>
          </div>
          {showSek && (
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, color: 'var(--text-mu)', letterSpacing: '0.08em', marginTop: 2 }}>
              ≈ {Math.round(sekRef).toLocaleString('sv-SE').replace(/,/g,' ')} SEK
            </div>
          )}
        </div>
        {direction === 'out' && (
          state === undefined ? (
            <button onClick={onSent} style={{
              padding: '8px 14px', border: '1px solid var(--cyan-500)',
              background: 'rgba(59,180,232,0.08)', color: 'var(--cyan-100)',
              fontFamily: 'var(--font-display)', letterSpacing: '0.18em', fontSize: 10, cursor: 'pointer', fontWeight: 600,
            }}>I'VE PAID</button>
          ) : state === 'sent' ? (
            <div style={{ padding: '8px 14px', border: '1px solid rgba(245,198,74,0.6)', color: '#F5C64A', fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em' }}>● WAITING</div>
          ) : (
            <div style={{ padding: '8px 14px', border: '1px solid rgba(125,224,139,0.6)', color: '#7DE08B', fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em' }}>✓ SETTLED</div>
          )
        )}
        {direction === 'in' && (
          state === 'sent' ? (
            <button onClick={onConfirm} style={{
              padding: '8px 14px', border: '1px solid #7DE08B',
              background: 'rgba(125,224,139,0.12)', color: '#7DE08B',
              fontFamily: 'var(--font-display)', letterSpacing: '0.18em', fontSize: 10, cursor: 'pointer', fontWeight: 600,
            }}>APPROVE →</button>
          ) : (
            <span style={{ fontSize: 10, color: 'var(--text-mu)', fontFamily: 'var(--font-display)', letterSpacing: '0.18em' }}>
              {state === 'confirmed' ? '✓ RECEIVED' : 'WAITING ON THEM'}
            </span>
          )
        )}
        {direction === 'other' && isCreatorView && (
          <span style={{ fontSize: 9, color: 'var(--text-mu)', fontFamily: 'var(--font-display)', letterSpacing: '0.16em' }}>
            {state === 'confirmed' ? '✓' : state === 'sent' ? '● WAITING' : 'UNPAID'}
          </span>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// CONFIRM
// ═══════════════════════════════════════════════════════════════
function SettleConfirmScreen({ ctx }) {
  const homeCurrency = (ctx.pot && ctx.pot.homeCurrency) || 'SEK';
  const fxRates = (ctx.pot && ctx.pot.fxRates) || null;
  // Demo amount: 400 home-currency units. We show the SEK reference too,
  // matching the rest of the settle flow.
  const demoHome = 400;
  const demoSek = (window.convertFx
    ? window.convertFx(demoHome, homeCurrency, 'SEK', fxRates, homeCurrency)
    : demoHome);
  return (
    <div>
      <AppHeader back={() => ctx.go('settle')} title="CONFIRM" />
      <div style={{ padding: '0 24px' }}>
        <div style={{ fontSize: 10, color: 'var(--cyan-500)', fontFamily: 'var(--font-display)', letterSpacing: '0.24em', marginBottom: 6 }}>
          ◉ NOTIFICATION · FROM NILS
        </div>
        <h1 className="display" style={{ fontSize: 26, lineHeight: 1.05, marginBottom: 14 }}>Did you receive the payment?</h1>

        <div className="bracket" style={{
          padding: 20, border: '1px solid var(--cyan-500)',
          background: 'linear-gradient(180deg, rgba(59,180,232,0.08), rgba(59,180,232,0.02))',
          marginBottom: 20,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14, justifyContent: 'center' }}>
            <CrewAvatar color={PEOPLE_COLORS.S} initial="N" size={40} />
            <svg width="28" height="14" viewBox="0 0 28 14" fill="none" stroke="var(--cyan-500)" strokeWidth="1.5"><path d="M0 7h24M20 2l5 5-5 5"/></svg>
            <CrewAvatar color={PEOPLE_COLORS.Y} initial="Y" size={40} />
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 38, color: 'var(--text-hi)', textAlign: 'center', letterSpacing: '-0.01em' }}>
            {demoHome} <span style={{ fontSize: 18, color: 'var(--text-mu)' }}>{homeCurrency}</span>
          </div>
          {homeCurrency !== 'SEK' && (
            <div style={{ textAlign: 'center', fontFamily: 'var(--font-display)', fontSize: 12, color: 'var(--text-mu)', letterSpacing: '0.08em', marginTop: 2 }}>
              ≈ {Math.round(demoSek).toLocaleString('sv-SE').replace(/,/g,' ')} SEK
            </div>
          )}
          <div style={{ textAlign: 'center', fontSize: 10, color: 'var(--text-mu)', fontFamily: 'var(--font-display)', letterSpacing: '0.2em', marginTop: 4 }}>
            SWISHED 14:32 · REF #8A4-F2K
          </div>
        </div>

        <div style={{ fontSize: 12, color: 'var(--text-mu)', marginBottom: 20, lineHeight: 1.5 }}>
          Check your Swish feed. When you approve, the transfer is marked settled for the whole crew.
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <button onClick={() => {
            // Mark a settlement on the trip — locks the creator's
            // "delete trip" and "kick guest" controls per the flow rules.
            if (ctx.recordSettlement) ctx.recordSettlement(1);
            ctx.go('settle');
          }} style={{
            width: '100%', padding: 15, background: 'rgba(125,224,139,0.12)',
            border: '1px solid #7DE08B', color: '#7DE08B',
            fontFamily: 'var(--font-display)', letterSpacing: '0.16em', fontSize: 13,
            cursor: 'pointer', fontWeight: 600,
          }}>✓ YES — APPROVE AND SETTLE</button>
          <button onClick={() => ctx.go('settle')} style={{
            width: '100%', padding: 14, background: 'transparent',
            border: '1px solid rgba(232,107,59,0.5)', color: '#E86B3B',
            fontFamily: 'var(--font-display)', letterSpacing: '0.16em', fontSize: 12,
            cursor: 'pointer',
          }}>✕ NO — I HAVEN'T RECEIVED IT</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SettleScreen, SettleConfirmScreen, computeTransfers });
