// screens_settle.jsx — per-person Share/Tip/Total, You special-cased,
// request via payment apps, save to history. -> window.

function PayGlyph({ app }) {
  const m = {
    venmo: <span style={{ fontWeight: 800, fontSize: 20, fontStyle: 'italic' }}>V</span>,
    cashapp: <IconDollar s={20} />,
    apple: <svg width="19" height="19" viewBox="0 0 24 24" fill="currentColor"><path d="M16.4 12.6c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.4-.1-2.8.8-3.5.8s-1.8-.8-3-.8c-1.5 0-3 .9-3.8 2.3-1.6 2.8-.4 7 1.2 9.3.8 1.1 1.7 2.4 2.9 2.3 1.2 0 1.6-.7 3-.7s1.8.7 3 .7 2-1.1 2.8-2.2c.9-1.3 1.2-2.5 1.3-2.6-.1 0-2.5-1-2.5-3.8zM14.2 5.4c.6-.8 1-1.9.9-3-.9 0-2 .6-2.7 1.4-.6.7-1.1 1.8-.9 2.9 1 .1 2-.5 2.7-1.3z"/></svg>,
    zelle: <span style={{ fontWeight: 800, fontSize: 19 }}>Z</span>,
    paypal: <span style={{ fontWeight: 800, fontSize: 18, fontStyle: 'italic' }}>P</span>,
  };
  return m[app.glyph] || <span style={{ fontWeight: 800 }}>{app.name[0]}</span>;
}

