// screens_meta.jsx — History, Settings, BottomNav. -> window.

function relTime(iso) {
  const d = new Date(iso), now = new Date();
  const diff = (now - d) / 1000;
  if (diff < 3600) return Math.max(1, Math.round(diff / 60)) + 'm ago';
  if (diff < 86400) return Math.round(diff / 3600) + 'h ago';
  if (diff < 86400 * 7) return Math.round(diff / 86400) + 'd ago';
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
function clockTime(iso) {
  return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
}

// ── History ───────────────────────────────────────────────────
function HistoryScreen({ history, setHistory, currency, nav, settings, setSettings, toast }) {
  const [open, setOpen] = React.useState(null);
  const [reqFor, setReqFor] = React.useState(null);   // { hid, pi } whose request sheet is open

  // map across the people of one record
  const patchPerson = (hid, pi, fn) => setHistory(history.map((h) => h.id !== hid ? h : {
    ...h, people: h.people.map((p, i) => i !== pi ? p : fn(p)) }));

  // Mark paid / unpaid. A person who was never requested becomes a "cash / other"
  // settle so the toggle still works straight from History.
  const togglePaid = (hid, pi) => patchPerson(hid, pi, (p) => p.you ? p
    : p.request ? { ...p, request: { ...p.request, received: !p.request.received } }
    : { ...p, request: { method: 'cash', at: new Date().toISOString(), received: true } });
  const remove = (hid) => setHistory(history.filter((h) => h.id !== hid));

  // RequestSheet works on a live-bill-shaped person; build one from the record.
  const reqRecord = reqFor && history.find((h) => h.id === reqFor.hid);
  const reqP = reqRecord && reqRecord.people[reqFor.pi];
  const reqPerson = reqP && { id: reqFor.hid + ':' + reqFor.pi, name: reqP.name, color: reqP.color || 'var(--primary)', total: reqP.total };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="Divvy History" sub={`${history.length} split${history.length === 1 ? '' : 's'}`} />
      {history.length === 0 ? (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, color: 'var(--on-surface-var)', padding: 30 }}>
          <div style={{ width: 64, height: 64, borderRadius: 99, background: 'var(--surface-variant)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconClock s={30} /></div>
          <div style={{ fontWeight: 700, color: 'var(--on-surface)' }}>No history yet</div>
          <div style={{ fontSize: 13.5, textAlign: 'center' }}>After you Divvy a tab it will show here</div>
          <Button full={false} onClick={() => nav('home')} leading={<IconPlus s={19} />}>New split</Button>
        </div>
      ) : (
        <div className="ta-scroll" style={{ flex: 1, minHeight: 0, padding: '2px 18px 18px', display: 'flex', flexDirection: 'column', gap: 11 }}>
          {history.map((h) => {
            const cur = h.currency || currency;
            const owedOthers = h.people.filter((p) => !p.you);
            const settled = owedOthers.filter((p) => p.request && p.request.received).length;
            const isOpen = open === h.id;
            return (
              <Card key={h.id} pad={0} style={{ overflow: 'hidden' }}>
                <div className="ta-press" onClick={() => setOpen(isOpen ? null : h.id)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 16px', cursor: 'pointer' }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--secondary-container)', color: 'var(--on-secondary-container)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {h.mode === 'items' ? <IconReceipt s={22} /> : h.mode === 'even' ? <IconPeople s={22} /> : <IconDollar s={22} />}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.merchant || 'Divvy'}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--on-surface-var)' }}>{relTime(h.date)} · {h.people.length} people · {settled}/{owedOthers.length} settled</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="ta-num" style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--num-weight)', fontSize: 17 }}>{fmt(h.grand, cur)}</div>
                    <div style={{ fontSize: 11, color: 'var(--on-surface-var)' }}>incl {fmt(h.tip, cur)} tip</div>
                  </div>
                </div>
                {isOpen && (
                  <div className="ta-fade" style={{ padding: '2px 16px 14px', borderTop: '1px solid var(--outline-faint)' }}>
                    {h.people.map((p, i) => {
                      const app = p.request && PAYMENT_APPS.find((a) => a.id === p.request.method);
                      const methodLabel = !p.request ? null : app ? app.name : p.request.method === 'cash' ? 'Cash / other' : 'Requested';
                      const paid = !!(p.request && p.request.received);
                      const sub = p.you ? 'your share'
                        : paid ? `Paid · ${methodLabel}`
                        : p.request ? `${methodLabel} · ${clockTime(p.request.at)}`
                        : 'not requested';
                      return (
                        <div key={i} style={{ padding: '11px 0', borderBottom: i < h.people.length - 1 ? '1px solid var(--outline-faint)' : 'none' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                            <Avatar person={{ name: p.name, color: p.color || 'var(--primary)' }} size={34} />
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                                <span style={{ overflowWrap: 'anywhere' }}>{p.name}</span>
                                {paid && <span style={{ fontSize: 10.5, fontWeight: 800, color: 'var(--good)', display: 'inline-flex', alignItems: 'center', gap: 2 }}><IconCheck s={12} />PAID</span>}
                              </div>
                              <div style={{ fontSize: 11.5, color: 'var(--on-surface-var)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>
                            </div>
                            <span className="ta-num" style={{ fontWeight: 700, fontSize: 14, flexShrink: 0, textDecoration: paid ? 'line-through' : 'none', opacity: paid ? 0.6 : 1 }}>{fmt(p.total, cur)}</span>
                          </div>
                          {!p.you && (
                            paid ? (
                              <button className="ta-press" onClick={() => togglePaid(h.id, i)} style={{ marginTop: 9, width: '100%', height: 36, borderRadius: 99, cursor: 'pointer', border: '1.5px solid var(--outline)', background: 'transparent', color: 'var(--on-surface-var)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12.5 }}>Mark as unpaid</button>
                            ) : (
                              <div style={{ display: 'flex', gap: 8, marginTop: 9 }}>
                                <button className="ta-press" onClick={() => setReqFor({ hid: h.id, pi: i })} style={{ flex: 1, height: 38, borderRadius: 99, border: 'none', cursor: 'pointer', background: p.request ? 'var(--primary-container)' : 'var(--primary)', color: p.request ? 'var(--on-primary-container)' : 'var(--on-primary)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                                  <IconDollar s={15} /> {p.request ? 'Requested · resend' : 'Request'}
                                </button>
                                <button className="ta-press" onClick={() => togglePaid(h.id, i)} title="Mark as paid" style={{ width: 44, height: 38, borderRadius: 99, cursor: 'pointer', border: '1.5px solid var(--outline)', background: 'transparent', color: 'var(--on-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><IconCheck s={18} /></button>
                              </div>
                            )
                          )}
                        </div>
                      );
                    })}
                    <button className="ta-press" onClick={() => remove(h.id)} style={{ marginTop: 12, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--danger)', fontWeight: 700, fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
                      <IconTrash s={15} /> Delete this split
                    </button>
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}

      <RequestSheet open={!!reqPerson} person={reqPerson} merchant={reqRecord && reqRecord.merchant}
        currency={(reqRecord && reqRecord.currency) || currency}
        settings={settings} setSettings={setSettings} toast={toast}
        onClose={() => setReqFor(null)}
        onRequested={(req) => {
          if (!reqFor) return;
          patchPerson(reqFor.hid, reqFor.pi, (p) => ({ ...p, request: { ...req, received: !!(p.request && p.request.received) } }));
        }} />
    </div>
  );
}

// ── Settings ──────────────────────────────────────────────────
function Row({ label, children, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 2px' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 15 }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: 'var(--on-surface-var)', marginTop: 1 }}>{sub}</div>}
      </div>
      {children}
    </div>
  );
}

function SettingsScreen({ settings, setSettings, nav }) {
  const set = (patch) => setSettings({ ...settings, ...patch });
  const sel = {
    appearance: 'transparent', borderRadius: 99, border: '1.5px solid var(--outline)', color: 'var(--on-surface)',
    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, padding: '9px 14px', cursor: 'pointer', background: 'var(--surface)',
  };

  const accents = [
    { k: 'default', c: null }, { k: 'teal', c: '#0c6b5f' }, { k: 'indigo', c: '#5b4bff' },
    { k: 'coral', c: '#e0533d' }, { k: 'amber', c: '#a86b00' }, { k: 'violet', c: '#7c3aed' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="Settings" />
      <div className="ta-scroll" style={{ flex: 1, minHeight: 0, padding: '4px 18px 20px' }}>
        {/* Look & feel */}
        <Label style={{ margin: '6px 2px 10px' }}>Look &amp; feel</Label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 9, marginBottom: 14 }}>
          {DIRECTIONS.map((d) => {
            const on = settings.theme === d.id;
            return (
              <button key={d.id} className="ta-press" onClick={() => set({ theme: d.id })} style={{ cursor: 'pointer', borderRadius: 'var(--radius-sm)', padding: 11, textAlign: 'left',
                border: on ? '2px solid var(--primary)' : '1.5px solid var(--outline)', background: d.tok.bg, position: 'relative' }}>
                <div style={{ display: 'flex', gap: 4, marginBottom: 10 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 7, background: d.tok.primary }} />
                  <span style={{ width: 13, height: 22, borderRadius: 7, background: d.tok.surface, border: '1px solid rgba(128,128,128,0.25)' }} />
                </div>
                <div style={{ fontFamily: d.fontDisplay, fontWeight: 700, fontSize: 13, color: d.tok.onSurface }}>{d.label}</div>
                <div style={{ fontSize: 10, color: d.tok.onSurfaceVar }}>{d.tag}</div>
                {on && <div style={{ position: 'absolute', top: 8, right: 8, width: 18, height: 18, borderRadius: 99, background: 'var(--primary)', color: 'var(--on-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconCheck s={12} /></div>}
              </button>
            );
          })}
        </div>

        <Card pad={16} style={{ marginBottom: 16 }}>
          <Row label="Accent color" sub="Type follows your device's text size">
            <div style={{ display: 'flex', gap: 6 }}>
              {accents.map((a) => {
                const on = settings.accent === a.k;
                return <button key={a.k} className="ta-press" onClick={() => set({ accent: a.k })} title={a.k} style={{ width: 26, height: 26, borderRadius: 8, cursor: 'pointer', flexShrink: 0,
                  border: on ? '2px solid var(--on-surface)' : '1px solid var(--outline)',
                  background: a.c || 'conic-gradient(from 90deg,#0c6b5f,#5b4bff,#e0533d,#a86b00,#0c6b5f)' }} />;
              })}
            </div>
          </Row>
        </Card>

        {/* Bill defaults */}
        <Label style={{ margin: '2px 2px 10px' }}>Bill defaults</Label>
        <Card pad={16} style={{ marginBottom: 16 }}>
          <Row label="Currency">
            <select value={settings.currency} onChange={(e) => set({ currency: e.target.value })} style={sel}>
              {Object.keys(CURRENCIES).map((c) => <option key={c} value={c}>{c} {curMeta(c).symbol}</option>)}
            </select>
          </Row>
          <div style={{ height: 1, background: 'var(--outline-faint)' }} />
          <Row label="Default tip" sub={`${settings.defaultTip}%`}>
            <div style={{ width: 130 }}><Slider value={settings.defaultTip} min={0} max={30} step={1} onChange={(v) => set({ defaultTip: v })} /></div>
          </Row>
          <div style={{ height: 1, background: 'var(--outline-faint)' }} />
          <Row label="Rounding" sub="applied to each person's total">
            <select value={settings.rounding} onChange={(e) => set({ rounding: e.target.value })} style={sel}>
              <option value="off">Off · to the cent</option>
              <option value="nearest">Nearest whole {curMeta(settings.currency).symbol}</option>
              <option value="up">Round each up</option>
            </select>
          </Row>
        </Card>

        {/* Payment methods */}
        <Label style={{ margin: '2px 2px 10px' }}>Payment methods</Label>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--on-surface-var)', marginBottom: 10 }}>Shown when requesting money</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {PAYMENT_APPS.map((a) => {
              const enabled = (settings.payApps || PAYMENT_APPS.map((x) => x.id)).includes(a.id);
              const toggle = () => {
                const cur = settings.payApps || PAYMENT_APPS.map((x) => x.id);
                set({ payApps: enabled ? cur.filter((x) => x !== a.id) : [...cur, a.id] });
              };
              return (
                <button key={a.id} className="ta-press" onClick={toggle} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', borderRadius: 99, padding: '7px 13px 7px 8px',
                  border: enabled ? 'none' : '1.5px solid var(--outline)', background: enabled ? 'var(--primary-container)' : 'transparent', color: enabled ? 'var(--on-primary-container)' : 'var(--on-surface-var)', fontWeight: 700, fontSize: 13 }}>
                  <span style={{ width: 24, height: 24, borderRadius: 7, background: a.color, color: a.fg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800 }}><PayGlyph app={a} /></span>
                  {a.name}{enabled && <IconCheck s={15} />}
                </button>
              );
            })}
          </div>
        </Card>

        {/* Your payment handles — used to build real request links */}
        <Label style={{ margin: '18px 2px 10px' }}>Your payment handles</Label>
        <Card pad={16}>
          <div style={{ fontSize: 12.5, color: 'var(--on-surface-var)', marginBottom: 12 }}>Used to build the links and QR codes people pay you with. Apple Cash needs nothing — it sends in Messages.</div>
          {(() => {
            const mh = settings.myHandles || {};
            const setH = (k, v) => set({ myHandles: { ...mh, [k]: v } });
            const inputBox = { display: 'flex', alignItems: 'center', borderRadius: 12, border: '1.5px solid var(--outline)', background: 'var(--surface-variant)', padding: '0 12px', height: 46 };
            const inputEl = { flex: 1, minWidth: 0, height: '100%', border: 'none', background: 'transparent', outline: 'none', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--on-surface)' };
            const pfx = { fontWeight: 700, color: 'var(--on-surface-var)', fontSize: 15, flexShrink: 0 };
            const rows = [
              { k: 'venmo', name: 'Venmo', prefix: '@', ph: 'username' },
              { k: 'cashapp', name: 'Cash App', prefix: '$', ph: 'cashtag' },
              { k: 'zelle', name: 'Zelle', prefix: '', ph: 'email or phone' },
            ];
            return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                {rows.map((r) => (
                  <div key={r.k}>
                    <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--on-surface-var)', marginBottom: 5, paddingLeft: 2 }}>{r.name}</div>
                    <div style={inputBox}>
                      {r.prefix && <span style={pfx}>{r.prefix}</span>}
                      <input value={mh[r.k] || ''} onChange={(e) => setH(r.k, e.target.value)} placeholder={r.ph} autoCapitalize="none" autoCorrect="off" spellCheck={false} style={inputEl} />
                    </div>
                  </div>
                ))}
              </div>
            );
          })()}
        </Card>

        <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--on-surface-var)', marginTop: 18 }}>DivvyTab · v{APP_VERSION}</div>
      </div>
    </div>
  );
}

// ── Bottom navigation ─────────────────────────────────────────
function BottomNav({ tab, nav }) {
  const items = [
    { id: 'home', label: 'Divvy', icon: IconDivvy },
    { id: 'history', label: 'History', icon: IconClock },
    { id: 'settings', label: 'Settings', icon: IconGear },
  ];
  return (
    <div style={{ display: 'flex', flexShrink: 0, background: 'var(--surface)', borderTop: '1px solid var(--outline-faint)', padding: '6px 8px 4px' }}>
      {items.map((it) => {
        const on = tab === it.id;
        const Ic = it.icon;
        return (
          <button key={it.id} className="ta-press" onClick={() => nav(it.id)} style={{ flex: 1, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '6px 0' }}>
            <span style={{ height: 30, width: 56, borderRadius: 99, display: 'flex', alignItems: 'center', justifyContent: 'center', background: on ? 'var(--primary-container)' : 'transparent', color: on ? 'var(--on-primary-container)' : 'var(--on-surface-var)' }}>
              <Ic s={21} />
            </span>
            <span style={{ fontSize: 11, fontWeight: 700, color: on ? 'var(--on-surface)' : 'var(--on-surface-var)' }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { HistoryScreen, SettingsScreen, BottomNav, relTime, clockTime });
