// Widget Gastei/Recebi — usado tanto no hero (mockup mobile) quanto na seção interativa

const CATEGORIAS = [
  { id: 'mercado', label: 'Supermercado', icon: 'Cart' },
  { id: 'alimentacao', label: 'Alimentação', icon: 'Coffee' },
  { id: 'transporte', label: 'Transporte', icon: 'Bolt' },
  { id: 'lazer', label: 'Lazer', icon: 'Heart' },
  { id: 'vestuario', label: 'Vestuário', icon: 'Bag' },
  { id: 'saude', label: 'Saúde', icon: 'Heart' },
];

const PAGAMENTOS = [
  { id: 'pix', label: 'Pix', icon: 'Bolt' },
  { id: 'credito', label: 'Cartão de crédito', icon: 'Card' },
  { id: 'debito', label: 'Cartão de débito', icon: 'Card' },
  { id: 'dinheiro', label: 'Dinheiro', icon: 'Wallet' },
  { id: 'boleto', label: 'Boleto', icon: 'Receipt' },
  { id: 'transferencia', label: 'Transferência bancária', icon: 'Bank' },
];

function formatBRL(n) {
  return n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function WidgetGasteiRecebi({ onRegister, compact = false, defaultTab = 'gastei' }) {
  const [tab, setTab] = React.useState(defaultTab);
  const [valor, setValor] = React.useState('');
  const [pagamento, setPagamento] = React.useState(PAGAMENTOS[0]);
  const [categoria, setCategoria] = React.useState(null);
  const [descricao, setDescricao] = React.useState('');
  const [recorrente, setRecorrente] = React.useState(false);
  const [parcelada, setParcelada] = React.useState(false);
  const [openPag, setOpenPag] = React.useState(false);
  const [openCat, setOpenCat] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  const handleValor = (e) => {
    const raw = e.target.value.replace(/\D/g, '');
    if (!raw) { setValor(''); return; }
    const cents = parseInt(raw, 10) / 100;
    setValor(cents.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
  };

  const valorNumber = valor ? parseFloat(valor.replace(/\./g, '').replace(',', '.')) : 0;
  const isValid = valorNumber > 0;

  const handleSubmit = () => {
    if (!isValid) return;
    setSuccess(true);
    if (onRegister) onRegister({ tipo: tab, valor: valorNumber, pagamento, categoria, descricao });
    setTimeout(() => {
      setValor(''); setDescricao(''); setCategoria(null); setRecorrente(false); setParcelada(false);
      setSuccess(false);
    }, 1800);
  };

  const isGastei = tab === 'gastei';
  const accent = isGastei ? '#50D080' : '#50D080';

  return (
    <div style={{
      background: 'var(--purple)',
      borderRadius: compact ? 18 : 22,
      padding: compact ? 14 : 18,
      boxShadow: '0 0 0 1px rgba(255,255,255,0.06) inset',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Tabs */}
      <div style={{
        display: 'flex',
        background: 'rgba(0,0,0,0.18)',
        borderRadius: 999,
        padding: 4,
        marginBottom: compact ? 12 : 14,
      }}>
        {['gastei', 'recebi'].map(t => (
          <button
            key={t}
            onClick={() => setTab(t)}
            style={{
              flex: 1,
              padding: compact ? '8px 12px' : '10px 16px',
              borderRadius: 999,
              fontSize: compact ? 13 : 14,
              fontWeight: 600,
              color: 'white',
              background: tab === t ? 'rgba(255,255,255,0.18)' : 'transparent',
              transition: 'background 0.2s',
            }}
          >
            {t === 'gastei' ? 'Gastei' : 'Recebi'}
          </button>
        ))}
      </div>

      {/* Valor */}
      <div style={{
        background: 'white',
        borderRadius: 12,
        padding: compact ? '12px 14px' : '14px 16px',
        marginBottom: 8,
        display: 'flex',
        alignItems: 'center',
        gap: 8,
      }}>
        <span style={{ color: valor ? 'var(--ink)' : 'var(--ink-4)', fontWeight: 500, fontSize: compact ? 14 : 15 }}>R$</span>
        <input
          type="text"
          inputMode="decimal"
          placeholder="Valor..."
          value={valor}
          onChange={handleValor}
          className="mono"
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontSize: compact ? 15 : 16,
            color: 'var(--ink)',
            fontWeight: 500,
          }}
        />
      </div>

      {/* Pago com */}
      <div style={{ position: 'relative', marginBottom: 8 }}>
        <button
          onClick={() => { setOpenPag(v => !v); setOpenCat(false); }}
          style={{
            width: '100%',
            background: 'white',
            borderRadius: 12,
            padding: compact ? '12px 14px' : '14px 16px',
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            fontSize: compact ? 13.5 : 14.5,
            color: 'var(--ink-2)',
            fontWeight: 500,
            border: 'none',
            textAlign: 'left',
          }}
        >
          {(() => { const I = Icon[pagamento.icon] || Icon.Card; return <I size={18} color="var(--purple)" />; })()}
          <span style={{ flex: 1 }}>{pagamento.label}</span>
          <Icon.ChevronDown size={16} color="var(--ink-3)" />
        </button>
        {openPag && (
          <div style={{
            position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4,
            background: 'white', borderRadius: 12, padding: 6, zIndex: 10,
            boxShadow: '0 12px 24px rgba(0,0,0,0.15)',
          }}>
            {PAGAMENTOS.map(p => {
              const I = Icon[p.icon] || Icon.Card;
              return (
                <button key={p.id} onClick={() => { setPagamento(p); setOpenPag(false); }} style={{
                  width: '100%', textAlign: 'left', padding: '10px 12px', fontSize: 14,
                  color: 'var(--ink-2)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10,
                  background: pagamento.id === p.id ? 'var(--purple-tint)' : 'transparent',
                }}>
                  <I size={16} color="var(--purple)" />
                  {p.label}
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Categoria */}
      <div style={{ position: 'relative', marginBottom: 8 }}>
        <button
          onClick={() => { setOpenCat(v => !v); setOpenPag(false); }}
          style={{
            width: '100%',
            background: 'white',
            borderRadius: 12,
            padding: compact ? '12px 14px' : '14px 16px',
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            fontSize: compact ? 13.5 : 14.5,
            color: categoria ? 'var(--ink-2)' : 'var(--ink-4)',
            fontWeight: 500,
            border: 'none',
            textAlign: 'left',
          }}
        >
          <Icon.Receipt size={18} color="var(--purple)" />
          <span style={{ flex: 1 }}>{categoria ? categoria.label : 'Categoria'}</span>
          <Icon.ChevronDown size={16} color="var(--ink-3)" />
        </button>
        {openCat && (
          <div style={{
            position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4,
            background: 'white', borderRadius: 12, padding: 6, zIndex: 10,
            boxShadow: '0 12px 24px rgba(0,0,0,0.15)',
            maxHeight: 220, overflowY: 'auto',
          }} className="no-scrollbar">
            {CATEGORIAS.map(c => {
              const I = Icon[c.icon];
              return (
                <button key={c.id} onClick={() => { setCategoria(c); setOpenCat(false); }} style={{
                  width: '100%', textAlign: 'left', padding: '10px 12px', fontSize: 14,
                  color: 'var(--ink-2)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10,
                  background: categoria?.id === c.id ? 'var(--purple-tint)' : 'transparent',
                }}>
                  <I size={16} color="var(--purple)" />
                  {c.label}
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Descrição */}
      <input
        type="text"
        placeholder="Descrição (opcional)"
        value={descricao}
        onChange={(e) => setDescricao(e.target.value)}
        style={{
          width: '100%',
          background: 'white',
          borderRadius: 12,
          padding: compact ? '12px 14px' : '14px 16px',
          fontSize: compact ? 13.5 : 14.5,
          color: 'var(--ink)',
          fontWeight: 500,
          border: 'none',
          outline: 'none',
          marginBottom: 12,
          fontFamily: 'inherit',
        }}
      />

      {/* Toggles */}
      {!compact && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 12 }}>
          <Toggle label="Salvar como Despesa Recorrente" value={recorrente} onChange={setRecorrente} />
          <Toggle label="Salvar como compra parcelada" value={parcelada} onChange={setParcelada} />
        </div>
      )}

      {/* CTA */}
      <button
        onClick={handleSubmit}
        disabled={!isValid}
        style={{
          width: '100%',
          background: isValid ? '#50D080' : 'rgba(255,255,255,0.25)',
          color: 'white',
          padding: compact ? 12 : 14,
          borderRadius: 12,
          fontSize: compact ? 14 : 15,
          fontWeight: 600,
          opacity: isValid ? 1 : 0.7,
          transition: 'all 0.2s',
          cursor: isValid ? 'pointer' : 'not-allowed',
          boxShadow: isValid ? '0 4px 12px rgba(80, 208, 128, 0.4)' : 'none',
        }}
      >
        {success ? '✓ Registrado!' : `Registrar ${isGastei ? 'Gasto' : 'Recebimento'}`}
      </button>
    </div>
  );
}

function Toggle({ label, value, onChange }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
      <button
        type="button"
        role="switch"
        aria-checked={value}
        onClick={() => onChange(!value)}
        style={{
          width: 38, height: 22, borderRadius: 999,
          background: value ? '#50D080' : 'rgba(255,255,255,0.25)',
          position: 'relative',
          transition: 'background 0.2s',
          flexShrink: 0,
        }}
      >
        <span style={{
          position: 'absolute',
          top: 2, left: value ? 18 : 2,
          width: 18, height: 18,
          background: 'white',
          borderRadius: '50%',
          transition: 'left 0.2s',
        }} />
      </button>
      <span style={{ fontSize: 13.5, color: 'white', fontWeight: 500 }}>{label}</span>
    </label>
  );
}

window.WidgetGasteiRecebi = WidgetGasteiRecebi;
window.formatBRL = formatBRL;
