// Formulario de alta/edición de CI — drawer dinámico
const { useState: useStateForm, useEffect: useEffectForm, useMemo: useMemoForm, useRef: useRefForm } = React;

// Definición de campos por tipo de CI
const FORM_SCHEMAS = {
  USR: {
    title: 'Empleado',
    idPrefix: 'USR',
    sections: [
      {
        title: 'Identidad',
        fields: [
          { k: 'nombre',    l: 'Nombre completo', t: 'text', required: true, ph: 'Ej. María Fernanda Quintero', w: 2 },
          { k: 'categoria', l: 'Tipo',            t: 'select', required: true, opts: ['empleado', 'externo'], default: 'empleado',
            hint: '"externo" = colaborador/freelance que usa recursos de Motion pero no es nómina' },
          { k: 'puesto',  l: 'Puesto',          t: 'text', required: true, ph: 'Ej. Directora de Operaciones' },
          { k: 'area',    l: 'Área',            t: 'select', required: true, opts: ['Operaciones','TI','Finanzas','Ventas','Recursos Humanos','Producto','Marketing','Administración','Colaboradores externos'] },
          { k: 'empresaId', l: 'Empresa del grupo', t: 'ref', refType: 'EMP', placeholder: 'Sin asignar' },
          { k: 'sitioId', l: 'Sitio', t: 'ref', refType: 'SIT', placeholder: 'Sin asignar', hint: 'Sus tickets nuevos se abren en este sitio (se puede cambiar en cada ticket)' },
          { k: 'esTecnico', l: 'Técnico de TI', t: 'bool',
            hint: 'Aparece en el picker de responsable/técnico al programar mantenimientos. Pensado también para limitar el login de la plataforma a técnicos más adelante.' },
        ],
      },
      {
        title: 'Contacto y empleo',
        fields: [
          { k: 'email',   l: 'Email corporativo', t: 'email', required: true, ph: 'usuario@grupoejemplo.mx', w: 2 },
          { k: 'ingreso', l: 'Fecha de ingreso',  t: 'date',  required: true },
          // "Estado" se quitó de este formulario a propósito: el alta y la
          // baja real de un empleado (con la liberación de equipo,
          // licencias y buzón) se hacen desde los procesos dedicados
          // (Alta / Baja / Reasignación en el menú de Procesos) -- cambiar
          // el estado aquí dejaría esos recursos asignados sin liberar.
          // Este formulario solo sirve para corregir datos de identidad
          // (nombre, puesto, área, correo, fecha de ingreso).
        ],
      },
    ],
  },
  EQP: {
    title: 'Equipo de cómputo',
    idPrefix: 'EQP',
    sections: [
      {
        title: 'Identificación',
        fields: [
          // Número de activo, serie, costo, fecha de adquisición y proveedor
          // se dejaron de exigir: en el inventario real casi nunca se
          // capturan para celulares y accesorios (a diferencia de
          // laptops/desktops) — así quedó también la base de datos
          // (columnas nullable), y el formulario debía reflejarlo.
          // Networking e Impresora se separaron a su propio tipo de CI
          // (Infraestructura, más abajo) — no son equipo de cómputo
          // asignado a una persona, son equipo de servicio compartido.
          { k: 'numActivo', l: 'Número de activo', t: 'text', ph: 'Ej. MSIMX0027 (si aplica)', mono: true, maxLength: 20, pattern: /^[A-Za-z0-9-]*$/, hint: 'Alfanumérico · máx. 20 caracteres', uppercase: true },
          { k: 'tipo',     l: 'Tipo',     t: 'select', required: true, opts: ['Laptop','Desktop','Tablet','Otro','Celular','Accesorio'] },
          { k: 'modelo',   l: 'Modelo',   t: 'text',   required: true, ph: 'Ej. Dell Latitude 5540' },
          { k: 'serie',    l: 'Número de serie', t: 'text', ph: 'Serie del fabricante (si aplica)', mono: true, w: 2 },
        ],
      },
      {
        title: 'Especificaciones',
        fields: [
          { k: 'sistema',  l: 'Sistema operativo', t: 'select', opts: ['Windows 11 Pro','Windows 10 Pro','Windows 11 Home','macOS 15','macOS 14','Ubuntu 22.04','Otro'] },
          { k: 'ram',      l: 'RAM',  t: 'select', opts: ['4GB','8GB','16GB','24GB','32GB','64GB'] },
          { k: 'procesador', l: 'Procesador', t: 'text', ph: 'Ej. Intel Core i5-1235U' },
          { k: 'disco',      l: 'Disco',      t: 'text', ph: 'Ej. 512GB SSD' },
          { k: 'macAddress', l: 'Dirección MAC', t: 'text', ph: 'AA:BB:CC:DD:EE:FF (si aplica)', mono: true },
          { k: 'ip',         l: 'Dirección IP', t: 'text', ph: '10.0.10.21 (si aplica)', mono: true },
        ],
      },
      {
        title: 'Adquisición y asignación',
        fields: [
          { k: 'adquirido',l: 'Fecha de adquisición', t: 'date' },
          { k: 'costo',    l: 'Costo (MXN)',          t: 'number', ph: '25000' },
          { k: 'proveedor',l: 'Proveedor',            t: 'ref', refType: 'PRV' },
          { k: 'asignadoA',l: 'Asignado a',           t: 'ref', refType: 'USR', placeholder: 'Sin asignar (en stock)' },
          { k: 'estado',   l: 'Estado',               t: 'select', opts: ['activo','stock','obsoleto','baja'], default: 'activo' },
          { k: 'notas',    l: 'Notas',                t: 'text', ph: 'Observaciones adicionales', w: 2 },
        ],
      },
    ],
  },
  INF: {
    title: 'Infraestructura / equipo de servicio',
    idPrefix: 'INF',
    sections: [
      {
        title: 'Identificación',
        fields: [
          // Equipo de servicio compartido, SIN responsable individual —
          // routers/switches/APs y otro equipo de red, e impresoras de
          // área común. A diferencia de Equipos, no tiene "asignado a".
          { k: 'numActivo', l: 'Número de activo', t: 'text', ph: 'Si aplica', mono: true, maxLength: 20, pattern: /^[A-Za-z0-9-]*$/, hint: 'Alfanumérico · máx. 20 caracteres', uppercase: true },
          { k: 'tipo',     l: 'Tipo',     t: 'select', required: true, opts: ['Networking','Impresora','Otro'] },
          { k: 'modelo',   l: 'Modelo',   t: 'text',   required: true, ph: 'Ej. Router Cisco RV340' },
          { k: 'serie',    l: 'Número de serie', t: 'text', ph: 'Serie del fabricante (si aplica)', mono: true, w: 2 },
          { k: 'ip',       l: 'Dirección IP', t: 'text', ph: '10.0.10.21 (routers, switches, APs)', mono: true },
        ],
      },
      {
        title: 'Adquisición y ubicación',
        fields: [
          { k: 'adquirido',      l: 'Fecha de adquisición', t: 'date' },
          { k: 'costo',          l: 'Costo (MXN)',          t: 'number', ph: '5000' },
          { k: 'garantiaVence',  l: 'Garantía vence',       t: 'date' },
          { k: 'proveedor',      l: 'Proveedor',            t: 'ref', refType: 'PRV' },
          { k: 'empresaId',      l: 'Empresa del grupo',    t: 'ref', refType: 'EMP', placeholder: 'Sin asignar' },
          { k: 'estado',         l: 'Estado',               t: 'select', opts: ['activo','stock','obsoleto','baja'], default: 'activo' },
          { k: 'notas',          l: 'Notas',                t: 'text', ph: 'Ubicación física, observaciones…', w: 2 },
        ],
      },
    ],
  },
  SRV: {
    title: 'Servidor',
    idPrefix: 'SRV',
    sections: [
      {
        title: 'Identificación',
        fields: [
          { k: 'nombre',    l: 'Hostname', t: 'text', required: true, ph: 'ejemplo-app-01', mono: true },
          { k: 'tipo',      l: 'Tipo',     t: 'select', required: true, opts: ['Aplicaciones','Base de Datos','Archivos','Active Directory','Correo Relay','Respaldos','Web','Otro'] },
          { k: 'ip',        l: 'Dirección IP', t: 'text', ph: '10.0.10.21', mono: true },
        ],
      },
      {
        title: 'Especificaciones',
        fields: [
          { k: 'so',  l: 'Sistema operativo', t: 'text', ph: 'Ubuntu 22.04 LTS' },
          { k: 'cpu', l: 'CPU',               t: 'text', ph: '16 vCPU', mono: true },
          { k: 'ram', l: 'RAM',               t: 'text', ph: '64GB', mono: true },
        ],
      },
      {
        title: 'Ubicación y proveedor',
        fields: [
          { k: 'ubicacion', l: 'Ubicación física', t: 'text', ph: 'KIO Querétaro / Oficina GDL', w: 2 },
          { k: 'adquirido', l: 'Fecha de adquisición', t: 'date' },
          { k: 'proveedor', l: 'Proveedor',           t: 'ref', refType: 'PRV' },
          { k: 'estado',    l: 'Estado',              t: 'select', opts: ['activo','obsoleto','mantenimiento','baja'], default: 'activo' },
        ],
      },
    ],
  },
  LIC: {
    title: 'Licencia',
    idPrefix: 'LIC',
    sections: [
      {
        title: 'Producto',
        fields: [
          { k: 'producto', l: 'Nombre del producto', t: 'text', required: true, ph: 'Ej. Microsoft 365 Business Premium', w: 2 },
          { k: 'tipo',     l: 'Tipo',     t: 'select', required: true, opts: ['SaaS','Software','Antivirus','OEM'] },
          { k: 'proveedor',l: 'Proveedor',t: 'ref', refType: 'PRV', required: true },
        ],
      },
      {
        title: 'Asientos y vigencia',
        fields: [
          { k: 'asientos',  l: 'Asientos contratados', t: 'number', required: true, ph: '50' },
          // "Asientos en uso" se quitó del formulario: no es un dato que se
          // capture, se calcula solo a partir de a quién se le ha asignado
          // la licencia (ver Procesos → Alta/Reasignación).
          { k: 'vence',     l: 'Vencimiento',          t: 'date',   required: true },
          { k: 'costoAnual',l: 'Costo anual (MXN)',    t: 'number', required: true, ph: '38400', hint: 'si se paga cada mes, captura el total anualizado (mensual × 12)' },
          { k: 'periodicidad', l: 'Periodicidad de pago', t: 'select', opts: ['anual', 'mensual'], default: 'anual' },
        ],
      },
    ],
  },
  MBX: {
    title: 'Buzón / Correo',
    idPrefix: 'MBX',
    sections: [
      {
        title: 'Buzón',
        fields: [
          { k: 'direccion', l: 'Dirección de correo', t: 'email', required: true, ph: 'usuario@grupoejemplo.mx', mono: true, w: 2 },
          { k: 'tipo',      l: 'Tipo',  t: 'select', required: true, opts: ['Usuario','Compartido','Sistema','Distribución'] },
          { k: 'plan',      l: 'Plan',  t: 'text',   ph: 'Ej. M365 Business Premium' },
        ],
      },
      {
        title: 'Almacenamiento y seguridad',
        fields: [
          { k: 'cuotaGB',  l: 'Cuota (GB)',  t: 'number', default: 50 },
          { k: 'usadoGB',  l: 'Usado (GB)',  t: 'number', default: 0 },
          { k: 'mfa',      l: 'MFA activado',t: 'bool',   default: false },
          { k: 'asociado', l: 'Asociado a',  t: 'ref',    refType: 'USR' },
          { k: 'licenciaId', l: 'Licencia del servicio de correo', t: 'ref', refType: 'LIC', hint: 'el buzón ocupa un asiento de esa licencia (p. ej. Google Workspace)' },
          { k: 'estado',   l: 'Estado',      t: 'select', opts: ['activo','suspendido','baja'], default: 'activo',
            hint: 'Se debería poner en "baja" al dar de baja al empleado asociado, pero puede editarse aquí en cualquier momento' },
        ],
      },
    ],
  },
  TEL: {
    title: 'Línea telefónica',
    idPrefix: 'TEL',
    sections: [
      {
        title: 'Línea',
        fields: [
          { k: 'numero',   l: 'Número',  t: 'text', required: true, ph: '+52 614 000 0000', mono: true },
          { k: 'compania', l: 'Compañía', t: 'select', required: true, opts: ['Telcel', 'AT&T', 'Movistar', 'Otro'], default: 'Telcel' },
          { k: 'asignadoA',l: 'Asignada a', t: 'ref', refType: 'USR', placeholder: 'Sin asignar (en stock)' },
        ],
      },
      {
        title: 'Contrato',
        fields: [
          { k: 'importeMensual', l: 'Importe mensual', t: 'number', ph: '350' },
          { k: 'moneda',         l: 'Moneda', t: 'select', opts: ['MXN', 'USD'], default: 'MXN' },
          { k: 'contratada',     l: 'Fecha de contratación', t: 'date' },
          { k: 'estado',         l: 'Estado', t: 'select', opts: ['activo', 'stock', 'baja'], default: 'activo' },
        ],
      },
    ],
  },
  DOM: {
    title: 'Dominio',
    idPrefix: 'DOM',
    sections: [
      {
        title: 'Dominio',
        fields: [
          { k: 'dominio',   l: 'Dominio', t: 'text', required: true, ph: 'empresa.com.mx', mono: true, w: 2, hint: 'sin http:// ni www' },
          { k: 'empresaId', l: 'Razón social (empresa del grupo)', t: 'ref', refType: 'EMP', required: true },
          { k: 'proveedor', l: 'Proveedor / registrador', t: 'ref', refType: 'PRV' },
        ],
      },
      {
        title: 'Renovación y costo',
        fields: [
          { k: 'registrado', l: 'Fecha de registro', t: 'date' },
          { k: 'vence',      l: 'Vencimiento (renovación)', t: 'date', required: true },
          { k: 'costoAnual', l: 'Costo anual (MXN)', t: 'number', ph: '450' },
          { k: 'renovacionAutomatica', l: 'Renovación automática', t: 'bool', default: false },
          { k: 'estado',     l: 'Estado', t: 'select', opts: ['activo', 'baja'], default: 'activo', hint: '"baja" = ya no se renueva ni genera alertas' },
          { k: 'notas',      l: 'Notas', t: 'text', w: 2, ph: 'Cuenta del registrador, contacto técnico…' },
        ],
      },
    ],
  },
  HST: {
    title: 'Hosting',
    idPrefix: 'HST',
    sections: [
      {
        title: 'Servicio',
        fields: [
          { k: 'nombre',    l: 'Nombre del plan', t: 'text', required: true, ph: 'Ej. Frappe', w: 2 },
          { k: 'tipo',      l: 'Tipo', t: 'select', required: true, opts: ['Servidor', 'Correo', 'Sitio web', 'Otro'], default: 'Servidor' },
          { k: 'proveedor', l: 'Proveedor', t: 'ref', refType: 'PRV' },
          { k: 'empresaId', l: 'Razón social que lo paga', t: 'ref', refType: 'EMP', placeholder: 'Sin asignar' },
          { k: 'servidor',  l: 'Servidor al que da servicio', t: 'ref', refType: 'SRV', placeholder: 'Ninguno', hint: 'solo si es el plan de un servidor; un hosting de correo o web no lo necesita' },
          { k: 'dominio',   l: 'Dominio ligado', t: 'ref', refType: 'DOM', placeholder: 'Ninguno' },
        ],
      },
      {
        title: 'Pago y renovación',
        fields: [
          { k: 'inicio',   l: 'Inicio del contrato', t: 'date' },
          { k: 'vence',    l: 'Próxima renovación', t: 'date', required: true },
          { k: 'ciclo',    l: 'Cada cuánto se paga', t: 'select', required: true, opts: Object.values(HST_CICLOS), default: 'Anual' },
          { k: 'moneda',   l: 'Moneda en que se paga', t: 'select', opts: ['MXN', 'USD'], default: 'MXN' },
          { k: 'costoCiclo',  l: 'Costo del ciclo (MXN)', t: 'number', ph: '35000', hint: 'si se paga en pesos. Si es en dólares se calcula solo con los dos campos siguientes' },
          { k: 'costoOrigen', l: 'Costo del ciclo en dólares (USD)', t: 'number', ph: '19299.24' },
          { k: 'tipoCambio',  l: 'Tipo de cambio ($ por dólar)', t: 'number', ph: '18.50', hint: 'el de la fecha en que lo registras; el costo en pesos = dólares × tipo de cambio' },
          { k: 'renovacionAutomatica', l: 'Renovación automática', t: 'bool', default: false },
          { k: 'estado',   l: 'Estado', t: 'select', opts: ['activo', 'baja'], default: 'activo', hint: '"baja" = ya no se renueva ni genera alertas' },
          { k: 'notas',    l: 'Notas', t: 'text', w: 2, ph: 'Cuenta, contacto técnico, qué incluye el plan…' },
        ],
      },
    ],
  },
  PRV: {
    title: 'Proveedor',
    idPrefix: 'PRV',
    sections: [
      {
        title: 'Empresa',
        fields: [
          { k: 'nombre',  l: 'Razón social / Nombre comercial', t: 'text', required: true, ph: 'Ej. Grupo CompuSoluciones', w: 2 },
          { k: 'tipo',    l: 'Tipo de servicio', t: 'select', required: true, opts: ['Hardware','Software','Telecom','Datacenter','Consultoría','Otro'] },
          { k: 'rfc',     l: 'RFC', t: 'text', ph: 'XAXX010101000', mono: true },
        ],
      },
      {
        title: 'Contacto',
        fields: [
          { k: 'contacto', l: 'Persona de contacto', t: 'text', ph: 'Lic. Rodrigo Tello' },
          { k: 'telefono', l: 'Teléfono', t: 'text', ph: '+52 33 0000-0000', mono: true },
          { k: 'email',    l: 'Email', t: 'email', ph: 'contacto@proveedor.mx', w: 2 },
        ],
      },
    ],
  },
};

