// inbox.jsx — Open transactions awaiting category assignment + category manager
// Reads from state.bank.transactions where cat == null. Each row lets Maud:
//   - tap a category chip to assign
//   - choose "always do this for [merchant]" to learn a rule
//
// Also exposes <CategoryManager> for the Mij tab — add / rename / delete / re-icon
// custom categories, with friendly fallout when a category is removed
// (rules pointing to it are dropped; tagged transactions return to the inbox).

const TB_INBOX = SAGE;

// ─── Inbox screen (renders inside Geld → Inbox sub-tab) ─────────
function ScreenInbox({ state, set, toast }) {
  const cal = state.bank || {};
  const accounts = cal.accounts || [];
  const allOpen = (cal.transactions || []).filter(t => t.amount < 0 && (t.cat == null || t.cat === ''));

  // Default tab: gezamenlijk als die bestaat, anders persoonlijk, anders eerste account
  const initial = accounts.find(a => a.kind === 'shared')?.uid
    || accounts.find(a => a.kind === 'personal')?.uid
    || accounts[0]?.uid
    || null;
  const [filter, setFilter] = React.useState(initial);
  const [showAdd, setShowAdd] = React.useState(false);
  const [expanded, setExpanded] = React.useState(null);  // tx.id momenteel uitgeklapt

  if (!cal.connected) {
    return (
      <div className="vb-card" style={{ padding: 22, textAlign: 'center', color: TB_INBOX.inkFaint, fontSize: 13 }}>
        Koppel je bank in <b>Mij</b> om uitgaven automatisch te zien verschijnen.
      </div>
    );
  }

  // Per-account counts voor de filter-chips
  const countByUid = {};
  allOpen.forEach(t => { if (t.accountUid) countByUid[t.accountUid] = (countByUid[t.accountUid] || 0) + 1; });

  const open = filter ? allOpen.filter(t => t.accountUid === filter) : allOpen;
  const groups = groupByDateBlock(open);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Filter chips per rekening — geen 'alles', alleen de daadwerkelijke accounts */}
      {accounts.length > 0 && (
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
          {accounts.map(a => (
            <FilterChip key={a.uid} active={filter === a.uid} onClick={() => setFilter(a.uid)}
              label={shortKindLabel(a)} count={countByUid[a.uid] || 0} kind={a.kind} />
          ))}
        </div>
      )}

      {/* Lijst — compact zoals "Recent" */}
      {open.length === 0 ? (
        <div className="vb-card" style={{ padding: 22, textAlign: 'center' }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}>✨</div>
          <div style={{ fontSize: 15, fontWeight: 500, color: TB_INBOX.ink }}>Niets open hier</div>
          <div style={{ fontSize: 13, color: TB_INBOX.inkFaint, marginTop: 4 }}>Op deze rekening staat alles op categorie.</div>
        </div>
      ) : (
        groups.map(g => (
          <React.Fragment key={g.label}>
            <div style={{
              fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase',
              color: TB_INBOX.inkFaint, padding: '4px 4px 0',
            }}>{g.label}</div>
            <div className="vb-card" style={{ padding: 0 }}>
              {g.items.map((tx, i) => (
                <InboxRow key={tx.id} tx={tx} state={state} set={set} toast={toast}
                  isFirst={i === 0}
                  isExpanded={expanded === tx.id}
                  onToggle={() => setExpanded(expanded === tx.id ? null : tx.id)}
                  onAddPotje={() => setShowAdd(true)} />
              ))}
            </div>
          </React.Fragment>
        ))
      )}

      {/* Floating + nieuw potje knop, altijd beschikbaar */}
      <button onClick={() => setShowAdd(true)} style={{
        position: 'sticky', bottom: 12, alignSelf: 'flex-end',
        padding: '10px 16px', borderRadius: 99, border: 'none',
        background: TB_INBOX.accent, color: '#fff', fontSize: 13, fontWeight: 600,
        cursor: 'pointer', fontFamily: 'inherit', marginTop: 8,
        boxShadow: '0 6px 20px rgba(28,42,36,0.18)',
      }}>+ nieuw potje</button>

      {showAdd && <AddCategorySheet state={state} set={set} onClose={() => setShowAdd(false)} toast={toast} />}
    </div>
  );
}

