/* ============================================================
   PANEL DE ADMINISTRACIÓN
   Áreas · Sucursales · Invitaciones · Colaboradores · Empresas
   ============================================================ */
const { useState: useSA, useEffect: useEA } = React;
const IHD = window.IH;

/* ── Shared hooks ─────────────────────────────────────────── */
function useList(fetchFn) {
  const [items, setItems] = useSA([]);
  const [busy, setBusy] = useSA(false);
  const reload = () => {
    setBusy(true);
    fetchFn().then(d => { setItems(d); setBusy(false); }).catch(() => setBusy(false));
  };
  useEA(() => { reload(); }, []);
  return { items, setItems, busy, reload };
}

/* ── Shared style constants ───────────────────────────────── */
const inputSt = {
  fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink)',
  background: 'var(--paper)', border: '1px solid var(--hair-2)',
  borderRadius: 7, padding: '9px 12px', outline: 'none', boxSizing: 'border-box',
};
const labelSt = {
  display: 'block', marginBottom: 6, fontSize: 10.5,
  fontFamily: 'var(--mono)', textTransform: 'uppercase',
  letterSpacing: '0.06em', color: 'var(--ink-3)', fontWeight: 500,
};
const btnSm = (variant) => ({
  border: 'none', cursor: 'pointer', borderRadius: 6, padding: '6px 12px',
  fontSize: 12, fontFamily: 'var(--sans)', fontWeight: 500,
  background: variant === 'danger' ? 'oklch(0.56 0.13 28 / 0.10)'
    : variant === 'primary' ? 'var(--ink)' : 'var(--panel)',
  color: variant === 'danger' ? 'var(--risk)' : variant === 'primary' ? '#fff' : 'var(--ink-2)',
  border: '1px solid ' + (variant === 'danger' ? 'oklch(0.56 0.13 28 / 0.25)' : 'var(--hair-2)'),
});

/* ── PageTitle ────────────────────────────────────────────── */
function AdminTitle({ title, sub }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <h2 className="serif" style={{ fontSize: 26, fontWeight: 600, margin: '0 0 4px' }}>{title}</h2>
      {sub && <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{sub}</div>}
    </div>
  );
}
function AdminLoading() {
  return <div className="mono" style={{ fontSize: 13, color: 'var(--ink-3)', padding: '20px 0' }}>Cargando…</div>;
}
function AdminEmpty({ text }) {
  return (
    <div style={{ fontSize: 13, color: 'var(--ink-3)', padding: '28px 0', textAlign: 'center', border: '1px dashed var(--hair)', borderRadius: 8 }}>
      {text}
    </div>
  );
}

