// notificaciones.jsx — Sistema de notificaciones de Serenia
// Cargado en SerenIA.html: <script type="text/babel" src="./notificaciones.jsx">

// ── Almacén de notificaciones (Supabase + localStorage como caché) ────────────
function notifKey(userId) { return 'serenia_notifs_' + userId; }

// Guarda en Supabase + localStorage
window.sereniaNotifAdd = function(userId, notif) {
  if (!userId) return;
  // Optimistic local
  try {
    const list = JSON.parse(localStorage.getItem(notifKey(userId)) || '[]');
    const local = { ...notif, id: 'n_' + Date.now(), read: false, created_at: new Date().toISOString() };
    localStorage.setItem(notifKey(userId), JSON.stringify([local, ...list].slice(0, 100)));
  } catch (_) {}
  // Supabase (fire and forget)
  if (window.SupaNotifications) {
    window.SupaNotifications.add(userId, notif).catch(() => {});
  }
};

// Retorna promesa; los componentes deben esperar
window.sereniaNotifGetAll = async function(userId) {
  if (window.SupaNotifications) {
    try {
      const data = await window.SupaNotifications.getAll(userId);
      // Actualizar caché local
      localStorage.setItem(notifKey(userId), JSON.stringify(data));
      return data;
    } catch (_) {}
  }
  try { return JSON.parse(localStorage.getItem(notifKey(userId)) || '[]'); } catch (_) { return []; }
};

window.sereniaNotifMarkRead = async function(userId, notifId) {
  try {
    const list = JSON.parse(localStorage.getItem(notifKey(userId)) || '[]');
    localStorage.setItem(notifKey(userId), JSON.stringify(list.map(n => n.id === notifId ? { ...n, read: true } : n)));
  } catch (_) {}
  if (window.SupaNotifications && !notifId.startsWith('n_')) {
    window.SupaNotifications.markRead(notifId).catch(() => {});
  }
};

window.sereniaNotifMarkAllRead = async function(userId) {
  try {
    const list = JSON.parse(localStorage.getItem(notifKey(userId)) || '[]');
    localStorage.setItem(notifKey(userId), JSON.stringify(list.map(n => ({ ...n, read: true }))));
  } catch (_) {}
  if (window.SupaNotifications) window.SupaNotifications.markAllRead(userId).catch(() => {});
};

window.sereniaNotifUnreadCount = async function(userId) {
  if (window.SupaNotifications) {
    try { return await window.SupaNotifications.unreadCount(userId); } catch (_) {}
  }
  try { return (JSON.parse(localStorage.getItem(notifKey(userId)) || '[]')).filter(n => !n.read).length; } catch (_) { return 0; }
};

// ── Íconos y metadatos por tipo ───────────────────────────────────────────────
const NOTIF_META = {
  forum_reply:      { icon: '💬', color: '#3A7BC4', label: 'Foro' },
  reminder:         { icon: '🔔', color: '#6B9B7A', label: 'Recordatorio' },
  streak:           { icon: '🔥', color: '#C4703A', label: 'Racha' },
  checkin:          { icon: '🌱', color: '#5A8C5A', label: 'Registro' },
  message:          { icon: '✉️', color: '#4F7A5C', label: 'Mensaje' },
  sos:              { icon: '🆘', color: '#C5524B', label: 'SOS' },
  sos_institution:  { icon: '🏫', color: '#C5524B', label: 'Alerta SOS' },
  collective_crisis:{ icon: '📊', color: '#E07B2A', label: 'Alerta grupal' },
  institution_message: { icon: '🎓', color: '#4A7C5C', label: 'Mi institución' },
  institution_reward:  { icon: '🎁', color: '#C9A24A', label: 'Premio' },
};

function notifTimeAgo(ts) {
  const d = Date.now() - new Date(ts).getTime();
  const m = Math.floor(d / 60000);
  if (m < 1) return 'ahora';
  if (m < 60) return m + ' min';
  const h = Math.floor(m / 60);
  if (h < 24) return h + 'h';
  return Math.floor(h / 24) + 'd';
}

