// Extra screens: AllTransactions, EditTransactionSheet, CategoriesScreen.

// ═══ ALL TRANSACTIONS ════════════════════════════
function AllTransactionsScreen({ dark, onBack, txs, onUpdateTx, onRemoveTx, openEdit }) {
  const t = T(dark);
  const [editId, setEditId] = React.useState(openEdit || null);
  const [filters, setFilters] = React.useState({
    type: 'all',         // 'all' | 'expense' | 'income'
    accountIds: [],
    categoryIds: [],
    dateFrom: '',
    dateTo: '',
    q: '',
  });
  const [showFilter, setShowFilter] = React.useState(false);

  React.useEffect(() => { if (openEdit) setEditId(openEdit); }, [openEdit]);

  const filtered = (txs || []).filter(tx => {
    if (filters.type !== 'all' && tx.type !== filters.type) return false;
    if (filters.accountIds.length && !filters.accountIds.includes(tx.accountId)) return false;
    if (filters.categoryIds.length && !filters.categoryIds.includes(tx.categoryId)) return false;
    if (filters.dateFrom && tx.date < filters.dateFrom) return false;
    if (filters.dateTo && tx.date > filters.dateTo + 'T23:59:59Z') return false;
    if (filters.q) {
      const q = filters.q.toLowerCase();
      const c = DATA.categories.find(c => c.id === tx.categoryId);
      const t = (tx.note || '') + ' ' + (c ? c.title : '');
      if (!t.toLowerCase().includes(q)) return false;
    }
    return true;
  });

  const groups = {};
  for (const tx of filtered) {
    const k = (tx.date || '').slice(0, 10);
    (groups[k] = groups[k] || []).push(tx);
  }
  const groupKeys = Object.keys(groups).sort((a,b) => b.localeCompare(a));

  const fmtDay = (k) => {
    if (!k) return '';
    const d = new Date(k + 'T00:00:00');
    const today = new Date();
    const yest = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
    const todayK = today.toISOString().slice(0, 10);
    const yestK = yest.toISOString().slice(0, 10);
    if (k === todayK) return 'Сегодня';
    if (k === yestK) return 'Вчера';
    const MS = ['янв','фев','мар','апр','май','июн','июл','авг','сен','окт','нояб','дек'];
    return `${d.getDate()} ${MS[d.getMonth()]}${d.getFullYear() !== today.getFullYear() ? ' ' + d.getFullYear() : ''}`;
  };

  const sums = {
    income: filtered.filter(t => t.type === 'income').reduce((s,t) => s + t.amount, 0),
    expense: filtered.filter(t => t.type === 'expense').reduce((s,t) => s + t.amount, 0),
  };

  const activeFilterCount =
    (filters.type !== 'all' ? 1 : 0) +
    (filters.accountIds.length ? 1 : 0) +
    (filters.categoryIds.length ? 1 : 0) +
    (filters.dateFrom || filters.dateTo ? 1 : 0) +
    (filters.q ? 1 : 0);

  return (
    <Screen dark={dark}>
      <PageHeader dark={dark} title="Операции" subtitle={`${filtered.length} записей · −${fmtR(sums.expense)} +${fmtR(sums.income)} ₽`} large
        leading={<BackBtn dark={dark} onClick={onBack} />}
        trailing={
          <button onClick={() => setShowFilter(true)} style={{
            width: 36, height: 36, borderRadius: 18, border: `1px solid ${t.line}`,
            background: activeFilterCount ? t.accent : t.surface, color: activeFilterCount ? '#fff' : t.ink,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', position: 'relative',
          }}>
            <Icon d={ICONS.filter} size={16} stroke="currentColor" />
            {activeFilterCount > 0 && (
              <div style={{ position: 'absolute', top: -4, right: -4, width: 16, height: 16, borderRadius: 8, background: t.danger, color: '#fff', fontSize: 9, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{activeFilterCount}</div>
            )}
          </button>
        }
      />

      {/* search */}
      <div style={{ padding: '0 20px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: t.surface, borderRadius: 14, border: `1px solid ${t.line}` }}>
          <Icon d={ICONS.search} size={16} stroke={t.muted} />
          <input value={filters.q} onChange={e => setFilters({ ...filters, q: e.target.value })}
            placeholder="Поиск по заметке или категории"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 14, fontWeight: 500, color: t.ink }} />
          {filters.q && (
            <button onClick={() => setFilters({ ...filters, q: '' })} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 2 }}>
              <Icon d={ICONS.x} size={14} stroke={t.muted} />
            </button>
          )}
        </div>
      </div>

      <div style={{ padding: '0 20px' }}>
        {groupKeys.length === 0 && (
          <Card dark={dark} pad={28} radius={20} style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>📒</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.ink }}>Операций пока нет</div>
            <div style={{ fontSize: 12, color: t.muted, marginTop: 6 }}>Добавьте первую через «+» внизу.</div>
          </Card>
        )}

        {groupKeys.map(k => (
          <div key={k} style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '0 4px 8px' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: t.muted, textTransform: 'uppercase', letterSpacing: 0.4 }}>{fmtDay(k)}</div>
              <div style={{ fontSize: 11, color: t.faint, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
                {(() => {
                  const g = groups[k];
                  const inc = g.filter(t => t.type === 'income').reduce((s,t) => s + t.amount, 0);
                  const exp = g.filter(t => t.type === 'expense').reduce((s,t) => s + t.amount, 0);
                  return (inc ? '+' + fmtR(inc) + ' ₽ ' : '') + (exp ? '−' + fmtR(exp) + ' ₽' : '');
                })()}
              </div>
            </div>
            <Card dark={dark} pad={0} radius={20}>
              {groups[k].map((tx, i) => {
                const c = DATA.categories.find(c => c.id === tx.categoryId) || { title: 'Прочее', color: '#9A938A', icon: 'plus' };
                const acct = DATA.accounts.find(a => a.id === tx.accountId);
                return (
                  <ListRow key={tx.id} dark={dark} icon={c.icon} color={c.color}
                    title={tx.note || c.title}
                    sub={`${c.title}${acct ? ' · ' + acct.bank : ''}`}
                    value={(tx.type === 'income' ? '+' : '−') + fmtR(tx.amount) + ' ₽'}
                    valueColor={tx.type === 'income' ? t.positive : t.ink}
                    onClick={() => setEditId(tx.id)}
                    last={i === groups[k].length - 1} />
                );
              })}
            </Card>
          </div>
        ))}
      </div>

      <EditTransactionSheet dark={dark} txId={editId}
        tx={editId ? (txs || []).find(t => t.id === editId) : null}
        onClose={() => setEditId(null)}
        onSave={async (patch) => { await onUpdateTx(editId, patch); setEditId(null); }}
        onDelete={async () => { await onRemoveTx(editId); setEditId(null); }} />

      <FiltersSheet dark={dark} open={showFilter} filters={filters} setFilters={setFilters} onClose={() => setShowFilter(false)} />
    </Screen>
  );
}

