// ─────────────────────────────────────────────────────────────
// goals-screen.jsx — Investment Goals portal (list → detail with holdings)
// ─────────────────────────────────────────────────────────────
const { LedgerIcon, LedgerButton, LedgerPageHeader, LedgerKpi, LedgerChip, LedgerStackedCategoryChart, LedgerTreemap } = window;

function LedgerGoalsScreen({ state, setState }) {
  const S = window.LedgerStore;
  const { isMobile } = window.useViewport();
  const [creating, setCreating]   = React.useState(false);
  const [selectedId, setSelectedId] = React.useState(null);
  const [aporteGoalId, setAporteGoalId] = React.useState(null);
  const [chartYear, setChartYear] = React.useState(String(new Date().getFullYear()));

  const selectedGoal = selectedId != null ? state.goals.find(g => g.id === selectedId) : null;

  // ── shared mutations ───────────────────────────────────────
  function commitAporte(goalId, amount, holding, label) {
    const goal = state.goals.find(g => g.id === goalId);
    const nextGoals = S.applyGoalAporte(state.goals, goalId, amount, holding);
    const tx = {
      id: Date.now(),
      date: new Date().toISOString(),
      amount: -Math.abs(amount),
      type: 'expense',
      categoryId: 'investments',
      subcategoryId: 'inv-goals',
      source: null,
      paymentMethod: 'pix',
      note: `Aporte: ${goal ? goal.name : 'Meta'}${label && label !== 'Geral' ? ' · ' + label : ''}`,
      fixed: false,
      goalId,
      transfer: true,
    };
    setState({ ...state, goals: nextGoals, transactions: [tx, ...state.transactions] });
  }

  function addHolding(goalId, holding) {
    // Declaring an existing investment: raise saved by its current value so the
    // breakdown stays consistent with the goal total.
    const nextGoals = state.goals.map(g => g.id === goalId
      ? { ...g, holdings: [...(g.holdings || []), holding], saved: (g.saved || 0) + (holding.currentValue || 0) }
      : g);
    setState({ ...state, goals: nextGoals });
  }
  function setHoldingValue(goalId, holdingId, value) {
    setState({ ...state, goals: S.updateHoldingValue(state.goals, goalId, holdingId, value) });
  }
  function editHolding(goalId, holdingId, patch) {
    const nextGoals = state.goals.map(g => g.id === goalId
      ? { ...g, holdings: (g.holdings || []).map(h => h.id === holdingId ? { ...h, ...patch } : h) }
      : g);
    setState({ ...state, goals: nextGoals });
  }
  function deleteHolding(goalId, holdingId) {
    setState({ ...state, goals: S.removeHolding(state.goals, goalId, holdingId) });
  }
  function deleteGoal(goalId) {
    setState({ ...state, goals: state.goals.filter(g => g.id !== goalId) });
    setSelectedId(null);
  }
  function editGoal(goalId, patch) {
    const nextGoals = state.goals.map(g => g.id === goalId ? { ...g, ...patch } : g);
    setState({ ...state, goals: nextGoals });
  }
  function redeemHolding(goalId, holdingId, holdingName, receivedAmount, note, partial, remainingCurrentValue, remainingInvested) {
    let nextGoals;
    // Usa remainingCurrentValue > 0 como critério de parcial (mais robusto que o boolean)
    const isPartial = partial === true || remainingCurrentValue > 0;
    if (isPartial) {
      // Resgate parcial: reduz currentValue e invested do holding, ajusta goal.saved
      nextGoals = state.goals.map(g => {
        if (String(g.id) !== String(goalId)) return g;
        const holdings = (g.holdings || []).map(h => {
          if (String(h.id) !== String(holdingId)) return h;
          return { ...h, currentValue: remainingCurrentValue, invested: remainingInvested };
        });
        const delta = -(receivedAmount); // goal.saved reduz pelo que foi resgatado
        return { ...g, holdings, saved: Math.max(0, (g.saved || 0) + delta) };
      });
    } else {
      // Resgate total: remove o holding (removeHolding já ajusta goal.saved)
      nextGoals = S.removeHolding(state.goals, goalId, holdingId);
    }
    // Cria lançamento de entrada
    const tx = {
      id: Date.now(),
      date: new Date().toISOString(),
      amount: Math.abs(receivedAmount),
      type: 'income',
      categoryId: 'investments',
      subcategoryId: 'inv-goals',
      source: 'Vencimento de Investimento',
      paymentMethod: null,
      note: note || holdingName,
      fixed: false,
      goalId,
      redeemed: true,
    };
    setState({ ...state, goals: nextGoals, transactions: [tx, ...(state.transactions || [])] });
  }

  // ── DETAIL VIEW ────────────────────────────────────────────
  if (selectedGoal) {
    return (
      <>
        <GoalDetail
          goal={selectedGoal}
          state={state}
          setState={setState}
          isMobile={isMobile}
          onBack={() => setSelectedId(null)}
          onAporte={() => setAporteGoalId(selectedGoal.id)}
          onAddHolding={(h) => addHolding(selectedGoal.id, h)}
          onSetValue={(hid, v) => setHoldingValue(selectedGoal.id, hid, v)}
          onEditHolding={(hid, patch) => editHolding(selectedGoal.id, hid, patch)}
          onDeleteHolding={(hid) => deleteHolding(selectedGoal.id, hid)}
          onDeleteGoal={() => deleteGoal(selectedGoal.id)}
          onEditGoal={(patch) => editGoal(selectedGoal.id, patch)}
          onRedeemHolding={(hid, hname, amt, note, partial, remCV, remInv) => redeemHolding(selectedGoal.id, hid, hname, amt, note, partial, remCV, remInv)}
        />
        {aporteGoalId != null && (
          <AporteModal
            goal={state.goals.find(g => g.id === aporteGoalId)}
            onClose={() => setAporteGoalId(null)}
            onSubmit={(amt, holding, label) => { commitAporte(aporteGoalId, amt, holding, label); setAporteGoalId(null); }}
          />
        )}
      </>
    );
  }

  // ── LIST VIEW ──────────────────────────────────────────────
  const totalSaved  = state.goals.reduce((s, g) => s + (g.saved || 0), 0);
  const totalTarget = state.goals.reduce((s, g) => s + (g.target || 0), 0);
  const totalYield  = state.goals.reduce((s, g) => s + S.goalYield(g), 0);
  const overallPct  = totalTarget > 0 ? Math.round((totalSaved / totalTarget) * 100) : 0;

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 1280, margin: '0 auto' }} data-screen-label="Investment Goals">
      <LedgerPageHeader
        eyebrow="Visão de Longo Prazo"
        title="Metas de Investimento"
        actions={
          <>
            <LedgerButton variant="secondary" icon="download" onClick={() => window.LedgerReport.downloadGoals(state)}>Relatório</LedgerButton>
            <LedgerButton variant="primary" icon="plus" onClick={() => setCreating(true)}>Nova Meta</LedgerButton>
          </>
        }
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <LedgerKpi label="Total Investido" value={S.fmtMoney(totalSaved)} variant="positive" footer={`Em ${state.goals.length} ${state.goals.length === 1 ? 'meta' : 'metas'}`} />
        <LedgerKpi label="Rendimento Total" value={S.fmtMoney(totalYield, { signed: true })} variant={totalYield >= 0 ? 'positive' : 'negative'} footer="Ganho acumulado dos investimentos" />
        <LedgerKpi label="Meta Total" value={S.fmtMoney(totalTarget)} footer="Ambição combinada" />
        <LedgerKpi label="Progresso Geral" value={overallPct + '%'} variant="inverse" footer={`Restante ${S.fmtMoney(Math.max(0, totalTarget - totalSaved))}`} />
      </div>

      {creating && <NewGoalModal onClose={() => setCreating(false)} onSave={(g) => {
        setState({ ...state, goals: [...state.goals, { ...g, id: Date.now(), holdings: [] }] });
        setCreating(false);
      }} />}

      {aporteGoalId != null && (
        <AporteModal
          goal={state.goals.find(g => g.id === aporteGoalId)}
          onClose={() => setAporteGoalId(null)}
          onSubmit={(amt, holding, label) => { commitAporte(aporteGoalId, amt, holding, label); setAporteGoalId(null); }}
        />
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 16 }}>
        {state.goals.length === 0 && (
          <div style={{
            gridColumn: '1 / -1',
            background: 'var(--bg-elevated)', border: '1px dashed var(--border-strong)', borderRadius: 'var(--r-5)',
            padding: 48, textAlign: 'center', color: 'var(--fg-2)',
          }}>
            <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 6 }}>VAZIO</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)', marginBottom: 8 }}>Nenhuma meta ainda</div>
            <div style={{ fontSize: 13, marginBottom: 16 }}>Defina uma ambição de longo prazo, coloque um valor e comece a acompanhar seu progresso.</div>
            <LedgerButton variant="primary" icon="plus" onClick={() => setCreating(true)}>Criar Primeira Meta</LedgerButton>
          </div>
        )}
        {state.goals.map(g => {
          const pct = Math.min(100, Math.round(((g.saved || 0) / Math.max(1, g.target)) * 100));
          const remaining = Math.max(0, g.target - (g.saved || 0));
          const yld = S.goalYield(g);
          const nHoldings = (g.holdings || []).length;
          return (
            <div key={g.id} onClick={() => setSelectedId(g.id)} style={{
              background: 'var(--bg-elevated)', borderRadius: 'var(--r-4)', padding: 24,
              border: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 18,
              cursor: 'pointer', transition: 'box-shadow var(--dur-fast), transform var(--dur-fast)',
            }}
            onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'center', minWidth: 0 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 'var(--r-4)', background: 'var(--bg-muted)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <LedgerIcon name={g.icon || 'target'} size={20} color="var(--fg-strong)" />
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.name}</div>
                    <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)', marginTop: 2 }}>
                      {nHoldings > 0 ? `${nHoldings} ${nHoldings === 1 ? 'investimento' : 'investimentos'}` : 'Sem investimentos detalhados'}
                    </div>
                  </div>
                </div>
                <LedgerIcon name="chevron-right" size={18} color="var(--fg-3)" />
              </div>
              <div style={{ height: 8, borderRadius: 'var(--r-1)', background: 'var(--bg-inset)', overflow: 'hidden' }}>
                <div style={{ width: pct + '%', height: '100%', background: pct >= 100 ? 'var(--positive-500)' : 'var(--brand-magenta)', transition: 'width var(--dur-slow) var(--ease-out)' }} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
                <div>
                  <div className="meta" style={{ color: 'var(--fg-3)' }}>TOTAL · {pct}%</div>
                  <div className="num" style={{ fontSize: 18, lineHeight: '26px' }}>{S.fmtMoney(g.saved || 0)}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="meta" style={{ color: 'var(--fg-3)' }}>RENDIMENTO</div>
                  <div className="num" style={{ fontSize: 15, lineHeight: '22px', color: yld > 0 ? 'var(--fg-positive)' : yld < 0 ? 'var(--brand-magenta)' : 'var(--fg-2)' }}>
                    {yld === 0 ? '—' : S.fmtMoney(yld, { signed: true })}
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, paddingTop: 4 }} onClick={e => e.stopPropagation()}>
                <LedgerButton variant="dark" size="sm" icon="plus" onClick={() => setAporteGoalId(g.id)}>Aportar</LedgerButton>
                <LedgerButton variant="ghost" size="sm" icon="arrow-right" onClick={() => setSelectedId(g.id)}>Abrir</LedgerButton>
              </div>
            </div>
          );
        })}
      </div>

      {/* GROWTH CHARTS */}
      {state.goals.length > 0 && (
        <GoalsGrowthCharts state={state} year={chartYear} setYear={setChartYear} isMobile={isMobile} />
      )}
    </div>
  );
}

