// ─── Sistema de notificaciones (asignación de rutas) ─────────────────────
// Modelo de aviso:
//   Notif {
//     id,
//     tipo: 'asignacion'      → admin asignó una ruta al mensajero
//         | 'rechazo'         → el mensajero rechazó una ruta (le llega al admin)
//         | 'autoasignacion'  → el mensajero se autoasignó una ruta (le llega al admin)
//     para: 'mensajero' | 'admin',   // a quién le aparece
//     estado: 'pendiente' | 'resuelta',
//     resolucion: 'aceptada' | 'rechazada' | 'revisada' | 'vista' | null,
//     taller, sede, accion ('recoger'|'entregar'|'otro'), referencia, paradaId,
//     actor: 'admin' | 'juan-diego',
//     motivo,                         // texto libre (solo rechazo)
//     createdAt, resolvedAt,
//   }
// El contador de la campana = avisos PENDIENTES dirigidos al rol activo.
// El contador baja cuando el aviso se RESUELVE (aceptar/rechazar/revisar), no
// con solo abrir la ventana.

const LS_NOTIF_KEY = 'rodando.notificaciones';

function loadNotifs() {
  try { return JSON.parse(localStorage.getItem(LS_NOTIF_KEY) || '[]'); }
  catch { return []; }
}
function saveNotifs(list) {
  localStorage.setItem(LS_NOTIF_KEY, JSON.stringify(list));
  // Avisar a otras vistas (campana, tablero) en la misma pestaña
  window.dispatchEvent(new Event('rodando-notifs'));
}
function addNotif(n) {
  const list = loadNotifs();
  list.unshift(n);
  saveNotifs(list);
  return n;
}
// Agrega un aviso, pero si ya existe uno SIN RESOLVER con la misma coalesceKey,
// lo actualiza en vez de apilar otro: sube el contador, refresca la hora y
// guarda un pequeño historial de los cambios. Evita la "lluvia" de avisos.
function addOrCoalesceNotif(n, coalesceKey) {
  if (!coalesceKey) return addNotif(n);
  const list = loadNotifs();
  const now = n.createdAt || Date.now();
  const entry = { ts: now, titulo: n.titulo, mensaje: n.mensaje, detalle: n.detalle, kind: n.kind };
  const idx = list.findIndex(x => x.estado === 'pendiente' && x.coalesceKey === coalesceKey && x.para === n.para && (x.paraUsuario || null) === (n.paraUsuario || null));
  if (idx !== -1) {
    const prev = list[idx];
    const prevHist = prev.history || [{ ts: prev.createdAt, titulo: prev.titulo, mensaje: prev.mensaje, detalle: prev.detalle, kind: prev.kind }];
    // Fusionar líneas idénticas: si el cambio es exactamente el mismo que el último, solo refresca su hora.
    const sameAsLast = prevHist[0] && entry.detalle && prevHist[0].detalle === entry.detalle;
    const history = sameAsLast
      ? [{ ...prevHist[0], ts: now }, ...prevHist.slice(1)]
      : [entry, ...prevHist].slice(0, 8);
    const merged = { ...prev, ...n, id: prev.id, coalesceKey, count: (prev.count || 1) + 1, history, createdAt: now };
    list.splice(idx, 1);
    list.unshift(merged);
    saveNotifs(list);
    return merged;
  }
  const fresh = { ...n, coalesceKey, count: 1, history: [entry] };
  list.unshift(fresh);
  saveNotifs(list);
  return fresh;
}
function updateNotif(id, patch) {
  const list = loadNotifs();
  const idx = list.findIndex(n => n.id === id);
  if (idx === -1) return false;
  list[idx] = { ...list[idx], ...patch };
  saveNotifs(list);
  return list[idx];
}
function clearNotifs() {
  localStorage.removeItem(LS_NOTIF_KEY);
  try { sessionStorage.removeItem('rodando.toasted'); } catch {}
  window.dispatchEvent(new Event('rodando-notifs'));
}
// Por usuario (13/11/2026): un aviso con paraUsuario solo le aparece a ese mensajero.
// Los que no lo traen (viejos) le aparecen a todos los mensajeros.
function notifsFor(role) {
  const para = role === 'admin' ? 'admin' : 'mensajero';
  const yo = ((window.usuarioActual && window.usuarioActual()) || {}).usuario;
  return loadNotifs().filter(n => n.para === para && (para === 'admin' || !n.paraUsuario || n.paraUsuario === yo));
}
function unreadCountFor(role) {
  return notifsFor(role).filter(n => n.estado === 'pendiente').length;
}

