// ─────────────────────────────────────────────────────────────
// entry-screen.jsx — Record entries (single or bulk)
//
// Two modes:
//   • Single  → rich form for one transaction
//   • Lote (Bulk) → a table where each row is one transaction.
//     Add as many rows as you want, then commit all at once.
// ─────────────────────────────────────────────────────────────

const { LedgerIcon, LedgerButton, LedgerPageHeader, LedgerSegmented } = window;

function LedgerEntryScreen({ state, setState, onNavigate }) {
  const [mode, setMode] = React.useState('single'); // 'single' | 'bulk'

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1180, margin: '0 auto' }} data-screen-label="New Entry">
      <LedgerPageHeader
        eyebrow="Curar o Razão"
        title={mode === 'single' ? 'Registrar lançamento' : 'Registrar vários lançamentos'}
        actions={
          <LedgerSegmented
            options={[
              { label: 'Uma entrada', value: 'single' },
              { label: 'Em lote',     value: 'bulk'   },
            ]}
            value={mode}
            onChange={setMode}
          />
        }
      />

      {mode === 'single'
        ? <SingleEntryForm state={state} setState={setState} onNavigate={onNavigate} />
        : <BulkEntryTable  state={state} setState={setState} onNavigate={onNavigate} />}
    </div>
  );
}

