// ─────────────────────────────────────────────────────────────
// goals-modals.jsx — modals for goals: aporte (with holding pick),
// new investment, update value, new goal.
// ─────────────────────────────────────────────────────────────

const { LedgerIcon: GMIcon, LedgerButton: GMButton, LedgerSegmented: GMSeg, LedgerChip: GMChip } = window;

function gmInput(focus, id, extra = {}) {
  return {
    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)', ...extra,
  };
}

function GMModalShell({ eyebrow, title, onClose, children, width = 480 }) {
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 150, padding: 24,
    }}>
      <div className="ledger-modal" onClick={e => e.stopPropagation()} style={{
        width, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto',
        background: 'var(--bg-elevated)', borderRadius: 'var(--r-5)',
        padding: 28, boxShadow: 'var(--shadow-pop)', display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)' }}>{eyebrow}</div>
            <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--fg-strong)' }}>{title}</h3>
          </div>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', padding: 6, borderRadius: 'var(--r-2)', color: 'var(--fg-2)' }}>
            <GMIcon name="x" size={18} color="currentColor" />
          </button>
        </div>
        {children}
      </div>
    </div>
  );
}

function gmLabel(text, color) {
  return <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: color || 'var(--fg)' }}>{text}</span>;
}

function gmError(msg) {
  if (!msg) return null;
  return (
    <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,
    }}>
      <GMIcon name="alert-circle" size={16} color="var(--brand-magenta-700)" /> {msg}
    </div>
  );
}