/* ── ScreenAdmin — contenedor principal ──────────────────── */
function ScreenAdmin({ adminUser, onBack, onLogout }) {
  const [tab, setTab] = useSA('areas');
  const [viewResult, setViewResult] = useSA(null);
  const [selectedCompanyId, setSelectedCompanyId] = useSA(null);
  const [mgmtCompanyId, setMgmtCompanyId] = useSA('');
  const [allCompanies, setAllCompanies] = useSA([]);
  const isSuperAdmin = adminUser?.role === 'superadmin';

  useEA(() => {
    if (isSuperAdmin) IHA.getCompanies().then(setAllCompanies).catch(() => {});
  }, []);

  const goToColabs = (companyId) => {
    setSelectedCompanyId(companyId);
    setTab('colaboradores');
  };

  if (viewResult) return <ResultModal result={viewResult} onClose={() => setViewResult(null)} />;

  const tabs = [
    { id: 'areas', label: 'Áreas' },
    { id: 'sucursales', label: 'Sucursales' },
    { id: 'invitaciones', label: 'Invitaciones' },
    { id: 'colaboradores', label: 'Colaboradores' },
    ...(isSuperAdmin ? [{ id: 'empresas', label: 'Empresas' }] : []),
  ];

  return (
    <div className="fade-in" style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      <header className="no-print" style={{
        position: 'sticky', top: 0, zIndex: 30, background: 'var(--paper)',
        borderBottom: '1px solid var(--hair)', display: 'flex',
        justifyContent: 'space-between', alignItems: 'center', padding: '14px 32px',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <Brand small />
          <div style={{ width: 1, height: 20, background: 'var(--hair-2)' }} />
          <span className="serif" style={{ fontSize: 17, fontWeight: 600 }}>Administración</span>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" onClick={onBack} style={{ fontSize: 13 }}>← Panel ejecutivo</button>
          <button className="btn btn-ghost" onClick={onLogout} style={{ fontSize: 13, color: 'var(--ink-3)' }}>Cerrar sesión</button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr', minHeight: 'calc(100vh - 57px)' }}>
        <nav style={{ borderRight: '1px solid var(--hair)', padding: '20px 0', background: 'var(--panel-soft)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
              padding: '11px 22px', fontSize: 14, fontFamily: 'var(--sans)',
              fontWeight: tab === t.id ? 600 : 400,
              background: tab === t.id ? 'var(--panel)' : 'transparent',
              color: tab === t.id ? 'var(--ink)' : 'var(--ink-2)',
              borderTop: 'none', borderBottom: 'none', borderRight: 'none',
              borderLeft: tab === t.id ? '3px solid var(--gold)' : '3px solid transparent',
              transition: 'all .12s',
            }}>{t.label}</button>
          ))}
        </nav>

        <main style={{ padding: '32px 40px', overflowY: 'auto' }}>
          {isSuperAdmin && (tab === 'areas' || tab === 'sucursales') && (
            <div style={{ marginBottom: 22, display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 8 }}>
              <span style={labelSt}>Empresa</span>
              <select value={mgmtCompanyId} onChange={e => setMgmtCompanyId(e.target.value)} style={{ ...inputSt, minWidth: 220 }}>
                <option value="">Mi empresa</option>
                {allCompanies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
          )}
          {tab === 'areas' && (
            <TabCrud key={`areas-${mgmtCompanyId}`} title="Áreas" subtitle="Departamentos de la organización"
              noun="área"
              fetchFn={() => IHA.getDepartments(mgmtCompanyId || undefined)}
              createFn={name => IHA.createDepartment(name, mgmtCompanyId || undefined)}
              updateFn={(id, name) => IHA.updateDepartment(id, name)}
              deleteFn={id => IHA.deleteDepartment(id)} />
          )}
          {tab === 'sucursales' && (
            <TabCrud key={`suc-${mgmtCompanyId}`} title="Sucursales" subtitle="Oficinas o ubicaciones de la empresa"
              noun="sucursal"
              fetchFn={() => IHA.getSucursales(mgmtCompanyId || undefined)}
              createFn={name => IHA.createSucursal(name, mgmtCompanyId || undefined)}
              updateFn={(id, name) => IHA.updateSucursal(id, name)}
              deleteFn={id => IHA.deleteSucursal(id)} />
          )}
          {tab === 'invitaciones' && <TabInvitaciones />}
          {tab === 'colaboradores' && <TabColaboradores key={selectedCompanyId || 'all'} onViewResult={setViewResult} adminUser={adminUser} initCompanyId={selectedCompanyId} />}
          {tab === 'empresas' && isSuperAdmin && <TabEmpresas onViewColabs={goToColabs} />}
        </main>
      </div>
    </div>
  );
}