// ── GROWTH CHARTS (list view) ────────────────────────────────
function GoalsGrowthCharts({ state, year, setYear, isMobile }) {
  const S = window.LedgerStore;
  const years = React.useMemo(() => S.goalAporteYears(state), [state]);
  const perMonth = React.useMemo(() => {
    const raw = S.goalsAportesPerMonth(state, year);
    const now = new Date();
    const currentYear = now.getFullYear();
    const lastRealIdx = Number(year) < currentYear ? 11 : (Number(year) > currentYear ? -1 : now.getMonth());
    // Per goal: aportes summed across the visible (real) months of this year.
    const aportesYear = {};
    state.goals.forEach(g => { aportesYear[String(g.id)] = 0; });
    raw.forEach((m, i) => {
      if (i > lastRealIdx) return;
      state.goals.forEach(g => { const id = String(g.id); aportesYear[id] += (m.perGoal[id] || 0); });
    });
    // Baseline so the accumulated curve ENDS at each goal's current saldo (total investido),
    // i.e. balance before this year's aportes = saved − aportes-this-year (incl. yield/initial).
    const running = {};
    state.goals.forEach(g => {
      const id = String(g.id);
      running[id] = Math.max(0, (g.saved || 0) - aportesYear[id]);
    });
    return raw.map((m, i) => {
      const cats = {};
      let total = 0;
      if (i <= lastRealIdx) {
        state.goals.forEach(g => {
          const id = String(g.id);
          running[id] = running[id] + (m.perGoal[id] || 0);
          if (running[id] > 0) cats[id] = running[id];
          total += running[id];
        });
      }
      return { ymk: m.ymk, label: m.label, total, cats };
    });
  }, [state, year]);
  const goalsAsCats = state.goals.map(g => ({ id: String(g.id), name: g.name, chipTone: 'alpha', icon: g.icon || 'target' }));
  const colors = {};
  state.goals.forEach(g => { colors[String(g.id)] = S.goalColor(state.goals, g.id); });
  const typeAlloc = React.useMemo(() => S.investmentTypeAllocation(state), [state]);
  const unallocTotal = React.useMemo(() => state.goals.reduce((s, g) => s + S.goalUnallocated(g), 0), [state]);
  const treemapItems = React.useMemo(() => {
    const items = typeAlloc.map(t => ({ type: t.type, value: t.value, color: t.color }));
    if (unallocTotal > 0) items.push({ type: 'Não alocado', value: unallocTotal, color: 'var(--slate-400)' });
    return items;
  }, [typeAlloc, unallocTotal]);
  const yearTotal = perMonth.reduce((mx, m) => Math.max(mx, m.total), 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>EVOLUÇÃO</div>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, lineHeight: '32px', color: 'var(--fg-strong)' }}>Crescimento dos Aportes</h2>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="meta" style={{ color: 'var(--fg-3)' }}>ACUMULADO EM {year}</span>
          <span className="num" style={{ fontSize: 16 }}>{S.fmtMoney(yearTotal)}</span>
          <select value={year} onChange={e => setYear(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',
          }}>
            {years.map(y => <option key={y} value={y}>Ano {y}</option>)}
          </select>
        </div>
      </div>

      {/* Month-by-month aportes per goal (stacked bars) */}
      <LedgerStackedCategoryChart
        data={perMonth}
        categories={goalsAsCats}
        colors={colors}
        activeYmk={null}
        onSelect={null}
        titleOverride={{ eyebrow: 'ACUMULADO MÊS A MÊS', title: 'Total acumulado por meta' }}
      />

      {/* Allocation by investment type (treemap) */}
      <LedgerTreemap
        items={treemapItems}
        eyebrow="ALOCAÇÃO ACUMULADA"
        title="Por tipo de investimento"
        totalLabel="TOTAL NAS METAS"
      />
    </div>
  );
}