// ─── helpers voor inbox ────────────────────────────────────────
function FilterChip({ active, onClick, label, count, kind }) {
  const meta = (typeof KIND_META !== 'undefined' && kind) ? KIND_META[kind] : null;
  return (
    <button onClick={onClick} style={{
      padding: '6px 12px', borderRadius: 99, border: `1px solid ${active ? TB_INBOX.accent : TB_INBOX.hairline}`,
      background: active ? TB_INBOX.accent : TB_INBOX.card,
      color: active ? '#fff' : TB_INBOX.ink,
      fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
      display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0,
    }}>
      {meta && <span style={{ fontSize: 13 }}>{meta.icon}</span>}
      <span>{label}</span>
      <span style={{
        padding: '0 6px', borderRadius: 99, fontSize: 10, fontWeight: 700,
        background: active ? 'rgba(255,255,255,0.22)' : TB_INBOX.bg,
        color: active ? '#fff' : TB_INBOX.inkSoft,
      }}>{count}</span>
    </button>
  );
}

function shortKindLabel(a) {
  if (a.kind === 'shared') return 'gezamenlijk';
  if (a.kind === 'personal') return 'persoonlijk';
  if (a.kind === 'savings') return 'spaar';
  return a.label || 'overig';
}

function groupByDateBlock(txs) {
  const groups = { today: [], yesterday: [], thisWeek: [], lastWeek: [], earlier: [] };
  for (const t of txs) {
    const d = t.daysAgo;
    if (d === 0) groups.today.push(t);
    else if (d === 1) groups.yesterday.push(t);
    else if (d <= 7) groups.thisWeek.push(t);
    else if (d <= 14) groups.lastWeek.push(t);
    else groups.earlier.push(t);
  }
  const out = [];
  if (groups.today.length)     out.push({ label: 'vandaag',         items: groups.today });
  if (groups.yesterday.length) out.push({ label: 'gisteren',        items: groups.yesterday });
  if (groups.thisWeek.length)  out.push({ label: 'deze week',       items: groups.thisWeek });
  if (groups.lastWeek.length)  out.push({ label: 'vorige week',     items: groups.lastWeek });
  if (groups.earlier.length)   out.push({ label: 'eerder',          items: groups.earlier });
  return out;
}

