/* ================================================================
   Khronus — Financeiro (Controle de Pagamento)
   Versão simples: lançar, editar e marcar pagamentos. Mesmo vocabulário
   do Notion (Nome, Conta, Forma de pagamento, Valor, Vencimento,
   Frequência, Status) pra não exigir reaprendizado.
   ================================================================ */
const { useState, useEffect, useRef } = React;

const FIN_WORKER_URL = 'https://khronus-nf.blindagem-fmn.workers.dev';
const CONTAS = ['FeM', 'FMN', 'Pessoal Lígia', 'Pessoa Felipe', 'Família'];
const FORMAS_PAGAMENTO = ['Pix', 'Débito em conta', 'Débito', 'Crédito', 'Boleto', 'Dinheiro'];
const FREQUENCIAS = ['Única', 'Mensal', 'Anual'];

function hojeISO() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
function addMesesISO(iso, meses) {
  const [y, m, d] = iso.split('-').map(Number);
  const dt = new Date(y, m - 1 + meses, d);
  return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
}
function fmtDataBR(iso) {
  if (!iso) return '—';
  const [y, m, d] = iso.split('-');
  return `${d}/${m}/${y}`;
}
// Vencida é calculado (venceu e não foi pago), não é um status que se marca à mão.
function statusDe(p) {
  if (p.status === 'Pago') return 'Pago';
  if (p.vencimento && p.vencimento < hojeISO()) return 'Vencida';
  return 'Pagar';
}
const STATUS_BADGE_FIN = {
  'Pagar': { tone: 'info', label: 'A pagar' },
  'Vencida': { tone: 'danger', label: 'Vencida' },
  'Pago': { tone: 'success', label: 'Pago' },
};

// Detecta se o comprovante é imagem (pra decidir como pré-visualizar no modal).
function isImagemComprovante(url) {
  const ext = (url.split('?')[0].split('.').pop() || '').toLowerCase();
  return ['jpg', 'jpeg', 'png', 'webp', 'heic', 'gif'].includes(ext);
}