function SettleScreen({ state, set, derived, currency, nav, toast, onComplete, settings }) {
  const [reqFor, setReqFor] = React.useState(null);
  const person = derived.rows.find((r) => r.id === reqFor);
  const requested = state.requested || {};
  const paid = state.paid || {};
  // people who actually owe something (a guest who ordered nothing is hidden)
  const owing = derived.rows.filter((r) => r.you || r.total > 0);

  const requestVia = (app) => {
    if (!person) return;
    const now = new Date();
    set({ requested: { ...requested, [person.id]: { method: app.id, at: now.toISOString(), amount: person.total } } });
    setReqFor(null);
    toast(`Requested ${fmt(person.total, currency)} from ${person.name} · ${app.name}`, <IconCheckCircle s={18} />);
  };
  const markPaid = (id) => set({ paid: { ...paid, [id]: !paid[id] } });

  const others = owing.filter((r) => !r.you);
  const allDone = others.every((r) => paid[r.id]);

  const save = () => { onComplete(); };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="Settle up" onBack={() => nav('tip')} sub={state.merchant || null} />
      <Steps active="Settle" />

      <div className="ta-scroll" style={{ flex: 1, padding: '10px 18px 8px' }}>
        {/* totals */}
        <Card style={{ marginBottom: 14, padding: '15px 18px' }}>
          {[['Subtotal', derived.subtotal], derived.tax ? [`Tax`, derived.tax] : null, [`Tip · ${state.tipPct}%`, derived.tip], derived.roundingAdj ? ['Rounding', derived.roundingAdj] : null].filter(Boolean).map(([l, v]) => (
            <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, marginBottom: 7 }}>
              <span style={{ color: 'var(--on-surface-var)', whiteSpace: 'nowrap' }}>{l}</span>
              <span className="ta-num" style={{ fontWeight: 700 }}>{l === 'Rounding' && v > 0 ? '+' : ''}{fmt(v, currency)}</span>
            </div>
          ))}
          <div style={{ height: 1, background: 'var(--outline-faint)', margin: '4px 0 10px' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontWeight: 700 }}>Total due</span>
            <span className="ta-num" style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--num-weight)', fontSize: 24 }}>{fmt(derived.grand, currency)}</span>
          </div>
        </Card>

        <Label style={{ marginBottom: 10, padding: '0 2px' }}>Who owes what</Label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {owing.map((r) => {
            const isPaid = paid[r.id];
            const req = requested[r.id];
            const reqApp = req && PAYMENT_APPS.find((a) => a.id === req.method);
            return (
              <div key={r.id} style={{ background: r.you ? 'var(--surface-alt)' : 'var(--surface)', borderRadius: 'var(--radius)', padding: '12px 14px',
                boxShadow: r.you ? 'none' : 'var(--shadow-soft)', border: r.you ? '1.5px solid var(--outline-faint)' : 'none', opacity: isPaid ? 0.62 : 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <Avatar person={r} size={42} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }}>
                      {r.you ? 'You' : r.name}
                      {r.you && <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: 0.4, color: 'var(--on-surface-var)', background: 'var(--surface-variant)', borderRadius: 99, padding: '2px 7px', whiteSpace: 'nowrap', flexShrink: 0 }}>YOUR SHARE</span>}
                      {isPaid && <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--good)', display: 'inline-flex', alignItems: 'center', gap: 3 }}><IconCheck s={13} />PAID</span>}
                    </div>
                    <div className="ta-num" style={{ fontSize: 12.5, color: 'var(--on-surface-var)' }}>
                      {fmt(r.share, currency)} + {fmt(r.tip, currency)} tip{reqApp && !isPaid ? ` · via ${reqApp.name}` : ''}
                    </div>
                  </div>
                  <span className="ta-num" style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--num-weight)', fontSize: 19, textDecoration: isPaid ? 'line-through' : 'none' }}>{fmt(r.total, currency)}</span>
                </div>
                {!r.you && !isPaid && (
                  <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
                    <button className="ta-press" onClick={() => setReqFor(r.id)} style={{ flex: 1, height: 42, borderRadius: 99, border: 'none', cursor: 'pointer', background: reqApp ? 'var(--primary-container)' : 'var(--primary)', color: reqApp ? 'var(--on-primary-container)' : 'var(--on-primary)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}>
                      <IconDollar s={16} /> {reqApp ? 'Requested · change' : 'Request'}
                    </button>
                    <button className="ta-press" onClick={() => markPaid(r.id)} title="Mark as paid" style={{ width: 46, height: 42, borderRadius: 99, cursor: 'pointer', border: '1.5px solid var(--outline)', background: 'transparent', color: 'var(--on-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconCheck s={20} /></button>
                  </div>
                )}
                {!r.you && isPaid && (
                  <button className="ta-press" onClick={() => markPaid(r.id)} style={{ marginTop: 10, width: '100%', height: 38, borderRadius: 99, cursor: 'pointer', border: '1.5px solid var(--outline)', background: 'transparent', color: 'var(--on-surface-var)', fontWeight: 700, fontSize: 13 }}>Mark as unpaid</button>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ background: 'var(--surface)', borderTopLeftRadius: 28, borderTopRightRadius: 28, padding: '12px 18px 14px', boxShadow: '0 -6px 24px rgba(0,0,0,0.05)' }}>
        <Button onClick={save} variant={allDone ? 'filled' : 'tonal'} leading={allDone ? <IconCheck s={20} /> : <IconClock s={19} />}>
          {allDone ? 'Done · save to history' : 'Save to history'}
        </Button>
      </div>

      <Sheet open={!!reqFor} onClose={() => setReqFor(null)} title={person ? `Request ${fmt(person.total, currency)}` : ''}>
        {person && <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, padding: '0 2px' }}>
          <Avatar person={person} size={34} /><span style={{ fontWeight: 600, color: 'var(--on-surface-var)' }}>from <b style={{ color: 'var(--on-surface)' }}>{person.name}</b></span>
        </div>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {PAYMENT_APPS.filter((a) => (settings.payApps || PAYMENT_APPS.map((x) => x.id)).includes(a.id)).map((a) => (
            <button key={a.id} className="ta-press" onClick={() => requestVia(a)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '12px 14px', borderRadius: 'var(--radius-sm)', border: 'none', cursor: 'pointer', background: 'var(--surface-variant)', textAlign: 'left' }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: a.color, color: a.fg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><PayGlyph app={a} /></div>
              <span style={{ flex: 1, fontWeight: 700, fontSize: 15.5, color: 'var(--on-surface)' }}>{a.name}</span>
              <IconChevron s={20} style={{ color: 'var(--on-surface-var)' }} />
            </button>
          ))}
        </div>
      </Sheet>
    </div>
  );
}

Object.assign(window, { SettleScreen, PayGlyph });