function InboxRow({ tx, state, set, toast, isFirst, isExpanded, onToggle, onAddPotje }) {
  const [confirm, setConfirm] = React.useState(null); // { cat, merchant }
  const merchant = normalizeMerchant(tx.description) || tx.description.slice(0, 24);
  const dayLabel = tx.daysAgo === 0 ? 'vandaag' : tx.daysAgo === 1 ? 'gisteren' : `${tx.daysAgo}d geleden`;

  // Find similar pending txs (same merchant, also uncategorized)
  const similarCount = (state.bank.transactions || [])
    .filter(t => t.id !== tx.id && !t.cat && t.amount < 0)
    .filter(t => merchant && t.description.toLowerCase().includes(merchant.toLowerCase()))
    .length;

  const assignOnce = (cat) => setConfirm({ cat, merchant });

  const confirmRule = (learn) => {
    const { cat, merchant: m } = confirm;
    set(s => {
      let rules = s.categoryRules || [];
      let txs = s.bank.transactions.map(t => t.id === tx.id ? { ...t, cat } : t);
      if (learn) {
        const exists = rules.find(r => r.match.toLowerCase() === m.toLowerCase());
        if (exists) {
          rules = rules.map(r => r.match.toLowerCase() === m.toLowerCase() ? { ...r, cat } : r);
        } else {
          rules = [...rules, { id: 'rule-' + Date.now(), match: m, cat, merchant: m }];
        }
        txs = txs.map(t => {
          if (t.id === tx.id) return t;
          if (t.cat) return t;
          return (t.description || '').toLowerCase().includes(m.toLowerCase()) ? { ...t, cat } : t;
        });
      }
      return { ...s, categoryRules: rules, bank: { ...s.bank, transactions: txs } };
    });
    const catMeta = state.budgets.find(b => b.cat === confirm.cat);
    toast(learn
      ? `${catMeta?.icon || '·'} ${merchant} → ${catMeta?.label || confirm.cat}${similarCount > 0 ? ` (+${similarCount})` : ''}`
      : `${catMeta?.icon || '·'} ${merchant} → ${catMeta?.label || confirm.cat}`);
    setConfirm(null);
  };

  return (
    <div style={{
      borderTop: isFirst ? 'none' : `1px solid ${TB_INBOX.hairline}`,
    }}>
      {/* Hoofdrij — compact, klikbaar */}
      <div onClick={onToggle} style={{
        display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
        cursor: 'pointer',
      }}>
        <span style={{ fontSize: 18, opacity: 0.55 }}>💸</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, color: TB_INBOX.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {tx.description}
          </div>
          <div style={{ fontSize: 11, color: TB_INBOX.inkFaint }}>{dayLabel}</div>
        </div>
        <div className="vb-num" style={{ fontSize: 14, fontWeight: 500, color: TB_INBOX.ink }}>
          {fmtEur(Math.abs(tx.amount))}
        </div>
        <svg width="6" height="10" viewBox="0 0 8 14" style={{
          marginLeft: 4, opacity: 0.4,
          transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)',
          transition: 'transform .15s',
        }}>
          <path d="M1 1l6 6-6 6" stroke={TB_INBOX.inkFaint} strokeWidth="2" fill="none" strokeLinecap="round"/>
        </svg>
      </div>

      {/* Uitklapbaar paneel met chips of rule-prompt */}
      {isExpanded && (
        <div style={{
          padding: '4px 16px 14px', background: TB_INBOX.bg,
        }}>
          {!confirm && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {state.budgets.map(b => (
                <button key={b.cat} onClick={() => assignOnce(b.cat)} style={{
                  padding: '8px 12px', borderRadius: 99, border: `1px solid ${TB_INBOX.hairline}`,
                  background: TB_INBOX.card, cursor: 'pointer', fontSize: 12, color: TB_INBOX.ink,
                  fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6,
                }}><span style={{ fontSize: 14 }}>{b.icon}</span>{b.label}</button>
              ))}
              {onAddPotje && (
                <button onClick={onAddPotje} style={{
                  padding: '8px 12px', borderRadius: 99, border: `1px dashed ${TB_INBOX.hairline}`,
                  background: 'transparent', cursor: 'pointer', fontSize: 12, color: TB_INBOX.inkSoft,
                  fontFamily: 'inherit',
                }}>+ potje</button>
              )}
            </div>
          )}

          {confirm && (() => {
            const cat = state.budgets.find(b => b.cat === confirm.cat);
            return (
              <div style={{
                padding: '12px 14px', borderRadius: 12, background: TB_INBOX.accentSoft,
                display: 'flex', flexDirection: 'column', gap: 10,
              }}>
                <div style={{ fontSize: 13, color: TB_INBOX.ink, lineHeight: 1.5 }}>
                  Altijd <b>{cat?.icon} {cat?.label}</b> voor <b>{confirm.merchant}</b>?
                  {similarCount > 0 && (
                    <div style={{ fontSize: 11, color: TB_INBOX.inkSoft, marginTop: 2 }}>
                      Werkt ook op {similarCount} vergelijkbare uitgave{similarCount === 1 ? '' : 'n'}.
                    </div>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button onClick={() => confirmRule(true)} style={{
                    flex: 1, padding: '10px', borderRadius: 10, border: 'none',
                    background: TB_INBOX.accent, color: '#fff', fontSize: 13, fontWeight: 600,
                    cursor: 'pointer', fontFamily: 'inherit',
                  }}>Ja, leer dit</button>
                  <button onClick={() => confirmRule(false)} style={{
                    flex: 1, padding: '10px', borderRadius: 10, border: `1px solid ${TB_INBOX.hairline}`,
                    background: TB_INBOX.card, color: TB_INBOX.ink, fontSize: 13, fontWeight: 600,
                    cursor: 'pointer', fontFamily: 'inherit',
                  }}>Alleen deze</button>
                  <button onClick={() => setConfirm(null)} style={{
                    padding: '10px 12px', borderRadius: 10, border: 'none',
                    background: 'transparent', color: TB_INBOX.inkFaint, fontSize: 13,
                    cursor: 'pointer', fontFamily: 'inherit',
                  }}>×</button>
                </div>
              </div>
            );
          })()}
        </div>
      )}
    </div>
  );
}

