// Cranodato — Invoice list screen + detail panel
const FACTURAS = [
  { id: '0001-00048', proveedor: 'Ferretería Central S.A.',    cuit: '30-71234500-1', monto: '$12.480,00',  iva: '$2.620,80',  neto: '$9.859,20',  tipo: 'Factura A', estado: 'procesada',  fecha: '30/04/2025', archivo: 'factura_048.pdf' },
  { id: '0001-00047', proveedor: 'Logística del Sur',          cuit: '27-38812341-5', monto: '$84.200,00',  iva: '$17.682,00', neto: '$66.518,00', tipo: 'Factura A', estado: 'revisar',    fecha: '30/04/2025', archivo: 'logistica_047.jpg' },
  { id: '0001-00046', proveedor: 'Distribuidora Norte S.A.',   cuit: '30-71100002-0', monto: '$48.320,00',  iva: '$10.147,20', neto: '$38.172,80', tipo: 'Factura B', estado: 'procesada',  fecha: '29/04/2025', archivo: 'norte_046.pdf' },
  { id: '0001-00045', proveedor: 'Tech Insumos SRL',           cuit: '—',             monto: '—',           iva: '—',          neto: '—',          tipo: '—',         estado: 'error',      fecha: '29/04/2025', archivo: 'scan_borroso.jpg' },
  { id: '0001-00044', proveedor: 'Papel y Cartón Nordeste',    cuit: '30-89200003-7', monto: '$6.750,00',   iva: '$1.417,50',  neto: '$5.332,50',  tipo: 'Factura B', estado: 'procesada',  fecha: '28/04/2025', archivo: 'papel_044.pdf' },
  { id: '0001-00043', proveedor: 'Insumos del Litoral',        cuit: '20-44312000-8', monto: '$31.000,00',  iva: '$6.510,00',  neto: '$24.490,00', tipo: 'Factura A', estado: 'procesando', fecha: '28/04/2025', archivo: 'litoral_043.pdf' },
  { id: '0001-00042', proveedor: 'Global Pack S.A.',           cuit: '30-54321000-4', monto: '$18.900,00',  iva: '$3.969,00',  neto: '$14.931,00', tipo: 'Nota crédito A', estado: 'procesada', fecha: '27/04/2025', archivo: 'globalpack_042.pdf' },
];

