// ─────────────────────────────────────────────────────────────
// forecasts-screen.jsx — Planned expenses AND income (Previsões)
// Pending forecasts do NOT affect the balance. Marking one as
// "happened" creates the real transaction and (for recurring)
// rolls the next cycle forward automatically.
// ─────────────────────────────────────────────────────────────

const { LedgerIcon, LedgerButton, LedgerPageHeader, LedgerKpi, LedgerAlert, LedgerSegmented, LedgerChip } = window;

function LedgerForecastsScreen({ state, setState, onNavigate }) {
  const S = window.LedgerStore;
  const { isMobile, isNarrow } = window.useViewport();
  const stack = isNarrow; // switch tables → cards while the content column is tight
  const [showForm, setShowForm]   = React.useState(false);
  const [editing, setEditing]     = React.useState(null);
  const [statusFilter, setStatusFilter] = React.useState('pending');  // pending | realized | all
  const [kindFilter,   setKindFilter]   = React.useState('all');      // all | expense | income
  const [monthFilter,  setMonthFilter]  = React.useState('all');      // 'all' | 'YYYY-MM'
  const [query, setQuery] = React.useState('');
  const [searchFocus, setSearchFocus] = React.useState(false);
  const PAGE = 20;
  const [visibleCount, setVisibleCount] = React.useState(PAGE);
  const loadMoreRef = React.useRef(null);

  const list = (state.forecasts || []).slice().sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate));

  // Lista de meses com previsões, considerando filtros ativos (status e tipo)
  // Só mostra meses que têm pelo menos uma previsão visível com os filtros atuais
  const availableMonths = React.useMemo(() => {
    const set = new Set();
    list.forEach(f => {
      if (!f.dueDate) return;
      if (statusFilter !== 'all' && f.status !== statusFilter) return;
      if (kindFilter !== 'all' && (f.kind || 'expense') !== kindFilter) return;
      set.add(S.ymKey(f.dueDate));
    });
    return Array.from(set).sort();
  }, [list, statusFilter, kindFilter]);
  const [bulkMode, setBulkMode] = React.useState(false);
  const [bulkRows, setBulkRows] = React.useState([newBulkForecastRow(), newBulkForecastRow(), newBulkForecastRow()]);

  function addBulkRow() { setBulkRows(rs => [...rs, newBulkForecastRow()]); }
  function removeBulkRow(rid) { setBulkRows(rs => rs.filter(r => r.rid !== rid)); }
  function duplicateBulkRow(rid) { setBulkRows(rs => { const idx = rs.findIndex(r => r.rid === rid); const copy = { ...rs[idx], rid: 'bf' + Date.now() + Math.random() }; return [...rs.slice(0, idx + 1), copy, ...rs.slice(idx + 1)]; }); }
  function updateBulkRow(rid, patch) { setBulkRows(rs => rs.map(r => r.rid === rid ? { ...r, ...patch } : r)); }

  function saveBulkForecasts() {
    const valid = bulkRows.filter(r => r.name.trim() && parseFloat((r.amount || '').replace(',', '.')) > 0);
    if (valid.length === 0) { setBulkMode(false); return; }
    const newForecasts = valid.map(r => ({
      id: 'f' + Date.now() + Math.random(),
      status: 'pending',
      realizedTxId: null,
      kind: r.kind,
      name: r.name.trim(),
      amount: Math.abs(parseFloat((r.amount || '').replace(',', '.'))),
      dueDate: new Date((r.dueDate || new Date().toISOString().slice(0, 10)) + 'T12:00:00').toISOString(),
      categoryId: r.kind === 'expense' ? r.categoryId : null,
      subcategoryId: r.kind === 'expense' ? r.subcategoryId : null,
      source: r.kind === 'income' ? r.source : null,
      recurrence: r.recurrence,
      fixed: r.fixed,
      note: '',
      goalId: null,
    }));
    setState({ ...state, forecasts: [...state.forecasts, ...newForecasts] });
    setBulkMode(false);
    setBulkRows([newBulkForecastRow(), newBulkForecastRow(), newBulkForecastRow()]);
  }
  const filtered = list.filter(f => {
    if (statusFilter !== 'all' && f.status !== statusFilter) return false;
    if (kindFilter !== 'all' && (f.kind || 'expense') !== kindFilter) return false;
    if (monthFilter !== 'all' && S.ymKey(f.dueDate) !== monthFilter) return false;
    if (query.trim()) {
      const q = query.toLowerCase();
      const cat = S.catLookup(f.categoryId);
      const sub = S.subLookup(f.categoryId, f.subcategoryId, state);
      const haystack = [f.name, f.note, f.source, cat && cat.name, sub && sub.name].filter(Boolean).join(' ').toLowerCase();
      if (!haystack.includes(q)) return false;
    }
    return true;
  });

  // Reinicia a paginação quando qualquer filtro muda
  React.useEffect(() => { setVisibleCount(PAGE); }, [statusFilter, kindFilter, monthFilter, query]);

  // Se o mês selecionado saiu da lista de disponíveis (sem previsões com filtros ativos), volta pra 'all'
  React.useEffect(() => {
    if (monthFilter !== 'all' && !availableMonths.includes(monthFilter)) {
      setMonthFilter('all');
    }
  }, [availableMonths, monthFilter]);

  const visibleFiltered = filtered.slice(0, visibleCount);
  const hasMore = filtered.length > visibleCount;

  // Scroll infinito
  React.useEffect(() => {
    if (!hasMore || !loadMoreRef.current) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) setVisibleCount(c => c + PAGE);
    }, { rootMargin: '200px' });
    obs.observe(loadMoreRef.current);
    return () => obs.disconnect();
  }, [hasMore, visibleCount, filtered.length]);

  // KPIs — respeitam o filtro de mês escolhido. Em "Todos os meses",
  // mostram o total de TODAS as previsões pendentes (não só do mês corrente).
  // Aportes (transfer) são contados separadamente — NÃO entram em "saídas".
  const now = new Date();
  const ymk = monthFilter !== 'all' ? monthFilter : S.ymKey(now);
  const pendingExpenses = list.filter(f => f.status === 'pending' && (f.kind || 'expense') === 'expense');
  const pendingIncome   = list.filter(f => f.status === 'pending' && f.kind === 'income');
  const pendingTransfers = list.filter(f => f.status === 'pending' && f.kind === 'transfer');
  const scopedExpenses = monthFilter === 'all' ? pendingExpenses : pendingExpenses.filter(f => S.ymKey(f.dueDate) === monthFilter);
  const scopedIncome   = monthFilter === 'all' ? pendingIncome   : pendingIncome.filter(f => S.ymKey(f.dueDate) === monthFilter);
  const scopedTransfers = monthFilter === 'all' ? pendingTransfers : pendingTransfers.filter(f => S.ymKey(f.dueDate) === monthFilter);
  const thisMonthOut = scopedExpenses.reduce((s, f) => s + Math.abs(f.amount), 0);
  const thisMonthIn  = scopedIncome.reduce((s, f) => s + Math.abs(f.amount), 0);
  const thisMonthTransfers = scopedTransfers.reduce((s, f) => s + Math.abs(f.amount), 0);
  const next30Out = pendingExpenses
    .filter(f => { const d = new Date(f.dueDate); const lim = new Date(); lim.setDate(now.getDate() + 30); return d >= now && d <= lim; })
    .reduce((s, f) => s + Math.abs(f.amount), 0);
  const next30In = pendingIncome
    .filter(f => { const d = new Date(f.dueDate); const lim = new Date(); lim.setDate(now.getDate() + 30); return d >= now && d <= lim; })
    .reduce((s, f) => s + Math.abs(f.amount), 0);

  function realizeForecast(f) {
    const kind = f.kind || 'expense';
    const isTransfer = kind === 'transfer';
    const goalRef = (((kind === 'expense' && f.categoryId === 'investments' && f.subcategoryId === 'inv-goals') || isTransfer) && f.goalId)
      ? (state.goals || []).find(g => String(g.id) === String(f.goalId))
      : null;
    // Create the actual transaction. Transfers are stored as an investment expense
    // (categoria Investimentos → Metas) so they leave the balance and feed the goal.
    const tx = {
      id: Date.now(),
      date: new Date().toISOString(),
      amount: kind === 'income' ? Math.abs(f.amount) : -Math.abs(f.amount),
      type: isTransfer ? 'expense' : kind,
      categoryId:    kind === 'income' ? null : (isTransfer ? 'investments' : f.categoryId),
      subcategoryId: kind === 'income' ? null : (isTransfer ? 'inv-goals'   : f.subcategoryId),
      source:        kind === 'income' ? f.source : null,
      paymentMethod: kind === 'income' ? null : (isTransfer ? 'pix' : (f.paymentMethod || 'debit')),
      note: f.name + (f.note ? ' — ' + f.note : '') + (goalRef ? ` · Meta: ${goalRef.name}` : ''),
      fixed: !!f.fixed,
      fromForecastId: f.id,
      goalId: goalRef ? goalRef.id : null,
      holdingId: f.holdingId || null,
      transfer: isTransfer || undefined,
    };

    let nextForecasts = state.forecasts.map(x =>
      x.id === f.id ? { ...x, status: 'realized', realizedTxId: tx.id, realizedAt: tx.date } : x
    );
    if (f.recurrence && f.recurrence !== 'once') {
      nextForecasts.push({
        ...f,
        id: 'f' + Date.now(),
        dueDate: S.nextRecurrence(f.dueDate, f.recurrence),
        status: 'pending',
        realizedTxId: null,
        realizedAt: null,
      });
    }

    const nextGoals = goalRef
      ? S.applyGoalAporte(state.goals, goalRef.id, Math.abs(f.amount), f.holdingId ? { id: f.holdingId } : null)
      : state.goals;

    setState({ ...state, transactions: [tx, ...state.transactions], forecasts: nextForecasts, goals: nextGoals });
  }

  function removeForecast(id) {
    setState({ ...state, forecasts: state.forecasts.filter(f => f.id !== id) });
  }

  function upsertForecast(payloadOrList) {
    const exists = editing && state.forecasts.find(f => f.id === editing);
    if (exists) {
      // Edição: sempre um único item, nunca duplica em massa
      const payload = Array.isArray(payloadOrList) ? payloadOrList[0] : payloadOrList;
      const next = state.forecasts.map(f => f.id === editing ? { ...f, ...payload } : f);
      setState({ ...state, forecasts: next });
    } else {
      // Criação: pode vir uma lista (despesa fixa por N meses) ou um único item
      const list = Array.isArray(payloadOrList) ? payloadOrList : [payloadOrList];
      const newOnes = list.map((payload, i) => ({ id: 'f' + Date.now() + '-' + i, status: 'pending', realizedTxId: null, ...payload }));
      setState({ ...state, forecasts: [...state.forecasts, ...newOnes] });
    }
    setShowForm(false);
    setEditing(null);
  }

  const netForecast = thisMonthIn - thisMonthOut;

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1280, margin: '0 auto' }} data-screen-label="Forecasts">
      <LedgerPageHeader
        eyebrow="Planejamento"
        title="Previsões"
        actions={<LedgerButton variant="primary" icon="plus" onClick={() => { setEditing(null); setShowForm(true); }}>Nova Previsão</LedgerButton>}
      />

      <LedgerAlert
        tone="info"
        title="Previsões não descontam do saldo"
        body="Registre entradas e saídas que você sabe que vão acontecer. Elas ficam aqui até você marcar como concluídas — só então viram transações reais."
        icon="calendar-clock"
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label="Entradas previstas" value={S.fmtMoney(thisMonthIn)}  variant="positive" footer={`${scopedIncome.length} ${monthFilter === 'all' ? 'no total' : 'no mês'} · próximos 30d ${S.fmtMoney(next30In)}`} />
        <LedgerKpi label="Saídas previstas"   value={S.fmtMoney(thisMonthOut)} variant="negative" footer={`${scopedExpenses.length} ${monthFilter === 'all' ? 'no total' : 'no mês'} · próximos 30d ${S.fmtMoney(next30Out)}`} />
        <LedgerKpi label="Aportes previstos" value={S.fmtMoney(thisMonthTransfers)} footer={`${scopedTransfers.length} ${monthFilter === 'all' ? 'no total' : 'no mês'} · não conta como saída`} />
        <LedgerKpi label={monthFilter === 'all' ? 'Saldo previsto (total)' : 'Saldo previsto do mês'} value={S.fmtMoney(thisMonthIn - thisMonthOut, { signed: true })} variant="inverse" footer={(thisMonthIn - thisMonthOut) >= 0 ? 'Entrada supera saídas' : 'Saídas superam entradas'} />
        <LedgerKpi label="Total pendente" value={`${pendingIncome.length + pendingExpenses.length + pendingTransfers.length}`} footer="previsões em aberto" />
      </div>

      <div style={{ position: 'relative' }}>
        <input
          placeholder="Buscar previsões por nome ou categoria…"
          value={query}
          onChange={e => setQuery(e.target.value)}
          onFocus={() => setSearchFocus(true)} onBlur={() => setSearchFocus(false)}
          style={{
            fontFamily: 'var(--font-body)', fontSize: 13, padding: '11px 14px 11px 38px', width: '100%', boxSizing: 'border-box',
            border: `1px solid ${searchFocus ? 'var(--slate-400)' : 'var(--border)'}`, borderRadius: 'var(--r-3)',
            background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
            boxShadow: searchFocus ? 'var(--shadow-focus)' : 'none',
            transition: 'all var(--dur-fast) var(--ease-out)',
          }}
        />
        <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', display: 'flex' }}>
          <LedgerIcon name="search" size={15} color="var(--fg-3)" />
        </span>
        {query && (
          <button onClick={() => setQuery('')} style={{
            all: 'unset', cursor: 'pointer', position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
            display: 'flex', color: 'var(--fg-3)',
          }}>
            <LedgerIcon name="x" size={15} color="currentColor" />
          </button>
        )}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <LedgerSegmented
            options={[
              { label: 'Pendentes',   value: 'pending' },
              { label: 'Realizadas',  value: 'realized' },
              { label: 'Todas',       value: 'all' },
            ]}
            value={statusFilter}
            onChange={setStatusFilter}
          />
          <LedgerSegmented
            options={[
              { label: 'Tudo',     value: 'all' },
              { label: 'Saídas',   value: 'expense' },
              { label: 'Entradas', value: 'income' },
              { label: 'Aportes',  value: 'transfer' },
            ]}
            value={kindFilter}
            onChange={setKindFilter}
          />
          <select
            value={monthFilter}
            onChange={e => setMonthFilter(e.target.value)}
            style={{
              fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600,
              padding: '8px 12px', borderRadius: 'var(--r-3)',
              border: '1px solid var(--border)', background: 'var(--bg-elevated)',
              color: 'var(--fg)', outline: 'none', cursor: 'pointer',
            }}
          >
            <option value="all">Todos os meses</option>
            {availableMonths.map(m => {
              const [y, mo] = m.split('-');
              const nome = new Date(Number(y), Number(mo) - 1, 1).toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
              return <option key={m} value={m}>{nome.charAt(0).toUpperCase() + nome.slice(1)}</option>;
            })}
          </select>
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)' }}>
          {filtered.length} {filtered.length === 1 ? 'item' : 'itens'}
        </div>
      </div>

      <div style={{ background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)', overflow: 'hidden', border: '1px solid var(--border)' }}>
        {filtered.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            Nada para mostrar com esses filtros.
          </div>
        )}
        {visibleFiltered.map((f, idx) => {
          const kind = f.kind || 'expense';
          const isIncome = kind === 'income';
          const isTransfer = kind === 'transfer';
          const goalRef = isTransfer && f.goalId ? (state.goals || []).find(g => String(g.id) === String(f.goalId)) : null;
          const cat = !isIncome && !isTransfer && S.catLookup(f.categoryId);
          const sub = !isIncome && !isTransfer && S.subLookup(f.categoryId, f.subcategoryId);
          const d = new Date(f.dueDate);
          const daysUntil = Math.ceil((d - new Date()) / (1000 * 60 * 60 * 24));
          const overdue = f.status === 'pending' && daysUntil < 0;
          const dueSoon = f.status === 'pending' && daysUntil >= 0 && daysUntil <= 7;
          const realized = f.status === 'realized';

          if (stack) {
            return (
              <div key={f.id} style={{
                padding: '14px 16px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
                display: 'flex', flexDirection: 'column', gap: 10,
                opacity: realized ? 0.6 : 1,
              }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <div style={{
                    width: 40, height: 40, borderRadius: 'var(--r-3)',
                    background: isIncome ? 'var(--positive-50)'
                              : isTransfer ? 'var(--positive-50)'
                              : overdue ? 'var(--brand-magenta-100)'
                              : dueSoon ? 'var(--warning-100)'
                              : 'var(--bg-muted)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <LedgerIcon
                      name={isIncome ? 'arrow-down-left' : isTransfer ? 'arrow-right-left' : (cat ? cat.icon : 'calendar')}
                      size={18}
                      color={isIncome || isTransfer ? 'var(--positive-700)' : (overdue ? 'var(--brand-magenta-700)' : 'var(--fg-strong)')}
                    />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                      <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--fg-strong)', textDecoration: realized ? 'line-through' : 'none', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
                      <div className="num" style={{ fontSize: 15, color: isIncome ? 'var(--fg-positive)' : 'var(--fg-strong)', whiteSpace: 'nowrap' }}>
                        {S.fmtMoney(isIncome ? Math.abs(f.amount) : -Math.abs(f.amount), { signed: true })}
                      </div>
                    </div>
                    <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                      {isIncome ? (f.source ? `Fonte · ${f.source}` : 'Entrada')
                        : isTransfer ? (goalRef ? `Aporte · ${goalRef.name}` : 'Aporte para meta')
                        : (sub ? sub.name : cat ? cat.name : '—')}
                      {f.recurrence && f.recurrence !== 'once' && ' · ' + ({ monthly: 'Mensal', yearly: 'Anual', weekly: 'Semanal' }[f.recurrence] || f.recurrence)}
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, flexWrap: 'wrap' }}>
                      <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: overdue ? 'var(--brand-magenta)' : 'var(--fg-2)' }}>
                        {S.fmtDate(f.dueDate, { short: true })}
                      </span>
                      <span style={{ fontFamily: 'var(--font-body)', fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.4px', textTransform: 'uppercase' }}>
                        · {overdue ? `Atrasado ${Math.abs(daysUntil)}d` : dueSoon ? `Em ${daysUntil}d` : realized ? 'Realizado' : `${daysUntil}d`}
                      </span>
                    </div>
                  </div>
                </div>
                {!realized && (
                  <div style={{ display: 'flex', gap: 6 }}>
                    <LedgerButton variant="primary" size="sm" icon="check" full onClick={() => realizeForecast(f)}>
                      {isIncome ? 'Confirmar recebimento' : isTransfer ? 'Confirmar aporte' : 'Marcar pago'}
                    </LedgerButton>
                    <button onClick={() => { setEditing(f.id); setShowForm(true); }} title="Editar" style={mobileIconBtn()}>
                      <LedgerIcon name="pencil" size={16} color="currentColor" />
                    </button>
                    <button onClick={() => removeForecast(f.id)} title="Remover" style={mobileIconBtn()}>
                      <LedgerIcon name="trash-2" size={16} color="currentColor" />
                    </button>
                  </div>
                )}
              </div>
            );
          }

          return (
            <div key={f.id} style={{
              display: 'grid',
              gridTemplateColumns: '88px minmax(0,1fr) 140px 120px 200px',
              padding: '16px 24px',
              borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
              alignItems: 'center', gap: 12,
              opacity: realized ? 0.6 : 1,
            }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                <div className="mono" style={{ fontSize: 13, color: overdue ? 'var(--brand-magenta)' : 'var(--fg)', fontWeight: 700 }}>
                  {S.fmtDate(f.dueDate, { short: true })}
                </div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '0.5px', color: 'var(--fg-3)', textTransform: 'uppercase' }}>
                  {overdue ? `Atrasado ${Math.abs(daysUntil)}d` : dueSoon ? `Em ${daysUntil}d` : realized ? 'Realizado' : `${daysUntil}d`}
                </div>
              </div>

              <div style={{ display: 'flex', gap: 12, alignItems: 'center', minWidth: 0 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 'var(--r-2)',
                  background: isIncome ? 'var(--positive-50)'
                            : isTransfer ? 'var(--positive-50)'
                            : overdue ? 'var(--brand-magenta-100)'
                            : dueSoon ? 'var(--warning-100)'
                            : 'var(--bg-muted)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <LedgerIcon
                    name={isIncome ? 'arrow-down-left' : isTransfer ? 'arrow-right-left' : (cat ? cat.icon : 'calendar')}
                    size={16}
                    color={isIncome || isTransfer ? 'var(--positive-700)' : (overdue ? 'var(--brand-magenta-700)' : 'var(--fg-strong)')}
                  />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)', textDecoration: realized ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                    {isIncome
                      ? (f.source ? `Fonte · ${f.source}` : 'Entrada')
                      : isTransfer
                        ? (goalRef ? `Aporte · ${goalRef.name}` : 'Aporte para meta')
                        : (sub ? sub.name : cat ? cat.name : '—')}
                    {f.fixed && ' · Fixo'}
                    {f.recurrence && f.recurrence !== 'once' && ' · ' + ({ monthly: 'Mensal', yearly: 'Anual', weekly: 'Semanal' }[f.recurrence] || f.recurrence)}
                  </div>
                </div>
              </div>

              <div>
                {isIncome
                  ? <LedgerChip tone="income">ENTRADA</LedgerChip>
                  : isTransfer
                    ? <LedgerChip tone="alpha">APORTE</LedgerChip>
                    : cat
                      ? <LedgerChip tone={cat.chipTone}>{cat.name}</LedgerChip>
                      : <LedgerChip tone="neutral">—</LedgerChip>}
              </div>

              <div className="num" style={{
                textAlign: 'right', fontSize: 16, whiteSpace: 'nowrap',
                color: realized ? 'var(--fg-2)' : (isIncome ? 'var(--fg-positive)' : 'var(--fg-strong)'),
              }}>
                {S.fmtMoney(isIncome ? Math.abs(f.amount) : -Math.abs(f.amount), { signed: true })}
              </div>

              <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', alignItems: 'center', minWidth: 0 }}>
                {!realized && (
                  <LedgerButton variant="primary" size="sm" icon="check" onClick={() => realizeForecast(f)}>
                    {isIncome ? 'Confirmar' : isTransfer ? 'Aportar' : 'Marcar pago'}
                  </LedgerButton>
                )}
                {!realized && (
                  <button onClick={() => { setEditing(f.id); setShowForm(true); }} title="Editar" style={iconBtnStyle('var(--fg-2)')}>
                    <LedgerIcon name="pencil" size={14} color="currentColor" />
                  </button>
                )}
                <button onClick={() => removeForecast(f.id)} title="Remover" style={iconBtnStyle('var(--fg-3)')}>
                  <LedgerIcon name="trash-2" size={14} color="currentColor" />
                </button>
              </div>
            </div>
          );
        })}
        {hasMore && (
          <div ref={loadMoreRef} style={{ padding: '18px 28px', textAlign: 'center', borderTop: '1px solid var(--border)' }}>
            <LedgerButton variant="secondary" size="sm" onClick={() => setVisibleCount(c => c + PAGE)}>
              Carregar mais ({filtered.length - visibleCount} restantes)
            </LedgerButton>
          </div>
        )}
      </div>

      {showForm && (
        <ForecastFormModal
          initial={editing && state.forecasts.find(f => f.id === editing)}
          goals={state.goals || []}
          onClose={() => { setShowForm(false); setEditing(null); }}
          onSave={upsertForecast}
        />
      )}
    </div>
  );
}