// ── SINGLE-ENTRY FORM ──────────────────────────────────────────
function SingleEntryForm({ state, setState, onNavigate }) {
  const S = window.LedgerStore;
  const { isMobile } = window.useViewport();
  const [type, setType]                   = React.useState('expense');
  const [amount, setAmount]               = React.useState('');
  const [date, setDate]                   = React.useState(new Date().toISOString().slice(0, 10));
  const [counterparty, setCounterparty]   = React.useState('');
  const [categoryId, setCategoryId]       = React.useState('basic');
  const [subcategoryId, setSubcategoryId] = React.useState('food-supermarket');
  const [paymentMethod, setPaymentMethod] = React.useState('debit');
  const [source, setSource]               = React.useState('Salary');
  const [customSource, setCustomSource]   = React.useState('');
  const [fixed, setFixed]                 = React.useState(false);
  // Marca se o usuário já mexeu manualmente no botão Fixo/Variável.
  // Depois disso, a troca de subcategoria não sobrescreve mais a escolha dele.
  const fixedTouchedRef = React.useRef(false);
  const [fixedMonthsRaw, setFixedMonths]  = React.useState(12);
  const [goalId, setGoalId]               = React.useState('');
  const [holdingDest, setHoldingDest]     = React.useState('general'); // 'general' | holdingId | '__new__'
  const [newHoldingName, setNewHoldingName] = React.useState('');
  const [newHoldingType, setNewHoldingType] = React.useState('Fundo');
  const [focus, setFocus]                 = React.useState(null);
  const [error, setError]                 = React.useState('');
  const [success, setSuccess]             = React.useState(false);

  const allCategories = S.getCategoriesWithCustom(state);
  const cat = allCategories.find(c => c.id === categoryId) || S.catLookup(categoryId);
  const isGoalAport = (type === 'expense' && categoryId === 'investments' && subcategoryId === 'inv-goals') || type === 'transfer';
  const isTransfer = type === 'transfer';
  const goals = state.goals || [];
  const selectedGoal = goals.find(g => String(g.id) === String(goalId));
  const goalHoldings = selectedGoal ? (selectedGoal.holdings || []) : [];
  // Reset holding destination when the goal changes
  React.useEffect(() => { setHoldingDest('general'); setNewHoldingName(''); }, [goalId]);
  // When the user picks an "Other" subcategory or source, force them to describe the transaction.
  const needsCustomDescription =
    (type === 'expense' && typeof subcategoryId === 'string' && subcategoryId.endsWith('-other')) ||
    (type === 'income' && source === 'Other');

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

  React.useEffect(() => {
    // Só sugere o padrão da subcategoria (fixo/variável) se o usuário ainda
    // não escolheu manualmente nesta sessão do formulário — evita sobrescrever
    // uma escolha explícita quando ele troca de categoria/subcategoria depois.
    if (fixedTouchedRef.current) return;
    const sub = S.subLookup(categoryId, subcategoryId, state);
    if (sub && typeof sub.fixed === 'boolean') setFixed(sub.fixed);
  }, [subcategoryId, categoryId]);

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

  function handleSubmit(e) {
    e.preventDefault();
    setError('');
    const n = parseFloat((amount || '').replace(',', '.'));
    if (!n || isNaN(n) || n <= 0) { setError('Entre um valor positivo.'); return; }
    if (isTransfer && !goalId) { setError('Escolha uma meta para receber o aporte.'); return; }
    if (needsCustomDescription && !counterparty.trim() && !(type === 'income' && source === 'Other' && customSource.trim())) {
      setError('Descreva o que é essa transação (você escolheu "Outros").');
      return;
    }
    // Garante um número válido mesmo se o campo de meses ficou vazio (ex: usuário apagou e ainda não digitou)
    const fixedMonths = (() => {
      const n2 = parseInt(fixedMonthsRaw, 10);
      return (!fixedMonthsRaw || isNaN(n2) || n2 < 1) ? 1 : Math.min(120, n2);
    })();

    const goalRef = isGoalAport && goalId ? goals.find(g => String(g.id) === String(goalId)) : null;

    // Resolve the holding destination for the aporte (only when a goal is targeted)
    let holdingSpec = null, holdingLabel = '';
    if (goalRef) {
      if (holdingDest === '__new__') {
        if (!newHoldingName.trim()) { setError('Dê um nome ao novo investimento.'); return; }
        holdingSpec = { name: newHoldingName.trim(), type: newHoldingType };
        holdingLabel = newHoldingName.trim();
      } else if (holdingDest !== 'general') {
        const h = (goalRef.holdings || []).find(x => x.id === holdingDest);
        if (h) { holdingSpec = { id: h.id }; holdingLabel = h.name; }
      }
    }

    // Quando o usuário não escreve uma descrição, usa o nome da subcategoria
    // (ou categoria, se a subcategoria não tiver nome próprio) como fallback —
    // para despesas. Para entradas, usa a fonte. Aportes mantêm o texto "Aporte: ...".
    const fallbackName = type === 'income'
      ? (source === 'Other' ? (customSource || 'Outros') : source)
      : (S.subLookup(categoryId, subcategoryId, state)?.name || S.catLookup(categoryId)?.name || 'Lançamento');
    const note = counterparty || (goalRef ? `Aporte: ${goalRef.name}${holdingLabel ? ' · ' + holdingLabel : ''}` : fallbackName);

    // Transfers are stored as expense → investments → inv-goals so they show up in the
    // Investments bucket on the Cockpit and contribute to the monthly outflow correctly.
    const effectiveCategoryId    = isTransfer ? 'investments' : (type === 'income' ? null : categoryId);
    const effectiveSubcategoryId = isTransfer ? 'inv-goals'   : (type === 'income' ? null : subcategoryId);
    const effectiveType          = isTransfer ? 'expense'     : type;

    // Determina se a data escolhida está no futuro (depois de hoje)
    const chosenDate = new Date(date + 'T12:00:00');
    const today = new Date();
    const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const isFuture = chosenDate > new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);

    // Vira previsão se: data futura (qualquer tipo, incluindo aporte).
    // Despesa fixa começando HOJE/PASSADO não entra aqui — o mês atual deve
    // virar uma transação real (tratado mais abaixo); só os meses seguintes
    // viram previsões. Despesa fixa começando no FUTURO entra aqui, e todos
    // os meses (inclusive o primeiro) viram previsão.
    const treatAsForecast = isFuture;

    if (treatAsForecast) {
      // Para aportes, guardamos o tipo correto ('transfer') e a meta de destino,
      // para que ao realizar a previsão o aporte caia na meta certa.
      const fcKind = isTransfer ? 'transfer' : (type === 'income' ? 'income' : 'expense');
      // Monta uma previsão a partir dos campos do formulário
      const makeForecast = (dueIso, idSuffix) => ({
        id: 'f' + Date.now() + (idSuffix || ''),
        status: 'pending',
        realizedTxId: null,
        kind: fcKind,
        name: note || (goalRef ? `Aporte: ${goalRef.name}` : (S.subLookup(categoryId, subcategoryId, state)?.name)) || 'Lançamento',
        amount: Math.abs(n),
        dueDate: dueIso,
        categoryId: isTransfer ? 'investments' : (type === 'income' ? null : categoryId),
        subcategoryId: isTransfer ? 'inv-goals' : (type === 'income' ? null : subcategoryId),
        source: type === 'income' ? (source === 'Other' ? (customSource || 'Other') : source) : null,
        paymentMethod: isTransfer ? 'pix' : (type === 'income' ? null : paymentMethod),
        recurrence: 'once',
        fixed: type === 'expense' ? fixed : false,
        note: '',
        goalId: goalRef ? goalRef.id : null,
      });

      const newForecasts = [];
      if (type === 'expense' && fixed && !isTransfer) {
        // Despesa fixa começando no futuro: cria uma previsão por mês, por `fixedMonths` meses
        for (let i = 0; i < fixedMonths; i++) {
          const d = new Date(chosenDate);
          d.setMonth(d.getMonth() + i);
          newForecasts.push(makeForecast(d.toISOString(), '-' + i));
        }
      } else {
        // Data futura simples (inclui aporte futuro) → uma única previsão
        newForecasts.push(makeForecast(chosenDate.toISOString(), ''));
      }

      setState({ ...state, forecasts: [...(state.forecasts || []), ...newForecasts] });
      setSuccess(true);
      setTimeout(() => onNavigate('forecasts'), 700);
      return;
    }

    const tx = {
      id: Date.now(),
      date: new Date(date + 'T12:00:00').toISOString(),
      amount: type === 'income' ? Math.abs(n) : -Math.abs(n),
      type: effectiveType,
      categoryId: effectiveCategoryId,
      subcategoryId: effectiveSubcategoryId,
      source: type === 'income' ? (source === 'Other' ? (customSource || 'Other') : source) : null,
      paymentMethod: type === 'income' ? null : (isTransfer ? 'pix' : paymentMethod),
      note,
      fixed: type === 'expense' ? fixed : false,
      goalId: goalRef ? goalRef.id : null,
      holdingId: (holdingSpec && holdingSpec.id) ? holdingSpec.id : null,
      transfer: isTransfer || undefined,
    };

    const nextGoals = goalRef
      ? S.applyGoalAporte(state.goals, goalRef.id, Math.abs(n), holdingSpec)
      : state.goals;

    // Se for despesa fixa começando hoje/no passado: o mês atual é transação real,
    // e os meses seguintes entram como previsões.
    if (type === 'expense' && fixed && fixedMonths > 1) {
      const extraForecasts = [];
      for (let i = 1; i < fixedMonths; i++) {
        const d = new Date(chosenDate);
        d.setMonth(d.getMonth() + i);
        extraForecasts.push({
          id: 'f' + Date.now() + '-' + i,
          status: 'pending',
          realizedTxId: null,
          kind: 'expense',
          name: note || 'Despesa fixa',
          amount: Math.abs(n),
          dueDate: d.toISOString(),
          categoryId,
          subcategoryId,
          source: null,
          paymentMethod,
          recurrence: 'once',
          fixed: true,
          note: '',
          goalId: null,
        });
      }
      setState({ ...state, transactions: [tx, ...state.transactions], goals: nextGoals, forecasts: [...(state.forecasts || []), ...extraForecasts] });
      setSuccess(true);
      setTimeout(() => onNavigate('transactions'), 700);
      return;
    }

    setState({ ...state, transactions: [tx, ...state.transactions], goals: nextGoals });
    setSuccess(true);
    setTimeout(() => onNavigate(goalRef ? 'goals' : 'transactions'), 700);
  }

  return (
    <form onSubmit={handleSubmit} style={{
      background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)', padding: 32,
      display: 'flex', flexDirection: 'column', gap: 24,
      border: '1px solid var(--border)',
    }}>
      {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>
      )}

      <Field label="Tipo">
        <LedgerSegmented
          options={[
            { label: 'Saída',     value: 'expense' },
            { label: 'Entrada',   value: 'income' },
            { label: 'Aporte', value: 'transfer' },
          ]}
          value={type}
          onChange={setType}
        />
      </Field>

      <Field label="Valor">
        <div style={{
          display: 'flex', alignItems: 'stretch',
          border: `1px solid ${focus === 'amt' ? 'var(--slate-400)' : 'var(--border)'}`,
          borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)',
          boxShadow: focus === 'amt' ? 'var(--shadow-focus)' : 'none',
          transition: 'all var(--dur-fast)',
        }}>
          <span style={{
            display: 'flex', alignItems: 'center', padding: '0 16px',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22,
            color: type === 'income' ? 'var(--fg-positive)' : 'var(--brand-magenta)',
            borderRight: '1px solid var(--border)',
          }}>{type === 'income' ? '+' : '−'} R$</span>
          <input
            value={amount}
            onChange={e => setAmount(e.target.value)}
            onFocus={() => setFocus('amt')} onBlur={() => setFocus(null)}
            placeholder="0,00"
            inputMode="decimal"
            style={{
              flex: 1, border: 0, padding: '16px', outline: 'none',
              fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24,
              color: 'var(--fg-strong)', background: 'transparent', minWidth: 0,
            }}
          />
          <span style={{
            display: 'flex', alignItems: 'center', padding: '0 16px',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, letterSpacing: '0.5px',
            color: 'var(--fg-2)', borderLeft: '1px solid var(--border)',
          }}>BRL</span>
        </div>
      </Field>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <Field label="Data">
          <input type="date" value={date} onChange={e => setDate(e.target.value)} onFocus={() => setFocus('d')} onBlur={() => setFocus(null)} style={inputStyle('d')} />
        </Field>
        <Field
          label={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              {type === 'income' ? 'Descrição' : 'Descrição / contraparte'}
              <span style={{
                fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 10, letterSpacing: '0.5px',
                color: needsCustomDescription ? 'var(--brand-magenta-700)' : 'var(--fg-3)',
                textTransform: 'uppercase',
              }}>
                {needsCustomDescription ? 'obrigatório' : 'opcional'}
              </span>
            </span>
          }
          hint={needsCustomDescription ? 'Você escolheu "Outros" — descreva o que é essa transação.' : undefined}
        >
          <input
            value={counterparty}
            onChange={e => setCounterparty(e.target.value)}
            onFocus={() => setFocus('c')} onBlur={() => setFocus(null)}
            placeholder={
              needsCustomDescription
                ? 'ex: Presente de aniversário, Reembolso, Multa...'
                : (type === 'income' ? 'ex: Salário Junho' : 'ex: Pão de Açúcar')
            }
            style={inputStyle('c', needsCustomDescription && !counterparty.trim() ? 'warn' : false)}
          />
        </Field>
      </div>

      {type === 'income' ? (
        <Field label="Fonte da entrada">
          <div style={{ display: 'flex', gap: 8, 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,
                  transition: 'all var(--dur-fast)',
                }}>{src}</button>
              );
            })}
          </div>
          {source === 'Other' && (
            <input value={customSource} onChange={e => setCustomSource(e.target.value)} onFocus={() => setFocus('cs')} onBlur={() => setFocus(null)} placeholder="Especifique a fonte" style={{ ...inputStyle('cs'), marginTop: 10 }} />
          )}
        </Field>
      ) : type === 'transfer' ? (
        <>
          <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 para meta de investimento</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--positive-700)', opacity: 0.85, marginTop: 2 }}>
                O valor sai do saldo geral, é registrado como Investimentos → Metas e soma à meta escolhida.
              </div>
            </div>
          </div>

          <Field label="Meta de destino">
            {goals.length === 0 ? (
              <div style={{
                padding: '14px 16px', borderRadius: 'var(--r-3)',
                background: 'var(--bg-muted)', border: '1px dashed var(--border-strong)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
              }}>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-2)' }}>
                  Você ainda não criou nenhuma meta. Crie uma primeiro para fazer aportes.
                </div>
                <LedgerButton variant="secondary" size="sm" icon="plus" onClick={() => onNavigate('goals')}>Criar meta</LedgerButton>
              </div>
            ) : (
              <>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {goals.map(g => {
                    const on = String(g.id) === String(goalId);
                    const pct = Math.min(100, Math.round((g.saved / Math.max(1, g.target)) * 100));
                    return (
                      <button key={g.id} type="button" onClick={() => setGoalId(String(g.id))} style={goalPillStyle(on)}>
                        <LedgerIcon name={g.icon || 'target'} size={14} color="currentColor" />
                        <span>{g.name}</span>
                        <span style={{ fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 600, color: on ? 'var(--fg-on-inverse)' : 'var(--fg-3)', opacity: 0.85 }}>
                          {pct}%
                        </span>
                      </button>
                    );
                  })}
                </div>
                {selectedGoal && amount && parseFloat(amount.replace(',', '.')) > 0 && (
                  <div style={{
                    marginTop: 10, padding: '10px 14px', borderRadius: 'var(--r-3)',
                    background: 'var(--positive-50)', border: '1px solid rgba(0,150,104,0.25)',
                    display: 'flex', alignItems: 'center', gap: 10,
                    fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--positive-700)', fontWeight: 600,
                  }}>
                    <LedgerIcon name="trending-up" size={14} color="var(--positive-700)" />
                    <span>
                      {S.fmtMoney(parseFloat(amount.replace(',', '.')))} → meta <b>{selectedGoal.name}</b>
                      {' '}· novo total {S.fmtMoney(selectedGoal.saved + parseFloat(amount.replace(',', '.')))}
                    </span>
                  </div>
                )}
                {selectedGoal && (
                  <HoldingPicker
                    goal={selectedGoal}
                    value={holdingDest} onChange={setHoldingDest}
                    newName={newHoldingName} setNewName={setNewHoldingName}
                    newType={newHoldingType} setNewType={setNewHoldingType}
                  />
                )}
              </>
            )}
          </Field>
        </>
      ) : (
        <>
          <Field label="Bucket">
            {isMobile ? (
              <div style={{ position: 'relative' }}>
                <select
                  value={categoryId}
                  onChange={e => {
                    const nextCat = allCategories.find(c => c.id === e.target.value);
                    setCategoryId(e.target.value);
                    if (nextCat && nextCat.subs.length) {
                      const sorted = [...nextCat.subs].sort((a, b) => a.name.localeCompare(b.name, 'pt-BR'));
                      setSubcategoryId(sorted[0].id);
                    }
                  }}
                  style={{
                    width: '100%', boxSizing: 'border-box', appearance: 'none',
                    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14,
                    padding: '12px 36px 12px 14px', borderRadius: 'var(--r-3)',
                    background: 'var(--bg-muted)', color: 'var(--fg)',
                    border: '1px solid var(--border)', outline: 'none',
                  }}
                >
                  {allCategories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
                <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
                  <LedgerIcon name="chevron-down" size={16} color="var(--fg-3)" />
                </span>
              </div>
            ) : (
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {allCategories.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: '9px 14px', 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: 13,
                      transition: 'all var(--dur-fast)',
                    }}>
                      <LedgerIcon name={c.icon} size={16} color={on ? 'var(--brand-magenta-700)' : 'var(--fg)'} />
                      {c.name}
                    </button>
                  );
                })}
              </div>
            )}
          </Field>

          <Field label="Subcategoria">
            {isMobile ? (
              <div style={{ position: 'relative' }}>
                <select
                  value={subcategoryId}
                  onChange={e => setSubcategoryId(e.target.value)}
                  style={{
                    width: '100%', boxSizing: 'border-box', appearance: 'none',
                    fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14,
                    padding: '12px 36px 12px 14px', borderRadius: 'var(--r-3)',
                    background: 'var(--bg-inset)', color: 'var(--fg)',
                    border: '1px solid var(--border)', outline: 'none',
                  }}
                >
                  {[...cat.subs].sort((a, b) => a.name.localeCompare(b.name, 'pt-BR')).map(s =>
                    <option key={s.id} value={s.id}>{s.name}</option>
                  )}
                </select>
                <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
                  <LedgerIcon name="chevron-down" size={16} color="var(--fg-3)" />
                </span>
              </div>
            ) : (
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {[...cat.subs].sort((a, b) => a.name.localeCompare(b.name, 'pt-BR')).map(s => {
                  const on = subcategoryId === s.id;
                  return (
                    <button key={s.id} type="button" onClick={() => setSubcategoryId(s.id)} style={{
                      all: 'unset', cursor: 'pointer',
                      padding: '6px 12px', borderRadius: 'var(--r-3)',
                      background: on ? 'var(--bg-inverse)' : 'var(--bg-inset)',
                      color: on ? 'var(--fg-on-inverse)' : 'var(--fg-2)',
                      fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12,
                      transition: 'all var(--dur-fast)',
                    }}>{s.name}</button>
                  );
                })}
              </div>
            )}
          </Field>

          {isGoalAport && type === 'expense' && (
            <Field label="Meta de investimento">
              {goals.length === 0 ? (
                <div style={{
                  padding: '14px 16px', borderRadius: 'var(--r-3)',
                  background: 'var(--bg-muted)', border: '1px dashed var(--border-strong)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
                }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-2)' }}>
                    Você ainda não criou nenhuma meta de investimento.
                  </div>
                  <LedgerButton variant="secondary" size="sm" icon="plus" onClick={() => onNavigate('goals')}>Criar meta</LedgerButton>
                </div>
              ) : (
                <>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    <button type="button" onClick={() => setGoalId('')} style={goalPillStyle(goalId === '')}>
                      <LedgerIcon name="circle" size={14} color="currentColor" />
                      Sem meta específica
                    </button>
                    {goals.map(g => {
                      const on = String(g.id) === String(goalId);
                      const pct = Math.min(100, Math.round((g.saved / Math.max(1, g.target)) * 100));
                      return (
                        <button key={g.id} type="button" onClick={() => setGoalId(String(g.id))} style={goalPillStyle(on)}>
                          <LedgerIcon name={g.icon || 'target'} size={14} color="currentColor" />
                          <span>{g.name}</span>
                          <span style={{ fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 600, color: on ? 'var(--fg-on-inverse)' : 'var(--fg-3)', opacity: 0.85 }}>
                            {pct}%
                          </span>
                        </button>
                      );
                    })}
                  </div>
                  {selectedGoal && amount && parseFloat(amount.replace(',', '.')) > 0 && (
                    <div style={{
                      marginTop: 10, padding: '10px 14px', borderRadius: 'var(--r-3)',
                      background: 'var(--positive-50)', border: '1px solid rgba(0,150,104,0.25)',
                      display: 'flex', alignItems: 'center', gap: 10,
                      fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--positive-700)', fontWeight: 600,
                    }}>
                      <LedgerIcon name="trending-up" size={14} color="var(--positive-700)" />
                      <span>
                        {S.fmtMoney(parseFloat(amount.replace(',', '.')))} serão somados à meta <b>{selectedGoal.name}</b>
                        {' '}— novo total {S.fmtMoney(selectedGoal.saved + parseFloat(amount.replace(',', '.')))}
                      </span>
                    </div>
                  )}
                  {selectedGoal && (
                    <HoldingPicker
                      goal={selectedGoal}
                      value={holdingDest} onChange={setHoldingDest}
                      newName={newHoldingName} setNewName={setNewHoldingName}
                      newType={newHoldingType} setNewType={setNewHoldingType}
                    />
                  )}
                </>
              )}
            </Field>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            <Field label="Forma de pagamento">
              <select value={paymentMethod} onChange={e => setPaymentMethod(e.target.value)} onFocus={() => setFocus('pm')} onBlur={() => setFocus(null)} style={inputStyle('pm')}>
                {S.PAYMENT_METHODS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </Field>
            <Field label="Recorrência">
              <div style={{ display: 'flex', gap: 8 }}>
                <button type="button" onClick={() => { fixedTouchedRef.current = true; 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={() => { fixedTouchedRef.current = true; setFixed(true); }} style={pillStyle(fixed)}>
                  <LedgerIcon name="repeat" size={14} color={fixed ? 'var(--fg-strong)' : 'var(--fg-3)'} /> Fixo
                </button>
              </div>
            </Field>
          </div>

          {fixed && (
            <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)' }}>
                Repetir esta despesa por
              </span>
              <input
                type="text" inputMode="numeric" pattern="[0-9]*"
                value={fixedMonthsRaw}
                onChange={e => {
                  // Mantém apenas dígitos (já que agora é texto livre, não input nativo numérico)
                  const v = e.target.value.replace(/[^0-9]/g, '');
                  // Permite o campo ficar vazio enquanto o usuário apaga para digitar de novo
                  if (v === '') { setFixedMonths(''); return; }
                  const n = parseInt(v, 10);
                  if (!isNaN(n)) setFixedMonths(Math.min(120, n));
                }}
                onBlur={() => {
                  // Só normaliza para o mínimo de 1 quando o campo perde o foco
                  setFixedMonths(prev => {
                    const n = parseInt(prev, 10);
                    return (!prev || isNaN(n) || n < 1) ? 1 : Math.min(120, n);
                  });
                }}
                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%' }}>
                Os meses futuros entram como previsões. Você confirma cada um quando pagar, e pode ajustar o valor individualmente (ex: juros num mês).
              </span>
            </div>
          )}
        </>
      )}

      <div style={{ borderTop: '1px solid var(--border)', paddingTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontFamily: 'var(--font-body)', fontStyle: 'italic', fontSize: 11, color: 'var(--fg-3)' }}>
          Tudo fica salvo no seu vault local.
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <LedgerButton variant="secondary" onClick={() => onNavigate('transactions')}>Cancelar</LedgerButton>
          <LedgerButton variant="primary" icon={success ? 'check' : 'check'} type="submit">
            {success ? 'Salvo' : 'Salvar entrada'}
          </LedgerButton>
        </div>
      </div>
    </form>
  );
}

