"use client"; import React, { useState, useEffect, useRef } from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { Bell, Sparkles, Shield, HelpCircle, LogOut, Radio, ChevronDown, Check, Info, AlertTriangle, CheckCircle2, X, User as UserIcon, Crown, Layers } from "lucide-react"; import { apiFetch, removeToken, getApiBase } from "@/lib/auth"; interface HeaderProps { user: any; status: any; onOpenSupport?: () => void; onOpenEntitlements?: () => void; } interface Broadcast { id: number; message: string; type: 'info' | 'warning' | 'success'; created_at?: string; } interface NotificationItem { id: string; title: string; message: string; type: 'info' | 'success' | 'warning'; time: string; read: boolean; } export function Header({ user, status, onOpenSupport, onOpenEntitlements }: HeaderProps) { const [broadcasts, setBroadcasts] = useState([]); const [isProfileOpen, setIsProfileOpen] = useState(false); const [isNotificationsOpen, setIsNotificationsOpen] = useState(false); const [notifications, setNotifications] = useState([]); const [unreadCount, setUnreadCount] = useState(0); const profileRef = useRef(null); const notifRef = useRef(null); const router = useRouter(); // Fetch broadcasts for marquee and notifications useEffect(() => { const fetchBroadcasts = async () => { try { const res = await apiFetch('/api/broadcasts'); if (res.ok) { const data = await res.json(); const items: Broadcast[] = data.broadcasts || []; setBroadcasts(items); // Build notifications const welcomeNotif: NotificationItem = { id: 'welcome-001', title: 'Welcome to ArkiTel', message: 'Your automation account is ready. Use coupon WELCOME20 to get 20% off any tier upgrade!', type: 'success', time: 'Just now', read: false, }; const broadcastNotifs: NotificationItem[] = items.map(b => ({ id: `broadcast-${b.id}`, title: b.type === 'warning' ? 'Important Alert' : b.type === 'success' ? 'Platform Update' : 'Breaking News', message: b.message, type: b.type, time: b.created_at ? new Date(b.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'Today', read: false, })); const allNotifs = [welcomeNotif, ...broadcastNotifs]; setNotifications(allNotifs); setUnreadCount(allNotifs.filter(n => !n.read).length); } } catch (err) { // Fallback default notification const welcomeNotif: NotificationItem = { id: 'welcome-001', title: 'Welcome to ArkiTel', message: 'Your automation account is ready. Use coupon WELCOME20 to get 20% off any tier upgrade!', type: 'success', time: 'Just now', read: false, }; setNotifications([welcomeNotif]); setUnreadCount(1); } }; fetchBroadcasts(); const interval = setInterval(fetchBroadcasts, 3 * 60 * 1000); return () => clearInterval(interval); }, []); // Close dropdowns on outside click useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (profileRef.current && !profileRef.current.contains(event.target as Node)) { setIsProfileOpen(false); } if (notifRef.current && !notifRef.current.contains(event.target as Node)) { setIsNotificationsOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); const handleMarkAllRead = () => { setNotifications(prev => prev.map(n => ({ ...n, read: true }))); setUnreadCount(0); }; const handleLogout = () => { removeToken(); const isAdminRoute = window.location.pathname.startsWith('/admin'); router.push(isAdminRoute ? '/admin/login' : '/login'); }; const planName = (status?.plan || user?.plan || 'Free').toUpperCase(); const apiBase = getApiBase(); // Resolve profile picture let avatarUrl: string | null = null; const rawPic = user?.profile_picture; const isEmojiAvatar = Boolean(rawPic && !rawPic.includes('/') && !rawPic.startsWith('http') && !rawPic.startsWith('data:')); if (rawPic && !isEmojiAvatar) { const cleanBase = apiBase ? apiBase.replace(/\/+$/, '') : ''; const cleanPath = rawPic.startsWith('/') ? rawPic : `/${rawPic}`; avatarUrl = rawPic.startsWith('http') || rawPic.startsWith('data:') ? rawPic : `${cleanBase}${cleanPath}`; } const initials = (user?.full_name || user?.username || 'U') .split(' ') .map((n: string) => n[0]) .join('') .slice(0, 2) .toUpperCase(); return (
{/* Left / Center: Breaking News Ticker (Only shown when admin broadcasts exist) */} {broadcasts.length > 0 ? (
{/* Breaking News Pulsing Badge */}
BREAKING NEWS NEWS
{/* Marquee Scroller */}
{broadcasts.map((b) => ( {b.message} • ))}
) : (
)} {/* Right Section: Notification Bell + User Profile Dropdown */}
{/* Notification Bell */}
{/* Notifications Dropdown Panel */} {isNotificationsOpen && (
Notifications {unreadCount > 0 && ( {unreadCount} new )}
{unreadCount > 0 && ( )}
{notifications.length === 0 ? (
No notifications yet
) : ( notifications.map((notif) => (
{notif.type === 'warning' ? ( ) : notif.type === 'success' ? ( ) : ( )}

{notif.title}

{notif.time}

{notif.message}

)) )}
)}
{/* Profile Avatar Trigger & Dropdown */}
{/* Profile Dropdown Menu */} {isProfileOpen && (
{/* User Identity Header Card */}
{avatarUrl ? ( Profile { (e.target as HTMLImageElement).style.display = 'none'; }} /> ) : isEmojiAvatar ? ( {rawPic} ) : ( {initials} )}

{user?.full_name || user?.username}

@{user?.username}

{user?.email || 'No email attached'}

{/* Plan Status Pill */}
Current Membership
{planName} PLAN
{planName !== 'UNLIMITED' && ( )}
{/* Quick Menu Options */}
{user?.role === 'admin' && ( setIsProfileOpen(false)} className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-foreground/70 hover:text-foreground hover:bg-foreground/5 transition-colors text-left" > Admin Control Panel )}
{/* Log Out Button */}
)}
); }