/* ── TabCrud — reutilizable para áreas y sucursales ──────── */
function TabCrud({ title, subtitle, noun, fetchFn, createFn, updateFn, deleteFn }) {
  const { items, setItems, busy } = useList(fetchFn);
  const [newName, setNewName] = useSA('');
  const [editing, setEditing] = useSA(null);
  const [saving, setSaving] = useSA(false);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setSaving(true);
    try {
      const item = await createFn(newName.trim());
      setItems(prev => [...prev, item]);
      setNewName('');
    } finally { setSaving(false); }
  };

  const handleUpdate = async () => {
    if (!editing?.name.trim()) return;
    setSaving(true);
    try {
      await updateFn(editing.id, editing.name.trim());
      setItems(prev => prev.map(i => i.id === editing.id ? { ...i, name: editing.name.trim() } : i));
      setEditing(null);
    } finally { setSaving(false); }
  };

  const handleDelete = async (id) => {
    if (!confirm(`¿Eliminar esta ${noun}?`)) return;
    await deleteFn(id);
    setItems(prev => prev.filter(i => i.id !== id));
  };

  return (
    <div>
      <AdminTitle title={title} sub={subtitle} />

      <div style={{ display: 'flex', gap: 10, marginBottom: 28 }}>
        <input value={newName} onChange={e => setNewName(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleCreate()}
          placeholder={`Nombre de la ${noun}…`}
          style={{ flex: 1, ...inputSt }} />
        <button className="btn btn-primary" onClick={handleCreate} disabled={saving || !newName.trim()} style={{ fontSize: 13 }}>
          + Agregar
        </button>
      </div>

      {busy ? <AdminLoading /> : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {items.length === 0 && <AdminEmpty text={`No hay ${title.toLowerCase()} aún.`} />}
          {items.map(item => (
            <div key={item.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
              background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 8,
            }}>
              {editing?.id === item.id ? (
                <>
                  <input value={editing.name} autoFocus
                    onChange={e => setEditing(p => ({ ...p, name: e.target.value }))}
                    onKeyDown={e => { if (e.key === 'Enter') handleUpdate(); if (e.key === 'Escape') setEditing(null); }}
                    style={{ flex: 1, ...inputSt, fontSize: 14 }} />
                  <button style={btnSm('primary')} onClick={handleUpdate} disabled={saving}>Guardar</button>
                  <button style={btnSm()} onClick={() => setEditing(null)}>Cancelar</button>
                </>
              ) : (
                <>
                  <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{item.name}</span>
                  <button style={btnSm()} onClick={() => setEditing({ id: item.id, name: item.name })}>Editar</button>
                  <button style={btnSm('danger')} onClick={() => handleDelete(item.id)}>Eliminar</button>
                </>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── TabInvitaciones ──────────────────────────────────────── */
function TabInvitaciones() {
  const { items: invs, setItems: setInvs, busy, reload } = useList(() => IHA.getInvitations());
  const { items: depts } = useList(() => IHA.getDepartments());
  const [form, setForm] = useSA({ department_id: '', max_uses: '', expires_in_days: '' });
  const [saving, setSaving] = useSA(false);
  const [copied, setCopied] = useSA(null);

  const handleCreate = async () => {
    setSaving(true);
    try {
      const data = {};
      if (form.department_id) data.department_id = parseInt(form.department_id);
      if (form.max_uses) data.max_uses = parseInt(form.max_uses);
      if (form.expires_in_days) data.expires_in_days = parseInt(form.expires_in_days);
      await IHA.createInvitation(data);
      setForm({ department_id: '', max_uses: '', expires_in_days: '' });
      reload();
    } finally { setSaving(false); }
  };

  const handleDelete = async (id) => {
    if (!confirm('¿Eliminar esta invitación?')) return;
    await IHA.deleteInvitation(id);
    setInvs(prev => prev.filter(i => i.id !== id));
  };

  const copyUrl = (url, id) => {
    navigator.clipboard.writeText(url).then(() => {
      setCopied(id);
      setTimeout(() => setCopied(null), 2000);
    });
  };

  return (
    <div>
      <AdminTitle title="Invitaciones" sub="Links para invitar colaboradores a la evaluación" />

      <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 10, padding: '20px 22px', marginBottom: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Nueva invitación</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 130px 150px auto', gap: 10, alignItems: 'end' }}>
          <div>
            <label style={labelSt}>Área (opcional)</label>
            <select value={form.department_id} onChange={e => setForm(p => ({ ...p, department_id: e.target.value }))}
              style={{ ...inputSt, width: '100%' }}>
              <option value="">Todas las áreas</option>
              {depts.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
            </select>
          </div>
          <div>
            <label style={labelSt}>Máx. usos</label>
            <input type="number" min="1" value={form.max_uses}
              onChange={e => setForm(p => ({ ...p, max_uses: e.target.value }))}
              placeholder="Sin límite" style={{ ...inputSt, width: '100%' }} />
          </div>
          <div>
            <label style={labelSt}>Expira en días</label>
            <input type="number" min="1" value={form.expires_in_days}
              onChange={e => setForm(p => ({ ...p, expires_in_days: e.target.value }))}
              placeholder="Sin expiración" style={{ ...inputSt, width: '100%' }} />
          </div>
          <button className="btn btn-primary" onClick={handleCreate} disabled={saving} style={{ fontSize: 13, whiteSpace: 'nowrap' }}>
            Crear link
          </button>
        </div>
      </div>

      {busy ? <AdminLoading /> : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {invs.length === 0 && <AdminEmpty text="No hay invitaciones aún." />}
          {invs.map(inv => (
            <div key={inv.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', flexWrap: 'wrap',
              background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 8,
            }}>
              <div style={{ flex: 1, minWidth: 240 }}>
                <div style={{ fontSize: 12.5, fontFamily: 'var(--mono)', wordBreak: 'break-all', color: 'var(--ink)' }}>
                  {inv.url}
                </div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 5 }}>
                  {inv.department_name || 'Todas las áreas'}
                  {' · '}{inv.uses}{inv.max_uses ? `/${inv.max_uses}` : ''} usos
                  {inv.expires_at && ` · Expira ${new Date(inv.expires_at).toLocaleDateString('es-MX')}`}
                </div>
              </div>
              <button style={btnSm(copied === inv.id ? 'primary' : '')} onClick={() => copyUrl(inv.url, inv.id)}>
                {copied === inv.id ? '✓ Copiado' : 'Copiar link'}
              </button>
              <button style={btnSm('danger')} onClick={() => handleDelete(inv.id)}>Eliminar</button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── TabColaboradores ─────────────────────────────────────── */
function TabColaboradores({ onViewResult, adminUser, initCompanyId }) {
  const isSuperAdmin = adminUser?.role === 'superadmin';
  const [assessments, setAssessments] = useSA([]);
  const [page, setPage] = useSA(1);
  const [pages, setPages] = useSA(1);
  const [total, setTotal] = useSA(0);
  const [area, setArea] = useSA('');
  const [companyId, setCompanyId] = useSA(initCompanyId || '');
  const { items: depts } = useList(() => IHA.getDepartments());
  const [companies, setCompanies] = useSA([]);
  const [busy, setBusy] = useSA(true);
  const [loadingId, setLoadingId] = useSA(null);

  useEA(() => {
    if (isSuperAdmin) IHA.getCompanies().then(setCompanies).catch(() => {});
  }, []);

  useEA(() => {
    setBusy(true);
    IHA.getAssessments({ page, area: area || undefined, company_id: companyId || undefined })
      .then(d => { setAssessments(d.data); setPages(d.pages); setTotal(d.total); setBusy(false); })
      .catch(() => setBusy(false));
  }, [page, area, companyId]);

  const viewResult = async (id) => {
    setLoadingId(id);
    try {
      const result = await IHA.getResult(id);
      onViewResult(result);
    } finally { setLoadingId(null); }
  };

  const thSt = {
    textAlign: 'left', padding: '8px 10px', fontFamily: 'var(--mono)',
    fontSize: 10.5, fontWeight: 500, color: 'var(--ink-3)',
    letterSpacing: '0.06em', textTransform: 'uppercase',
  };

  return (
    <div>
      <AdminTitle title="Colaboradores" sub={`${total} evaluaciones completadas`} />

      <div style={{ display: 'flex', gap: 12, marginBottom: 20, alignItems: 'center', flexWrap: 'wrap' }}>
        {isSuperAdmin && (
          <select value={companyId} onChange={e => { setCompanyId(e.target.value); setPage(1); setArea(''); }}
            style={{ ...inputSt, minWidth: 200 }}>
            <option value="">Todas las empresas</option>
            {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        )}
        <select value={area} onChange={e => { setArea(e.target.value); setPage(1); }}
          style={{ ...inputSt, width: 200 }}>
          <option value="">Todas las áreas</option>
          {depts.map(d => <option key={d.id} value={d.name}>{d.name}</option>)}
        </select>
      </div>

      {busy ? <AdminLoading /> : (
        <>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ borderBottom: '1.5px solid var(--ink)' }}>
                  {['Nombre', 'Área', 'Puesto', 'Arquetipo', 'Evolución', 'Fecha', ''].map(h => (
                    <th key={h} style={thSt}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {assessments.length === 0 && (
                  <tr>
                    <td colSpan="7" style={{ padding: '28px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
                      Sin evaluaciones completadas.
                    </td>
                  </tr>
                )}
                {assessments.map(a => {
                  const arch = IHD?.byId?.[a.dominant];
                  const ei = parseInt(a.evolution_index) || 0;
                  return (
                    <tr key={a.id} style={{ borderBottom: '1px solid var(--hair)' }}>
                      <td style={{ padding: '11px 10px', fontWeight: 500 }}>{a.respondent_name || '—'}</td>
                      <td style={{ padding: '11px 10px', color: 'var(--ink-2)' }}>{a.department || '—'}</td>
                      <td style={{ padding: '11px 10px', color: 'var(--ink-2)' }}>{a.puesto || '—'}</td>
                      <td style={{ padding: '11px 10px' }}>
                        {arch ? (
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12.5, fontWeight: 600, color: arch.hex }}>
                            <Glyph id={a.dominant} size={13} stroke={1.6} />{arch.name}
                          </span>
                        ) : '—'}
                      </td>
                      <td style={{ padding: '11px 10px' }}>
                        <span className="mono" style={{ fontWeight: 600, color: ei >= 60 ? 'var(--good)' : ei >= 40 ? 'var(--warn)' : 'var(--risk)' }}>
                          {ei}
                        </span>
                      </td>
                      <td style={{ padding: '11px 10px', color: 'var(--ink-3)', fontSize: 12 }}>
                        {a.updated_at ? new Date(a.updated_at).toLocaleDateString('es-MX') : '—'}
                      </td>
                      <td style={{ padding: '11px 10px', whiteSpace: 'nowrap' }}>
                        <button style={{ ...btnSm(), marginRight: 6 }} onClick={() => viewResult(a.id)} disabled={loadingId === a.id}>
                          {loadingId === a.id ? '…' : 'Ver'}
                        </button>
                        <button style={btnSm('danger')} onClick={async () => {
                          if (!confirm(`¿Eliminar la evaluación de ${a.respondent_name || 'este colaborador'}?`)) return;
                          await IHA.deleteAssessment(a.id);
                          setAssessments(prev => prev.filter(x => x.id !== a.id));
                          setTotal(t => t - 1);
                        }}>×</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {pages > 1 && (
            <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 20 }}>
              <button className="btn btn-ghost" disabled={page <= 1} onClick={() => setPage(p => p - 1)} style={{ fontSize: 13 }}>← Anterior</button>
              <span className="mono" style={{ fontSize: 13, color: 'var(--ink-3)', alignSelf: 'center' }}>{page} / {pages}</span>
              <button className="btn btn-ghost" disabled={page >= pages} onClick={() => setPage(p => p + 1)} style={{ fontSize: 13 }}>Siguiente →</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

/* ── TabEmpresas (superadmin) ─────────────────────────────── */
const AREA_SUGGESTIONS = ['Ventas', 'Operaciones', 'Administración', 'Dirección', 'Tecnología', 'Recursos Humanos', 'Marketing', 'Finanzas', 'Logística', 'Servicio al cliente', 'Calidad', 'Producción'];

function TabEmpresas({ onViewColabs }) {
  const { items: companies, reload } = useList(() => IHA.getCompanies());
  const [form, setForm] = useSA({ name: '', admin_email: '', admin_password: '' });
  const [areas, setAreas] = useSA([]);
  const [sucursales, setSucursales] = useSA([]);
  const [newArea, setNewArea] = useSA('');
  const [newSuc, setNewSuc] = useSA('');
  const [saving, setSaving] = useSA(false);
  const [created, setCreated] = useSA(null);
  const [err, setErr] = useSA(null);

  const toggleArea = (name) => setAreas(prev =>
    prev.includes(name) ? prev.filter(a => a !== name) : [...prev, name]
  );
  const addCustomArea = () => {
    const v = newArea.trim();
    if (v && !areas.includes(v)) { setAreas(p => [...p, v]); setNewArea(''); }
  };
  const addSuc = () => {
    const v = newSuc.trim();
    if (v && !sucursales.includes(v)) { setSucursales(p => [...p, v]); setNewSuc(''); }
  };

  const handleCreate = async () => {
    if (!form.name || !form.admin_email || !form.admin_password) return;
    setSaving(true);
    setErr(null);
    try {
      const c = await IHA.createCompany({ ...form, departments: areas, sucursales });
      setCreated(c);
      setForm({ name: '', admin_email: '', admin_password: '' });
      setAreas([]); setSucursales([]);
      reload();
    } catch (e) {
      setErr(e.message);
    } finally { setSaving(false); }
  };

  const tagSt = (active) => ({
    display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12.5,
    padding: '5px 11px', borderRadius: 20, cursor: 'pointer', border: '1px solid',
    fontFamily: 'var(--sans)',
    background: active ? 'var(--ink)' : 'var(--panel)',
    color: active ? '#fff' : 'var(--ink-2)',
    borderColor: active ? 'var(--ink)' : 'var(--hair-2)',
  });

  return (
    <div>
      <AdminTitle title="Empresas" sub="Gestión multi-empresa (solo superadmin)" />

      {created && (
        <div style={{ background: 'oklch(0.60 0.09 150 / 0.10)', border: '1px solid var(--good)', borderRadius: 8, padding: '14px 18px', marginBottom: 20, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span><strong style={{ color: 'var(--good)' }}>✓ Empresa creada:</strong> {created.name} — Admin: <strong>{created.admin_email}</strong></span>
          <button style={btnSm('danger')} onClick={() => setCreated(null)}>×</button>
        </div>
      )}

      {err && (
        <div style={{ background: 'oklch(0.56 0.13 28 / 0.08)', border: '1px solid var(--risk)', borderRadius: 8, padding: '12px 18px', marginBottom: 20, fontSize: 13, color: 'var(--risk)' }}>
          {err}
        </div>
      )}

      <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 10, padding: '22px 24px', marginBottom: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>Nueva empresa</div>

        {/* Datos básicos */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 22 }}>
          {[
            ['name', 'Nombre de empresa', 'text', 'Grupo Ejemplo'],
            ['admin_email', 'Email del admin', 'email', 'admin@empresa.com'],
            ['admin_password', 'Contraseña admin', 'password', 'Mínimo 8 caracteres'],
          ].map(([k, l, t, ph]) => (
            <div key={k}>
              <label style={labelSt}>{l}</label>
              <input type={t} value={form[k]} placeholder={ph}
                onChange={e => setForm(p => ({ ...p, [k]: e.target.value }))}
                style={{ ...inputSt, width: '100%' }} />
            </div>
          ))}
        </div>

        {/* Áreas */}
        <div style={{ marginBottom: 18 }}>
          <label style={labelSt}>Áreas <span style={{ fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>(opcional)</span></label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
            {AREA_SUGGESTIONS.map(s => (
              <button key={s} style={tagSt(areas.includes(s))} onClick={() => toggleArea(s)}>
                {s}{areas.includes(s) && <span style={{ fontSize: 14, lineHeight: 1 }}>×</span>}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input value={newArea} onChange={e => setNewArea(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addCustomArea()}
              placeholder="Área personalizada…" style={{ flex: 1, ...inputSt }} />
            <button style={btnSm('primary')} onClick={addCustomArea} disabled={!newArea.trim()}>+ Agregar</button>
          </div>
          {areas.filter(a => !AREA_SUGGESTIONS.includes(a)).length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 8 }}>
              {areas.filter(a => !AREA_SUGGESTIONS.includes(a)).map(a => (
                <span key={a} style={tagSt(true)}>
                  {a}<span style={{ cursor: 'pointer', fontSize: 14 }} onClick={() => setAreas(p => p.filter(x => x !== a))}>×</span>
                </span>
              ))}
            </div>
          )}
        </div>

        {/* Sucursales */}
        <div style={{ marginBottom: 22 }}>
          <label style={labelSt}>Sucursales <span style={{ fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>(opcional)</span></label>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            <input value={newSuc} onChange={e => setNewSuc(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addSuc()}
              placeholder="Ej. Ciudad de México…" style={{ flex: 1, ...inputSt }} />
            <button style={btnSm('primary')} onClick={addSuc} disabled={!newSuc.trim()}>+ Agregar</button>
          </div>
          {sucursales.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
              {sucursales.map(s => (
                <span key={s} style={tagSt(true)}>
                  {s}<span style={{ cursor: 'pointer', fontSize: 14 }} onClick={() => setSucursales(p => p.filter(x => x !== s))}>×</span>
                </span>
              ))}
            </div>
          )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn btn-primary" onClick={handleCreate}
            disabled={saving || !form.name || !form.admin_email || !form.admin_password}
            style={{ fontSize: 13 }}>
            {saving ? 'Creando…' : 'Crear empresa'}
          </button>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {companies.length === 0 && <AdminEmpty text="No hay empresas registradas." />}
        {companies.map(c => (
          <div key={c.id} style={{
            display: 'flex', alignItems: 'center', gap: 18, padding: '14px 18px',
            background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 8,
          }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{c.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>
                {c.admin_count} admin · {c.assessment_count} evaluaciones
                {c.created_at && ` · ${new Date(c.created_at).toLocaleDateString('es-MX')}`}
              </div>
            </div>
            {c.assessment_count > 0 && (
              <button style={btnSm()} onClick={() => onViewColabs(c.id)}>
                Ver colaboradores →
              </button>
            )}
            <button style={btnSm('danger')} onClick={async () => {
              const msg = c.assessment_count > 0
                ? `¿Eliminar "${c.name}"? Se borrarán ${c.assessment_count} evaluaciones permanentemente.`
                : `¿Eliminar "${c.name}"?`;
              if (!confirm(msg)) return;
              await IHA.deleteCompany(c.id);
              reload();
            }}>
              Eliminar
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── ResultModal — overlay con resultado individual ───────── */
function ResultModal({ result, onClose }) {
  const arch = IHD?.byId?.[result.dominant];
  const scores = result.scores || {};
  const respondent = result.respondent || {};
  const ei = parseInt(result.evolution_index) || 0;
  const diagLine = result.diagnostic_line;

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.52)', zIndex: 100,
      overflowY: 'auto', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '40px 20px',
    }} onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ maxWidth: 780, width: '100%', background: 'var(--paper)', borderRadius: 14, padding: '40px 44px', position: 'relative' }}>
        <button onClick={onClose} style={{
          position: 'absolute', top: 16, right: 18, border: 'none', background: 'none',
          cursor: 'pointer', fontSize: 24, color: 'var(--ink-3)', lineHeight: 1,
        }}>×</button>

        <div className="eyebrow" style={{ marginBottom: 10 }}>Resultado individual</div>
        <h2 className="serif" style={{ fontSize: 28, fontWeight: 600, margin: '0 0 10px' }}>
          {respondent.name || result.respondent_name || 'Colaborador'}
        </h2>
        <div style={{ display: 'flex', gap: 8, marginBottom: 28, flexWrap: 'wrap' }}>
          {[respondent.area || result.department, respondent.puesto || result.puesto, respondent.antiguedad].filter(Boolean).map((t, i) => (
            <span key={i} className="mono" style={{
              fontSize: 11.5, background: 'var(--panel)', border: '1px solid var(--hair)',
              borderRadius: 20, padding: '4px 12px', color: 'var(--ink-2)',
            }}>{t}</span>
          ))}
          {result.period && (
            <span className="mono" style={{
              fontSize: 11.5, background: 'var(--panel)', border: '1px solid var(--hair)',
              borderRadius: 20, padding: '4px 12px', color: 'var(--ink-3)',
            }}>{result.period}</span>
          )}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 260px', gap: 32, marginBottom: 28 }}>
          <div>
            {arch && (
              <>
                <div className="eyebrow" style={{ marginBottom: 12 }}>Opera principalmente desde</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
                  <div style={{ width: 52, height: 52, borderRadius: 12, background: arch.hex + '1c', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
                    <Glyph id={result.dominant} size={30} stroke={2} />
                  </div>
                  <div>
                    <div className="serif" style={{ fontSize: 32, fontWeight: 600, color: arch.hex, lineHeight: 1 }}>{arch.name}</div>
                    {arch.glyph && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{arch.glyph}</div>}
                  </div>
                </div>
              </>
            )}
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 22 }}>
              <div>
                <div className="eyebrow" style={{ marginBottom: 6 }}>Índice de evolución</div>
                <span className="serif" style={{ fontSize: 40, fontWeight: 600, color: 'var(--gold)' }}>{ei}</span>
                <span className="mono" style={{ fontSize: 13, color: 'var(--ink-3)' }}> /100</span>
              </div>
            </div>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Scores por arquetipo</div>
            {IHD && IHD.order.map(id => <ScoreBar key={id} id={id} value={scores[id] || 0} showGlyph />)}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            {arch && <Radar size={250} series={[{ scores, color: arch.hex, fillOpacity: 0.13 }]} />}
          </div>
        </div>

        {diagLine && (
          <div style={{ background: 'var(--panel)', borderLeft: '3px solid var(--gold)', borderRadius: 8, padding: '16px 20px', marginBottom: 22 }}>
            <p className="serif" style={{ fontSize: 16, lineHeight: 1.5, margin: 0 }}>
              {diagLine.lead}
              {diagLine.turn && (
                <em style={{ color: 'var(--gold)', fontStyle: 'italic' }}> {diagLine.turn}</em>
              )}
            </p>
          </div>
        )}

        <button className="btn btn-ghost" onClick={onClose} style={{ fontSize: 13, marginTop: 4 }}>Cerrar</button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenAdmin });
