File size: 42,924 Bytes
9e497a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cea1f8
 
 
 
9e497a6
238a2ce
ed191e7
a91ee9c
ff1aa72
6b2f36c
 
 
 
 
aa58c7d
 
 
 
 
9e497a6
 
3f64f7a
b31cb3a
9e497a6
 
 
 
0cea1f8
 
aa58c7d
0cea1f8
6b2f36c
 
6c2d0ad
 
6b2f36c
 
9e497a6
 
 
 
 
028f096
9e497a6
fd477ea
9e497a6
 
 
 
 
 
b31cb3a
 
9e497a6
 
b31cb3a
9e497a6
 
 
 
 
 
 
6b2f36c
028f096
6b2f36c
 
028f096
 
 
 
9e497a6
d5b4856
028f096
 
 
 
 
6b2f36c
 
 
 
 
9e497a6
 
 
 
d5b4856
9e497a6
 
 
028f096
9e497a6
3ab7243
 
 
 
9e497a6
 
 
 
 
 
 
 
bfaa533
 
 
 
 
 
 
 
d5b4856
bfaa533
 
 
 
b31cb3a
 
bfaa533
 
 
 
b31cb3a
bfaa533
 
9e497a6
 
0cea1f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e497a6
 
 
 
 
 
 
 
 
 
 
 
0cea1f8
9e497a6
 
238a2ce
ed191e7
ff1aa72
9e497a6
 
 
 
 
 
 
 
b31cb3a
 
 
9e497a6
 
 
 
 
 
 
 
f211d9b
9e497a6
 
 
 
 
 
902a16c
9e497a6
2ff713b
9e497a6
 
 
 
 
 
f211d9b
9e497a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ff713b
9e497a6
ed2fb7c
9e497a6
 
ed2fb7c
9e497a6
 
 
 
 
f211d9b
9e497a6
 
 
 
 
 
 
 
 
 
 
ed2fb7c
9e497a6
 
 
 
 
 
 
 
ed2fb7c
 
9e497a6
ed2fb7c
2ff713b
9e497a6
 
 
ed2fb7c
 
9e497a6
 
 
6b2f36c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e497a6
 
0cea1f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e497a6
 
 
0cea1f8
 
 
9e497a6
 
0cea1f8
9e497a6
 
 
0cea1f8
9e497a6
aa58c7d
0cea1f8
 
d5b4856
 
 
 
 
 
0aefca0
 
028f096
d5b4856
aa58c7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
028f096
0aefca0
028f096
 
 
 
0cea1f8
4c18d20
0aefca0
 
4c18d20
fd477ea
0aefca0
 
d5b4856
0aefca0
fd477ea
0aefca0
 
028f096
0aefca0
4c18d20
633cebc
 
4c18d20
fd477ea
633cebc
 
 
 
fd477ea
633cebc
 
 
 
9fb76ee
 
 
 
 
 
fd477ea
9fb76ee
 
d5b4856
9fb76ee
fd477ea
9fb76ee
 
 
0aefca0
4c18d20
cf944ae
9fb76ee
fd477ea
9fb76ee
 
 
028f096
 
aa58c7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
028f096
0aefca0
028f096
 
9e497a6
 
 
 
 
 
 
4d5557c
 
902a16c
9e497a6
4d5557c
 
 
 
 
 
 
 
 
9e497a6
 
 
6b2f36c
b31cb3a
 
 
 
1d80adf
b31cb3a
 
1d80adf
 
 
b31cb3a
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
 
1d80adf
b31cb3a
fd477ea
b31cb3a
 
1d80adf
b31cb3a
fd477ea
b31cb3a
 
1d80adf
b31cb3a
fd477ea
b31cb3a
 
1d80adf
b31cb3a
fd477ea
b31cb3a
 
1d80adf
b31cb3a
fd477ea
b31cb3a
 
1d80adf
b31cb3a
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
1d80adf
b31cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b2f36c
 
6c2d0ad
6b2f36c
1d80adf
6b2f36c
 
1d80adf
 
 
6b2f36c
 
 
 
 
1d80adf
6b2f36c
 
 
 
 
1d80adf
6b2f36c
 
 
 
 
 
 
 
6c2d0ad
6b2f36c
 
 
 
 
 
 
 
6c2d0ad
6b2f36c
 
 
 
 
 
 
6c2d0ad
6b2f36c
 
 
 
 
 
 
 
 
 