// ── BULK-ENTRY TABLE ─────────────────────────────────────────
function newBulkRow() {
  return {
    rid: Math.random().toString(36).slice(2, 9),
    type: 'expense',
    date: new Date().toISOString().slice(0, 10),
    amount: '',
    counterparty: '',
    categoryId: 'basic',
    subcategoryId: 'food-supermarket',
    source: 'Salary',
    paymentMethod: 'debit',
    fixed: false,
    fixedMonths: 12,
    goalId: '',
    holdingDest: 'general',  // 'general' | holdingId
  };
}

function BulkEntryTable({ state, setState, onNavigate }) {
  const S = window.LedgerStore;
  const { isMobile, isNarrow, width } = window.useViewport();
  // The desktop grid needs ~880px of inner width; below that (accounting for the
  // 256px sidebar + padding) it overflows the card, so fall back to stacked cards.
  const stack = width <= 1340;
  const [rows, setRows] = React.useState(() => [
    newBulkRow(), newBulkRow(), newBulkRow(),
  ]);
  const [error, setError] = React.useState('');
  const [savedCount, setSavedCount] = React.useState(0);
  const [savedBreakdown, setSavedBreakdown] = React.useState(null); // { tx, fc }

  function updateRow(rid, patch) {
    setRows(rs => rs.map(r => {
      if (r.rid !== rid) return r;
      const next = { ...r, ...patch };
      // Auto-adjust subcategory if category changed
      if (patch.categoryId && patch.categoryId !== r.categoryId) {
        const cat = S.catLookup(patch.categoryId);
        if (cat && !cat.subs.find(s => s.id === next.subcategoryId)) next.subcategoryId = cat.subs[0].id;
      }
      return next;
    }));
  }
  function addRow() { setRows(rs => [...rs, newBulkRow()]); }
  function duplicateRow(rid) {
    setRows(rs => {
      const idx = rs.findIndex(r => r.rid === rid);
      if (idx < 0) return rs;
      const original = rs[idx];
      const copy = {
        ...original,
        rid: Math.random().toString(36).slice(2, 9) + '-' + Date.now().toString(36),
        // Reforça explicitamente os campos que precisam vir idênticos ao original
        date: original.date,
        counterparty: original.counterparty,
      };
      return [...rs.slice(0, idx + 1), copy, ...rs.slice(idx + 1)];
    });
  }
  function removeRow(rid) { setRows(rs => rs.length === 1 ? rs : rs.filter(r => r.rid !== rid)); }

  function totals() {
    let inSum = 0, outSum = 0, valid = 0;
    rows.forEach(r => {
      const n = parseFloat((r.amount || '').replace(',', '.'));
      if (!isNaN(n) && n > 0) {
        valid++;
        if (r.type === 'income') inSum += n;
        else outSum += n;
      }
    });
    return { inSum, outSum, valid };
  }

  function commitAll() {
    setError('');
    const valid = [];
    const futureForecasts = [];
    const errors = [];
    const goalAdditions = {}; // goalId -> [{amount, holdingSpec}] (apenas para linhas de hoje/passado)

    const today = new Date();
    const endOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);

    rows.forEach((r, i) => {
      const n = parseFloat((r.amount || '').replace(',', '.'));
      if (!r.amount && !r.counterparty) return; // skip empty rows silently
      if (!n || isNaN(n) || n <= 0) { errors.push(`Linha ${i + 1}: valor inválido`); return; }
      const isTransferRow = r.type === 'transfer';
      if (isTransferRow && !r.goalId) { errors.push(`Linha ${i + 1}: escolha uma meta para o aporte`); return; }
      // If "Other" subcategory is chosen, require a description
      const needsDesc = (r.type === 'expense' && typeof r.subcategoryId === 'string' && r.subcategoryId.endsWith('-other')) ||
                        (r.type === 'income' && r.source === 'Other');
      if (needsDesc && !r.counterparty.trim()) { errors.push(`Linha ${i + 1}: descreva o item (você escolheu "Outros")`); return; }

      const goalRef = ((r.type === 'expense' && r.categoryId === 'investments' && r.subcategoryId === 'inv-goals' && r.goalId) || (isTransferRow && r.goalId))
        ? (state.goals || []).find(g => String(g.id) === String(r.goalId))
        : null;
      // Resolve which investment (holding) receives the aporte
      let holdingSpec = null, holdingLabel = '';
      if (goalRef && r.holdingDest && r.holdingDest !== 'general') {
        const h = (goalRef.holdings || []).find(x => String(x.id) === String(r.holdingDest));
        if (h) { holdingSpec = { id: h.id }; holdingLabel = h.name; }
      }
      // Quando não há descrição, usa o nome da subcategoria/categoria (despesa)
      // ou a fonte (entrada) como fallback. Aportes mantêm "Aporte: ...".
      const fallbackName = r.type === 'income'
        ? r.source
        : (S.subLookup(r.categoryId, r.subcategoryId, state)?.name || S.catLookup(r.categoryId)?.name || 'Lançamento');
      const note = r.counterparty || (goalRef ? `Aporte: ${goalRef.name}${holdingLabel ? ' · ' + holdingLabel : ''}` : fallbackName);

      const effectiveCategoryId    = isTransferRow ? 'investments' : (r.type === 'income' ? null : r.categoryId);
      const effectiveSubcategoryId = isTransferRow ? 'inv-goals'   : (r.type === 'income' ? null : r.subcategoryId);
      const effectiveType          = isTransferRow ? 'expense'     : r.type;

      const rowDate = new Date(r.date + 'T12:00:00');
      const isFutureRow = rowDate > endOfToday;

      if (isFutureRow) {
        // Linha com data futura → vira previsão pendente (não mexe na meta agora)
        const baseForecast = {
          status: 'pending',
          realizedTxId: null,
          kind: isTransferRow ? 'transfer' : (r.type === 'income' ? 'income' : 'expense'),
          name: note || 'Lançamento',
          amount: Math.abs(n),
          categoryId: effectiveCategoryId,
          subcategoryId: effectiveSubcategoryId,
          source: r.type === 'income' ? r.source : null,
          paymentMethod: r.type === 'income' ? null : (isTransferRow ? 'pix' : r.paymentMethod),
          recurrence: 'once',
          fixed: r.type === 'expense' ? r.fixed : false,
          note: '',
          goalId: goalRef ? goalRef.id : null,
          holdingId: holdingSpec && holdingSpec.id ? holdingSpec.id : null,
        };

        // Despesa fixa começando no futuro: gera uma previsão por mês, pelos
        // `fixedMonths` meses definidos — não só a do mês inicial.
        if (r.type === 'expense' && r.fixed && !isTransferRow) {
          const months = Math.max(1, Math.min(120, r.fixedMonths || 12));
          for (let m = 0; m < months; m++) {
            const d = new Date(rowDate);
            d.setMonth(d.getMonth() + m);
            futureForecasts.push({
              ...baseForecast,
              id: 'f' + Date.now() + '-' + i + '-' + m,
              dueDate: d.toISOString(),
            });
          }
        } else {
          // Data futura simples (não fixa) → uma única previsão
          futureForecasts.push({
            ...baseForecast,
            id: 'f' + Date.now() + '-' + i,
            dueDate: rowDate.toISOString(),
          });
        }
        return; // não adiciona como transação nem soma na meta agora
      }

      valid.push({
        id: Date.now() + i,
        date: rowDate.toISOString(),
        amount: r.type === 'income' ? Math.abs(n) : -Math.abs(n),
        type: effectiveType,
        categoryId:    effectiveCategoryId,
        subcategoryId: effectiveSubcategoryId,
        source:        r.type === 'income' ? r.source : null,
        paymentMethod: r.type === 'income' ? null : (isTransferRow ? 'pix' : r.paymentMethod),
        note,
        fixed: r.type === 'expense' ? r.fixed : false,
        goalId: goalRef ? goalRef.id : null,
        holdingId: (holdingSpec && holdingSpec.id) ? holdingSpec.id : null,
        transfer: isTransferRow || undefined,
      });
      if (goalRef) {
        const key = goalRef.id;
        if (!goalAdditions[key]) goalAdditions[key] = [];
        goalAdditions[key].push({ amount: Math.abs(n), holdingSpec });
      }
      // Despesa fixa em lote: cria previsões para os meses seguintes
      if (r.type === 'expense' && r.fixed && !isTransferRow) {
        const months = Math.max(1, Math.min(120, r.fixedMonths || 12));
        for (let m = 1; m < months; m++) {
          const d = new Date(rowDate);
          d.setMonth(d.getMonth() + m);
          futureForecasts.push({
            id: 'f' + Date.now() + '-' + i + '-' + m,
            status: 'pending',
            realizedTxId: null,
            kind: 'expense',
            name: note || 'Despesa fixa',
            amount: Math.abs(n),
            dueDate: d.toISOString(),
            categoryId: effectiveCategoryId,
            subcategoryId: effectiveSubcategoryId,
            source: null,
            paymentMethod: r.paymentMethod,
            recurrence: 'once',
            fixed: true,
            note: '',
            goalId: null,
            holdingId: null,
          });
        }
      }
    });
    if (errors.length) { setError(errors.join(' · ')); return; }
    if (valid.length === 0 && futureForecasts.length === 0) { setError('Preencha pelo menos uma linha.'); return; }

    let nextGoals = state.goals;
    Object.keys(goalAdditions).forEach(gid => {
      goalAdditions[gid].forEach(({ amount, holdingSpec }) => {
        nextGoals = S.applyGoalAporte(nextGoals, gid, amount, holdingSpec);
      });
    });

    setState({
      ...state,
      transactions: [...valid, ...state.transactions],
      goals: nextGoals,
      forecasts: [...(state.forecasts || []), ...futureForecasts],
    });
    setSavedCount(valid.length + futureForecasts.length);
    setSavedBreakdown({ tx: valid.length, fc: futureForecasts.length });
    // Se só criou previsões futuras, leva para a tela de previsões
    const dest = valid.length === 0 && futureForecasts.length > 0 ? 'forecasts' : 'transactions';
    setTimeout(() => onNavigate(dest), futureForecasts.length > 0 ? 1400 : 800);
  }

  const { inSum, outSum, valid } = totals();
  const net = inSum - outSum;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {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={{
        background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-5)',
        overflow: 'visible',
      }}>
        {/* Header */}
        {!stack && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: '110px 120px 1fr 150px 180px 130px 120px 56px',
          padding: '14px 18px', gap: 8, background: 'var(--bg-muted)',
          fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
          color: 'var(--fg-3)', textTransform: 'uppercase',
          borderBottom: '1px solid var(--border)',
        }}>
          <div>Tipo</div>
          <div>Data</div>
          <div>Descrição</div>
          <div>Categoria</div>
          <div>Subcategoria / Fonte</div>
          <div>Pagamento</div>
          <div style={{ textAlign: 'right' }}>Valor (R$)</div>
          <div />
        </div>
        )}

        {/* Rows */}
        {rows.map((r, idx) => stack
          ? <BulkRowMobile key={r.rid} row={r} idx={idx} goals={state.goals || []} categories={S.getCategoriesWithCustom(state)} onChange={(p) => updateRow(r.rid, p)} onRemove={() => removeRow(r.rid)} onDuplicate={() => duplicateRow(r.rid)} />
          : <BulkRow       key={r.rid} row={r} idx={idx} goals={state.goals || []} categories={S.getCategoriesWithCustom(state)} onChange={(p) => updateRow(r.rid, p)} onRemove={() => removeRow(r.rid)} onDuplicate={() => duplicateRow(r.rid)} />)}

        {/* Add row */}
        <div style={{ padding: '12px 18px', borderTop: '1px dashed var(--border)' }}>
          <button onClick={addRow} type="button" style={{
            all: 'unset', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '8px 14px', borderRadius: 'var(--r-3)',
            background: 'var(--bg-inset)', color: 'var(--fg-strong)',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13,
            transition: 'all var(--dur-fast)',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-muted)'}
          onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-inset)'}>
            <LedgerIcon name="plus" size={14} color="currentColor" />
            Adicionar linha
          </button>
        </div>
      </div>

      {/* Footer / commit bar */}
      <div style={{
        background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-4)',
        padding: '18px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap' }}>
          <SummaryStat label="Linhas válidas" value={`${valid}/${rows.length}`} />
          <SummaryStat label="Entradas"        value={S.fmtMoney(inSum)}     color="var(--fg-positive)" />
          <SummaryStat label="Saídas"          value={S.fmtMoney(outSum)}    color="var(--brand-magenta)" />
          <SummaryStat label="Líquido"         value={S.fmtMoney(net, { signed: true })} color={net >= 0 ? 'var(--fg-positive)' : 'var(--brand-magenta)'} />
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <LedgerButton variant="secondary" onClick={() => onNavigate('transactions')}>Cancelar</LedgerButton>
          <LedgerButton variant="primary" icon={savedCount ? 'check' : 'check-check'} onClick={commitAll}>
            {savedCount ? `${savedCount} salvas` : `Salvar ${valid} ${valid === 1 ? 'entrada' : 'entradas'}`}
          </LedgerButton>
        </div>
      </div>

      {savedBreakdown && (savedBreakdown.fc > 0) && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '12px 18px',
          borderRadius: 'var(--r-4)', background: 'var(--info-100)', border: '1px solid var(--info-500)',
        }}>
          <LedgerIcon name="calendar-clock" size={16} color="var(--info-500)" />
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-strong)' }}>
            {savedBreakdown.tx > 0
              ? `${savedBreakdown.tx} ${savedBreakdown.tx === 1 ? 'lançamento criado' : 'lançamentos criados'} e ${savedBreakdown.fc} ${savedBreakdown.fc === 1 ? 'previsão futura criada' : 'previsões futuras criadas'} (meses seguintes das despesas fixas).`
              : `${savedBreakdown.fc} ${savedBreakdown.fc === 1 ? 'previsão criada' : 'previsões criadas'} — nenhum lançamento imediato, pois ${savedBreakdown.fc === 1 ? 'a data é futura' : 'as datas são futuras'}.`}
            {' '}Veja em <strong>Previsões</strong>.
          </span>
        </div>
      )}

      <div style={{ fontFamily: 'var(--font-body)', fontStyle: 'italic', fontSize: 11, color: 'var(--fg-3)', textAlign: 'center' }}>
        Linhas vazias são ignoradas · use duplicar para repetir uma despesa rapidamente
      </div>
    </div>
  );
}