// Seed demo (simula el grupo de WhatsApp donde hoy llegan las paradas)
function seedDemoNotifsIfEmpty() {
  if (localStorage.getItem(LS_NOTIF_KEY) !== null || localStorage.getItem('rodando.sinDemo') === '1') return;
  const now = Date.now();
  saveNotifs([
    { id: 'n-seed-1', tipo: 'asignacion', para: 'mensajero', estado: 'pendiente',
      taller: 'Arautos', sede: 'Sur', accion: 'recoger',
      referencia: '4 rines y llantas', paradaId: 'p-seed-1', actor: 'admin',
      createdAt: now - 6 * 60000, resolucion: null },
    { id: 'n-seed-2', tipo: 'asignacion', para: 'mensajero', estado: 'pendiente',
      taller: 'Renovautos', sede: 'Sur', accion: 'entregar',
      referencia: '6022', paradaId: 'p-seed-2', actor: 'admin',
      createdAt: now - 24 * 60000, resolucion: null },
    { id: 'n-seed-3', tipo: 'autoasignacion', para: 'admin', estado: 'pendiente',
      taller: 'Almotores', sede: 'Kia', accion: 'recoger',
      referencia: '2 llantas', paradaId: 'p-seed-3', actor: 'juan-diego',
      createdAt: now - 12 * 60000, resolucion: null },
  ]);
}

// ── Hook: avisos del rol + contador, reactivo a cambios ──────────────────
function useNotifs(role) {
  const [list, setList] = React.useState(() => notifsFor(role));
  React.useEffect(() => {
    const refresh = () => setList(notifsFor(role));
    refresh();
    window.addEventListener('rodando-notifs', refresh);
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    return () => {
      window.removeEventListener('rodando-notifs', refresh);
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
    };
  }, [role]);
  return list;
}

// ── Helpers de presentación ──────────────────────────────────────────────
function accionLabel(a) {
  return a === 'recoger' ? 'Recoger' : a === 'entregar' ? 'Entregar' : 'Otro';
}
function accionColor(a) {
  return a === 'recoger' ? TOKENS.primary : a === 'entregar' ? TOKENS.success : TOKENS.otro;
}
function accionIcon(a, s, c) {
  return (a === 'entregar' ? I.truck : a === 'recoger' ? I.recoger : I.route)(s, c);
}
function relTime(ts) {
  const diff = Date.now() - (ts || 0);
  const min = Math.round(diff / 60000);
  if (min < 1) return 'ahora';
  if (min < 60) return `hace ${min} min`;
  const h = Math.round(min / 60);
  if (h < 24) return `hace ${h} h`;
  const d = Math.round(h / 24);
  return `hace ${d} d`;
}

// ── Acciones (compartidas por pantalla y toast) ──────────────────────────
function acceptNotif(n) {
  updateNotif(n.id, { estado: 'resuelta', resolucion: 'aceptada', resolvedAt: Date.now() });
  // La parada ya existe como pendiente en la ruta del día: queda aceptada.
}
function rejectNotif(n, motivo) {
  updateNotif(n.id, { estado: 'resuelta', resolucion: 'rechazada', motivo, resolvedAt: Date.now() });
  if (n.paradaId && window.updateParada) window.updateParada(n.paradaId, { estado: 'cancelada' });
  // Le llega al admin como aviso informativo
  addNotif({
    id: 'n-' + Date.now(), tipo: 'rechazo', para: 'admin', estado: 'pendiente',
    taller: n.taller, sede: n.sede, accion: n.accion, referencia: n.referencia,
    paradaId: n.paradaId, actor: ((window.usuarioActual && window.usuarioActual()) || {}).usuario || 'mensajero', motivo, createdAt: Date.now(), resolucion: null,
  });
}
function reviewNotif(n) {
  updateNotif(n.id, { estado: 'resuelta', resolucion: 'revisada', resolvedAt: Date.now() });
}
function acknowledgeNotif(n) {
  updateNotif(n.id, { estado: 'resuelta', resolucion: 'vista', resolvedAt: Date.now() });
}

// Aviso al admin cuando se anula un registro (incluye en campo por el mensajero)
function notifyAnulacion(ticket, { motivo, por }) {
  return addNotif({
    id: 'n-anu-' + Date.now(),
    tipo: 'anulacion', para: 'admin', estado: 'pendiente',
    taller: ticket.taller, sede: ticket.sede, accion: 'otro',
    referencia: `${ticket.codigo} · ${ticket.placa}`,
    motivo: motivo || '', actor: por || ((window.usuarioActual && window.usuarioActual()) || {}).usuario || 'admin',
    createdAt: Date.now(), resolucion: null,
  });
}

Object.assign(window, {
  loadNotifs, saveNotifs, addNotif, addOrCoalesceNotif, updateNotif, clearNotifs,
  notifsFor, unreadCountFor, seedDemoNotifsIfEmpty, useNotifs,
  accionLabel, accionColor, accionIcon, relTime,
  acceptNotif, rejectNotif, reviewNotif, acknowledgeNotif, notifyAnulacion,
});