const inputStyle = {
  width: '100%', boxSizing: 'border-box', padding: '8px 12px', borderRadius: 'var(--r-sm)',
  background: 'var(--app-surface-2)', border: '1px solid var(--app-border)',
  color: 'var(--text-1)', fontFamily: 'Roboto, sans-serif', fontSize: 'var(--fs-lg)', outline: 'none',
};
function Campo({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 'var(--fs-xs)', fontFamily: 'Roboto, sans-serif', fontWeight: 700,
        letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-3)' }}>{label}</span>
      {children}
    </div>
  );
}
function Select({ value, onChange, opcoes, placeholder }) {
  return (
    <select value={value || ''} onChange={e => onChange(e.target.value)} style={inputStyle}>
      <option value="">{placeholder || 'Selecione'}</option>
      {opcoes.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

/* ── Campo de anexo (usado tanto pra Conta/boleto quanto pra Comprovante
   de pagamento) — mesmo arquivo pode ter os dois, cada um no seu campo. */
function AnexoCampo({ label, placeholder, arquivo, setArquivo, urlExistente, fileRef }) {
  return (
    <Campo label={label}>
      <input ref={fileRef} type="file" accept="application/pdf,image/*" style={{ display: 'none' }}
        onChange={e => setArquivo(e.target.files[0])} />
      <button onClick={() => fileRef.current.click()}
        style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderRadius: 'var(--r-sm)',
          background: 'var(--app-surface-2)', border: '1px dashed var(--app-border)',
          color: 'var(--text-2)', fontFamily: 'Roboto, sans-serif', fontSize: 'var(--fs-md)', cursor: 'pointer', width: '100%' }}>
        <LucideIcon icon="paperclip" size={15} />
        {arquivo ? arquivo.name : (urlExistente ? 'Já anexado — trocar arquivo' : placeholder)}
      </button>

      {(arquivo || urlExistente) && (() => {
        const previewUrl = arquivo ? URL.createObjectURL(arquivo) : urlExistente;
        const ehImagem = arquivo ? arquivo.type.startsWith('image/') : isImagemComprovante(urlExistente);
        return (
          <div style={{ marginTop: 8, borderRadius: 'var(--r-sm)', overflow: 'hidden', border: '1px solid var(--app-border)',
            background: 'rgba(0,0,0,.25)' }}>
            {ehImagem ? (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <img src={previewUrl} style={{ maxWidth: '100%', maxHeight: 260, objectFit: 'contain' }} />
              </div>
            ) : (
              <iframe src={previewUrl} title={label}
                style={{ width: '100%', height: 300, border: 'none', display: 'block' }} />
            )}
          </div>
        );
      })()}
    </Campo>
  );
}

/* ── Modal de lançar / editar pagamento ──────────────────────────*/
function PagamentoModal({ item, defaultVencimento, onClose, onSaved, onDelete }) {
  useEscapeToClose(onClose);
  const [form, setForm] = useState(() => item || {
    nome: '', conta: '', forma_pagamento: '', valor: '', vencimento: defaultVencimento || hojeISO(),
    frequencia: 'Única', status: 'Pagar', observacoes: '',
  });
  const [arquivoConta, setArquivoConta] = useState(null);
  const [arquivoComprovante, setArquivoComprovante] = useState(null);
  const [salvando, setSalvando] = useState(false);
  const [erro, setErro] = useState('');
  const fileContaRef = useRef(null);
  const fileComprovanteRef = useRef(null);
  const set = (campo, valor) => setForm(f => ({ ...f, [campo]: valor }));

  async function subirArquivo(chave, file) {
    const fd = new FormData();
    fd.append('chave', chave);
    fd.append('file', file, file.name);
    const res = await fetch(`${FIN_WORKER_URL}/upload-comprovante`, { method: 'POST', body: fd });
    const data = await res.json();
    if (!res.ok || !data.comprovante_url) throw new Error(data.error || 'Falha ao subir arquivo.');
    return data.comprovante_url;
  }

  async function handleSalvar() {
    if (!form.nome.trim()) { setErro('Dê um nome pro pagamento.'); return; }
    setSalvando(true); setErro('');
    try {
      const payload = {
        nome: form.nome.trim(),
        conta: form.conta || null,
        forma_pagamento: form.forma_pagamento || null,
        valor: form.valor ? Number(form.valor) : null,
        vencimento: form.vencimento || null,
        frequencia: form.frequencia || 'Única',
        status: form.status || 'Pagar',
        data_pagamento: form.status === 'Pago' ? (form.data_pagamento || hojeISO()) : (form.data_pagamento || null),
        observacoes: form.observacoes || null,
      };
      let id = item?.id;
      if (id) {
        if (arquivoConta) payload.conta_url = await subirArquivo(`${id}-conta`, arquivoConta);
        if (arquivoComprovante) payload.comprovante_url = await subirArquivo(`${id}-comprovante`, arquivoComprovante);
        const { error } = await window.db.from('crm_payments').update(payload).eq('id', id);
        if (error) throw error;
      } else {
        const { data, error } = await window.db.from('crm_payments').insert(payload).select().single();
        if (error) throw error;
        id = data.id;
        const extras = {};
        if (arquivoConta) extras.conta_url = await subirArquivo(`${id}-conta`, arquivoConta);
        if (arquivoComprovante) extras.comprovante_url = await subirArquivo(`${id}-comprovante`, arquivoComprovante);
        if (Object.keys(extras).length) await window.db.from('crm_payments').update(extras).eq('id', id);
      }
      onSaved();
    } catch (e) {
      setErro(e.message || String(e));
    } finally {
      setSalvando(false);
    }
  }

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.55)', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}
      onClick={onClose}>
      <div style={{ width: '100%', maxWidth: 460, maxHeight: '88vh', overflowY: 'auto',
        background: 'var(--app-surface)', border: '1px solid var(--app-border)',
        borderRadius: 'var(--r-xl)', padding: 22, display: 'flex', flexDirection: 'column', gap: 12 }}
        onClick={e => e.stopPropagation()}>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'Roboto, sans-serif', fontWeight: 900, fontSize: 'var(--fs-xl)', color: 'var(--text-1)' }}>
            {item?.id ? 'Editar pagamento' : 'Novo pagamento'}
          </span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)' }}>
            <LucideIcon icon="x" size={18} />
          </button>
        </div>

        <Campo label="Nome">
          <input style={inputStyle} value={form.nome} placeholder="Ex.: Energia Julho, Freela Amanda, Simples Nacional"
            onChange={e => set('nome', e.target.value)} />
        </Campo>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Campo label="Conta">
            <Select value={form.conta} onChange={v => set('conta', v)} opcoes={CONTAS} />
          </Campo>
          <Campo label="Forma de pagamento">
            <Select value={form.forma_pagamento} onChange={v => set('forma_pagamento', v)} opcoes={FORMAS_PAGAMENTO} />
          </Campo>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Campo label="Valor">
            <input type="number" step="0.01" style={inputStyle} value={form.valor} placeholder="0,00"
              onChange={e => set('valor', e.target.value)} />
          </Campo>
          <Campo label="Frequência">
            <Select value={form.frequencia} onChange={v => set('frequencia', v)} opcoes={FREQUENCIAS} />
          </Campo>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Campo label="Vencimento">
            <input type="date" style={inputStyle} value={form.vencimento || ''}
              onChange={e => set('vencimento', e.target.value)} />
          </Campo>
          <Campo label="Status">
            <Select value={form.status} onChange={v => set('status', v)} opcoes={['Pagar', 'Pago']} />
          </Campo>
        </div>

        <Campo label="Data do pagamento (preenche quando pago)">
          <input type="date" style={inputStyle} value={form.data_pagamento || (form.status === 'Pago' ? hojeISO() : '')}
            onChange={e => set('data_pagamento', e.target.value)} />
        </Campo>

        <Campo label="Observações (opcional)">
          <textarea rows={2} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.5 }}
            value={form.observacoes || ''} onChange={e => set('observacoes', e.target.value)} />
        </Campo>

        <AnexoCampo label="Conta (boleto/fatura, opcional)" placeholder="Anexar a conta (PDF ou imagem)"
          arquivo={arquivoConta} setArquivo={setArquivoConta} urlExistente={form.conta_url} fileRef={fileContaRef} />

        <AnexoCampo label="Comprovante de pagamento (opcional)" placeholder="Anexar comprovante (PDF ou imagem)"
          arquivo={arquivoComprovante} setArquivo={setArquivoComprovante} urlExistente={form.comprovante_url} fileRef={fileComprovanteRef} />

        {erro && (
          <div style={{ padding: '8px 12px', borderRadius: 'var(--r-sm)', background: 'rgba(248,113,113,.1)',
            border: '1px solid rgba(248,113,113,.25)', color: 'var(--clr-neg)', fontSize: 'var(--fs-md)' }}>{erro}</div>
        )}

        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginTop: 4 }}>
          {item?.id ? (
            <Btn variant="danger" icon="trash-2" onClick={() => onDelete(item)}>Excluir</Btn>
          ) : <span />}
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
            <Btn variant="primary" onClick={handleSalvar} disabled={salvando} icon={salvando ? undefined : 'check'}>
              {salvando ? 'Salvando…' : 'Salvar'}
            </Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Visualização em calendário ───────────────────────────────────
   Mesma base de grade do CalendarioView do Orgânico (organico.jsx):
   estado local de mês/ano, primeiro-dia-da-semana + dias-no-mês via
   Date, células vazias até fechar múltiplo de 7. Card por item troca
   o layout "ORG 003 + horário" do Orgânico por nome + status + valor,
   que é o que faz sentido pra um lançamento financeiro.
   Data de exibição: enquanto não foi pago, aparece no dia do
   vencimento; assim que marcado como pago, passa a aparecer no dia
   em que foi pago de fato (data_pagamento). Arrastar um card muda
   a data que está sendo exibida no momento (vencimento se ainda não
   pago, data_pagamento se já pago) — mesmo padrão de drag do
   Orgânico: draggable no card, onDragOver/onDrop na célula do dia. */