function BulkRow({ row, idx, goals, categories, onChange, onRemove, onDuplicate }) {
  const S = window.LedgerStore;
  const allCats = categories || S.CATEGORIES;
  const cat = allCats.find(c => c.id === row.categoryId) || S.catLookup(row.categoryId);
  const isTransfer = row.type === 'transfer';
  const showGoal = (row.type === 'expense' && row.categoryId === 'investments' && row.subcategoryId === 'inv-goals') || isTransfer;
  const needsDesc = (row.type === 'expense' && typeof row.subcategoryId === 'string' && row.subcategoryId.endsWith('-other')) ||
                    (row.type === 'income' && row.source === 'Other');
  const descMissing = needsDesc && !(row.counterparty || '').trim();

  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 10px center',
    paddingRight: 26,
  };

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

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

      <input
        value={row.counterparty}
        onChange={e => onChange({ counterparty: e.target.value })}
        placeholder={needsDesc
          ? 'Descreva o item (obrigatório — você escolheu "Outros")'
          : (row.type === 'income' ? 'ex: Salário Junho' : 'ex: Mercado Pão de Açúcar')}
        style={{
          ...cellInput,
          background: descMissing ? 'var(--brand-magenta-100)' : cellInput.background,
          border: descMissing ? '1px solid var(--brand-magenta)' : cellInput.border,
          color: descMissing ? 'var(--brand-magenta-700)' : cellInput.color,
        }}
      />

      {row.type === 'income' ? (
        <div style={{ ...cellInput, color: 'var(--fg-3)', cursor: 'default', display: 'flex', alignItems: 'center' }}>—</div>
      ) : isTransfer ? (
        <div style={{ ...cellInput, display: 'flex', alignItems: 'center', gap: 6, color: 'var(--positive-700)', fontWeight: 700, background: 'var(--positive-50)' }}>
          <LedgerIcon name="arrow-right-left" size={13} color="currentColor" />
          Investments
        </div>
      ) : (
        <select value={row.categoryId} onChange={e => onChange({ categoryId: e.target.value })} style={cellSelect}>
          {allCats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
      )}

      {row.type === 'income' ? (
        <select value={row.source} onChange={e => onChange({ source: e.target.value })} style={cellSelect}>
          {S.INCOME_SOURCES.map(src => <option key={src} value={src}>{src}</option>)}
        </select>
      ) : isTransfer ? (
        <div style={{ ...cellInput, color: 'var(--fg-3)', cursor: 'default', display: 'flex', alignItems: 'center' }}>
          Goals · escolha a meta ↓
        </div>
      ) : (
        <select value={row.subcategoryId} onChange={e => onChange({ subcategoryId: e.target.value })} style={cellSelect}>
          {cat && cat.subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
      )}

      {/* Forma de pagamento */}
      {row.type === 'expense' ? (
        <select value={row.paymentMethod || 'debit'} onChange={e => onChange({ paymentMethod: e.target.value })} style={cellSelect}>
          {S.PAYMENT_METHODS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
        </select>
      ) : (
        <div style={{ ...cellInput, color: 'var(--fg-3)', cursor: 'default', display: 'flex', alignItems: 'center' }}>—</div>
      )}

      <input
        value={row.amount}
        onChange={e => onChange({ amount: e.target.value })}
        placeholder="0,00"
        inputMode="decimal"
        style={{
          ...cellInput,
          textAlign: 'right',
          fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14,
          color: row.type === 'income' ? 'var(--fg-positive)' : 'var(--fg-strong)',
        }}
      />

      <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>
    {/* Fixo/Variável toggle — só para despesas */}
    {row.type === 'expense' && (
      <div style={{ padding: '4px 18px 8px', display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.5px', textTransform: 'uppercase' }}>Tipo:</span>
        <button type="button" onClick={() => onChange({ fixed: false })} style={{
          all: 'unset', cursor: 'pointer', padding: '3px 10px', borderRadius: 'var(--r-2)',
          fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700,
          background: !row.fixed ? 'var(--bg-muted)' : 'transparent',
          color: !row.fixed ? 'var(--fg-strong)' : 'var(--fg-3)',
          border: !row.fixed ? '1px solid var(--border)' : '1px solid transparent',
        }}>Variável</button>
        <button type="button" onClick={() => onChange({ fixed: true })} style={{
          all: 'unset', cursor: 'pointer', padding: '3px 10px', borderRadius: 'var(--r-2)',
          fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700,
          background: row.fixed ? 'var(--bg-muted)' : 'transparent',
          color: row.fixed ? 'var(--fg-strong)' : 'var(--fg-3)',
          border: row.fixed ? '1px solid var(--border)' : '1px solid transparent',
        }}>Fixo</button>
        {row.fixed && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 4 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>por</span>
            <input
              type="text" inputMode="numeric" pattern="[0-9]*"
              value={row.fixedMonths != null ? row.fixedMonths : 12}
              onChange={e => {
                const v = e.target.value.replace(/[^0-9]/g, '');
                if (v === '') { onChange({ fixedMonths: '' }); return; }
                const n2 = parseInt(v, 10);
                if (!isNaN(n2)) onChange({ fixedMonths: Math.min(120, n2) });
              }}
              onBlur={e => {
                const n2 = parseInt(e.target.value, 10);
                onChange({ fixedMonths: (!e.target.value || isNaN(n2) || n2 < 1) ? 1 : Math.min(120, n2) });
              }}
              style={{
                width: 52, fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, textAlign: 'center',
                padding: '4px 6px', borderRadius: 'var(--r-2)',
                border: '1px solid var(--border)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
              }} />
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>meses</span>
          </span>
        )}
      </div>
    )}
    {showGoal && (
      <div style={{
        padding: '0 18px 12px',
        display: 'flex', alignItems: 'center', gap: 10,
        background: 'var(--bg-muted)',
        marginTop: -2,
      }}>
        <LedgerIcon name={isTransfer ? 'arrow-right-left' : 'target'} size={14} color="var(--positive-700)" />
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, letterSpacing: '0.5px', color: 'var(--positive-700)', textTransform: 'uppercase' }}>
          {isTransfer ? 'Aporte para' : 'Aporte para meta'}
        </span>
        <select
          value={row.goalId || ''}
          onChange={e => onChange({ goalId: e.target.value })}
          style={{
            ...cellSelect,
            flex: 1, maxWidth: 360,
            border: '1px solid var(--positive-500)',
            background: 'var(--bg-elevated)',
            color: 'var(--fg-strong)',
            fontWeight: 600,
          }}
        >
          <option value="">{isTransfer ? 'Escolha uma meta' : 'Sem meta específica'}</option>
          {goals.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
        </select>
        {(() => {
          const selGoal = goals.find(g => String(g.id) === String(row.goalId));
          const hs = selGoal ? (selGoal.holdings || []) : [];
          if (!selGoal || hs.length === 0) return null;
          return (
            <>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, letterSpacing: '0.5px', color: 'var(--fg-3)', textTransform: 'uppercase' }}>em</span>
              <select
                value={row.holdingDest || 'general'}
                onChange={e => onChange({ holdingDest: e.target.value })}
                style={{ ...cellSelect, flex: 1, maxWidth: 240, border: '1px solid var(--positive-500)', background: 'var(--bg-elevated)', color: 'var(--fg-strong)', fontWeight: 600 }}
              >
                <option value="general">Geral (sem investimento específico)</option>
                {hs.map(h => <option key={h.id} value={h.id}>{h.name}</option>)}
              </select>
            </>
          );
        })()}
        {goals.length === 0 && (
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>
            (crie metas para fazer aportes)
          </span>
        )}
      </div>
    )}
    </div>
  );
}

