import { Head, Link, usePage } from '@inertiajs/react';
import { type ReactNode, useState, useEffect, useMemo } from 'react';
import { Toaster, toast } from 'sonner';
import {
    BarChart3,
    Calendar,
    CalendarCheck,
    ClipboardList,
    Home,
    LogOut,
    Menu,
    Settings,
    X,
    RefreshCw,
    School,
    Users,
    BookOpen,
    FileSignature,
    CheckSquare,
    ChevronRight,
    ChevronLeft,
    Sun,
    Moon,
    Bell,
    Gamepad2,
    UserSquare,
    Vote,
    ScanLine,
    CalendarRange,
    AlertTriangle,
    GraduationCap,
    ClipboardCheck,
    ShieldCheck,
    Database,
    ContactRound,
    NotebookPen,
    Award,
    Activity,
    ExternalLink,
    Wallet,
} from 'lucide-react';
import { cn, getInitials } from '@/lib/utils';
import { claimVisualEffectsNotice, useVisualEffects } from '@/hooks/useVisualEffects';
import BrandLogo from '@/components/BrandLogo';
import VisualEffectsToggle from '@/components/VisualEffectsToggle';
import NotificationTimestamp from '@/components/NotificationTimestamp';
import type { PageProps } from '@/types';

interface Props {
    children: ReactNode;
    title?: string;
    backHref?: string;
    hideMobileDock?: boolean;
}

interface NavItem {
    href: string;
    label: string;
    icon: any;
    exact?: boolean;
    guruOnly?: boolean;
    siswaOnly?: boolean;
    adminOnly?: boolean;
    homeroomOnly?: boolean;
    staffOnly?: boolean;
    opensExternalApp?: boolean;
    sectionHeader?: string;
    sectionHeaderBadgeClass?: string;
    sectionHeaderLineClass?: string;
    subGroup?: string;
    subGroupBadgeClass?: string;
    subGroupBorderClass?: string;
    subGroupBgClass?: string;
    subGroupDividerClass?: string;
    subGroupActiveClass?: string;
}

interface NavCategory {
    label: string;
    icon?: any;
    guruOnly?: boolean;
    siswaOnly?: boolean;
    adminOnly?: boolean;
    homeroomOnly?: boolean;
    staffOnly?: boolean;
    items: NavItem[];
}

const topNavItem: NavItem = {
    href: '/dashboard',
    label: 'Dashboard',
    icon: Home,
};

const authenticatedHeaderHeight = 'h-16 sm:h-18';