6c2d0ad
6b2f36c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e497a6
 
 
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import {
    LayoutDashboard,
    Users,
    Megaphone,
    Search,
    Menu,
    X,
    Sun,
    Moon,
    ChevronLeft,
    ChevronDown,
    ChevronUp,
    GripHorizontal,
    ArrowLeftRight,
    LogOut,
    Shield,
    Bookmark,
    FileText,
    Sparkles,
    Inbox,
    HelpCircle,
    MessageCircle,
    Send,
    Mail,
    ExternalLink,
    CheckCircle2,
    Clock,
    Lock,
    ShieldCheck
} from "lucide-react";
import { getToken, removeToken, apiFetch } from "@/lib/auth";
import { BroadcastBanner } from "./BroadcastBanner";
import { Header } from "./Header";

export function Sidebar({ children }: { children: React.ReactNode }) {
    const [isMobileOpen, setIsMobileOpen] = useState(false);
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [isFooterCollapsed, setIsFooterCollapsed] = useState(false);
    const [footerHeight, setFooterHeight] = useState<number>(300);
    const [showEntitlementsFlyout, setShowEntitlementsFlyout] = useState(false);
    const [isDragging, setIsDragging] = useState(false);
    const [showSupportModal, setShowSupportModal] = useState(false);
    const [supportConfig, setSupportConfig] = useState({
        whatsapp_number: 'https://wa.link/p0uv2l',
        support_email: 'arkilostudios@gmail.com',
        telegram_support: 'arkitel_support'
    });
    const pathname = usePathname();
    const router = useRouter();
    const { theme, setTheme } = useTheme();
    const [mounted, setMounted] = useState(false);
    const [user, setUser] = useState<any>(null);
    const [status, setStatus] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const isUnlimited = (status?.plan || '').toLowerCase() === 'unlimited' || Boolean(status?.is_unlimited) || ((status?.max_daily_campaigns || 0) >= 99999);

    useEffect(() => {
        setMounted(true);
        const fetchUser = async () => {
            const token = getToken();
            const isAdminRoute = pathname.startsWith('/admin');
            const isAuthRoute = pathname === '/login' || pathname === '/register' || pathname === '/admin/login' || pathname === '/get-started';
            const isLandingRoute = pathname === '/';

            if (!token) {
                if (!isAuthRoute && !isLandingRoute) {
                    router.push(isAdminRoute ? '/admin/login' : '/login');
                }
                setLoading(false);
                return;
            }

            try {
                const [meRes, statusRes, settingsRes] = await Promise.all([
                    apiFetch('/api/auth/me'),
                    apiFetch('/api/monetization/status'),
                    apiFetch('/api/system/settings').catch(() => null)
                ]);

                if (meRes.ok) {
                    const data = await meRes.json();
                    setUser(data);

                    if (statusRes.ok) {
                        const sData = await statusRes.json();
                        setStatus(sData);
                    }

                    if (settingsRes && settingsRes.ok) {
                        const setts = await settingsRes.json();
                        setSupportConfig(setts);
                    }

                    // Admin route protection
                    if (isAdminRoute && data.role !== 'admin' && pathname !== '/admin/login') {
                        router.push('/');
                    }

                    if (!data.passkey_verified && pathname !== '/verify-passkey' && !isAdminRoute) {
                        router.push('/verify-passkey');
                    }
                } else if (meRes.status === 401) {
                    removeToken();
                    setUser(null);
                    if (!isLandingRoute && !isAuthRoute) {
                        router.push(isAdminRoute ? '/admin/login' : '/login');
                    }
                }
            } catch (err) {
                console.error("Auth check failed", err);
            } finally {
                setLoading(false);
            }
        };
        fetchUser();

        const updateStatus = () => {
            if (getToken()) {
                apiFetch('/api/monetization/status')
                    .then(res => res.ok ? res.json() : null)
                    .then(data => {
                        if (data) setStatus(data);
                    })
                    .catch(() => { });
            }
        };

        window.addEventListener('update_status', updateStatus);
        const handleOpenEntitlements = () => setShowEntitlementsFlyout(true);
        window.addEventListener('open-entitlements-modal', handleOpenEntitlements);
        const intervalId = setInterval(updateStatus, 15000);

        return () => {
            window.removeEventListener('update_status', updateStatus);
            window.removeEventListener('open-entitlements-modal', handleOpenEntitlements);
            clearInterval(intervalId);
        };
    }, [pathname, router]);

    // Load and persist sidebar footer preference
    useEffect(() => {
        try {
            const savedCollapsed = localStorage.getItem('arkitel_sidebar_footer_collapsed');
            if (savedCollapsed !== null) {
                setIsFooterCollapsed(savedCollapsed === 'true');
            }
            const savedHeight = localStorage.getItem('arkitel_sidebar_footer_height');
            if (savedHeight !== null) {
                const h = parseInt(savedHeight, 10);
                if (!isNaN(h) && h >= 100 && h <= 500) {
                    setFooterHeight(h);
                }
            }
        } catch (e) { }
    }, []);

    const toggleFooterCollapse = () => {
        setIsFooterCollapsed(prev => {
            const next = !prev;
            try {
                localStorage.setItem('arkitel_sidebar_footer_collapsed', String(next));
            } catch (e) { }
            return next;
        });
    };

    const handleDragStart = (e: React.MouseEvent) => {
        e.preventDefault();
        setIsDragging(true);
        const startY = e.clientY;
        const startHeight = isFooterCollapsed ? 0 : footerHeight;

        const onMouseMove = (moveEvent: MouseEvent) => {
            const deltaY = startY - moveEvent.clientY;
            const newHeight = startHeight + deltaY;

            if (newHeight < 60) {
                setIsFooterCollapsed(true);
                try { localStorage.setItem('arkitel_sidebar_footer_collapsed', 'true'); } catch (e) { }
            } else {
                setIsFooterCollapsed(false);
                const clamped = Math.min(Math.max(newHeight, 120), 480);
                setFooterHeight(clamped);
                try {
                    localStorage.setItem('arkitel_sidebar_footer_collapsed', 'false');
                    localStorage.setItem('arkitel_sidebar_footer_height', String(clamped));
                } catch (e) { }
            }
        };

        const onMouseUp = () => {
            setIsDragging(false);
            window.removeEventListener('mousemove', onMouseMove);
            window.removeEventListener('mouseup', onMouseUp);
        };

        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    };

    const handleLogout = () => {
        removeToken();
        const isAdminRoute = pathname.startsWith('/admin');
        router.push(isAdminRoute ? '/admin/login' : '/login');
    };

    const toggleSidebar = () => setIsMobileOpen(!isMobileOpen);
    const toggleCollapse = () => setIsCollapsed(!isCollapsed);

    const navItems = [
        { name: "Dashboard", href: "/", icon: LayoutDashboard },
        { name: "Accounts", href: "/accounts", icon: Users },
        { name: "Fleet Compare", href: "/compare", icon: ArrowLeftRight },
        { name: "Campaigns", href: "/campaigns", icon: Megaphone },
        { name: "Scraper", href: "/scraper", icon: Search },
        { name: "Leads", href: "/leads", icon: Bookmark },
        { name: "Templates", href: "/templates", icon: FileText },
        { name: "DM Inbox", href: "/ai-assistant", icon: Inbox },
    ];

    if (user?.role === 'admin') {
        navItems.push({ name: "Admin Panel", href: "/admin", icon: Shield });
    }

    if (!mounted) return null;

    const noSidebarRoutes = ['/login', '/register', '/verify-passkey', '/admin/login', '/get-started'];
    const isPublicLanding = pathname === '/' && !getToken();
    if (noSidebarRoutes.includes(pathname) || isPublicLanding) {
        return <div className="w-full min-h-screen">{children}</div>;
    }

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-screen w-full bg-background font-sans">
                <div className="flex flex-col items-center gap-4">
                    <div className="w-12 h-12 border-4 border-indigo-500/30 border-t-indigo-500 rounded-full animate-spin" />
                    <p className="text-foreground/40 text-sm font-medium animate-pulse">Initializing ArkiTel...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="flex w-full min-h-screen min-w-0 max-w-full overflow-x-hidden">
            {/* Mobile Topbar */}
            <div className="md:hidden fixed top-0 left-0 right-0 h-16 bg-background/80 backdrop-blur-3xl border-b border-border flex items-center justify-between px-4 z-50">
                <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/20">
                        <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                        </svg>
                    </div>
                    <h1 className="text-sm font-semibold tracking-wider text-foreground">ARKITEL</h1>
                </div>
                <button onClick={toggleSidebar} className="p-2 text-foreground/70 hover:text-foreground">
                    {isMobileOpen ? <X size={24} /> : <Menu size={24} />}
                </button>
            </div>

            {/* Sidebar Overlay (Mobile) */}
            {isMobileOpen && (
                <div
                    className="md:hidden fixed inset-0 bg-black/60 backdrop-blur-sm z-40"
                    onClick={() => setIsMobileOpen(false)}
                />
            )}

            {/* Main Sidebar */}
            <nav className={`
        fixed top-0 left-0 h-full bg-background/90 md:bg-background/80 backdrop-blur-3xl 
        border-r border-border flex flex-col pt-20 md:pt-5 z-50 transition-all duration-300
        ${isMobileOpen ? "translate-x-0 w-64" : "-translate-x-full md:translate-x-0"}
        ${isCollapsed ? "md:w-20" : "md:w-50"}
      `}>
                {/* Logo Area (Desktop) */}
                <div className={`hidden md:flex items-center gap-2.5 mb-8 px-5 ${isCollapsed ? "justify-center px-0" : ""}`}>
                    <div className="w-8 h-8 min-w-[32px] rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/20">
                        <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                        </svg>
                    </div>
                    {!isCollapsed && <h1 className="text-sm font-semibold tracking-wider text-foreground animate-in fade-in duration-300">ARKITEL</h1>}
                </div>

                {/* Collapse Button */}
                <button
                    onClick={toggleCollapse}
                    className="hidden md:flex absolute -right-3 top-7 w-6 h-6 bg-indigo-500 rounded-full items-center justify-center text-white shadow-lg hover:scale-110 transition-transform z-50"
                >
                    <ChevronLeft size={14} className={`transition-transform duration-300 ${isCollapsed ? "rotate-180" : ""}`} />
                </button>

                {/* Navigation Links */}
                <div className="space-y-1 flex-1 px-2.5 overflow-y-auto overflow-x-hidden custom-scrollbar">
                    {navItems.map((item) => {
                        const isActive = pathname === item.href;
                        return (
                            <Link
                                key={item.name}
                                href={item.href}
                                onClick={() => setIsMobileOpen(false)}
                                className={`
                  flex items-center gap-2.5 py-2.5 rounded-xl text-xs font-medium transition-all group
                  ${isCollapsed ? "justify-center px-0" : "px-3"}
                  ${isActive
                                        ? "bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 font-semibold"
                                        : "text-foreground/60 hover:text-foreground hover:bg-foreground/5"}
                `}
                                title={isCollapsed ? item.name : ""}
                            >
                                <item.icon size={18} className={isActive ? "text-indigo-600 dark:text-indigo-400" : "text-foreground/50 group-hover:text-foreground/80"} />
                                {!isCollapsed && <span className="animate-in fade-in duration-300 truncate">{item.name}</span>}
                            </Link>
                        );
                    })}

                    {/* Support Desk Trigger */}
                    <button
                        type="button"
                        onClick={() => {
                            setIsMobileOpen(false);
                            setShowSupportModal(true);
                        }}
                        className={`
                            flex items-center gap-2.5 py-2.5 rounded-xl text-xs font-medium transition-all group w-full text-left cursor-pointer
                            ${isCollapsed ? "justify-center px-0" : "px-3"}
                            text-foreground/60 hover:text-foreground hover:bg-foreground/5
                        `}
                        title={isCollapsed ? "Support Desk" : ""}
                    >
                        <HelpCircle size={18} className="text-foreground/50 group-hover:text-indigo-400 transition-colors" />
                        {!isCollapsed && <span className="animate-in fade-in duration-300 truncate">Support</span>}
                    </button>
                </div>

                {/* Draggable & Collapsible Divider Bar */}
                <div
                    onMouseDown={handleDragStart}
                    className={`w-full py-1.5 flex items-center justify-center cursor-row-resize hover:bg-foreground/5 transition-colors group select-none border-t border-border shrink-0 ${isDragging ? 'bg-indigo-500/10' : ''}`}
                    title="Drag up/down to resize or click arrows to collapse/expand system status"
                >
                    <div className="flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-border/60 group-hover:bg-indigo-500/20 group-hover:border-indigo-500/40 border border-transparent transition-all">
                        <GripHorizontal size={13} className="text-foreground/40 group-hover:text-indigo-400 transition-colors" />
                        <button
                            type="button"
                            onClick={(e) => {
                                e.stopPropagation();
                                toggleFooterCollapse();
                            }}
                            className="text-foreground/40 hover:text-indigo-400 p-0.5 transition-colors cursor-pointer"
                            title={isFooterCollapsed ? "Expand system status" : "Collapse system status"}
                        >
                            {isFooterCollapsed ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
                        </button>
                    </div>
                </div>

                {/* Footer Status & Logout Section */}
                <div 
                    style={!isCollapsed && !isFooterCollapsed ? { height: `${footerHeight}px` } : undefined}
                    className={`
                        border-border transition-all duration-300 flex flex-col justify-between shrink-0 overflow-hidden
                        ${isFooterCollapsed ? 'h-auto p-2 pb-3' : 'p-4 overflow-y-auto custom-scrollbar'}
                    `}
                >
                    <button
                        onClick={handleLogout}
                        className={`
                            flex items-center gap-3 py-2.5 w-full rounded-xl text-xs font-semibold transition-all text-red-500/70 hover:text-red-500 hover:bg-red-500/10 shrink-0
                            ${isCollapsed ? "justify-center px-0" : "px-3.5"}
                        `}
                        title={isCollapsed ? "Logout" : ""}
                    >
                        <LogOut size={16} />
                        {!isCollapsed && <span className="animate-in fade-in duration-300">Logout</span>}
                    </button>

                    {/* Collapsible System Status & Telemetry */}
                    {!isCollapsed && user && (
                        <div className={`relative transition-all duration-300 space-y-3.5 ${isFooterCollapsed ? 'opacity-0 max-h-0 pointer-events-none mt-0' : 'opacity-100 mt-2'}`}>
                            <div className="flex items-center justify-between pt-2 border-t border-border/50">
                                <div className="text-[10px] text-foreground/40 uppercase tracking-[0.2em] font-bold">System Status</div>
                                <span className={`text-[9px] font-black px-2 py-0.5 rounded-full border border-current uppercase ${status?.plan === 'unlimited' ? 'text-rose-400 bg-rose-500/10' :
                                        status?.plan === 'premium' ? 'text-indigo-400 bg-indigo-500/10' :
                                            status?.plan === 'standard' ? 'text-amber-400 bg-amber-500/10' :
                                                status?.plan === 'basic' ? 'text-emerald-400 bg-emerald-500/10' :
                                                    'text-foreground/40 bg-foreground/5'
                                    }`}>
                                    {status?.plan || 'Free'}
                                </span>
                            </div>

                            {/* Active Coupon Badge & Expiry (if applied) */}
                            {status?.active_coupon_code && (
                                <div className="p-2 rounded-xl bg-emerald-500/10 border border-emerald-500/25 flex items-center justify-between text-[10px]">
                                    <div className="flex items-center gap-1.5 font-bold text-emerald-400">
                                        <Sparkles size={11} className="text-emerald-400" />
                                        <span>Coupon:</span>
                                        <span className="font-mono text-white font-extrabold">{status.active_coupon_code}</span>
                                    </div>
                                    {status?.coupon_expires_at && (
                                        <span className="text-[9px] text-emerald-300/90 font-mono font-medium">
                                            {(() => {
                                                const diff = new Date(status.coupon_expires_at).getTime() - Date.now();
                                                if (diff <= 0) return 'Expiring';
                                                const hrs = Math.floor(diff / 3600000);
                                                const mins = Math.floor((diff % 3600000) / 60000);
                                                return hrs > 0 ? `${hrs}h ${mins}m` : `${mins}m`;
                                            })()}
                                        </span>
                                    )}
                                </div>
                            )}

                            {status?.plan === 'free' && (
                                <Link href="/scraper" className="block w-full text-center py-2 bg-indigo-500/10 hover:bg-indigo-500 text-indigo-500 hover:text-white text-[10px] font-black tracking-widest rounded-lg transition-all border border-indigo-500/20 shadow-lg shadow-indigo-500/10">
                                    UPGRADE NOW
                                </Link>
                            )}

                            <div className="space-y-3 pt-1">
                                {/* Templates usage - Global visibility */}
                                <div className="space-y-1">
                                    <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase">
                                        <span>Templates Saved</span>
                                        <span>{isUnlimited ? `${status?.template_count || 0} / ∞ Unlimited` : `${status?.template_count || 0} / ${status?.max_templates || 1}`}</span>
                                    </div>
                                    <div className="h-1 w-full bg-foreground/5 rounded-full overflow-hidden">
                                        <div
                                            className="h-full bg-indigo-500 transition-all duration-1000"
                                            style={{ width: `${isUnlimited ? 100 : Math.min(100, ((status?.template_count || 0) / (status?.max_templates || 1)) * 100)}%` }}
                                        />
                                    </div>
                                </div>

                                {/* Campaigns Limit */}
                                <div className="space-y-1">
                                    <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase">
                                        <span>Daily Campaigns</span>
                                        <span>{isUnlimited ? `${status?.daily_campaign_count || 0} / ∞ Unlimited` : `${status?.daily_campaign_count || 0} / ${status?.max_daily_campaigns || 20}`}</span>
                                    </div>
                                    <div className="h-1 w-full bg-foreground/5 rounded-full overflow-hidden">
                                        <div
                                            className="h-full bg-blue-500 transition-all duration-1000"
                                            style={{ width: `${isUnlimited ? 100 : Math.min(100, ((status?.daily_campaign_count || 0) / (status?.max_daily_campaigns || 20)) * 100)}%` }}
                                        />
                                    </div>
                                </div>

                                {status?.plan !== 'free' && (
                                    <>
                                        {/* Keyword Limit */}
                                        <div className="space-y-1">
                                            <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase">
                                                <span>Keywords Searched</span>
                                                <span>{isUnlimited ? `${status?.daily_keyword_count || 0} / ∞ Unlimited` : `${status?.daily_keyword_count || 0} / ${status?.max_daily_keywords || 5}`}</span>
                                            </div>
                                            <div className="h-1 w-full bg-foreground/5 rounded-full overflow-hidden">
                                                <div
                                                    className="h-full bg-emerald-500 transition-all duration-1000"
                                                    style={{ width: `${isUnlimited ? 100 : Math.min(100, ((status?.daily_keyword_count || 0) / (status?.max_daily_keywords || 5)) * 100)}%` }}
                                                />
                                            </div>
                                        </div>

                                        {/* Scrape Power */}
                                        <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase pt-1">
                                            <span>Scrape Limit</span>
                                            <span className="text-foreground/60">{isUnlimited ? '∞ Unlimited' : `${status?.scrape_limit || 50} / search`}</span>
                                        </div>
                                    </>
                                )}
                            </div>

                            {/* View Full Plan Entitlements Submenu Trigger */}
                            <button
                                type="button"
                                onClick={() => setShowEntitlementsFlyout(!showEntitlementsFlyout)}
                                className="w-full flex items-center justify-between p-2 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] border border-white/10 hover:border-indigo-500/40 text-[11px] font-bold text-foreground transition-all cursor-pointer group shadow-xs"
                            >
                                <span className="flex items-center gap-1.5 text-indigo-400 group-hover:text-indigo-300">
                                    <Sparkles size={12} />
                                    <span>All Entitlements</span>
                                </span>
                                <span className="text-[10px] text-foreground/40 group-hover:text-foreground">
                                    {showEntitlementsFlyout ? 'Close βœ•' : 'Details β†’'}
                                </span>
                            </button>

                            <div className="pt-2 border-t border-border/50">
                                <div className="text-[10px] text-foreground/30 uppercase tracking-[0.2em] font-bold">Session</div>
                                <div className="text-xs text-foreground/60 font-semibold truncate mt-0.5">{user.username}</div>
                            </div>
                        </div>
                    )}
                </div>
            </nav>

            {/* Main Content Wrapper */}
            <main className={`
        flex-1 min-w-0 max-w-full transition-all duration-300 flex flex-col
        ${pathname === '/ai-assistant' ? 'h-screen max-h-screen overflow-hidden pt-16 md:pt-0' : 'min-h-screen overflow-x-hidden pt-16 md:pt-0'}
        ${isCollapsed ? "md:ml-20 md:max-w-[calc(100vw-5rem)]" : "md:ml-50 md:max-w-[calc(100vw-12.5rem)]"}
      `}>
                <div className="shrink-0">
                    <Header 
                        user={user} 
                        status={status} 
                        onOpenSupport={() => setShowSupportModal(true)} 
                        onOpenEntitlements={() => setShowEntitlementsFlyout(true)} 
                    />
                </div>
                <div className={pathname === '/ai-assistant' ? 'p-2 md:p-3 max-w-[110rem] mx-auto flex flex-col flex-1 min-h-0 w-full overflow-hidden' : 'p-4 md:p-8 max-w-7xl mx-auto flex-1 w-full min-w-0'}>
                    {children}
                </div>
            </main>

            {/* Full Plan Entitlements Modal Dialog (Outside Overflow Container) */}
            {showEntitlementsFlyout && (
                <div className="fixed inset-0 z-[80] flex items-end sm:items-center justify-center p-3 sm:p-4">
                    <div 
                        className="fixed inset-0 bg-black/75 backdrop-blur-sm transition-opacity"
                        onClick={() => setShowEntitlementsFlyout(false)}
                    />
                    <div className="relative my-auto w-full max-w-md bg-card border border-border/80 rounded-2xl p-5 shadow-2xl text-foreground space-y-4 animate-in fade-in zoom-in-95 duration-150 z-[81] 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">
                            <div className="flex items-center gap-2">
                                <div className="p-1.5 rounded-lg bg-indigo-500/10 text-indigo-400">
                                    <ShieldCheck size={16} />
                                </div>
                                <div>
                                    <div className="text-xs font-bold text-foreground">Full Plan Entitlements</div>
                                    <div className="text-[10px] text-foreground/50">Active Tier: <span className="text-indigo-400 font-bold uppercase">{status?.plan || 'Free'}</span></div>
                                </div>
                            </div>
                            <button 
                                type="button" 
                                onClick={() => setShowEntitlementsFlyout(false)}
                                className="text-foreground/40 hover:text-foreground p-1 rounded-lg hover:bg-foreground/5 transition-colors cursor-pointer"
                            >
                                <X size={15} />
                            </button>
                        </div>

                        {/* 10 Package Features Matrix */}
                        <div className="space-y-2 text-xs max-h-[55vh] overflow-y-auto custom-scrollbar pr-1">
                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">1. Telegram Accounts</span>
                                <span className="font-bold text-foreground text-[11px] font-mono">{isUnlimited ? '∞ Unlimited Allowed' : `${status?.max_accounts || 1} Allowed`}</span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">2. Daily Campaigns</span>
                                <span className="font-bold text-foreground text-[11px] font-mono">{isUnlimited ? `${status?.daily_campaign_count || 0} / ∞ Unlimited` : `${status?.daily_campaign_count || 0} / ${status?.max_daily_campaigns || 20}`}</span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">3. Scraper Power</span>
                                <span className="font-bold text-foreground text-[11px] font-mono">{isUnlimited ? '∞ Unlimited (1,500+ groups)' : `${status?.scrape_limit || 50} groups / search`}</span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">4. AI Keyword Suggestions</span>
                                <span className="font-bold text-foreground text-[11px] font-mono">{isUnlimited ? '100 per prompt (Natural Max)' : `${status?.ai_keyword_cap || 5} per prompt`}</span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">5. Saved Templates</span>
                                <span className="font-bold text-foreground text-[11px] font-mono">{isUnlimited ? `${status?.template_count || 0} / ∞ Unlimited` : `${status?.template_count || 0} / ${status?.max_templates || 1}`}</span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">6. Fleet Compare & Audit</span>
                                <span className={`font-bold text-[11px] ${status?.has_fleet_compare ? 'text-emerald-400' : 'text-foreground/30'}`}>
                                    {status?.has_fleet_compare ? 'βœ“ Unlocked' : 'πŸ”’ Locked (Basic+)'}
                                </span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">7. Delivery Speed Modes</span>
                                <span className="font-bold text-indigo-300 text-[11px] capitalize truncate max-w-[170px] text-right">
                                    {status?.allowed_speeds?.join(', ') || 'Balanced'}
                                </span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">8. Spintax Generator</span>
                                <span className={`font-bold text-[11px] ${status?.has_spintax ? 'text-emerald-400' : 'text-foreground/30'}`}>
                                    {status?.has_spintax ? 'βœ“ Unlocked' : 'πŸ”’ Locked (Basic+)'}
                                </span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">9. Bulk Join Minimizer</span>
                                <span className={`font-bold text-[11px] ${status?.has_fleet_compare ? 'text-emerald-400' : 'text-foreground/30'}`}>
                                    {status?.has_fleet_compare ? 'βœ“ Unlocked' : 'πŸ”’ Locked (Basic+)'}
                                </span>
                            </div>

                            <div className="p-2.5 rounded-xl bg-input/40 border border-border/60 flex items-center justify-between">
                                <span className="text-foreground/60 text-[11px]">10. Leads CSV Export</span>
                                <span className="font-bold text-emerald-400 text-[11px]">βœ“ Full Export</span>
                            </div>
                        </div>

                        {/* Upgrade CTA if not on highest plan */}
                        {status?.plan !== 'unlimited' && (
                            <button
                                type="button"
                                onClick={() => {
                                    setShowEntitlementsFlyout(false);
                                    window.dispatchEvent(new Event('open-monetization-modal'));
                                }}
                                className="w-full py-2.5 rounded-xl bg-indigo-500 hover:bg-indigo-600 text-white font-bold text-xs transition-colors shadow-md flex items-center justify-center gap-1.5 cursor-pointer"
                            >
                                <Sparkles size={13} />
                                <span>Upgrade Plan / Extend Limits</span>
                            </button>
                        )}
                    </div>
                </div>
            )}

            {/* Support Modal */}
            {showSupportModal && (
                <div className="fixed inset-0 z-[70] flex items-center justify-center p-4 overflow-y-auto">
                    <div 
                        className="fixed inset-0 bg-black/75 backdrop-blur-sm"
                        onClick={() => setShowSupportModal(false)}
                    />
                    <div className="relative my-auto w-full max-w-[480px] bg-card border border-border/80 rounded-2xl p-6 sm:p-7 shadow-2xl relative overflow-hidden animate-in fade-in zoom-in-95 duration-200">
                        <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-4 border-b border-border/60 mb-4">
                            <div className="flex items-center gap-2.5">
                                <div className="w-9 h-9 rounded-xl bg-indigo-500/15 border border-indigo-500/30 flex items-center justify-center text-indigo-400">
                                    <HelpCircle size={20} />
                                </div>
                                <div>
                                    <h3 className="font-black text-sm text-foreground">ArkiTel Support Desk</h3>
                                    <p className="text-[10px] text-foreground/40 font-semibold">Choose your preferred support channel</p>
                                </div>
                            </div>
                            <button 
                                onClick={() => setShowSupportModal(false)}
                                className="p-1.5 rounded-lg text-foreground/40 hover:text-foreground hover:bg-foreground/5 transition-colors cursor-pointer"
                            >
                                <X size={18} />
                            </button>
                        </div>

                        <div className="space-y-3">
                            {/* Email Mailto Link */}
                            <a
                                href={`mailto:${supportConfig.support_email || 'arkilostudios@gmail.com'}?subject=ArkiTel%20Support%20Request%20-%20${encodeURIComponent(user?.username || '')}`}
                                className="flex items-center justify-between p-3.5 rounded-2xl bg-white/[0.03] border border-white/5 hover:border-indigo-500/30 hover:bg-white/[0.05] transition-all group cursor-pointer"
                            >
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 rounded-xl bg-blue-500/10 text-blue-400 flex items-center justify-center">
                                        <Mail size={20} />
                                    </div>
                                    <div>
                                        <div className="text-xs font-bold text-white group-hover:text-indigo-400 transition-colors">Email Support</div>
                                        <div className="text-[10px] text-foreground/40 font-mono">{supportConfig.support_email || 'arkilostudios@gmail.com'}</div>
                                    </div>
                                </div>
                                <ExternalLink size={14} className="text-foreground/30 group-hover:text-white transition-colors" />
                            </a>

                            {/* WhatsApp Direct Link */}
                            <a
                                href={supportConfig.whatsapp_number.startsWith('http') ? supportConfig.whatsapp_number : 'https://wa.link/p0uv2l'}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center justify-between p-3.5 rounded-2xl bg-[#25D366]/5 border border-[#25D366]/20 hover:bg-[#25D366]/10 transition-all group cursor-pointer"
                            >
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 rounded-xl bg-[#25D366]/20 text-[#25D366] flex items-center justify-center">
                                        <MessageCircle size={20} />
                                    </div>
                                    <div>
                                        <div className="text-xs font-bold text-white group-hover:text-[#25D366] transition-colors">WhatsApp Live DM</div>
                                        <div className="text-[10px] text-foreground/40 font-mono">Chat on WhatsApp Desk</div>
                                    </div>
                                </div>
                                <ExternalLink size={14} className="text-foreground/30 group-hover:text-white transition-colors" />
                            </a>

                            {/* Telegram Support Link */}
                            <a
                                href={supportConfig.telegram_support.startsWith('http') ? supportConfig.telegram_support : `https://t.me/${supportConfig.telegram_support.replace('@', '')}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center justify-between p-3.5 rounded-2xl bg-[#229ED9]/5 border border-[#229ED9]/20 hover:bg-[#229ED9]/10 transition-all group cursor-pointer"
                            >
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 rounded-xl bg-[#229ED9]/20 text-[#229ED9] flex items-center justify-center">
                                        <Send size={20} />
                                    </div>
                                    <div>
                                        <div className="text-xs font-bold text-white group-hover:text-[#229ED9] transition-colors">Telegram Support</div>
                                        <div className="text-[10px] text-foreground/40 font-mono">@{supportConfig.telegram_support.replace('@', '')}</div>
                                    </div>
                                </div>
                                <ExternalLink size={14} className="text-foreground/30 group-hover:text-white transition-colors" />
                            </a>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}