// ── DETAIL ───────────────────────────────────────────────────
function GoalDetail({ goal, state, setState, isMobile, onBack, onAporte, onAddHolding, onSetValue, onEditHolding, onDeleteHolding, onDeleteGoal, onEditGoal, onRedeemHolding }) {
  const S = window.LedgerStore;
  const [adding, setAdding]   = React.useState(false);
  const [valuing, setValuing] = React.useState(null); // holding being valued
  const [editing, setEditing] = React.useState(null); // holding being edited
  const [redeeming, setRedeeming] = React.useState(null); // holding being redeemed
  const [chartYear, setChartYear] = React.useState(String(new Date().getFullYear()));
  const [editingAporte, setEditingAporte] = React.useState(null);
  const [editingGoal, setEditingGoal] = React.useState(false);

  // Aportes deste goal (transações com goalId)
  const aporteHistory = React.useMemo(() =>
    (state.transactions || [])
      .filter(t => String(t.goalId) === String(goal.id) && t.amount < 0)
      .sort((a, b) => new Date(b.date) - new Date(a.date)),
    [state.transactions, goal.id]
  );

  function deleteAporte(txId, amount) {
    if (!window.confirm('Remover este aporte? O valor será subtraído do saldo da meta.')) return;
    const abs = Math.abs(amount);
    const nextTx = (state.transactions || []).filter(t => t.id !== txId);
    const nextGoals = (state.goals || []).map(g =>
      String(g.id) === String(goal.id)
        ? { ...g, saved: Math.max(0, (g.saved || 0) - abs) }
        : g
    );
    setState({ ...state, transactions: nextTx, goals: nextGoals });
  }

  function saveEditAporte(txId, oldAmount, newAmount, newDate, newNote) {
    const oldAbs = Math.abs(oldAmount);
    const newAbs = Math.abs(newAmount);
    const delta = newAbs - oldAbs;
    const nextTx = (state.transactions || []).map(t =>
      t.id === txId
        ? { ...t, amount: -newAbs, date: new Date(newDate + 'T12:00:00').toISOString(), note: newNote }
        : t
    );
    const nextGoals = (state.goals || []).map(g =>
      String(g.id) === String(goal.id)
        ? { ...g, saved: Math.max(0, (g.saved || 0) + delta) }
        : g
    );
    setState({ ...state, transactions: nextTx, goals: nextGoals });
    setEditingAporte(null);
  }

  const pct = Math.min(100, Math.round(((goal.saved || 0) / Math.max(1, goal.target)) * 100));
  const remaining = Math.max(0, goal.target - (goal.saved || 0));
  const invested = S.goalHoldingsInvested(goal);
  const current = S.goalHoldingsCurrent(goal);
  const unalloc = S.goalUnallocated(goal);
  const yld = S.goalYield(goal);
  const yldPct = invested > 0 ? (yld / invested) * 100 : 0;
  const holdings = goal.holdings || [];

  return (
    <div className="ledger-screen" style={{ padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1100, margin: '0 auto' }} data-screen-label="Goal Detail">
      <button onClick={onBack} style={{
        all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
        fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--fg-2)',
      }}>
        <LedgerIcon name="arrow-left" size={16} color="currentColor" /> Voltar às metas
      </button>

      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', minWidth: 0 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 'var(--r-4)', background: 'var(--bg-inverse)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <LedgerIcon name={goal.icon || 'target'} size={26} color="var(--fg-on-inverse)" />
          </div>
          <div style={{ minWidth: 0 }}>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Meta · {goal.by || 'Sem prazo'}</div>
            <h1 className="hero" style={{ fontSize: 32, lineHeight: '38px' }}>{goal.name}</h1>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <LedgerButton variant="primary" icon="plus" onClick={onAporte}>Aportar</LedgerButton>
          <LedgerButton variant="secondary" icon="pencil" onClick={() => setEditingGoal(true)}>Editar</LedgerButton>
          <LedgerButton variant="ghost" icon="trash-2" onClick={() => { if (window.confirm('Remover esta meta e todos os seus investimentos?')) onDeleteGoal(); }}>Remover</LedgerButton>
        </div>
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 14 }}>
        <LedgerKpi label="Total na meta" value={S.fmtMoney(goal.saved || 0)} variant="positive" footer={`${pct}% de ${S.fmtMoney(goal.target)}`} />
        <LedgerKpi label="Aportado" value={S.fmtMoney(invested + unalloc)} footer="Capital colocado" />
        <LedgerKpi label="Rendimento" value={S.fmtMoney(yld, { signed: true })} variant={yld >= 0 ? 'positive' : 'negative'} footer={invested > 0 ? `${S.fmtPct(yldPct)} sobre o aportado` : 'Sem investimentos detalhados'} />
        <LedgerKpi label="Restante" value={S.fmtMoney(remaining)} variant="inverse" footer="Para bater a meta" />
      </div>

      {/* Progress bar */}
      <div style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-4)', padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
          <span className="meta" style={{ color: 'var(--fg-3)' }}>PROGRESSO DA META</span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>{S.fmtMoney(goal.saved || 0)} / {S.fmtMoney(goal.target)}</span>
        </div>
        <div style={{ height: 10, borderRadius: 'var(--r-1)', background: 'var(--bg-inset)', overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: pct >= 100 ? 'var(--positive-500)' : 'var(--brand-magenta)', transition: 'width var(--dur-slow) var(--ease-out)' }} />
        </div>
      </div>

      {/* Holdings */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>COMPOSIÇÃO</div>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--fg-strong)' }}>Investimentos</h2>
        </div>
        <LedgerButton variant="secondary" size="sm" icon="plus" onClick={() => setAdding(true)}>Novo investimento</LedgerButton>
      </div>

      <div style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-5)', overflow: 'hidden' }}>
        {holdings.length === 0 && unalloc <= 0 && (
          <div style={{ padding: 48, textAlign: 'center', color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            Nenhum investimento detalhado ainda. Use "Novo investimento" para registrar onde este dinheiro está aplicado.
          </div>
        )}

        {!isMobile && holdings.length > 0 && (
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 130px 130px 150px 160px',
            padding: '14px 24px', background: 'var(--bg-muted)', gap: 12,
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
            color: 'var(--fg-3)', textTransform: 'uppercase',
          }}>
            <div>Investimento</div>
            <div style={{ textAlign: 'right' }}>Aportado</div>
            <div style={{ textAlign: 'right' }}>Valor atual</div>
            <div style={{ textAlign: 'right' }}>Rendimento</div>
            <div />
          </div>
        )}

        {holdings.map((h, idx) => {
          const hy = S.holdingYield(h);
          const hyPct = (h.invested || 0) > 0 ? (hy / h.invested) * 100 : 0;
          if (isMobile) {
            return (
              <div key={h.id} style={{ padding: '14px 16px', borderTop: idx === 0 ? 'none' : '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <div style={{ width: 38, height: 38, borderRadius: 'var(--r-3)', background: 'var(--bg-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <LedgerIcon name={S.INVESTMENT_TYPE_ICON[h.type] || 'circle-dollar-sign'} size={18} color="var(--fg-strong)" />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.name}</div>
                    <div style={{ marginTop: 2 }}><LedgerChip tone="alpha">{h.type}</LedgerChip></div>
                  </div>
                  <div className="num" style={{ fontSize: 15, textAlign: 'right', whiteSpace: 'nowrap' }}>{S.fmtMoney(h.currentValue || 0)}</div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>
                  <span>Aportado {S.fmtMoney(h.invested || 0)}</span>
                  <span style={{ fontWeight: 700, color: hy > 0 ? 'var(--fg-positive)' : hy < 0 ? 'var(--brand-magenta)' : 'var(--fg-2)' }}>
                    {hy === 0 ? '—' : `${S.fmtMoney(hy, { signed: true })} (${S.fmtPct(hyPct)})`}
                  </span>
                </div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  <LedgerButton variant="secondary" size="sm" icon="refresh-cw" onClick={() => setValuing(h)}>Atualizar valor</LedgerButton>
                  <LedgerButton variant="secondary" size="sm" icon="landmark" onClick={() => setRedeeming(h)}>Resgatar</LedgerButton>
                  <button onClick={() => setEditing(h)} title="Editar" style={hIconBtn()}><LedgerIcon name="pencil" size={15} color="currentColor" /></button>
                  <button onClick={() => { if (window.confirm(`Remover ${h.name}?`)) onDeleteHolding(h.id); }} title="Remover" style={hIconBtn()}><LedgerIcon name="trash-2" size={15} color="currentColor" /></button>
                </div>
              </div>
            );
          }
          return (
            <div key={h.id} style={{
              display: 'grid', gridTemplateColumns: '1fr 130px 130px 150px 160px',
              padding: '16px 24px', gap: 12, alignItems: 'center',
              borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
            }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', minWidth: 0 }}>
                <div style={{ width: 36, height: 36, borderRadius: 'var(--r-2)', background: 'var(--bg-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <LedgerIcon name={S.INVESTMENT_TYPE_ICON[h.type] || 'circle-dollar-sign'} size={16} color="var(--fg-strong)" />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.name}</div>
                  <div style={{ marginTop: 2 }}><LedgerChip tone="alpha">{h.type}</LedgerChip></div>
                </div>
              </div>
              <div className="num" style={{ textAlign: 'right', fontSize: 14, color: 'var(--fg-2)' }}>{S.fmtMoney(h.invested || 0)}</div>
              <div className="num" style={{ textAlign: 'right', fontSize: 15, color: 'var(--fg-strong)' }}>{S.fmtMoney(h.currentValue || 0)}</div>
              <div className="num" style={{ textAlign: 'right', fontSize: 13, color: hy > 0 ? 'var(--fg-positive)' : hy < 0 ? 'var(--brand-magenta)' : 'var(--fg-2)' }}>
                {hy === 0 ? '—' : `${S.fmtMoney(hy, { signed: true })}`}
                {hy !== 0 && <div style={{ fontSize: 11, opacity: 0.8 }}>{S.fmtPct(hyPct)}</div>}
              </div>
              <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                <button onClick={() => setValuing(h)} title="Atualizar valor" style={hIconBtn()}><LedgerIcon name="refresh-cw" size={15} color="currentColor" /></button>
                <button onClick={() => setRedeeming(h)} title="Resgatar investimento" style={{ ...hIconBtn(), color: 'var(--positive-700)', background: 'var(--positive-50)' }}><LedgerIcon name="landmark" size={15} color="currentColor" /></button>
                <button onClick={() => setEditing(h)} title="Editar" style={hIconBtn()}><LedgerIcon name="pencil" size={15} color="currentColor" /></button>
                <button onClick={() => { if (window.confirm(`Remover ${h.name}?`)) onDeleteHolding(h.id); }} title="Remover" style={hIconBtn()}><LedgerIcon name="trash-2" size={15} color="currentColor" /></button>
              </div>
            </div>
          );
        })}

        {unalloc > 0 && (
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '16px 24px', borderTop: holdings.length ? '1px solid var(--border)' : 'none',
            background: 'var(--bg-muted)',
          }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{ width: 36, height: 36, borderRadius: 'var(--r-2)', background: 'var(--bg-elevated)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <LedgerIcon name="wallet" size={16} color="var(--fg-2)" />
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)' }}>Não alocado</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>Saldo da meta ainda sem investimento específico</div>
              </div>
            </div>
            <div className="num" style={{ fontSize: 15, color: 'var(--fg-2)' }}>{S.fmtMoney(unalloc)}</div>
          </div>
        )}
      </div>

      {/* Histórico de aportes */}
      {aporteHistory.length > 0 && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 14 }}>
            <div>
              <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>HISTÓRICO</div>
              <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--fg-strong)' }}>Aportes realizados</h2>
            </div>
          </div>
          <div style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-5)', overflow: 'hidden' }}>
            {aporteHistory.map((tx, idx) => (
              <div key={tx.id} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 20px',
                borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 'var(--r-3)', background: 'var(--positive-50)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <LedgerIcon name="trending-up" size={16} color="var(--positive-700)" />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--fg-strong)' }}>
                    {tx.note || 'Aporte'}
                  </div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                    {S.fmtDate(tx.date)}
                  </div>
                </div>
                <div className="num" style={{ fontSize: 15, fontWeight: 700, color: 'var(--positive-700)', whiteSpace: 'nowrap' }}>
                  {S.fmtMoney(Math.abs(tx.amount))}
                </div>
                <div style={{ display: 'flex', gap: 4 }}>
                  <button onClick={() => setEditingAporte(tx)} style={{
                    all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
                    display: 'flex', alignItems: 'center', transition: 'all var(--dur-fast)',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-muted)'; e.currentTarget.style.color = 'var(--fg)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
                  title="Editar aporte">
                    <LedgerIcon name="pencil" size={15} color="currentColor" />
                  </button>
                  <button onClick={() => deleteAporte(tx.id, tx.amount)} style={{
                    all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-3)',
                    display: 'flex', alignItems: 'center', transition: 'all var(--dur-fast)',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--brand-magenta-100)'; e.currentTarget.style.color = 'var(--brand-magenta-700)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
                  title="Remover aporte">
                    <LedgerIcon name="trash-2" size={15} color="currentColor" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Growth chart for this goal */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12, marginTop: 4 }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 4 }}>EVOLUÇÃO</div>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--fg-strong)' }}>Crescimento acumulado</h2>
        </div>
        <select value={chartYear} onChange={e => setChartYear(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',
        }}>
          {S.goalAporteYears(state).map(y => <option key={y} value={y}>Ano {y}</option>)}
        </select>
      </div>
      <GoalAportesChart goal={goal} state={state} year={chartYear} />

      {adding && <NewInvestmentModal goal={goal} onClose={() => setAdding(false)} onSubmit={(h) => { onAddHolding(h); setAdding(false); }} />}
      {valuing && <UpdateValueModal goal={goal} holding={valuing} onClose={() => setValuing(null)} onSubmit={(v) => { onSetValue(valuing.id, v); setValuing(null); }} />}
      {editing && <EditHoldingModal holding={editing} onClose={() => setEditing(null)} onSubmit={(patch) => { onEditHolding(editing.id, patch); setEditing(null); }} />}
      {redeeming && (
        <RedeemHoldingModal
          holding={redeeming}
          goal={goal}
          onClose={() => setRedeeming(null)}
          onSubmit={(amt, note, partial, remCV, remInv) => {
            onRedeemHolding(redeeming.id, redeeming.name, amt, note, partial, remCV, remInv);
            setRedeeming(null);
          }}
        />
      )}
      {editingAporte && (
        <EditAporteModal
          tx={editingAporte}
          onClose={() => setEditingAporte(null)}
          onSave={(newAmount, newDate, newNote) => saveEditAporte(editingAporte.id, editingAporte.amount, newAmount, newDate, newNote)}
        />
      )}
      {editingGoal && (
        <EditGoalModal
          goal={goal}
          onClose={() => setEditingGoal(false)}
          onSave={(patch) => { onEditGoal(patch); setEditingGoal(false); }}
        />
      )}
    </div>
  );
}

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

