// Finance screen — wallet, transactions, charts, cofrinhos

const FinanceScreen = ({ state, setState, navigate, showToast }) => {
  const { finance } = state;
  const [tab, setTab] = React.useState('geral');
  const [hideValues, setHideValues] = React.useState(false);
  const [showNew, setShowNew] = React.useState(false);
  const [showNewCofrinho, setShowNewCofrinho] = React.useState(false);
  const [showAnalise, setShowAnalise] = React.useState(false);
  const [showNewCard, setShowNewCard] = React.useState(false);

  const addCard = (card) => {
    setState(s => ({
      ...s,
      finance: {
        ...s.finance,
        cards: [...(s.finance.cards || []), { ...card, id: 'card' + Date.now(), fatura: 0 }],
      }
    }));
    setShowNewCard(false);
    showToast('Cartão adicionado');
  };

  const deleteCard = (cardId) => {
    if (!window.confirm || window.confirm('Excluir este cartão? As transações registradas continuam no histórico.')) {
      setState(s => ({
        ...s,
        finance: {
          ...s.finance,
          cards: (s.finance.cards || []).filter(c => c.id !== cardId),
        }
      }));
      showToast('Cartão removido');
    }
  };

  const addCofrinho = (cof) => {
    setState(s => ({
      ...s,
      finance: { ...s.finance, cofrinhos: [...s.finance.cofrinhos, { ...cof, id: 'c' + Date.now(), saved: 0 }] }
    }));
    setShowNewCofrinho(false);
    showToast('Cofrinho criado');
  };

  const addTransaction = (tx) => {
    const value = (tx.type === 'gasto' ? -1 : 1) * Math.abs(Number((tx.value || '0').toString().replace(',', '.')) || 0);
    setState(s => ({
      ...s,
      finance: {
        ...s.finance,
        saldo: s.finance.saldo + value,
        entradas: value > 0 ? s.finance.entradas + value : s.finance.entradas,
        saidas: value < 0 ? s.finance.saidas + Math.abs(value) : s.finance.saidas,
        transactions: [
          { id: 'tx' + Date.now(), title: tx.desc || (tx.type === 'gasto' ? 'Saída' : 'Entrada'), cat: 'outros', value, time: 'agora', icon: tx.type === 'gasto' ? 'arrowUp' : 'arrowDown' },
          ...s.finance.transactions,
        ],
      }
    }));
    setShowNew(false);
    showToast('Movimentação adicionada');
  };

  const fmt = (v) => {
    if (hideValues) return '••••';
    return `R$ ${Math.abs(v).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  // Intent: abrir modal de nova movimentação via evento global
  React.useEffect(() => {
    const handler = () => setShowNew(true);
    window.addEventListener('cdv:open-new-transaction', handler);
    return () => window.removeEventListener('cdv:open-new-transaction', handler);
  }, []);

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Finanças" subtitle="JUNHO DE 2026" right={
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setHideValues(!hideValues)} style={{
            background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, width: 38, height: 38, borderRadius: 99,
            color: CDV.textDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name={hideValues ? 'eyeOff' : 'eye'} size={18} /></button>
          <button onClick={() => setShowNew(true)} style={{
            background: CDV.brandGrad, border: 'none', width: 38, height: 38, borderRadius: 99,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
          }}><Icon name="plus" size={18} /></button>
        </div>
      } />

      {/* Balance hero card */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 22, borderRadius: 26, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, #1B1A25 0%, #25223A 100%)',
          border: `1px solid ${CDV.strokeHi}`,
        }}>
          <div style={{
            position: 'absolute', top: -60, right: -40, width: 220, height: 220, borderRadius: 99,
            background: 'radial-gradient(circle, rgba(94,227,168,0.18), transparent 70%)',
            filter: 'blur(30px)',
          }} />
          <div style={{ position: 'relative' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Saldo total</div>
              <Pill color={CDV.mint} size="sm">
                <Icon name="arrowUp" size={10} /> +12% este mês
              </Pill>
            </div>
            <div style={{ fontSize: 38, fontWeight: 700, marginTop: 8, letterSpacing: -1, fontFamily: 'inherit' }}>
              {fmt(finance.saldo)}
            </div>
            <div style={{ display: 'flex', gap: 14, marginTop: 18 }}>
              <FinSplit label="Entradas" value={fmt(finance.entradas)} color={CDV.mint} icon="arrowDown" iconRot={180} />
              <div style={{ width: 1, background: CDV.stroke }} />
              <FinSplit label="Saídas" value={fmt(finance.saidas)} color={CDV.coral} icon="arrowUp" iconRot={180} />
            </div>
          </div>
        </div>
      </div>

      {/* Tab switcher */}
      <div style={{ padding: '0 22px 14px', display: 'flex', gap: 6 }}>
        {[
          { id: 'geral', label: 'Geral' },
          { id: 'cartao', label: 'Cartão' },
          { id: 'cofrinhos', label: 'Cofrinhos' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            flex: 1, height: 36, borderRadius: 12,
            background: tab === t.id ? CDV.surfaceHi : 'transparent',
            color: tab === t.id ? CDV.text : CDV.textDim,
            border: `1px solid ${tab === t.id ? CDV.strokeHi : 'transparent'}`,
            fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'geral' && (
        <>
          {/* Spending by category */}
          <SectionHeader title="Gastos por categoria" action="Análise →" onAction={() => setShowAnalise(true)} />
          <div style={{ padding: '0 22px 18px' }}>
            <Card padding={18}>
              <SpendingChart cats={finance.categoriaGastos} hideValues={hideValues} />
            </Card>
          </div>

          {/* AI insight */}
          <div style={{ padding: '0 22px 18px' }}>
            <div style={{
              padding: 14, borderRadius: 16,
              background: 'linear-gradient(135deg, rgba(255,181,71,0.10), rgba(255,122,107,0.08))',
              border: `1px solid ${CDV.amber}30`,
              display: 'flex', gap: 12, alignItems: 'flex-start',
            }}>
              <div style={{
                width: 34, height: 34, borderRadius: 10, background: CDV.amberSoft,
                display: 'flex', alignItems: 'center', justifyContent: 'center', color: CDV.amber, flexShrink: 0,
              }}><Icon name="insight" size={18} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: CDV.amber, letterSpacing: 0.4, textTransform: 'uppercase' }}>Alerta da IA</div>
                <div style={{ fontSize: 13, color: CDV.text, marginTop: 4, lineHeight: 1.4 }}>
                  Você gastou <b>23% a mais com iFood</b> esta semana. Posso te sugerir um teto semanal de R$ 200?
                </div>
              </div>
            </div>
          </div>

          {/* Recent transactions */}
          <SectionHeader title="Últimas movimentações" action="Ver todas" />
          <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 6 }}>
            {finance.transactions.map(tx => (
              <TransactionRow key={tx.id} tx={tx} hide={hideValues} />
            ))}
          </div>
        </>
      )}

      {tab === 'cartao' && <CardTab finance={finance} hide={hideValues} fmt={fmt} onAdd={() => setShowNewCard(true)} onDelete={deleteCard} />}
      {tab === 'cofrinhos' && <CofrinhosTab cofrinhos={finance.cofrinhos} hide={hideValues} onAdd={() => setShowNewCofrinho(true)} />}

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Nova movimentação">
        <NewTransactionForm onDone={addTransaction} />
      </Sheet>

      <Sheet open={showNewCofrinho} onClose={() => setShowNewCofrinho(false)} title="Novo cofrinho">
        <NewCofrinhoForm onSubmit={addCofrinho} />
      </Sheet>

      <Sheet open={showAnalise} onClose={() => setShowAnalise(false)} title="Análise detalhada">
        <AnaliseGastos finance={finance} hide={hideValues} />
      </Sheet>

      <Sheet open={showNewCard} onClose={() => setShowNewCard(false)} title="Adicionar cartão">
        <NewCardForm onSubmit={addCard} />
      </Sheet>
    </div>
  );
};

const NewCofrinhoForm = ({ onSubmit }) => {
  const [name, setName] = React.useState('');
  const [target, setTarget] = React.useState('');
  const icons = ['plane', 'car', 'shield', 'home', 'star', 'book'];
  const colors = ['#FF8FB1', '#6FB8FF', '#5EE3A8', '#FFB547', '#B197FC', '#FF7A6B'];
  const [icon, setIcon] = React.useState(icons[0]);
  const [color, setColor] = React.useState(colors[0]);
  const canSave = name.trim() && Number(target) > 0;
  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Nome do cofrinho (ex: Viagem)"
        style={{ width: '100%', height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 15, outline: 'none', fontFamily: 'inherit', marginBottom: 12 }} />

      <div style={{ background: CDV.surfaceHi, borderRadius: 14, padding: 14, marginBottom: 12, textAlign: 'center' }}>
        <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600 }}>META</div>
        <input value={target} onChange={e => setTarget(e.target.value.replace(/[^\d]/g, ''))} placeholder="0"
          style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', color, fontSize: 34, fontWeight: 700, textAlign: 'center', marginTop: 4, fontFamily: 'inherit' }} />
        <div style={{ fontSize: 12, color: CDV.textDim }}>R$</div>
      </div>

      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Ícone</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        {icons.map(ic => (
          <button key={ic} onClick={() => setIcon(ic)} style={{
            width: 46, height: 46, borderRadius: 12,
            background: icon === ic ? color + '24' : CDV.surfaceHi,
            border: `1.5px solid ${icon === ic ? color : CDV.stroke}`,
            color: icon === ic ? color : CDV.textDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name={ic} size={18} /></button>
        ))}
      </div>

      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Cor</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
        {colors.map(c => (
          <button key={c} onClick={() => setColor(c)} style={{
            width: 34, height: 34, borderRadius: 99, background: c,
            border: color === c ? `2.5px solid ${CDV.text}` : '2.5px solid transparent',
          }} />
        ))}
      </div>

      <button onClick={() => canSave && onSubmit({ name, target: Number(target), icon, color })} style={{
        width: '100%', height: 54, borderRadius: 16, background: CDV.brandGrad,
        border: 'none', color: '#fff', fontWeight: 600, fontSize: 15, opacity: canSave ? 1 : 0.4,
      }}>Criar cofrinho</button>
    </div>
  );
};

const AnaliseGastos = ({ finance, hide }) => {
  const total = finance.categoriaGastos.reduce((a, b) => a + b.value, 0);
  const top = [...finance.categoriaGastos].sort((a, b) => b.value - a.value);
  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <div style={{ padding: 18, borderRadius: 18, background: CDV.surfaceHi, marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600 }}>TOTAL DO MÊS</div>
        <div style={{ fontSize: 32, fontWeight: 700, color: CDV.text, letterSpacing: -0.5, marginTop: 4 }}>
          {hide ? '••••' : `R$ ${total.toLocaleString('pt-BR')}`}
        </div>
        <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>
          Média diária: {hide ? '••••' : `R$ ${Math.round(total / 30).toLocaleString('pt-BR')}`}
        </div>
      </div>

      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
        Ranking por categoria
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {top.map((c, i) => (
          <div key={c.cat} style={{ background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 14, padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: c.color + '22', color: c.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700 }}>{i + 1}</div>
              <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: CDV.text }}>{c.cat}</div>
              <div style={{ fontSize: 14, fontWeight: 700, color: CDV.text }}>{hide ? '••••' : `R$ ${c.value.toLocaleString('pt-BR')}`}</div>
            </div>
            <ProgressBar percent={c.percent} color={c.color} height={4} />
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 6 }}>{c.percent}% do total</div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 14, padding: 14, borderRadius: 14, background: 'linear-gradient(135deg, rgba(255,181,71,0.10), rgba(255,122,107,0.06))', border: `1px solid ${CDV.amber}30` }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: CDV.amber, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 4 }}>Observação</div>
        <div style={{ fontSize: 13, color: CDV.text, lineHeight: 1.4 }}>
          Sua maior categoria ({top[0].cat}) representa {top[0].percent}% do total. Cortar 10% aqui sobraria {hide ? '••' : `R$ ${Math.round(top[0].value * 0.1)}`} no mês.
        </div>
      </div>
    </div>
  );
};

const FinSplit = ({ label, value, color, icon, iconRot }) => (
  <div style={{ flex: 1 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ width: 22, height: 22, borderRadius: 7, background: color + '20', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={11} color={color} />
      </div>
      <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600 }}>{label}</div>
    </div>
    <div style={{ fontSize: 17, fontWeight: 600, marginTop: 4, color: CDV.text, letterSpacing: -0.3 }}>{value}</div>
  </div>
);

const SpendingChart = ({ cats, hideValues }) => {
  const total = cats.reduce((a, b) => a + b.value, 0);
  const ringSize = 130;
  const stroke = 22;
  const r = (ringSize - stroke) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
      <div style={{ position: 'relative', width: ringSize, height: ringSize, flexShrink: 0 }}>
        <svg width={ringSize} height={ringSize} style={{ transform: 'rotate(-90deg)' }}>
          <circle cx={ringSize / 2} cy={ringSize / 2} r={r} stroke={CDV.surfaceHi} strokeWidth={stroke} fill="none" />
          {cats.map((cat, i) => {
            const len = (cat.percent / 100) * c;
            const o = c - offset - len;
            offset += len;
            return (
              <circle key={i} cx={ringSize / 2} cy={ringSize / 2} r={r}
                stroke={cat.color} strokeWidth={stroke} fill="none"
                strokeDasharray={`${len} ${c}`} strokeDashoffset={-(offset - len)}
                style={{ transition: 'stroke-dashoffset .6s' }} />
            );
          })}
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Mês</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text }}>{hideValues ? '••••' : 'R$ ' + total.toLocaleString('pt-BR')}</div>
        </div>
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7 }}>
        {cats.map((cat, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 8, height: 8, borderRadius: 99, background: cat.color }} />
            <div style={{ flex: 1, fontSize: 12, color: CDV.text }}>{cat.cat}</div>
            <div style={{ fontSize: 12, fontWeight: 600, color: CDV.textDim }}>{cat.percent}%</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const TransactionRow = ({ tx, hide }) => {
  const color = CDV.cats[tx.cat] || CDV.brand;
  const pos = tx.value > 0;
  const valueColor = pos ? CDV.mint : CDV.coral;
  return (
    <div style={{
      padding: 12, paddingLeft: 14, borderRadius: 14,
      background: `linear-gradient(135deg, ${color}0d 0%, ${CDV.surface} 50%)`,
      border: `1px solid ${color}1f`,
      display: 'flex', alignItems: 'center', gap: 12,
      position: 'relative', overflow: 'hidden',
      boxShadow: `0 4px 14px -10px ${color}40`,
    }}>
      <div style={{
        position: 'absolute', left: 0, top: 12, bottom: 12, width: 3, borderRadius: 99,
        background: `linear-gradient(180deg, ${color}, ${color}40)`,
        boxShadow: `0 0 10px ${color}70`,
      }} />
      <IconTile name={tx.icon} color={color} size={38} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: CDV.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tx.title}</div>
        <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2, textTransform: 'capitalize' }}>{tx.cat} · {tx.time}</div>
      </div>
      <div style={{
        fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
        backgroundImage: `linear-gradient(135deg, ${valueColor}, ${valueColor}99)`,
        WebkitBackgroundClip: 'text', backgroundClip: 'text',
        WebkitTextFillColor: 'transparent', color: 'transparent',
      }}>
        {hide ? '••••' : `${pos ? '+' : '−'} R$ ${Math.abs(tx.value).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`}
      </div>
    </div>
  );
};

// Constrói lista de cartões: usa state.finance.cards, e se vazio mas tiver
// dados legados (cartao/cartaoLimite/vencimento), mostra como fallback.
function getCards(finance) {
  if (Array.isArray(finance.cards) && finance.cards.length > 0) return finance.cards;
  if (finance.cartao && finance.cartaoLimite) {
    return [{
      id: '_legacy',
      apelido: 'Cartão principal',
      bandeira: 'mastercard',
      cor: '#2A1B4A',
      corGrad: 'linear-gradient(135deg, #2A1B4A 0%, #4A1B33 100%)',
      limite: finance.cartaoLimite,
      fatura: finance.cartao,
      vencimento: finance.vencimento,
      digitos: '••••',
    }];
  }
  return [];
}

const CardTab = ({ finance, hide, fmt, onAdd, onDelete }) => {
  const cards = getCards(finance);
  return (
    <div style={{ padding: '0 22px 18px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>
          Seus cartões {cards.length > 0 && `· ${cards.length}`}
        </div>
        <button onClick={onAdd} style={{
          background: CDV.brandGrad, border: 'none', padding: '6px 12px', borderRadius: 99,
          color: '#fff', fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
        }}>
          <Icon name="plus" size={12} /> Cartão
        </button>
      </div>

      {cards.length === 0 ? (
        <div style={{
          padding: 28, borderRadius: 18, background: CDV.surface, border: `1px dashed ${CDV.stroke}`,
          textAlign: 'center', color: CDV.textDim, fontSize: 13, marginBottom: 16,
        }}>
          <div style={{ width: 60, height: 60, borderRadius: 16, background: CDV.brandSoft, margin: '0 auto 12px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: CDV.brand }}>
            <Icon name="wallet" size={28} />
          </div>
          <div style={{ color: CDV.text, fontWeight: 600, marginBottom: 4 }}>Nenhum cartão cadastrado</div>
          <div>Adicione seus cartões pra acompanhar fatura e limite.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 16 }}>
          {cards.map(c => (
            <CreditCardItem key={c.id} card={c} hide={hide} fmt={fmt} onDelete={c.id === '_legacy' ? null : () => onDelete(c.id)} />
          ))}
        </div>
      )}

      <SectionHeader title="Próximas faturas previstas" />
      {[
        { mes: 'Julho 2026', val: 2840, status: 'previsto' },
        { mes: 'Agosto 2026', val: 2200, status: 'previsto' },
      ].map((p, i) => (
        <div key={i} style={{
          padding: 14, borderRadius: 14, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
          display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8,
        }}>
          <IconTile name="calendar" color={CDV.brand} size={36} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{p.mes}</div>
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>Previsão da IA</div>
          </div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{fmt(p.val)}</div>
        </div>
      ))}
    </div>
  );
};

const CreditCardItem = ({ card, hide, fmt, onDelete }) => {
  const usedPct = card.limite > 0 ? (card.fatura / card.limite) * 100 : 0;
  const grad = card.corGrad || `linear-gradient(135deg, ${card.cor} 0%, ${card.cor}cc 100%)`;
  return (
    <div style={{
      padding: 22, borderRadius: 22,
      background: grad,
      border: `1px solid ${CDV.strokeHi}`,
      height: 200, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: -40, right: -40, width: 200, height: 200, borderRadius: 99,
        background: 'radial-gradient(circle, rgba(255,255,255,0.18), transparent 60%)', filter: 'blur(20px)',
      }} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', fontWeight: 600 }}>Fatura atual</div>
            <div style={{ fontSize: 28, fontWeight: 700, marginTop: 4, color: '#fff', letterSpacing: -0.5 }}>
              {fmt(card.fatura || 0)}
            </div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>
              {card.apelido} · {bandeiraLabel(card.bandeira)} {card.digitos && `· •• ${card.digitos}`}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
            <Icon name="wallet" size={22} color="rgba(255,255,255,0.55)" />
            {onDelete && (
              <button onClick={onDelete} style={{
                background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
                color: '#fff', width: 28, height: 28, borderRadius: 8,
                display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
                fontSize: 14,
              }}>×</button>
            )}
          </div>
        </div>
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'rgba(255,255,255,0.7)', marginBottom: 6 }}>
            <div>Usado {hide ? '••' : `${Math.round(usedPct)}%`}</div>
            <div>Limite {fmt(card.limite || 0)}</div>
          </div>
          <ProgressBar percent={usedPct} gradient="linear-gradient(90deg, #FFB547, #FF7A6B)" height={5} />
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', marginTop: 10 }}>
            Vence {typeof card.vencimento === 'number' ? `dia ${card.vencimento}` : card.vencimento || '—'}
          </div>
        </div>
      </div>
    </div>
  );
};

function bandeiraLabel(b) {
  const map = { visa: 'Visa', mastercard: 'Mastercard', elo: 'Elo', amex: 'Amex', hipercard: 'Hipercard', outra: 'Outro' };
  return map[b] || 'Cartão';
}

const NewCardForm = ({ onSubmit }) => {
  const [apelido, setApelido] = React.useState('');
  const [digitos, setDigitos] = React.useState('');
  const [bandeira, setBandeira] = React.useState('mastercard');
  const [limite, setLimite] = React.useState('');
  const [vencimento, setVencimento] = React.useState('10');
  const [cor, setCor] = React.useState('#2A1B4A');

  const presets = [
    { name: 'Nubank', cor: '#820AD1' },
    { name: 'Itaú', cor: '#EC7000' },
    { name: 'Bradesco', cor: '#CC092F' },
    { name: 'Santander', cor: '#EC0000' },
    { name: 'BB', cor: '#FAE128' },
    { name: 'C6', cor: '#222328' },
    { name: 'Inter', cor: '#FF7A00' },
    { name: 'Roxo', cor: '#2A1B4A' },
  ];
  const bandeiras = ['visa', 'mastercard', 'elo', 'amex', 'hipercard', 'outra'];

  const canSave = apelido.trim() && digitos.length === 4 && Number(limite) > 0;

  return (
    <div style={{ padding: '12px 22px 28px' }}>
      {/* Preview */}
      <div style={{
        padding: 18, borderRadius: 18, marginBottom: 16, height: 140,
        background: `linear-gradient(135deg, ${cor} 0%, ${cor}cc 100%)`,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>{apelido || 'Apelido do cartão'}</div>
            <div style={{ fontSize: 13, color: '#fff', fontWeight: 600, marginTop: 4 }}>
              {bandeiraLabel(bandeira)}
            </div>
          </div>
          <Icon name="wallet" size={22} color="rgba(255,255,255,0.55)" />
        </div>
        <div style={{ position: 'absolute', bottom: 18, left: 18, fontSize: 16, color: '#fff', letterSpacing: 2, fontWeight: 600 }}>
          •••• •••• •••• {digitos || '••••'}
        </div>
      </div>

      <input value={apelido} onChange={e => setApelido(e.target.value)} placeholder="Apelido (ex: Nubank pessoal)"
        style={{ width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14, outline: 'none', fontFamily: 'inherit', marginBottom: 10 }} />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
        <input value={digitos} onChange={e => setDigitos(e.target.value.replace(/[^\d]/g, '').slice(0, 4))} placeholder="Últimos 4 dígitos" inputMode="numeric"
          style={{ height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14, outline: 'none', fontFamily: 'inherit', letterSpacing: 2 }} />
        <input value={vencimento} onChange={e => setVencimento(e.target.value.replace(/[^\d]/g, '').slice(0, 2))} placeholder="Vencimento (dia)" inputMode="numeric"
          style={{ height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14, outline: 'none', fontFamily: 'inherit' }} />
      </div>

      <input value={limite} onChange={e => setLimite(e.target.value.replace(/[^\d.,]/g, ''))} placeholder="Limite total (R$)" inputMode="decimal"
        style={{ width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14, outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />

      <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Bandeira</div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        {bandeiras.map(b => {
          const active = bandeira === b;
          return (
            <button key={b} onClick={() => setBandeira(b)} style={{
              padding: '8px 12px', borderRadius: 99,
              background: active ? CDV.brandSoft : CDV.surfaceHi,
              border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
              color: active ? CDV.brand : CDV.textDim,
              fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
            }}>{bandeiraLabel(b)}</button>
          );
        })}
      </div>

      <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Cor do banco</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
        {presets.map(p => (
          <button key={p.cor} onClick={() => setCor(p.cor)} title={p.name} style={{
            width: 38, height: 38, borderRadius: 12, background: p.cor,
            border: cor === p.cor ? `2.5px solid ${CDV.text}` : `2.5px solid transparent`,
            cursor: 'pointer',
          }} />
        ))}
      </div>

      <button onClick={() => canSave && onSubmit({
        apelido,
        digitos,
        bandeira,
        limite: Number((limite || '0').replace(',', '.')),
        vencimento: vencimento ? Number(vencimento) : null,
        cor,
      })} style={{
        width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
        opacity: canSave ? 1 : 0.4, cursor: canSave ? 'pointer' : 'not-allowed',
      }}>Salvar cartão</button>

      <div style={{ marginTop: 12, fontSize: 11, color: CDV.textMuted, textAlign: 'center', lineHeight: 1.5 }}>
        Não armazenamos número completo nem CVV — apenas os últimos 4 dígitos pra você identificar.
      </div>
    </div>
  );
};

const CofrinhosTab = ({ cofrinhos, hide, onAdd }) => (
  <div style={{ padding: '0 22px 18px' }}>
    <SectionHeader title="Seus cofrinhos" action="+ Novo cofrinho" onAction={onAdd} />
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {cofrinhos.map(c => {
        const pct = (c.saved / c.target) * 100;
        return (
          <div key={c.id} style={{
            padding: 16, paddingLeft: 18, borderRadius: 18,
            background: `linear-gradient(135deg, ${c.color}14 0%, ${c.color}04 40%, ${CDV.surface} 100%)`,
            border: `1px solid ${c.color}2c`,
            position: 'relative', overflow: 'hidden',
            boxShadow: `0 6px 18px -10px ${c.color}50`,
          }}>
            <div style={{
              position: 'absolute', top: -30, right: -30, width: 120, height: 120, borderRadius: 99,
              background: `radial-gradient(circle, ${c.color}55, transparent 60%)`,
              filter: 'blur(22px)', opacity: 0.55, pointerEvents: 'none',
            }} />
            <div style={{
              position: 'absolute', left: 0, top: 14, bottom: 14, width: 3, borderRadius: 99,
              background: `linear-gradient(180deg, ${c.color}, ${c.color}40)`,
              boxShadow: `0 0 12px ${c.color}80`,
            }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
              <div style={{
                width: 46, height: 46, borderRadius: 14,
                background: `linear-gradient(135deg, ${c.color}38, ${c.color}14)`,
                border: `1px solid ${c.color}30`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', color: c.color,
                boxShadow: `0 8px 18px -8px ${c.color}80, inset 0 0 0 1px rgba(255,255,255,0.06)`,
              }}><Icon name={c.icon} size={22} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{c.name}</div>
                <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>
                  {hide ? '••••' : `R$ ${c.saved.toLocaleString('pt-BR')} de R$ ${c.target.toLocaleString('pt-BR')}`}
                </div>
              </div>
              <ProgressRing percent={pct} size={44} stroke={4} color={c.color}>
                <div style={{ fontSize: 11, fontWeight: 700, color: c.color }}>{Math.round(pct)}%</div>
              </ProgressRing>
            </div>
            <div style={{ marginTop: 14 }}>
              <ProgressBar percent={pct} color={c.color} height={5} />
            </div>
          </div>
        );
      })}
    </div>
  </div>
);

const NewTransactionForm = ({ onDone }) => {
  const [type, setType] = React.useState('gasto');
  const [value, setValue] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const submit = () => {
    if (typeof onDone === 'function') {
      onDone({ type, value, desc });
    }
  };
  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
        {[{ id: 'gasto', label: 'Saída', c: CDV.coral }, { id: 'receita', label: 'Entrada', c: CDV.mint }].map(t => (
          <button key={t.id} onClick={() => setType(t.id)} style={{
            flex: 1, height: 48, borderRadius: 14,
            background: type === t.id ? t.c + '22' : CDV.surfaceHi,
            border: `1.5px solid ${type === t.id ? t.c : CDV.stroke}`,
            color: type === t.id ? t.c : CDV.textDim,
            fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
          }}>{t.label}</button>
        ))}
      </div>
      <div style={{
        padding: 24, borderRadius: 18, background: CDV.surfaceHi, textAlign: 'center', marginBottom: 12,
      }}>
        <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600 }}>VALOR</div>
        <input value={value} onChange={e => setValue(e.target.value)} placeholder="0,00"
          style={{
            border: 'none', outline: 'none', background: 'transparent',
            color: type === 'gasto' ? CDV.coral : CDV.mint, fontSize: 40, fontWeight: 700,
            textAlign: 'center', width: '100%', marginTop: 6, fontFamily: 'inherit',
          }} />
        <div style={{ fontSize: 13, color: CDV.textDim, marginTop: 2 }}>R$</div>
      </div>
      <input value={desc} onChange={e => setDesc(e.target.value)} placeholder="Descrição"
        style={{
          width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
          background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14,
          outline: 'none', fontFamily: 'inherit', marginBottom: 10,
        }} />
      <div style={{ fontSize: 12, color: CDV.brand, display: 'flex', alignItems: 'center', gap: 4, marginBottom: 16 }}>
        <Icon name="sparkle" size={12} /> A categoria será detectada automaticamente
      </div>
      <button onClick={submit} style={{
        width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
      }}>Salvar</button>
    </div>
  );
};

Object.assign(window, { FinanceScreen });