function dataExibicaoDe(p) {
  return (p.status === 'Pago' && p.data_pagamento) ? p.data_pagamento : p.vencimento;
}
const DIAS_SEMANA_FIN = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
const MESES_PT_FIN = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
  'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const STATUS_COLOR_FIN = { 'Pago': 'var(--clr-pos)', 'Vencida': 'var(--clr-neg)', 'Pagar': 'var(--clr-info)' };

function FinanceiroCalendario({ items, onOpen, onNewWithDate, onReschedule }) {
  const today = new Date();
  const [ano, setAno] = useState(today.getFullYear());
  const [mes, setMes] = useState(today.getMonth());
  const [dragId, setDragId] = useState(null);
  const [dragOverDate, setDragOverDate] = useState(null);

  const primeiroDia = new Date(ano, mes, 1).getDay();
  const diasNoMes = new Date(ano, mes + 1, 0).getDate();
  const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

  const byDate = {};
  items.forEach(p => {
    const dataRef = dataExibicaoDe(p);
    if (!dataRef) return;
    const d = dataRef.slice(0, 10);
    if (!byDate[d]) byDate[d] = [];
    byDate[d].push(p);
  });

  const prevMes = () => { if (mes === 0) { setMes(11); setAno(a => a - 1); } else setMes(m => m - 1); };
  const nextMes = () => { if (mes === 11) { setMes(0); setAno(a => a + 1); } else setMes(m => m + 1); };

  const cells = [];
  for (let i = 0; i < primeiroDia; i++) cells.push(null);
  for (let d = 1; d <= diasNoMes; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, padding: '8px 0 14px' }}>
        <button onClick={prevMes}
          style={{ width: 30, height: 30, borderRadius: 'var(--r-sm)', border: '1px solid var(--app-border)',
            background: 'var(--overlay-05)', color: 'var(--text-2)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <LucideIcon icon="chevron-left" size={16} />
        </button>
        <span style={{ fontSize: 'var(--fs-xl)', fontFamily: 'Roboto, sans-serif', fontWeight: 900,
          color: 'var(--text-1)', minWidth: 180, textAlign: 'center' }}>
          {MESES_PT_FIN[mes]} {ano}
        </span>
        <button onClick={nextMes}
          style={{ width: 30, height: 30, borderRadius: 'var(--r-sm)', border: '1px solid var(--app-border)',
            background: 'var(--overlay-05)', color: 'var(--text-2)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <LucideIcon icon="chevron-right" size={16} />
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4, marginBottom: 4 }}>
        {DIAS_SEMANA_FIN.map((d, i) => {
          const isWeekend = i === 0 || i === 6;
          return (
            <div key={d} style={{ textAlign: 'center', fontSize: 'var(--fs-xs)', fontFamily: 'Roboto, sans-serif',
              fontWeight: 900, letterSpacing: '0.06em',
              color: isWeekend ? 'rgba(148,163,184,.45)' : 'var(--text-3)',
              textTransform: 'uppercase', padding: '4px 0' }}>
              {d}
            </div>
          );
        })}
      </div>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gridAutoRows: 'minmax(84px, auto)', gap: 4 }}>
        {cells.map((dia, idx) => {
          const colIdx = idx % 7;
          const isWeekend = colIdx === 0 || colIdx === 6;
          if (!dia) return (
            <div key={`e${idx}`} style={{ background: isWeekend ? 'var(--overlay-05)' : 'transparent', borderRadius: 'var(--r-sm)' }} />
          );

          const dateStr = `${ano}-${String(mes + 1).padStart(2, '0')}-${String(dia).padStart(2, '0')}`;
          const dayItems = byDate[dateStr] || [];
          const isToday = dateStr === todayStr;

          let bgColor = 'var(--app-surface-2)';
          if (isToday) bgColor = 'rgba(234,170,65,.06)';
          else if (isWeekend) bgColor = 'var(--overlay-05)';

          let borderColor = 'var(--app-border)';
          if (isToday) borderColor = 'rgba(234,170,65,.45)';
          else if (isWeekend) borderColor = 'var(--overlay-08)';

          const isDragOver = dragOverDate === dateStr;

          return (
            <div key={dateStr} onClick={() => onNewWithDate(dateStr)}
              onDragOver={e => { e.preventDefault(); if (dragOverDate !== dateStr) setDragOverDate(dateStr); }}
              onDragLeave={() => setDragOverDate(prev => prev === dateStr ? null : prev)}
              onDrop={e => {
                e.preventDefault();
                setDragOverDate(null);
                if (dragId) onReschedule(dragId, dateStr);
                setDragId(null);
              }}
              style={{ border: isDragOver ? '1px solid rgba(234,170,65,.7)' : `1px solid ${borderColor}`,
                borderRadius: 'var(--r-sm)', padding: '6px 8px',
                background: isDragOver ? 'rgba(234,170,65,.1)' : bgColor,
                cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 4,
                transition: 'border-color 150ms, background 150ms',
                opacity: isWeekend && !isToday ? 0.75 : 1 }}>
              <span style={{ fontSize: 'var(--fs-sm)', fontFamily: 'Roboto, sans-serif', fontWeight: 900,
                color: isToday ? 'var(--accent)' : isWeekend ? 'rgba(148,163,184,.5)' : 'var(--text-3)',
                background: isToday ? 'rgba(234,170,65,.15)' : 'transparent',
                borderRadius: 5, padding: isToday ? '1px 5px' : '0',
                alignSelf: 'flex-start', lineHeight: 1.6, flexShrink: 0 }}>
                {dia}
              </span>

              {dayItems.map(p => {
                const st = statusDe(p);
                const color = STATUS_COLOR_FIN[st] || STATUS_COLOR_FIN['Pagar'];
                return (
                  <div key={p.id}
                    draggable
                    onDragStart={e => { e.stopPropagation(); setDragId(p.id); e.dataTransfer.effectAllowed = 'move'; }}
                    onDragEnd={() => setDragId(null)}
                    onClick={e => { e.stopPropagation(); onOpen(p); }}
                    style={{ padding: '4px 6px', borderRadius: 'var(--r-sm)', background: `${color}18`,
                      border: `1px solid ${color}33`, cursor: 'grab', display: 'flex',
                      flexDirection: 'column', gap: 4, overflow: 'hidden',
                      opacity: dragId === p.id ? 0.4 : 1 }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 'var(--fs-xs)',
                      fontFamily: 'Roboto, sans-serif', fontWeight: 700, color: 'var(--text-1)',
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {(p.conta_url || p.comprovante_url) && <LucideIcon icon="paperclip" size={10} style={{ flexShrink: 0, color: 'var(--text-3)' }} />}
                      {p.nome}
                    </span>
                    <span style={{ fontSize: 'var(--fs-xs)', fontFamily: 'Roboto, sans-serif', fontWeight: 900,
                      color, letterSpacing: '0.04em' }}>
                      {STATUS_BADGE_FIN[st]?.label || st}
                    </span>
                    <span style={{ fontSize: 'var(--fs-xs)', fontFamily: 'Roboto, sans-serif', color: 'var(--text-3)' }}>
                      {p.valor ? fmtBRL(p.valor) : '—'}
                    </span>
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Tela principal ────────────────────────────────────────────────*/
function FinanceiroScreen({ focus } = {}) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filtro, setFiltro] = useState('todos');
  const [modal, setModal] = useState(null);
  const [viewMode, setViewMode] = useState('calendario'); // 'lista' | 'calendario'
  const [dataDe, setDataDe] = useState('');
  const [dataAte, setDataAte] = useState('');
  const [busca, setBusca] = useState('');

  useEffect(() => { load(); }, []);
  async function load() {
    setLoading(true);
    const { data } = await window.db.from('crm_payments').select('*').order('vencimento', { ascending: true });
    setItems(data || []);
    setLoading(false);
  }

  // Chegada vinda da Agenda ("abrir este registro"): assim que os itens
  // carregarem, abre o modal do pagamento pedido.
  useEffect(() => {
    if (focus?.tipo === 'financeiro' && focus.id && items.length) {
      const item = items.find(i => i.id === focus.id);
      if (item) setModal({ item });
    }
  }, [focus, items]);

  async function marcarPago(p) {
    await window.db.from('crm_payments').update({ status: 'Pago', data_pagamento: hojeISO() }).eq('id', p.id);
    load();
  }

  async function handleReschedule(itemId, novaData) {
    const item = items.find(i => i.id === itemId);
    if (!item) return;
    // Arrastar muda a data que está sendo exibida no momento: vencimento se
    // ainda não foi pago, data_pagamento se já foi (mesma regra do calendário).
    const campo = (item.status === 'Pago' && item.data_pagamento) ? 'data_pagamento' : 'vencimento';
    if (item[campo] === novaData) return;
    setItems(prev => prev.map(i => i.id === itemId ? { ...i, [campo]: novaData } : i));
    await window.db.from('crm_payments').update({ [campo]: novaData }).eq('id', itemId);
  }

  async function excluir(p) {
    if (!confirm(`Excluir "${p.nome}"? Essa ação não pode ser desfeita.`)) return false;
    await window.db.from('crm_payments').delete().eq('id', p.id);
    load();
    return true;
  }

  async function duplicar(p) {
    const proximoVencimento = p.vencimento
      ? addMesesISO(p.vencimento, p.frequencia === 'Anual' ? 12 : 1)
      : hojeISO();
    await window.db.from('crm_payments').insert({
      nome: p.nome, conta: p.conta, forma_pagamento: p.forma_pagamento, valor: p.valor,
      vencimento: proximoVencimento, frequencia: p.frequencia, status: 'Pagar',
    });
    load();
  }

  const filtrados = items
    .filter(p => filtro === 'todos' ? true : statusDe(p) === filtro)
    .filter(p => !dataDe || (p.vencimento && p.vencimento >= dataDe))
    .filter(p => !dataAte || (p.vencimento && p.vencimento <= dataAte))
    .filter(p => !busca || p.nome.toLowerCase().includes(busca.trim().toLowerCase()));
  const kpi = {
    aPagar: items.filter(p => p.status !== 'Pago').reduce((s, p) => s + Number(p.valor || 0), 0),
    vencidas: items.filter(p => statusDe(p) === 'Vencida').length,
    vencendoSemana: items.filter(p => {
      if (p.status === 'Pago' || !p.vencimento) return false;
      const dias = (new Date(p.vencimento) - new Date(hojeISO())) / 86400000;
      return dias >= 0 && dias <= 7;
    }).length,
    pagoMes: items.filter(p => p.status === 'Pago' && (p.data_pagamento || '').slice(0, 7) === hojeISO().slice(0, 7))
      .reduce((s, p) => s + Number(p.valor || 0), 0),
  };

  const FILTROS = [
    { id: 'todos', label: 'Todos' },
    { id: 'Pagar', label: 'A pagar' },
    { id: 'Vencida', label: 'Vencidas' },
    { id: 'Pago', label: 'Pagos' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, overflow: 'hidden' }}>
      <TopBar title="Financeiro"
        actions={(
          <>
            <div style={{ display: 'flex', gap: 4, padding: 3, borderRadius: 'var(--r-sm)',
              background: 'var(--overlay-05)', border: '1px solid var(--app-border)' }}>
              {[['lista', 'list', 'Lista'], ['calendario', 'calendar', 'Calendário']].map(([id, icon, label]) => (
                <button key={id} onClick={() => setViewMode(id)}
                  style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '4px 10px',
                    borderRadius: 'var(--r-sm)', cursor: 'pointer', fontSize: 'var(--fs-sm)', fontFamily: 'Roboto, sans-serif',
                    fontWeight: 700, transition: 'all 130ms', border: 'none',
                    background: viewMode === id ? 'rgba(234,170,65,.18)' : 'transparent',
                    color: viewMode === id ? 'var(--accent)' : 'var(--text-3)' }}>
                  <LucideIcon icon={icon} size={12} />{label}
                </button>
              ))}
            </div>
            <Btn variant="primary" icon="plus" onClick={() => setModal({ item: null })}>Novo pagamento</Btn>
          </>
        )} />

      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '18px 24px 24px',
        display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', gap: 12 }}>
          <CardKPI label="Em aberto" value={fmtBRL(kpi.aPagar)} icon="wallet" />
          <CardKPI label="Vencidas" value={kpi.vencidas} icon="alert-octagon" accent={kpi.vencidas > 0} />
          <CardKPI label="Vencendo em 7 dias" value={kpi.vencendoSemana} icon="alert-triangle" accent={kpi.vencendoSemana > 0} />
          <CardKPI label="Pago este mês" value={fmtBRL(kpi.pagoMes)} icon="check-circle-2" />
        </div>

        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '0 10px', borderRadius: 'var(--r-sm)',
            background: 'var(--app-surface-2)', border: '1px solid var(--app-border)', minWidth: 200 }}>
            <LucideIcon icon="search" size={13} style={{ color: 'var(--text-3)', flexShrink: 0 }} />
            <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar por nome..."
              style={{ flex: 1, border: 'none', background: 'none', outline: 'none', padding: '7px 0',
                color: 'var(--text-1)', fontFamily: 'Roboto, sans-serif', fontSize: 'var(--fs-md)' }} />
            {busca && (
              <button onClick={() => setBusca('')}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)', display: 'flex', padding: 0 }}>
                <LucideIcon icon="x" size={13} />
              </button>
            )}
          </div>

          <div style={{ display: 'flex', gap: 6 }}>
            {FILTROS.map(f => (
              <button key={f.id} onClick={() => setFiltro(f.id)}
                style={{
                  padding: '6px 12px', borderRadius: 'var(--r-full)', cursor: 'pointer',
                  background: filtro === f.id ? 'rgba(234,170,65,.15)' : 'var(--app-surface-2)',
                  border: `1px solid ${filtro === f.id ? 'rgba(234,170,65,.3)' : 'var(--app-border)'}`,
                  color: filtro === f.id ? 'var(--accent)' : 'var(--text-2)',
                  fontFamily: 'Roboto, sans-serif', fontWeight: 700, fontSize: 'var(--fs-sm)',
                }}>{f.label}</button>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <span style={{ fontSize: 'var(--fs-sm)', fontFamily: 'Roboto, sans-serif', color: 'var(--text-3)' }}>Vencimento entre</span>
            <input type="date" value={dataDe} onChange={e => setDataDe(e.target.value)}
              style={{ ...inputStyle, width: 'auto', padding: '4px 8px', fontSize: 'var(--fs-md)' }} />
            <span style={{ fontSize: 'var(--fs-sm)', fontFamily: 'Roboto, sans-serif', color: 'var(--text-3)' }}>e</span>
            <input type="date" value={dataAte} onChange={e => setDataAte(e.target.value)}
              style={{ ...inputStyle, width: 'auto', padding: '4px 8px', fontSize: 'var(--fs-md)' }} />
            {(dataDe || dataAte) && (
              <button onClick={() => { setDataDe(''); setDataAte(''); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)',
                  fontFamily: 'Roboto, sans-serif', fontSize: 'var(--fs-sm)', textDecoration: 'underline' }}>
                limpar
              </button>
            )}
          </div>
        </div>

        {viewMode === 'calendario' ? (
          <FinanceiroCalendario items={filtrados}
            onOpen={p => setModal({ item: p })}
            onNewWithDate={dateStr => setModal({ item: null, prefillDate: dateStr })}
            onReschedule={handleReschedule} />
        ) : (
        <SectionCard noPad>
          {loading ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 'var(--fs-lg)' }}>Carregando…</div>
          ) : filtrados.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 'var(--fs-lg)' }}>Nenhum pagamento aqui ainda.</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--app-border)' }}>
                  {['Nome', 'Conta', 'Forma', 'Vencimento', 'Valor', 'Status', ''].map(h => (
                    <th key={h} style={{ textAlign: 'left', padding: '10px 12px', fontSize: 'var(--fs-xs)',
                      fontFamily: 'Roboto, sans-serif', fontWeight: 700, letterSpacing: '0.08em',
                      textTransform: 'uppercase', color: 'var(--text-3)' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtrados.map(p => {
                  const badge = STATUS_BADGE_FIN[statusDe(p)];
                  return (
                    <tr key={p.id} style={{ borderBottom: '1px solid var(--app-border)', cursor: 'pointer' }}
                      onClick={() => setModal({ item: p })}>
                      <td style={{ padding: '10px 12px', fontSize: 'var(--fs-md)', color: 'var(--text-1)', fontWeight: 700,
                        maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.nome}</td>
                      <td style={{ padding: '10px 12px', fontSize: 'var(--fs-md)', color: 'var(--text-2)' }}>{p.conta || '—'}</td>
                      <td style={{ padding: '10px 12px', fontSize: 'var(--fs-md)', color: 'var(--text-2)' }}>{p.forma_pagamento || '—'}</td>
                      <td style={{ padding: '10px 12px', fontSize: 'var(--fs-md)', color: 'var(--text-2)' }}>{fmtDataBR(p.vencimento)}</td>
                      <td style={{ padding: '10px 12px', fontSize: 'var(--fs-md)', color: 'var(--text-2)' }}>{p.valor ? fmtBRL(p.valor) : '—'}</td>
                      <td style={{ padding: '10px 12px' }}><Badge tone={badge.tone}>{badge.label}</Badge></td>
                      <td style={{ padding: '10px 12px', textAlign: 'right' }} onClick={e => e.stopPropagation()}>
                        <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', alignItems: 'center' }}>
                          {p.conta_url && (
                            <a href={p.conta_url} target="_blank" rel="noreferrer"
                              style={{ color: 'var(--text-3)', display: 'flex' }} title="Ver conta/boleto">
                              <LucideIcon icon="file-text" size={15} />
                            </a>
                          )}
                          {p.comprovante_url && (
                            <a href={p.comprovante_url} target="_blank" rel="noreferrer"
                              style={{ color: 'var(--text-3)', display: 'flex' }} title="Ver comprovante de pagamento">
                              <LucideIcon icon="paperclip" size={15} />
                            </a>
                          )}
                          {p.frequencia !== 'Única' && (
                            <Btn variant="ghost" size="sm" onClick={() => duplicar(p)} icon="copy-plus">Duplicar</Btn>
                          )}
                          {p.status !== 'Pago' && (
                            <Btn variant="ghost" size="sm" onClick={() => marcarPago(p)}>Marcar pago</Btn>
                          )}
                          <button onClick={() => excluir(p)} title="Excluir"
                            style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)',
                              display: 'flex', padding: 4 }}>
                            <LucideIcon icon="trash-2" size={15} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </SectionCard>
        )}
      </div>

      {modal && (
        <PagamentoModal item={modal.item} defaultVencimento={modal.prefillDate} onClose={() => setModal(null)}
          onSaved={() => { setModal(null); load(); }}
          onDelete={async (p) => { if (await excluir(p)) setModal(null); }} />
      )}
    </div>
  );
}

Object.assign(window, { FinanceiroScreen });