const DetailPanel = ({ factura, onClose }) => {
  if (!factura) return null;
  const Field = ({ label, value, mono }) => (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 14, color: '#0F172A', fontFamily: mono ? "'DM Mono',monospace" : "'DM Sans',sans-serif", fontWeight: mono ? 400 : 400 }}>{value}</div>
    </div>
  );
  return (
    <div style={{ width: 320, background: 'white', borderLeft: '1px solid #E2E8F0', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
      <div style={{ padding: '14px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Detalle</span>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex' }}>
          <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
        </button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px' }}>
        {/* File preview placeholder */}
        <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, height: 140, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, marginBottom: 20 }}>
          <i data-lucide="file-text" style={{ width: 32, height: 32, color: '#CBD5E1' }}></i>
          <span style={{ fontSize: 12, color: '#94A3B8' }}>{factura.archivo}</span>
          <Btn variant="ghost" size="sm"><i data-lucide="download" style={{width:14,height:14}}></i>Descargar</Btn>
        </div>
        <div style={{ marginBottom: 14 }}><StatusBadge status={factura.estado} /></div>
        <Field label="N° comprobante" value={factura.id} mono />
        <Field label="Tipo" value={factura.tipo} />
        <Field label="Proveedor" value={factura.proveedor} />
        <Field label="CUIT" value={factura.cuit} mono />
        <hr style={{ border: 'none', borderTop: '1px solid #F1F5F9', margin: '4px 0 16px' }} />
        <Field label="Neto gravado" value={factura.neto} mono />
        <Field label="IVA" value={factura.iva} mono />
        <div style={{ background: '#ECFDF5', borderRadius: 8, padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 12, fontWeight: 600, color: '#047857', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Total</span>
          <span style={{ fontSize: 20, fontWeight: 700, color: '#047857', fontFamily: "'DM Mono',monospace" }}>{factura.monto}</span>
        </div>
        {factura.estado === 'revisar' && (
          <div style={{ marginTop: 16, background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: '#B45309' }}>
            <div style={{ fontWeight: 600, marginBottom: 4 }}>Revisión requerida</div>
            <div style={{ fontSize: 12 }}>El CUIT detectado no coincide con proveedores registrados.</div>
          </div>
        )}
        {factura.estado === 'error' && (
          <div style={{ marginTop: 16, background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: '#B91C1C' }}>
            <div style={{ fontWeight: 600, marginBottom: 4 }}>Error de lectura</div>
            <div style={{ fontSize: 12 }}>La imagen está borrosa o es de baja calidad. Volvé a subir.</div>
          </div>
        )}
      </div>
      <div style={{ padding: '14px 20px', borderTop: '1px solid #F1F5F9', display: 'flex', gap: 8 }}>
        {factura.estado === 'revisar' && <Btn size="sm">Aprobar</Btn>}
        <Btn variant="secondary" size="sm">Editar datos</Btn>
        <Btn variant="ghost" size="sm" style={{ marginLeft: 'auto' }}><i data-lucide="trash-2" style={{width:14,height:14}}></i></Btn>
      </div>
    </div>
  );
};

const FacturasScreen = ({ nuevasFacturas = [] }) => {
  const [selected, setSelected] = React.useState(null);
  const [filter, setFilter] = React.useState('todas');

  const todas = [...nuevasFacturas, ...FACTURAS];

  const tabs = [
    { id: 'todas',      label: 'Todas',       count: todas.length },
    { id: 'revisar',    label: 'Revisar',      count: todas.filter(f => f.estado === 'revisar').length },
    { id: 'procesada',  label: 'Procesadas',   count: todas.filter(f => f.estado === 'procesada').length },
    { id: 'error',      label: 'Con error',    count: todas.filter(f => f.estado === 'error').length },
  ];

  const visible = filter === 'todas' ? todas : todas.filter(f => f.estado === filter);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar title="Facturas" subtitle={`${FACTURAS.length} comprobantes este mes`}
        actions={<Btn><i data-lucide="upload-cloud" style={{width:16,height:16}}></i>Subir factura</Btn>}
      />
      {/* Filter tabs */}
      <div style={{ background: 'white', borderBottom: '1px solid #E2E8F0', padding: '0 28px', display: 'flex', gap: 0 }}>
        {tabs.map(tab => (
          <button key={tab.id} onClick={() => setFilter(tab.id)} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: '12px 16px',
            fontSize: 14, fontWeight: filter === tab.id ? 600 : 400,
            color: filter === tab.id ? '#059669' : '#64748B',
            borderBottom: filter === tab.id ? '2px solid #059669' : '2px solid transparent',
            display: 'flex', alignItems: 'center', gap: 6, transition: 'color 150ms', fontFamily: "'DM Sans',sans-serif",
          }}>
            {tab.label}
            {tab.count > 0 && <span style={{ fontSize: 11, background: filter === tab.id ? '#ECFDF5' : '#F1F5F9', color: filter === tab.id ? '#047857' : '#64748B', padding: '1px 6px', borderRadius: 9999, fontWeight: 600 }}>{tab.count}</span>}
          </button>
        ))}
        {/* Search */}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', padding: '8px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 6, padding: '6px 12px' }}>
            <i data-lucide="search" style={{ width: 14, height: 14, color: '#94A3B8' }}></i>
            <input placeholder="Buscar factura…" style={{ border: 'none', background: 'transparent', fontSize: 13, color: '#0F172A', outline: 'none', width: 160, fontFamily: "'DM Sans',sans-serif" }} />
          </div>
        </div>
      </div>
      {/* Table + detail */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        <div style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#F8FAFC', position: 'sticky', top: 0, zIndex: 1 }}>
                {['N° factura','Proveedor','CUIT','Tipo','Monto','Estado','Fecha'].map(h => (
                  <th key={h} style={{ padding: '10px 20px', textAlign: 'left', fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', borderBottom: '1px solid #E2E8F0', whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map((f, i) => {
                const isActive = selected?.id === f.id;
                return (
                  <tr key={f.id}
                    onClick={() => setSelected(isActive ? null : f)}
                    style={{ borderBottom: '1px solid #F1F5F9', cursor: 'pointer', background: isActive ? '#ECFDF5' : 'transparent', transition: 'background 100ms' }}
                    onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#F8FAFC'; }}
                    onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
                    <td style={{ padding: '12px 20px', fontSize: 13, fontFamily: "'DM Mono',monospace", color: '#0F172A', fontWeight: isActive ? 600 : 400 }}>{f.id}</td>
                    <td style={{ padding: '12px 20px', fontSize: 13, color: '#0F172A' }}>{f.proveedor}</td>
                    <td style={{ padding: '12px 20px', fontSize: 12, fontFamily: "'DM Mono',monospace", color: '#64748B' }}>{f.cuit}</td>
                    <td style={{ padding: '12px 20px', fontSize: 12, color: '#64748B' }}>{f.tipo}</td>
                    <td style={{ padding: '12px 20px', fontSize: 13, fontFamily: "'DM Mono',monospace", color: '#047857', fontWeight: 500 }}>{f.monto}</td>
                    <td style={{ padding: '12px 20px' }}><StatusBadge status={f.estado} /></td>
                    <td style={{ padding: '12px 20px', fontSize: 12, color: '#94A3B8' }}>{f.fecha}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <DetailPanel factura={selected} onClose={() => setSelected(null)} />
      </div>
    </div>
  );
};

Object.assign(window, { FacturasScreen });