function FiltersSheet({ dark, open, filters, setFilters, onClose }) {
  const t = T(dark);
  if (!open) return null;
  const toggle = (key, id) => {
    const arr = filters[key];
    setFilters({ ...filters, [key]: arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id] });
  };
  return (
    <Sheet open={open} onClose={onClose} dark={dark} title="Фильтры" height="86%">
      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Тип</div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
        {[{ v: 'all', l: 'Все' },{ v: 'expense', l: 'Расходы' },{ v: 'income', l: 'Доходы' }].map(o => (
          <Pill key={o.v} dark={dark} active={filters.type === o.v} onClick={() => setFilters({ ...filters, type: o.v })}>{o.l}</Pill>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Счета</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
        {DATA.accounts.map(a => (
          <Pill key={a.id} dark={dark} active={filters.accountIds.includes(a.id)} color={a.color} onClick={() => toggle('accountIds', a.id)}>{a.bank}</Pill>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Категории</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
        {DATA.categories.filter(c => !c.archived).map(c => (
          <Pill key={c.id} dark={dark} active={filters.categoryIds.includes(c.id)} color={c.color} onClick={() => toggle('categoryIds', c.id)}>{c.title}</Pill>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Период</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
        <div style={{ background: t.surface, padding: '10px 12px', borderRadius: 10, border: `1px solid ${t.line}` }}>
          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700 }}>С</div>
          <input type="date" value={filters.dateFrom} onChange={e => setFilters({ ...filters, dateFrom: e.target.value })}
            style={{ border: 'none', outline: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: t.ink, width: '100%' }} />
        </div>
        <div style={{ background: t.surface, padding: '10px 12px', borderRadius: 10, border: `1px solid ${t.line}` }}>
          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700 }}>По</div>
          <input type="date" value={filters.dateTo} onChange={e => setFilters({ ...filters, dateTo: e.target.value })}
            style={{ border: 'none', outline: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: t.ink, width: '100%' }} />
        </div>
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <button onClick={() => setFilters({ type: 'all', accountIds: [], categoryIds: [], dateFrom: '', dateTo: '', q: filters.q })} style={{
          padding: '14px 16px', borderRadius: 14, border: 'none', cursor: 'pointer',
          background: t.surfaceAlt, color: t.ink, fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
        }}>Сбросить</button>
        <Btn dark={dark} primary full icon="check" onClick={onClose} style={{ flex: 1 }}>Применить</Btn>
      </div>
    </Sheet>
  );
}

// ═══ EDIT TRANSACTION ════════════════════════════
function EditTransactionSheet({ dark, txId, tx, onClose, onSave, onDelete }) {
  const t = T(dark);
  const [form, setForm] = React.useState(tx);
  React.useEffect(() => { if (tx) setForm(tx); }, [tx ? tx.id : null]);
  if (!txId || !form) return null;

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const cat = DATA.categories.find(c => c.id === form.categoryId);
  const acct = DATA.accounts.find(a => a.id === form.accountId);

  const dateLocal = (() => {
    try { return form.date ? new Date(form.date).toISOString().slice(0, 10) : ''; } catch { return ''; }
  })();

  return (
    <Sheet open={!!txId} onClose={onClose} dark={dark} title={form.type === 'income' ? 'Доход' : 'Расход'} height="92%">
      <div style={{ marginBottom: 14, padding: 18, borderRadius: 18, background: t.surface, textAlign: 'center' }}>
        <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>Сумма</div>
        <input value={form.amount} type="number" step="0.01" onChange={e => set('amount', parseFloat(e.target.value) || 0)}
          style={{ marginTop: 6, fontFamily: TOK.fontDisplay, fontSize: 36, fontWeight: 800, letterSpacing: -1.2,
            border: 'none', outline: 'none', background: 'transparent', textAlign: 'center', width: '100%',
            color: form.type === 'income' ? t.positive : t.ink, fontVariantNumeric: 'tabular-nums' }} />
        <div style={{ fontSize: 11, color: t.muted, marginTop: 4 }}>{form.currency || 'RUB'}</div>
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Категория</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
        {DATA.categories.filter(c => !c.archived).map(c => (
          <Pill key={c.id} dark={dark} active={form.categoryId === c.id} color={c.color} onClick={() => set('categoryId', c.id)}>{c.title}</Pill>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Счёт</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
        {DATA.accounts.map(a => (
          <button key={a.id} onClick={() => set('accountId', a.id)} style={{
            padding: '10px 12px', borderRadius: 12, border: `1.5px solid ${form.accountId === a.id ? t.accent : t.line}`,
            background: form.accountId === a.id ? t.accentSoft : t.surface, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'inherit',
          }}>
            <div style={{ width: 22, height: 22, borderRadius: 6, background: a.color }} />
            <div style={{ flex: 1, textAlign: 'left' }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: t.ink }}>{a.bank} · {a.title}</div>
            </div>
            {form.accountId === a.id && <Icon d={ICONS.check} size={14} stroke={t.accent} sw={2.4} />}
          </button>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Заметка</div>
      <input value={form.note || ''} onChange={e => set('note', e.target.value)} placeholder="—"
        style={{ width: '100%', marginBottom: 12, padding: '12px 14px', borderRadius: 12, border: `1px solid ${t.line}`, background: t.surface, fontFamily: 'inherit', fontSize: 14, color: t.ink, fontWeight: 600, outline: 'none' }} />

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>Дата</div>
      <input type="date" value={dateLocal} onChange={e => set('date', new Date(e.target.value).toISOString())}
        style={{ width: '100%', marginBottom: 12, padding: '12px 14px', borderRadius: 12, border: `1px solid ${t.line}`, background: t.surface, fontFamily: 'inherit', fontSize: 14, color: t.ink, fontWeight: 600, outline: 'none' }} />

      <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
        <button onClick={() => { if (confirm('Удалить операцию?')) onDelete(); }} style={{
          padding: '14px 16px', borderRadius: 14, border: 'none', cursor: 'pointer',
          background: t.dangerSoft, color: t.danger, fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <Icon d={ICONS.trash} size={16} stroke={t.danger} sw={2} />
          Удалить
        </button>
        <Btn dark={dark} primary full icon="check" onClick={() => onSave(form)} style={{ flex: 1 }}>Сохранить</Btn>
      </div>
    </Sheet>
  );
}

// ═══ CATEGORIES (CRUD) ════════════════════════════
function CategoriesScreen({ dark, onBack }) {
  const t = T(dark);
  const [showArchived, setShowArchived] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [, force] = React.useReducer(x => x + 1, 0);

  const active = DATA.categories.filter(c => !c.archived);
  const archived = DATA.categories.filter(c => c.archived);
  const list = showArchived ? archived : active;

  const onSave = (c) => {
    if (c.__delete) deleteCategory(c.id);
    else if (c.id === '__new') addCategory({ ...c, id: undefined });
    else updateCategory(c.id, c);
    setEditing(null); force();
  };

  return (
    <Screen dark={dark}>
      <PageHeader dark={dark} title="Категории" subtitle={`${active.length} активных · ${archived.length} в архиве`} large
        leading={<BackBtn dark={dark} onClick={onBack} />}
        trailing={
          <button onClick={() => setEditing('__new')} style={{ width: 36, height: 36, borderRadius: 18, border: `1px solid ${t.line}`, background: t.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon d={ICONS.plus} size={18} stroke={t.ink} sw={2.2} />
          </button>
        }
      />

      <div style={{ padding: '0 20px 12px' }}>
        <Segmented dark={dark} value={showArchived ? 'arch' : 'active'} onChange={v => setShowArchived(v === 'arch')} options={[
          { value: 'active', label: `Активные · ${active.length}` },
          { value: 'arch', label: `Архив · ${archived.length}` },
        ]} />
      </div>

      <div style={{ padding: '0 20px' }}>
        {list.length === 0 && (
          <Card dark={dark} pad={28} radius={20} style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>📂</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.ink }}>{showArchived ? 'В архиве пусто' : 'Пока без категорий'}</div>
          </Card>
        )}
        <Card dark={dark} pad={0} radius={20}>
          {list.map((c, i) => {
            const pct = c.planned > 0 ? Math.round((c.spent / c.planned) * 100) : 0;
            const over = pct > 100;
            return (
              <button key={c.id} onClick={() => setEditing(c.id)} style={{
                width: '100%', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
                padding: '14px 16px', borderBottom: i === list.length - 1 ? 'none' : `1px solid ${t.line}`,
                display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'inherit',
              }}>
                <IconCircle icon={c.icon} color={c.color} size={40} dark={dark} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: t.ink }}>{c.emoji ? c.emoji + ' ' : ''}{c.title}</div>
                  {c.planned > 0 && (
                    <>
                      <div style={{ fontSize: 11, color: t.muted, fontWeight: 500, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
                        {fmtR(c.spent)} / {fmtR(c.planned)} ₽ · {pct}%
                      </div>
                      <div style={{ height: 4, background: t.surfaceAlt, borderRadius: 2, marginTop: 4, overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: `${Math.min(100, pct)}%`, background: over ? t.danger : c.color }} />
                      </div>
                    </>
                  )}
                </div>
                <Icon d={ICONS.chevronR} size={14} stroke={t.faint} />
              </button>
            );
          })}
        </Card>

        <button onClick={() => setEditing('__new')} style={{
          marginTop: 14, padding: '16px 18px', borderRadius: 18, border: `2px dashed ${t.lineStrong}`,
          background: 'transparent', color: t.accent, cursor: 'pointer', width: '100%',
          fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon d={ICONS.plus} size={16} stroke={t.accent} sw={2.4} />
          Добавить категорию
        </button>
      </div>

      <EditCategorySheet dark={dark} editingId={editing}
        initial={editing && editing !== '__new' ? DATA.categories.find(c => c.id === editing) : null}
        onClose={() => setEditing(null)} onSave={onSave} />
    </Screen>
  );
}

function EditCategorySheet({ dark, editingId, initial, onClose, onSave }) {
  const t = T(dark);
  const isNew = editingId === '__new';
  const [form, setForm] = React.useState(initial || { id: '__new', title: '', emoji: '✨', color: '#5B8BAA', icon: 'plus', planned: 0, spent: 0, archived: false });
  React.useEffect(() => {
    if (initial) setForm(initial);
    else if (isNew) setForm({ id: '__new', title: '', emoji: '✨', color: '#5B8BAA', icon: 'plus', planned: 0, spent: 0, archived: false });
  }, [editingId]);
  if (!editingId) return null;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const PALETTE = ['#C77B4A','#5B8BAA','#D4A23A','#7A6BB8','#5BA68A','#FF3D9A','#6D8FFF','#B86F8E','#3DDBDB','#A38869','#3DBA85','#C68FB8','#8A7B5A','#FF6DB1','#1F8F87'];
  const ICONOPTS = ['cart','car','coffee','book','heart','film','music','gift','plane','shirt','bank','invest','briefcase','plus','card','target'];

  return (
    <Sheet open={!!editingId} onClose={onClose} dark={dark} title={isNew ? 'Новая категория' : 'Изменить категорию'} height="92%">
      <div style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: t.surface, borderRadius: 16 }}>
        <div style={{ width: 48, height: 48, borderRadius: 14, background: form.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {form.emoji ? <span style={{ fontSize: 22 }}>{form.emoji}</span> : <Icon d={ICONS[form.icon] || ICONS.plus} size={22} stroke="#fff" sw={1.8} />}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: t.ink }}>{form.title || 'Название'}</div>
          <div style={{ fontSize: 11, color: t.muted, marginTop: 2 }}>{form.planned > 0 ? `Бюджет ${fmtR(form.planned)} ₽` : 'без бюджета'}</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '64px 1fr 1fr', gap: 10 }}>
        <div>
          <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>Эмодзи</div>
          <input value={form.emoji || ''} onChange={e => set('emoji', e.target.value.slice(0, 2))} style={{
            width: '100%', textAlign: 'center', padding: '12px 0', borderRadius: 12, border: `1px solid ${t.line}`,
            background: t.surface, fontFamily: 'inherit', fontSize: 22,
          }} />
        </div>
        <div>
          <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>Название</div>
          <input value={form.title} onChange={e => set('title', e.target.value)} placeholder="Парковка"
            style={{ width: '100%', padding: '12px 14px', borderRadius: 12, border: `1px solid ${t.line}`, background: t.surface, fontFamily: 'inherit', fontSize: 14, color: t.ink, fontWeight: 600, outline: 'none' }} />
        </div>
        <div>
          <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>Бюджет</div>
          <input value={form.planned} type="number" onChange={e => set('planned', parseFloat(e.target.value) || 0)}
            style={{ width: '100%', padding: '12px 14px', borderRadius: 12, border: `1px solid ${t.line}`, background: t.surface, fontFamily: 'inherit', fontSize: 14, color: t.ink, fontWeight: 600, outline: 'none', fontVariantNumeric: 'tabular-nums' }} />
        </div>
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, margin: '12px 0 6px' }}>Цвет</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
        {PALETTE.map(p => (
          <button key={p} onClick={() => set('color', p)} style={{
            width: 30, height: 30, borderRadius: 8, border: 'none', background: p, cursor: 'pointer',
            boxShadow: form.color === p ? `0 0 0 3px ${t.bg}, 0 0 0 5px ${p}` : 'none',
          }}>
            {form.color === p && <Icon d={ICONS.check} size={14} stroke="#fff" sw={3} />}
          </button>
        ))}
      </div>

      <div style={{ fontSize: 11, color: t.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, margin: '4px 0 6px' }}>Иконка</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
        {ICONOPTS.map(ic => (
          <button key={ic} onClick={() => set('icon', ic)} style={{
            width: 38, height: 38, borderRadius: 10, border: 'none', cursor: 'pointer',
            background: form.icon === ic ? form.color : t.surface,
            color: form.icon === ic ? '#fff' : form.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon d={ICONS[ic]} size={16} stroke="currentColor" sw={1.8} />
          </button>
        ))}
      </div>

      <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12, background: t.surface, cursor: 'pointer', marginBottom: 12 }}>
        <input type="checkbox" checked={!!form.archived} onChange={e => set('archived', e.target.checked)} />
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: t.ink }}>В архиве</div>
          <div style={{ fontSize: 11, color: t.muted, marginTop: 2 }}>Не показывать в добавлении трат и аналитике (история сохранится).</div>
        </div>
      </label>

      <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
        {!isNew && (
          <button onClick={() => onSave({ ...form, __delete: true })} style={{
            padding: '14px 16px', borderRadius: 14, border: 'none', cursor: 'pointer',
            background: t.dangerSoft, color: t.danger, fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon d={ICONS.trash} size={16} stroke={t.danger} sw={2} />
            Удалить
          </button>
        )}
        <Btn dark={dark} primary full icon="check" onClick={() => onSave(form)} style={{ flex: 1 }}>
          {isNew ? 'Создать' : 'Сохранить'}
        </Btn>
      </div>
    </Sheet>
  );
}

Object.assign(window, { AllTransactionsScreen, EditTransactionSheet, FiltersSheet, CategoriesScreen, EditCategorySheet });