function iconBtnStyle(color) {
  return {
    all: 'unset', cursor: 'pointer',
    padding: 8, borderRadius: 'var(--r-2)', color,
    transition: 'all var(--dur-fast)',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  };
}

function mobileIconBtn() {
  return {
    all: 'unset', cursor: 'pointer',
    width: 40, height: 40, borderRadius: 'var(--r-3)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: 'var(--bg-inset)', color: 'var(--fg-2)', flexShrink: 0,
  };
}

function ForecastFormModal({ initial, goals, onClose, onSave }) {
  const S = window.LedgerStore;
  const [kind,        setKind]        = React.useState(initial?.kind || 'expense');
  const [name,        setName]        = React.useState(initial?.name || '');
  const [amount,      setAmount]      = React.useState(initial ? String(initial.amount).replace('.', ',') : '');
  const [dueDate,     setDueDate]     = React.useState(initial ? new Date(initial.dueDate).toISOString().slice(0, 10) : new Date().toISOString().slice(0, 10));
  const [categoryId,  setCategoryId]  = React.useState(initial?.categoryId || 'basic');
  const [subcategoryId, setSubcategoryId] = React.useState(initial?.subcategoryId || 'bills-other');
  const [source,      setSource]      = React.useState(initial?.source || 'Salary');
  const [customSource, setCustomSource] = React.useState('');
  const [recurrence,  setRecurrence]  = React.useState(initial?.recurrence || 'monthly');
  const [fixed,       setFixed]       = React.useState(initial?.fixed ?? true);
  const [fixedMonthsRaw, setFixedMonths] = React.useState(12);
  const [goalId,      setGoalId]      = React.useState(initial?.goalId || '');
  const [note,        setNote]        = React.useState(initial?.note || '');
  const [focus,       setFocus]       = React.useState(null);
  const [error,       setError]       = React.useState('');

  const cat = S.catLookup(categoryId);
  const isTransfer = kind === 'transfer';
  const isGoalAport = kind === 'expense' && categoryId === 'investments' && subcategoryId === 'inv-goals';

  React.useEffect(() => {
    if (cat && !cat.subs.find(s => s.id === subcategoryId)) setSubcategoryId(cat.subs[0].id);
  }, [categoryId]);

  const inputStyle = (id) => ({
    fontFamily: 'var(--font-body)', fontSize: 14, padding: '11px 14px', width: '100%', boxSizing: 'border-box',
    border: `1px solid ${focus === id ? 'var(--slate-400)' : 'var(--border)'}`,
    borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
    boxShadow: focus === id ? 'var(--shadow-focus)' : 'none', transition: 'all var(--dur-fast)',
  });

  function save() {
    setError('');
    const n = parseFloat((amount || '').replace(',', '.'));
    if (!name.trim()) { setError('Dê um nome para a previsão.'); return; }
    if (!n || isNaN(n) || n <= 0) { setError('Informe um valor positivo.'); return; }
    if (isTransfer && !goalId) { setError('Escolha a meta de destino do aporte.'); return; }
    const basePayload = {
      kind,
      name: name.trim(),
      amount: Math.abs(n),
      dueDate: new Date(dueDate + 'T12:00:00').toISOString(),
      recurrence,
      fixed,
      note: note.trim(),
    };
    if (kind === 'income') {
      basePayload.source = source === 'Other' ? (customSource || 'Other') : source;
      basePayload.categoryId = null;
      basePayload.subcategoryId = null;
      basePayload.goalId = null;
    } else if (isTransfer) {
      basePayload.categoryId = 'investments';
      basePayload.subcategoryId = 'inv-goals';
      basePayload.source = null;
      basePayload.goalId = goalId;
    } else {
      basePayload.categoryId = categoryId;
      basePayload.subcategoryId = subcategoryId;
      basePayload.source = null;
      basePayload.goalId = null;
    }

    // Despesa fixa criada do zero (não edição): gera uma previsão por mês,
    // pelo número de meses escolhido — mesmo padrão do lançamento fixo.
    const isNewFixedExpense = !initial && fixed && kind === 'expense';
    if (isNewFixedExpense) {
      const months = (() => {
        const m = parseInt(fixedMonthsRaw, 10);
        return (!fixedMonthsRaw || isNaN(m) || m < 1) ? 1 : Math.min(120, m);
      })();
      const baseDate = new Date(dueDate + 'T12:00:00');
      const list = [];
      for (let i = 0; i < months; i++) {
        const d = new Date(baseDate);
        d.setMonth(d.getMonth() + i);
        list.push({ ...basePayload, dueDate: d.toISOString() });
      }
      onSave(list);
      return;
    }

    onSave(basePayload);
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 150, padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 560, maxHeight: '90vh', overflow: 'auto',
        background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)',
        padding: 28, boxShadow: 'var(--shadow-pop)', display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>PREVISÃO</div>
            <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>
              {initial ? 'Editar previsão' : 'Nova previsão'}
            </h3>
          </div>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-2)' }}>
            <LedgerIcon name="x" size={18} color="currentColor" />
          </button>
        </div>

        {error && (
          <div style={{
            padding: '10px 12px', borderRadius: 'var(--r-3)', display: 'flex', alignItems: 'center', gap: 10,
            background: 'var(--brand-magenta-100)', border: '1px solid rgba(176,3,105,0.22)',
            color: 'var(--brand-magenta-700)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13,
          }}>
            <LedgerIcon name="alert-circle" size={16} color="var(--brand-magenta-700)" /> {error}
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Tipo da previsão</span>
          <LedgerSegmented
            options={[
              { label: 'Saída',   value: 'expense' },
              { label: 'Entrada', value: 'income' },
              { label: 'Aporte',  value: 'transfer' },
            ]}
            value={kind}
            onChange={setKind}
          />
        </div>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Nome</span>
          <input value={name} onChange={e => setName(e.target.value)} placeholder={kind === 'income' ? 'ex: Salário Junho' : isTransfer ? 'ex: Aporte mensal ETFs' : 'ex: Mensalidade Faculdade'} onFocus={() => setFocus('n')} onBlur={() => setFocus(null)} style={inputStyle('n')} />
        </label>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Valor médio (R$)</span>
            <input value={amount} onChange={e => setAmount(e.target.value)} placeholder="2400,00" inputMode="decimal" onFocus={() => setFocus('a')} onBlur={() => setFocus(null)} style={inputStyle('a')} />
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>{kind === 'income' ? 'Data prevista' : 'Vencimento'}</span>
            <input type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} onFocus={() => setFocus('d')} onBlur={() => setFocus(null)} style={inputStyle('d')} />
          </label>
        </div>

        {kind === 'income' ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Fonte</span>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {S.INCOME_SOURCES.map(src => {
                const on = source === src;
                return (
                  <button key={src} type="button" onClick={() => setSource(src)} style={{
                    all: 'unset', cursor: 'pointer',
                    padding: '8px 14px', borderRadius: 'var(--r-3)',
                    background: on ? 'var(--positive-50)' : 'var(--bg-muted)',
                    color: on ? 'var(--positive-700)' : 'var(--fg)',
                    border: on ? '1px solid var(--positive-500)' : '1px solid transparent',
                    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13,
                  }}>{src}</button>
                );
              })}
            </div>
            {source === 'Other' && (
              <input value={customSource} onChange={e => setCustomSource(e.target.value)} placeholder="Especifique" onFocus={() => setFocus('cs')} onBlur={() => setFocus(null)} style={{ ...inputStyle('cs'), marginTop: 6 }} />
            )}
          </div>
        ) : isTransfer ? (
          <>
            <div style={{
              padding: '14px 16px', borderRadius: 'var(--r-3)',
              background: 'var(--positive-50)', border: '1px solid rgba(0,150,104,0.25)',
              display: 'flex', gap: 12, alignItems: 'flex-start',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 'var(--r-3)', background: 'var(--positive-100)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <LedgerIcon name="arrow-right-left" size={16} color="var(--positive-700)" />
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--positive-700)' }}>Aporte previsto para meta</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--positive-700)', opacity: 0.85, marginTop: 2 }}>
                  Quando confirmado, o valor sai do saldo, entra em Investimentos → Metas e soma à meta escolhida.
                </div>
              </div>
            </div>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--positive-700)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <LedgerIcon name="target" size={14} color="var(--positive-700)" />
                Meta de destino
              </span>
              {goals.length === 0 ? (
                <div style={{
                  padding: '10px 12px', borderRadius: 'var(--r-3)',
                  background: 'var(--bg-muted)', border: '1px dashed var(--border-strong)',
                  fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)',
                }}>
                  Crie metas em "Metas de Investimento" para fazer aportes previstos.
                </div>
              ) : (
                <select value={goalId} onChange={e => setGoalId(e.target.value)} onFocus={() => setFocus('g')} onBlur={() => setFocus(null)} style={{
                  ...inputStyle('g'),
                  border: '1px solid var(--positive-500)',
                  background: 'var(--positive-50)',
                  color: 'var(--positive-700)',
                  fontWeight: 600,
                }}>
                  <option value="">Escolha uma meta</option>
                  {goals.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
                </select>
              )}
            </label>
          </>
        ) : (
          <>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Categoria</span>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {S.CATEGORIES.map(c => {
                  const on = categoryId === c.id;
                  return (
                    <button key={c.id} type="button" onClick={() => setCategoryId(c.id)} style={{
                      all: 'unset', cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 8,
                      padding: '8px 12px', borderRadius: 'var(--r-3)',
                      background: on ? 'var(--brand-magenta-100)' : 'var(--bg-muted)',
                      color: on ? 'var(--brand-magenta-700)' : 'var(--fg)',
                      border: on ? '1px solid var(--brand-magenta)' : '1px solid transparent',
                      fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12,
                    }}>
                      <LedgerIcon name={c.icon} size={14} color={on ? 'var(--brand-magenta-700)' : 'var(--fg)'} />
                      {c.name}
                    </button>
                  );
                })}
              </div>
            </div>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Subcategoria</span>
              <select value={subcategoryId} onChange={e => setSubcategoryId(e.target.value)} onFocus={() => setFocus('s')} onBlur={() => setFocus(null)} style={inputStyle('s')}>
                {cat && cat.subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </label>

            {isGoalAport && (
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--positive-700)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <LedgerIcon name="target" size={14} color="var(--positive-700)" />
                  Aporte para meta
                </span>
                {goals.length === 0 ? (
                  <div style={{
                    padding: '10px 12px', borderRadius: 'var(--r-3)',
                    background: 'var(--bg-muted)', border: '1px dashed var(--border-strong)',
                    fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)',
                  }}>
                    Crie metas em "Investment Goals" para vincular aportes a elas.
                  </div>
                ) : (
                  <select value={goalId} onChange={e => setGoalId(e.target.value)} onFocus={() => setFocus('g')} onBlur={() => setFocus(null)} style={{
                    ...inputStyle('g'),
                    border: '1px solid var(--positive-500)',
                    background: 'var(--positive-50)',
                    color: 'var(--positive-700)',
                    fontWeight: 600,
                  }}>
                    <option value="">Sem meta específica</option>
                    {goals.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
                  </select>
                )}
              </label>
            )}
          </>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Recorrência</span>
            <select value={recurrence} onChange={e => setRecurrence(e.target.value)} onFocus={() => setFocus('r')} onBlur={() => setFocus(null)} style={inputStyle('r')}>
              <option value="once">Única vez</option>
              <option value="weekly">Semanal</option>
              <option value="monthly">Mensal</option>
              <option value="yearly">Anual</option>
            </select>
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Tipo</span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button type="button" onClick={() => setFixed(false)} style={pillStyle(!fixed)}>
                <LedgerIcon name="activity" size={14} color={!fixed ? 'var(--fg-strong)' : 'var(--fg-3)'} /> Variável
              </button>
              <button type="button" onClick={() => setFixed(true)} style={pillStyle(fixed)}>
                <LedgerIcon name="repeat" size={14} color={fixed ? 'var(--fg-strong)' : 'var(--fg-3)'} /> Fixo
              </button>
            </div>
          </label>
        </div>

        {fixed && kind === 'expense' && !initial && (
          <div style={{
            padding: '14px 16px', borderRadius: 'var(--r-3)',
            background: 'var(--bg-muted)', border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap',
          }}>
            <LedgerIcon name="repeat" size={16} color="var(--fg-2)" />
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg)' }}>
              Criar previsão repetida por
            </span>
            <input
              type="text" inputMode="numeric" pattern="[0-9]*"
              value={fixedMonthsRaw}
              onChange={e => {
                const v = e.target.value.replace(/[^0-9]/g, '');
                if (v === '') { setFixedMonths(''); return; }
                const n2 = parseInt(v, 10);
                if (!isNaN(n2)) setFixedMonths(Math.min(120, n2));
              }}
              onBlur={() => {
                setFixedMonths(prev => {
                  const n2 = parseInt(prev, 10);
                  return (!prev || isNaN(n2) || n2 < 1) ? 1 : Math.min(120, n2);
                });
              }}
              style={{
                width: 70, fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700,
                padding: '8px 10px', borderRadius: 'var(--r-2)', textAlign: 'center',
                border: '1px solid var(--border)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
              }}
            />
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg)' }}>meses</span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', flexBasis: '100%' }}>
              Cria uma previsão em cada um desses meses, a partir da data escolhida. Você pode editar ou apagar cada mês individualmente depois.
            </span>
          </div>
        )}

        {fixed && initial && (
          <div style={{
            padding: '10px 14px', borderRadius: 'var(--r-3)',
            background: 'var(--info-100)', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <LedgerIcon name="info" size={15} color="var(--info-500)" />
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)' }}>
              Editando apenas esta previsão. Para repetir por vários meses, crie uma nova.
            </span>
          </div>
        )}

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Observação <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>(opcional)</span></span>
          <input value={note} onChange={e => setNote(e.target.value)} placeholder="ex: Estimativa baseada nos 3 últimos meses" onFocus={() => setFocus('o')} onBlur={() => setFocus(null)} style={inputStyle('o')} />
        </label>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
          <LedgerButton variant="secondary" onClick={onClose}>Cancelar</LedgerButton>
          <LedgerButton variant="primary" icon="check" onClick={save}>{initial ? 'Salvar' : 'Criar previsão'}</LedgerButton>
        </div>
      </div>
    </div>
  );
}

