/* global React, Icon, Button, Badge, Card, KpiMini, brl */
// ─── NF Widgets — Constants, utilities, shared components ────────────────

// ─── Constantes ──────────────────────────────────────────────────────────────

const NF_STATUS = {
  'Rascunho':    'neutral',
  'Processando': 'info',
  'Autorizada':  'success',
  'Rejeitada':   'danger',
  'Cancelada':   'warning',
  'Inutilizada': 'neutral',
  'Denegada':    'danger',
};

const NATUREZAS_OPERACAO = [
  'Venda de mercadoria',
  'Devolução de mercadoria',
  'Remessa para demonstração',
  'Bonificação',
  'Transferência',
];

const MODALIDADES_FRETE = [
  { id: '0', label: 'Emitente (CIF)' },
  { id: '1', label: 'Destinatário (FOB)' },
  { id: '2', label: 'Terceiros' },
  { id: '9', label: 'Sem frete' },
];

const REGIMES_TRIBUTARIOS = [
  'Simples Nacional',
  'Simples Nacional - Excesso',
  'Lucro Presumido',
  'Lucro Real',
];

const EMPRESA_CORES = [
  '#C9A36B', '#6BA3D6', '#5BB17A', '#D4A04A',
  '#D9655E', '#9B6DD7', '#E88C5D',
];

const BLANK_EMPRESA = {
  razaoSocial: '', nomeFantasia: '', cnpj: '', ie: '', im: '',
  regimeTributario: 'Simples Nacional',
  endereco: {
    logradouro: '', numero: '', complemento: '',
    bairro: '', cidade: '', uf: 'SP', cep: '',
  },
  telefone: '', email: '', ambiente: 'homologacao', serieNfe: 1, ativo: true, cor: '#C9A36B',
};

// ─── Utilitários ─────────────────────────────────────────────────────────────

function formatCNPJ(v) {
  if (!v) return '—';
  const d = String(v).replace(/\D/g, '');
  if (d.length !== 14) return v;
  return d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5');
}

function formatChaveAcesso(ch) {
  if (!ch) return '—';
  return ch.replace(/(.{4})/g, '$1 ').trim();
}

// ─── Componentes compartilhados ──────────────────────────────────────────────

function NFStatusBadge({ status }) {
  return <Badge tone={NF_STATUS[status] || 'neutral'}>{status}</Badge>;
}

function EmpresaBadge({ nome, cor }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '3px 10px', borderRadius: 6,
      background: (cor || '#C9A36B') + '18',
      color: cor || '#C9A36B',
      fontSize: 12, fontWeight: 500,
    }}>
      <span style={{
        width: 7, height: 7, borderRadius: 2,
        background: cor || '#C9A36B',
      }} />
      {nome || '—'}
    </span>
  );
}

function NFKpiCards({ nfs }) {
  const list = nfs || [];
  const emitidas   = list.filter(n => n.status !== 'Rascunho').length;
  const autorizadas = list.filter(n => n.status === 'Autorizada').length;
  const rejeitadas  = list.filter(n => n.status === 'Rejeitada').length;
  const valorTotal  = list
    .filter(n => n.status === 'Autorizada')
    .reduce((s, n) => s + (Number(n.valor_total) || 0), 0);

  return (
    <div className="grid-4">
      <KpiMini label="Total emitidas"  value={emitidas} />
      <KpiMini label="Autorizadas"     value={autorizadas} />
      <KpiMini label="Rejeitadas"      value={rejeitadas} />
      <KpiMini label="Valor total"     value={brl(valorTotal)} />
    </div>
  );
}

function NFTabs({ active, onNav }) {
  const tabs = [
    { id: 'emissao',   label: 'Emissão' },
    { id: 'historico',  label: 'Histórico' },
    { id: 'empresas',   label: 'Empresas Emissoras' },
    { id: 'importar',   label: 'Importar XML' },
    { id: 'logs',       label: 'Logs' },
  ];
  return (
    <div className="tabs">
      {tabs.map(t => (
        <div key={t.id}
          className={`tab ${active === t.id ? 'active' : ''}`}
          onClick={() => onNav(`nf/${t.id}`)}>
          {t.label}
        </div>
      ))}
    </div>
  );
}

// ─── Export ──────────────────────────────────────────────────────────────────

Object.assign(window, {
  NF_STATUS, NATUREZAS_OPERACAO, MODALIDADES_FRETE,
  REGIMES_TRIBUTARIOS, EMPRESA_CORES, BLANK_EMPRESA,
  formatCNPJ, formatChaveAcesso,
  NFStatusBadge, EmpresaBadge, NFKpiCards, NFTabs,
});
