function AdminZonas() {
  const [zones, setZones]       = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [error, setError]       = React.useState(null);
  const [newName, setNewName]   = React.useState('');
  const [adding, setAdding]     = React.useState(false);
  const [editId, setEditId]     = React.useState(null);
  const [editName, setEditName] = React.useState('');
  const [savingEdit, setSavingEdit] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [checkingDel, setCheckingDel] = React.useState(false);
  const [deletingZone, setDeletingZone] = React.useState(false);
  // confirmRename: { id, oldName, newName, prospeccionCount, edificiosCount, edificiosCACount, usersCount } | null
  const [confirmRename, setConfirmRename] = React.useState(null);
  const [checkingRename, setCheckingRename] = React.useState(false);
  const [dragIndex, setDragIndex]   = React.useState(null);
  const [dragOver, setDragOver]     = React.useState(null);

  const inp = { width: '100%', padding: '9px 12px', borderRadius: 9, fontSize: 13,
                border: '1px solid rgba(15,28,46,0.15)', background: '#fff', color: '#1a1a1a',
                fontFamily: "'Inter',sans-serif", outline: 'none', boxSizing: 'border-box' };

  async function cargar() {
    setLoading(true); setError(null);
    try {
      const res = await fetch('/api/zones', { headers: getATHeaders() });
      if (!res.ok) throw new Error((await res.json()).error || res.status);
      const d = await res.json();
      setZones(d.zones || []);
    } catch(e) { setError(e.message); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { cargar(); }, []);

  async function agregarZona() {
    if (!newName.trim()) return;
    setAdding(true);
    try {
      const res = await fetch('/api/admin/zones', {
        method: 'POST', headers: getATHeaders(),
        body: JSON.stringify({ name: newName.trim() }),
      });
      const d = await res.json();
      if (!res.ok) { toast(d.error || 'Error al añadir', 'error'); return; }
      setNewName('');
      invalidateZonasCache();
      cargar();
      toast('Zona creada', 'success');
    } catch(e) { toast(e.message, 'error'); }
    finally { setAdding(false); }
  }

  // Step 1: fetch affected-record count and open confirmation modal
  async function guardarEdicion(id) {
    if (!editName.trim()) return;
    const oldZone = zones.find(z => z.id === id);
    const oldName = oldZone ? oldZone.name : '';
    const newName = editName.trim();
    if (oldName === newName) { setEditId(null); return; }
    setCheckingRename(true);
    try {
      const res = await fetch(`/api/admin/zones/${id}/rename-preview`, { headers: getATHeaders() });
      const d = await res.json();
      if (!res.ok) { toast(d.error || 'Error al comprobar registros', 'error'); return; }
      setConfirmRename({ id, oldName: d.oldName, newName, prospeccionCount: d.prospeccionCount, edificiosCount: d.edificiosCount, propertiesCount: d.propertiesCount || 0, edificiosCACount: d.edificiosCACount || 0, usersCount: d.usersCount || 0 });
    } catch(e) { toast(e.message, 'error'); }
    finally { setCheckingRename(false); }
  }

  // Step 2: confirmed — actually commit the rename
  async function confirmarRename() {
    if (!confirmRename) return;
    setSavingEdit(true);
    try {
      const res = await fetch(`/api/admin/zones/${confirmRename.id}`, {
        method: 'PATCH', headers: getATHeaders(),
        body: JSON.stringify({ name: confirmRename.newName }),
      });
      const d = await res.json().catch(() => ({}));
      if (!res.ok) { toast(d.error || 'Error al renombrar', 'error'); return; }
      setConfirmRename(null);
      setEditId(null);
      invalidateZonasCache();
      cargar();
      const zonaTotal = (d.updatedProspeccion || 0) + (d.updatedEdificios || 0);
      const caTotal = d.updatedEdificiosCA || 0;
      const total = zonaTotal + caTotal;
      let renameMsg;
      if (total === 0) {
        renameMsg = 'Zona renombrada';
      } else if (zonaTotal > 0 && caTotal > 0) {
        renameMsg = 'Zona renombrada \xB7 ' + zonaTotal + ' Zona, ' + caTotal + ' Comercial_Asignado';
      } else if (caTotal > 0) {
        renameMsg = 'Zona renombrada \xB7 ' + caTotal + ' Comercial_Asignado';
      } else {
        renameMsg = 'Zona renombrada \xB7 ' + zonaTotal + ' registro' + (zonaTotal !== 1 ? 's' : '') + ' actualizado' + (zonaTotal !== 1 ? 's' : '');
      }
      toast(renameMsg, 'success');
    } catch(e) { toast(e.message, 'error'); }
    finally { setSavingEdit(false); }
  }

  // Step 1: fetch affected users + record counts, then open confirmation modal
  async function prepararEliminacion(z) {
    setCheckingDel(z.id);
    try {
      const res = await fetch(`/api/admin/zones/${z.id}/delete-preview`, { headers: getATHeaders() });
      // A proxy/database timeout can return an HTML/plain-text 503.  Do not
      // let its JSON parser error mask the actionable server status.
      const d = await res.json().catch(() => ({
        error: res.status === 503
          ? 'Servicio temporalmente no disponible. Inténtalo de nuevo.'
          : `No se pudo comprobar la zona (HTTP ${res.status})`,
      }));
      if (!res.ok) { toast(d.error || 'Error al comprobar', 'error'); return; }
      setConfirmDel({
        ...z,
        affectedUsers:       d.affectedUsers       || [],
        affectedProspeccion: d.affectedProspeccion || 0,
        affectedEdificios:   d.affectedEdificios   || 0,
        affectedProperties:  d.affectedProperties  || 0,
        edificiosCACount:    d.edificiosCACount    || 0,
        targetZone: 'Zona por determinar',
      });
    } catch(e) { toast(e.message, 'error'); }
    finally { setCheckingDel(false); }
  }

  async function eliminarZona(id) {
    if (deletingZone) return;
    setDeletingZone(true);
    try {
      const res = await fetch(`/api/admin/zones/${id}`, {
        method: 'DELETE', headers: getATHeaders(),
        body: JSON.stringify({ targetZone: confirmDel && confirmDel.targetZone ? confirmDel.targetZone : 'Zona por determinar' }),
      });
      const d = await res.json();
      if (!res.ok) { toast(d.error || 'Error al eliminar', 'error'); return; }
      setConfirmDel(null);
      invalidateZonasCache();
      cargar();
      const total = (d.updatedProspeccion || 0) + (d.updatedEdificios || 0);
      let msg = 'Zona eliminada';
      if (total > 0) msg += ` · ${total} registro${total !== 1 ? 's' : ''} reasignado${total !== 1 ? 's' : ''} a "${d.targetZone}"`;
      else if (d.updatedUsers > 0) msg += ` · ${d.updatedUsers} usuario${d.updatedUsers === 1 ? '' : 's'} actualizado${d.updatedUsers === 1 ? '' : 's'}`;
      toast(msg, 'success');
    } catch(e) { toast(e.message, 'error'); }
    finally { setDeletingZone(false); }
  }

  // Move a zone up (-1) or down (+1) in the ordered list
  async function moverZona(index, dir) {
    const targetIndex = index + dir;
    if (targetIndex < 0 || targetIndex >= zones.length) return;
    const a = zones[index];
    const b = zones[targetIndex];

    // Optimistic update: swap positions in local state immediately
    const newZones = zones.map(z => {
      if (z.id === a.id) return { ...z, position: b.position };
      if (z.id === b.id) return { ...z, position: a.position };
      return z;
    });
    newZones.sort((x, y) => x.position - y.position || x.id - y.id);
    setZones(newZones);

    try {
      // Patch both zones in parallel
      const [ra, rb] = await Promise.all([
        fetch(`/api/admin/zones/${a.id}`, {
          method: 'PATCH', headers: getATHeaders(),
          body: JSON.stringify({ position: b.position }),
        }),
        fetch(`/api/admin/zones/${b.id}`, {
          method: 'PATCH', headers: getATHeaders(),
          body: JSON.stringify({ position: a.position }),
        }),
      ]);
      if (!ra.ok || !rb.ok) {
        toast('Error al reordenar', 'error');
        cargar(); // reload to fix optimistic state
        return;
      }
      invalidateZonasCache();
    } catch(e) {
      toast(e.message, 'error');
      cargar();
    }
  }

  // ── Drag-and-drop handlers ──────────────────────────────
  function handleDragStart(e, index) {
    setDragIndex(index);
    e.dataTransfer.effectAllowed = 'move';
    // Minimal ghost: use the row itself (browser default)
  }

  function handleDragOver(e, index) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (dragOver !== index) setDragOver(index);
  }

  function handleDragLeave(e) {
    // Only clear if we've actually left the row (not entered a child)
    if (!e.currentTarget.contains(e.relatedTarget)) setDragOver(null);
  }

  function handleDrop(e, targetIndex) {
    e.preventDefault();
    const from = dragIndex;
    setDragIndex(null);
    setDragOver(null);
    if (from === null || from === targetIndex) return;

    // Reorder optimistically
    const reordered = [...zones];
    const [moved] = reordered.splice(from, 1);
    reordered.splice(targetIndex, 0, moved);
    // Assign sequential positions 0..n-1
    const withPos = reordered.map((z, i) => ({ ...z, position: i }));
    setZones(withPos);

    // Send the full ordered list in one atomic request so concurrent drags
    // cannot interleave and produce inconsistent positions in the database.
    fetch('/api/admin/zones/reorder', {
      method: 'POST', headers: getATHeaders(),
      body: JSON.stringify({ zones: withPos.map(z => ({ id: z.id, position: z.position })) }),
    }).then(r => {
      if (!r.ok) {
        toast('Error al reordenar', 'error');
        cargar();
      } else {
        invalidateZonasCache();
      }
    }).catch(err => {
      toast(err.message, 'error');
      cargar();
    });
  }

  function handleDragEnd() {
    setDragIndex(null);
    setDragOver(null);
  }

  return (
    <div className="admin-zonas-responsive">
      <style>{`
        .admin-zonas-responsive,.admin-zonas-responsive *{box-sizing:border-box}
        .admin-zonas-add-row{display:flex;gap:10px}
        .admin-zonas-table-wrap{max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-gutter:stable}
        .admin-zonas-table{width:100%;border-collapse:collapse;min-width:520px}
        .admin-zonas-table td:nth-child(2)>div,.admin-zonas-table td:nth-child(2) input{min-width:0}
        .admin-zonas-name{overflow-wrap:anywhere;word-break:break-word}
        .admin-zonas-modal{width:min(100%,calc(100vw - 24px))!important;max-height:calc(100dvh - 24px);overflow-y:auto;overflow-x:hidden}
        .admin-zonas-modal li,.admin-zonas-modal p{overflow-wrap:anywhere}
        @media(max-width:560px){
          .admin-zonas-add-row{flex-direction:column}
          .admin-zonas-add-row>button{width:100%;min-height:44px}
          .admin-zonas-table{min-width:400px}
          .admin-zonas-table td:nth-child(2)>div{flex-wrap:wrap}
          .admin-zonas-table td:nth-child(2) input{flex:1 1 100%!important}
          .admin-zonas-table td:nth-child(2) button{min-height:44px}
          .admin-zonas-modal{padding:20px!important;border-radius:13px!important}
          .admin-zonas-modal-actions{display:grid!important;grid-template-columns:1fr!important}
          .admin-zonas-modal-actions button{width:100%;min-height:44px}
          .admin-zonas-rename-flow{display:flex;flex-direction:column;gap:4px;overflow-wrap:anywhere}
          .admin-zonas-rename-flow span{margin:0!important}
        }
      `}</style>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ fontSize: 20, fontWeight: 700, color: 'var(--navy)', margin: 0 }}>Zonas comerciales</h2>
        <p style={{ fontSize: 13, color: '#6b7280', margin: '4px 0 0' }}>
          Define las zonas que aparecen en el selector de usuarios y en los filtros de prospección.
          Al renombrar una zona se actualizan automáticamente los registros de prospección y edificios que la referencian.
        </p>
      </div>

      {error && <div style={{ background: 'rgba(220,38,38,0.07)', border: '1px solid rgba(220,38,38,0.2)', color: '#b91c1c', borderRadius: 10, padding: '10px 16px', marginBottom: 16, fontSize: 13 }}>{error}</div>}

      {/* Add new zone */}
      <div style={{ background: '#fff', borderRadius: 12, border: '1px solid rgba(15,28,46,0.08)', padding: '16px 20px', marginBottom: 20 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Nueva zona</div>
        <div className="admin-zonas-add-row">
          <input style={{ ...inp, flex: 1 }} value={newName} onChange={e => setNewName(e.target.value)}
            placeholder="ej: Zona 3 — Norte"
            onKeyDown={e => e.key === 'Enter' && agregarZona()} />
          <button onClick={agregarZona} disabled={adding || !newName.trim()}
            style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: 'var(--navy)', color: '#fff',
                     fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Inter',sans-serif",
                     opacity: (adding || !newName.trim()) ? 0.5 : 1, whiteSpace: 'nowrap' }}>
            {adding ? 'Añadiendo…' : '+ Añadir zona'}
          </button>
        </div>
      </div>

      {/* Zone list */}
      <div className="admin-zonas-table-wrap" style={{ background: '#fff', borderRadius: 14, border: '1px solid rgba(15,28,46,0.08)' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94a3b8', fontSize: 14 }}>Cargando zonas…</div>
        ) : zones.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94a3b8', fontSize: 14 }}>No hay zonas definidas.</div>
        ) : (
          <table className="admin-zonas-table">
            <thead>
              <tr style={{ borderBottom: '1px solid rgba(15,28,46,0.08)', background: 'rgba(245,240,232,0.5)' }}>
                <th style={{ width: 36, padding: '11px 0 11px 14px' }} />
                {['Nombre de zona', ''].map(h => (
                  <th key={h} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {zones.map((z, i) => (
                <tr key={z.id}
                  draggable={editId !== z.id}
                  onDragStart={editId !== z.id ? e => handleDragStart(e, i) : undefined}
                  onDragOver={editId !== z.id ? e => handleDragOver(e, i) : undefined}
                  onDragLeave={editId !== z.id ? handleDragLeave : undefined}
                  onDrop={editId !== z.id ? e => handleDrop(e, i) : undefined}
                  onDragEnd={handleDragEnd}
                  style={{
                    borderBottom: i < zones.length - 1 ? '1px solid rgba(15,28,46,0.06)' : 'none',
                    background: dragOver === i && dragIndex !== i
                      ? 'rgba(201,169,110,0.12)'
                      : dragIndex === i
                        ? 'rgba(201,169,110,0.07)'
                        : '',
                    opacity: dragIndex === i ? 0.55 : 1,
                    transition: 'background 0.12s, opacity 0.12s',
                    outline: dragOver === i && dragIndex !== i ? '2px solid rgba(201,169,110,0.55)' : 'none',
                    outlineOffset: -2,
                  }}
                  onMouseEnter={e => { if (dragIndex === null) e.currentTarget.style.background = 'rgba(245,240,232,0.4)'; }}
                  onMouseLeave={e => { if (dragIndex === null) e.currentTarget.style.background = ''; }}>
                  {/* Drag handle */}
                  <td style={{ padding: '0 0 0 14px', width: 36, cursor: editId === z.id ? 'default' : 'grab', color: '#c9a96e', fontSize: 16, userSelect: 'none', verticalAlign: 'middle' }}
                    title={editId === z.id ? '' : 'Arrastrar para reordenar'}>
                    {editId !== z.id && '≡'}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: 14 }}>
                    {editId === z.id ? (
                      <div style={{ display: 'flex', gap: 8 }}>
                        <input style={{ ...inp, flex: 1 }} value={editName}
                          onChange={e => setEditName(e.target.value)}
                          onKeyDown={e => { if (e.key === 'Enter') guardarEdicion(z.id); if (e.key === 'Escape') setEditId(null); }}
                          autoFocus />
                        <button onClick={() => guardarEdicion(z.id)} disabled={savingEdit || checkingRename}
                          style={{ padding: '7px 14px', borderRadius: 8, border: 'none', background: 'var(--navy)', color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: "'Inter',sans-serif",
                                   opacity: (savingEdit || checkingRename) ? 0.6 : 1 }}>
                          {checkingRename ? '…' : 'Guardar'}
                        </button>
                        <button onClick={() => setEditId(null)}
                          style={{ padding: '7px 10px', borderRadius: 8, border: '1px solid rgba(15,28,46,0.15)', background: '#fff', fontSize: 12, cursor: 'pointer', fontFamily: "'Inter',sans-serif" }}>
                          ✕
                        </button>
                      </div>
                    ) : (
                      <span className="admin-zonas-name" style={{ fontWeight: 500, color: 'var(--navy)' }}>{z.name}</span>
                    )}
                  </td>
                  <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                    {editId !== z.id && (
                      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', alignItems: 'center' }}>
                        <button onClick={() => moverZona(i, -1)} disabled={i === 0}
                          className="row-action-btn" title="Subir"
                          style={{ opacity: i === 0 ? 0.3 : 1, fontSize: 12 }}>▲</button>
                        <button onClick={() => moverZona(i, 1)} disabled={i === zones.length - 1}
                          className="row-action-btn" title="Bajar"
                          style={{ opacity: i === zones.length - 1 ? 0.3 : 1, fontSize: 12 }}>▼</button>
                        <div style={{ width: 1, height: 18, background: 'rgba(15,28,46,0.1)', margin: '0 2px' }} />
                        <button onClick={() => { setEditId(z.id); setEditName(z.name); }} className="row-action-btn" title="Renombrar">✏️</button>
                        <button onClick={() => prepararEliminacion(z)} disabled={checkingDel === z.id}
                          className="row-action-btn" title="Eliminar"
                          style={{ opacity: checkingDel === z.id ? 0.5 : 1 }}>
                          {checkingDel === z.id ? '…' : '🗑'}
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Delete confirmation modal */}
      {confirmDel && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,28,46,0.55)', zIndex: 1001,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div className="modal-spring admin-zonas-modal" style={{ background: '#fff', borderRadius: 16, padding: 28, maxWidth: 460, width: '100%' }}>
            <h3 style={{ fontSize: 15, fontWeight: 700, color: '#111', margin: '0 0 10px' }}>¿Eliminar zona?</h3>
            <p style={{ fontSize: 13, color: '#6b7280', margin: '0 0 12px' }}>
              Se eliminará <strong>{confirmDel.name}</strong> de la lista de zonas.
            </p>

            {/* Affected records warning */}
            {(confirmDel.affectedProspeccion > 0 || confirmDel.affectedEdificios > 0 || confirmDel.affectedProperties > 0 || confirmDel.edificiosCACount > 0) && (
              <div style={{ background: 'rgba(245,158,11,0.07)', border: '1px solid rgba(245,158,11,0.28)', borderRadius: 10, padding: '12px 14px', marginBottom: 14 }}>
                <p style={{ fontSize: 12, fontWeight: 700, color: '#92400e', margin: '0 0 6px' }}>
                  ⚠ Registros que perderían su zona:
                </p>
                {confirmDel.affectedProspeccion > 0 && (
                  <p style={{ fontSize: 12, color: '#78350f', margin: '0 0 2px' }}>
                    · {confirmDel.affectedProspeccion} registro{confirmDel.affectedProspeccion !== 1 ? 's' : ''} de prospección
                  </p>
                )}
                {confirmDel.affectedEdificios > 0 && (
                  <p style={{ fontSize: 12, color: '#78350f', margin: '0 0 2px' }}>
                    · {confirmDel.affectedEdificios} edificio{confirmDel.affectedEdificios !== 1 ? 's' : ''} (campo Zona)
                  </p>
                )}
                {confirmDel.affectedProperties > 0 && (
                  <p style={{ fontSize: 12, color: '#78350f', margin: '0 0 2px' }}>
                    · {confirmDel.affectedProperties} inmueble{confirmDel.affectedProperties !== 1 ? 's' : ''} (Zona_ID)
                  </p>
                )}
                {confirmDel.edificiosCACount > 0 && (
                  <p style={{ fontSize: 12, color: '#78350f', margin: 0 }}>
                    · {confirmDel.edificiosCACount} edificio{confirmDel.edificiosCACount !== 1 ? 's' : ''} (campo Comercial_Asignado)
                  </p>
                )}
                <p style={{ fontSize: 11, color: '#92400e', margin: '10px 0 4px', fontWeight: 600 }}>
                  Reasignar a:
                </p>
                <input
                  type="text"
                  value={confirmDel.targetZone}
                  onChange={e => setConfirmDel(prev => ({ ...prev, targetZone: e.target.value }))}
                  style={{ width: '100%', padding: '7px 11px', borderRadius: 8, border: '1px solid rgba(15,28,46,0.2)', fontSize: 13, fontFamily: "'Inter',sans-serif", outline: 'none' }}
                  placeholder="Zona por determinar"
                />
                <p style={{ fontSize: 11, color: '#9ca3af', margin: '5px 0 0' }}>
                  Deja el campo con "Zona por determinar" para que estos registros queden visibles en la pestaña Revisar.
                </p>
              </div>
            )}

            {/* Affected users warning */}
            {confirmDel.affectedUsers && confirmDel.affectedUsers.length > 0 && (
              <div style={{ background: 'rgba(220,38,38,0.06)', border: '1px solid rgba(220,38,38,0.18)', borderRadius: 10, padding: '12px 14px', marginBottom: 16 }}>
                <p style={{ fontSize: 12, fontWeight: 700, color: '#b91c1c', margin: '0 0 8px' }}>
                  ⚠ {confirmDel.affectedUsers.length} usuario{confirmDel.affectedUsers.length !== 1 ? 's' : ''} tiene{confirmDel.affectedUsers.length !== 1 ? 'n' : ''} esta zona asignada:
                </p>
                <ul style={{ margin: 0, padding: '0 0 0 16px', fontSize: 12, color: '#7f1d1d', lineHeight: 1.7 }}>
                  {confirmDel.affectedUsers.map(u => (
                    <li key={u.username}><strong>{u.nombre}</strong> <span style={{ color: '#9ca3af' }}>({u.username})</span></li>
                  ))}
                </ul>
                <p style={{ fontSize: 11, color: '#b45309', margin: '8px 0 0' }}>
                  La zona quedará eliminada de la lista asignada a estos usuarios.
                </p>
              </div>
            )}

            {confirmDel.affectedProspeccion === 0 && confirmDel.affectedEdificios === 0 && confirmDel.affectedProperties === 0 && confirmDel.edificiosCACount === 0 && (!confirmDel.affectedUsers || confirmDel.affectedUsers.length === 0) && (
              <p style={{ fontSize: 12, color: '#6b7280', margin: '0 0 16px' }}>
                No hay registros de prospección, edificios ni usuarios con esta zona.
              </p>
            )}

            <div className="admin-zonas-modal-actions" style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
              <button onClick={() => setConfirmDel(null)}
                style={{ padding: '9px 16px', borderRadius: 9, border: '1px solid rgba(15,28,46,0.15)', background: '#fff', fontSize: 13, cursor: 'pointer', fontFamily: "'Inter',sans-serif" }}>
                Cancelar
              </button>
              <button onClick={() => eliminarZona(confirmDel.id)}
                disabled={deletingZone}
                style={{ padding: '9px 16px', borderRadius: 9, border: 'none', background: deletingZone ? '#f87171' : '#dc2626', color: '#fff', fontSize: 13, fontWeight: 700, cursor: deletingZone ? 'not-allowed' : 'pointer', fontFamily: "'Inter',sans-serif", opacity: deletingZone ? 0.7 : 1 }}>
                {deletingZone ? 'Eliminando…' : 'Eliminar zona'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Rename confirmation modal */}
      {confirmRename && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,28,46,0.55)', zIndex: 1001,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div className="modal-spring admin-zonas-modal" style={{ background: '#fff', borderRadius: 16, padding: 28, maxWidth: 420, width: '100%' }}>
            <h3 style={{ fontSize: 15, fontWeight: 700, color: '#111', margin: '0 0 12px' }}>¿Confirmar cambio de nombre?</h3>
            <p className="admin-zonas-rename-flow" style={{ fontSize: 13, color: '#374151', margin: '0 0 14px' }}>
              <strong>{confirmRename.oldName}</strong>
              <span style={{ margin: '0 8px', color: '#9ca3af' }}>→</span>
              <strong>{confirmRename.newName}</strong>
            </p>
            {(confirmRename.prospeccionCount > 0 || confirmRename.edificiosCount > 0 || confirmRename.propertiesCount > 0 || confirmRename.edificiosCACount > 0 || confirmRename.usersCount > 0) ? (
              <div style={{ background: 'rgba(201,169,110,0.08)', border: '1px solid rgba(201,169,110,0.3)',
                            borderRadius: 10, padding: '10px 14px', marginBottom: 20 }}>
                <p style={{ fontSize: 13, color: '#92650a', margin: '0 0 4px', fontWeight: 600 }}>
                  ⚠ Se actualizarán automáticamente:
                </p>
                {confirmRename.prospeccionCount > 0 && (
                  <p style={{ fontSize: 12, color: '#92650a', margin: '2px 0 0' }}>
                    · {confirmRename.prospeccionCount} registro{confirmRename.prospeccionCount !== 1 ? 's' : ''} de prospección
                  </p>
                )}
                {confirmRename.edificiosCount > 0 && (
                  <p style={{ fontSize: 12, color: '#92650a', margin: '2px 0 0' }}>
                    · {confirmRename.edificiosCount} edificio{confirmRename.edificiosCount !== 1 ? 's' : ''} (campo Zona)
                  </p>
                )}
                {confirmRename.propertiesCount > 0 && (
                  <p style={{ fontSize: 12, color: '#92650a', margin: '2px 0 0' }}>
                    · {confirmRename.propertiesCount} inmueble{confirmRename.propertiesCount !== 1 ? 's' : ''} (Zona_ID)
                  </p>
                )}
                {confirmRename.edificiosCACount > 0 && (
                  <p style={{ fontSize: 12, color: '#92650a', margin: '2px 0 0' }}>
                    · {confirmRename.edificiosCACount} edificio{confirmRename.edificiosCACount !== 1 ? 's' : ''} (campo Comercial_Asignado)
                  </p>
                )}
                {confirmRename.usersCount > 0 && (
                  <p style={{ fontSize: 12, color: '#92650a', margin: '2px 0 0' }}>
                    · {confirmRename.usersCount} usuario{confirmRename.usersCount !== 1 ? 's' : ''} con esta zona asignada
                  </p>
                )}
              </div>
            ) : (
              <p style={{ fontSize: 13, color: '#6b7280', marginBottom: 20 }}>
                No hay registros de prospección, edificios ni usuarios con esta zona.
              </p>
            )}
            <div className="admin-zonas-modal-actions" style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button onClick={() => setConfirmRename(null)} disabled={savingEdit}
                style={{ padding: '9px 16px', borderRadius: 9, border: '1px solid rgba(15,28,46,0.15)', background: '#fff', fontSize: 13, cursor: 'pointer', fontFamily: "'Inter',sans-serif" }}>
                Cancelar
              </button>
              <button onClick={confirmarRename} disabled={savingEdit}
                style={{ padding: '9px 16px', borderRadius: 9, border: 'none', background: 'var(--navy)', color: '#fff',
                         fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: "'Inter',sans-serif",
                         opacity: savingEdit ? 0.6 : 1 }}>
                {savingEdit ? 'Guardando…' : 'Confirmar cambio'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
