/* notifications.jsx — Sistema de notificaciones ASSYST */
const { useState: useStateNB, useEffect: useEffectNB, useRef: useRefNB } = React;

var NOTIF_KEY = 'sst_notifs_v2';



/* ── Iconos por tipo ───────────────────────────────────── */
var NOTIF_ICONS = {
  forum_comment:    '💬',
  course_complete:  '🏆',
  new_student:      '👤',
  profile_complete: '✅',
  new_announcement: '📢',
  instructor_reply: '💬',
  support_request:  '🎫',
  support_resolved: '✅',
};

/* ── Tiempo relativo ───────────────────────────────────── */
function timeAgo(ts) {
  var diff = Math.max(0, Date.now() - ts);
  var sec  = Math.floor(diff / 1000);
  if (sec < 90)    return 'hace un momento';
  var min  = Math.floor(sec / 60);
  if (min < 60)    return 'hace ' + min + ' min';
  var hr   = Math.floor(min / 60);
  if (hr < 24)     return 'hace ' + hr + (hr === 1 ? ' hora' : ' horas');
  var days = Math.floor(hr / 24);
  if (days === 1)  return 'ayer';
  return 'hace ' + days + ' días';
}

/* ── Persistencia ──────────────────────────────────────── */
function loadNotifs(role) {
  try {
    var s = localStorage.getItem(NOTIF_KEY + '_' + role);
    if (s) {
      var p = JSON.parse(s);
      if (Array.isArray(p)) return p;
    }
  } catch (e) {}
  return [];
}

function saveNotifs(role, list) {
  try { localStorage.setItem(NOTIF_KEY + '_' + role, JSON.stringify(list)); } catch (e) {}
  if (typeof window.sbSave === 'function') window.sbSave(NOTIF_KEY + '_' + role, list);
}

/* ── BellIcon SVG ──────────────────────────────────────── */
function BellSVG({ color }) {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none"
      stroke={color} strokeWidth="2.1" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
      <path d="M13.73 21a2 2 0 0 1-3.46 0" />
    </svg>
  );
}