const navCategories: NavCategory[] = [
    {
        label: 'Manajemen Data',
        icon: Database,
        adminOnly: true,
        items: [
            { href: '/classes', label: 'Data Kelas', icon: School },
            { href: '/students', label: 'Data Siswa', icon: Users },
            { href: '/teachers', label: 'Data Guru', icon: UserSquare },
            { href: '/sync', label: 'Sync Data', icon: RefreshCw, adminOnly: true },
            { href: '/activity', label: 'Log Aktivitas', icon: ShieldCheck },
        ],
    },
    {
        label: 'Kelas Saya',
        icon: GraduationCap,
        guruOnly: true,
        items: [
            { href: '/my-classes', label: 'Daftar Siswa', icon: Users, exact: true },
            { href: '/my-schedule', label: 'Jadwal Mengajar', icon: CalendarCheck },
            { href: '/booking-drafts', label: 'Rancangan Booking', icon: CalendarRange },
            { href: '/my-classes/setup', label: 'Plotting Kelas', icon: Settings },
        ],
    },
    {
        label: 'KBM & Jurnal',
        icon: ClipboardCheck,
        guruOnly: true,
        items: [
            { href: '/attendance', label: 'Kehadiran', icon: CalendarCheck, exact: true },
            { href: '/attendance/recap', label: 'Rekap Kehadiran', icon: BarChart3 },
            { href: '/journal', label: 'Jurnal Mengajar', icon: ClipboardList },
            { href: '/activity/students', label: 'Log Aktivitas Siswa', icon: Activity },
        ],
    },
    {
        label: 'Pembelajaran',
        icon: BookOpen,
        items: [
            { href: '/materials', label: 'Materi Pelajaran', icon: BookOpen },
            { href: '/assignments', label: 'Tugas Siswa', icon: FileSignature },
            { href: '/games', label: 'Arena UtiClass', icon: Gamepad2 },
            { href: '/grades', label: 'Penilaian & Koreksi', icon: CheckSquare, guruOnly: true },
            { href: '/initial-assessments', label: 'Asesmen Awal (OMR)', icon: ScanLine, guruOnly: true },
        ],
    },
    {
        label: 'Wali Kelas',
        icon: ShieldCheck,
        homeroomOnly: true,
        items: [
            {
                href: '/homeroom',
                label: 'Ringkasan Wali Kelas',
                icon: Home,
                homeroomOnly: true,
                exact: true,
                subGroup: 'Operasional Kelas',
                subGroupBadgeClass: 'text-emerald-500 dark:text-emerald-400 font-extrabold',
            },
            {
                href: '/homeroom/attendance',
                label: 'Absensi Harian',
                icon: CalendarCheck,
                homeroomOnly: true,
                subGroup: 'Operasional Kelas',
                subGroupBadgeClass: 'text-emerald-500 dark:text-emerald-400 font-extrabold',
            },
            {
                href: '/homeroom/officers', label: 'Pengurus Kelas', icon: Users,
                homeroomOnly: true, subGroup: 'Operasional Kelas',
                subGroupBadgeClass: 'text-emerald-500 dark:text-emerald-400 font-extrabold',
            },
            {
                href: '/homeroom/finances',
                label: 'Kas & Keuangan Kelas',
                icon: Wallet,
                homeroomOnly: true,
                subGroup: 'Operasional Kelas',
                subGroupBadgeClass: 'text-emerald-500 dark:text-emerald-400 font-extrabold',
            },
            {
                href: '/voting',
                label: 'Voting Kelas',
                icon: Users,
                homeroomOnly: true,
                subGroup: 'Operasional Kelas',
                subGroupBadgeClass: 'text-emerald-500 dark:text-emerald-400 font-extrabold',
            },
            {
                href: '/homeroom/student-profiles',
                label: 'Kelengkapan Biodata',
                icon: ContactRound,
                homeroomOnly: true,
                subGroup: 'Bimbingan & Siswa',
                subGroupBadgeClass: 'text-sky-500 dark:text-sky-400 font-extrabold',
            },
            {
                href: '/homeroom/violations',
                label: 'Catatan Pelanggaran',
                icon: AlertTriangle,
                homeroomOnly: true,
                subGroup: 'Bimbingan & Siswa',
                subGroupBadgeClass: 'text-sky-500 dark:text-sky-400 font-extrabold',
            },
            {
                href: '/homeroom/guidance',
                label: 'Pembinaan Wali Kelas',
                icon: NotebookPen,
                homeroomOnly: true,
                subGroup: 'Bimbingan & Siswa',
                subGroupBadgeClass: 'text-sky-500 dark:text-sky-400 font-extrabold',
            },
            {
                href: '/homeroom/recognitions',
                label: 'Apresiasi & Prestasi',
                icon: Award,
                homeroomOnly: true,
                subGroup: 'Bimbingan & Siswa',
                subGroupBadgeClass: 'text-sky-500 dark:text-sky-400 font-extrabold',
            },
        ],
    },
    {
        label: 'Voting',
        icon: Vote,
        siswaOnly: true,
        items: [
            { href: '/student/voting', label: 'Voting Kelas', icon: Vote, siswaOnly: true },
        ],
    },
    {
        label: 'Sistem',
        icon: Settings,
        items: [
            { href: '/settings', label: 'Pengaturan', icon: Settings },
            { href: '/school-holidays', label: 'Kalender Libur', icon: Calendar, adminOnly: true },
        ],
    },
];

