import ApplicationLogo from "@/Components/ApplicationLogo";
import Dropdown from "@/Components/Dropdown";
import { Link, usePage } from "@inertiajs/react";
import { useState, useEffect, useMemo, useRef } from "react";
import { usePermissions } from "@/lib/usePermissions";
import {
    LayoutDashboard,
    Users,
    ShieldCheck,
    UsersRound,
    Contact,
    Briefcase,
    Folders,
    Tags,
    CheckSquare,
    LogOut,
    UserCircle,
    Menu,
    X,
    Bell,
    Key,
    Shield,
    ChevronLeft,
    ChevronRight,
    Sun,
    Moon,
    CheckCircle2,
    Activity,
    BarChart3,
    DollarSign,
    Calendar,
    AlertCircle,
    Search,
} from "lucide-react";
import { Toaster, toast } from "sonner";
import { cn } from "@/lib/utils";
import QuickActionsFAB from "@/Pages/Execution/Planning/Partials/QuickActionsFAB";
import CommandPalette from "@/Components/CommandPalette";
import useTranslation from "@/Hooks/useTranslation";

// ─── Cookie helpers ────────────────────────────────────────────────────────────
function getCookie(name) {
    const match = document.cookie.match(
        new RegExp("(^| )" + name + "=([^;]+)"),
    );
    return match ? match[2] : null;
}
function setCookie(name, value, days = 365) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${name}=${value}; expires=${expires}; path=/`;
}

// ─── Tooltip wrapper for collapsed items ──────────────────────────────────────
function Tooltip({ label, children, show }) {
    if (!show) return children;
    return (
        <div className="relative group/tooltip">
            {children}
            <div
                className="pointer-events-none absolute left-full top-1/2 -translate-y-1/2 ml-3 z-50
                            opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-150"
            >
                <div
                    className="bg-slate-900 text-white text-xs font-bold px-3 py-1.5 rounded-lg
                                shadow-xl border border-slate-700 whitespace-nowrap"
                >
                    {label}
                    <div
                        className="absolute right-full top-1/2 -translate-y-1/2 border-4
                                    border-transparent border-r-slate-900"
                    />
                </div>
            </div>
        </div>
    );
}

export default function AuthenticatedLayout({ header, children }) {
    const user = usePage().props.auth.user;
    const { can } = usePermissions();
    const { t, locale } = useTranslation();

    const translateStatus = (statusName) => {
        if (!statusName) return "";
        const key = `status_task_assignments.${statusName.toLowerCase()}`;
        const translated = t(key);
        return translated === key ? statusName : translated;
    };

    // ── Sidebar state – initialise from cookie ────────────────────────────────
    const [isSidebarOpen, setIsSidebarOpen] = useState(() => {
        const saved = getCookie("sidebar_open");
        return saved === null ? true : saved === "true";
    });
    const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
    const [planningDropdownOpen, setPlanningDropdownOpen] = useState(false);
    const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false);
    const planningDropdownRef = useRef(null);

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (planningDropdownRef.current && !planningDropdownRef.current.contains(event.target)) {
                setPlanningDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    // ── Theme state – initialise from cookie ──────────────────────────────────
    const [theme, setTheme] = useState(() => {
        return getCookie("theme") || "light";
    });

    // Track which items are manually expanded/collapsed
    const [expandedItems, setExpandedItems] = useState(() => {
        try {
            const saved = getCookie("sidebar_expanded");
            return saved ? JSON.parse(decodeURIComponent(saved)) : {};
        } catch (e) {
            return {};
        }
    });

    const toggleExpanded = (label) => {
        setExpandedItems((prev) => {
            // Accordion mode: if opening a new one, close all others.
            // If clicking the currently open one, toggle it.
            const isCurrentlyOpen = prev[label];
            const next = isCurrentlyOpen ? {} : { [label]: true };

            setCookie(
                "sidebar_expanded",
                encodeURIComponent(JSON.stringify(next)),
            );
            return next;
        });
    };

    // Toggle theme and persist
    const toggleTheme = () => {
        const newTheme = theme === "light" ? "dark" : "light";
        setTheme(newTheme);
        setCookie("theme", newTheme);
        if (newTheme === "dark") {
            document.documentElement.classList.add("dark");
        } else {
            document.documentElement.classList.remove("dark");
        }
    };

    // Persist to cookie whenever it changes
    useEffect(() => {
        setCookie("sidebar_open", String(isSidebarOpen));
    }, [isSidebarOpen]);

    const { flash } = usePage().props;
    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success, {
                className:
                    "rounded-[20px] bg-[#0c1527] border-slate-800 text-white font-black uppercase text-[10px] tracking-widest p-5 shadow-2xl",
            });
        }
        if (flash?.error) {
            toast.error(flash.error, {
                className:
                    "rounded-[20px] bg-red-600 border-red-500 text-white font-black uppercase text-[10px] tracking-widest p-5 shadow-2xl",
            });
        }
    }, [flash]);

    // ── Nav definitions ───────────────────────────────────────────────────────
    const { today_tasks_count, draft_tasks_count, active_users_count, unplanned_tasks_count } =
        usePage().props.auth;

    const navItems = useMemo(
        () => [
            {
                label: t('sidebar.dashboard'),
                route: "dashboard",
                active: "dashboard",
                icon: LayoutDashboard,
                can: true,
            },
            {
                label: t('sidebar.planning'),
                icon: Calendar,
                can: can("view_planning") || can("manage_tasks"),
                active: "planning.*",
                subItems: [
                    {
                        label: t('sidebar.my_planning'),
                        route: "planning.my",
                        active: "planning.my",
                        badge: today_tasks_count,
                        can: can("view_planning"),
                    },
                    {
                        label: t('sidebar.my_plannings'),
                        route: "planning.my-plannings",
                        active: "planning.my-plannings",
                        can: can("view_planning"),
                    },
                    {
                        label: t('sidebar.my_unplanned_tasks'),
                        route: "planning.my-unplanned-tasks",
                        active: "planning.my-unplanned-tasks",
                        can: can("view_planning"),
                        badge: unplanned_tasks_count,
                    },
                    {
                        label: t('sidebar.planned_tasks_logs'),
                        route: "planned-tasks.index",
                        active: "planned-tasks.index",
                        can: can("view_planning") || can("manage_tasks"),
                    },
                    {
                        label: t('sidebar.team_planning'),
                        route: "planning.index",
                        active: "planning.index",
                        can: can("view_planning") && can("manage_tasks"),
                    },
                    {
                        label: t('sidebar.timeline'),
                        route: "planning.timeline",
                        active: "planning.timeline",
                        can: can("view_planning") && can("manage_tasks"),
                    },
                    {
                        label: t('sidebar.draft_tasks'),
                        route: "planning.drafts",
                        active: "planning.drafts",
                        badge: draft_tasks_count,
                        can: can("view_planning") && can("manage_tasks"),
                    },
                ],
            },
            {
                label: t('sidebar.operations'),
                icon: CheckSquare,
                can: can("view_tasks") || can("manage_tasks") || can("view_planning"),
                active: ["tasks.*", "who-does-what", "work-logs.*"],
                subItems: [
                    { label: t('sidebar.tasks'), route: "tasks.index", active: "tasks.*", can: can("view_tasks") },
                    {
                        label: t('sidebar.who_does_what'),
                        route: "who-does-what",
                        active: "who-does-what",
                        badge: active_users_count,
                        can: can("manage_tasks"),
                    },
                    {
                        label: t('sidebar.work_logs'),
                        route: "work-logs.index",
                        active: "work-logs.*",
                        can: can("view_tasks") || can("view_planning"),
                    },
                ],
            },
            {
                label: t('sidebar.contacts'),
                icon: Contact,
                can: can("view_contacts"),
                active: "contacts.*",
                subItems: [
                    {
                        label: t('sidebar.contacts_list'),
                        route: "contacts.index",
                        active: "contacts.index",
                    },
                ],
            },
            {
                label: t('sidebar.business'),
                icon: Briefcase,
                can: can("view_affaires") || can("view_projects"),
                active: ["affaires.*", "projects.*"],
                subItems: [
                    {
                        label: t('sidebar.affaires'),
                        route: "affaires.index",
                        active: "affaires.*",
                        can: can("view_affaires"),
                    },
                    {
                        label: t('sidebar.projects'),
                        route: "projects.index",
                        active: "projects.*",
                    },
                ],
            },
            {
                label: t('sidebar.analysis'),
                icon: BarChart3,
                can: can("view_rapports") || can("view_planning"),
                active: ["rapports.*", "work-logs.index"],
                subItems: [
                    {
                        label: t('sidebar.reports'),
                        route: "rapports.index",
                        active: "rapports.*",
                        can: can("view_rapports"),
                    },
                    {
                        label: t('sidebar.long_work_logs', 'Journaux longs'),
                        route: "work-logs.index",
                        queryParams: { type: 'long', min_duration: 8 },
                        active: "work-logs.index",
                        can: can("view_planning"),
                    },
                ],
            },
        ],
        [can, today_tasks_count, draft_tasks_count, active_users_count, unplanned_tasks_count, t],
    );

    const governanceItems = useMemo(
        () => [
            {
                label: t('sidebar.identity'),
                icon: Users,
                can: can("view_users") || can("view_teams"),
                active: "users.*",
                subItems: [
                    { label: t('sidebar.users'), route: "users.index", active: "users.*" },
                    { label: t('sidebar.teams'), route: "teams.index", active: "teams.*" },
                ],
            },
            {
                label: t('sidebar.access'),
                icon: Shield,
                can: can("view_roles"),
                active: "roles.*",
                subItems: [
                    { label: t('sidebar.roles'), route: "roles.index", active: "roles.*" },
                    {
                        label: t('sidebar.permissions'),
                        route: "permissions.index",
                        active: "permissions.*",
                    },
                ],
            },
        ],
        [can, t],
    );

    const configurationItems = useMemo(
        () => [
            {
                label: t('sidebar.workflows'),
                icon: Activity,
                can: can("view_status_tasks") || can("view_status_projects") || can("manage_tasks"),
                active: "status-*",
                subItems: [
                    {
                        label: t('sidebar.status_tasks'),
                        route: "status-tasks.index",
                        active: "status-tasks.*",
                    },
                    {
                        label: t('sidebar.status_projects'),
                        route: "status-projects.index",
                        active: "status-projects.*",
                    },
                    {
                        label: t('sidebar.status_task_assignments'),
                        route: "status-task-assignments.index",
                        active: "status-task-assignments.*",
                        can: can("manage_tasks"),
                    },
                ],
            },
            {
                label: t('sidebar.business_rules'),
                icon: Briefcase,
                can: can("view_type_affaires") || can("view_status_affaires"),
                active: "*-affaires.*",
                subItems: [
                    {
                        label: t('sidebar.type_affaires'),
                        route: "type-affaires.index",
                        active: "type-affaires.*",
                    },
                    {
                        label: t('sidebar.status_affaires'),
                        route: "status-affaires.index",
                        active: "status-affaires.*",
                    },
                ],
            },
            {
                label: t('sidebar.finance'),
                icon: DollarSign,
                can: can("view_expense_categories"),
                active: "expenses.*",
                subItems: [
                    {
                        label: t('sidebar.expenses'),
                        route: "expenses.index",
                        active: "expenses.*",
                    },
                ],
            },
            {
                label: t('sidebar.integrations'),
                icon: Key,
                can: can("sync_dolibarr_admin"),
                active: "integrations.*",
                subItems: [
                    {
                        label: t('sidebar.dolibarr'),
                        route: "integrations.dolibarr.index",
                        active: "integrations.dolibarr.*",
                    },
                ],
            },
            {
                label: t('sidebar.categorization'),
                icon: Tags,
                can: can("view_tags"),
                active: "tags.*",
                subItems: [
                    { label: t('sidebar.tags'), route: "tags.index", active: "tags.*" },
                ],
            },
            {
                label: t('sidebar.security_logs'),
                icon: ShieldCheck,
                can: can("view_logs"),
                active: "logs.*",
                subItems: [
                    { label: t('sidebar.logs'), route: "logs.index", active: "logs.*" },
                ],
            },
            {
                label: t('sidebar.control_panel'),
                icon: Shield,
                can: can("view_control_panel"),
                active: "control-panel.*",
                subItems: [
                    { label: t('sidebar.control_panel'), route: "control-panel.index", active: "control-panel.*" },
                ],
            },
        ],
        [can, t],
    );

    // ── Sidebar Components (Shadcn-inspired) ──────────────────────────────────
    const SidebarMenu = ({ children }) => (
        <ul className="flex w-full min-w-0 flex-col gap-1">{children}</ul>
    );

    const SidebarMenuItem = ({ children }) => (
        <li className="group/menu-item relative list-none">{children}</li>
    );

    const SidebarMenuButton = ({
        item,
        active,
        onClick,
        className,
        children,
    }) => {
        const Icon = item?.icon;

        const baseClassName = cn(
            "relative flex w-full items-center gap-3 rounded-xl transition-all duration-200 outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50",
            isSidebarOpen ? "px-3 py-2.5" : "px-0 py-2.5 justify-center",
            active
                ? "bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow-lg shadow-blue-600/25"
                : "text-slate-400 hover:bg-slate-800/70 hover:text-white",
            className,
        );

        const content = children ? (
            children
        ) : (
            <>
                {Icon && (
                    <Icon
                        className={cn(
                            "shrink-0 size-[18px] transition-colors duration-200",
                            active
                                ? "text-white"
                                : "text-slate-500 group-hover/menu-item:text-slate-300",
                        )}
                    />
                )}
                {isSidebarOpen && item?.label && (
                    <span className="text-sm font-semibold tracking-tight truncate flex-1">
                        {item.label}
                    </span>
                )}
            </>
        );

        if (item?.route) {
            return (
                <Link href={route(item.route)} className={baseClassName}>
                    {active && isSidebarOpen && (
                        <span className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-white rounded-full -ml-px" />
                    )}
                    {content}
                </Link>
            );
        }

        return (
            <button onClick={onClick} className={baseClassName}>
                {active && isSidebarOpen && (
                    <span className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-white rounded-full -ml-px" />
                )}
                {content}
            </button>
        );
    };

    const SidebarMenuAction = ({ icon: ActionIcon, onClick, className }) => {
        if (!isSidebarOpen) return null;
        return (
            <button
                onClick={onClick}
                className={cn(
                    "absolute right-2 top-1/2 -translate-y-1/2 flex h-6 w-6 items-center justify-center rounded-md text-slate-500 hover:bg-slate-700 hover:text-white transition-all opacity-0 group-hover/menu-item:opacity-100",
                    className,
                )}
            >
                <ActionIcon className="size-3.5" />
            </button>
        );
    };

    const SidebarMenuBadge = ({ children, className }) => {
        if (!isSidebarOpen) return null;
        return (
            <span
                className={cn(
                    "ml-auto flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 text-[10px] font-black tabular-nums bg-blue-500/20 text-blue-400 border border-blue-500/20",
                    className,
                )}
            >
                {children}
            </span>
        );
    };

    const SidebarMenuSub = ({ children }) => (
        <ul className="relative flex flex-col gap-1 border-l border-slate-800/60 ml-[26px] pl-4 py-1">
            {children}
        </ul>
    );

    const SidebarMenuSubItem = ({ children }) => (
        <li className="list-none">{children}</li>
    );

    const SidebarMenuSubButton = ({ active, children, href, badge }) => (
        <Link
            href={href}
            className={cn(
                "flex h-8 w-full items-center justify-between rounded-md px-2 text-sm transition-colors duration-200 outline-none",
                active
                    ? "bg-slate-800/60 text-white font-semibold"
                    : "text-slate-500 hover:bg-slate-800/40 hover:text-slate-200",
            )}
        >
            <span className="truncate">{children}</span>
            {badge > 0 && (
                <span className="flex h-4 min-w-4 items-center justify-center rounded-md px-1.5 text-[9px] font-black tabular-nums bg-blue-500/20 text-blue-400 border border-blue-500/20">
                    {badge}
                </span>
            )}
        </Link>
    );

    const SidebarItem = ({ item }) => {
        const isChildActive = item.subItems?.some((sub) =>
            route().current(sub.active),
        );

        const isParentActive = Array.isArray(item.active)
            ? item.active.some((pattern) => route().current(pattern))
            : route().current(item.active);

        const active = isParentActive || isChildActive;

        // Use persistent expanded state, but default to open if active and not explicitly recorded
        const isOpen =
            expandedItems[item.label] === true ||
            (Object.keys(expandedItems).length === 0 && active);

        const hasSubItems = item.subItems && item.subItems.length > 0;

        return (
            <Tooltip label={item.label} show={!isSidebarOpen}>
                <SidebarMenuItem>
                    {hasSubItems ? (
                        <>
                            <SidebarMenuButton
                                onClick={() =>
                                    isSidebarOpen && toggleExpanded(item.label)
                                }
                                active={active}
                                className="group/parent"
                            >
                                <item.icon
                                    className={cn(
                                        "shrink-0 size-[18px] transition-colors duration-200",
                                        active
                                            ? "text-white"
                                            : "text-slate-500 group-hover/parent:text-slate-300",
                                    )}
                                />
                                {isSidebarOpen && (
                                    <>
                                        <span className="text-sm font-semibold tracking-tight truncate flex-1 text-left">
                                            {item.label}
                                        </span>
                                        <ChevronRight
                                            className={cn(
                                                "size-3.5 text-slate-600 transition-transform duration-200",
                                                isOpen && "rotate-90",
                                            )}
                                        />
                                    </>
                                )}
                            </SidebarMenuButton>
                            {isSidebarOpen && isOpen && (
                                <SidebarMenuSub>
                                    {item.subItems
                                        .filter((sub) => sub.can !== false)
                                        .map((sub) => {
                                            const hasTypeParam = new URLSearchParams(window.location.search).get('type') === sub.queryParams?.type;
                                            const hasActionParam = new URLSearchParams(window.location.search).get('action') === sub.queryParams?.action;
                                            
                                            // Determine active state elegantly
                                            let isSubActive = false;
                                            if (sub.queryParams) {
                                                if (sub.queryParams.type) {
                                                    isSubActive = route().current(sub.active) && hasTypeParam;
                                                } else if (sub.queryParams.action) {
                                                    isSubActive = route().current(sub.active) && hasActionParam;
                                                }
                                            } else {
                                                // General "Liste" or other subItems without query parameters
                                                isSubActive = route().current(sub.active) && 
                                                    !new URLSearchParams(window.location.search).has('type') && 
                                                    !new URLSearchParams(window.location.search).has('action');
                                            }

                                            return (
                                                <SidebarMenuSubItem key={sub.label}>
                                                    <SidebarMenuSubButton
                                                        href={route(sub.route, sub.queryParams)}
                                                        active={isSubActive}
                                                        badge={sub.badge}
                                                    >
                                                        {sub.label}
                                                    </SidebarMenuSubButton>
                                                </SidebarMenuSubItem>
                                            );
                                        })}
                                </SidebarMenuSub>
                            )}
                        </>
                    ) : (
                        <SidebarMenuButton item={item} active={active} />
                    )}
                </SidebarMenuItem>
            </Tooltip>
        );
    };

    // ── Sidebar group ──────────────────────────────────────────────────────────
    const SidebarGroup = ({ title, items }) => {
        if (!items.some((i) => i.can)) return null;

        return (
            <div className="space-y-2">
                {isSidebarOpen && (
                    <p className="px-3 text-[9px] font-black uppercase tracking-[0.2em] text-slate-600">
                        {title}
                    </p>
                )}
                {!isSidebarOpen && (
                    <div className="mx-auto w-6 h-px bg-slate-700/70 my-2" />
                )}
                <SidebarMenu>
                    {items
                        .filter((i) => i.can)
                        .map((item) => (
                            <SidebarItem key={item.label} item={item} />
                        ))}
                </SidebarMenu>
            </div>
        );
    };

    // ── Sidebar shell (shared between desktop/mobile) ─────────────────────────
    const SidebarContent = ({ closeMobile = null }) => (
        <>
            {/* Logo + toggle */}
            <div
                className={`flex items-center h-16 px-4 border-b border-slate-800/60 shrink-0
                             ${isSidebarOpen ? "justify-between" : "justify-center"}`}
            >
                {isSidebarOpen && (
                    <Link
                        href="/"
                        className="flex items-center gap-2 overflow-hidden"
                    >
                        <ApplicationLogo className="h-8 shrink-0" />
                    </Link>
                )}

                {/* Desktop toggle */}
                {closeMobile === null ? (
                    <button
                        onClick={() => setIsSidebarOpen((v) => !v)}
                        title={
                            isSidebarOpen
                                ? t('sidebar.collapse')
                                : t('sidebar.expand')
                        }
                        className="flex items-center justify-center size-8 rounded-lg
                                   bg-slate-800/60 hover:bg-slate-700 text-slate-400
                                   hover:text-white transition-all duration-200 shrink-0"
                    >
                        {isSidebarOpen ? (
                            <ChevronLeft className="size-4" />
                        ) : (
                            <ChevronRight className="size-4" />
                        )}
                    </button>
                ) : (
                    /* Mobile close button */
                    <button
                        onClick={closeMobile}
                        className="size-8 flex items-center justify-center text-slate-400 hover:text-white"
                    >
                        <X className="size-5" />
                    </button>
                )}
            </div>

            {/* Sidebar Search Trigger */}
            <div className="px-3 pb-2 pt-4">
                <button
                    onClick={() => setIsCommandPaletteOpen(true)}
                    className={cn(
                        "flex items-center gap-2 w-full h-9 rounded-lg bg-slate-800/40 hover:bg-slate-800 border border-slate-700/50 hover:border-slate-600 transition-all text-slate-400 hover:text-slate-200 outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 group",
                        isSidebarOpen ? "px-3" : "justify-center px-0"
                    )}
                >
                    <Search className="size-4 shrink-0" />
                    {isSidebarOpen && (
                        <>
                            <span className="text-xs font-semibold flex-1 text-left">{t('sidebar.search')}</span>
                            <kbd className="hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-800 text-slate-500 group-hover:bg-slate-700 group-hover:text-slate-400">
                                <span className="text-xs">⌘</span>K
                            </kbd>
                        </>
                    )}
                </button>
            </div>

            {/* Nav items */}
            <div className="flex-1 overflow-y-auto py-2 px-3 space-y-6 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-slate-700">
                <SidebarGroup title={t('sidebar.navigation')} items={navItems} />
                <SidebarGroup title={t('sidebar.governance')} items={governanceItems} />
                <SidebarGroup
                    title={t('sidebar.configuration')}
                    items={configurationItems}
                />
            </div>

            {/* User profile footer */}
            <div className="shrink-0 px-3 pb-4 pt-2 border-t border-slate-800/60">
                <div
                    className={`flex items-center gap-3 p-2.5 rounded-xl bg-slate-800/40
                                 hover:bg-slate-800/70 transition-colors cursor-default
                                 ${!isSidebarOpen ? "justify-center" : ""}`}
                >
                    <div
                        className="size-9 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600
                                    flex-shrink-0 flex items-center justify-center text-white
                                    text-sm font-bold shadow-lg shadow-blue-600/20"
                    >
                        {user.name.charAt(0).toUpperCase()}
                    </div>
                    {isSidebarOpen && (
                        <>
                            <div className="flex-1 min-w-0">
                                <p className="text-sm font-bold text-white truncate leading-tight">
                                    {user.name}
                                </p>
                                <p className="text-[11px] text-slate-500 truncate leading-tight">
                                    {user.email}
                                </p>
                            </div>
                            <Link
                                href={route("logout")}
                                method="post"
                                as="button"
                                title={t('sidebar.logout')}
                                className="p-1.5 rounded-lg text-slate-500 hover:text-red-400 hover:bg-slate-700 transition-colors"
                            >
                                <LogOut className="size-4" />
                            </Link>
                        </>
                    )}
                </div>
            </div>
        </>
    );

    return (
        <div 
            className="min-h-screen bg-slate-50 dark:bg-slate-950 flex text-slate-900 dark:text-slate-100"
            dir={locale === 'ar' ? 'rtl' : 'ltr'}
        >
            {/* ── Desktop Sidebar ─────────────────────────────────────────────── */}
            <aside
                className={`hidden lg:flex flex-col bg-[#0c1527] text-slate-300
                            border-slate-800/60 shrink-0 overflow-hidden
                            transition-[width] duration-300 ease-in-out
                            ${locale === 'ar' ? 'border-l' : 'border-r'}
                            ${isSidebarOpen ? "w-64" : "w-[68px]"}`}
                style={{
                    position: "sticky",
                    top: 0,
                    height: "100vh",
                    alignSelf: "flex-start",
                }}
            >
                <SidebarContent />
            </aside>

            {/* ── Main Content ────────────────────────────────────────────────── */}
            <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
                {/* Top navbar */}
                <header
                    className="h-14 border-b border-slate-200 dark:border-slate-800
                                   bg-white dark:bg-slate-900 z-30 flex items-center
                                   justify-between px-4 sm:px-6 shrink-0"
                >
                    <div className="flex items-center gap-3">
                        {/* Mobile hamburger */}
                        <button
                            onClick={() => setMobileMenuOpen(true)}
                            className="lg:hidden p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                        >
                            <Menu className="size-5" />
                        </button>
                    </div>

                    <div className="flex items-center gap-3">
                        {/* Today's Planning Notification */}
                        <div className="relative" ref={planningDropdownRef}>
                            <button
                                onClick={() => setPlanningDropdownOpen(!planningDropdownOpen)}
                                className={cn(
                                    "relative p-2 rounded-xl text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800 hover:text-blue-600 transition-all border border-transparent hover:border-slate-200 dark:hover:border-slate-700",
                                    planningDropdownOpen && "bg-slate-100 dark:bg-slate-800 text-blue-600"
                                )}
                                title={t('sidebar.my_planning_today')}
                            >
                                <Bell className="size-5" />
                                {(usePage().props.auth.today_tasks_count || 0) > 0 && (
                                    <span className="absolute top-1.5 right-1.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-rose-500 px-1 text-[9px] font-black text-white ring-2 ring-white dark:ring-slate-900">
                                        {usePage().props.auth.today_tasks_count}
                                    </span>
                                )}
                            </button>

                            {planningDropdownOpen && (
                                <div className="absolute right-0 mt-2.5 w-80 sm:w-[22rem] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-3xl shadow-2xl p-4 z-[9999] animate-in fade-in slide-in-from-top-3 duration-200">
                                    <div className="flex items-center justify-between pb-3 border-b border-slate-100 dark:border-slate-800/80 mb-3">
                                        <div className="flex items-center gap-2">
                                            <span className="text-sm font-black text-slate-900 dark:text-white">{t('navbar.todays_schedule')}</span>
                                            {(usePage().props.auth.today_tasks_count || 0) > 0 && (
                                                <span className="bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 text-[10px] font-black px-2 py-0.5 rounded-full">
                                                    {usePage().props.auth.today_tasks_count}
                                                </span>
                                            )}
                                        </div>
                                        <Link 
                                            href={route("planning.my")}
                                            onClick={() => setPlanningDropdownOpen(false)}
                                            className="text-xs font-bold text-blue-600 dark:text-blue-400 hover:underline"
                                        >
                                            {t('navbar.my_calendar')}
                                        </Link>
                                    </div>

                                    <div className="max-h-[320px] overflow-y-auto space-y-2 pr-1 scrollbar-thin scrollbar-thumb-slate-200">
                                        {(!usePage().props.auth.today_tasks || usePage().props.auth.today_tasks.length === 0) ? (
                                            <div className="flex flex-col items-center justify-center py-8 text-center text-slate-400">
                                                <AlertCircle className="size-8 opacity-20 mb-2" />
                                                <p className="text-xs font-bold uppercase tracking-wider">{t('navbar.no_tasks_planned')}</p>
                                                <p className="text-[10px] font-medium text-slate-500 mt-1">{t('navbar.enjoy_free_day')}</p>
                                            </div>
                                        ) : (
                                            usePage().props.auth.today_tasks.map((assignment) => (
                                                <Link
                                                    key={assignment.id}
                                                    href={route("tasks.show", {
                                                        task: assignment.task_id,
                                                        ...(assignment.affaire_id && { affaire_id: assignment.affaire_id }),
                                                        ...(assignment.business_tier_id && { business_tier_id: assignment.business_tier_id }),
                                                        ...(assignment.business_contact_id && { business_contact_id: assignment.business_contact_id }),
                                                    })}
                                                    onClick={() => setPlanningDropdownOpen(false)}
                                                    className="group flex flex-col p-3 rounded-2xl bg-slate-50/50 dark:bg-slate-800/30 hover:bg-slate-100 dark:hover:bg-slate-800 border border-transparent hover:border-slate-100 dark:hover:border-slate-700 transition-all duration-150"
                                                >
                                                    <div className="flex items-start justify-between gap-2">
                                                        <div className="flex items-start gap-2.5">
                                                            <span
                                                                className={cn(
                                                                    "size-2 rounded-full mt-1.5 shrink-0",
                                                                    !assignment.status_task_assignment
                                                                        ? (assignment.status === "completed" 
                                                                            ? "bg-emerald-500" 
                                                                            : "bg-blue-500 animate-pulse")
                                                                        : ""
                                                                )}
                                                                style={assignment.status_task_assignment ? { backgroundColor: assignment.status_task_assignment.color } : {}}
                                                            />
                                                            <div>
                                                                <h4 className="text-sm font-bold text-slate-800 dark:text-slate-200 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors leading-tight">
                                                                    {assignment.task_title || t('navbar.untitled_task')}
                                                                </h4>
                                                                <div className="flex flex-wrap items-center gap-1.5 mt-0.5">
                                                                    {assignment.project_name && (
                                                                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-none">
                                                                            {assignment.project_name}
                                                                        </p>
                                                                    )}
                                                                    <div
                                                                        className={cn(
                                                                            "px-1.5 py-0.5 rounded-full text-[8px] font-black uppercase tracking-widest border flex items-center gap-1 w-fit",
                                                                            !assignment.status_task_assignment
                                                                                ? (assignment.status === "completed"
                                                                                    ? "bg-emerald-500/10 text-emerald-600 border-emerald-500/20"
                                                                                    : "bg-blue-500/10 text-blue-600 border-blue-500/20")
                                                                                : ""
                                                                        )}
                                                                        style={
                                                                            assignment.status_task_assignment
                                                                                ? {
                                                                                    backgroundColor: `${assignment.status_task_assignment.color}15`,
                                                                                    color: assignment.status_task_assignment.color,
                                                                                    borderColor: `${assignment.status_task_assignment.color}30`,
                                                                                }
                                                                                : {}
                                                                        }
                                                                    >
                                                                        {translateStatus(assignment.status_task_assignment ? assignment.status_task_assignment.name : assignment.status)}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    {(assignment.start_time || assignment.end_time) ? (
                                                        <div className="flex items-center gap-1.5 text-[10px] font-black text-blue-600 dark:text-blue-400 bg-blue-500/5 px-2 py-0.5 rounded-lg w-fit mt-2 ml-4">
                                                            <Bell className="size-2.5" />
                                                            {assignment.start_time?.substring(0, 5) || "00:00"} - {assignment.end_time?.substring(0, 5) || "23:59"}
                                                        </div>
                                                    ) : (
                                                        <div className="flex items-center gap-1.5 text-[10px] font-black text-slate-500 dark:text-slate-400 bg-slate-500/5 px-2 py-0.5 rounded-lg w-fit mt-2 ml-4">
                                                            <Bell className="size-2.5" />
                                                            {t('navbar.all_day')}
                                                        </div>
                                                    )}
                                                </Link>
                                            ))
                                        )}
                                    </div>

                                    {usePage().props.auth.today_tasks && usePage().props.auth.today_tasks.length > 0 && (
                                        <div className="pt-3 border-t border-slate-100 dark:border-slate-800/80 mt-3">
                                            <Link
                                                href={route("planning.my")}
                                                onClick={() => setPlanningDropdownOpen(false)}
                                                className="flex items-center justify-center w-full py-2.5 px-4 text-xs font-black text-white bg-blue-600 hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700 rounded-2xl shadow-lg shadow-blue-500/10 hover:shadow-blue-500/20 transition-all text-center"
                                            >
                                                {t('navbar.go_to_my_planning')}
                                            </Link>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>

                        {/* Theme Toggle */}
                        <button
                            onClick={toggleTheme}
                            className="p-2 rounded-xl text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800 hover:text-blue-600 transition-all border border-transparent hover:border-slate-200 dark:hover:border-slate-700"
                            title={
                                theme === "light"
                                    ? t('navbar.switch_to_dark_mode')
                                    : t('navbar.switch_to_light_mode')
                            }
                        >
                            {theme === "light" ? (
                                <Moon className="size-5" />
                            ) : (
                                <Sun className="size-5" />
                            )}
                        </button>

                        <div className="h-7 w-px bg-slate-200 dark:bg-slate-800 mx-1" />

                        {/* User info + dropdown */}
                        <div className="flex items-center gap-3">
                            <div className="text-right hidden sm:block">
                                <p className="text-sm font-bold text-slate-900 dark:text-white leading-tight">
                                    {user.name}
                                </p>
                                <p className="text-[10px] text-slate-500 font-bold uppercase tracking-wider leading-tight">
                                    {usePage().props.auth.role_names?.[0] ||
                                        t('navbar.user')}
                                </p>
                            </div>
                            <Dropdown>
                                <Dropdown.Trigger>
                                    <button
                                        className="size-9 rounded-full flex items-center justify-center
                                                       overflow-hidden border-2 border-slate-200 dark:border-slate-700
                                                       hover:border-blue-500 transition-all shadow-sm"
                                    >
                                        <div
                                            className="size-full bg-gradient-to-br from-blue-500 to-indigo-600
                                                        flex items-center justify-center text-white font-bold text-sm"
                                        >
                                            {user.name.charAt(0).toUpperCase()}
                                        </div>
                                    </button>
                                </Dropdown.Trigger>
                                <Dropdown.Content>
                                    <Dropdown.Link href={route("profile.edit")}>
                                        {t('navbar.profile')}
                                    </Dropdown.Link>
                                    <Dropdown.Link
                                        href={route("logout")}
                                        method="post"
                                        as="button"
                                    >
                                        {t('navbar.log_out')}
                                    </Dropdown.Link>
                                </Dropdown.Content>
                            </Dropdown>
                        </div>
                    </div>
                </header>

                {/* Page content */}
                <main className="flex-1 overflow-y-auto p-4 sm:p-6 lg:p-8 bg-slate-50 dark:bg-slate-950">
                    {header && (
                        <div className="mb-8 animate-in fade-in slide-in-from-top-4 duration-500">
                            {header}
                        </div>
                    )}
                    {children}
                </main>
            </div>

            {/* Mobile Sidebar Overlay */}
            {mobileMenuOpen && (
                <div className="fixed inset-0 z-50 lg:hidden">
                    {/* Backdrop */}
                    <div
                        className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm"
                        onClick={() => setMobileMenuOpen(false)}
                    />
                    {/* Drawer */}
                    <aside
                        className={`fixed inset-y-0 ${locale === 'ar' ? 'right-0 border-l animate-in slide-in-from-right' : 'left-0 border-r animate-in slide-in-from-left'} w-72 bg-[#0c1527] shadow-2xl
                                      flex flex-col border-slate-800/60
                                      duration-300 overflow-hidden`}
                    >
                        <SidebarContent
                            closeMobile={() => setMobileMenuOpen(false)}
                        />
                    </aside>
                </div>
            )}
            
            <CommandPalette 
                isOpen={isCommandPaletteOpen} 
                setIsOpen={setIsCommandPaletteOpen} 
            />

            <Toaster
                position="top-right"
                expand={true}
                richColors
                closeButton
            />
            <QuickActionsFAB />
        </div>
    );
}