/* ── Componente principal ──────────────────────────────── */
function NotificationBell({ role, darkBg, openRight }) {
  var _n   = useStateNB(function () { return loadNotifs(role); });
  var notifs = _n[0]; var setNotifs = _n[1];
  var _o   = useStateNB(false);
  var open = _o[0]; var setOpen = _o[1];
  var panelRef = useRefNB(null);

  var unread = notifs.filter(function (n) { return !n.read; }).length;

  /* Cerrar al hacer clic fuera */
  useEffectNB(function () {
    if (!open) return;
    function handler(e) {
      if (panelRef.current && !panelRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', handler);
    return function () { document.removeEventListener('mousedown', handler); };
  }, [open]);

  function mark(id) {
    setNotifs(function (prev) {
      var next = prev.map(function (n) {
        return n.id === id ? Object.assign({}, n, { read: true }) : n;
      });
      saveNotifs(role, next);
      return next;
    });
  }

  function markAll() {
    /* Primero marcar todas como leídas visualmente, luego limpiar */
    setNotifs(function (prev) {
      var allRead = prev.map(function (n) { return Object.assign({}, n, { read: true }); });
      saveNotifs(role, allRead);
      return allRead;
    });
    /* Desaparecer después de 450 ms para que el usuario vea el cambio */
    setTimeout(function () {
      setNotifs([]);
      saveNotifs(role, []);
    }, 450);
  }

  function clearOne(id) {
    setNotifs(function (prev) {
      var next = prev.filter(function (n) { return n.id !== id; });
      saveNotifs(role, next);
      return next;
    });
  }

  /* Refrescar cuando otra parte de la app empuje una notificación */
  useEffectNB(function () {
    function onNewNotif(e) {
      if (e.detail && e.detail.role === role) {
        setNotifs(loadNotifs(role));
      }
    }
    window.addEventListener('sst_notif_added', onNewNotif);
    return function () { window.removeEventListener('sst_notif_added', onNewNotif); };
  }, []);

  /* Colores adaptativos según fondo */
  var bellColor  = darkBg ? 'rgba(255,255,255,.88)' : '#1c79b4';
  var btnBg      = darkBg ? 'rgba(255,255,255,.1)'  : 'transparent';
  var btnHoverBg = darkBg ? 'rgba(255,255,255,.2)'  : '#eef2f7';
  var badgeBorder= darkBg ? '#1c79b4'               : 'white';

  return (
    <div ref={panelRef} style={{ position: 'relative' }}>

      {/* ── Botón campana ── */}
      <button
        onClick={function () { setOpen(function (v) { return !v; }); }}
        title="Notificaciones"
        aria-label="Notificaciones"
        style={{
          position: 'relative',
          background: open ? btnHoverBg : btnBg,
          border: 'none',
          borderRadius: 8,
          width: 36,
          height: 36,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
          transition: 'background .15s',
          flexShrink: 0,
        }}
        onMouseOver={function (e) { e.currentTarget.style.background = btnHoverBg; }}
        onMouseOut={function (e) { e.currentTarget.style.background = open ? btnHoverBg : btnBg; }}
      >
        <BellSVG color={bellColor} />

        {/* Badge de no leídas */}
        {unread > 0 && (
          <span style={{
            position: 'absolute', top: 5, right: 5,
            minWidth: 15, height: 15, padding: '0 3px',
            background: '#ef4444',
            borderRadius: 8,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 9, fontWeight: 800, color: 'white',
            fontFamily: "'Montserrat', sans-serif",
            border: '1.5px solid ' + badgeBorder,
            lineHeight: 1, boxSizing: 'border-box',
            letterSpacing: '-0.02em',
          }}>
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {/* ── Panel desplegable ── */}
      {open && (
        <div className={openRight ? 'sst-notif-panel-mobile' : ''} style={{
          position: openRight ? 'fixed' : 'absolute',
          top: openRight ? 60 : 'calc(100% + 10px)',
          right: openRight ? 'auto' : 0,
          left: openRight ? 270 : 'auto',
          width: 348,
          maxHeight: 'calc(100vh - 80px)',
          overflowY: 'auto',
          background: 'white',
          borderRadius: 14,
          boxShadow: '0 20px 56px rgba(15,32,68,.18), 0 4px 16px rgba(0,0,0,.08)',
          border: '1px solid #e5e7eb',
          zIndex: openRight ? 9999 : 700,
          fontFamily: "'Montserrat', sans-serif",
        }}>

          {/* Cabecera del panel */}
          <div style={{
            padding: '12px 16px',
            background: '#f8fafc',
            borderBottom: '1px solid #f1f5f9',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <BellSVG color="#1c79b4" />
              <span style={{ fontSize: 13, fontWeight: 700, color: '#0F2044' }}>
                Notificaciones
              </span>
              {unread > 0 && (
                <span style={{
                  background: '#1c79b4', color: 'white',
                  borderRadius: 10, padding: '2px 7px',
                  fontSize: 10, fontWeight: 700,
                }}>
                  {unread}
                </span>
              )}
            </div>
            {unread > 0 && (
              <button
                onClick={markAll}
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  fontSize: 10.5, color: '#c4b400', fontWeight: 700,
                  fontFamily: 'inherit', padding: '4px 8px',
                  borderRadius: 6, transition: 'background .12s',
                }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#fefce8'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = 'none'; }}
              >
                Marcar todo leído
              </button>
            )}
          </div>

          {/* Lista */}
          <div style={{ maxHeight: 370, overflowY: 'auto' }}>
            {notifs.length === 0 && (
              <div style={{
                padding: '40px 18px', textAlign: 'center',
                color: '#9ca3af', fontSize: 13,
              }}>
                <div style={{ fontSize: 28, marginBottom: 8, opacity: .4 }}>🔔</div>
                No tienes notificaciones nuevas
              </div>
            )}

            {notifs.map(function (n, i) {
              return (
                <div
                  key={n.id}
                  onClick={function () { mark(n.id); }}
                  style={{
                    display: 'flex', alignItems: 'flex-start', gap: 11,
                    padding: '12px 16px',
                    background: n.read ? 'white' : '#eff6ff',
                    borderBottom: i < notifs.length - 1 ? '1px solid #f1f5f9' : 'none',
                    cursor: 'pointer', transition: 'background .12s',
                  }}
                  onMouseOver={function (e) {
                    e.currentTarget.style.background = n.read ? '#f8fafc' : '#dbeafe';
                  }}
                  onMouseOut={function (e) {
                    e.currentTarget.style.background = n.read ? 'white' : '#eff6ff';
                  }}
                >
                  {/* Ícono tipo o avatar de estudiante */}
                  {n.studentId
                    ? <StudentAvatar userId={n.studentId} userName={n.studentName || ''} size={36} style={{ borderRadius: 10, border: '1.5px solid #e5e7eb' }} />
                    : <div style={{ width: 36, height: 36, flexShrink: 0, borderRadius: 10, background: n.read ? '#f1f5f9' : 'rgba(28,121,180,.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15 }}>{NOTIF_ICONS[n.type] || '🔔'}</div>
                  }

                  {/* Texto */}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 12, lineHeight: 1.55,
                      color: n.read ? '#6b7280' : '#0F2044',
                      fontWeight: n.read ? 400 : 600,
                      marginBottom: 4,
                      textWrap: 'pretty',
                    }}>
                      {n.text}
                    </div>
                    <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 500 }}>
                      {timeAgo(n.time)}
                    </div>
                  </div>

                  {/* Punto azul si no leída */}
                  {!n.read && (
                    <div style={{
                      width: 7, height: 7,
                      background: '#1c79b4',
                      borderRadius: '50%',
                      flexShrink: 0, marginTop: 6,
                    }} />
                  )}
                  {/* Botón eliminar */}
                  <button
                    onClick={function (e) { e.stopPropagation(); clearOne(n.id); }}
                    title="Eliminar"
                    style={{
                      background: 'none', border: 'none', cursor: 'pointer',
                      color: '#d1d5db', fontSize: 13, lineHeight: 1,
                      padding: '2px 4px', borderRadius: 4, flexShrink: 0,
                      transition: 'color .12s',
                    }}
                    onMouseOver={function (e) { e.currentTarget.style.color = '#ef4444'; }}
                    onMouseOut={function (e) { e.currentTarget.style.color = '#d1d5db'; }}
                  >✕</button>
                </div>
              );
            })}
          </div>

          {/* Footer decorativo */}
          <div style={{
            padding: '8px 16px',
            background: '#f8fafc',
            borderTop: '1px solid #f1f5f9',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <div style={{ width: 6, height: 6, background: '#c4b400', borderRadius: '50%' }} />
            <span style={{ fontSize: 10, color: '#9ca3af', fontWeight: 500 }}>
              ASSYST — Plataforma SG-SST
            </span>
          </div>
        </div>
      )}
    </div>
  );
}

/* ── API global: empujar notificación al admin ──────────── */
window.pushAdminNotif = function (notif) {
  var existing = loadNotifs('admin');
  existing.unshift(notif);
  saveNotifs('admin', existing);
  window.dispatchEvent(new CustomEvent('sst_notif_added', { detail: { role: 'admin' } }));
};

/* ── API global: empujar notificación a estudiantes ─────── */
window.pushStudentNotif = function (notif) {
  var existing = loadNotifs('estudiante');
  existing.unshift(notif);
  saveNotifs('estudiante', existing);
  window.dispatchEvent(new CustomEvent('sst_notif_added', { detail: { role: 'estudiante' } }));
};

/* ── API global: notificación a un estudiante por su ID ─── */
window.pushStudentNotifById = function (userId, notif) {
  var existing = loadNotifs(userId);
  existing.unshift(notif);
  saveNotifs(userId, existing);
  window.dispatchEvent(new CustomEvent('sst_notif_added', { detail: { role: userId } }));
};

/* ── Toast global ───────────────────────────────────────── */
window.showToast = function (message, type) {
  type = type || 'success';
  var palettes = {
    success: { bg: '#1c79b4', border: '#c4b400', icon: '✓' },
    info:    { bg: '#0F2044', border: '#1c79b4', icon: '🔔' },
    error:   { bg: '#b91c1c', border: '#ef4444', icon: '✕' },
  };
  var p = palettes[type] || palettes.info;

  /* Eliminar toast anterior si existe */
  var prev = document.getElementById('sst-toast');
  if (prev) prev.remove();

  var toast = document.createElement('div');
  toast.id = 'sst-toast';
  toast.innerHTML =
    '<span style="display:flex;align-items:center;justify-content:center;width:22px;height:22px;background:' + p.border + ';border-radius:50%;color:' + (type === 'success' ? '#0F2044' : 'white') + ';font-size:11px;font-weight:900;flex-shrink:0">' + p.icon + '</span>' +
    '<span style="flex:1">' + message + '</span>';

  Object.assign(toast.style, {
    position:   'fixed',
    bottom:     '28px',
    right:      '28px',
    background: p.bg,
    color:      'white',
    padding:    '13px 18px',
    borderRadius: '12px',
    fontFamily: "'Montserrat',sans-serif",
    fontSize:   '13px',
    fontWeight: '600',
    boxShadow:  '0 10px 36px rgba(0,0,0,.28)',
    zIndex:     '99999',
    maxWidth:   '360px',
    display:    'flex',
    alignItems: 'center',
    gap:        '10px',
    border:     '1.5px solid ' + p.border,
    transform:  'translateY(90px)',
    opacity:    '0',
    transition: 'transform .32s cubic-bezier(.34,1.56,.64,1), opacity .28s',
    pointerEvents: 'none',
    lineHeight: '1.4',
  });

  document.body.appendChild(toast);

  requestAnimationFrame(function () {
    requestAnimationFrame(function () {
      toast.style.transform = 'translateY(0)';
      toast.style.opacity   = '1';
    });
  });

  setTimeout(function () {
    toast.style.transform = 'translateY(90px)';
    toast.style.opacity   = '0';
    setTimeout(function () { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 400);
  }, 3500);
};

window.NotificationBell = NotificationBell;