export default function AuthenticatedLayout({ children, title, backHref, hideMobileDock = false }: Props) {
    const { auth, flash, currentAcademicYear, currentSemester } = usePage<PageProps>().props;
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [isScrollingDown, setIsScrollingDown] = useState(false);
    useVisualEffects();

    // Notification State
    const [unreadCount, setUnreadCount] = useState(0);
    const [notifications, setNotifications] = useState<any[]>([]);
    const [showNotifications, setShowNotifications] = useState(false);

    const [theme, setTheme] = useState<'light' | 'dark'>(() => {
        if (typeof window !== 'undefined') {
            const saved = localStorage.getItem('theme');
            if (saved === 'light' || saved === 'dark') {
                return saved;
            }
            return 'dark'; // Default to dark mode as approved
        }
        return 'dark';
    });

    const [isCollapsed, setIsCollapsed] = useState(() => {
        if (typeof window !== 'undefined') {
            return localStorage.getItem('sidebarCollapsed') === 'true';
        }
        return false;
    });

    useEffect(() => {
        localStorage.setItem('sidebarCollapsed', isCollapsed.toString());
    }, [isCollapsed]);

    useEffect(() => {
        if (window.location.pathname === '/settings') return;

        if (claimVisualEffectsNotice()) {
            toast.info('Mode performa otomatis aktif.', {
                id: 'visual-effects-notice',
                duration: 2500,
                closeButton: true,
            });
        }
    }, []);

    useEffect(() => {
        const scrollContainer = document.getElementById('main-scroll-container');
        const scrollTarget = scrollContainer || window;
        
        let lastScrollY = scrollContainer ? scrollContainer.scrollTop : window.scrollY;
        
        const handleScroll = () => {
            const currentScrollY = scrollContainer ? scrollContainer.scrollTop : window.scrollY;
            if (Math.abs(currentScrollY - lastScrollY) < 15) return;
            
            if (currentScrollY > lastScrollY && currentScrollY > 60) {
                setIsScrollingDown(true);
            } else {
                setIsScrollingDown(false);
            }
            lastScrollY = currentScrollY;
        };
        
        scrollTarget.addEventListener('scroll', handleScroll, { passive: true });
        return () => scrollTarget.removeEventListener('scroll', handleScroll);
    }, []);

    useEffect(() => {
        const root = window.document.documentElement;
        if (theme === 'dark') {
            root.classList.add('dark');
        } else {
            root.classList.remove('dark');
        }
        localStorage.setItem('theme', theme);
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prev => (prev === 'dark' ? 'light' : 'dark'));
    };

    const currentPath = typeof window !== 'undefined' ? window.location.pathname : '';

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('revealed');
                    }
                });
            },
            { threshold: 0.1, rootMargin: '0px 0px -30px 0px' }
        );

        const els = document.querySelectorAll('.reveal');
        els.forEach((el) => observer.observe(el));

        return () => observer.disconnect();
    }, [currentPath]);

    // Polling logic for Notifications
    useEffect(() => {
        const fetchNotifications = async () => {
            try {
                const response = await fetch('/notifications/unread', {
                    credentials: 'same-origin',
                    headers: {
                        Accept: 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });

                const redirectedToLogin = response.redirected
                    && new URL(response.url).pathname === '/login';

                if (response.status === 401 || redirectedToLogin) {
                    window.location.assign('/login');
                    return;
                }

                if (response.ok) {
                    const data = await response.json();
                    setUnreadCount(data.count);
                    setNotifications(data.notifications);
                }
            } catch (error) {
                console.error('Failed to fetch notifications:', error);
            }
        };

        // Initial fetch
        fetchNotifications();

        // Polling every 30 seconds
        const intervalId = setInterval(fetchNotifications, 30000);

        return () => clearInterval(intervalId);
    }, []);

    // Track which single category is currently expanded (null = all collapsed)
    const [openCategory, setOpenCategory] = useState<string | null>(null);

    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success, { id: 'success-' + Date.now() });
        }
        if (flash?.error) {
            toast.error(flash.error, { id: 'error-' + Date.now() });
        }
    }, [flash]);

    // Auto-open the category containing the current active route on mount
    useEffect(() => {
        const path = window.location.pathname;
        const activeCategory = navCategories.find(cat =>
            cat.items.some(item => path.startsWith(item.href))
        );
        if (activeCategory) {
            setOpenCategory(activeCategory.label);
        }
    }, []);

    // Pre-compute particle positions to avoid Math.random() on every render
    const particles = useMemo(() =>
        Array.from({ length: 12 }, (_, i) => ({
            left: `${(i * 8.3) % 100}%`,
            bottom: `-${(i * 2.1) % 10}%`,
            animationDuration: `${8 + (i * 1.7) % 12}s`,
            animationDelay: `${(i * 0.8) % 10}s`,
            width: `${2 + (i * 0.4) % 3}px`,
            height: `${2 + (i * 0.4) % 3}px`,
        })), []
    );

    // Accordion toggle: clicking the open category closes it; clicking another opens it & closes the rest
    const toggleCategory = (label: string) => {
        setOpenCategory(prev => (prev === label ? null : label));
    };

    // Filter categories based on user role
    const userRole = auth.user.role;
    const isStaff = userRole === 'guru' || userRole === 'admin';
    const isHomeroomTeacher = auth.user.is_homeroom_teacher;
    const activeSemesterLabel = currentSemester
        ? currentSemester.type === 'ganjil' ? 'Ganjil' : 'Genap'
        : '';
    const activeAcademicYearLabel = currentAcademicYear?.name ?? '';
    const compactAcademicPeriod = [
        activeAcademicYearLabel.replace(/20(\d\d)/g, '$1'),
        activeSemesterLabel,
    ].filter(Boolean).join(' · ');
    const fullAcademicPeriod = [
        activeAcademicYearLabel,
        activeSemesterLabel ? `Semester ${activeSemesterLabel}` : '',
    ].filter(Boolean).join(' · ');

    const filteredCategories = navCategories
        .map(category => {
            const filteredItems = category.items.filter(item => {
                if (item.adminOnly && userRole !== 'admin') return false;
                if (item.guruOnly && userRole !== 'guru') return false;
                if (item.siswaOnly && userRole !== 'siswa') return false;
                if (item.homeroomOnly && !isHomeroomTeacher) return false;
                if (item.staffOnly && userRole !== 'guru' && userRole !== 'admin') return false;
                if (userRole === 'admin' && category.label === 'Pembelajaran' && !item.staffOnly && !item.adminOnly) return false;
                return true;
            });

            return { ...category, items: filteredItems };
        })
        .filter(category => {
            if (category.items.length === 0) return false;
            if (category.adminOnly && userRole !== 'admin') return false;
            if (category.guruOnly && userRole !== 'guru') return false;
            if (category.siswaOnly && userRole !== 'siswa') return false;
            if (category.homeroomOnly && !isHomeroomTeacher) return false;
            if (category.staffOnly && userRole !== 'guru' && userRole !== 'admin') return false;
            // Admin doesn't see teaching-related categories
            if (userRole === 'admin' && !category.adminOnly && !category.staffOnly && !category.items.some(item => item.staffOnly) && category.label !== 'Sistem') return false;
            return true;
        });

    return (
        <>
            <Head title={title} />
            <div className="flex h-dvh relative bg-transparent overflow-hidden">
                <style dangerouslySetInnerHTML={{__html: `
                    .reveal {
                        opacity: 0;
                        transform: translateY(30px) scale(0.95);
                        transition: all 0.8s cubic-bezier(0.16, 1, 0.3, 1);
                    }
                    .reveal.revealed {
                        opacity: 1;
                        transform: translateY(0) scale(1);
                    }
                    .reveal-delay-1 { transition-delay: 100ms; }
                    .reveal-delay-2 { transition-delay: 200ms; }
                    .reveal-delay-3 { transition-delay: 300ms; }
                    .reveal-delay-4 { transition-delay: 400ms; }
                    .reveal-delay-5 { transition-delay: 500ms; }
                    .reveal-delay-6 { transition-delay: 600ms; }
                    .reveal-delay-7 { transition-delay: 700ms; }
                    .reveal-delay-8 { transition-delay: 800ms; }
                    .reveal-delay-9 { transition-delay: 900ms; }
                    .reveal-delay-10 { transition-delay: 1000ms; }
                `}} />
                {/* Unified Aurora Mesh Background */}
                <div className="aurora-mesh fixed inset-0 z-0 pointer-events-none">
                    <div className="aurora-orb-accent" />

                    {/* Floating particles */}
                    {particles.map((p, i) => (
                        <div
                            key={i}
                            className="aurora-particle"
                            style={{
                                left: p.left,
                                bottom: p.bottom,
                                animationDuration: p.animationDuration,
                                animationDelay: p.animationDelay,
                                width: p.width,
                                height: p.height,
                            }}
                        />
                    ))}
                </div>

                {/* Subtle dot grid overlay */}
                <div
                    className="fixed inset-0 z-1 opacity-10 dark:opacity-[0.07] pointer-events-none"
                    style={{
                        backgroundImage: 'radial-gradient(currentColor 1px, transparent 1px)',
                        backgroundSize: '24px 24px',
                    }}
                />
                {/* Sidebar overlay (mobile) */}
                <div
                    className={cn(
                        "fixed inset-0 z-40 bg-black/50 lg:hidden transition-opacity duration-300 ease-in-out",
                        sidebarOpen ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none"
                    )}
                    onClick={() => setSidebarOpen(false)}
                />

                {/* Sidebar */}
                <aside
                    className={cn(
                        'app-shell-surface app-shell-sidebar fixed inset-y-0 left-0 z-50 flex h-dvh flex-col border-r border-border bg-surface/80 backdrop-blur-xl transition-all duration-300 ease-in-out lg:sticky lg:top-0 lg:translate-x-0',
                        sidebarOpen ? 'translate-x-0' : '-translate-x-full',
                        isCollapsed ? 'w-20' : 'w-64'
                    )}
                >
                    {/* Floating Toggle Button (Desktop Only) */}
                    <button
                        className="hidden lg:flex absolute -right-3.5 top-6 h-7 w-7 items-center justify-center rounded-full border border-border bg-surface shadow-md text-text-muted hover:text-text hover:bg-surface-hover transition-all z-50"
                        onClick={() => setIsCollapsed(!isCollapsed)}
                    >
                        {isCollapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
                    </button>

                    {/* Logo */}
                    <div className={cn(authenticatedHeaderHeight, 'flex shrink-0 items-center justify-between border-b border-border px-4')}>
                        <div className="flex items-center gap-3 overflow-hidden">
                            <BrandLogo
                                alt="Ikon UtiClass"
                                className="h-8 w-8 shrink-0 object-contain drop-shadow-md"
                            />
                            {!isCollapsed && (
                                <span className="truncate text-lg font-extrabold tracking-tight text-slate-900 dark:text-white">
                                    UtiClass
                                </span>
                            )}
                        </div>
                        <button
                            className="lg:hidden shrink-0"
                            onClick={() => setSidebarOpen(false)}
                        >
                            <X className="h-5 w-5 text-text-muted" />
                        </button>
                    </div>

                    {/* Navigation — scrolls independently inside the locked sidebar */}
                    <nav className={cn("flex-1 overflow-y-auto p-4 scrollbar-thin", isCollapsed ? "space-y-2" : "space-y-4")}>
                        {/* Standalone Top Item: Dashboard */}
                        {(() => {
                            const isDashboardActive = currentPath === '/dashboard' || currentPath === '/';
                            const DashboardIcon = topNavItem.icon;
                            return (
                                <div className="mb-2">
                                    <Link
                                        href={topNavItem.href}
                                        title={isCollapsed ? topNavItem.label : undefined}
                                        onClick={() => setSidebarOpen(false)}
                                        className={cn(
                                            'flex items-center rounded-lg py-2.5 text-sm font-semibold transition-all overflow-hidden',
                                            isCollapsed ? 'justify-center px-0' : 'gap-3 px-3',
                                            isDashboardActive
                                                ? 'bg-primary-500/15 text-primary-500 shadow-sm ring-1 ring-primary-500/20'
                                                : 'text-text-muted hover:bg-surface-hover hover:text-text',
                                        )}
                                    >
                                        <DashboardIcon className="h-4.5 w-4.5 shrink-0 text-primary-400" />
                                        {!isCollapsed && <span className="truncate">{topNavItem.label}</span>}
                                    </Link>
                                </div>
                            );
                        })()}

                        {/* Categories Accordions */}
                        {filteredCategories.map((category) => {
                            const isOpen = openCategory === category.label;
                            const CategoryIcon = category.icon;
                            return (
                                <div key={category.label} className={cn(!isCollapsed && "space-y-1")}>
                                    {/* Category Header */}
                                    {!isCollapsed && (
                                        <button
                                            onClick={() => toggleCategory(category.label)}
                                            className="flex w-full items-center justify-between px-3 py-1.5 text-xs font-semibold uppercase tracking-wider text-text-muted hover:text-text transition-colors group"
                                        >
                                            <div className="flex items-center gap-2 truncate">
                                                {CategoryIcon && <CategoryIcon className="h-3.5 w-3.5 text-primary-400/80 group-hover:text-primary-400 shrink-0 transition-colors" />}
                                                <span className="truncate">{category.label}</span>
                                            </div>
                                            <ChevronRight
                                                className={cn(
                                                    'h-3 w-3 shrink-0 transition-transform duration-200',
                                                    isOpen && 'rotate-90',
                                                )}
                                            />
                                        </button>
                                    )}

                                    {/* Category Items — animated accordion */}
                                    <div
                                        className={cn(
                                            'grid transition-[grid-template-rows] duration-200 ease-in-out',
                                            isOpen || isCollapsed ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',
                                        )}
                                    >
                                        <div className="overflow-hidden">
                                            <div className={cn("space-y-0.5", !isCollapsed && "pt-0.5")}>
                                                {(() => {
                                                    type SubGroupChunk = {
                                                        subGroup?: string;
                                                        badgeClass?: string;
                                                        borderClass?: string;
                                                        bgClass?: string;
                                                        dividerClass?: string;
                                                        activeClass?: string;
                                                        items: NavItem[];
                                                    };

                                                    const chunks: SubGroupChunk[] = [];
                                                    for (const item of category.items) {
                                                        const lastChunk = chunks[chunks.length - 1];
                                                        if (lastChunk && lastChunk.subGroup === item.subGroup) {
                                                            lastChunk.items.push(item);
                                                        } else {
                                                            chunks.push({
                                                                subGroup: item.subGroup,
                                                                badgeClass: item.subGroupBadgeClass,
                                                                borderClass: item.subGroupBorderClass,
                                                                bgClass: item.subGroupBgClass,
                                                                dividerClass: item.subGroupDividerClass,
                                                                activeClass: item.subGroupActiveClass,
                                                                items: [item],
                                                            });
                                                        }
                                                    }

                                                    const path = typeof window !== 'undefined' ? window.location.pathname : '';
                                                    const isPrefixMatch = (p: string, prefix: string) => p === prefix || p.startsWith(prefix + '/');
                                                    const allNavItems = navCategories.flatMap(c => c.items);
                                                    const matchingItems = allNavItems.filter(i => isPrefixMatch(path, i.href));
                                                    const activeNavItem = matchingItems.length > 0
                                                        ? matchingItems.reduce((a, b) => (a.href.length > b.href.length ? a : b))
                                                        : null;

                                                    const renderItemLink = (item: NavItem, isIndented = false, groupActiveClass?: string) => {
                                                        const isActive = activeNavItem ? activeNavItem.href === item.href : (item.exact ? path === item.href : path.startsWith(item.href));

                                                        return (
                                                            <Link
                                                                key={item.href}
                                                                href={item.href}
                                                                target={item.opensExternalApp ? '_blank' : undefined}
                                                                rel={item.opensExternalApp ? 'noopener noreferrer' : undefined}
                                                                title={isCollapsed ? item.label : undefined}
                                                                onClick={() => setSidebarOpen(false)}
                                                                className={cn(
                                                                    'flex items-center transition-colors overflow-hidden',
                                                                    isCollapsed
                                                                        ? 'justify-center rounded-lg py-2 px-0 text-sm font-medium'
                                                                        : isIndented
                                                                            ? 'gap-2.5 rounded-md py-1.5 px-2.5 text-xs font-medium'
                                                                            : 'gap-2.5 rounded-lg py-1.5 px-2.5 text-xs font-medium',
                                                                    isActive
                                                                        ? isIndented && groupActiveClass
                                                                            ? groupActiveClass
                                                                            : 'bg-primary-500/15 text-primary-500 shadow-sm ring-1 ring-primary-500/20 font-semibold'
                                                                        : 'text-text-muted hover:bg-surface-hover hover:text-text',
                                                                )}
                                                            >
                                                                <item.icon className={cn("shrink-0", !isCollapsed ? "h-3.5 w-3.5" : "h-4.5 w-4.5")} />
                                                                {!isCollapsed && <span className="truncate">{item.label}</span>}
                                                            </Link>
                                                        );
                                                    };

                                                    return chunks.map((chunk, chunkIdx) => {
                                                        if (isCollapsed) {
                                                            return (
                                                                <div key={chunkIdx} className="space-y-0.5">
                                                                    {chunk.items.map(item => renderItemLink(item, false))}
                                                                </div>
                                                            );
                                                        }

                                                        if (!chunk.subGroup) {
                                                            return (
                                                                <div
                                                                    key={chunkIdx}
                                                                    className="ml-3.5 my-1 pl-2.5 border-l-2 border-border/70 dark:border-border/50 space-y-0.5 rounded-r-lg"
                                                                >
                                                                    {chunk.items.map(item => renderItemLink(item, true))}
                                                                </div>
                                                            );
                                                        }

                                                        return (
                                                            <div
                                                                key={chunk.subGroup}
                                                                className={cn(
                                                                    "ml-3.5 my-1 pl-2.5 border-l-2 space-y-0.5 rounded-r-lg",
                                                                    chunk.borderClass ?? "border-border/70 dark:border-border/50",
                                                                    chunk.bgClass
                                                                )}
                                                            >
                                                                <div className="flex items-center gap-2 px-1 pt-1.5 pb-0.5 select-none">
                                                                    <span className={cn(
                                                                        "text-[9px] font-bold uppercase tracking-wider",
                                                                        chunk.badgeClass ?? "text-text-muted"
                                                                    )}>
                                                                        {chunk.subGroup}
                                                                    </span>
                                                                    <div className={cn(
                                                                        "flex-1 h-px",
                                                                        chunk.dividerClass ?? "bg-border/50 dark:bg-border/30"
                                                                    )} />
                                                                </div>
                                                                <div className="space-y-0.5">
                                                                    {chunk.items.map(item => renderItemLink(item, true, chunk.activeClass))}
                                                                </div>
                                                            </div>
                                                        );
                                                    });
                                                })()}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </nav>

                    {/* User section */}
                    <div className="border-t border-border p-4">
                        <div className={cn("flex items-center", isCollapsed ? "justify-center" : "gap-3")}>
                            <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary-500/20 text-xs font-bold text-primary-300 shrink-0">
                                {getInitials(auth.user.name)}
                            </div>
                            {!isCollapsed && (
                                <>
                                    <div className="flex-1 truncate">
                                        <p className="truncate text-sm font-medium">
                                            {auth.user.name}
                                        </p>
                                        <p className="text-xs text-text-muted capitalize">
                                            {auth.user.role}
                                        </p>
                                    </div>
                                    <Link
                                        href="/logout"
                                        method="post"
                                        as="button"
                                        className="rounded-lg p-2 text-text-muted transition-colors hover:bg-surface-hover hover:text-rose-400 shrink-0"
                                        title="Keluar"
                                    >
                                        <LogOut className="h-4 w-4" />
                                    </Link>
                                </>
                            )}
                        </div>
                    </div>
                </aside>

                {/* Main content */}
                <main id="main-scroll-container" className="flex-1 relative z-10 flex flex-col min-w-0 h-dvh overflow-y-auto overflow-x-hidden">
                    {/* Top bar */}
                    <header className={cn(authenticatedHeaderHeight, 'app-shell-surface app-shell-header sticky top-0 z-30 flex shrink-0 items-center justify-between gap-2 border-b border-border bg-surface/80 px-3 backdrop-blur-xl sm:px-6')}>
                        <div className="flex min-w-0 flex-1 items-center gap-1 sm:gap-3">
                            <button
                                className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-border/60 bg-surface-hover/60 text-text-muted shadow-sm shadow-black/10 transition-all duration-150 hover:border-border hover:bg-surface-hover hover:text-text-light active:scale-95 lg:hidden"
                                onClick={() => setSidebarOpen(true)}
                                aria-label="Buka menu"
                            >
                                <Menu className="h-6 w-6" strokeWidth={2.25} />
                            </button>
                            {backHref && (
                                <Link
                                    href={backHref}
                                    className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/50 bg-surface text-text-muted transition-colors hover:bg-surface-hover hover:text-text"
                                    aria-label="Kembali"
                                >
                                    <ChevronLeft className="h-5 w-5" />
                                </Link>
                            )}
                            <div className="flex min-w-0 flex-col items-start gap-0.5 sm:flex-row sm:items-center sm:gap-2">
                                {title && (
                                    <h1 className="max-w-full truncate text-lg font-extrabold leading-tight tracking-tight text-text-light sm:text-xl lg:text-2xl">
                                        {title}
                                    </h1>
                                )}
                                {fullAcademicPeriod && (
                                    <span
                                        className="inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full border border-border/60 bg-surface-hover/70 px-2 text-[10px] font-bold leading-none text-text-muted shadow-sm sm:h-7 sm:px-2.5 sm:text-xs"
                                        aria-label={`Periode aktif: ${fullAcademicPeriod}`}
                                        title={`Periode aktif: ${fullAcademicPeriod}`}
                                    >
                                        <span
                                            className="h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.65)]"
                                            aria-hidden="true"
                                        />
                                        <span className="sm:hidden">{compactAcademicPeriod}</span>
                                        <span className="hidden sm:inline">{fullAcademicPeriod}</span>
                                    </span>
                                )}
                            </div>
                        </div>

                        <div className="flex shrink-0 items-center gap-1 sm:gap-2">
                            {isStaff && (
                                <a
                                    href="/utiplay/launch"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="inline-flex items-center gap-1.5 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-2.5 py-1.5 text-xs font-semibold text-emerald-600 hover:bg-emerald-500/20 dark:border-emerald-400/30 dark:bg-emerald-400/10 dark:text-emerald-400 dark:hover:bg-emerald-400/20 transition-all shadow-sm active:scale-95"
                                    title="Buka Arena UtiPlay di tab baru"
                                >
                                    <Gamepad2 className="h-4 w-4" />
                                    <span className="hidden sm:inline">UtiPlay</span>
                                    <ExternalLink className="h-3 w-3 opacity-70" />
                                </a>
                            )}

                            <VisualEffectsToggle />

                            {/* Theme Toggle Button */}
                            <button
                                onClick={toggleTheme}
                                className="rounded-lg p-2 text-text-muted hover:bg-surface-hover hover:text-text transition-colors"
                                title={theme === 'dark' ? 'Aktifkan Mode Terang' : 'Aktifkan Mode Gelap'}
                            >
                                {theme === 'dark' ? (
                                    <Sun className="h-5 w-5 text-amber-400" />
                                ) : (
                                    <Moon className="h-5 w-5" />
                                )}
                            </button>

                            {/* Notifications Dropdown */}
                            <div className="relative">
                                <button
                                    onClick={() => setShowNotifications(!showNotifications)}
                                    className="relative rounded-lg p-2 text-text-muted hover:bg-surface-hover hover:text-text transition-colors"
                                    title="Notifikasi"
                                    aria-label="Notifikasi"
                                    aria-expanded={showNotifications}
                                >
                                    <Bell className="h-5 w-5" />
                                    {unreadCount > 0 && (
                                        <span className="absolute top-1.5 right-1.5 flex h-3 w-3 items-center justify-center rounded-full bg-rose-500 text-[8px] font-bold text-white shadow-sm ring-2 ring-surface">
                                            {unreadCount > 9 ? '9+' : unreadCount}
                                        </span>
                                    )}
                                </button>

                                {showNotifications && (
                                    <div className="absolute right-0 top-full mt-2 w-72 max-w-[calc(100vw-4rem)] sm:w-80 sm:max-w-none overflow-hidden rounded-xl border border-border bg-surface shadow-xl ring-1 ring-black/5 dark:ring-white/5 origin-top-right z-50">
                                        <div className="flex items-center justify-between border-b border-border bg-surface-hover/50 px-4 py-3">
                                            <h3 className="font-semibold text-text">Notifikasi</h3>
                                            <Link href={route('notifications.index')} className="text-xs font-medium text-primary-500 hover:text-primary-600" onClick={() => setShowNotifications(false)}>
                                                Lihat Semua
                                            </Link>
                                        </div>
                                        <div className="max-h-[60vh] overflow-y-auto overscroll-contain">
                                            {notifications.length > 0 ? (
                                                <div className="divide-y divide-border">
                                                    {notifications.map((notif) => (
                                                        <Link
                                                            key={notif.id}
                                                            href={notif.data.url}
                                                            onClick={() => {
                                                                setShowNotifications(false);
                                                                // Optimistically decrease count when clicked (it remains unread in db until read-all or explicit read, but index page will handle it)
                                                                // Real app might want to POST to /read endpoint here
                                                                fetch(`/notifications/${notif.id}/read`, {
                                                                    method: 'POST',
                                                                    headers: {
                                                                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
                                                                    },
                                                                });
                                                            }}
                                                            className="flex flex-col gap-1 p-4 transition-colors hover:bg-surface-hover hover:cursor-pointer"
                                                        >
                                                            <div className="flex items-start justify-between gap-2">
                                                                <p className="text-sm font-semibold text-text leading-tight">{notif.data.title}</p>
                                                                <span title="Belum dibaca" className="shrink-0 text-[10px] text-text-muted mt-0.5">
                                                                    Baru
                                                                </span>
                                                            </div>
                                                            <p className="text-xs text-text-muted line-clamp-2 leading-relaxed">
                                                                {notif.data.message}
                                                            </p>
                                                            <NotificationTimestamp notification={notif} className="mt-1" />
                                                        </Link>
                                                    ))}
                                                </div>
                                            ) : (
                                                <div className="flex flex-col items-center justify-center p-8 text-center">
                                                    <div className="rounded-full bg-surface-hover p-3 mb-2">
                                                        <Bell className="h-6 w-6 text-text-muted" />
                                                    </div>
                                                    <p className="text-sm font-medium text-text">Tidak ada notifikasi baru</p>
                                                    <p className="text-xs text-text-muted mt-1">Anda sudah melihat semuanya.</p>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>

                            {/* Mobile Logout Button */}
                            <Link
                                href="/logout"
                                method="post"
                                as="button"
                                className="lg:hidden rounded-lg p-2 text-text-muted hover:bg-surface-hover hover:text-rose-400 transition-colors"
                                title="Keluar"
                            >
                                <LogOut className="h-5 w-5" />
                            </Link>
                        </div>
                    </header>

                    {/* Sonner Toaster */}
                    <Toaster richColors position="top-right" theme={theme === 'dark' ? 'dark' : 'light'} style={{ zIndex: 99999 }} />

                    {/* Page content */}
                    <div className={cn(
                        "p-4 sm:p-6 lg:p-8",
                        userRole === 'guru' && !hideMobileDock ? "mobile-dock-content pb-24 lg:pb-8" : ""
                    )}>
                        {children}
                    </div>
                </main>

                {/* Floating Bottom Navigation Dock (Visible only for teachers on mobile/tablet) */}
                {userRole === 'guru' && !hideMobileDock && (
                    <div className="app-mobile-dock-shell mobile-safe-dock fixed bottom-5 left-0 right-0 z-30 lg:hidden flex justify-center px-4 transition-all duration-300 pointer-events-none">
                        <div className={cn(
                            "app-mobile-dock flex items-center justify-between rounded-full border border-white/20 dark:border-white/10 bg-surface/50 dark:bg-surface/40 backdrop-blur-xl shadow-lg dark:shadow-[0_8px_30px_rgba(0,0,0,0.6)] transition-all duration-300 ease-in-out pointer-events-auto",
                            isScrollingDown 
                                ? "h-13 w-64 px-4 gap-2" 
                                : "h-17 w-full max-w-md px-2"
                        )}>
                            {[
                                { href: '/dashboard', label: 'Beranda', icon: Home },
                                { href: '/my-schedule', label: 'Jadwal', icon: CalendarCheck },
                                { href: '/materials', label: 'Materi', icon: BookOpen },
                                { href: '/assignments', label: 'Tugas', icon: FileSignature },
                                { href: '/games', label: 'Arena', icon: Gamepad2 }
                            ].map((item) => {
                                const Icon = item.icon;
                                const isActive = item.href === '/dashboard'
                                    ? currentPath === '/dashboard'
                                    : currentPath.startsWith(item.href);

                                return (
                                    <Link
                                        key={item.href}
                                        href={item.href}
                                        className="group relative flex flex-1 flex-col items-center justify-center h-full transition-all duration-300"
                                    >
                                        {/* Active Indicator Pill */}
                                        <div className={cn(
                                            "absolute inset-0 m-auto rounded-full transition-all duration-300",
                                            isScrollingDown ? "h-9 w-9" : "h-13 w-18",
                                            isActive ? "bg-primary-500/20 scale-100 opacity-100" : "scale-50 opacity-0"
                                        )} />
                                        
                                        <Icon className={cn(
                                            "relative z-10 transition-all duration-300",
                                            isActive ? "h-6 w-6 text-primary-400" : "h-5 w-5 text-text-muted group-hover:text-text-light",
                                            isScrollingDown && !isActive ? "h-5.5 w-5.5" : ""
                                        )} />
                                        
                                        <span className={cn(
                                            "relative z-10 text-[10px] font-medium transition-all duration-300 origin-bottom whitespace-nowrap",
                                            isActive ? "text-primary-400 font-bold" : "text-text-muted group-hover:text-text-light",
                                            isScrollingDown 
                                                ? "max-h-0 opacity-0 scale-0 pointer-events-none mt-0 overflow-hidden" 
                                                : "max-h-4 opacity-100 mt-0.5 scale-100"
                                        )}>
                                            {item.label}
                                        </span>
                                    </Link>
                                );
                            })}
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}
