/* ADMIN VIEW — dashboard + mantenimientos (empleados, profesionales, especialidades)
   Hydrated: recibe { user, onNavigate, onLogout } desde MainApp.
   Pestanas: Dashboard | Empleados | Profesionales | Especialidades */

const Sparkline = ({ data, tone='midnight', height=42 }) => {
  if (!data || data.length < 2) return null;
  const w = 140, h = height, pad = 2;
  const min = Math.min(...data), max = Math.max(...data);
  const dx = (w - pad*2) / (data.length - 1);
  const norm = (v) => h - pad - ((v - min) / (max - min || 1)) * (h - pad*2);
  const pts = data.map((v, i) => [pad + i*dx, norm(v)]);
  const path = pts.map((p,i) => (i===0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = `${path} L${w-pad},${h-pad} L${pad},${h-pad} Z`;
  const stroke = tone === 'mint' ? '#2FA176' : tone === 'rose' ? '#E11D48' : '#102452';
  const fill   = tone === 'mint' ? 'rgba(127,209,176,.20)' : tone === 'rose' ? 'rgba(225,29,72,.10)' : 'rgba(16,36,82,.10)';
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full" preserveAspectRatio="none">
      <path d={area} fill={fill}/>
      <path d={path} fill="none" stroke={stroke} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.6" fill={stroke}/>
    </svg>
  );
};

const KPICard = ({ label, value, hint, tone='midnight' }) => (
  <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
    <div className="text-[12px] text-slate-500 font-medium">{label}</div>
    <div className="mt-3 text-[26px] font-semibold text-midnight-900 tnum tracking-tight">{value}</div>
    <div className="text-[11px] text-slate-400 mt-1">{hint}</div>
  </div>
);

const StatusPill = ({ status, tone }) => {
  const map = {
    mint:     'bg-mint-50 text-mint-700 ring-mint-200',
    midnight: 'bg-midnight-50 text-midnight-700 ring-midnight-100',
    amber:    'bg-amber-50 text-amber-700 ring-amber-200',
    rose:     'bg-rose-50 text-rose-700 ring-rose-200',
    slate:    'bg-slate-50 text-slate-600 ring-slate-200',
  };
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium ring-1 ring-inset ${map[tone] || map.slate}`}>
      <StatusDot tone={tone}/>
      {status}
    </span>
  );
};

const SpecMix = ({ data }) => {
  const entries = Object.entries(data || {}).sort((a,b) => b[1] - a[1]);
  const total = entries.reduce((s, [,v]) => s + v, 0) || 1;
  const colors = ['bg-midnight-900','bg-midnight-600','bg-mint-500','bg-mint-300','bg-midnight-300','bg-slate-300'];
  return (
    <div className="bg-white rounded-2xl ring-1 ring-line p-6 shadow-card">
      <div className="text-[14px] font-semibold text-midnight-900">Mix por especialidad</div>
      <div className="text-[12px] text-slate-500 mt-0.5">% del total de citas del mes</div>
      {entries.length > 0 && (
        <>
          <div className="mt-4 flex h-2 rounded-full overflow-hidden">
            {entries.map(([,v], i) => <div key={i} className={colors[i % colors.length]} style={{width:`${(v/total)*100}%`}}/>)}
          </div>
          <div className="mt-5 space-y-2.5">
            {entries.slice(0,6).map(([name,v], i) => (
              <div key={name} className="flex items-center text-[12.5px]">
                <span className={`h-2 w-2 rounded-sm ${colors[i % colors.length]}`}/>
                <span className="ml-2.5 text-slate-700 flex-1">{name}</span>
                <span className="tnum text-midnight-900 font-medium">{Math.round((v/total)*100)}%</span>
              </div>
            ))}
          </div>
        </>
      )}
      {entries.length === 0 && <div className="mt-4 text-[12px] text-slate-400">Sin datos aun</div>}
    </div>
  );
};

/* ═══════════════════════════════════════════════════
   Modal reutilizable
   ═══════════════════════════════════════════════════ */
const AdminModal = ({ title, onClose, children }) => (
  <div className="fixed inset-0 z-50 grid place-items-center bg-midnight-950/40 backdrop-blur-sm" onClick={onClose}>
    <div className="bg-white rounded-2xl shadow-pop ring-1 ring-line w-[520px] max-h-[85vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
      <div className="flex items-center justify-between px-6 py-4 border-b border-line">
        <h3 className="text-[15px] font-semibold text-midnight-900">{title}</h3>
        <button onClick={onClose} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-slate-600">
          <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
        </button>
      </div>
      <div className="p-6 space-y-4">{children}</div>
    </div>
  </div>
);

/* Campo de formulario */
const Field = ({ label, children, hint }) => (
  <div>
    <label className="text-[12px] font-medium text-midnight-800">{label}</label>
    <div className="mt-1">{children}</div>
    {hint && <div className="text-[11px] text-slate-400 mt-1">{hint}</div>}
  </div>
);

const inputCls = "w-full h-10 rounded-xl bg-white ring-1 ring-line px-3 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-400 transition";
const selectCls = "w-full h-10 rounded-xl bg-white ring-1 ring-line px-3 text-[13px] text-midnight-900 focus:outline-none focus:ring-midnight-400 transition";
const btnPrimary = "h-10 px-5 rounded-xl bg-midnight-900 text-white text-[13px] font-semibold hover:bg-midnight-800 transition disabled:opacity-50 disabled:cursor-not-allowed";
const btnSecondary = "h-10 px-5 rounded-xl bg-white text-midnight-900 text-[13px] font-medium ring-1 ring-line hover:bg-slate-50 transition";

/* ═══════════════════════════════════════════════════
   Modal: Disponibilidad semanal de un profesional
   ═══════════════════════════════════════════════════ */
const DAY_LABELS = [
  {key:'monday',   label:'Lunes'},
  {key:'tuesday',  label:'Martes'},
  {key:'wednesday',label:'Miercoles'},
  {key:'thursday', label:'Jueves'},
  {key:'friday',   label:'Viernes'},
];

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

function AvailabilityModal({ prof, onClose }) {
  const [rows, setRows]       = React.useState(DAY_LABELS.map(d => ({ day:d.key, active:false, start:'08:00', end:'17:00', companies:[] })));
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving]   = React.useState(false);
  const [msg, setMsg]         = React.useState('');

  React.useEffect(() => {
    window.apiFetch(`/api/admin/availability/${prof.id}`)
      .then(r => r.ok ? r.json() : { availability:[] })
      .then(d => {
        const avail = d.availability || [];
        setRows(DAY_LABELS.map(dl => {
          const match = avail.find(a => a.day === dl.key && a.is_active);
          return {
            day: dl.key,
            active: !!match,
            start: match ? match.start_time.slice(0,5) : '08:00',
            end:   match ? match.end_time.slice(0,5) : '17:00',
            companies: match && Array.isArray(match.company_prefixes) ? match.company_prefixes : [],
          };
        }));
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [prof.id]);

  function updateRow(idx, field, value) {
    setRows(prev => prev.map((r,i) => i===idx ? {...r, [field]:value} : r));
  }

  async function handleSave() {
    setSaving(true); setMsg('');
    const slots = rows.filter(r => r.active).map(r => {
      const slot = { day: r.day, start_time: r.start, end_time: r.end };
      if (r.companies.length > 0) slot.company_prefixes = r.companies;
      return slot;
    });
    try {
      const res = await window.apiFetch(`/api/admin/availability/${prof.id}`, {
        method: 'PUT', body: JSON.stringify({ slots }),
      });
      const data = await res.json();
      if (res.ok) setMsg('Horario guardado');
      else setMsg(data.error || 'Error');
    } catch { setMsg('Error de conexion'); }
    finally { setSaving(false); setTimeout(() => setMsg(''), 4000); }
  }

  return (
    <AdminModal title={`Horario: ${prof.full_name}`} onClose={onClose}>
      {loading ? (
        <div className="py-8 text-center text-[13px] text-slate-400">Cargando horario...</div>
      ) : (
        <div className="space-y-2">
          {rows.map((r,i) => {
            const dl = DAY_LABELS[i];
            return (
              <div key={r.day} className={`flex items-center gap-3 rounded-xl p-3 ring-1 transition ${r.active ? 'ring-midnight-200 bg-white' : 'ring-line bg-paper/60'}`}>
                <button type="button" onClick={() => updateRow(i,'active',!r.active)}
                  className={`h-5 w-5 rounded-md grid place-items-center ring-1 shrink-0 transition
                    ${r.active ? 'bg-midnight-900 ring-midnight-900' : 'bg-white ring-slate-300'}`}>
                  {r.active && <I.check className="h-3 w-3 text-mint-300"/>}
                </button>
                <div className="w-24 text-[13px] font-medium text-midnight-900">{dl.label}</div>
                {r.active ? (
                  <div className="flex flex-col gap-1.5 flex-1">
                    <div className="flex items-center gap-2">
                      <input type="time" value={r.start} onChange={e => updateRow(i,'start',e.target.value)}
                        className="h-9 rounded-lg ring-1 ring-line px-2.5 text-[13px] tnum text-midnight-900 focus:outline-none focus:ring-midnight-300"/>
                      <span className="text-[12px] text-slate-400">a</span>
                      <input type="time" value={r.end} onChange={e => updateRow(i,'end',e.target.value)}
                        className="h-9 rounded-lg ring-1 ring-line px-2.5 text-[13px] tnum text-midnight-900 focus:outline-none focus:ring-midnight-300"/>
                      <div className="ml-auto text-[11px] text-slate-400 tnum">
                        {(() => {
                          const [sh,sm] = r.start.split(':').map(Number);
                          const [eh,em] = r.end.split(':').map(Number);
                          const mins = (eh*60+em) - (sh*60+sm);
                          return mins > 0 ? `${Math.floor(mins/60)}h ${mins%60 ? mins%60+'m' : ''}` : '';
                        })()}
                      </div>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <span className="text-[11px] text-slate-400 mr-1">Empresas:</span>
                      {COMPANY_OPTIONS.map(co => {
                        const sel = r.companies.includes(co.prefix);
                        return (
                          <button key={co.prefix} type="button"
                            onClick={() => {
                              const next = sel ? r.companies.filter(p => p !== co.prefix) : [...r.companies, co.prefix];
                              updateRow(i, 'companies', next);
                            }}
                            className={`h-6 px-2 rounded-md text-[11px] font-medium ring-1 transition
                              ${sel ? 'bg-midnight-900 text-white ring-midnight-900' : 'bg-white text-slate-500 ring-slate-200 hover:ring-slate-300'}`}>
                            {co.label}
                          </button>
                        );
                      })}
                      {r.companies.length === 0 && <span className="text-[10px] text-slate-300 ml-1">Todas</span>}
                    </div>
                  </div>
                ) : (
                  <div className="text-[12.5px] text-slate-400 italic">No atiende</div>
                )}
              </div>
            );
          })}
        </div>
      )}
      {msg && <div className={`text-[12px] font-medium ${msg.includes('guardado') ? 'text-mint-600' : 'text-rose-500'}`}>{msg}</div>}
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={onClose} className={btnSecondary}>Cerrar</button>
        <button onClick={handleSave} disabled={saving} className={btnPrimary}>
          {saving ? 'Guardando...' : 'Guardar horario'}
        </button>
      </div>
    </AdminModal>
  );
}

/* ═══════════════════════════════════════════════════
   Panel: Empleados
   ═══════════════════════════════════════════════════ */
function EmployeesPanel() {
  const [employees, setEmployees]   = React.useState([]);
  const [total, setTotal]           = React.useState(0);
  const [page, setPage]             = React.useState(1);
  const [search, setSearch]         = React.useState('');
  const [companyFilter, setCompanyFilter] = React.useState('');
  const [statusFilter, setStatusFilter]   = React.useState('');
  const [loading, setLoading]       = React.useState(true);
  const [modal, setModal]           = React.useState(null); /* null | 'create' | employee obj */
  const [saving, setSaving]         = React.useState(false);
  const [formErr, setFormErr]       = React.useState(null);
  const limit = 15;

  function load() {
    setLoading(true);
    let url = `/api/admin/employees?page=${page}&limit=${limit}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    if (companyFilter) url += `&company=${companyFilter}`;
    if (statusFilter) url += `&status=${statusFilter}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { employees:[], total:0 })
      .then(d => { setEmployees(d.employees || []); setTotal(d.total || 0); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  React.useEffect(() => { load(); }, [page, search, companyFilter, statusFilter]);

  function exportCSV() {
    /* Exportar lo visible (con filtros) sin paginacion */
    let url = `/api/admin/employees?page=1&limit=9999`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    if (companyFilter) url += `&company=${companyFilter}`;
    if (statusFilter) url += `&status=${statusFilter}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { employees:[] })
      .then(d => {
        const rows = d.employees || [];
        if (rows.length === 0) return;
        const headers = ['Codigo','Nombre','Area','Rol','EPS','Tipo sangre','Email','Telefono','Estado','Empresas permitidas'];
        const csvRows = [headers.join(',')];
        rows.forEach(e => {
          csvRows.push([
            e.code || '',
            `"${(e.full_name || '').replace(/"/g, '""')}"`,
            `"${(e.area || '').replace(/"/g, '""')}"`,
            e.role || 'user',
            `"${(e.eps || '').replace(/"/g, '""')}"`,
            e.blood_type || '',
            e.email_corporate || '',
            e.phone || '',
            e.is_active ? 'Activo' : 'Inactivo',
            Array.isArray(e.allowed_companies) ? e.allowed_companies.map(p => ({1:'Polyec',3:'Polinter',4:'Lacoplast'}[p] || p)).join('; ') : 'Solo su empresa',
          ].join(','));
        });
        const blob = new Blob(['﻿' + csvRows.join('\n')], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `empleados_${new Date().toISOString().slice(0,10)}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
      });
  }

  function handleSave(formData) {
    setSaving(true);
    setFormErr(null);
    const isEdit = modal && modal !== 'create' && modal.id;
    const url  = isEdit ? `/api/admin/employees/${modal.id}` : '/api/admin/employees';
    const method = isEdit ? 'PATCH' : 'POST';

    window.apiFetch(url, { method, body: JSON.stringify(formData) })
      .then(async r => {
        const d = await r.json();
        if (!r.ok) throw new Error(d.error || 'Error al guardar.');
        setModal(null);
        load();
      })
      .catch(err => setFormErr(err.message))
      .finally(() => setSaving(false));
  }

  function toggleActive(emp) {
    window.apiFetch(`/api/admin/employees/${emp.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ is_active: !emp.is_active }),
    }).then(() => load());
  }

  const totalPages = Math.ceil(total / limit);

  return (
    <>
      {/* Header */}
      <div className="flex items-center justify-between mb-5">
        <div>
          <div className="text-[15px] font-semibold text-midnight-900">Empleados</div>
          <div className="text-[12px] text-slate-500 mt-0.5">{total} registros</div>
        </div>
        <div className="flex items-center gap-2">
          <div className="relative">
            <I.search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"/>
            <input placeholder="Buscar por codigo o nombre..." value={search}
              onChange={e => { setSearch(e.target.value); setPage(1); }}
              className="h-9 w-52 rounded-lg bg-paper ring-1 ring-line pl-9 pr-3 text-[12.5px] placeholder:text-slate-400 focus:outline-none focus:ring-midnight-300"/>
          </div>
          <select value={companyFilter} onChange={e => { setCompanyFilter(e.target.value); setPage(1); }}
            className="h-9 rounded-lg bg-paper ring-1 ring-line px-3 text-[12.5px] text-slate-700 focus:outline-none focus:ring-midnight-300">
            <option value="">Todas empresas</option>
            <option value="1">Polyec</option>
            <option value="3">Polinter</option>
            <option value="4">Lacoplast</option>
          </select>
          <select value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1); }}
            className="h-9 rounded-lg bg-paper ring-1 ring-line px-3 text-[12.5px] text-slate-700 focus:outline-none focus:ring-midnight-300">
            <option value="">Todos estados</option>
            <option value="active">Activos</option>
            <option value="inactive">Inactivos</option>
          </select>
          <button onClick={exportCSV} className={btnSecondary + ' flex items-center gap-1.5'} title="Exportar a CSV/Excel">
            <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Exportar
          </button>
          <button onClick={() => setModal('create')} className={btnPrimary + ' flex items-center gap-1.5'}>
            <I.plus className="h-3.5 w-3.5"/> Nuevo
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
        <table className="w-full text-left">
          <thead>
            <tr className="text-[11px] uppercase tracking-wider text-slate-500 bg-paper/50">
              <th className="font-medium px-5 py-3">Empleado</th>
              <th className="font-medium px-3 py-3">Codigo</th>
              <th className="font-medium px-3 py-3">Area</th>
              <th className="font-medium px-3 py-3">Rol sistema</th>
              <th className="font-medium px-3 py-3">Estado</th>
              <th className="font-medium px-3 py-3 w-24">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading && <tr><td colSpan={6} className="px-5 py-8 text-center text-[13px] text-slate-400">Cargando...</td></tr>}
            {!loading && employees.length === 0 && <tr><td colSpan={6} className="px-5 py-8 text-center text-[13px] text-slate-400">Sin empleados</td></tr>}
            {!loading && employees.map((emp, i) => {
              const ini = emp.full_name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
              return (
                <tr key={emp.id} className={`text-[12.5px] ${i !== employees.length-1 ? 'border-b border-line' : ''} hover:bg-paper/50 transition`}>
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <div className="h-8 w-8 rounded-full bg-midnight-50 text-midnight-700 grid place-items-center text-[11px] font-semibold">{ini}</div>
                      <div>
                        <div className="text-midnight-900 font-medium">{emp.full_name}</div>
                        {emp.email_corporate && <div className="text-slate-400 text-[11px]">{emp.email_corporate}</div>}
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3 tnum text-midnight-800 font-medium">{emp.code}</td>
                  <td className="px-3 py-3 text-slate-600">{emp.area || '-'}</td>
                  <td className="px-3 py-3">
                    {emp.role === 'admin'
                      ? <Badge tone="midnight">admin</Badge>
                      : <span className="text-slate-500">user</span>
                    }
                  </td>
                  <td className="px-3 py-3">
                    <StatusPill status={emp.is_active ? 'Activo' : 'Inactivo'} tone={emp.is_active ? 'mint' : 'slate'}/>
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-1">
                      <button onClick={() => setModal(emp)} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700" title="Editar">
                        <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
                      </button>
                      <button onClick={() => toggleActive(emp)}
                        className={`h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center ${emp.is_active ? 'text-slate-400 hover:text-rose-600' : 'text-slate-400 hover:text-mint-600'}`}
                        title={emp.is_active ? 'Desactivar' : 'Activar'}>
                        {emp.is_active
                          ? <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
                          : <I.check className="h-3.5 w-3.5"/>
                        }
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {totalPages > 1 && (
          <div className="px-5 py-3 border-t border-line flex items-center justify-between text-[12px] text-slate-500">
            <div>Pagina {page} de {totalPages}</div>
            <div className="flex items-center gap-1">
              <button disabled={page<=1} onClick={() => setPage(p => p-1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevL className="h-3.5 w-3.5"/></button>
              <span className="h-7 px-2 grid place-items-center rounded-md bg-midnight-900 text-white text-[11.5px] tnum">{page}</span>
              <button disabled={page>=totalPages} onClick={() => setPage(p => p+1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevR className="h-3.5 w-3.5"/></button>
            </div>
          </div>
        )}
      </div>

      {/* Modal crear/editar */}
      {modal && <EmployeeFormModal item={modal === 'create' ? null : modal} onClose={() => { setModal(null); setFormErr(null); }} onSave={handleSave} saving={saving} error={formErr}/>}
    </>
  );
}

function EmployeeFormModal({ item, onClose, onSave, saving, error }) {
  const [code, setCode]       = React.useState(item?.code || '');
  const [fullName, setName]   = React.useState(item?.full_name || '');
  const [area, setArea]       = React.useState(item?.area || '');
  const [role, setRole]       = React.useState(item?.role || 'user');
  const [eps, setEps]         = React.useState(item?.eps || '');
  const [blood, setBlood]     = React.useState(item?.blood_type || '');
  const [email, setEmail]     = React.useState(item?.email_corporate || '');
  const [phone, setPhone]     = React.useState(item?.phone || '');
  const [companies, setCompanies] = React.useState(
    Array.isArray(item?.allowed_companies) && item.allowed_companies.length > 0
      ? item.allowed_companies
      : []
  );

  function toggleCompany(prefix) {
    setCompanies(prev => prev.includes(prefix) ? prev.filter(p => p !== prefix) : [...prev, prefix]);
  }

  function submit() {
    const data = { full_name: fullName, area, role, eps, blood_type: blood, email_corporate: email || '', phone };
    if (!item) data.code = code;
    if (companies.length > 0) data.allowed_companies = companies;
    else data.allowed_companies = null;
    onSave(data);
  }

  return (
    <AdminModal title={item ? 'Editar empleado' : 'Nuevo empleado'} onClose={onClose}>
      {!item && (
        <Field label="Codigo de empleado" hint="Formato: 1-XXXX, 3-XXXX o 4-XXXX">
          <input value={code} onChange={e => setCode(e.target.value)} className={inputCls} placeholder="3-4148"/>
        </Field>
      )}
      <Field label="Nombre completo">
        <input value={fullName} onChange={e => setName(e.target.value)} className={inputCls} placeholder="Valentina Aguirre"/>
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Area">
          <input value={area} onChange={e => setArea(e.target.value)} className={inputCls} placeholder="Tecnologia"/>
        </Field>
        <Field label="Rol del sistema">
          <select value={role} onChange={e => setRole(e.target.value)} className={selectCls}>
            <option value="user">user</option>
            <option value="admin">admin</option>
          </select>
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="EPS">
          <input value={eps} onChange={e => setEps(e.target.value)} className={inputCls} placeholder="Compensar"/>
        </Field>
        <Field label="Tipo de sangre">
          <input value={blood} onChange={e => setBlood(e.target.value)} className={inputCls} placeholder="O+"/>
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Correo corporativo">
          <input value={email} onChange={e => setEmail(e.target.value)} className={inputCls} placeholder="nombre@empresa.com" type="email"/>
        </Field>
        <Field label="Telefono">
          <input value={phone} onChange={e => setPhone(e.target.value)} className={inputCls} placeholder="+502 5555-1234"/>
        </Field>
      </div>
      <Field label="Empresas permitidas" hint="Si no selecciona ninguna, solo ve horarios de su empresa (prefijo del codigo)">
        <div className="flex items-center gap-2 mt-1">
          {COMPANY_OPTIONS.map(co => {
            const sel = companies.includes(co.prefix);
            return (
              <button key={co.prefix} type="button" onClick={() => toggleCompany(co.prefix)}
                className={`h-8 px-3 rounded-lg text-[12.5px] font-medium ring-1 transition
                  ${sel ? 'bg-midnight-900 text-white ring-midnight-900' : 'bg-white text-slate-500 ring-slate-200 hover:ring-slate-300'}`}>
                {co.label}
              </button>
            );
          })}
          {companies.length === 0 && <span className="text-[11px] text-slate-400 ml-1">Solo su empresa</span>}
        </div>
      </Field>
      {error && (
        <div className="flex items-start gap-2 bg-rose-50 ring-1 ring-rose-200 text-rose-700 text-[12.5px] px-4 py-3 rounded-xl">
          <svg className="h-4 w-4 shrink-0 mt-0.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
          <span>{error}</span>
        </div>
      )}
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={onClose} className={btnSecondary}>Cancelar</button>
        <button onClick={submit} disabled={saving || !fullName.trim()} className={btnPrimary}>
          {saving ? 'Guardando...' : item ? 'Guardar cambios' : 'Crear empleado'}
        </button>
      </div>
    </AdminModal>
  );
}

/* ═══════════════════════════════════════════════════
   Panel: Profesionales
   ═══════════════════════════════════════════════════ */
function ProfessionalsPanel() {
  const [professionals, setProfessionals] = React.useState([]);
  const [specialties, setSpecialties]     = React.useState([]);
  const [total, setTotal]                 = React.useState(0);
  const [page, setPage]                   = React.useState(1);
  const [search, setSearch]               = React.useState('');
  const [loading, setLoading]             = React.useState(true);
  const [modal, setModal]                 = React.useState(null);
  const [saving, setSaving]               = React.useState(false);
  const [formErr, setFormErr]             = React.useState(null);
  const [scheduleProf, setScheduleProf]  = React.useState(null); /* prof obj for AvailabilityModal */
  const limit = 15;

  function load() {
    setLoading(true);
    let url = `/api/admin/professionals?page=${page}&limit=${limit}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { professionals:[], total:0 })
      .then(d => { setProfessionals(d.professionals || []); setTotal(d.total || 0); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  React.useEffect(() => { load(); }, [page, search]);

  /* Cargar especialidades para el select del modal */
  React.useEffect(() => {
    window.apiFetch('/api/admin/specialties')
      .then(r => r.ok ? r.json() : { specialties:[] })
      .then(d => setSpecialties(d.specialties || []))
      .catch(() => {});
  }, []);

  function handleSave(formData) {
    setSaving(true);
    setFormErr(null);
    const isEdit = modal && modal !== 'create' && modal.id;
    const url = isEdit ? `/api/admin/professionals/${modal.id}` : '/api/admin/professionals';
    const method = isEdit ? 'PATCH' : 'POST';

    window.apiFetch(url, { method, body: JSON.stringify(formData) })
      .then(async r => {
        const d = await r.json();
        if (!r.ok) throw new Error(d.error || 'Error al guardar.');
        setModal(null);
        load();
      })
      .catch(err => setFormErr(err.message))
      .finally(() => setSaving(false));
  }

  function toggleActive(prof) {
    window.apiFetch(`/api/admin/professionals/${prof.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ is_active: !prof.is_active }),
    }).then(() => load());
  }

  const totalPages = Math.ceil(total / limit);

  return (
    <>
      <div className="flex items-center justify-between mb-5">
        <div>
          <div className="text-[15px] font-semibold text-midnight-900">Profesionales medicos</div>
          <div className="text-[12px] text-slate-500 mt-0.5">{total} registros</div>
        </div>
        <div className="flex items-center gap-2">
          <div className="relative">
            <I.search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"/>
            <input placeholder="Buscar por nombre o correo..." value={search}
              onChange={e => { setSearch(e.target.value); setPage(1); }}
              className="h-9 w-64 rounded-lg bg-paper ring-1 ring-line pl-9 pr-3 text-[12.5px] placeholder:text-slate-400 focus:outline-none focus:ring-midnight-300"/>
          </div>
          <button onClick={() => setModal('create')} className={btnPrimary + ' flex items-center gap-1.5'}>
            <I.plus className="h-3.5 w-3.5"/> Nuevo
          </button>
        </div>
      </div>

      <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
        <table className="w-full text-left">
          <thead>
            <tr className="text-[11px] uppercase tracking-wider text-slate-500 bg-paper/50">
              <th className="font-medium px-5 py-3">Profesional</th>
              <th className="font-medium px-3 py-3">Especialidad</th>
              <th className="font-medium px-3 py-3">Correo calendario</th>
              <th className="font-medium px-3 py-3">Consultorio</th>
              <th className="font-medium px-3 py-3">Estado</th>
              <th className="font-medium px-3 py-3 w-24">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading && <tr><td colSpan={6} className="px-5 py-8 text-center text-[13px] text-slate-400">Cargando...</td></tr>}
            {!loading && professionals.length === 0 && <tr><td colSpan={6} className="px-5 py-8 text-center text-[13px] text-slate-400">Sin profesionales</td></tr>}
            {!loading && professionals.map((prof, i) => {
              const ini = prof.initials || prof.full_name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
              return (
                <tr key={prof.id} className={`text-[12.5px] ${i !== professionals.length-1 ? 'border-b border-line' : ''} hover:bg-paper/50 transition`}>
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <div className="h-8 w-8 rounded-full bg-mint-50 text-mint-700 grid place-items-center text-[11px] font-semibold">{ini}</div>
                      <div>
                        <div className="text-midnight-900 font-medium">{prof.full_name}</div>
                        {prof.sub_specialty && <div className="text-slate-400 text-[11px]">{prof.sub_specialty}</div>}
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3"><Badge tone="midnight">{prof.specialty?.name || '-'}</Badge></td>
                  <td className="px-3 py-3 text-slate-600 text-[11.5px]">{prof.google_calendar_id || '-'}</td>
                  <td className="px-3 py-3 text-slate-600">{prof.room || '-'}</td>
                  <td className="px-3 py-3">
                    <StatusPill status={prof.is_active ? 'Activo' : 'Inactivo'} tone={prof.is_active ? 'mint' : 'slate'}/>
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-1">
                      <button onClick={() => setModal(prof)} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700" title="Editar">
                        <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
                      </button>
                      <button onClick={() => setScheduleProf(prof)} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-mint-700" title="Horario">
                        <I.clock className="h-3.5 w-3.5"/>
                      </button>
                      <button onClick={() => toggleActive(prof)}
                        className={`h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center ${prof.is_active ? 'text-slate-400 hover:text-rose-600' : 'text-slate-400 hover:text-mint-600'}`}
                        title={prof.is_active ? 'Desactivar' : 'Activar'}>
                        {prof.is_active
                          ? <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
                          : <I.check className="h-3.5 w-3.5"/>
                        }
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {totalPages > 1 && (
          <div className="px-5 py-3 border-t border-line flex items-center justify-between text-[12px] text-slate-500">
            <div>Pagina {page} de {totalPages}</div>
            <div className="flex items-center gap-1">
              <button disabled={page<=1} onClick={() => setPage(p => p-1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevL className="h-3.5 w-3.5"/></button>
              <span className="h-7 px-2 grid place-items-center rounded-md bg-midnight-900 text-white text-[11.5px] tnum">{page}</span>
              <button disabled={page>=totalPages} onClick={() => setPage(p => p+1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevR className="h-3.5 w-3.5"/></button>
            </div>
          </div>
        )}
      </div>

      {modal && <ProfessionalFormModal item={modal === 'create' ? null : modal} specialties={specialties} onClose={() => { setModal(null); setFormErr(null); }} onSave={handleSave} saving={saving} error={formErr}/>}
      {scheduleProf && <AvailabilityModal prof={scheduleProf} onClose={() => setScheduleProf(null)}/>}
    </>
  );
}

function ProfessionalFormModal({ item, specialties, onClose, onSave, saving, error }) {
  const [fullName, setName]       = React.useState(item?.full_name || '');
  const [specId, setSpecId]       = React.useState(item?.specialty?.id || item?.specialty_id || '');
  const [calId, setCalId]         = React.useState(item?.google_calendar_id || '');
  const [subSpec, setSubSpec]     = React.useState(item?.sub_specialty || '');
  const [years, setYears]         = React.useState(item?.experience_years ?? '');
  const [room, setRoom]           = React.useState(item?.room || '');
  const [modes, setModes]         = React.useState(item?.modes || ['presencial']);
  const [newPin, setNewPin]       = React.useState('');
  const [pinMsg, setPinMsg]       = React.useState('');
  const [pinSaving, setPinSaving] = React.useState(false);

  function toggleMode(m) {
    setModes(prev => prev.includes(m) ? prev.filter(x => x !== m) : [...prev, m]);
  }

  function submit() {
    const data = {
      full_name: fullName,
      specialty_id: specId,
      google_calendar_id: calId,
      sub_specialty: subSpec,
      room,
      modes,
    };
    if (years !== '') data.experience_years = Number(years);
    onSave(data);
  }

  return (
    <AdminModal title={item ? 'Editar profesional' : 'Nuevo profesional'} onClose={onClose}>
      <Field label="Nombre completo">
        <input value={fullName} onChange={e => setName(e.target.value)} className={inputCls} placeholder="Dra. Helena Restrepo"/>
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Especialidad">
          <select value={specId} onChange={e => setSpecId(e.target.value)} className={selectCls}>
            <option value="">Seleccionar...</option>
            {specialties.filter(s => s.is_active).map(s => (
              <option key={s.id} value={s.id}>{s.name}</option>
            ))}
          </select>
        </Field>
        <Field label="Subespecialidad">
          <input value={subSpec} onChange={e => setSubSpec(e.target.value)} className={inputCls} placeholder="Ej: Cardiologia pediatrica"/>
        </Field>
      </div>
      <Field label="Correo Google Calendar" hint="Este correo se usa para login del profesional y sincronizacion de agenda.">
        <input value={calId} onChange={e => setCalId(e.target.value)} className={inputCls} placeholder="helena.restrepo@polytec.com.gt" type="email"/>
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Consultorio">
          <input value={room} onChange={e => setRoom(e.target.value)} className={inputCls} placeholder="Consultorio 2, Piso 4"/>
        </Field>
        <Field label="Anos de experiencia">
          <input value={years} onChange={e => setYears(e.target.value)} className={inputCls} placeholder="10" type="number" min="0"/>
        </Field>
      </div>
      <Field label="Modalidades">
        <div className="flex gap-3 mt-1">
          {['presencial','telemedicina'].map(m => (
            <label key={m} className="flex items-center gap-2 cursor-pointer select-none">
              <button type="button" onClick={() => toggleMode(m)}
                className={`h-4 w-4 rounded-[5px] grid place-items-center ring-1 transition
                  ${modes.includes(m) ? 'bg-midnight-900 ring-midnight-900' : 'bg-white ring-slate-300'}`}>
                {modes.includes(m) && <I.check className="h-3 w-3 text-mint-300"/>}
              </button>
              <span className="text-[12.5px] text-midnight-800 capitalize">{m}</span>
            </label>
          ))}
        </div>
      </Field>
      {/* PIN de acceso (solo en edicion) */}
      {item && (
        <Field label="PIN de acceso" hint="4 a 6 digitos numericos. Requerido para login del profesional.">
          <div className="flex gap-2">
            <input value={newPin}
              onChange={e => { setNewPin(e.target.value.replace(/\D/g,'').slice(0,6)); setPinMsg(''); }}
              className={inputCls + ' flex-1'} placeholder="Nuevo PIN" type="password" inputMode="numeric" maxLength={6}/>
            <button type="button" disabled={pinSaving || newPin.length < 4}
              onClick={() => {
                setPinSaving(true); setPinMsg('');
                window.apiFetch(`/api/admin/professionals/${item.id}/pin`, {
                  method: 'PATCH', body: JSON.stringify({ pin: newPin }),
                }).then(async r => {
                  const d = await r.json();
                  if (r.ok) { setPinMsg('PIN asignado'); setNewPin(''); }
                  else setPinMsg(d.error || 'Error');
                }).catch(() => setPinMsg('Error de conexion'))
                .finally(() => setPinSaving(false));
              }}
              className="h-10 px-4 rounded-xl bg-midnight-50 text-midnight-700 text-[12px] font-medium hover:bg-midnight-100 disabled:opacity-40 whitespace-nowrap">
              {pinSaving ? 'Guardando...' : 'Asignar PIN'}
            </button>
          </div>
          {pinMsg && <div className={`text-[11px] mt-1 ${pinMsg.includes('asignado') ? 'text-mint-600' : 'text-rose-500'}`}>{pinMsg}</div>}
        </Field>
      )}
      {error && (
        <div className="flex items-start gap-2 bg-rose-50 ring-1 ring-rose-200 text-rose-700 text-[12.5px] px-4 py-3 rounded-xl">
          <svg className="h-4 w-4 shrink-0 mt-0.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
          <span>{error}</span>
        </div>
      )}
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={onClose} className={btnSecondary}>Cancelar</button>
        <button onClick={submit} disabled={saving || !fullName.trim() || !specId || !calId.trim()} className={btnPrimary}>
          {saving ? 'Guardando...' : item ? 'Guardar cambios' : 'Crear profesional'}
        </button>
      </div>
    </AdminModal>
  );
}

/* ═══════════════════════════════════════════════════
   Panel: Especialidades
   ═══════════════════════════════════════════════════ */
function SpecialtiesPanel() {
  const [specialties, setSpecialties] = React.useState([]);
  const [loading, setLoading]         = React.useState(true);
  const [modal, setModal]             = React.useState(null);
  const [saving, setSaving]           = React.useState(false);
  const [formErr, setFormErr]         = React.useState(null);

  function load() {
    setLoading(true);
    window.apiFetch('/api/admin/specialties')
      .then(r => r.ok ? r.json() : { specialties:[] })
      .then(d => setSpecialties(d.specialties || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  React.useEffect(() => { load(); }, []);

  function handleSave(formData) {
    setSaving(true);
    setFormErr(null);
    const isEdit = modal && modal !== 'create' && modal.id;
    const url = isEdit ? `/api/admin/specialties/${modal.id}` : '/api/admin/specialties';
    const method = isEdit ? 'PATCH' : 'POST';

    window.apiFetch(url, { method, body: JSON.stringify(formData) })
      .then(async r => {
        const d = await r.json();
        if (!r.ok) throw new Error(d.error || 'Error al guardar.');
        setModal(null);
        load();
      })
      .catch(err => setFormErr(err.message))
      .finally(() => setSaving(false));
  }

  function toggleActive(spec) {
    window.apiFetch(`/api/admin/specialties/${spec.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ is_active: !spec.is_active }),
    }).then(() => load());
  }

  return (
    <>
      <div className="flex items-center justify-between mb-5">
        <div>
          <div className="text-[15px] font-semibold text-midnight-900">Especialidades</div>
          <div className="text-[12px] text-slate-500 mt-0.5">{specialties.length} registradas</div>
        </div>
        <button onClick={() => setModal('create')} className={btnPrimary + ' flex items-center gap-1.5'}>
          <I.plus className="h-3.5 w-3.5"/> Nueva
        </button>
      </div>

      <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
        <table className="w-full text-left">
          <thead>
            <tr className="text-[11px] uppercase tracking-wider text-slate-500 bg-paper/50">
              <th className="font-medium px-5 py-3">Simbolo</th>
              <th className="font-medium px-3 py-3">Nombre</th>
              <th className="font-medium px-3 py-3">Estado</th>
              <th className="font-medium px-3 py-3">Creada</th>
              <th className="font-medium px-3 py-3 w-24">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading && <tr><td colSpan={5} className="px-5 py-8 text-center text-[13px] text-slate-400">Cargando...</td></tr>}
            {!loading && specialties.length === 0 && <tr><td colSpan={5} className="px-5 py-8 text-center text-[13px] text-slate-400">Sin especialidades</td></tr>}
            {!loading && specialties.map((spec, i) => (
              <tr key={spec.id} className={`text-[12.5px] ${i !== specialties.length-1 ? 'border-b border-line' : ''} hover:bg-paper/50 transition`}>
                <td className="px-5 py-3">
                  <span className="h-8 w-8 rounded-lg bg-midnight-50 grid place-items-center text-[16px]">{spec.glyph || '-'}</span>
                </td>
                <td className="px-3 py-3 text-midnight-900 font-medium">{spec.name}</td>
                <td className="px-3 py-3">
                  <StatusPill status={spec.is_active ? 'Activa' : 'Inactiva'} tone={spec.is_active ? 'mint' : 'slate'}/>
                </td>
                <td className="px-3 py-3 text-slate-500 tnum text-[11.5px]">
                  {new Date(spec.created_at).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' })}
                </td>
                <td className="px-3 py-3">
                  <div className="flex items-center gap-1">
                    <button onClick={() => setModal(spec)} className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700" title="Editar">
                      <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
                    </button>
                    <button onClick={() => toggleActive(spec)}
                      className={`h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center ${spec.is_active ? 'text-slate-400 hover:text-rose-600' : 'text-slate-400 hover:text-mint-600'}`}
                      title={spec.is_active ? 'Desactivar' : 'Activar'}>
                      {spec.is_active
                        ? <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
                        : <I.check className="h-3.5 w-3.5"/>
                      }
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal && <SpecialtyFormModal item={modal === 'create' ? null : modal} onClose={() => { setModal(null); setFormErr(null); }} onSave={handleSave} saving={saving} error={formErr}/>}
    </>
  );
}

function SpecialtyFormModal({ item, onClose, onSave, saving, error }) {
  const [name, setName]   = React.useState(item?.name || '');
  const [glyph, setGlyph] = React.useState(item?.glyph || '');

  function submit() {
    const data = { name };
    if (glyph) data.glyph = glyph;
    onSave(data);
  }

  return (
    <AdminModal title={item ? 'Editar especialidad' : 'Nueva especialidad'} onClose={onClose}>
      <Field label="Nombre de la especialidad">
        <input value={name} onChange={e => setName(e.target.value)} className={inputCls} placeholder="Ej: Odontologia"/>
      </Field>
      <Field label="Simbolo (glyph)" hint="Un caracter o simbolo para la UI.">
        <input value={glyph} onChange={e => setGlyph(e.target.value)} className={inputCls + ' w-24'} placeholder="+" maxLength={4}/>
      </Field>
      {error && (
        <div className="flex items-start gap-2 bg-rose-50 ring-1 ring-rose-200 text-rose-700 text-[12.5px] px-4 py-3 rounded-xl">
          <svg className="h-4 w-4 shrink-0 mt-0.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
          <span>{error}</span>
        </div>
      )}
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={onClose} className={btnSecondary}>Cancelar</button>
        <button onClick={submit} disabled={saving || !name.trim()} className={btnPrimary}>
          {saving ? 'Guardando...' : item ? 'Guardar cambios' : 'Crear especialidad'}
        </button>
      </div>
    </AdminModal>
  );
}

/* ═══════════════════════════════════════════════════
   ADMIN VIEW PRINCIPAL
   ═══════════════════════════════════════════════════ */
function AdminView({ user, onNavigate, onLogout }) {
  const u = user || { full_name:'Diego Marin', role:'admin', code:'1-0000' };
  const initials = u.full_name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
  const firstName = u.full_name.split(' ')[0];

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

  const [kpis, setKpis]               = React.useState(null);
  const [bySpec, setBySpec]            = React.useState({});
  const [appointments, setAppointments] = React.useState([]);
  const [totalAppts, setTotalAppts]     = React.useState(0);
  const [loading, setLoading]           = React.useState(true);
  const [page, setPage]                 = React.useState(1);
  const [dateFrom, setDateFrom]         = React.useState('');
  const [dateTo, setDateTo]             = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('');
  const [search, setSearch]             = React.useState('');

  /* Cargar KPIs */
  React.useEffect(() => {
    if (tab !== 'dashboard') return;
    window.apiFetch('/api/admin/kpis')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data) { setKpis(data.kpis); setBySpec(data.by_specialty || {}); }
      })
      .catch(() => {});
  }, [tab]);

  /* Cargar tabla de citas */
  React.useEffect(() => {
    if (tab !== 'dashboard') return;
    setLoading(true);
    let url = `/api/admin/appointments?page=${page}&limit=10`;
    if (dateFrom) url += `&dateFrom=${dateFrom}`;
    if (dateTo) url += `&dateTo=${dateTo}`;
    if (statusFilter) url += `&status=${statusFilter}`;

    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { appointments:[], total:0 })
      .then(data => { setAppointments(data.appointments || []); setTotalAppts(data.total || 0); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page, dateFrom, dateTo, statusFilter, tab]);

  function exportAppointmentsCSV() {
    let url = `/api/admin/appointments?page=1&limit=9999`;
    if (dateFrom) url += `&dateFrom=${dateFrom}`;
    if (dateTo) url += `&dateTo=${dateTo}`;
    if (statusFilter) url += `&status=${statusFilter}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    window.apiFetch(url)
      .then(r => r.ok ? r.json() : { appointments:[] })
      .then(data => {
        const rows = data.appointments || [];
        if (rows.length === 0) return;
        const headers = ['Fecha','Hora','Paciente','Codigo','Area','Profesional','Especialidad','Modalidad','Estado'];
        const csvRows = [headers.join(',')];
        rows.forEach(a => {
          const d = new Date(a.start_at);
          const pName = a.employee?.full_name || a.beneficiary?.name || 'Paciente';
          csvRows.push([
            d.toLocaleDateString('es-CO', { day:'2-digit', month:'2-digit', year:'numeric' }),
            d.toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false }),
            `"${pName.replace(/"/g, '""')}"`,
            a.employee?.code || '',
            `"${(a.employee?.area || '').replace(/"/g, '""')}"`,
            `"${(a.professional?.full_name || '').replace(/"/g, '""')}"`,
            a.specialty?.name || '',
            a.mode === 'telemedicina' ? 'Telemedicina' : 'Presencial',
            statusMap[a.status] || a.status,
          ].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 rangeLabel = dateFrom && dateTo ? `${dateFrom}_a_${dateTo}` : dateFrom || dateTo || 'todo';
        link.download = `trazabilidad_citas_${rangeLabel}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
      });
  }

  const statusMap  = { confirmed:'Confirmada', completed:'Atendida', cancelled:'Cancelada', in_progress:'En consulta', no_show:'No asistio' };
  const toneMap    = { confirmed:'mint', completed:'slate', cancelled:'rose', in_progress:'midnight', no_show:'rose' };

  const filtered = search
    ? appointments.filter(a => {
        const q = search.toLowerCase();
        return (a.employee?.full_name||'').toLowerCase().includes(q) ||
               (a.professional?.full_name||'').toLowerCase().includes(q) ||
               (a.employee?.code||'').toLowerCase().includes(q);
      })
    : appointments;

  const totalPages = Math.ceil(totalAppts / 10);

  const TABS = [
    { key: 'dashboard',      label: 'Dashboard',       icon: <I.grid/> },
    { key: 'employees',      label: 'Empleados',       icon: <I.users/> },
    { key: 'professionals',  label: 'Profesionales',   icon: <I.user/> },
    { key: 'specialties',    label: 'Especialidades',  icon: <I.chart/> },
    { key: 'promotions',     label: 'Promociones',     icon: <I.bell/> },
  ];

  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">
        <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">Administracion</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('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>
          <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.user/></span><span className="flex-1">Mis citas</span>
          </a>
        </nav>

        <div className="mt-auto pt-4 border-t border-white/10">
          <button onClick={onLogout} className="w-full h-9 rounded-lg text-white/60 text-[12.5px] hover:bg-white/5 hover:text-white/80">
            Cerrar sesion
          </button>
        </div>
      </aside>

      {/* MAIN */}
      <main className="flex-1 min-w-0">
        {/* TOPBAR */}
        <div className="h-16 border-b border-line bg-white/70 backdrop-blur px-8 flex items-center gap-4">
          <div>
            <div className="text-[11px] text-slate-500">Servicio medico interno</div>
            <div className="text-[14px] font-semibold text-midnight-900 leading-tight">Panel administrativo</div>
          </div>
          <div className="ml-auto flex items-center gap-2.5 pl-3 border-l border-line">
            <div className="h-8 w-8 rounded-full bg-gradient-to-br from-midnight-700 to-midnight-900 text-white grid place-items-center text-[11px] font-semibold">{initials}</div>
            <div className="leading-tight">
              <div className="text-[12.5px] font-medium text-midnight-900">{firstName}</div>
              <div className="text-[11px] text-slate-500">Administrador</div>
            </div>
          </div>
        </div>

        {/* CONTENT */}
        <div className="p-8 space-y-6">

          {/* ── DASHBOARD ── */}
          {tab === 'dashboard' && (
            <>
              <div className="flex items-end justify-between">
                <div>
                  <h1 className="text-[26px] font-semibold tracking-tight text-midnight-900 leading-tight">Buenos dias, {firstName}.</h1>
                  <p className="text-[13.5px] text-slate-500 mt-1">Clinica interna corporativa, resumen del mes en curso.</p>
                </div>
                <div className="flex items-center gap-2 text-[11.5px] text-slate-500">
                  <span className="inline-flex items-center gap-1.5"><span className="h-1.5 w-1.5 rounded-full bg-mint-500"/>Sistema operativo</span>
                </div>
              </div>

              <div className="grid grid-cols-5 gap-4">
                <KPICard label="Citas del mes" value={kpis ? String(kpis.total_month) : '...'} hint="total agendadas"/>
                <KPICard label="Tasa de asistencia" value={kpis ? `${kpis.attend_rate}%` : '...'} hint="meta interna 90%"/>
                <KPICard label="Empleados atendidos" value={kpis ? String(kpis.unique_employees) : '...'} hint="unicos este mes"/>
                <KPICard label="Canceladas" value={kpis ? String(kpis.cancelled) : '...'} hint="este mes"/>
                <KPICard label="No-show" value={kpis ? `${kpis.no_show_rate}%` : '...'} hint="objetivo <5%"/>
              </div>

              <div className="grid grid-cols-12 gap-4">
                <div className="col-span-4"><SpecMix data={bySpec}/></div>
                <div className="col-span-8">
                  <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
                    <div className="flex items-center justify-between px-6 py-5 border-b border-line">
                      <div>
                        <div className="text-[15px] font-semibold text-midnight-900">Trazabilidad de citas</div>
                        <div className="text-[12px] text-slate-500 mt-0.5">{totalAppts} registros</div>
                      </div>
                      <div className="flex items-center gap-2 flex-wrap">
                        <div className="relative">
                          <I.search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"/>
                          <input placeholder="Buscar paciente, doctor..." value={search} onChange={e => setSearch(e.target.value)}
                            className="h-9 w-48 rounded-lg bg-paper ring-1 ring-line pl-9 pr-3 text-[12.5px] placeholder:text-slate-400 focus:outline-none focus:ring-midnight-300"/>
                        </div>
                        <div className="flex items-center gap-1">
                          <input type="date" value={dateFrom} onChange={e => { setDateFrom(e.target.value); setPage(1); }}
                            className="h-9 rounded-lg bg-paper ring-1 ring-line px-2 text-[11.5px] text-slate-700 focus:outline-none focus:ring-midnight-300" title="Desde"/>
                          <span className="text-[11px] text-slate-400">a</span>
                          <input type="date" value={dateTo} onChange={e => { setDateTo(e.target.value); setPage(1); }}
                            className="h-9 rounded-lg bg-paper ring-1 ring-line px-2 text-[11.5px] text-slate-700 focus:outline-none focus:ring-midnight-300" title="Hasta"/>
                        </div>
                        <select value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1); }}
                          className="h-9 rounded-lg bg-paper ring-1 ring-line px-3 text-[12.5px] text-slate-700 focus:outline-none focus:ring-midnight-300">
                          <option value="">Todos</option>
                          <option value="confirmed">Confirmada</option>
                          <option value="completed">Atendida</option>
                          <option value="cancelled">Cancelada</option>
                          <option value="no_show">No-show</option>
                        </select>
                        <button onClick={exportAppointmentsCSV}
                          className="h-9 px-3 rounded-lg bg-white ring-1 ring-line text-[12px] text-midnight-800 font-medium hover:bg-slate-50 flex items-center gap-1.5 transition" title="Exportar a CSV/Excel">
                          <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                          Exportar
                        </button>
                        {(dateFrom || dateTo || statusFilter) && (
                          <button onClick={() => { setDateFrom(''); setDateTo(''); setStatusFilter(''); setPage(1); }}
                            className="h-9 px-2 text-[11px] text-slate-400 hover:text-slate-600">Limpiar filtros</button>
                        )}
                      </div>
                    </div>

                    <table className="w-full text-left">
                      <thead>
                        <tr className="text-[11px] uppercase tracking-wider text-slate-500 bg-paper/50">
                          <th className="font-medium px-6 py-3">Paciente</th>
                          <th className="font-medium px-3 py-3">Profesional</th>
                          <th className="font-medium px-3 py-3">Especialidad</th>
                          <th className="font-medium px-3 py-3">Fecha</th>
                          <th className="font-medium px-3 py-3">Modalidad</th>
                          <th className="font-medium px-3 py-3">Estado</th>
                        </tr>
                      </thead>
                      <tbody>
                        {loading && (
                          <tr><td colSpan={6} className="px-6 py-8 text-center text-[13px] text-slate-400">Cargando...</td></tr>
                        )}
                        {!loading && filtered.length === 0 && (
                          <tr><td colSpan={6} className="px-6 py-8 text-center text-[13px] text-slate-400">Sin citas encontradas</td></tr>
                        )}
                        {!loading && filtered.map((a, i) => {
                          const patientName = a.employee?.full_name || a.beneficiary?.name || 'Paciente';
                          const patientCode = a.employee?.code || (a.beneficiary ? `Benef: ${a.beneficiary.relation}` : '');
                          const patientInitials = patientName.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
                          const startDate = new Date(a.start_at);
                          return (
                            <tr key={a.id} className={`text-[12.5px] ${i!==filtered.length-1 ? 'border-b border-line' : ''} hover:bg-paper/50 transition`}>
                              <td className="px-6 py-3.5">
                                <div className="flex items-center gap-3">
                                  <div className="h-8 w-8 rounded-full bg-midnight-50 text-midnight-700 grid place-items-center text-[11px] font-semibold">{patientInitials}</div>
                                  <div>
                                    <div className="text-midnight-900 font-medium">{patientName}</div>
                                    <div className="text-slate-400 text-[11px] tnum">{patientCode}{a.employee?.area ? ` | ${a.employee.area}` : ''}</div>
                                  </div>
                                </div>
                              </td>
                              <td className="px-3 py-3.5 text-slate-700">{a.professional?.full_name || ''}</td>
                              <td className="px-3 py-3.5"><Badge tone="midnight">{a.specialty?.name || ''}</Badge></td>
                              <td className="px-3 py-3.5 text-midnight-800 tnum">
                                {startDate.toLocaleDateString('es-CO', { day:'2-digit', month:'short' })} {startDate.toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false })}
                              </td>
                              <td className="px-3 py-3.5">
                                <span className="inline-flex items-center gap-1.5 text-slate-700">
                                  {a.mode==='telemedicina' ? <I.video className="h-3.5 w-3.5 text-mint-600"/> : <I.pin className="h-3.5 w-3.5 text-midnight-500"/>}
                                  {a.mode === 'telemedicina' ? 'Telemed' : 'Presencial'}
                                </span>
                              </td>
                              <td className="px-3 py-3.5">
                                <StatusPill status={statusMap[a.status] || a.status} tone={toneMap[a.status] || 'slate'}/>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>

                    {totalPages > 1 && (
                      <div className="px-6 py-4 border-t border-line flex items-center justify-between text-[12px] text-slate-500">
                        <div>Pagina {page} de {totalPages}</div>
                        <div className="flex items-center gap-1">
                          <button disabled={page<=1} onClick={() => setPage(p => p-1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevL className="h-3.5 w-3.5"/></button>
                          <span className="h-7 px-2 grid place-items-center rounded-md bg-midnight-900 text-white text-[11.5px] tnum">{page}</span>
                          <button disabled={page>=totalPages} onClick={() => setPage(p => p+1)} className="h-7 w-7 grid place-items-center rounded-md hover:bg-paper disabled:opacity-30"><I.chevR className="h-3.5 w-3.5"/></button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </>
          )}

          {/* ── EMPLEADOS ── */}
          {tab === 'employees' && <EmployeesPanel />}

          {/* ── PROFESIONALES ── */}
          {tab === 'professionals' && <ProfessionalsPanel />}

          {/* ── ESPECIALIDADES ── */}
          {tab === 'specialties' && <SpecialtiesPanel />}

          {/* ── PROMOCIONES ── */}
          {tab === 'promotions' && <PromotionsPanel />}

        </div>
      </main>
    </div>
  );
}

/* ── Panel de Promociones de Salud ── */
function PromotionsPanel() {
  const [promotions, setPromotions] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showModal, setShowModal] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  function load() {
    setLoading(true);
    window.apiFetch('/api/admin/promotions')
      .then(r => r.ok ? r.json() : { promotions: [] })
      .then(data => setPromotions(data.promotions || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  React.useEffect(() => { load(); }, []);

  async function handleDelete(id) {
    if (!confirm('Eliminar esta promocion?')) return;
    await window.apiFetch(`/api/admin/promotions/${id}`, { method: 'DELETE' });
    load();
  }

  async function handleToggle(promo) {
    await window.apiFetch(`/api/admin/promotions/${promo.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ is_active: !promo.is_active }),
    });
    load();
  }

  const ICON_MAP = { cal: <I.cal/>, shield: <I.shield/>, clock: <I.clock/>, chart: <I.chart/>, bell: <I.bell/>, video: <I.video/>, user: <I.user/>, check: <I.check/> };
  const toneClasses = {
    mint: 'bg-mint-100 text-mint-700',
    amber: 'bg-amber-50 text-amber-700',
    rose: 'bg-rose-50 text-rose-700',
    midnight: 'bg-midnight-50 text-midnight-700',
    slate: 'bg-slate-100 text-slate-600',
  };

  return (
    <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">
        <div>
          <div className="text-[14px] font-semibold text-midnight-900">Promociones de salud</div>
          <div className="text-[12px] text-slate-500 mt-0.5">Se muestran en la seccion "Salud preventiva" de la vista del empleado</div>
        </div>
        <button onClick={() => { setEditing(null); setShowModal(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"/>Nueva promocion
        </button>
      </div>

      {loading ? (
        <div className="p-8 text-center text-[13px] text-slate-400">Cargando...</div>
      ) : promotions.length === 0 ? (
        <div className="p-8 text-center text-[13px] text-slate-400">Sin promociones. Crea la primera.</div>
      ) : (
        <div className="divide-y divide-line">
          {promotions.map(p => (
            <div key={p.id} className="px-5 py-4 flex items-center gap-4 hover:bg-slate-50/50 transition">
              <div className={`h-9 w-9 rounded-lg grid place-items-center shrink-0 ${toneClasses[p.tone] || toneClasses.slate}`}>
                {React.cloneElement(ICON_MAP[p.icon] || ICON_MAP.shield, { className: 'h-4.5 w-4.5' })}
              </div>
              <div className="min-w-0 flex-1">
                <div className="text-[13px] font-medium text-midnight-900">{p.title}</div>
                <div className="text-[12px] text-slate-500">{p.subtitle}</div>
              </div>
              <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-medium ring-1 ring-inset
                ${p.is_active ? 'bg-mint-50 text-mint-700 ring-mint-200' : 'bg-slate-50 text-slate-500 ring-slate-200'}`}>
                <span className={`h-1.5 w-1.5 rounded-full ${p.is_active ? 'bg-mint-500' : 'bg-slate-400'}`}/>
                {p.is_active ? 'Activa' : 'Inactiva'}
              </span>
              <div className="flex items-center gap-1.5">
                <button onClick={() => handleToggle(p)}
                  className="h-7 px-2 rounded-lg text-[11px] text-slate-600 ring-1 ring-line hover:bg-slate-50">
                  {p.is_active ? 'Desactivar' : 'Activar'}
                </button>
                <button onClick={() => { setEditing(p); setShowModal(true); }}
                  className="h-7 px-2 rounded-lg text-[11px] text-midnight-700 ring-1 ring-line hover:bg-slate-50">
                  Editar
                </button>
                <button onClick={() => handleDelete(p.id)}
                  className="h-7 px-2 rounded-lg text-[11px] text-rose-600 ring-1 ring-rose-200 hover:bg-rose-50">
                  Eliminar
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <PromotionModal
          promotion={editing}
          onClose={() => { setShowModal(false); setEditing(null); }}
          onSaved={() => { setShowModal(false); setEditing(null); load(); }}
        />
      )}
    </div>
  );
}

function PromotionModal({ promotion, onClose, onSaved }) {
  const isEdit = !!promotion;
  const [form, setForm] = React.useState({
    title: promotion?.title || '',
    subtitle: promotion?.subtitle || '',
    icon: promotion?.icon || 'shield',
    tone: promotion?.tone || 'mint',
    sort_order: promotion?.sort_order || 0,
    is_active: promotion?.is_active !== false,
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const ICONS = ['shield', 'cal', 'clock', 'chart', 'bell', 'video', 'user', 'check'];
  const TONES = ['mint', 'amber', 'rose', 'midnight', 'slate'];
  const ICON_MAP = { cal: <I.cal/>, shield: <I.shield/>, clock: <I.clock/>, chart: <I.chart/>, bell: <I.bell/>, video: <I.video/>, user: <I.user/>, check: <I.check/> };
  const toneClasses = {
    mint: 'bg-mint-100 text-mint-700 ring-mint-300',
    amber: 'bg-amber-50 text-amber-700 ring-amber-200',
    rose: 'bg-rose-50 text-rose-700 ring-rose-200',
    midnight: 'bg-midnight-50 text-midnight-700 ring-midnight-100',
    slate: 'bg-slate-100 text-slate-600 ring-slate-200',
  };

  async function handleSubmit(e) {
    e.preventDefault();
    if (!form.title) { setError('El titulo es obligatorio.'); return; }
    setSaving(true);
    setError('');
    try {
      const url = isEdit ? `/api/admin/promotions/${promotion.id}` : '/api/admin/promotions';
      const method = isEdit ? 'PATCH' : 'POST';
      const res = await window.apiFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error'); }
      onSaved();
    } catch (err) {
      setError(err.message);
    } finally { setSaving(false); }
  }

  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-[440px]" 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 promocion' : 'Nueva promocion'}</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>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Titulo *</label>
            <input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
              className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"
              placeholder="Examenes preventivos anuales"/>
          </div>
          <div>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Subtitulo</label>
            <input value={form.subtitle} onChange={e => setForm(f => ({ ...f, subtitle: e.target.value }))}
              className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"
              placeholder="Consulta con tu medico"/>
          </div>

          {/* Icono selector */}
          <div>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-2">Icono</label>
            <div className="flex gap-2 flex-wrap">
              {ICONS.map(ic => (
                <button key={ic} type="button" onClick={() => setForm(f => ({ ...f, icon: ic }))}
                  className={`h-9 w-9 rounded-lg grid place-items-center ring-1 ring-inset transition
                    ${form.icon === ic ? 'bg-midnight-100 text-midnight-700 ring-midnight-300' : 'bg-paper text-slate-500 ring-line hover:bg-slate-50'}`}>
                  {React.cloneElement(ICON_MAP[ic], { className: 'h-4 w-4' })}
                </button>
              ))}
            </div>
          </div>

          {/* Tono selector */}
          <div>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-2">Color</label>
            <div className="flex gap-2">
              {TONES.map(t => (
                <button key={t} type="button" onClick={() => setForm(f => ({ ...f, tone: t }))}
                  className={`h-8 px-3 rounded-lg text-[12px] font-medium capitalize ring-1 ring-inset transition
                    ${form.tone === t ? toneClasses[t] : 'bg-paper text-slate-500 ring-line hover:bg-slate-50'}`}>
                  {t}
                </button>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[11.5px] font-medium text-slate-500 mb-1">Orden</label>
              <input type="number" value={form.sort_order} onChange={e => setForm(f => ({ ...f, sort_order: Number(e.target.value) }))}
                className="w-full h-9 px-3 rounded-lg ring-1 ring-line text-[13px] text-midnight-900 bg-paper"/>
            </div>
            <div className="flex items-end">
              <button type="button" onClick={() => setForm(f => ({ ...f, is_active: !f.is_active }))}
                className={`h-9 px-4 rounded-lg text-[12px] font-medium ring-1 ring-inset
                  ${form.is_active ? 'bg-mint-100 text-mint-700 ring-mint-300' : 'bg-slate-100 text-slate-500 ring-slate-200'}`}>
                {form.is_active ? 'Activa' : 'Inactiva'}
              </button>
            </div>
          </div>

          {/* Preview */}
          <div>
            <label className="block text-[11.5px] font-medium text-slate-500 mb-2">Vista previa</label>
            <div className="p-3 rounded-xl bg-paper ring-1 ring-line flex items-start gap-3">
              <div className={`h-8 w-8 rounded-lg grid place-items-center shrink-0 ${
                form.tone === 'amber' ? 'bg-amber-50 text-amber-700' :
                form.tone === 'mint' ? 'bg-mint-100 text-mint-700' :
                form.tone === 'rose' ? 'bg-rose-50 text-rose-700' :
                'bg-slate-100 text-slate-600'}`}>
                {React.cloneElement(ICON_MAP[form.icon] || ICON_MAP.shield, { className: 'h-4 w-4' })}
              </div>
              <div>
                <div className="text-[12.5px] font-medium text-midnight-900">{form.title || 'Titulo'}</div>
                <div className="text-[11.5px] text-slate-500">{form.subtitle || 'Subtitulo'}</div>
              </div>
            </div>
          </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' : 'Crear'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

window.AdminView = AdminView;
