arkitel / frontend /src /components /Header.tsx
CBV01
feat: scale indexes, discrete scrollbar, viewport payment modal, avatar persistence, simple dashboard english, plan limits card, and live smtp verification
504c45c
Raw History Blame Contribute Delete
19.7 kB
"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<Broadcast[]>([]);
const [isProfileOpen, setIsProfileOpen] = useState(false);
const [isNotificationsOpen, setIsNotificationsOpen] = useState(false);
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const profileRef = useRef<HTMLDivElement>(null);
const notifRef = useRef<HTMLDivElement>(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 (
<header className="sticky top-0 z-30 w-full bg-background/80 backdrop-blur-xl border-b border-border/60 transition-all">
<div className="flex items-center justify-between gap-3 px-4 md:px-8 py-2.5 max-w-7xl mx-auto w-full min-w-0">
{/* Left / Center: Breaking News Ticker (Only shown when admin broadcasts exist) */}
{broadcasts.length > 0 ? (
<div className="flex-1 min-w-0 flex items-center gap-3 mr-2 overflow-hidden">
{/* Breaking News Pulsing Badge */}
<div className="shrink-0 flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-rose-500/15 border border-rose-500/30 text-rose-400 text-[10px] font-black tracking-wider uppercase shadow-xs">
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-2 w-2 bg-rose-500"></span>
</span>
<span className="hidden sm:inline">BREAKING NEWS</span>
<span className="sm:hidden">NEWS</span>
</div>
{/* Marquee Scroller */}
<div className="flex-1 min-w-0 overflow-hidden relative group/ticker py-1 mask-linear-fade [contain:paint]">
<div className="animate-marquee cursor-default">
{broadcasts.map((b) => (
<span key={b.id} className="inline-flex items-center text-xs font-medium text-foreground/85 mr-10">
<span className={`w-1.5 h-1.5 rounded-full mr-2 shrink-0 ${
b.type === 'warning' ? 'bg-amber-400' :
b.type === 'success' ? 'bg-emerald-400' : 'bg-indigo-400'
}`} />
<span className="hover:text-indigo-400 transition-colors font-semibold">
{b.message}
</span>
<span className="mx-6 text-foreground/20 font-bold">•</span>
</span>
))}
</div>
</div>
</div>
) : (
<div className="flex-1" />
)}
{/* Right Section: Notification Bell + User Profile Dropdown */}
<div className="flex items-center gap-2.5 shrink-0">
{/* Notification Bell */}
<div className="relative" ref={notifRef}>
<button
type="button"
onClick={() => {
setIsNotificationsOpen(!isNotificationsOpen);
setIsProfileOpen(false);
}}
className="relative p-2 rounded-xl bg-foreground/[0.03] hover:bg-foreground/[0.08] border border-border/70 text-foreground/70 hover:text-foreground transition-all cursor-pointer group shadow-2xs"
title="Notifications"
>
<Bell size={17} className="group-hover:scale-105 transition-transform" />
{unreadCount > 0 && (
<span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-rose-500 text-[9px] font-black text-white shadow-xs animate-pulse">
{unreadCount}
</span>
)}
</button>
{/* Notifications Dropdown Panel */}
{isNotificationsOpen && (
<div className="absolute right-0 top-full mt-2 w-80 sm:w-96 rounded-2xl bg-card border border-border/80 p-4 shadow-2xl text-foreground z-50 animate-in fade-in zoom-in-95 duration-150 overflow-hidden">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-1/2 h-[2px] bg-gradient-to-r from-transparent via-indigo-500 to-transparent"></div>
<div className="flex items-center justify-between pb-3 border-b border-border/60 mb-2">
<div className="flex items-center gap-2">
<div className="p-1 rounded-lg bg-indigo-500/10 text-indigo-400">
<Bell size={14} />
</div>
<span className="text-xs font-bold text-foreground">Notifications</span>
{unreadCount > 0 && (
<span className="px-1.5 py-0.2 rounded-full bg-indigo-500/20 text-indigo-300 text-[10px] font-bold">
{unreadCount} new
</span>
)}
</div>
{unreadCount > 0 && (
<button
type="button"
onClick={handleMarkAllRead}
className="text-[10px] font-bold text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer"
>
Mark all read
</button>
)}
</div>
<div className="space-y-2 max-h-72 overflow-y-auto custom-scrollbar pr-1">
{notifications.length === 0 ? (
<div className="py-6 text-center text-xs text-foreground/40 font-medium">
No notifications yet
</div>
) : (
notifications.map((notif) => (
<div
key={notif.id}
className={`p-3 rounded-xl border transition-all ${
notif.read
? 'bg-input/30 border-border/40 opacity-70'
: 'bg-input/60 border-indigo-500/20 shadow-xs'
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex items-center gap-2">
{notif.type === 'warning' ? (
<AlertTriangle size={14} className="text-amber-400 shrink-0 mt-0.5" />
) : notif.type === 'success' ? (
<CheckCircle2 size={14} className="text-emerald-400 shrink-0 mt-0.5" />
) : (
<Info size={14} className="text-indigo-400 shrink-0 mt-0.5" />
)}
<h4 className="text-xs font-bold text-foreground leading-tight">
{notif.title}
</h4>
</div>
<span className="text-[9px] text-foreground/40 shrink-0">{notif.time}</span>
</div>
<p className="text-[11px] text-foreground/60 mt-1 pl-5.5 leading-relaxed">
{notif.message}
</p>
</div>
))
)}
</div>
</div>
)}
</div>
{/* Profile Avatar Trigger & Dropdown */}
<div className="relative" ref={profileRef}>
<button
type="button"
onClick={() => {
setIsProfileOpen(!isProfileOpen);
setIsNotificationsOpen(false);
}}
className="flex items-center gap-2 p-1 pl-1.5 pr-2.5 rounded-full bg-foreground/[0.03] hover:bg-foreground/[0.08] border border-border/80 transition-all cursor-pointer group shadow-2xs"
>
{/* Avatar circle */}
<div className="relative w-7 h-7 rounded-full overflow-hidden bg-indigo-600 flex items-center justify-center text-[11px] font-black text-white shadow-xs shrink-0 border border-indigo-400/40">
{avatarUrl ? (
<img
src={avatarUrl}
alt={user?.username || 'Avatar'}
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : isEmojiAvatar ? (
<span className="text-sm select-none">{rawPic}</span>
) : (
<span>{initials}</span>
)}
</div>
{/* Name & Plan indicator */}
<div className="hidden sm:flex flex-col text-left leading-none">
<span className="text-xs font-bold text-foreground truncate max-w-[110px]">
{user?.full_name || user?.username || 'Member'}
</span>
<span className="text-[9px] text-indigo-400 font-extrabold tracking-wider uppercase mt-0.5">
{planName}
</span>
</div>
<ChevronDown size={13} className={`text-foreground/40 group-hover:text-foreground transition-transform duration-200 ${isProfileOpen ? 'rotate-180' : ''}`} />
</button>
{/* Profile Dropdown Menu */}
{isProfileOpen && (
<div className="absolute right-0 top-full mt-2 w-72 rounded-2xl bg-card border border-border/80 p-4 shadow-2xl text-foreground z-50 animate-in fade-in zoom-in-95 duration-150 space-y-3.5 overflow-hidden">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-1/2 h-[2px] bg-gradient-to-r from-transparent via-indigo-500 to-transparent"></div>
{/* User Identity Header Card */}
<div className="flex items-center gap-3 pb-3 border-b border-border/60">
<div className="w-11 h-11 rounded-2xl overflow-hidden bg-indigo-600 flex items-center justify-center text-sm font-black text-white shadow-md border border-indigo-400/40 shrink-0">
{avatarUrl ? (
<img
src={avatarUrl}
alt="Profile"
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : isEmojiAvatar ? (
<span className="text-2xl select-none">{rawPic}</span>
) : (
<span>{initials}</span>
)}
</div>
<div className="min-w-0 flex-1">
<h3 className="text-xs font-bold text-foreground truncate">
{user?.full_name || user?.username}
</h3>
<p className="text-[10px] text-indigo-400 font-mono truncate">
@{user?.username}
</p>
<p className="text-[10px] text-foreground/45 truncate mt-0.5">
{user?.email || 'No email attached'}
</p>
</div>
</div>
{/* Plan Status Pill */}
<div className="p-2.5 rounded-xl bg-input/50 border border-border/60 flex items-center justify-between">
<div>
<div className="text-[9px] font-bold text-foreground/40 uppercase tracking-wider">Current Membership</div>
<div className="text-xs font-black text-indigo-400 flex items-center gap-1 mt-0.5">
<Crown size={12} className="text-amber-400" />
<span>{planName} PLAN</span>
</div>
</div>
{planName !== 'UNLIMITED' && (
<button
type="button"
onClick={() => {
setIsProfileOpen(false);
window.dispatchEvent(new Event('open-monetization-modal'));
}}
className="px-2.5 py-1 rounded-lg bg-indigo-500 hover:bg-indigo-600 text-white font-bold text-[10px] transition-colors shadow-xs cursor-pointer"
>
Upgrade
</button>
)}
</div>
{/* Quick Menu Options */}
<div className="space-y-1 text-xs">
<button
type="button"
onClick={() => {
setIsProfileOpen(false);
if (onOpenEntitlements) onOpenEntitlements();
else window.dispatchEvent(new Event('open-entitlements-modal'));
}}
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 cursor-pointer text-left"
>
<Sparkles size={14} className="text-indigo-400" />
<span>View Plan Entitlements</span>
</button>
<button
type="button"
onClick={() => {
setIsProfileOpen(false);
if (onOpenSupport) onOpenSupport();
}}
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 cursor-pointer text-left"
>
<HelpCircle size={14} className="text-foreground/40" />
<span>Support Desk</span>
</button>
{user?.role === 'admin' && (
<Link
href="/admin"
onClick={() => 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"
>
<Shield size={14} className="text-rose-400" />
<span>Admin Control Panel</span>
</Link>
)}
</div>
{/* Log Out Button */}
<div className="pt-2 border-t border-border/60">
<button
type="button"
onClick={handleLogout}
className="w-full flex items-center gap-2 px-3 py-2 rounded-xl text-rose-400 hover:text-rose-300 hover:bg-rose-500/10 text-xs font-semibold transition-colors cursor-pointer"
>
<LogOut size={14} />
<span>Sign Out</span>
</button>
</div>
</div>
)}
</div>
</div>
</div>
</header>
);
}