// ─── Lanven — Sueldos ────────────────────────────────────────────────────────
// Módulo de sueldos y liquidación de comisiones. Solo ADMIN / GERENCIA.
//
// Tab 1 — Empleados (sueldo fijo)
//   GET  /api/usuarios?activo=true
//   PUT  /api/usuarios/:id        { sueldo }
//   POST /api/finanzas            EGRESO/FIJO/SUELDO
//   GET  /api/finanzas?tipo=EGRESO&categoria=SUELDO&usuarioId=:id
//
// Tab 2 — Comisiones por operación
//   GET  /api/operaciones?estado=COBRADA&comisionLiquidada=false
//   GET  /api/operaciones/:id/participantes
//   POST /api/operaciones/:id/participantes     { userId, rol, porcentaje }
//   PUT  /api/operaciones/:id/participantes/:pid { porcentaje }
//   DEL  /api/operaciones/:id/participantes/:pid
//   POST /api/operaciones/:id/liquidar-comisiones { fecha }
//
// Tab 3 — Historial
//   GET  /api/finanzas?tipo=EGRESO&categoria=SUELDO
//   GET  /api/finanzas?tipo=EGRESO&categoria=COMISION


// ── Constantes ────────────────────────────────────────────────────────────────
const ROL_LABELS = {
  ADMIN:       'Administración',
  GERENCIA:    'Gerencia',
  TEAM_LEADER: 'Team Leader',
  BROKER:      'Broker',
  MARKETING:   'Marketing',
};

const ROL_COLORS = {
  ADMIN:       '#3D4F5C',
  GERENCIA:    '#3D4F5C',
  TEAM_LEADER: '#A88A47',
  BROKER:      '#3F8A6B',
  MARKETING:   '#B33A8E',
};

const PART_LABELS = {
  PRODUCCION:  'Producción',
  VENTA:       'Venta',
  BUSQUEDA:    'Búsqueda',
  TEAM_LEADER: 'Team Leader',
};

const PART_COLORS = {
  PRODUCCION:  '#3F8A6B',
  VENTA:       '#3D4F5C',
  BUSQUEDA:    '#A88A47',
  TEAM_LEADER: '#677A88',
};

const PART_DEFAULTS = { PRODUCCION: 35, VENTA: 15, BUSQUEDA: 40, TEAM_LEADER: 10 };

const MESES_ES = [
  'Enero','Febrero','Marzo','Abril','Mayo','Junio',
  'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre',
];

// ── Helpers ───────────────────────────────────────────────────────────────────
function generarPeriodosLiq() {
  const hoy = new Date();
  const result = [];
  for (let i = 0; i < 12; i++) {
    const d = new Date(hoy.getFullYear(), hoy.getMonth() - i, 1);
    const year  = d.getFullYear();
    const month = d.getMonth() + 1;
    result.push({
      value: `${year}-${String(month).padStart(2,'0')}`,
      label: `${MESES_ES[d.getMonth()]} ${year}`,
      year, month,
    });
  }
  return result;
}

function ultimoDiaMes(year, month) {
  const d = new Date(year, month, 0);
  return `${year}-${String(month).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function hoyISO() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function fmtFecha(str) {
  if (!str) return '—';
  return String(str).slice(0, 10);
}

function nombreCompleto(u) {
  return [u?.nombre, u?.apellido].filter(Boolean).join(' ');
}

// ── Íconos locales ────────────────────────────────────────────────────────────
function PencilIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
    </svg>
  );
}

function TrashIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="3 6 5 6 21 6" />
      <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
      <path d="M10 11v6M14 11v6" />
      <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
    </svg>
  );
}

function CheckSmIcon({ size = 13 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12" />
    </svg>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
//  TAB 1 — EMPLEADOS
// ═══════════════════════════════════════════════════════════════════════════════

// ── EditSueldoModal ───────────────────────────────────────────────────────────
function EditSueldoModal({ user, onClose, onSaved }) {
  const [sueldo, setSueldo] = React.useState(user.sueldo != null ? String(user.sueldo) : '');
  const [saving, setSaving] = React.useState(false);
  const [error,  setError]  = React.useState(null);

  async function handleSave() {
    const n = Number(sueldo);
    if (sueldo.trim() === '' || isNaN(n) || n < 0) {
      setError('Ingresá un monto válido (0 o mayor).');
      return;
    }
    setSaving(true); setError(null);
    try {
      const r = await fetch(`${API_BASE}/api/usuarios/${user.id}`, {
        method: 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sueldo: n }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'Error al guardar.'); return; }
      onSaved({ ...user, sueldo: data.sueldo });
    } catch { setError('Error de red.'); }
    finally  { setSaving(false); }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
      <div className="bg-white rounded-lg shadow-pop w-[400px] p-6 fade-in" onClick={e => e.stopPropagation()}>
        <h2 className="font-serif text-[22px] text-ink leading-tight mb-0.5">Editar sueldo</h2>
        <p className="text-[13px] text-slate-500 mb-5">
          {nombreCompleto(user)}
          <span className="ml-2 text-[11px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 font-medium">
            {ROL_LABELS[user.rol] || user.rol}
          </span>
        </p>
        <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Sueldo base (ARS)</label>
        <input type="number" min="0" step="1" value={sueldo}
          onChange={e => setSueldo(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') handleSave(); if (e.key === 'Escape') onClose(); }}
          className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] font-mono focus:outline-none focus:border-slate-400"
          placeholder="0" autoFocus />
        {error && <p className="mt-2 text-[12px] text-bad">{error}</p>}
        <div className="mt-5 flex items-center justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-[13px] text-slate-600 hover:text-ink transition-colors">Cancelar</button>
          <button onClick={handleSave} disabled={saving}
            className="px-4 py-2 text-[13px] bg-slate-700 text-white rounded hover:bg-slate-600 disabled:opacity-50 transition-colors">
            {saving ? 'Guardando…' : 'Guardar'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── LiquidarSueldoModal ───────────────────────────────────────────────────────
function LiquidarSueldoModal({ user, onClose, onSaved }) {
  const periodos = React.useMemo(generarPeriodosLiq, []);
  const [periodo,     setPeriodo]     = React.useState(periodos[0]?.value || '');
  const [monto,       setMonto]       = React.useState(user.sueldo != null ? String(user.sueldo) : '');
  const [descripcion, setDescripcion] = React.useState('');
  const [notas,       setNotas]       = React.useState('');
  const [saving,      setSaving]      = React.useState(false);
  const [error,       setError]       = React.useState(null);

  React.useEffect(() => {
    const p = periodos.find(x => x.value === periodo);
    if (p) setDescripcion(`Liquidación sueldo ${nombreCompleto(user)} · ${p.label}`);
  }, [periodo]);

  async function handleLiquidar() {
    const n = Number(monto);
    if (!periodo)           { setError('Seleccioná un período.'); return; }
    if (isNaN(n) || n <= 0) { setError('El monto debe ser mayor a 0.'); return; }
    if (!descripcion.trim()) { setError('La descripción es requerida.'); return; }

    const p = periodos.find(x => x.value === periodo);
    setSaving(true); setError(null);
    try {
      const r = await fetch(`${API_BASE}/api/finanzas`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tipo: 'EGRESO', periodicidad: 'FIJO', categoria: 'SUELDO',
          monto: n, descripcion: descripcion.trim(),
          fecha: ultimoDiaMes(p.year, p.month),
          moneda: 'ARS', notas: notas.trim() || null, usuarioId: user.id,
        }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'Error al liquidar.'); return; }
      onSaved(data); onClose();
    } catch { setError('Error de red.'); }
    finally  { setSaving(false); }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
      <div className="bg-white rounded-lg shadow-pop w-[500px] p-6 fade-in" onClick={e => e.stopPropagation()}>
        <h2 className="font-serif text-[22px] text-ink leading-tight mb-0.5">Liquidar sueldo</h2>
        <p className="text-[13px] text-slate-500 mb-5">
          {nombreCompleto(user)}
          {user.sueldo != null && <span className="ml-2 text-slate-400">· Sueldo base {ARS(user.sueldo)}</span>}
        </p>
        <div className="space-y-4">
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Período</label>
            <select value={periodo} onChange={e => setPeriodo(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400 bg-white">
              {periodos.map(p => <option key={p.value} value={p.value}>{p.label}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Monto (ARS)</label>
            <input type="number" min="1" value={monto} onChange={e => setMonto(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] font-mono focus:outline-none focus:border-slate-400"
              placeholder="0" />
          </div>
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Descripción</label>
            <input type="text" value={descripcion} onChange={e => setDescripcion(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400" />
          </div>
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">
              Notas <span className="ml-1 text-slate-400 normal-case tracking-normal font-normal">(opcional)</span>
            </label>
            <textarea value={notas} onChange={e => setNotas(e.target.value)} rows={2}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400 resize-none" />
          </div>
        </div>
        {error && <p className="mt-3 text-[12px] text-bad">{error}</p>}
        <div className="mt-5 flex items-center justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-[13px] text-slate-600 hover:text-ink transition-colors">Cancelar</button>
          <button onClick={handleLiquidar} disabled={saving}
            className="px-4 py-2 text-[13px] bg-gold text-white rounded hover:bg-gold-deep disabled:opacity-50 transition-colors font-medium">
            {saving ? 'Liquidando…' : 'Liquidar'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── HistorialEmpleadoPanel ────────────────────────────────────────────────────
function HistorialEmpleadoPanel({ user, onClose, refreshKey }) {
  const [movs,    setMovs]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error,   setError]   = React.useState(null);

  React.useEffect(() => {
    setLoading(true); setError(null);
    fetch(`${API_BASE}/api/finanzas?tipo=EGRESO&categoria=SUELDO&usuarioId=${user.id}`, { credentials: 'include' })
      .then(r => r.ok ? r.json() : Promise.reject(r))
      .then(data => setMovs(Array.isArray(data) ? data : []))
      .catch(() => setError('Error al cargar historial.'))
      .finally(() => setLoading(false));
  }, [user.id, refreshKey]);

  const total = movs.reduce((s, m) => s + (m.monto || 0), 0);

  return (
    <div className="flex-1 min-w-0 pl-8 border-l border-slate-100 fade-in">
      <div className="flex items-start justify-between mb-6">
        <div>
          <h2 className="font-serif text-[22px] text-ink leading-tight">{nombreCompleto(user)}</h2>
          <p className="text-[12px] text-slate-500 mt-0.5">
            Historial de sueldos ·&nbsp;
            <span className="font-medium" style={{ color: ROL_COLORS[user.rol] }}>
              {ROL_LABELS[user.rol] || user.rol}
            </span>
            {user.sueldo != null && <span className="ml-2 text-slate-400">· Sueldo base {ARS(user.sueldo)}</span>}
          </p>
        </div>
        <button onClick={onClose} className="p-1.5 rounded hover:bg-slate-100 text-slate-400 hover:text-ink transition-colors">
          <I.X size={15} />
        </button>
      </div>

      {loading && <p className="text-[13px] text-slate-400 py-12 text-center">Cargando historial…</p>}
      {error   && <p className="text-[13px] text-bad py-4">{error}</p>}
      {!loading && !error && movs.length === 0 && (
        <div className="py-12 text-center">
          <p className="text-[13px] text-slate-400">Sin liquidaciones registradas.</p>
        </div>
      )}
      {!loading && !error && movs.length > 0 && (
        <>
          <table className="w-full text-[12px]">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="text-left pb-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Fecha</th>
                <th className="text-left pb-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium pl-3">Descripción</th>
                <th className="text-right pb-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Monto</th>
              </tr>
            </thead>
            <tbody>
              {movs.map(m => (
                <tr key={m.id} className="border-b border-slate-50 tr-hover">
                  <td className="py-2.5 text-slate-500 font-mono whitespace-nowrap">{fmtFecha(m.fecha)}</td>
                  <td className="py-2.5 text-ink pl-3">{m.descripcion}</td>
                  <td className="py-2.5 text-right font-mono text-ink whitespace-nowrap">{ARS(m.monto)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="mt-3 pt-3 border-t border-slate-100 flex items-center justify-between">
            <span className="text-[11px] text-slate-400">{movs.length} liquidación{movs.length !== 1 ? 'es' : ''}</span>
            <span className="font-mono font-semibold text-ink text-[13px]">{ARS(total)}</span>
          </div>
        </>
      )}
    </div>
  );
}

// ── TabEmpleados ──────────────────────────────────────────────────────────────
function TabEmpleados() {
  const [empleados,      setEmpleados]      = React.useState([]);
  const [loading,        setLoading]        = React.useState(true);
  const [error,          setError]          = React.useState(null);
  const [editingUser,    setEditingUser]    = React.useState(null);
  const [liquidandoUser, setLiquidandoUser] = React.useState(null);
  const [selectedUser,   setSelectedUser]   = React.useState(null);
  const [refreshKey,     setRefreshKey]     = React.useState(0);

  React.useEffect(() => {
    fetch(`${API_BASE}/api/usuarios?activo=true`, { credentials: 'include' })
      .then(r => r.ok ? r.json() : Promise.reject(r))
      .then(data => setEmpleados(Array.isArray(data) ? data : []))
      .catch(() => setError('Error al cargar empleados.'))
      .finally(() => setLoading(false));
  }, []);

  function handleSueldoSaved(updatedUser) {
    setEmpleados(prev => prev.map(u => u.id === updatedUser.id ? updatedUser : u));
    if (selectedUser?.id === updatedUser.id) setSelectedUser(updatedUser);
    setEditingUser(null);
  }

  function handleLiquidacionSaved() {
    if (selectedUser && liquidandoUser && selectedUser.id === liquidandoUser.id) {
      setRefreshKey(k => k + 1);
    }
  }

  function toggleHistorial(u) {
    if (selectedUser?.id === u.id) { setSelectedUser(null); }
    else { setSelectedUser(u); setRefreshKey(0); }
  }

  if (loading) return <p className="text-[13px] text-slate-400 py-16 text-center">Cargando empleados…</p>;
  if (error)   return <p className="text-[13px] text-bad py-6">{error}</p>;

  return (
    <div className="flex gap-8 items-start">
      {/* Tabla */}
      <div className={selectedUser ? 'w-[600px] flex-shrink-0' : 'w-full'}>
        <div className="bg-white border border-slate-100 rounded-lg shadow-card overflow-hidden">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="border-b border-slate-100 bg-slate-50/60">
                <th className="text-left px-5 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Empleado</th>
                <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Rol</th>
                <th className="text-right px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Sueldo ARS</th>
                <th className="px-4 py-3 text-right text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Acciones</th>
              </tr>
            </thead>
            <tbody>
              {empleados.length === 0 && (
                <tr><td colSpan={4} className="px-5 py-12 text-center text-[13px] text-slate-400">Sin empleados activos.</td></tr>
              )}
              {empleados.map(u => {
                const isSelected = selectedUser?.id === u.id;
                const rolColor   = ROL_COLORS[u.rol] || '#677A88';
                const initials   = ((u.nombre?.[0] || '') + (u.apellido?.[0] || '')).toUpperCase();
                return (
                  <tr key={u.id} onClick={() => toggleHistorial(u)}
                    className={`border-b border-slate-50 tr-hover cursor-pointer ${isSelected ? 'bg-slate-50/70' : ''}`}>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-[11px] font-semibold flex-shrink-0"
                          style={{ background: rolColor + 'CC' }}>{initials || '?'}</div>
                        <div>
                          <div className="font-medium text-ink leading-none">{nombreCompleto(u)}</div>
                          <div className="text-[11px] text-slate-400 font-mono mt-0.5">{u.email}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-[10px] uppercase tracking-[0.08em] px-2 py-0.5 rounded font-medium"
                        style={{ background: rolColor + '18', color: rolColor }}>
                        {ROL_LABELS[u.rol] || u.rol}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right font-mono">
                      {u.sueldo != null
                        ? <span className="text-ink">{ARS(u.sueldo)}</span>
                        : <span className="text-slate-400">—</span>}
                    </td>
                    <td className="px-4 py-3 text-right" onClick={e => e.stopPropagation()}>
                      <div className="flex items-center justify-end gap-1.5">
                        <button onClick={() => setEditingUser(u)} title="Editar sueldo"
                          className="p-1.5 rounded text-slate-400 hover:text-ink hover:bg-slate-100 transition-colors">
                          <PencilIcon size={13} />
                        </button>
                        <button onClick={() => setLiquidandoUser(u)} title="Liquidar sueldo"
                          className="px-2.5 py-1 rounded text-[11px] font-medium transition-colors"
                          style={{ background: '#C9A96118', color: '#A88A47' }}
                          onMouseEnter={e => e.currentTarget.style.background = '#C9A96130'}
                          onMouseLeave={e => e.currentTarget.style.background = '#C9A96118'}>
                          Liquidar
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {empleados.length > 0 && (
            <div className="px-5 py-3 border-t border-slate-50 bg-slate-50/40 flex items-center justify-between">
              <span className="text-[11px] text-slate-400">{empleados.length} empleado{empleados.length !== 1 ? 's' : ''} activos</span>
              <span className="text-[11px] text-slate-400">
                Sueldo total mensual:&nbsp;
                <span className="font-mono text-ink">{ARS(empleados.reduce((s, u) => s + (Number(u.sueldo) || 0), 0))}</span>
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Historial panel */}
      {selectedUser && (
        <HistorialEmpleadoPanel user={selectedUser} onClose={() => setSelectedUser(null)} refreshKey={refreshKey} />
      )}

      {/* Modales */}
      {editingUser && (
        <EditSueldoModal user={editingUser} onClose={() => setEditingUser(null)} onSaved={handleSueldoSaved} />
      )}
      {liquidandoUser && (
        <LiquidarSueldoModal user={liquidandoUser} onClose={() => setLiquidandoUser(null)} onSaved={handleLiquidacionSaved} />
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
//  TAB 2 — COMISIONES
// ═══════════════════════════════════════════════════════════════════════════════

// ── AgregarParticipanteModal ──────────────────────────────────────────────────
function AgregarParticipanteModal({ operacion, usuarios, onClose, onSaved }) {
  const [userId,    setUserId]    = React.useState('');
  const [rol,       setRol]       = React.useState('PRODUCCION');
  const [porcentaje,setPorcentaje]= React.useState(String(PART_DEFAULTS['PRODUCCION']));
  const [saving,    setSaving]    = React.useState(false);
  const [error,     setError]     = React.useState(null);

  // Auto-actualizar porcentaje al cambiar rol
  React.useEffect(() => {
    setPorcentaje(String(PART_DEFAULTS[rol] ?? 0));
  }, [rol]);

  const montoPreview = operacion.comisionMonto != null && porcentaje
    ? Number(operacion.comisionMonto) * Number(porcentaje) / 100
    : null;

  async function handleGuardar() {
    if (!userId)    { setError('Seleccioná un empleado.'); return; }
    if (!porcentaje || Number(porcentaje) <= 0) { setError('El porcentaje debe ser mayor a 0.'); return; }
    setSaving(true); setError(null);
    try {
      const r = await fetch(`${API_BASE}/api/operaciones/${operacion.id}/participantes`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, rol, porcentaje: Number(porcentaje) }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'Error al agregar.'); return; }
      onSaved(data); onClose();
    } catch { setError('Error de red.'); }
    finally  { setSaving(false); }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
      <div className="bg-white rounded-lg shadow-pop w-[440px] p-6 fade-in" onClick={e => e.stopPropagation()}>
        <h2 className="font-serif text-[22px] text-ink leading-tight mb-0.5">Agregar participante</h2>
        <p className="text-[12px] text-slate-400 mb-5 font-mono">
          {operacion.propiedad?.direccion || `Op. ${operacion.id?.slice(-8).toUpperCase()}`}
        </p>

        <div className="space-y-4">
          {/* Empleado */}
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Empleado</label>
            <select value={userId} onChange={e => setUserId(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400 bg-white">
              <option value="">— Seleccioná —</option>
              {usuarios.map(u => (
                <option key={u.id} value={u.id}>
                  {nombreCompleto(u)} · {ROL_LABELS[u.rol] || u.rol}
                </option>
              ))}
            </select>
          </div>

          {/* Rol de participación */}
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Rol en la operación</label>
            <select value={rol} onChange={e => setRol(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400 bg-white">
              {Object.entries(PART_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v} (default {PART_DEFAULTS[k]}%)</option>
              ))}
            </select>
          </div>

          {/* Porcentaje */}
          <div>
            <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Porcentaje (%)</label>
            <input type="number" min="0.01" max="100" step="0.01" value={porcentaje}
              onChange={e => setPorcentaje(e.target.value)}
              className="w-full border border-slate-200 rounded px-3 py-2 text-[13px] font-mono focus:outline-none focus:border-slate-400" />
          </div>

          {/* Preview de monto */}
          {montoPreview != null && (
            <div className="bg-slate-50 rounded px-4 py-3 flex items-center justify-between">
              <span className="text-[12px] text-slate-500">Monto calculado</span>
              <span className="font-mono font-semibold text-ink text-[14px]">{ARS(montoPreview)}</span>
            </div>
          )}
        </div>

        {error && <p className="mt-3 text-[12px] text-bad">{error}</p>}
        <div className="mt-5 flex items-center justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-[13px] text-slate-600 hover:text-ink transition-colors">Cancelar</button>
          <button onClick={handleGuardar} disabled={saving}
            className="px-4 py-2 text-[13px] bg-slate-700 text-white rounded hover:bg-slate-600 disabled:opacity-50 transition-colors">
            {saving ? 'Agregando…' : 'Agregar'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── LiquidarComisionesModal ───────────────────────────────────────────────────
function LiquidarComisionesModal({ operacion, participantes, onClose, onSaved }) {
  const [fecha,   setFecha]   = React.useState(hoyISO());
  const [saving,  setSaving]  = React.useState(false);
  const [error,   setError]   = React.useState(null);

  const pendientes  = participantes.filter(p => !p.liquidado);
  const totalMonto  = pendientes.reduce((s, p) => s + (p.monto || 0), 0);

  async function handleLiquidar() {
    if (pendientes.length === 0) { setError('No hay participantes pendientes.'); return; }
    setSaving(true); setError(null);
    try {
      const r = await fetch(`${API_BASE}/api/operaciones/${operacion.id}/liquidar-comisiones`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fecha }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'Error al liquidar.'); return; }
      onSaved(data); onClose();
    } catch { setError('Error de red.'); }
    finally  { setSaving(false); }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
      <div className="bg-white rounded-lg shadow-pop w-[520px] p-6 fade-in" onClick={e => e.stopPropagation()}>
        <h2 className="font-serif text-[22px] text-ink leading-tight mb-0.5">Liquidar comisiones</h2>
        <p className="text-[12px] text-slate-400 mb-5 font-mono">
          {operacion.propiedad?.direccion || `Op. ${operacion.id?.slice(-8).toUpperCase()}`}
          {operacion.comisionMonto != null && (
            <span className="ml-2 text-slate-400">· Comisión total {ARS(operacion.comisionMonto)}</span>
          )}
        </p>

        {/* Tabla de participantes pendientes */}
        <div className="border border-slate-100 rounded-lg overflow-hidden mb-4">
          <table className="w-full text-[12px]">
            <thead>
              <tr className="bg-slate-50/60 border-b border-slate-100">
                <th className="text-left px-4 py-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Empleado</th>
                <th className="text-left px-3 py-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Rol</th>
                <th className="text-right px-3 py-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">%</th>
                <th className="text-right px-4 py-2 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Monto</th>
              </tr>
            </thead>
            <tbody>
              {pendientes.length === 0 && (
                <tr><td colSpan={4} className="px-4 py-6 text-center text-[12px] text-slate-400">Sin participantes pendientes.</td></tr>
              )}
              {pendientes.map(p => (
                <tr key={p.id} className="border-b border-slate-50">
                  <td className="px-4 py-2.5 text-ink">{nombreCompleto(p.user)}</td>
                  <td className="px-3 py-2.5">
                    <span className="text-[10px] px-1.5 py-0.5 rounded"
                      style={{ background: (PART_COLORS[p.rol] || '#677A88') + '18', color: PART_COLORS[p.rol] || '#677A88' }}>
                      {PART_LABELS[p.rol] || p.rol}
                    </span>
                  </td>
                  <td className="px-3 py-2.5 text-right font-mono text-slate-500">{p.porcentaje}%</td>
                  <td className="px-4 py-2.5 text-right font-mono font-semibold text-ink">
                    {p.monto != null ? ARS(p.monto) : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {pendientes.length > 0 && (
            <div className="px-4 py-2.5 bg-slate-50/60 border-t border-slate-100 flex items-center justify-between">
              <span className="text-[11px] text-slate-400">{pendientes.length} participante{pendientes.length !== 1 ? 's' : ''}</span>
              <span className="font-mono font-semibold text-ink text-[13px]">{ARS(totalMonto)}</span>
            </div>
          )}
        </div>

        {/* Fecha de pago */}
        <div>
          <label className="block text-[11px] uppercase tracking-[0.1em] text-slate-500 mb-1.5">Fecha de pago</label>
          <input type="date" value={fecha} onChange={e => setFecha(e.target.value)}
            className="border border-slate-200 rounded px-3 py-2 text-[13px] focus:outline-none focus:border-slate-400 font-mono" />
        </div>

        {error && <p className="mt-3 text-[12px] text-bad">{error}</p>}
        <div className="mt-5 flex items-center justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-[13px] text-slate-600 hover:text-ink transition-colors">Cancelar</button>
          <button onClick={handleLiquidar} disabled={saving || pendientes.length === 0}
            className="px-4 py-2 text-[13px] bg-ok text-white rounded hover:opacity-90 disabled:opacity-50 transition-colors font-medium">
            {saving ? 'Liquidando…' : `Liquidar ${pendientes.length} comisión${pendientes.length !== 1 ? 'es' : ''}`}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── ParticipantesPanel ────────────────────────────────────────────────────────
function ParticipantesPanel({ operacion, usuarios, onClose, onLiquidado }) {
  const [participantes, setParticipantes] = React.useState([]);
  const [loading,       setLoading]       = React.useState(true);
  const [error,         setError]         = React.useState(null);
  const [editingId,     setEditingId]     = React.useState(null);
  const [editPct,       setEditPct]       = React.useState('');
  const [editSaving,    setEditSaving]    = React.useState(false);
  const [agregando,     setAgregando]     = React.useState(false);
  const [liquidando,    setLiquidando]    = React.useState(false);
  const [refreshKey,    setRefreshKey]    = React.useState(0);

  React.useEffect(() => {
    setLoading(true); setError(null);
    fetch(`${API_BASE}/api/operaciones/${operacion.id}/participantes`, { credentials: 'include' })
      .then(r => r.ok ? r.json() : Promise.reject(r))
      .then(data => setParticipantes(Array.isArray(data) ? data : []))
      .catch(() => setError('Error al cargar participantes.'))
      .finally(() => setLoading(false));
  }, [operacion.id, refreshKey]);

  async function handleSavePct(p) {
    const pct = Number(editPct);
    if (isNaN(pct) || pct <= 0 || pct > 100) { setEditingId(null); return; }
    setEditSaving(true);
    try {
      const r = await fetch(`${API_BASE}/api/operaciones/${operacion.id}/participantes/${p.id}`, {
        method: 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ porcentaje: pct }),
      });
      const data = await r.json();
      if (r.ok) {
        setParticipantes(prev => prev.map(x => x.id === p.id ? data : x));
      }
    } catch { /* silencioso */ }
    finally { setEditSaving(false); setEditingId(null); }
  }

  async function handleDelete(p) {
    if (!window.confirm(`¿Eliminar a ${nombreCompleto(p.user)} de los participantes?`)) return;
    try {
      const r = await fetch(`${API_BASE}/api/operaciones/${operacion.id}/participantes/${p.id}`, {
        method: 'DELETE', credentials: 'include',
      });
      if (r.ok) setParticipantes(prev => prev.filter(x => x.id !== p.id));
    } catch { /* silencioso */ }
  }

  function handleParticipanteAgregado(newPart) {
    setParticipantes(prev => [...prev, newPart]);
  }

  function handleLiquidadoSaved() {
    setRefreshKey(k => k + 1);
    onLiquidado(operacion.id);
  }

  const pendientes  = participantes.filter(p => !p.liquidado);
  const totalMonto  = pendientes.reduce((s, p) => s + (p.monto || 0), 0);

  return (
    <div className="flex-1 min-w-0 pl-8 border-l border-slate-100 fade-in">
      {/* Header */}
      <div className="flex items-start justify-between mb-5">
        <div>
          <h2 className="font-serif text-[22px] text-ink leading-tight">
            {operacion.propiedad?.direccion || `Op. ${operacion.id?.slice(-8).toUpperCase()}`}
          </h2>
          <p className="text-[12px] text-slate-500 mt-0.5">
            Participantes de comisión
            {operacion.comisionMonto != null && (
              <span className="ml-2 text-slate-400">· Comisión {ARS(operacion.comisionMonto)}</span>
            )}
          </p>
        </div>
        <button onClick={onClose} className="p-1.5 rounded hover:bg-slate-100 text-slate-400 hover:text-ink transition-colors flex-shrink-0">
          <I.X size={15} />
        </button>
      </div>

      {loading && <p className="text-[13px] text-slate-400 py-8 text-center">Cargando…</p>}
      {error   && <p className="text-[13px] text-bad py-4">{error}</p>}

      {!loading && !error && (
        <>
          {/* Tabla participantes */}
          <div className="bg-white border border-slate-100 rounded-lg shadow-card overflow-hidden mb-4">
            <table className="w-full text-[12px]">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50/60">
                  <th className="text-left px-4 py-2.5 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Empleado</th>
                  <th className="text-left px-3 py-2.5 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Rol</th>
                  <th className="text-right px-3 py-2.5 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">%</th>
                  <th className="text-right px-4 py-2.5 text-[10px] uppercase tracking-[0.1em] text-slate-400 font-medium">Monto</th>
                  <th className="px-3 py-2.5"></th>
                </tr>
              </thead>
              <tbody>
                {participantes.length === 0 && (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-[12px] text-slate-400">Sin participantes. Agregá el primero.</td></tr>
                )}
                {participantes.map(p => {
                  const color     = PART_COLORS[p.rol] || '#677A88';
                  const isEditing = editingId === p.id;
                  return (
                    <tr key={p.id} className="border-b border-slate-50">
                      <td className="px-4 py-2.5">
                        <div className="text-ink font-medium leading-none">{nombreCompleto(p.user)}</div>
                        <div className="text-[10px] text-slate-400 mt-0.5">{p.user?.email}</div>
                      </td>
                      <td className="px-3 py-2.5">
                        <span className="text-[10px] px-1.5 py-0.5 rounded font-medium"
                          style={{ background: color + '18', color }}>
                          {PART_LABELS[p.rol] || p.rol}
                        </span>
                      </td>
                      <td className="px-3 py-2.5 text-right">
                        {isEditing ? (
                          <div className="flex items-center justify-end gap-1">
                            <input type="number" min="0.01" max="100" step="0.01" value={editPct}
                              onChange={e => setEditPct(e.target.value)}
                              onKeyDown={e => { if (e.key === 'Enter') handleSavePct(p); if (e.key === 'Escape') setEditingId(null); }}
                              className="w-16 border border-slate-300 rounded px-2 py-0.5 text-[12px] font-mono focus:outline-none focus:border-slate-500 text-right"
                              autoFocus />
                            <button onClick={() => handleSavePct(p)} disabled={editSaving}
                              className="p-1 rounded text-ok hover:bg-slate-100 transition-colors">
                              <CheckSmIcon size={12} />
                            </button>
                          </div>
                        ) : (
                          <span className={`font-mono ${p.liquidado ? 'text-slate-400' : 'text-ink'}`}>{p.porcentaje}%</span>
                        )}
                      </td>
                      <td className="px-4 py-2.5 text-right font-mono text-ink">
                        {p.monto != null ? ARS(p.monto) : '—'}
                        {p.liquidado && (
                          <div className="text-[10px] text-ok mt-0.5">✓ Liquidado</div>
                        )}
                      </td>
                      <td className="px-3 py-2.5">
                        {!p.liquidado && (
                          <div className="flex items-center gap-1">
                            <button onClick={() => { setEditingId(p.id); setEditPct(String(p.porcentaje)); }}
                              className="p-1 rounded text-slate-400 hover:text-ink hover:bg-slate-100 transition-colors">
                              <PencilIcon size={11} />
                            </button>
                            <button onClick={() => handleDelete(p)}
                              className="p-1 rounded text-slate-400 hover:text-bad hover:bg-slate-100 transition-colors">
                              <TrashIcon size={11} />
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            {participantes.length > 0 && pendientes.length > 0 && (
              <div className="px-4 py-2.5 bg-slate-50/60 border-t border-slate-100 flex items-center justify-between">
                <span className="text-[11px] text-slate-400">{pendientes.length} pendiente{pendientes.length !== 1 ? 's' : ''}</span>
                <span className="font-mono font-semibold text-ink text-[13px]">{ARS(totalMonto)}</span>
              </div>
            )}
          </div>

          {/* Acciones */}
          <div className="flex items-center gap-2">
            <button onClick={() => setAgregando(true)}
              className="flex items-center gap-1.5 px-3 py-1.5 text-[12px] border border-slate-200 rounded hover:bg-slate-50 text-slate-600 hover:text-ink transition-colors">
              <I.Plus size={12} />
              Agregar participante
            </button>
            {pendientes.length > 0 && (
              <button onClick={() => setLiquidando(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-[12px] bg-ok text-white rounded hover:opacity-90 transition-colors font-medium">
                Liquidar {pendientes.length} comisión{pendientes.length !== 1 ? 'es' : ''}
              </button>
            )}
          </div>
        </>
      )}

      {/* Modales */}
      {agregando && (
        <AgregarParticipanteModal
          operacion={operacion}
          usuarios={usuarios}
          onClose={() => setAgregando(false)}
          onSaved={newPart => { handleParticipanteAgregado(newPart); setAgregando(false); }}
        />
      )}
      {liquidando && (
        <LiquidarComisionesModal
          operacion={operacion}
          participantes={participantes}
          onClose={() => setLiquidando(false)}
          onSaved={handleLiquidadoSaved}
        />
      )}
    </div>
  );
}

// ── TabComisiones ─────────────────────────────────────────────────────────────
function TabComisiones() {
  const [ops,       setOps]       = React.useState([]);
  const [usuarios,  setUsuarios]  = React.useState([]);
  const [loading,   setLoading]   = React.useState(true);
  const [error,     setError]     = React.useState(null);
  const [selectedOp, setSelectedOp] = React.useState(null);

  React.useEffect(() => {
    // Cargar operaciones COBRADA con comisionLiquidada=false + usuarios activos en paralelo
    Promise.all([
      fetch(`${API_BASE}/api/operaciones?estado=COBRADA&comisionLiquidada=false&limit=100`, { credentials: 'include' })
        .then(r => r.ok ? r.json() : Promise.reject(r)),
      fetch(`${API_BASE}/api/usuarios?activo=true`, { credentials: 'include' })
        .then(r => r.ok ? r.json() : Promise.reject(r)),
    ])
      .then(([opsRes, usersRes]) => {
        const opsArr   = Array.isArray(opsRes?.data) ? opsRes.data : (Array.isArray(opsRes) ? opsRes : []);
        setOps(opsArr);
        setUsuarios(Array.isArray(usersRes) ? usersRes : []);
      })
      .catch(() => setError('Error al cargar datos.'))
      .finally(() => setLoading(false));
  }, []);

  // Cuando se liquida una operación, removerla de la lista
  function handleLiquidado(opId) {
    setOps(prev => prev.filter(o => o.id !== opId));
    setSelectedOp(null);
  }

  if (loading) return <p className="text-[13px] text-slate-400 py-16 text-center">Cargando operaciones…</p>;
  if (error)   return <p className="text-[13px] text-bad py-6">{error}</p>;

  return (
    <div className="flex gap-8 items-start">
      {/* Tabla de operaciones */}
      <div className={selectedOp ? 'w-[620px] flex-shrink-0' : 'w-full'}>
        <div className="bg-white border border-slate-100 rounded-lg shadow-card overflow-hidden">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="border-b border-slate-100 bg-slate-50/60">
                <th className="text-left px-5 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Fecha</th>
                <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Propiedad</th>
                <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Broker</th>
                <th className="text-right px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Comisión</th>
                <th className="text-right px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Participantes</th>
              </tr>
            </thead>
            <tbody>
              {ops.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-5 py-16 text-center">
                    <p className="text-[13px] text-slate-400">No hay operaciones con comisiones pendientes de liquidar.</p>
                    <p className="text-[12px] text-slate-400 mt-1">Las operaciones aparecen aquí cuando están en estado COBRADA.</p>
                  </td>
                </tr>
              )}
              {ops.map(op => {
                const isSelected = selectedOp?.id === op.id;
                const direccion  = op.propiedad?.direccion || `Op. ${op.id?.slice(-8).toUpperCase()}`;
                return (
                  <tr key={op.id} onClick={() => setSelectedOp(isSelected ? null : op)}
                    className={`border-b border-slate-50 tr-hover cursor-pointer ${isSelected ? 'bg-slate-50/70' : ''}`}>
                    <td className="px-5 py-3 font-mono text-slate-500 whitespace-nowrap">{fmtFecha(op.fecha)}</td>
                    <td className="px-4 py-3">
                      <div className="text-ink font-medium leading-none truncate max-w-[200px]">{direccion}</div>
                      <div className="text-[11px] text-slate-400 mt-0.5">{op.tipo}</div>
                    </td>
                    <td className="px-4 py-3 text-slate-600">
                      {op.broker ? `${op.broker.nombre} ${op.broker.apellido}` : '—'}
                    </td>
                    <td className="px-4 py-3 text-right font-mono text-ink">
                      {op.comisionMonto != null ? ARS(op.comisionMonto) : '—'}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <span className="text-[11px] px-2 py-0.5 rounded bg-slate-100 text-slate-500">
                        {isSelected ? 'Ver →' : 'Configurar'}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {ops.length > 0 && (
            <div className="px-5 py-3 border-t border-slate-50 bg-slate-50/40">
              <span className="text-[11px] text-slate-400">{ops.length} operación{ops.length !== 1 ? 'es' : ''} con comisiones pendientes</span>
            </div>
          )}
        </div>
      </div>

      {/* Panel de participantes */}
      {selectedOp && (
        <ParticipantesPanel
          operacion={selectedOp}
          usuarios={usuarios}
          onClose={() => setSelectedOp(null)}
          onLiquidado={handleLiquidado}
        />
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
//  TAB 3 — HISTORIAL
// ═══════════════════════════════════════════════════════════════════════════════

function TabHistorial() {
  const [movs,    setMovs]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error,   setError]   = React.useState(null);

  React.useEffect(() => {
    // Traer sueldos y comisiones en paralelo
    Promise.all([
      fetch(`${API_BASE}/api/finanzas?tipo=EGRESO&categoria=SUELDO`, { credentials: 'include' })
        .then(r => r.ok ? r.json() : Promise.reject(r)),
      fetch(`${API_BASE}/api/finanzas?tipo=EGRESO&categoria=COMISION`, { credentials: 'include' })
        .then(r => r.ok ? r.json() : Promise.reject(r)),
    ])
      .then(([sueldos, comisiones]) => {
        const all = [
          ...(Array.isArray(sueldos)   ? sueldos   : []),
          ...(Array.isArray(comisiones) ? comisiones : []),
        ];
        all.sort((a, b) => (b.fecha || '').localeCompare(a.fecha || ''));
        setMovs(all);
      })
      .catch(() => setError('Error al cargar historial.'))
      .finally(() => setLoading(false));
  }, []);

  const totalSueldos   = movs.filter(m => m.categoria === 'SUELDO')  .reduce((s, m) => s + (m.monto || 0), 0);
  const totalComisiones= movs.filter(m => m.categoria === 'COMISION').reduce((s, m) => s + (m.monto || 0), 0);

  if (loading) return <p className="text-[13px] text-slate-400 py-16 text-center">Cargando historial…</p>;
  if (error)   return <p className="text-[13px] text-bad py-6">{error}</p>;

  return (
    <div>
      {/* KPIs rápidos */}
      {movs.length > 0 && (
        <div className="grid grid-cols-3 gap-4 mb-6">
          {[
            { label: 'Total pagado', value: ARS(totalSueldos + totalComisiones) },
            { label: 'En sueldos',   value: ARS(totalSueldos)   },
            { label: 'En comisiones',value: ARS(totalComisiones) },
          ].map(k => (
            <div key={k.label} className="bg-white border border-slate-100 rounded-lg shadow-card px-5 py-4">
              <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400 mb-1">{k.label}</div>
              <div className="font-mono font-semibold text-ink text-[18px]">{k.value}</div>
            </div>
          ))}
        </div>
      )}

      {/* Tabla */}
      <div className="bg-white border border-slate-100 rounded-lg shadow-card overflow-hidden">
        <table className="w-full text-[13px]">
          <thead>
            <tr className="border-b border-slate-100 bg-slate-50/60">
              <th className="text-left px-5 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Fecha</th>
              <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Tipo</th>
              <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Empleado</th>
              <th className="text-left px-4 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Descripción</th>
              <th className="text-right px-5 py-3 text-[10px] uppercase tracking-[0.12em] text-slate-400 font-medium">Monto</th>
            </tr>
          </thead>
          <tbody>
            {movs.length === 0 && (
              <tr><td colSpan={5} className="px-5 py-16 text-center text-[13px] text-slate-400">Sin liquidaciones registradas.</td></tr>
            )}
            {movs.map(m => {
              const isSueldo = m.categoria === 'SUELDO';
              return (
                <tr key={m.id} className="border-b border-slate-50 tr-hover">
                  <td className="px-5 py-3 font-mono text-slate-500 whitespace-nowrap">{fmtFecha(m.fecha)}</td>
                  <td className="px-4 py-3">
                    <span className={`text-[10px] px-2 py-0.5 rounded font-medium uppercase tracking-[0.06em] ${
                      isSueldo
                        ? 'bg-slate-100 text-slate-600'
                        : 'bg-green-50 text-ok'
                    }`}>
                      {isSueldo ? 'Sueldo' : 'Comisión'}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-ink">
                    {m.usuario ? nombreCompleto(m.usuario) : '—'}
                  </td>
                  <td className="px-4 py-3 text-slate-500 text-[12px] max-w-[260px] truncate">{m.descripcion}</td>
                  <td className="px-5 py-3 text-right font-mono font-semibold text-ink whitespace-nowrap">{ARS(m.monto)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {movs.length > 0 && (
          <div className="px-5 py-3 border-t border-slate-50 bg-slate-50/40 flex items-center justify-between">
            <span className="text-[11px] text-slate-400">{movs.length} registro{movs.length !== 1 ? 's' : ''}</span>
            <span className="font-mono font-semibold text-ink text-[13px]">{ARS(totalSueldos + totalComisiones)}</span>
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
//  MAIN — Sueldos
// ═══════════════════════════════════════════════════════════════════════════════

function Sueldos() {
  const [tab, setTab] = React.useState('empleados');

  const TABS = [
    { id: 'empleados',  label: 'Empleados',   desc: 'Sueldos fijos y liquidaciones' },
    { id: 'comisiones', label: 'Comisiones',  desc: 'Operaciones cobradas pendientes de liquidar' },
    { id: 'historial',  label: 'Historial',   desc: 'Todos los pagos realizados' },
  ];

  return (
    <div className="fade-in">
      {/* Page header */}
      <div className="mb-6">
        <div className="text-[11px] uppercase tracking-[0.14em] text-slate-400 font-medium mb-1">RRHH · Finanzas</div>
        <h1 className="font-serif text-[34px] text-ink leading-none">Sueldos</h1>
        <p className="text-[13px] text-slate-500 mt-1.5">Gestión de sueldos y liquidación de comisiones del equipo</p>
      </div>

      {/* Tab navigation */}
      <div className="flex items-center gap-1 mb-6 border-b border-slate-100">
        {TABS.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`px-4 py-2.5 text-[13px] font-medium relative transition-colors ${
              tab === t.id
                ? 'text-ink'
                : 'text-slate-400 hover:text-slate-600'
            }`}
          >
            {t.label}
            {tab === t.id && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gold rounded-t" />
            )}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div key={tab}>
        {tab === 'empleados'  && <TabEmpleados />}
        {tab === 'comisiones' && <TabComisiones />}
        {tab === 'historial'  && <TabHistorial />}
      </div>
    </div>
  );
}

window.Sueldos = Sueldos;