function BulkRowMobile({ row, idx, goals, categories, onChange, onRemove, onDuplicate }) {
  const S = window.LedgerStore;
  const allCats = categories || S.CATEGORIES;
  const cat = allCats.find(c => c.id === row.categoryId) || S.catLookup(row.categoryId);
  const isIncome = row.type === 'income';
  const isTransfer = row.type === 'transfer';
  const showGoal = (row.type === 'expense' && row.categoryId === 'investments' && row.subcategoryId === 'inv-goals') || isTransfer;
  const needsDesc = (row.type === 'expense' && typeof row.subcategoryId === 'string' && row.subcategoryId.endsWith('-other')) ||
                    (isIncome && row.source === 'Other');
  const descMissing = needsDesc && !(row.counterparty || '').trim();

  const cellInput = {
    all: 'unset', boxSizing: 'border-box',
    width: '100%', padding: '10px 12px',
    fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--fg)',
    border: '1px solid var(--border)', borderRadius: 'var(--r-2)',
    background: 'var(--bg)', cursor: 'text',
    transition: 'all var(--dur-fast)',
  };
  const cellSelect = { ...cellInput, cursor: 'pointer', appearance: 'none' };

  return (
    <div style={{
      padding: '14px 16px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', gap: 10,
      background: idx % 2 === 0 ? 'transparent' : 'var(--bg)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, letterSpacing: '1px', color: 'var(--fg-3)', textTransform: 'uppercase' }}>
          Linha {idx + 1}
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          <button type="button" onClick={onDuplicate} title="Duplicar" style={mobileBulkBtn()}>
            <LedgerIcon name="copy" size={15} color="currentColor" />
          </button>
          <button type="button" onClick={onRemove} title="Remover" style={mobileBulkBtn('magenta')}>
            <LedgerIcon name="trash-2" size={15} color="currentColor" />
          </button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <select value={row.type} onChange={e => onChange({ type: e.target.value })} style={{
          ...cellSelect,
          color: isIncome ? 'var(--fg-positive)' : 'var(--brand-magenta)',
          fontWeight: 700,
        }}>
          <option value="expense">Saída</option>
          <option value="income">Entrada</option>
          <option value="transfer">Aporte</option>
        </select>
        <input type="date" value={row.date} onChange={e => onChange({ date: e.target.value })} style={cellInput} />
      </div>

      <input
        value={row.counterparty}
        onChange={e => onChange({ counterparty: e.target.value })}
        placeholder={needsDesc
          ? 'Descreva (obrigatório — "Outros")'
          : (isIncome ? 'ex: Salário Junho' : 'ex: Mercado Pão de Açúcar')}
        style={{
          ...cellInput,
          background: descMissing ? 'var(--brand-magenta-100)' : cellInput.background,
          border: descMissing ? '1px solid var(--brand-magenta)' : cellInput.border,
          color: descMissing ? 'var(--brand-magenta-700)' : cellInput.color,
        }}
      />

      {!isIncome && !isTransfer && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <select value={row.categoryId} onChange={e => onChange({ categoryId: e.target.value })} style={cellSelect}>
            {allCats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <select value={row.subcategoryId} onChange={e => onChange({ subcategoryId: e.target.value })} style={cellSelect}>
            {cat && cat.subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </div>
      )}
      {isIncome && (
        <select value={row.source} onChange={e => onChange({ source: e.target.value })} style={cellSelect}>
          {S.INCOME_SOURCES.map(src => <option key={src} value={src}>{src}</option>)}
        </select>
      )}

      {showGoal && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 12px', borderRadius: 'var(--r-2)',
          background: 'var(--positive-50)', border: '1px solid rgba(0,150,104,0.25)',
        }}>
          <LedgerIcon name={isTransfer ? 'arrow-right-left' : 'target'} size={14} color="var(--positive-700)" />
          <select
            value={row.goalId || ''}
            onChange={e => onChange({ goalId: e.target.value })}
            style={{
              ...cellSelect,
              flex: 1, border: 'none', background: 'transparent',
              color: 'var(--positive-700)', fontWeight: 700,
            }}
          >
            <option value="">{isTransfer ? 'Escolha a meta de destino' : 'Aporte sem meta específica'}</option>
            {goals.map(g => <option key={g.id} value={g.id}>{isTransfer ? '→ ' : 'Meta: '}{g.name}</option>)}
          </select>
        </div>
      )}

      {showGoal && (() => {
        const selGoal = goals.find(g => String(g.id) === String(row.goalId));
        const hs = selGoal ? (selGoal.holdings || []) : [];
        if (!selGoal || hs.length === 0) return null;
        return (
          <select
            value={row.holdingDest || 'general'}
            onChange={e => onChange({ holdingDest: e.target.value })}
            style={{ ...cellSelect, border: '1px solid var(--positive-500)' }}
          >
            <option value="general">Geral (sem investimento específico)</option>
            {hs.map(h => <option key={h.id} value={h.id}>Em: {h.name}</option>)}
          </select>
        );
      })()}

      {row.type === 'expense' && !showGoal && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Tipo:</span>
          <button type="button" onClick={() => onChange({ fixed: false })} style={{
            all: 'unset', cursor: 'pointer', padding: '4px 12px', borderRadius: 'var(--r-2)',
            fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700,
            background: !row.fixed ? 'var(--bg-muted)' : 'transparent',
            color: !row.fixed ? 'var(--fg-strong)' : 'var(--fg-3)',
            border: !row.fixed ? '1px solid var(--border)' : '1px solid transparent',
          }}>Variável</button>
          <button type="button" onClick={() => onChange({ fixed: true })} style={{
            all: 'unset', cursor: 'pointer', padding: '4px 12px', borderRadius: 'var(--r-2)',
            fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700,
            background: row.fixed ? 'var(--bg-muted)' : 'transparent',
            color: row.fixed ? 'var(--fg-strong)' : 'var(--fg-3)',
            border: row.fixed ? '1px solid var(--border)' : '1px solid transparent',
          }}>Fixo</button>
          {row.fixed && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>por</span>
              <input
                type="text" inputMode="numeric" pattern="[0-9]*"
                value={row.fixedMonths != null ? row.fixedMonths : 12}
                onChange={e => {
                  const v = e.target.value.replace(/[^0-9]/g, '');
                  if (v === '') { onChange({ fixedMonths: '' }); return; }
                  const n2 = parseInt(v, 10);
                  if (!isNaN(n2)) onChange({ fixedMonths: Math.min(120, n2) });
                }}
                onBlur={e => {
                  const n2 = parseInt(e.target.value, 10);
                  onChange({ fixedMonths: (!e.target.value || isNaN(n2) || n2 < 1) ? 1 : Math.min(120, n2) });
                }}
                style={{
                  width: 54, fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700, textAlign: 'center',
                  padding: '5px 6px', borderRadius: 'var(--r-2)',
                  border: '1px solid var(--border)', background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
                }} />
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>meses</span>
            </span>
          )}
        </div>
      )}

      <div style={{
        display: 'flex', alignItems: 'stretch',
        border: '1px solid var(--border)', borderRadius: 'var(--r-2)', background: 'var(--bg)',
      }}>
        <span style={{
          display: 'flex', alignItems: 'center', padding: '0 12px',
          fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13,
          color: isIncome ? 'var(--fg-positive)' : 'var(--brand-magenta)',
          borderRight: '1px solid var(--border)',
        }}>{isIncome ? '+' : '−'} R$</span>
        <input
          value={row.amount}
          onChange={e => onChange({ amount: e.target.value })}
          placeholder="0,00"
          inputMode="decimal"
          style={{
            flex: 1, border: 0, padding: '10px 12px', outline: 'none', background: 'transparent',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
            color: 'var(--fg-strong)', minWidth: 0, textAlign: 'right',
          }}
        />
      </div>
    </div>
  );
}

function mobileBulkBtn(tone) {
  return {
    all: 'unset', cursor: 'pointer',
    width: 36, height: 36, borderRadius: 'var(--r-2)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: tone === 'magenta' ? 'var(--brand-magenta-100)' : 'var(--bg-inset)',
    color: tone === 'magenta' ? 'var(--brand-magenta-700)' : 'var(--fg-2)',
  };
}

function SummaryStat({ label, value, color }) {  return (
    <div>
      <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>{label}</div>
      <div className="num" style={{ fontSize: 16, lineHeight: '22px', color: color || 'var(--fg-strong)' }}>{value}</div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)', letterSpacing: '0.2px' }}>{label}</span>
      {children}
      {hint && <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>{hint}</span>}
    </label>
  );
}

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)',
  };
}

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

window.LedgerEntryScreen = LedgerEntryScreen;

// Holding destination picker for an aporte to a goal (single-entry form).
function HoldingPicker({ goal, value, onChange, newName, setNewName, newType, setNewType }) {
  const S = window.LedgerStore;
  const holdings = goal.holdings || [];
  const opt = (v, label, sub, icon) => {
    const on = value === v;
    return (
      <button key={v} type="button" onClick={() => onChange(v)} style={{
        all: 'unset', cursor: 'pointer', boxSizing: 'border-box', width: '100%',
        display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
        borderRadius: 'var(--r-3)',
        background: on ? 'var(--positive-50)' : 'var(--bg-muted)',
        border: on ? '1px solid var(--positive-500)' : '1px solid transparent',
      }}>
        <div style={{
          width: 30, height: 30, borderRadius: 'var(--r-2)', flexShrink: 0,
          background: on ? 'var(--positive-100)' : 'var(--bg-elevated)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <LedgerIcon name={icon} size={15} color={on ? 'var(--positive-700)' : 'var(--fg-2)'} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
          {sub && <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 1 }}>{sub}</div>}
        </div>
        {on && <LedgerIcon name="check" size={15} color="var(--positive-700)" />}
      </button>
    );
  };
  return (
    <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>
        Onde alocar dentro de “{goal.name}”
      </span>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {holdings.map(h => opt(h.id, h.name, `${h.type} · atual ${S.fmtMoney(h.currentValue || 0)}`, S.INVESTMENT_TYPE_ICON[h.type] || 'circle-dollar-sign'))}
        {opt('__new__', 'Novo investimento', 'Criar um instrumento nesta meta', 'plus')}
        {opt('general', 'Geral (sem investimento específico)', 'Soma ao total da meta', 'wallet')}
      </div>
      {value === '__new__' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 160px', gap: 8, marginTop: 2 }}>
          <input
            value={newName}
            onChange={e => setNewName(e.target.value)}
            placeholder="Nome do investimento"
            style={{
              fontFamily: 'var(--font-body)', fontSize: 14, padding: '10px 12px', boxSizing: 'border-box',
              border: '1px solid var(--positive-500)', borderRadius: 'var(--r-3)',
              background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
            }}
          />
          <select
            value={newType}
            onChange={e => setNewType(e.target.value)}
            style={{
              fontFamily: 'var(--font-body)', fontSize: 14, padding: '10px 12px', boxSizing: 'border-box',
              border: '1px solid var(--border)', borderRadius: 'var(--r-3)',
              background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
            }}
          >
            {S.INVESTMENT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
          </select>
        </div>
      )}
    </div>
  );
}
window.HoldingPicker = HoldingPicker;