// Single-goal month-by-month ACCUMULATED balance, stacked by investment (holding),
// anchored so the current month equals the goal's saldo — mirrors the general chart.
function GoalAportesChart({ goal, state, year }) {
  const S = window.LedgerStore;
  const raw = React.useMemo(() => S.goalAportesPerMonthForGoal(state, goal.id, year), [state, goal.id, year]);
  const now = new Date();
  const currentYear = now.getFullYear();
  const lastRealIdx = Number(year) < currentYear ? 11 : (Number(year) > currentYear ? -1 : now.getMonth());

  const holdings = goal.holdings || [];
  const unalloc = S.goalUnallocated(goal);
  const palette = ['#0891B2', '#0F766E', '#B00369', '#D97706', '#65A30D', '#7C3AED', '#DC2626', '#3B6FF1'];
  const cats = holdings.map((h, i) => ({ id: String(h.id), name: h.name, chipTone: 'alpha', icon: S.INVESTMENT_TYPE_ICON[h.type] || 'circle-dollar-sign' }));
  const colors = {};
  holdings.forEach((h, i) => { colors[String(h.id)] = palette[i % palette.length]; });
  if (unalloc > 0 || holdings.length === 0) { cats.push({ id: '__unalloc', name: 'Não alocado', icon: 'wallet' }); colors['__unalloc'] = 'var(--slate-400)'; }
  const denom = holdings.reduce((s, h) => s + (h.currentValue || 0), 0) + unalloc || 1;

  const data = React.useMemo(() => {
    const sumAportes = raw.reduce((s, m, i) => i <= lastRealIdx ? s + m.value : s, 0);
    let running = Math.max(0, (goal.saved || 0) - sumAportes); // pre-year balance
    return raw.map((m, i) => {
      const catsVals = {};
      let total = 0;
      if (i <= lastRealIdx) {
        running += m.value;
        total = running;
        if (total > 0) {
          holdings.forEach(h => { const v = total * ((h.currentValue || 0) / denom); if (v > 0) catsVals[String(h.id)] = v; });
          const uv = total * (unalloc / denom);
          if (uv > 0) catsVals['__unalloc'] = uv;
        }
      }
      return { ymk: m.ymk, label: m.label, total, cats: catsVals };
    });
  }, [raw, lastRealIdx, goal.saved, denom]);

  const LedgerStackedCategoryChart = window.LedgerStackedCategoryChart;
  return (
    <LedgerStackedCategoryChart
      data={data}
      categories={cats}
      colors={colors}
      activeYmk={null}
      onSelect={null}
      titleOverride={{ eyebrow: 'ACUMULADO MÊS A MÊS', title: 'Acumulado por investimento' }}
    />
  );
}

