// 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 }) {
  const [open, setOpen] = React.useState(null);

  const toggleReceived = (hid, pi) => setHistory(history.map((h) => h.id !== hid ? h : {
    ...h, people: h.people.map((p, i) => i !== pi || !p.request ? p : { ...p, request: { ...p.request, received: !p.request.received } }) }));
  const remove = (hid) => setHistory(history.filter((h) => h.id !== hid));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="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 splits yet</div>
          <div style={{ fontSize: 13.5, textAlign: 'center' }}>Finished bills land here with who paid and how.</div>
          <Button full={false} onClick={() => nav('home')} leading={<IconPlus s={19} />}>New split</Button>
        </div>
      ) : (
        <div className="ta-scroll" style={{ flex: 1, 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);
                      return (
                        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 0', borderBottom: i < h.people.length - 1 ? '1px solid var(--outline-faint)' : 'none' }}>
                          <Avatar person={{ name: p.name, color: p.color || 'var(--primary)' }} size={34} />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}{p.you && <span style={{ fontSize: 11, color: 'var(--on-surface-var)', marginLeft: 5 }}>· you</span>}</div>
                            <div style={{ fontSize: 11.5, color: 'var(--on-surface-var)' }}>
                              {p.you ? 'your share' : p.request ? `${app ? app.name : 'Requested'} · ${clockTime(p.request.at)}` : 'not requested'}
                            </div>
                          </div>
                          <span className="ta-num" style={{ fontWeight: 700, fontSize: 14 }}>{fmt(p.total, cur)}</span>
                          {!p.you && p.request && (
                            <button className="ta-press" onClick={() => toggleReceived(h.id, i)} style={{ border: 'none', cursor: 'pointer', borderRadius: 99, padding: '5px 11px', fontWeight: 800, fontSize: 11, letterSpacing: 0.3, display: 'flex', alignItems: 'center', gap: 4,
                              background: p.request.received ? 'var(--good)' : 'var(--surface-variant)', color: p.request.received ? '#06210f' : 'var(--on-surface-var)' }}>
                              {p.request.received ? <><IconCheck s={12} />PAID</> : 'MARK PAID'}
                            </button>
                          )}
                          {!p.you && !p.request && <span style={{ fontSize: 11, color: 'var(--on-surface-var)' }}>—</span>}
                        </div>
                      );
                    })}
                    <button className="ta-press" onClick={() => remove(h.id)} style={{ marginTop: 10, 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>
      )}
    </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' },
  ];
  const fonts = [
    { k: 'default', label: 'Theme default' }, { k: 'clean', label: 'Clean' }, { k: 'rounded', label: 'Rounded' },
    { k: 'grotesk', label: 'Grotesk' }, { k: 'editorial', label: 'Editorial' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader title="Settings" />
      <div className="ta-scroll" style={{ flex: 1, 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">
            <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',
                  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>
          <div style={{ height: 1, background: 'var(--outline-faint)' }} />
          <Row label="Typeface">
            <select value={settings.font} onChange={(e) => set({ font: e.target.value })} style={sel}>
              {fonts.map((f) => <option key={f.k} value={f.k}>{f.label}</option>)}
            </select>
          </Row>
          <div style={{ height: 1, background: 'var(--outline-faint)' }} />
          <Row label="Text size" sub={`${Math.round(settings.fontScale * 100)}%`}>
            <div style={{ width: 130 }}><Slider value={settings.fontScale} min={0.9} max={1.18} step={0.02} onChange={(v) => set({ fontScale: v })} /></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>

        <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--on-surface-var)', marginTop: 18 }}>DivvyTab · prototype</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 });