// ── APORTE MODAL ─────────────────────────────────────────────
// Choose amount + destination (general pool / existing holding / new holding).
function AporteModal({ goal, onClose, onSubmit }) {
  const S = window.LedgerStore;
  const holdings = goal.holdings || [];
  const [amount, setAmount] = React.useState('');
  // dest: 'general' | holdingId | '__new__'
  const [dest, setDest]     = React.useState(holdings.length ? holdings[0].id : 'general');
  const [newName, setNewName] = React.useState('');
  const [newType, setNewType] = React.useState('Fundo');
  const [focus, setFocus]   = React.useState(null);
  const [error, setError]   = React.useState('');

  function submit() {
    setError('');
    const n = parseFloat((amount || '').replace(',', '.'));
    if (!n || isNaN(n) || n <= 0) { setError('Informe um valor positivo.'); return; }
    let holding = null, label = 'Geral';
    if (dest === '__new__') {
      if (!newName.trim()) { setError('Dê um nome ao novo investimento.'); return; }
      holding = { name: newName.trim(), type: newType };
      label = newName.trim();
    } else if (dest !== 'general') {
      const h = holdings.find(x => x.id === dest);
      holding = { id: dest };
      label = h ? h.name : 'Investimento';
    }
    onSubmit(n, holding, label);
  }

  const destBtn = (value, label, sub, icon) => {
    const on = dest === value;
    return (
      <button key={value} type="button" onClick={() => setDest(value)} style={{
        all: 'unset', cursor: 'pointer', boxSizing: 'border-box', width: '100%',
        display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
        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: 34, height: 34, borderRadius: 'var(--r-2)', flexShrink: 0,
          background: on ? 'var(--positive-100)' : 'var(--bg-elevated)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <GMIcon name={icon} size={16} 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 && <GMIcon name="check" size={16} color="var(--positive-700)" />}
      </button>
    );
  };

  return (
    <GMModalShell eyebrow="APORTE" title={`Aportar em ${goal.name}`} onClose={onClose} width={500}>
      {gmError(error)}

      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Valor do aporte (R$)')}
        <input autoFocus value={amount} onChange={e => setAmount(e.target.value)} placeholder="500,00" inputMode="decimal"
          onFocus={() => setFocus('a')} onBlur={() => setFocus(null)} style={gmInput(focus, 'a', { fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 })} />
      </label>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {gmLabel('Destino do aporte')}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {holdings.map(h => destBtn(
            h.id, h.name,
            `${h.type} · atual ${S.fmtMoney(h.currentValue || 0)}`,
            S.INVESTMENT_TYPE_ICON[h.type] || 'circle-dollar-sign',
          ))}
          {destBtn('__new__', 'Novo investimento', 'Criar um instrumento dentro desta meta', 'plus')}
          {destBtn('general', 'Geral (sem investimento específico)', 'Soma ao total da meta', 'wallet')}
        </div>
      </div>

      {dest === '__new__' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: 14, background: 'var(--bg-muted)', borderRadius: 'var(--r-3)' }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {gmLabel('Nome do investimento')}
            <input value={newName} onChange={e => setNewName(e.target.value)} placeholder="ex: CDB Banco XP 2028"
              onFocus={() => setFocus('nn')} onBlur={() => setFocus(null)} style={gmInput(focus, 'nn')} />
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {gmLabel('Tipo')}
            <select value={newType} onChange={e => setNewType(e.target.value)} onFocus={() => setFocus('nt')} onBlur={() => setFocus(null)} style={gmInput(focus, 'nt')}>
              {S.INVESTMENT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </label>
        </div>
      )}

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
        <GMButton variant="secondary" onClick={onClose}>Cancelar</GMButton>
        <GMButton variant="primary" icon="check" onClick={submit}>Confirmar aporte</GMButton>
      </div>
    </GMModalShell>
  );
}

// ── NEW INVESTMENT MODAL (no cash movement; declares an existing holding) ──
function NewInvestmentModal({ goal, onClose, onSubmit }) {
  const S = window.LedgerStore;
  const [name, setName]       = React.useState('');
  const [type, setType]       = React.useState('Fundo');
  const [invested, setInvested] = React.useState('');
  const [current, setCurrent] = React.useState('');
  const [focus, setFocus]     = React.useState(null);
  const [error, setError]     = React.useState('');

  function submit() {
    setError('');
    if (!name.trim()) { setError('Dê um nome ao investimento.'); return; }
    const inv = parseFloat((invested || '').replace(',', '.')) || 0;
    const cur = current.trim() ? (parseFloat(current.replace(',', '.')) || 0) : inv;
    if (inv <= 0 && cur <= 0) { setError('Informe o valor aportado ou o valor atual.'); return; }
    onSubmit({ id: S.newHoldingId(), name: name.trim(), type, invested: inv, currentValue: cur });
  }

  return (
    <GMModalShell eyebrow="NOVO INVESTIMENTO" title={`Adicionar a ${goal.name}`} onClose={onClose}>
      {gmError(error)}
      <p style={{ margin: 0, fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)' }}>
        Use isto para registrar um investimento que você já possui. Não cria lançamento no saldo — apenas descreve a composição da meta.
      </p>
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Nome do investimento')}
        <input autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="ex: LCI Banco Inter"
          onFocus={() => setFocus('n')} onBlur={() => setFocus(null)} style={gmInput(focus, 'n')} />
      </label>
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Tipo')}
        <select value={type} onChange={e => setType(e.target.value)} onFocus={() => setFocus('t')} onBlur={() => setFocus(null)} style={gmInput(focus, 't')}>
          {S.INVESTMENT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
        </select>
      </label>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {gmLabel('Valor aportado (R$)')}
          <input value={invested} onChange={e => setInvested(e.target.value)} placeholder="10000" inputMode="decimal"
            onFocus={() => setFocus('i')} onBlur={() => setFocus(null)} style={gmInput(focus, 'i')} />
        </label>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {gmLabel('Valor atual (R$)')}
          <input value={current} onChange={e => setCurrent(e.target.value)} placeholder="= aportado" inputMode="decimal"
            onFocus={() => setFocus('c')} onBlur={() => setFocus(null)} style={gmInput(focus, 'c')} />
        </label>
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
        <GMButton variant="secondary" onClick={onClose}>Cancelar</GMButton>
        <GMButton variant="primary" icon="check" onClick={submit}>Adicionar</GMButton>
      </div>
    </GMModalShell>
  );
}

// ── UPDATE VALUE MODAL (reflect yield) ───────────────────────
function UpdateValueModal({ goal, holding, onClose, onSubmit }) {
  const S = window.LedgerStore;
  const [value, setValue] = React.useState(String(holding.currentValue || 0).replace('.', ','));
  const [focus, setFocus] = React.useState(null);
  const [error, setError] = React.useState('');

  const parsed = parseFloat((value || '').replace(',', '.'));
  const delta = (!isNaN(parsed) ? parsed : (holding.currentValue || 0)) - (holding.currentValue || 0);
  const newYield = (!isNaN(parsed) ? parsed : 0) - (holding.invested || 0);

  function submit() {
    setError('');
    if (isNaN(parsed) || parsed < 0) { setError('Informe um valor válido.'); return; }
    onSubmit(parsed);
  }

  return (
    <GMModalShell eyebrow="ATUALIZAR VALOR" title={holding.name} onClose={onClose}>
      {gmError(error)}
      <div style={{ display: 'flex', gap: 18, padding: '12px 0' }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>APORTADO</div>
          <div className="num" style={{ fontSize: 16 }}>{S.fmtMoney(holding.invested || 0)}</div>
        </div>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>VALOR ATUAL</div>
          <div className="num" style={{ fontSize: 16 }}>{S.fmtMoney(holding.currentValue || 0)}</div>
        </div>
      </div>
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Novo valor atual (R$)')}
        <input autoFocus value={value} onChange={e => setValue(e.target.value)} inputMode="decimal"
          onFocus={() => setFocus('v')} onBlur={() => setFocus(null)} style={gmInput(focus, 'v', { fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 })} />
      </label>
      <div style={{
        padding: '10px 14px', borderRadius: 'var(--r-3)',
        background: newYield >= 0 ? 'var(--positive-50)' : 'var(--brand-magenta-100)',
        border: `1px solid ${newYield >= 0 ? 'rgba(0,150,104,0.25)' : 'rgba(176,3,105,0.22)'}`,
        fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600,
        color: newYield >= 0 ? 'var(--positive-700)' : 'var(--brand-magenta-700)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <GMIcon name={newYield >= 0 ? 'trending-up' : 'trending-down'} size={14} color="currentColor" />
        <span>
          Rendimento: {S.fmtMoney(newYield, { signed: true })}
          {delta !== 0 && ` · variação ${S.fmtMoney(delta, { signed: true })}`}
        </span>
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
        <GMButton variant="secondary" onClick={onClose}>Cancelar</GMButton>
        <GMButton variant="primary" icon="check" onClick={submit}>Salvar valor</GMButton>
      </div>
    </GMModalShell>
  );
}

// ── EDIT HOLDING MODAL (name / type) ─────────────────────────
function EditHoldingModal({ holding, onClose, onSubmit }) {
  const S = window.LedgerStore;
  const [name, setName] = React.useState(holding.name);
  const [type, setType] = React.useState(holding.type || 'Outro');
  const [focus, setFocus] = React.useState(null);

  return (
    <GMModalShell eyebrow="EDITAR INVESTIMENTO" title={holding.name} onClose={onClose}>
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Nome')}
        <input autoFocus value={name} onChange={e => setName(e.target.value)} onFocus={() => setFocus('n')} onBlur={() => setFocus(null)} style={gmInput(focus, 'n')} />
      </label>
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Tipo')}
        <select value={type} onChange={e => setType(e.target.value)} onFocus={() => setFocus('t')} onBlur={() => setFocus(null)} style={gmInput(focus, 't')}>
          {S.INVESTMENT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
        </select>
      </label>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
        <GMButton variant="secondary" onClick={onClose}>Cancelar</GMButton>
        <GMButton variant="primary" icon="check" onClick={() => name.trim() && onSubmit({ name: name.trim(), type })}>Salvar</GMButton>
      </div>
    </GMModalShell>
  );
}

// ── REDEEM HOLDING MODAL (vencimento / resgate parcial ou total) ──
// partial=false → holding removido da meta
// partial=true  → holding reduzido proporcionalmente (invested + currentValue)
// Em ambos os casos cria um lançamento de entrada em Lançamentos.
function RedeemHoldingModal({ holding, goal, onClose, onSubmit }) {
  const S = window.LedgerStore;
  const currentVal = holding.currentValue || 0;
  const invested   = holding.invested   || 0;

  const [partial,  setPartial]  = React.useState(false);
  const partialRef = React.useRef(false); // mirror para submit() evitar stale closure
  const [received, setReceived] = React.useState(String(currentVal).replace('.', ','));
  const [note,     setNote]     = React.useState('');
  const [focus,    setFocus]    = React.useState(null);
  const [error,    setError]    = React.useState('');

  const parsedReceived = parseFloat((received || '').replace(',', '.'));

  // Para resgate parcial: quanto sobra no investimento (em currentValue)
  const remaining = !isNaN(parsedReceived) ? Math.max(0, currentVal - parsedReceived) : currentVal;
  // Proporção resgatada → ajusta invested proporcionalmente
  const redeemRatio = currentVal > 0 ? Math.min(1, parsedReceived / currentVal) : 1;
  const investedRedeemed = invested * redeemRatio;
  const investedRemaining = invested - investedRedeemed;

  const irDiscount = !isNaN(parsedReceived) && !partial
    ? (currentVal - parsedReceived)
    : 0;

  // Ao trocar de modo, redefine o valor sugerido
  function switchMode(toPartial) {
    partialRef.current = toPartial;
    setPartial(toPartial);
    setReceived(toPartial ? '' : String(currentVal).replace('.', ','));
    setError('');
  }

  function submit() {
    setError('');
    // Lê partialRef para evitar stale closure no boolean de state
    const isPartial = partialRef.current;
    if (isNaN(parsedReceived) || parsedReceived <= 0) {
      setError('Informe o valor recebido.');
      return;
    }
    if (isPartial && parsedReceived >= currentVal) {
      setError('Para resgatar tudo use "Resgate total".');
      return;
    }
    // Sempre passa remaining e investedRemaining reais
    // isPartial=true → remainingCV > 0 (holding fica reduzido)
    // isPartial=false → remainingCV = 0 (holding é removido)
    const remainingCV  = isPartial ? Math.max(0, currentVal - parsedReceived) : 0;
    const remainingInv = isPartial ? Math.max(0, investedRemaining)          : 0;
    onSubmit(parsedReceived, note.trim(), isPartial, remainingCV, remainingInv);
  }

  const tabStyle = (active) => ({
    flex: 1, padding: '9px 0', textAlign: 'center',
    fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13,
    borderRadius: 'var(--r-2)', cursor: 'pointer', border: 'none',
    background: active ? 'var(--bg-elevated)' : 'transparent',
    color: active ? 'var(--fg-strong)' : 'var(--fg-3)',
    boxShadow: active ? 'var(--shadow-sm)' : 'none',
    transition: 'all var(--dur-fast)',
  });

  return (
    <GMModalShell eyebrow="RESGATAR INVESTIMENTO" title={holding.name} onClose={onClose} width={500}>
      {gmError(error)}

      {/* Holding summary */}
      <div style={{ display: 'flex', gap: 20, padding: '12px 16px', background: 'var(--bg-muted)', borderRadius: 'var(--r-3)' }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>APORTADO</div>
          <div className="num" style={{ fontSize: 14 }}>{S.fmtMoney(invested)}</div>
        </div>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>VALOR ATUAL</div>
          <div className="num" style={{ fontSize: 14 }}>{S.fmtMoney(currentVal)}</div>
        </div>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>META</div>
          <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--fg)' }}>{goal.name}</div>
        </div>
      </div>

      {/* Toggle total / parcial */}
      <div style={{ display: 'flex', padding: 4, background: 'var(--bg-muted)', borderRadius: 'var(--r-3)', gap: 2 }}>
        <button style={tabStyle(!partial)} onClick={() => switchMode(false)}>Resgate total</button>
        <button style={tabStyle(partial)}  onClick={() => switchMode(true)}>Resgate parcial</button>
      </div>

      {/* Valor recebido */}
      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Valor recebido (R$)')}
        <div style={{
          display: 'flex', alignItems: 'stretch',
          border: `1px solid ${focus === 'rv' ? 'var(--slate-400)' : 'var(--border)'}`,
          borderRadius: 'var(--r-3)', background: 'var(--bg-elevated)',
          boxShadow: focus === 'rv' ? 'var(--shadow-focus)' : 'none',
          transition: 'all var(--dur-fast)',
        }}>
          <span style={{
            display: 'flex', alignItems: 'center', padding: '0 14px',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
            color: 'var(--positive-700)', borderRight: '1px solid var(--border)',
          }}>R$</span>
          <input
            autoFocus
            value={received}
            onChange={e => setReceived(e.target.value)}
            onFocus={() => setFocus('rv')}
            onBlur={() => setFocus(null)}
            inputMode="decimal"
            placeholder="0,00"
            style={{
              flex: 1, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
              padding: '11px 14px', border: 'none', background: 'transparent',
              color: 'var(--fg)', outline: 'none',
            }}
          />
        </div>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>
          {partial
            ? 'Valor líquido recebido neste resgate parcial.'
            : 'Valor líquido recebido na conta (com IR descontado, se houver).'}
        </span>
      </label>

      {/* Indicadores contextuais */}
      {!partial && !isNaN(parsedReceived) && irDiscount > 0.005 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderRadius: 'var(--r-3)', background: 'rgba(217,119,6,0.08)', border: '1px solid rgba(217,119,6,0.25)', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600, color: '#b45309' }}>
          <GMIcon name="info" size={14} color="currentColor" />
          IR / desconto de {S.fmtMoney(irDiscount)} em relação ao valor registrado.
        </div>
      )}
      {!partial && !isNaN(parsedReceived) && parsedReceived > currentVal && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderRadius: 'var(--r-3)', background: 'var(--positive-50)', border: '1px solid rgba(0,150,104,0.25)', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600, color: 'var(--positive-700)' }}>
          <GMIcon name="trending-up" size={14} color="currentColor" />
          Recebimento superior ao valor registrado — ótimo!
        </div>
      )}

      {/* Preview do saldo que fica (resgate parcial) */}
      {partial && !isNaN(parsedReceived) && parsedReceived > 0 && parsedReceived < currentVal && (
        <div style={{ display: 'flex', gap: 20, padding: '12px 16px', background: 'var(--positive-50)', borderRadius: 'var(--r-3)', border: '1px solid rgba(0,150,104,0.2)' }}>
          <div>
            <div className="meta" style={{ color: 'var(--positive-700)', marginBottom: 2 }}>VOCÊ RECEBE</div>
            <div className="num" style={{ fontSize: 14, color: 'var(--positive-700)' }}>{S.fmtMoney(parsedReceived)}</div>
          </div>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>FICA INVESTIDO</div>
            <div className="num" style={{ fontSize: 14 }}>{S.fmtMoney(remaining)}</div>
          </div>
          <div>
            <div className="meta" style={{ color: 'var(--fg-3)', marginBottom: 2 }}>APORTADO RESTANTE</div>
            <div className="num" style={{ fontSize: 14 }}>{S.fmtMoney(investedRemaining)}</div>
          </div>
        </div>
      )}

      <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {gmLabel('Observação')}
        <input
          value={note}
          onChange={e => setNote(e.target.value)}
          onFocus={() => setFocus('nt')}
          onBlur={() => setFocus(null)}
          placeholder="Opcional — ex: resgate parcial debenture Arteris set/2026"
          style={gmInput(focus, 'nt')}
        />
      </label>

      {/* Aviso do que vai acontecer */}
      <div style={{ padding: '10px 14px', borderRadius: 'var(--r-3)', background: 'var(--brand-magenta-100)', border: '1px solid rgba(176,3,105,0.22)', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600, color: 'var(--brand-magenta-700)', display: 'flex', alignItems: 'flex-start', gap: 8 }}>
        <GMIcon name="alert-triangle" size={14} color="currentColor" />
        <span>
          {partial
            ? <>O saldo de <strong>{holding.name}</strong> será reduzido para {!isNaN(parsedReceived) && parsedReceived < currentVal ? S.fmtMoney(remaining) : '—'} e {!isNaN(parsedReceived) ? S.fmtMoney(parsedReceived) : 'o valor recebido'} entrará como recebimento em <strong>Lançamentos</strong>.</>
            : <><strong>{holding.name}</strong> será removido da meta e {!isNaN(parsedReceived) ? S.fmtMoney(parsedReceived) : 'o valor recebido'} entrará como recebimento em <strong>Lançamentos</strong>.</>
          }
        </span>
      </div>

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
        <GMButton variant="secondary" onClick={onClose}>Cancelar</GMButton>
        <GMButton variant="primary" icon="check" onClick={submit}>Confirmar resgate</GMButton>
      </div>
    </GMModalShell>
  );
}

window.AporteModal = AporteModal;
window.NewInvestmentModal = NewInvestmentModal;
window.UpdateValueModal = UpdateValueModal;
window.EditHoldingModal = EditHoldingModal;
window.RedeemHoldingModal = RedeemHoldingModal;
window.GMModalShell = GMModalShell;
window.gmInput = gmInput;
window.gmLabel = gmLabel;