// ===== Generate next ID for a type =====
function nextIdFor(prefix) {
  const D = window.CMDB_DATA;
  const collMap = { USR: D.empleados, EQP: D.equipos, SRV: D.servidores, LIC: D.licencias, MBX: D.correos, PRV: D.proveedores, TEL: D.lineas, INF: D.infraestructura, DOM: D.dominios, HST: D.hostings };
  const coll = collMap[prefix] || [];
  const nums = coll.map(c => parseInt(c.id.split('-')[1], 10)).filter(n => !isNaN(n));
  const max = nums.length ? Math.max(...nums) : 0;
  return `${prefix}-${String(max + 1).padStart(4, '0')}`;
}

// ===== Initial values =====
function initialValues(schema, existing) {
  if (existing) return { ...existing };
  const v = {};
  schema.sections.forEach(s => s.fields.forEach(f => {
    if (f.default !== undefined) v[f.k] = f.default;
    else if (f.t === 'bool') v[f.k] = false;
    else if (f.t === 'number') v[f.k] = '';
    else v[f.k] = '';
  }));
  return v;
}

// ===== The form drawer =====
function CIFormDrawer({ open, mode, initialType, existingCI, prefill, onClose, onSave }) {
  const [pickedType, setPickedType] = useStateForm(initialType || null);
  const [values, setValues] = useStateForm({});
  const [errors, setErrors] = useStateForm({});
  const inicialRef = useRefForm('{}'); // lo que había al abrir, para avisar antes de cerrar con datos sin guardar

  // When opening, init type + values
  useEffectForm(() => {
    if (!open) return;
    let vals = {};
    if (existingCI) {
      setPickedType(existingCI.kind);
      const schema = FORM_SCHEMAS[existingCI.kind];
      vals = initialValues(schema, existingCI.data);
    } else if (initialType) {
      setPickedType(initialType);
      vals = { ...initialValues(FORM_SCHEMAS[initialType]), ...(prefill || {}) };
    } else {
      setPickedType(null);
    }
    setValues(vals);
    inicialRef.current = JSON.stringify(vals);
    setErrors({});
  }, [open, mode, initialType, existingCI && existingCI.data && existingCI.data.id, prefill && prefill.dominio]);

  if (!open) return null;

  const schema = pickedType ? FORM_SCHEMAS[pickedType] : null;
  const isEdit = mode === 'edit';
  const sucio = !!pickedType && JSON.stringify(values) !== inicialRef.current;
  const pedirCerrar = async () => { if (await confirmarDescarte(sucio, 'Tienes datos sin guardar en este formulario. Si lo cierras, se pierden.')) onClose(); };

  const setField = (k, v) => {
    setValues(prev => ({ ...prev, [k]: v }));
    setErrors(prev => { if (!prev[k]) return prev; const n = { ...prev }; delete n[k]; return n; });
  };

  const validate = () => {
    const e = {};
    schema.sections.forEach(s => s.fields.forEach(f => {
      const v = values[f.k];
      if (f.required && (v === '' || v === null || v === undefined)) {
        e[f.k] = 'Requerido';
        return;
      }
      if (typeof v === 'string' && v !== '') {
        if (f.maxLength != null && v.length > f.maxLength) e[f.k] = `Máximo ${f.maxLength} caracteres`;
        if (f.pattern && !f.pattern.test(v)) e[f.k] = 'Caracteres no permitidos';
      }
    }));
    // unicidad del número de activo entre equipos
    if (pickedType === 'EQP' && values.numActivo) {
      const dup = window.CMDB_DATA.equipos.find(eq => eq.numActivo && eq.numActivo.toUpperCase() === values.numActivo.toUpperCase() && (!isEdit || eq.id !== existingCI.data.id));
      if (dup) e.numActivo = `Ya en uso por ${dup.id}`;
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSave = () => {
    if (!validate()) return;
    onSave({ kind: pickedType, values, isEdit, id: isEdit ? existingCI.data.id : nextIdFor(pickedType) });
  };

  return (
    <>
      <div className="drawer-scrim" onClick={pedirCerrar} />
      <aside className="drawer">
        <header className="drawer-h">
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              {isEdit ? 'Editando' : 'Nuevo CI'}
            </div>
            <h3 style={{ margin: '4px 0 0', fontSize: 18, fontWeight: 600 }}>
              {schema ? schema.title : 'Selecciona el tipo de CI'}
            </h3>
            {schema && (
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>
                ID asignado: <span style={{ color: 'var(--ink-2)' }}>{isEdit ? existingCI.data.id : nextIdFor(pickedType)}</span>
              </div>
            )}
          </div>
          <button className="btn ghost" onClick={pedirCerrar}><Icon name="x" /></button>
        </header>

        <div className="drawer-body">
          {!pickedType ? (
            <TypePicker onPick={(k) => { const v0 = { ...initialValues(FORM_SCHEMAS[k]), ...(prefill && initialType === k ? prefill : {}) }; setPickedType(k); setValues(v0); inicialRef.current = JSON.stringify(v0); setErrors({}); }} />
          ) : (
            <>
              {isEdit && (
                <div className="form-banner">
                  <Icon name="warn" />
                  <div>
                    <strong>Estás editando un CI existente.</strong>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
                      Los cambios se registrarán en el historial del CI ({existingCI.data.id}).
                    </div>
                  </div>
                </div>
              )}
              {schema.sections.map((s, i) => (
                <FormSection key={i} title={s.title}>
                  {s.fields.map(f => (
                    <FormField key={f.k} f={f} value={values[f.k]} onChange={v => setField(f.k, v)} error={errors[f.k]} />
                  ))}
                </FormSection>
              ))}
            </>
          )}
        </div>

        {schema && (
          <footer className="drawer-f">
            <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
              {Object.keys(errors).length > 0 && <span style={{ color: 'var(--crit)' }}>· {Object.keys(errors).length} campo(s) requeridos faltan</span>}
            </span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="btn" onClick={pedirCerrar}>Cancelar</button>
              {!isEdit && (
                <button className="btn" onClick={() => { setPickedType(null); setValues({}); setErrors({}); }}>
                  ← Cambiar tipo
                </button>
              )}
              <button className="btn primary" onClick={handleSave}>
                <Icon name="check" /> {isEdit ? 'Guardar cambios' : 'Crear CI'}
              </button>
            </div>
          </footer>
        )}
      </aside>
    </>
  );
}

function TypePicker({ onPick }) {
  const D = window.CMDB_DATA;
  const types = [
    { k: 'USR', desc: 'Persona que trabaja en la empresa', count: D.empleados.length },
    { k: 'EQP', desc: 'Laptops, desktops y otros equipos de cómputo', count: D.equipos.length },
    { k: 'SRV', desc: 'Servidores físicos o virtuales', count: D.servidores.length },
    { k: 'LIC', desc: 'Licencias de software, SaaS, antivirus', count: D.licencias.length },
    { k: 'MBX', desc: 'Buzones de correo (usuario, compartidos, sistema)', count: D.correos.length },
    { k: 'PRV', desc: 'Empresas que nos venden hardware/software/servicios', count: D.proveedores.length },
    { k: 'TEL', desc: 'Líneas telefónicas asignadas a personal o en stock', count: D.lineas.length },
    { k: 'INF', desc: 'Equipo de red e impresoras de área común (sin responsable individual)', count: D.infraestructura.length },
    { k: 'DOM', desc: 'Dominios de internet: razón social, proveedor, costo y renovación', count: (D.dominios || []).length },
    { k: 'HST', desc: 'Contratos de hosting (planes de servidor, correo o sitio web): ciclo de pago, costo y renovación', count: (D.hostings || []).length },
  ];
  return (
    <div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>
        Tipos de CI
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {types.map(t => {
          const meta = CI_TYPES[t.k];
          return (
            <button key={t.k} className="type-pick" onClick={() => onPick(t.k)}>
              <div className="type-pick-icon" style={{ background: meta.color }}>
                <Icon name={iconForType(t.k)} size={18} />
              </div>
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{meta.plural}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t.desc}</div>
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t.count} existentes</div>
              <Icon name="arrow" />
            </button>
          );
        })}
      </div>
    </div>
  );
}