function NewGoalModal({ onClose, onSave }) {
  const S = window.LedgerStore;
  const [name, setName]     = React.useState('');
  const [target, setTarget] = React.useState('');
  const [saved, setSaved]   = React.useState('');
  const [by, setBy]         = React.useState('');
  const [icon, setIcon]     = React.useState('target');
  const [focus, setFocus]   = React.useState(null);

  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() {
    const t = parseFloat((target || '').replace(',', '.'));
    if (!name || !t || t <= 0) return;
    onSave({
      name,
      target: t,
      saved: parseFloat((saved || '0').replace(',', '.')) || 0,
      by: by || 'Sem prazo',
      icon,
    });
  }

  const icons = ['target', 'vault', 'landmark', 'briefcase', 'plane', 'car', 'home', 'graduation-cap', 'baby', 'gift', 'gem'];

  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: 100, padding: 24,
    }}>
      <div className="ledger-modal" onClick={e => e.stopPropagation()} style={{
        width: 480, maxWidth: '100%', 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: 'center' }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>NOVA META</div>
            <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>Crie uma Meta</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>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Nome da meta</span>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="ex: Viagem para Lisboa" 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 alvo</span>
            <input value={target} onChange={e => setTarget(e.target.value)} placeholder="9000" inputMode="decimal" onFocus={() => setFocus('t')} onBlur={() => setFocus(null)} style={inputStyle('t')} />
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Já poupado</span>
            <input value={saved} onChange={e => setSaved(e.target.value)} placeholder="0" inputMode="decimal" onFocus={() => setFocus('s')} onBlur={() => setFocus(null)} style={inputStyle('s')} />
          </label>
        </div>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Prazo final <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>(opcional)</span></span>
          <input value={by} onChange={e => setBy(e.target.value)} placeholder="ex: Dez 2027 ou 'Sem prazo'" onFocus={() => setFocus('b')} onBlur={() => setFocus(null)} style={inputStyle('b')} />
        </label>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Ícone</span>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {icons.map(i => (
              <button key={i} type="button" onClick={() => setIcon(i)} style={{
                all: 'unset', cursor: 'pointer',
                width: 38, height: 38, borderRadius: 'var(--r-3)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: icon === i ? 'var(--bg-inverse)' : 'var(--bg-muted)',
                color: icon === i ? 'var(--fg-on-inverse)' : 'var(--fg)',
                border: icon === i ? '1px solid var(--bg-inverse)' : '1px solid var(--border)',
                transition: 'all var(--dur-fast)',
              }}>
                <LedgerIcon name={i} size={16} color="currentColor" />
              </button>
            ))}
          </div>
        </div>

        <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}>Criar Meta</LedgerButton>
        </div>
      </div>
    </div>
  );
}

// ── EDIT GOAL MODAL ─────────────────────────────────────────
// Permite editar nome, valor-alvo, prazo e ícone de uma meta já existente.
// "Já poupado" não é editável aqui de propósito — esse valor reflete os
// aportes reais (histórico de transações), então mudá-lo direto desalinharia
// os números. Para corrigir o saldo, edite/apague os aportes no histórico.
function EditGoalModal({ goal, onClose, onSave }) {
  const S = window.LedgerStore;
  const [name, setName]     = React.useState(goal.name || '');
  const [target, setTarget] = React.useState(String(goal.target || '').replace('.', ','));
  const [by, setBy]         = React.useState(goal.by || '');
  const [icon, setIcon]     = React.useState(goal.icon || 'target');
  const [focus, setFocus]   = React.useState(null);
  const [error, setError]   = React.useState('');

  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 t = parseFloat((target || '').replace(',', '.'));
    if (!name.trim()) { setError('Dê um nome para a meta.'); return; }
    if (!t || isNaN(t) || t <= 0) { setError('Informe um valor-alvo positivo.'); return; }
    onSave({ name: name.trim(), target: t, by: by.trim() || 'Sem prazo', icon });
  }

  const icons = ['target', 'vault', 'landmark', 'briefcase', 'plane', 'car', 'home', 'graduation-cap', 'baby', 'gift', 'gem'];

  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: 100, padding: 24,
    }}>
      <div className="ledger-modal" onClick={e => e.stopPropagation()} style={{
        width: 480, maxWidth: '100%', 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: 'center' }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>EDITAR META</div>
            <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>{goal.name}</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)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--brand-magenta-700)' }}>
            <LedgerIcon name="alert-circle" size={16} color="var(--brand-magenta-700)" /> {error}
          </div>
        )}

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Nome da meta</span>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="ex: Viagem para Lisboa" onFocus={() => setFocus('n')} onBlur={() => setFocus(null)} style={inputStyle('n')} />
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Valor alvo</span>
          <input value={target} onChange={e => setTarget(e.target.value)} placeholder="9000" inputMode="decimal" onFocus={() => setFocus('t')} onBlur={() => setFocus(null)} style={inputStyle('t')} />
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>
            Já poupado hoje: {S.fmtMoney(goal.saved || 0)} — esse valor segue o histórico de aportes e não é editado aqui.
          </span>
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Prazo final <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>(opcional)</span></span>
          <input value={by} onChange={e => setBy(e.target.value)} placeholder="ex: Dez 2027 ou 'Sem prazo'" onFocus={() => setFocus('b')} onBlur={() => setFocus(null)} style={inputStyle('b')} />
        </label>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: 'var(--fg)' }}>Ícone</span>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {icons.map(i => (
              <button key={i} type="button" onClick={() => setIcon(i)} style={{
                all: 'unset', cursor: 'pointer',
                width: 38, height: 38, borderRadius: 'var(--r-3)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: icon === i ? 'var(--bg-inverse)' : 'var(--bg-muted)',
                color: icon === i ? 'var(--fg-on-inverse)' : 'var(--fg)',
                border: icon === i ? '1px solid var(--bg-inverse)' : '1px solid var(--border)',
                transition: 'all var(--dur-fast)',
              }}>
                <LedgerIcon name={i} size={16} color="currentColor" />
              </button>
            ))}
          </div>
        </div>

        <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}>Salvar alterações</LedgerButton>
        </div>
      </div>
    </div>
  );
}

// ── EDIT APORTE MODAL ──────────────────────────────────────
function EditAporteModal({ tx, onClose, onSave }) {
  const S = window.LedgerStore;
  const [amount, setAmount] = React.useState(String(Math.abs(tx.amount)).replace('.', ','));
  const [date, setDate]     = React.useState(tx.date ? tx.date.slice(0, 10) : '');
  const [note, setNote]     = React.useState(tx.note || '');
  const [error, setError]   = React.useState('');
  const [focus, setFocus]   = React.useState(null);

  const inputStyle = (id) => ({
    fontFamily: 'var(--font-body)', fontSize: 14, padding: '10px 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) var(--ease-out)',
  });

  function handleSave(e) {
    e.preventDefault();
    const n = parseFloat((amount || '').replace(',', '.'));
    if (!n || isNaN(n) || n <= 0) { setError('Entre um valor positivo.'); return; }
    onSave(n, date, note);
  }

  const labelStyle = {
    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10,
    letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)',
    display: 'block', marginBottom: 6,
  };

  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: 200, padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 460, maxWidth: '100%', background: 'var(--bg-elevated)',
        borderRadius: 'var(--r-5)', padding: 32, boxShadow: 'var(--shadow-pop)',
        display: 'flex', flexDirection: 'column', gap: 20,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>
            Editar Aporte
          </h2>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: 'var(--fg-3)', padding: 4 }}>
            <LedgerIcon name="x" size={20} 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)', 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>
        )}

        <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <span style={labelStyle}>Valor (R$)</span>
            <div style={{
              display: 'flex', alignItems: 'stretch',
              border: `1px solid ${focus === 'amt' ? 'var(--slate-400)' : 'var(--border)'}`,
              borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)',
            }}>
              <span style={{
                display: 'flex', alignItems: 'center', padding: '0 14px',
                fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
                color: 'var(--positive-700)', borderRight: '1px solid var(--border)',
              }}>+ R$</span>
              <input value={amount} onChange={e => setAmount(e.target.value)}
                onFocus={() => setFocus('amt')} onBlur={() => setFocus(null)}
                inputMode="decimal"
                style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 16, padding: '11px 14px',
                  border: 'none', background: 'transparent', color: 'var(--fg)', outline: 'none' }} />
            </div>
          </div>
          <div>
            <span style={labelStyle}>Data</span>
            <input type="date" value={date} onChange={e => setDate(e.target.value)}
              onFocus={() => setFocus('dt')} onBlur={() => setFocus(null)}
              style={inputStyle('dt')} />
          </div>
          <div>
            <span style={labelStyle}>Descrição</span>
            <input value={note} onChange={e => setNote(e.target.value)}
              onFocus={() => setFocus('nt')} onBlur={() => setFocus(null)}
              placeholder="Ex: Aporte mensal..."
              style={inputStyle('nt')} />
          </div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
            <LedgerButton type="button" variant="secondary" onClick={onClose}>Cancelar</LedgerButton>
            <LedgerButton type="submit" variant="primary" icon="check">Salvar alterações</LedgerButton>
          </div>
        </form>
      </div>
    </div>
  );
}

window.LedgerGoalsScreen = LedgerGoalsScreen;