// ── Campana con badge ─────────────────────────────────────────────────────────
function NotificationsBell({ p, userId, onOpen }) {
  const [unread, setUnread] = React.useState(0);

  React.useEffect(() => {
    const update = async () => {
      const count = await window.sereniaNotifUnreadCount(userId);
      setUnread(count || 0);
    };
    update();
    const interval = setInterval(update, 8000);
    return () => clearInterval(interval);
  }, [userId]);

  return (
    <button onClick={onOpen} className="notif-bell-btn" style={{
      position: 'relative', background: p.surface, border: 'none',
      padding: 10, borderRadius: 14, cursor: 'pointer',
      color: p.ink,
      boxShadow: `0 12px 26px ${p.ink}1f, 0 0 0 1px ${p.line}`,
      transition: 'all .15s ease',
      flexShrink: 0,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <style>{`
        .notif-bell-btn:hover { background: ${p.bg} !important; }
        .notif-bell-btn:active { filter: brightness(0.92); }
        @keyframes notifPing {
          0%   { transform: scale(1); opacity: 1; }
          75%, 100% { transform: scale(2.2); opacity: 0; }
        }
      `}</style>
      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none" viewBox="0 0 24 24"
        strokeWidth="1.5" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round"
          d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0" />
      </svg>
      {unread > 0 && (
        <div style={{
          position: 'absolute', top: -4, right: -4,
          minWidth: 16, height: 16, borderRadius: '50%',
          background: '#E05555', color: '#fff',
          fontSize: 9, fontWeight: 700, lineHeight: '16px', textAlign: 'center',
          padding: unread > 9 ? '0 4px' : 0,
          border: `2px solid ${p.surface}`, boxSizing: 'content-box',
        }}>
          <span style={{ position: 'relative' }}>{unread > 9 ? '9+' : unread}</span>
        </div>
      )}
    </button>
  );
}

// ── Pantalla de notificaciones ────────────────────────────────────────────────
function NotificationsScreen({ p, userId, onBack }) {
  const [notifs, setNotifs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    // Mostrar caché local inmediatamente
    try { setNotifs(JSON.parse(localStorage.getItem(notifKey(userId)) || '[]')); } catch (_) {}
    // Cargar desde Supabase
    window.sereniaNotifGetAll(userId)
      .then(data => { setNotifs(data || []); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [userId]);

  const markAll = async () => {
    await window.sereniaNotifMarkAllRead(userId);
    setNotifs(n => n.map(x => ({ ...x, read: true })));
  };

  const markOne = async (id) => {
    await window.sereniaNotifMarkRead(userId, id);
    setNotifs(n => n.map(x => x.id === id ? { ...x, read: true } : x));
  };

  const hasUnread = notifs.some(n => !n.read);

  const grouped = (() => {
    const today = new Date().toISOString().slice(0, 10);
    const yest = (() => { const d = new Date(); d.setDate(d.getDate()-1); return d.toISOString().slice(0,10); })();
    const groups = {};
    notifs.forEach(n => {
      const day = new Date(n.created_at).toISOString().slice(0, 10);
      const label = day === today ? 'Hoy' : day === yest ? 'Ayer' : new Date(n.created_at)
        .toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' });
      const cap = label.charAt(0).toUpperCase() + label.slice(1);
      if (!groups[cap]) groups[cap] = [];
      groups[cap].push(n);
    });
    return groups;
  })();

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: p.bg }}>
      {/* Cabecera */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 10px', borderBottom: `1px solid ${p.line}`, flexShrink: 0 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer',
          color: p.primaryDeep, fontSize: 15, fontWeight: 600, padding: '4px 0' }}>‹ Inicio</button>
        <div style={{ fontSize: 15, fontWeight: 700, color: p.ink }}>Notificaciones</div>
        {hasUnread ? (
          <button onClick={markAll} style={{ background: 'transparent', border: 'none',
            cursor: 'pointer', color: p.primaryDeep, fontSize: 12, fontWeight: 600, padding: '4px 0' }}>
            Leer todo
          </button>
        ) : (
          <div style={{ width: 60 }} />
        )}
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {notifs.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '70px 24px', color: p.inkMute }}>
            <div style={{ fontSize: 36, marginBottom: 14 }}>🔕</div>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Sin notificaciones</div>
            <div style={{ fontSize: 13 }}>Cuando alguien responda tu post o llegue un recordatorio, aparecerá aquí.</div>
          </div>
        ) : (
          Object.entries(grouped).map(([label, items]) => (
            <div key={label}>
              <div style={{ padding: '14px 18px 6px', fontSize: 11, fontWeight: 700,
                color: p.inkMute, textTransform: 'uppercase', letterSpacing: '0.07em' }}>
                {label}
              </div>
              {items.map(n => {
                const meta = NOTIF_META[n.type] || NOTIF_META.reminder;
                return (
                  <div key={n.id} onClick={() => markOne(n.id)}
                    style={{ display: 'flex', alignItems: 'flex-start', gap: 14,
                      padding: '14px 18px', borderBottom: `1px solid ${p.line}`,
                      background: n.read ? 'transparent' : p.primarySoft + '44',
                      cursor: 'pointer', transition: 'background .2s' }}>
                    {/* Icono */}
                    <div style={{ width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
                      background: meta.color + '18', display: 'grid', placeItems: 'center', fontSize: 18 }}>
                      {meta.icon}
                    </div>
                    {/* Texto */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: n.read ? 500 : 700, color: p.ink, marginBottom: 3 }}>
                        {n.title}
                      </div>
                      {n.body && (
                        <div style={{ fontSize: 12, color: p.inkSoft, lineHeight: 1.4,
                          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                          {n.body}
                        </div>
                      )}
                      <div style={{ fontSize: 10, color: p.inkMute, marginTop: 4 }}>
                        {meta.label} · {notifTimeAgo(n.created_at)}
                      </div>
                    </div>
                    {/* Punto de no leído */}
                    {!n.read && (
                      <div style={{ width: 8, height: 8, borderRadius: '50%',
                        background: meta.color, flexShrink: 0, marginTop: 4 }} />
                    )}
                  </div>
                );
              })}
            </div>
          ))
        )}
      </div>
    </div>
  );
}
