// components/NotificationBell.tsx
'use client';

import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { getUnreadCount } from '@/lib/api/notification.api';
import { playNotificationSound } from '@/lib/notificationSound';

// ✅ FIXED — reads userId from JWT sub field (same as import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";)
function getUserId(): number | null {
  try {
    // Prefer the CLIENT token when present (client portal), else staff token.
    const token =
      localStorage.getItem('clientPortalToken') ||   // ← client first
      localStorage.getItem('access_token') ||
      localStorage.getItem('token');
    if (token) {
      const payload = JSON.parse(atob(token.split('.')[1]));
      const id = payload?.sub ?? payload?.id ?? payload?.userId ?? null;
      if (id) return Number(id);
    }
  } catch { /* ignore */ }
  return null;
}

export default function NotificationBell() {
  const router = useRouter();
  const [count, setCount] = useState(0);
  const prevCount = useRef<number>(0);

  const refresh = useCallback(async () => {
    const userId = getUserId();
    if (!userId) return;
    try {
      const c = await getUnreadCount(userId);
      setCount(prev => {
        if (c > prevCount.current) {
          playNotificationSound('default');
        }
        prevCount.current = c;
        return c;
      });
    } catch { /* ignore */ }
  }, []);

  // Poll every 30 seconds as fallback
  useEffect(() => {
    refresh();
    const interval = setInterval(refresh, 30000);
    return () => clearInterval(interval);
  }, [refresh]);

  // Expose refresh so SSE hook can trigger it from anywhere
  useEffect(() => {
    (window as any).__refreshNotificationBell = refresh;
    return () => { delete (window as any).__refreshNotificationBell; };
  }, [refresh]);

  return (
    <button
      onClick={() => router.push('/modules/notifications')}
      style={{
        position: 'relative', background: 'none', border: 'none',
        cursor: 'pointer', padding: 8, borderRadius: 8,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#6b7280', transition: 'background 0.15s',
      }}
      title="Notifications"
      onMouseEnter={e => (e.currentTarget.style.background = '#f3f4f6')}
      onMouseLeave={e => (e.currentTarget.style.background = 'none')}
    >
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
        stroke="currentColor" strokeWidth="2"
        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>

      {count > 0 && (
        <span style={{
          position: 'absolute', top: 2, right: 2,
          width: count > 9 ? 18 : 16, height: 16,
          borderRadius: 99,
          backgroundColor: '#ef4444', color: '#fff',
          fontSize: 9, fontWeight: 800,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '2px solid #fff', lineHeight: 1,
        }}>
          {count > 99 ? '99+' : count}
        </span>
      )}
    </button>
  );
}