function FormSection({ title, children }) {
  return (
    <section className="form-section">
      <div className="form-section-h">{title}</div>
      <div className="form-grid">{children}</div>
    </section>
  );
}

function FormField({ f, value, onChange, error }) {
  const span = f.w === 2 ? { gridColumn: 'span 2' } : {};
  const wrapCls = `form-field ${f.mono ? 'mono' : ''} ${error ? 'has-err' : ''}`;
  const remaining = (f.maxLength != null && typeof value === 'string') ? (f.maxLength - value.length) : null;
  return (
    <div className={wrapCls} style={span}>
      <label className="form-label">
        {f.l}{f.required && <span style={{ color: 'var(--crit)' }}>*</span>}
        {remaining != null && (
          <span style={{ marginLeft: 'auto', fontFamily: 'IBM Plex Mono, monospace', color: remaining < 0 ? 'var(--crit)' : 'var(--ink-3)' }}>
            {value?.length || 0}/{f.maxLength}
          </span>
        )}
      </label>
      <FormControl f={f} value={value} onChange={onChange} />
      {f.hint && !error && <span style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'IBM Plex Mono, monospace' }}>{f.hint}</span>}
      {error && <span className="form-err">{error}</span>}
    </div>
  );
}

function FormControl({ f, value, onChange }) {
  const D = window.CMDB_DATA;
  if (f.t === 'text' || f.t === 'email') {
    const handleChange = (e) => {
      let v = e.target.value;
      if (f.uppercase) v = v.toUpperCase();
      if (f.pattern && v !== '' && !f.pattern.test(v)) return; // bloquea caracteres inválidos
      if (f.maxLength != null && v.length > f.maxLength) v = v.slice(0, f.maxLength);
      onChange(v);
    };
    return <input type={f.t} className="form-input" value={value || ''} onChange={handleChange} placeholder={f.ph || ''} maxLength={f.maxLength} />;
  }
  if (f.t === 'number') {
    return <input type="number" className="form-input mono" value={value || ''} onChange={e => onChange(e.target.value === '' ? '' : Number(e.target.value))} placeholder={f.ph || ''} />;
  }
  if (f.t === 'date') {
    return <input type="date" className="form-input mono" value={value || ''} onChange={e => onChange(e.target.value)} />;
  }
  if (f.t === 'select') {
    return (
      <select className="form-input" value={value || ''} onChange={e => onChange(e.target.value)}>
        <option value="">— Selecciona —</option>
        {f.opts.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    );
  }
  if (f.t === 'bool') {
    return (
      <button type="button" className={`form-toggle ${value ? 'on' : ''}`} onClick={() => onChange(!value)}>
        <span className="form-toggle-knob" />
        <span style={{ marginLeft: 8, fontSize: 12 }}>{value ? 'Activado' : 'Desactivado'}</span>
      </button>
    );
  }
  if (f.t === 'ref' && f.refType === 'PRV') return <ProveedorSelect f={f} value={value} onChange={onChange} />;
  if (f.t === 'ref') {
    const collMap = {
      USR: D.empleados, EQP: D.equipos, SRV: D.servidores, LIC: D.licencias, MBX: D.correos, PRV: D.proveedores, TEL: D.lineas, INF: D.infraestructura, DOM: D.dominios || [],
      EMP: (window.CFG ? window.CFG.get().asociadas : []),   // catálogo de Configuración, no un CI
      SIT: (window.CFG ? window.CFG.get().sitios : []),      // ídem: localizaciones
    };
    const coll = collMap[f.refType] || [];
    const labelOf = (item) => {
      if (f.refType === 'USR') return `${item.nombre} · ${item.area}`;
      if (f.refType === 'EQP') return `${item.modelo} · ${item.serie}`;
      if (f.refType === 'SRV') return `${item.nombre} · ${item.ip}`;
      if (f.refType === 'LIC') return item.producto;
      if (f.refType === 'MBX') return item.direccion;
      if (f.refType === 'PRV') return item.nombre;
      if (f.refType === 'EMP') return item.razon;
      if (f.refType === 'SIT') return item.nombre;
      if (f.refType === 'DOM') return item.dominio;
      if (f.refType === 'INF') return `${item.modelo}${item.serie ? ' · ' + item.serie : ''}`;
      return item.id;
    };
    return (
      <select className="form-input" value={value || ''} onChange={e => onChange(e.target.value)}>
        <option value="">{f.placeholder || '— Sin seleccionar —'}</option>
        {coll.map(item => <option key={item.id} value={item.id}>{item.id} · {labelOf(item)}</option>)}
      </select>
    );
  }
  return null;
}

// ===== Selector de proveedor con "dar de alta uno nuevo" sin salir del formulario =====
const NUEVO_PRV = '__nuevo_prv__';
function ProveedorSelect({ f, value, onChange }) {
  const D = window.CMDB_DATA;
  const [abierto, setAbierto] = useStateForm(false);
  return (
    <>
      <select className="form-input" value={value || ''} onChange={e => e.target.value === NUEVO_PRV ? setAbierto(true) : onChange(e.target.value)}>
        <option value="">{f.placeholder || '— Sin seleccionar —'}</option>
        {D.proveedores.map(p => <option key={p.id} value={p.id}>{p.id} · {p.nombre}</option>)}
        <option value={NUEVO_PRV}>＋ Dar de alta un proveedor nuevo…</option>
      </select>
      {abierto && <NuevoProveedorModal onClose={() => setAbierto(false)} onCreado={(id) => { setAbierto(false); onChange(id); }} />}
    </>
  );
}

// Alta rápida de proveedor: mismos campos que el alta normal; al guardar queda seleccionado en el formulario de origen
function NuevoProveedorModal({ onClose, onCreado }) {
  const schema = FORM_SCHEMAS.PRV;
  const [values, setValues] = useStateForm({ nombre: '', tipo: '', rfc: '', contacto: '', telefono: '', email: '' });
  const [errors, setErrors] = useStateForm({});
  const [busy, setBusy] = useStateForm(false);
  const cerrar = async () => { if (!busy && await confirmarDescarte(Object.values(values).some(v => String(v).trim()), 'Tienes datos del proveedor sin guardar. Si lo cierras, se pierden.')) onClose(); };
  const setField = (k, v) => { setValues(p => ({ ...p, [k]: v })); setErrors(p => { if (!p[k]) return p; const n = { ...p }; delete n[k]; return n; }); };

  const guardar = async () => {
    const e = {};
    schema.sections.forEach(sec => sec.fields.forEach(fl => { if (fl.required && !String(values[fl.k] || '').trim()) e[fl.k] = 'Requerido'; }));
    const nombre = values.nombre.trim();
    const dup = nombre && window.CMDB_DATA.proveedores.find(p => p.nombre.trim().toLowerCase() === nombre.toLowerCase());
    if (!e.nombre && dup) e.nombre = `Ya existe: ${dup.id} · ${dup.nombre}`;
    setErrors(e);
    if (Object.keys(e).length) return;
    setBusy(true);
    try {
      const r = await window.cmdbApiPost('proveedores', {
        nombre, tipo: values.tipo, rfc: values.rfc.trim() || null, contacto: values.contacto.trim() || null,
        telefono: values.telefono.trim() || null, email: values.email.trim() || null,
      });
      await window.CMDB_LOAD(); // para que el proveedor nuevo ya aparezca en las listas
      window.notify({ kind: 'ok', title: 'Proveedor creado', detail: `${r.id} · ${nombre}` });
      onCreado(r.id);
    } catch (err) {
      console.error(err);
      window.notifyError(err, 'No se pudo crear el proveedor');
      setBusy(false);
    }
  };

  return ReactDOM.createPortal(
    <>
      <div className="drawer-scrim" style={{ zIndex: 69 }} onClick={cerrar} />
      <div className="rsp-modal" style={{ width: 560, maxWidth: '94vw' }} role="dialog" aria-label="Nuevo proveedor">
        <header className="wiz-h">
          <div>
            <div className="mono wiz-kicker">Alta rápida</div>
            <h3>Nuevo proveedor</h3>
            <div className="wiz-sub">Al guardarlo queda seleccionado en el formulario que tenías abierto.</div>
          </div>
          <button className="btn ghost" onClick={cerrar} disabled={busy}><Icon name="x" /></button>
        </header>
        <div style={{ padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {schema.sections.map((sec, i) => (
            <FormSection key={i} title={sec.title}>
              {sec.fields.map(fl => <FormField key={fl.k} f={fl} value={values[fl.k]} onChange={v => setField(fl.k, v)} error={errors[fl.k]} />)}
            </FormSection>
          ))}
        </div>
        <footer className="wiz-f">
          <span className="mono wiz-pos">{Object.keys(errors).length > 0 ? <span style={{ color: 'var(--crit)' }}>Revisa los campos marcados</span> : ''}</span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn" onClick={cerrar} disabled={busy}>Cancelar</button>
            <button className="btn primary" onClick={guardar} disabled={busy}><Icon name="check" /> {busy ? 'Guardando…' : 'Crear proveedor'}</button>
          </div>
        </footer>
      </div>
    </>,
    document.body
  );
}

Object.assign(window, { CIFormDrawer, FORM_SCHEMAS, nextIdFor });
