/* RRHH VIEW — Dashboard de asistencia + gestion de empleados
   Hydrated: recibe { user, onNavigate, onLogout } desde MainApp.
   Pestanas: Dashboard | Empleados */

function RRHHView({ user, onNavigate, onLogout }) {
  const u = user || { full_name: 'RRHH User', code: '1-0000', role: 'rrhh' };
  const initials = u.full_name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase();

  const [tab, setTab] = React.useState('dashboard');

  // Dashboard state
  const [dash, setDash] = React.useState(null);
  const [loadingDash, setLoadingDash] = React.useState(true);

  // Attendance state
  const [attendance, setAttendance] = React.useState([]);
  const [attTotal, setAttTotal] = React.useState(0);
  const [attPage, setAttPage] = React.useState(1);
  const [dateFrom, setDateFrom] = React.useState('');
  const [dateTo, setDateTo] = React.useState('');

  // Employees state
  const [employees, setEmployees] = React.useState([]);
  const [loadingEmps, setLoadingEmps] = React.useState(false);
  const [empSearch, setEmpSearch] = React.useState('');
  const [empCompany, setEmpCompany] = React.useState('');
  const [empStatus, setEmpStatus] = React.useState('');
  const [showEmpModal, setShowEmpModal] = React.useState(false);
  const [editingEmp, setEditingEmp] = React.useState(null);

  // Load dashboard
  React.useEffect(() => {
    if (tab !== 'dashboard') return;
    setLoadingDash(true);
    window.apiFetch('/api/rrhh/dashboard')
      .then(r => r.ok ? r.json() : null)
      .then(data => setDash(data))
      .catch(() => {})
      .finally(() => setLoadingDash(false));
  }, [tab]);

  // Load attendance
  React.useEffect(() => {
    if (tab !== 'dashboard') return;
    let url = `/api/rrhh/attendance?page=${attPage}&limit=15`;
    if (dateFrom) url += `&dateFrom=${dateFrom}`;
    if (dateTo) url += `&dateTo=${dateTo}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { employees: [], total: 0 })
      .then(data => { setAttendance(data.employees || []); setAttTotal(data.total || 0); })
      .catch(() => {});
  }, [tab, attPage, dateFrom, dateTo]);

  // Load employees
  React.useEffect(() => {
    if (tab !== 'employees') return;
    setLoadingEmps(true);
    let url = '/api/rrhh/employees?';
    if (empSearch) url += `&search=${encodeURIComponent(empSearch)}`;
    if (empCompany) url += `&company=${empCompany}`;
    if (empStatus) url += `&status=${empStatus}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { employees: [] })
      .then(data => setEmployees(data.employees || []))
      .catch(() => {})
      .finally(() => setLoadingEmps(false));
  }, [tab, empSearch, empCompany, empStatus]);

  function exportAttendanceCSV() {
    let url = `/api/rrhh/attendance?page=1&limit=9999`;
    if (dateFrom) url += `&dateFrom=${dateFrom}`;
    if (dateTo) url += `&dateTo=${dateTo}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { employees: [] })
      .then(data => {
        const rows = data.employees || [];
        if (rows.length === 0) return;
        const headers = ['Codigo', 'Nombre', 'Area', 'Total citas', 'Atendidas', 'Canceladas', 'No asistio', 'Pendientes'];
        const csvRows = [headers.join(',')];
        rows.forEach(e => {
          csvRows.push([
            e.code,
            `"${(e.full_name || '').replace(/"/g, '""')}"`,
            `"${(e.area || '').replace(/"/g, '""')}"`,
            e.total, e.completed, e.cancelled, e.no_show, e.pending,
          ].join(','));
        });
        const blob = new Blob(['﻿' + csvRows.join('\n')], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        const label = dateFrom && dateTo ? `${dateFrom}_a_${dateTo}` : 'mes_actual';
        link.download = `reporte_asistencia_${label}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
      });
  }

  const TABS = [
    { key: 'dashboard', label: 'Asistencia', icon: <I.chart/> },
    { key: 'employees', label: 'Colaboradores', icon: <I.users/> },
  ];

  const COMPANY_OPTIONS = [
    { value: '1', label: 'Polytec' },
    { value: '3', label: 'Polinter' },
    { value: '4', label: 'Lacoplast' },
  ];

  const companyName = (code) => {
    const p = code?.split('-')[0];
    return p === '1' ? 'Polytec' : p === '3' ? 'Polinter' : p === '4' ? 'Lacoplast' : p;
  };

  const attTotalPages = Math.ceil(attTotal / 15);

  return (
    <div className="flex bg-paper min-h-screen font-sans text-ink">
      {/* SIDEBAR */}
      <aside className="w-[232px] shrink-0 bg-midnight-950 text-white px-4 py-6 flex flex-col sticky top-0 h-screen overflow-y-auto">
        <div className="px-2 mb-8"><Logo tone="light"/></div>

        <div className="px-2 mb-2 text-[10.5px] uppercase tracking-[0.16em] text-white/30 font-medium">Recursos Humanos</div>
        <nav className="space-y-1">
          {TABS.map(t => (
            <a key={t.key} onClick={() => setTab(t.key)}
              className={`flex items-center gap-3 h-10 px-3 rounded-lg text-[13px] font-medium cursor-pointer transition
                ${tab === t.key ? 'bg-white/10 text-white' : 'text-white/55 hover:bg-white/5 hover:text-white/80'}`}>
              <span className={`h-4 w-4 ${tab === t.key ? 'text-mint-300' : ''}`}>{t.icon}</span>
              <span className="flex-1">{t.label}</span>
            </a>
          ))}
        </nav>

        <div className="px-2 mt-7 mb-2 text-[10.5px] uppercase tracking-[0.16em] text-white/30 font-medium">Navegacion</div>
        <nav className="space-y-1">
          <a onClick={() => onNavigate && onNavigate('employee')} className="flex items-center gap-3 h-10 px-3 rounded-lg text-[13px] font-medium cursor-pointer text-white/55 hover:bg-white/5 hover:text-white/80">
            <span className="h-4 w-4"><I.cal/></span><span className="flex-1">Mis citas</span>
          </a>
          <a onClick={() => onNavigate && onNavigate('patient')} className="flex items-center gap-3 h-10 px-3 rounded-lg text-[13px] font-medium cursor-pointer text-white/55 hover:bg-white/5 hover:text-white/80">
            <span className="h-4 w-4"><I.plus/></span><span className="flex-1">Agendar cita</span>
          </a>
        </nav>

        <div className="mt-auto pt-4 border-t border-white/10">
          <div className="flex items-center gap-3 px-3 py-2 rounded-lg">
            <div className="h-8 w-8 rounded-full bg-midnight-700 grid place-items-center text-[11px] font-bold text-white">{initials}</div>
            <div className="min-w-0 flex-1">
              <div className="text-[12.5px] font-medium text-white/90 truncate">{u.full_name}</div>
              <div className="text-[10.5px] text-white/40">RRHH</div>
            </div>
          </div>
          <button onClick={onLogout} className="w-full h-9 rounded-lg text-white/60 text-[12.5px] hover:bg-white/5 hover:text-white/80 mt-1">
            Cerrar sesion
          </button>
        </div>
      </aside>

      {/* MAIN */}
      <main className="flex-1 min-w-0 overflow-y-auto">
        {/* TOPBAR */}
        <div className="sticky top-0 z-10 bg-white/80 backdrop-blur-md border-b border-line px-8 h-14 flex items-center justify-between">
          <div className="text-[15px] font-semibold text-midnight-900">
            {tab === 'dashboard' ? 'Dashboard de asistencia' : 'Gestion de colaboradores'}
          </div>
          <div className="flex items-center gap-3 text-[12.5px] text-slate-500">
            <I.shield className="h-4 w-4 text-midnight-600"/>
            <span>Recursos Humanos</span>
          </div>
        </div>

        <div className="p-8 max-w-[1200px] mx-auto">

          {/* ── DASHBOARD ── */}
          {tab === 'dashboard' && (
            <>
              {/* KPIs */}
              {loadingDash ? (
                <div className="grid grid-cols-4 gap-4 mb-6">
                  {[1,2,3,4].map(i => (
                    <div key={i} className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card animate-pulse h-[100px]"/>
                  ))}
                </div>
              ) : dash && (
                <>
                  <div className="grid grid-cols-4 gap-4 mb-6">
                    <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                      <div className="text-[12px] text-slate-500 font-medium">Citas del mes</div>
                      <div className="mt-2 text-[28px] font-semibold text-midnight-900 tnum">{dash.totalMonth}</div>
                      <div className="text-[11px] text-slate-400 mt-1">total registradas</div>
                    </div>
                    <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                      <div className="text-[12px] text-slate-500 font-medium">Tasa de asistencia</div>
                      <div className="mt-2 text-[28px] font-semibold text-mint-700 tnum">{dash.attendanceRate}%</div>
                      <div className="text-[11px] text-slate-400 mt-1">{dash.completed} atendidas</div>
                    </div>
                    <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                      <div className="text-[12px] text-slate-500 font-medium">Inasistencias</div>
                      <div className="mt-2 text-[28px] font-semibold text-rose-600 tnum">{dash.noShow}</div>
                      <div className="text-[11px] text-slate-400 mt-1">no asistieron</div>
                    </div>
                    <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                      <div className="text-[12px] text-slate-500 font-medium">Colaboradores activos</div>
                      <div className="mt-2 text-[28px] font-semibold text-midnight-900 tnum">{dash.uniqueEmployees}</div>
                      <div className="text-[11px] text-slate-400 mt-1">de {dash.totalEmployees} registrados</div>
                    </div>
                  </div>

                  {/* Mini cards fila 2 */}
                  <div className="grid grid-cols-3 gap-4 mb-8">
                    <div className="bg-white rounded-2xl ring-1 ring-line p-4 shadow-card flex items-center gap-4">
                      <div className="h-10 w-10 rounded-xl bg-mint-100 text-mint-700 grid place-items-center shrink-0">
                        <I.check className="h-5 w-5"/>
                      </div>
                      <div>
                        <div className="text-[20px] font-semibold text-midnight-900 tnum">{dash.completed}</div>
                        <div className="text-[11.5px] text-slate-500">Completadas</div>
                      </div>
                    </div>
                    <div className="bg-white rounded-2xl ring-1 ring-line p-4 shadow-card flex items-center gap-4">
                      <div className="h-10 w-10 rounded-xl bg-amber-50 text-amber-700 grid place-items-center shrink-0">
                        <I.clock className="h-5 w-5"/>
                      </div>
                      <div>
                        <div className="text-[20px] font-semibold text-midnight-900 tnum">{dash.pending}</div>
                        <div className="text-[11.5px] text-slate-500">Pendientes</div>
                      </div>
                    </div>
                    <div className="bg-white rounded-2xl ring-1 ring-line p-4 shadow-card flex items-center gap-4">
                      <div className="h-10 w-10 rounded-xl bg-rose-50 text-rose-700 grid place-items-center shrink-0">
                        <I.cal className="h-5 w-5"/>
                      </div>
                      <div>
                        <div className="text-[20px] font-semibold text-midnight-900 tnum">{dash.cancelled}</div>
                        <div className="text-[11.5px] text-slate-500">Canceladas</div>
                      </div>
                    </div>
                  </div>
                </>
              )}

              {/* Reporte de asistencia */}
              <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
                <div className="p-5 border-b border-line flex items-center justify-between gap-4 flex-wrap">
                  <div className="text-[14px] font-semibold text-midnight-900">Reporte de asistencia por colaborador</div>
                  <div className="flex items-center gap-3 flex-wrap">
                    <div className="flex items-center gap-2 text-[12px] text-slate-500">
                      <span>Desde</span>
                      <input type="date" value={dateFrom} onChange={e => { setDateFrom(e.target.value); setAttPage(1); }}
                        className="h-8 px-2 rounded-lg ring-1 ring-line text-[12px] text-midnight-900 bg-paper"/>
                      <span>Hasta</span>
                      <input type="date" value={dateTo} onChange={e => { setDateTo(e.target.value); setAttPage(1); }}
                        className="h-8 px-2 rounded-lg ring-1 ring-line text-[12px] text-midnight-900 bg-paper"/>
                    </div>
                    <button onClick={exportAttendanceCSV}
                      className="h-8 px-3 rounded-lg bg-mint-600 text-white text-[12px] font-medium hover:bg-mint-700 flex items-center gap-1.5">
                      <I.download className="h-3.5 w-3.5"/>Exportar
                    </button>
                    {(dateFrom || dateTo) && (
                      <a onClick={() => { setDateFrom(''); setDateTo(''); setAttPage(1); }}
                        className="text-[11.5px] text-mint-700 cursor-pointer hover:underline">Limpiar</a>
                    )}
                  </div>
                </div>

                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-slate-50/80 text-[11px] uppercase tracking-wider text-slate-500">
                      <th className="px-5 py-3 font-medium">Colaborador</th>
                      <th className="px-5 py-3 font-medium">Codigo</th>
                      <th className="px-5 py-3 font-medium">Area</th>
                      <th className="px-5 py-3 font-medium text-center">Total</th>
                      <th className="px-5 py-3 font-medium text-center">Atendidas</th>
                      <th className="px-5 py-3 font-medium text-center">Canceladas</th>
                      <th className="px-5 py-3 font-medium text-center">No asistio</th>
                      <th className="px-5 py-3 font-medium text-center">Tasa</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-line">
                    {attendance.length === 0 && (
                      <tr><td colSpan="8" className="px-5 py-8 text-center text-[13px] text-slate-400">Sin datos para el periodo seleccionado</td></tr>
                    )}
                    {attendance.map(e => {
                      const rate = e.total > 0 ? Math.round((e.completed / e.total) * 100) : 0;
                      return (
                        <tr key={e.employee_id} className="hover:bg-slate-50/50 transition">
                          <td className="px-5 py-3 text-[13px] font-medium text-midnight-900">{e.full_name}</td>
                          <td className="px-5 py-3 text-[12.5px] text-slate-600 tnum">{e.code}</td>
                          <td className="px-5 py-3 text-[12.5px] text-slate-600">{e.area || '-'}</td>
                          <td className="px-5 py-3 text-[13px] text-midnight-900 font-medium text-center tnum">{e.total}</td>
                          <td className="px-5 py-3 text-center">
                            <span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ring-1 ring-inset bg-mint-50 text-mint-700 ring-mint-200">{e.completed}</span>
                          </td>
                          <td className="px-5 py-3 text-center">
                            <span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ring-1 ring-inset bg-amber-50 text-amber-700 ring-amber-200">{e.cancelled}</span>
                          </td>
                          <td className="px-5 py-3 text-center">
                            {e.no_show > 0
                              ? <span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ring-1 ring-inset bg-rose-50 text-rose-700 ring-rose-200">{e.no_show}</span>
                              : <span className="text-[12px] text-slate-400">0</span>
                            }
                          </td>
                          <td className="px-5 py-3 text-center">
                            <div className="flex items-center justify-center gap-2">
                              <div className="w-16 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                                <div className={`h-full rounded-full ${rate >= 80 ? 'bg-mint-500' : rate >= 50 ? 'bg-amber-500' : 'bg-rose-500'}`}
                                  style={{ width: `${rate}%` }}/>
                              </div>
                              <span className="text-[11px] text-slate-600 tnum">{rate}%</span>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>

                {/* Paginacion */}
                {attTotalPages > 1 && (
                  <div className="px-5 py-3 border-t border-line flex items-center justify-between text-[12px] text-slate-500">
                    <span>{attTotal} colaboradores</span>
                    <div className="flex items-center gap-2">
                      <button disabled={attPage <= 1} onClick={() => setAttPage(p => p - 1)}
                        className="h-7 w-7 rounded-lg ring-1 ring-line grid place-items-center disabled:opacity-30 hover:bg-slate-50">
                        <I.chevL className="h-3.5 w-3.5"/>
                      </button>
                      <span className="tnum">{attPage} / {attTotalPages}</span>
                      <button disabled={attPage >= attTotalPages} onClick={() => setAttPage(p => p + 1)}
                        className="h-7 w-7 rounded-lg ring-1 ring-line grid place-items-center disabled:opacity-30 hover:bg-slate-50">
                        <I.chevR className="h-3.5 w-3.5"/>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </>
          )}

          {/* ── EMPLEADOS ── */}
          {tab === 'employees' && (
            <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
              <div className="p-5 border-b border-line flex items-center justify-between gap-4 flex-wrap">
                <div className="text-[14px] font-semibold text-midnight-900">Colaboradores</div>
                <div className="flex items-center gap-3 flex-wrap">
                  <div className="relative">
                    <I.search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"/>
                    <input value={empSearch} onChange={e => setEmpSearch(e.target.value)}
                      placeholder="Buscar por nombre..."
                      className="h-8 pl-8 pr-3 rounded-lg ring-1 ring-line text-[12px] text-midnight-900 bg-paper w-48"/>
                  </div>
                  <select value={empCompany} onChange={e => setEmpCompany(e.target.value)}
                    className="h-8 px-2 rounded-lg ring-1 ring-line text-[12px] text-midnight-900 bg-paper">
                    <option value="">Todas las empresas</option>
                    {COMPANY_OPTIONS.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
                  </select>
                  <select value={empStatus} onChange={e => setEmpStatus(e.target.value)}
                    className="h-8 px-2 rounded-lg ring-1 ring-line text-[12px] text-midnight-900 bg-paper">
                    <option value="">Todos los estados</option>
                    <option value="active">Activos</option>
                    <option value="inactive">Inactivos</option>
                  </select>
                  <button onClick={() => { setEditingEmp(null); setShowEmpModal(true); }}
                    className="h-8 px-3 rounded-lg bg-mint-600 text-white text-[12px] font-medium hover:bg-mint-700 flex items-center gap-1.5">
                    <I.plus className="h-3.5 w-3.5"/>Nuevo colaborador
                  </button>
                </div>
              </div>

              <table className="w-full text-left">
                <thead>
                  <tr className="bg-slate-50/80 text-[11px] uppercase tracking-wider text-slate-500">
                    <th className="px-5 py-3 font-medium">Nombre</th>
                    <th className="px-5 py-3 font-medium">Codigo</th>
                    <th className="px-5 py-3 font-medium">Empresa</th>
                    <th className="px-5 py-3 font-medium">Area</th>
                    <th className="px-5 py-3 font-medium">Rol</th>
                    <th className="px-5 py-3 font-medium">Estado</th>
                    <th className="px-5 py-3 font-medium text-right">Acciones</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line">
                  {loadingEmps && (
                    <tr><td colSpan="7" className="px-5 py-8 text-center text-[13px] text-slate-400">Cargando...</td></tr>
                  )}
                  {!loadingEmps && employees.length === 0 && (
                    <tr><td colSpan="7" className="px-5 py-8 text-center text-[13px] text-slate-400">Sin empleados</td></tr>
                  )}
                  {!loadingEmps && employees.map(e => (
                    <tr key={e.id} className="hover:bg-slate-50/50 transition">
                      <td className="px-5 py-3">
                        <div className="flex items-center gap-2.5">
                          <div className="h-7 w-7 rounded-full bg-midnight-100 text-midnight-700 grid place-items-center text-[10px] font-bold shrink-0">
                            {e.full_name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase()}
                          </div>
                          <span className="text-[13px] font-medium text-midnight-900">{e.full_name}</span>
                        </div>
                      </td>
                      <td className="px-5 py-3 text-[12.5px] text-slate-600 tnum">{e.code}</td>
                      <td className="px-5 py-3 text-[12.5px] text-slate-600">{companyName(e.code)}</td>
                      <td className="px-5 py-3 text-[12.5px] text-slate-600">{e.area || '-'}</td>
                      <td className="px-5 py-3">
                        <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10.5px] font-medium ring-1 ring-inset
                          ${e.role === 'admin' ? 'bg-midnight-50 text-midnight-700 ring-midnight-100' :
                            e.role === 'rrhh' ? 'bg-amber-50 text-amber-700 ring-amber-200' :
                                                'bg-slate-50 text-slate-600 ring-slate-200'}`}>
                          {e.role === 'rrhh' ? 'RRHH' : e.role === 'admin' ? 'Admin' : 'Empleado'}
                        </span>
                      </td>
                      <td className="px-5 py-3">
                        <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-medium ring-1 ring-inset
                          ${e.is_active ? 'bg-mint-50 text-mint-700 ring-mint-200' : 'bg-rose-50 text-rose-700 ring-rose-200'}`}>
                          <span className={`h-1.5 w-1.5 rounded-full ${e.is_active ? 'bg-mint-500' : 'bg-rose-500'}`}/>
                          {e.is_active ? 'Activo' : 'Inactivo'}
                        </span>
                      </td>
                      <td className="px-5 py-3 text-right">
                        <button onClick={() => { setEditingEmp(e); setShowEmpModal(true); }}
                          className="h-7 px-2.5 rounded-lg text-[11.5px] font-medium text-midnight-700 ring-1 ring-line hover:bg-slate-50">
                          Editar
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div className="px-5 py-3 border-t border-line text-[12px] text-slate-400">
                {employees.length} colaboradores
              </div>
            </div>
          )}
        </div>
      </main>

      {/* MODAL Crear/Editar empleado */}
      {showEmpModal && (
        <RRHHEmployeeModal
          employee={editingEmp}
          onClose={() => { setShowEmpModal(false); setEditingEmp(null); }}
          onSaved={() => {
            setShowEmpModal(false);
            setEditingEmp(null);
            // Refrescar lista
            setEmpSearch(s => s + ' ');
            setTimeout(() => setEmpSearch(s => s.trim()), 100);
          }}
        />
      )}
    </div>
  );
}

/* ── Modal crear/editar empleado ── */
function RRHHEmployeeModal({ employee, onClose, onSaved }) {
  const isEdit = !!employee;
  const [form, setForm] = React.useState({
    code: employee?.code || '',
    full_name: employee?.full_name || '',
    area: employee?.area || '',
    role: employee?.role || 'employee',
    email_corporate: employee?.email_corporate || '',
    eps: employee?.eps || '',
    blood_type: employee?.blood_type || '',
    phone: employee?.phone || '',
    is_active: employee?.is_active !== false,
    allowed_companies: employee?.allowed_companies || [],
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const COMPANY_CHIPS = [
    { value: '1', label: 'Polytec' },
    { value: '3', label: 'Polinter' },
    { value: '4', label: 'Lacoplast' },
  ];

  function toggleCompany(val) {
    setForm(f => ({
      ...f,
      allowed_companies: f.allowed_companies.includes(val)
        ? f.allowed_companies.filter(v => v !== val)
        : [...f.allowed_companies, val],
    }));
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setSaving(true);
    setError('');
    try {
      const url = isEdit ? `/api/rrhh/employees/${employee.id}` : '/api/rrhh/employees';
      const method = isEdit ? 'PATCH' : 'POST';
      const body = { ...form };
      if (!isEdit && !body.code) { setError('El codigo es obligatorio.'); setSaving(false); return; }
      if (!body.full_name) { setError('El nombre es obligatorio.'); setSaving(false); return; }

      const res = await window.apiFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al guardar');
      onSaved();
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  }

  const set = (key) => (e) => setForm(f => ({ ...f, [key]: e.target.value }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-midnight-950/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl ring-1 ring-line shadow-2xl w-[520px] max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="p-5 border-b border-line flex items-center justify-between">
          <div className="text-[15px] font-semibold text-midnight-900">{isEdit ? 'Editar colaborador' : 'Nuevo colaborador'}</div>
          <button onClick={onClose} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-500">
            <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Codigo *</label>
              <input value={form.code} onChange={set('code')} disabled={isEdit}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper disabled:opacity-50" placeholder="3-4148"/>
            </div>
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Nombre completo *</label>
              <input value={form.full_name} onChange={set('full_name')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Area</label>
              <input value={form.area} onChange={set('area')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Rol</label>
              <select value={form.role} onChange={set('role')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper">
                <option value="employee">Empleado</option>
                <option value="rrhh">RRHH</option>
                <option value="admin">Admin</option>
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Email corporativo</label>
              <input value={form.email_corporate} onChange={set('email_corporate')} type="email"
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Telefono</label>
              <input value={form.phone} onChange={set('phone')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">EPS</label>
              <input value={form.eps} onChange={set('eps')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Tipo de sangre</label>
              <input value={form.blood_type} onChange={set('blood_type')}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
          </div>

          {/* Empresas permitidas */}
          <div>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-2">Empresas permitidas</label>
            <div className="flex gap-2">
              {COMPANY_CHIPS.map(c => (
                <button key={c.value} type="button" onClick={() => toggleCompany(c.value)}
                  className={`h-8 px-3 rounded-lg text-[12px] font-medium transition ring-1 ring-inset
                    ${form.allowed_companies.includes(c.value)
                      ? 'bg-mint-100 text-mint-700 ring-mint-300'
                      : 'bg-paper text-slate-500 ring-line hover:bg-slate-50'}`}>
                  {c.label}
                </button>
              ))}
            </div>
          </div>

          {/* Estado (solo edicion) */}
          {isEdit && (
            <div className="flex items-center gap-3">
              <label className="text-[12px] text-slate-600">Estado:</label>
              <button type="button" onClick={() => setForm(f => ({ ...f, is_active: !f.is_active }))}
                className={`h-8 px-3 rounded-lg text-[12px] font-medium ring-1 ring-inset
                  ${form.is_active ? 'bg-mint-100 text-mint-700 ring-mint-300' : 'bg-rose-50 text-rose-700 ring-rose-200'}`}>
                {form.is_active ? 'Activo' : 'Inactivo'}
              </button>
            </div>
          )}

          {error && <div className="text-[12.5px] text-rose-600 bg-rose-50 rounded-lg p-3">{error}</div>}

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="h-9 px-4 rounded-lg text-[13px] font-medium text-slate-600 ring-1 ring-line hover:bg-slate-50">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="h-9 px-5 rounded-lg bg-mint-600 text-white text-[13px] font-medium hover:bg-mint-700 disabled:opacity-50">
              {saving ? 'Guardando...' : isEdit ? 'Guardar cambios' : 'Crear colaborador'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

window.RRHHView = RRHHView;
