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b31cb3a
 
 
 
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"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>
  );
}