function pillStyle(on) {
  return {
    all: 'unset', cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: '8px 14px', borderRadius: 'var(--r-3)',
    background: on ? 'var(--bg-elevated)' : 'var(--bg-inset)',
    color: on ? 'var(--fg-strong)' : 'var(--fg-3)',
    border: on ? '1px solid var(--border)' : '1px solid transparent',
    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12,
    transition: 'all var(--dur-fast)',
  };
}

// ── BULK FORECAST HELPERS ────────────────────────────────────
function newBulkForecastRow() {
  const today = new Date().toISOString().slice(0, 10);
  return {
    rid: 'bf' + Date.now() + Math.random(),
    kind: 'expense',
    name: '',
    amount: '',
    dueDate: today,
    categoryId: 'basic',
    subcategoryId: 'bills-other',
    source: 'Salário',
    recurrence: 'monthly',
    fixed: true,
  };
}

function BulkForecastRow({ row, idx, state, onChange, onRemove, onDuplicate }) {
  const S = window.LedgerStore;
  const allCats = S.getCategoriesWithCustom(state);
  const cat = allCats.find(c => c.id === row.categoryId) || S.catLookup(row.categoryId);

  const cellInput = {
    all: 'unset', boxSizing: 'border-box', width: '100%', padding: '8px 10px',
    fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg)',
    border: '1px solid transparent', borderRadius: 'var(--r-2)',
    background: 'var(--bg-muted)', cursor: 'text', transition: 'all var(--dur-fast)',
  };
  const cellSelect = {
    ...cellInput, cursor: 'pointer', appearance: 'none',
    backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2210%22 height=%226%22 viewBox=%220 0 10 6%22><path fill=%22none%22 stroke=%22%2364748B%22 stroke-width=%221.5%22 d=%22M1 1l4 4 4-4%22/></svg>")',
    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center', paddingRight: 24,
  };

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '110px 1fr 120px 130px 160px 110px 56px',
      padding: '8px 18px', gap: 8, alignItems: 'center',
      borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
    }}>
      {/* Tipo */}
      <select value={row.kind} onChange={e => onChange({ kind: e.target.value })} style={{
        ...cellSelect,
        color: row.kind === 'income' ? 'var(--fg-positive)' : 'var(--brand-magenta)',
        fontWeight: 700,
      }}>
        <option value="expense">Saída</option>
        <option value="income">Entrada</option>
      </select>

      {/* Nome */}
      <input value={row.name} onChange={e => onChange({ name: e.target.value })}
        placeholder="Nome da previsão..."
        style={cellInput} />

      {/* Valor */}
      <input value={row.amount} onChange={e => onChange({ amount: e.target.value })}
        inputMode="decimal" placeholder="0,00"
        style={{ ...cellInput, textAlign: 'right', fontWeight: 700,
          color: row.kind === 'income' ? 'var(--fg-positive)' : 'var(--brand-magenta)' }} />

      {/* Vencimento */}
      <input type="date" value={row.dueDate} onChange={e => onChange({ dueDate: e.target.value })}
        style={cellInput} />

      {/* Categoria / Fonte */}
      {row.kind === 'income' ? (
        <select value={row.source} onChange={e => onChange({ source: e.target.value })} style={cellSelect}>
          {S.INCOME_SOURCES.map(s => <option key={s} value={s}>{s}</option>)}
        </select>
      ) : (
        <select value={row.categoryId} onChange={e => onChange({
          categoryId: e.target.value,
          subcategoryId: (S.catLookup(e.target.value)?.subs[0]?.id || '')
        })} style={cellSelect}>
          {allCats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
      )}

      {/* Recorrência */}
      <select value={row.recurrence} onChange={e => onChange({ recurrence: e.target.value })} style={cellSelect}>
        <option value="once">Uma vez</option>
        <option value="monthly">Mensal</option>
        <option value="weekly">Semanal</option>
        <option value="yearly">Anual</option>
      </select>

      {/* Ações */}
      <div style={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
        <button type="button" onClick={onDuplicate} title="Duplicar" style={{
          all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
        }} onMouseEnter={e => e.currentTarget.style.color = 'var(--fg)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-3)'}>
          <LedgerIcon name="copy" size={13} color="currentColor" />
        </button>
        <button type="button" onClick={onRemove} title="Remover" style={{
          all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
        }} onMouseEnter={e => { e.currentTarget.style.color = 'var(--brand-magenta-700)'; e.currentTarget.style.background = 'var(--brand-magenta-100)'; }}
           onMouseLeave={e => { e.currentTarget.style.color = 'var(--fg-3)'; e.currentTarget.style.background = 'transparent'; }}>
          <LedgerIcon name="trash-2" size={13} color="currentColor" />
        </button>
      </div>
    </div>
  );
}

window.LedgerForecastsScreen = LedgerForecastsScreen;