// ─── Category manager (replaces "Categorieën" in Mij tab) ──────
const SUGGEST_ICONS = ['🥑','🎈','🚲','🪴','🛒','☕','🍕','🚗','💊','📱','🎬','💄','🎁','✈️','🏋️','📚','💻','👕','🐈','🌿','✨','💼','🪙','🩹'];

function CategoryManager({ state, set, toast }) {
  const [adding, setAdding] = React.useState(false);
  const [editing, setEditing] = React.useState(null); // category id being edited

  const rulesForCat = (catId) => (state.categoryRules || []).filter(r => r.cat === catId);
  const txsForCat = (catId) => (state.bank?.transactions || []).filter(t => t.cat === catId);

  const deleteCat = (cat) => {
    const linkedTx = txsForCat(cat.cat).length;
    const linkedRules = rulesForCat(cat.cat).length;
    const msg = `Verwijder "${cat.label}"?` +
      (linkedTx ? `\n\n${linkedTx} bank-uitgave${linkedTx===1?'':'n'} gaan terug naar de inbox.` : '') +
      (linkedRules ? `\n${linkedRules} regel${linkedRules===1?'':'s'} verdwijnen mee.` : '');
    if (!confirm(msg)) return;
    set(s => ({
      ...s,
      budgets: s.budgets.filter(b => b.cat !== cat.cat),
      categoryRules: (s.categoryRules || []).filter(r => r.cat !== cat.cat),
      bank: {
        ...s.bank,
        transactions: (s.bank?.transactions || []).map(t => t.cat === cat.cat ? { ...t, cat: null, ruleId: null } : t),
      },
      // also clean any historical 'expenses' that reference the cat
      expenses: (s.expenses || []).map(e => e.cat === cat.cat ? { ...e, cat: 'other' } : e),
    }));
    toast(`${cat.label} weg`);
  };

  return (
    <React.Fragment>
      <SectionHeader
        eyebrow="instellingen"
        title="Categorieën"
        right={
          <button onClick={() => setAdding(true)} style={{
            padding: '4px 10px', borderRadius: 99, border: `1px solid ${TB_INBOX.hairline}`,
            background: 'transparent', cursor: 'pointer', fontSize: 12, color: TB_INBOX.ink,
            fontWeight: 600, fontFamily: 'inherit',
          }}>+ nieuw</button>
        }
      />
      <div className="vb-card" style={{ padding: 0, marginBottom: 18 }}>
        {state.budgets.map((b, i) => (
          <CategoryRow
            key={b.cat} cat={b} state={state} set={set} toast={toast}
            isLast={i === state.budgets.length - 1}
            isEditing={editing === b.cat}
            onEdit={() => setEditing(b.cat)}
            onClose={() => setEditing(null)}
            onDelete={() => deleteCat(b)}
            txCount={txsForCat(b.cat).length}
            ruleCount={rulesForCat(b.cat).length}
          />
        ))}
      </div>
      {adding && <AddCategorySheet state={state} set={set} onClose={() => setAdding(false)} toast={toast} />}
    </React.Fragment>
  );
}

function CategoryRow({ cat, state, set, toast, isLast, isEditing, onEdit, onClose, onDelete, txCount, ruleCount }) {
  const [draft, setDraft] = React.useState({ ...cat });
  React.useEffect(() => { setDraft({ ...cat }); }, [cat]);

  const save = () => {
    set(s => ({
      ...s,
      budgets: s.budgets.map(b => b.cat === cat.cat ? { ...b, label: draft.label.trim() || cat.label, icon: draft.icon || cat.icon, limit: Number(draft.limit) || 0 } : b),
    }));
    toast(`${draft.label} opgeslagen`);
    onClose();
  };

  if (!isEditing) {
    return (
      <div onClick={onEdit} style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px',
        borderTop: isLast ? 'none' : '',
        borderBottom: isLast ? 'none' : `1px solid ${TB_INBOX.hairline}`,
        cursor: 'pointer',
      }}>
        <span style={{ fontSize: 22 }}>{cat.icon}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, color: TB_INBOX.ink }}>{cat.label}</div>
          <div style={{ fontSize: 11, color: TB_INBOX.inkFaint }}>
            {txCount} uitgaven{ruleCount > 0 ? ` · ${ruleCount} regel${ruleCount === 1 ? '' : 's'}` : ''}
          </div>
        </div>
        <div className="vb-num" style={{ fontSize: 13, color: TB_INBOX.inkSoft, fontWeight: 500 }}>
          {fmtEurShort(cat.limit)}
        </div>
        <svg width="6" height="10" viewBox="0 0 8 14" style={{ marginLeft: 4 }}>
          <path d="M1 1l6 6-6 6" stroke={TB_INBOX.inkFaint} strokeWidth="2" fill="none" strokeLinecap="round"/>
        </svg>
      </div>
    );
  }

  return (
    <div style={{ padding: '12px 14px', background: TB_INBOX.bg, borderBottom: isLast ? 'none' : `1px solid ${TB_INBOX.hairline}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <input value={draft.icon} onChange={e => setDraft({...draft, icon: e.target.value.slice(0, 4)})}
          style={{ width: 50, padding: '10px', fontSize: 22, textAlign: 'center', border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 10, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit' }} />
        <input value={draft.label} onChange={e => setDraft({...draft, label: e.target.value})}
          style={{ flex: 1, padding: '10px 12px', fontSize: 14, border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 10, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit', color: TB_INBOX.ink }} />
      </div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 }}>
        {SUGGEST_ICONS.map(i => (
          <button key={i} onClick={() => setDraft({...draft, icon: i})} style={{
            width: 30, height: 30, borderRadius: 8, border: 'none', cursor: 'pointer',
            background: draft.icon === i ? TB_INBOX.accentSoft : 'transparent',
            fontSize: 16, padding: 0, fontFamily: 'inherit',
          }}>{i}</button>
        ))}
      </div>
      <label style={{ fontSize: 11, color: TB_INBOX.inkSoft, display: 'block', marginBottom: 4 }}>Maandlimiet €</label>
      <input type="number" value={draft.limit} onChange={e => setDraft({...draft, limit: e.target.value})}
        style={{ width: '100%', padding: '10px 12px', fontSize: 14, border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 10, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit', color: TB_INBOX.ink, boxSizing: 'border-box' }} />
      <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
        <button onClick={save} style={{
          flex: 1, padding: '10px', borderRadius: 10, border: 'none',
          background: TB_INBOX.accent, color: '#fff', fontSize: 13, fontWeight: 600,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Opslaan</button>
        <button onClick={onDelete} style={{
          padding: '10px 14px', borderRadius: 10, border: 'none',
          background: 'transparent', color: '#C44A3A', fontSize: 13, fontWeight: 600,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Verwijder</button>
        <button onClick={onClose} style={{
          padding: '10px 12px', borderRadius: 10, border: 'none',
          background: 'transparent', color: TB_INBOX.inkFaint, fontSize: 13,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>×</button>
      </div>

      {/* Linked rules */}
      {(state.categoryRules || []).filter(r => r.cat === cat.cat).length > 0 && (
        <div style={{ marginTop: 12, paddingTop: 10, borderTop: `1px solid ${TB_INBOX.hairline}` }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.1, color: TB_INBOX.inkFaint, fontWeight: 600, marginBottom: 6 }}>
            Regels
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {(state.categoryRules || []).filter(r => r.cat === cat.cat).map(r => (
              <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: TB_INBOX.ink }}>
                <span style={{ flex: 1 }}>{r.match}</span>
                <button onClick={() => {
                  set(s => ({ ...s, categoryRules: (s.categoryRules || []).filter(x => x.id !== r.id) }));
                  toast('Regel weg');
                }} style={{
                  background: 'transparent', border: 'none', color: TB_INBOX.inkFaint,
                  cursor: 'pointer', fontSize: 14, padding: 0, fontFamily: 'inherit',
                }}>×</button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function AddCategorySheet({ state, set, onClose, toast }) {
  const [label, setLabel] = React.useState('');
  const [icon, setIcon] = React.useState('🌿');
  const [limit, setLimit] = React.useState('');

  const submit = () => {
    if (!label.trim()) return;
    const slug = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
    const id = state.budgets.find(b => b.cat === slug) ? slug + '-' + Date.now() : slug;
    set(s => ({
      ...s,
      budgets: [...s.budgets, { cat: id, label: label.trim(), icon, limit: Number(limit) || 0, color: 'sage' }],
    }));
    toast(`${label} toegevoegd`);
    onClose();
  };

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(28,42,36,0.32)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="vb-sheet" style={{
        width: '100%', background: TB_INBOX.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '14px 18px 32px', maxHeight: '80%', overflow: 'auto',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: TB_INBOX.hairline, margin: '0 auto 16px' }} />
        <div className="vb-display" style={{ fontSize: 20, marginBottom: 14 }}>Nieuwe categorie</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input value={icon} onChange={e => setIcon(e.target.value.slice(0,4))}
              style={{ width: 60, padding: '14px', fontSize: 26, textAlign: 'center', border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 12, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit' }} />
            <input value={label} onChange={e => setLabel(e.target.value)} placeholder="bv. Cadeaus" autoFocus
              style={{ flex: 1, padding: '14px 16px', fontSize: 16, border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 12, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit', color: TB_INBOX.ink, boxSizing: 'border-box' }} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: TB_INBOX.inkSoft, marginBottom: 6 }}>Kies een icoon</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {SUGGEST_ICONS.map(i => (
                <button key={i} onClick={() => setIcon(i)} style={{
                  width: 38, height: 38, borderRadius: 10, border: 'none', cursor: 'pointer',
                  background: icon === i ? TB_INBOX.accent : TB_INBOX.card,
                  fontSize: 20, padding: 0, fontFamily: 'inherit',
                  boxShadow: icon === i ? '0 4px 12px rgba(94,124,107,0.3)' : 'none',
                }}>{i}</button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: TB_INBOX.inkSoft, marginBottom: 4 }}>Maandlimiet (optioneel)</div>
            <input type="number" value={limit} onChange={e => setLimit(e.target.value)} placeholder="€"
              style={{ width: '100%', padding: '14px 16px', fontSize: 16, border: `1px solid ${TB_INBOX.hairline}`, borderRadius: 12, background: TB_INBOX.card, outline: 'none', fontFamily: 'inherit', color: TB_INBOX.ink, boxSizing: 'border-box' }} />
          </div>
        </div>
        <button onClick={submit} disabled={!label.trim()} style={{
          width: '100%', marginTop: 16, padding: '14px', borderRadius: 14, border: 'none',
          background: label.trim() ? TB_INBOX.accent : TB_INBOX.hairline, color: '#fff', fontSize: 15, fontWeight: 600,
          cursor: label.trim() ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
        }}>Toevoegen</button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenInbox, CategoryManager });
