import React, { useState } from 'react';
import ThemeToggle from '@/Components/ThemeToggle';
import { Link, usePage, router } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Sheet, SheetContent, SheetTrigger, SheetTitle, SheetDescription } from "@/components/ui/sheet";
import { Toaster } from "@/Components/ui/sonner"; 
import useFlashMessages from '@/hooks/useFlashMessages'; 
import useTranslation from '@/hooks/useTranslation'; 
import AdSlot from '@/Components/AdSlot'; 
import RightSidebarFooter from '@/Components/RightSidebarFooter'; 
import SiteLogo from '@/Components/SiteLogo';

import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
  navigationMenuTriggerStyle,
} from "@/components/ui/navigation-menu";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { 
    LayoutDashboard, Newspaper, FilePlus, User, LogOut, Menu, Search, 
    ChevronDown, X, LogIn, UserPlus 
} from 'lucide-react';
import { cn } from "@/lib/utils";

function MobileExpandableItem({ category }) {
    const [isOpen, setIsOpen] = useState(false); 
    const hasChildren = category.children && category.children.length > 0;

    return (
        <div className="border-b border-border last:border-0">
            <div className="flex items-center justify-between w-full py-3">
                <Link 
                    href={route('category.show', category.slug)} 
                    className="flex-1 font-bold text-lg hover:text-primary transition-colors text-start"
                >
                    {category.name}
                </Link>
                
                {hasChildren && (
                    <button 
                        onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setIsOpen(!isOpen);
                        }}
                        className="p-2 -me-2 text-muted-foreground hover:text-foreground focus:outline-none"
                    >
                        <ChevronDown 
                            className={cn(
                                "h-5 w-5 transition-transform duration-300", 
                                isOpen && "rotate-180"
                            )} 
                        />
                    </button>
                )}
            </div>
            
            <div 
                className={cn(
                    "overflow-hidden transition-all duration-300 ease-in-out",
                    isOpen ? "max-h-[500px] opacity-100 mb-4" : "max-h-0 opacity-0"
                )}
            >
                <div className="flex flex-col gap-3 ps-4 border-s-2 border-muted ms-1">
                    {category.children?.map((child) => (
                        <Link 
                            key={child.id}
                            href={route('category.show', child.slug)}
                            className="block text-sm text-muted-foreground hover:text-foreground hover:translate-x-1 rtl:hover:-translate-x-1 transition-transform text-start"
                        >
                            {child.name}
                        </Link>
                    ))}
                </div>
            </div>
        </div>
    );
}

const ListItem = React.forwardRef(({ className, title, children, href, ...props }, ref) => {
  return (
    <li>
      <NavigationMenuLink asChild>
        <Link
          ref={ref}
          href={href}
          className={cn(
            "block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground text-start",
            className
          )}
          {...props}
        >
          <div className="text-sm font-medium leading-none">{title}</div>
          <p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
            {children}
          </p>
        </Link>
      </NavigationMenuLink>
    </li>
  );
});
ListItem.displayName = "ListItem";

export default function GuestLayout({ children }) {
    useFlashMessages();
    const { t } = useTranslation();

    const { props } = usePage();
    const { auth, categories, registration_enabled, global_ads } = props;
    const { user } = auth || {}; 

    const [searchQuery, setSearchQuery] = useState('');
    const [showStickyAd, setShowStickyAd] = useState(true);
    
    // --- NEW: State for Mobile Search Bar Toggle ---
    const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
    
    const handleSearch = (e) => {
        e.preventDefault();
        if (searchQuery.trim()) {
            router.get(route('news.search'), { q: searchQuery });
            setIsMobileSearchOpen(false); // Close on search
        }
    };

    const headerAd = global_ads?.['global_header_top'];
    const stickyAd = global_ads?.['global_sticky_bottom'];

    return (
        <div className="min-h-screen flex flex-col bg-background text-foreground transition-colors duration-300 relative">
            
            {headerAd && headerAd.is_active && (
                <div className="w-full bg-muted/20 border-b border-border flex justify-center py-2">
                    <AdSlot ad={headerAd} className="max-w-[728px] w-full" />
                </div>
            )}

            <header className="bg-background/95 backdrop-blur border-b border-border sticky top-0 z-50 shadow-sm">
                
                {/* --- MOBILE SEARCH BAR OVERLAY --- */}
                <div className={cn(
                    "absolute inset-0 bg-background z-50 flex items-center px-4 transition-all duration-300 lg:hidden",
                    isMobileSearchOpen ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-full pointer-events-none"
                )}>
                    <form onSubmit={handleSearch} className="relative w-full flex items-center gap-2">
                        <div className="relative flex-1">
                            <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input 
                                type="search" 
                                placeholder={t('_search_placeholder', 'Search news...')}
                                className="ps-10 w-full bg-muted/50 border-input focus:bg-background rounded-full"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                autoFocus={isMobileSearchOpen}
                            />
                        </div>
                        <Button 
                            type="button" 
                            variant="ghost" 
                            size="icon" 
                            onClick={() => setIsMobileSearchOpen(false)}
                            className="shrink-0 rounded-full"
                        >
                            <X className="h-5 w-5" />
                        </Button>
                    </form>
                </div>
                {/* --------------------------------- */}

                <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between items-center h-16 gap-4">
                        
                        <div className="flex items-center gap-2 sm:gap-4 shrink-0">
                            
                            <div className="lg:hidden">
                                <Sheet>
                                    <SheetTrigger asChild>
                                        <Button variant="ghost" size="icon" className="-ms-2"><Menu className="h-6 w-6" /></Button>
                                    </SheetTrigger>
                                    
                                    <SheetContent side="left" className="w-[300px] sm:w-[350px] p-0 flex flex-col h-full rtl:[&>button]:left-4 rtl:[&>button]:right-auto">
                                        <SheetTitle className="sr-only">Navigation</SheetTitle>
                                        <SheetDescription className="sr-only">Mobile Menu</SheetDescription>
                                        
                                        <div className="flex-1 overflow-y-auto px-6 py-6">
                                            
                                            <Link href="/" className="flex items-center gap-2 mb-6">
                                                <SiteLogo className="h-8 w-auto" />
                                            </Link>
                                            
                                            {/* Search inside sidebar is optional now, but kept for UX */}
                                            <form onSubmit={handleSearch} className="relative mb-6">
                                                <Search className="absolute start-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                                                <Input 
                                                    type="search" 
                                                    placeholder={t('_search_placeholder', 'Search news...')}
                                                    className="ps-9 bg-muted"
                                                    value={searchQuery}
                                                    onChange={(e) => setSearchQuery(e.target.value)}
                                                />
                                            </form>

                                            <nav className="flex flex-col">
                                                {categories.map((category) => (
                                                    <MobileExpandableItem key={category.id} category={category} />
                                                ))}
                                            </nav>
                                        </div>

                                        <div className="border-t border-border bg-muted/10">
                                            <div className="-mt-6 mb-4">
                                                <RightSidebarFooter />
                                            </div>
                                        </div>

                                    </SheetContent>
                                </Sheet>
                            </div>
                            
                            <Link href="/" className="flex items-center gap-2">
                                <SiteLogo className="h-8 sm:h-10 w-auto" />
                            </Link>
                        </div>

                        {/* Desktop Search */}
                        <div className="hidden lg:flex flex-1 max-w-xl mx-auto">
                            <form onSubmit={handleSearch} className="relative w-full">
                                <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                                <Input 
                                    type="search" 
                                    placeholder={t('_search_placeholder', 'Search for topics, locations & sources...')}
                                    className="ps-10 w-full bg-muted/50 border-input focus:bg-background transition-colors rounded-full"
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                />
                            </form>
                        </div>
                        
                        <div className="flex items-center gap-1 sm:gap-2 shrink-0">
                            
                            {/* --- MOBILE SEARCH TRIGGER ICON --- */}
                            <Button 
                                variant="ghost" 
                                size="icon" 
                                className="lg:hidden" 
                                onClick={() => setIsMobileSearchOpen(true)}
                                aria-label="Open Search"
                            >
                                <Search className="h-5 w-5" />
                            </Button>

                            <ThemeToggle />
                            
                            {user ? (
                                <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                        <Button variant="ghost" className="relative h-9 w-9 sm:h-10 sm:w-10 rounded-full">
                                            <Avatar className="h-9 w-9 sm:h-10 sm:w-10">
                                                <AvatarImage src={user.avatar || `https://ui-avatars.com/api/?name=${user.name.replace(/\s/g, '+')}`} alt={user.name} />
                                                <AvatarFallback>{user.name.substring(0, 2).toUpperCase()}</AvatarFallback>
                                            </Avatar>
                                        </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent className="w-56" align="end" forceMount>
                                        <DropdownMenuLabel className="font-normal">
                                            <div className="flex flex-col space-y-1 text-start">
                                                <p className="text-sm font-medium">{user.name}</p>
                                                <p className="text-xs text-muted-foreground">{user.email}</p>
                                            </div>
                                        </DropdownMenuLabel>
                                        <DropdownMenuSeparator />
                                        
                                        {user.role === 'admin' && (
                                            <DropdownMenuItem asChild>
                                                <a href={route('admin.dashboard')} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 cursor-pointer">
                                                    <LayoutDashboard className="h-4 w-4" /> {t('_admin_panel', 'Admin Panel')}
                                                </a>
                                            </DropdownMenuItem>
                                        )}
                                        
                                        <DropdownMenuItem asChild>
                                            <Link href={route('dashboard')} className="flex items-center gap-2 cursor-pointer">
                                                <LayoutDashboard className="h-4 w-4" /> {t('_dashboard', 'Dashboard')}
                                            </Link>
                                        </DropdownMenuItem>
                                        <DropdownMenuItem asChild>
                                            <Link href={route('my-posts.index')} className="flex items-center gap-2 cursor-pointer">
                                                <Newspaper className="h-4 w-4" /> {t('_my_posts', 'My Posts')}
                                            </Link>
                                        </DropdownMenuItem>
                                        <DropdownMenuItem asChild>
                                            <Link href={route('news.submit')} className="flex items-center gap-2 cursor-pointer">
                                                <FilePlus className="h-4 w-4" /> {t('_submit_news', 'Submit News')}
                                            </Link>
                                        </DropdownMenuItem>
                                        <DropdownMenuItem asChild>
                                            <Link href={route('settings.edit')} className="flex items-center gap-2 cursor-pointer">
                                                <User className="h-4 w-4" /> {t('_profile', 'Profile')}
                                            </Link>
                                        </DropdownMenuItem>
                                        <DropdownMenuSeparator />
                                        <DropdownMenuItem asChild>
                                            <Link href={route('logout')} method="post" as="button" className="w-full flex items-center gap-2 cursor-pointer text-red-500 focus:text-red-500">
                                                <LogOut className="h-4 w-4" /> {t('_logout', 'Log Out')}
                                            </Link>
                                        </DropdownMenuItem>
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            ) : (
                                <>
                                    <div className="hidden sm:flex items-center gap-2">
                                        <Link href={route('login')}>
                                            <Button variant="ghost" className="font-semibold">{t('_login', 'Log in')}</Button>
                                        </Link>
                                        {registration_enabled && (
                                            <Link href={route('register')}>
                                                <Button className="rounded-full">{t('_signup', 'Sign Up')}</Button>
                                            </Link>
                                        )}
                                    </div>

                                    <div className="sm:hidden">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" size="icon" className="h-9 w-9">
                                                    <User className="h-5 w-5" />
                                                    <span className="sr-only">Account</span>
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end" className="w-40">
                                                <DropdownMenuLabel>{t('_profile', 'Account')}</DropdownMenuLabel>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem asChild>
                                                    <Link href={route('login')} className="flex items-center gap-2 cursor-pointer">
                                                        <LogIn className="h-4 w-4" /> {t('_login', 'Log In')}
                                                    </Link>
                                                </DropdownMenuItem>
                                                {registration_enabled && (
                                                    <DropdownMenuItem asChild>
                                                        <Link href={route('register')} className="flex items-center gap-2 cursor-pointer">
                                                            <UserPlus className="h-4 w-4" /> {t('_signup', 'Sign Up')}
                                                        </Link>
                                                    </DropdownMenuItem>
                                                )}
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </div>
                                </>
                            )}
                        </div>
                    </div>
                </div>

                {/* Desktop Category Menu */}
                <div className="hidden lg:block border-t border-border bg-background/50 backdrop-blur-sm">
                    <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                        <div className="flex justify-center h-12 items-center">
                            <NavigationMenu>
                                <NavigationMenuList>
                                    {categories.slice(0, 8).map((category) => (
                                        <NavigationMenuItem key={category.id}>
                                            {category.children && category.children.length > 0 ? (
                                                <>
                                                    <NavigationMenuTrigger className="bg-transparent h-9 px-4 text-sm font-semibold text-muted-foreground hover:text-foreground data-[state=open]:text-primary">
                                                        {category.name}
                                                    </NavigationMenuTrigger>
                                                    <NavigationMenuContent>
                                                        <ul className="grid w-[400px] gap-3 p-4 md:w-[500px] md:grid-cols-2 lg:w-[600px] text-start">
                                                            <ListItem 
                                                                title={t('_view_all', 'View All')}
                                                                href={route('category.show', category.slug)}
                                                            >
                                                                {t('_see_all_in', 'See all latest news in')} {category.name}
                                                            </ListItem>

                                                            {category.children.map((child) => (
                                                                <ListItem 
                                                                    key={child.id} 
                                                                    href={route('category.show', child.slug)} 
                                                                    title={child.name}
                                                                >
                                                                    {t('_explore', 'Explore')} {child.name} {t('_headlines', 'headlines')}.
                                                                </ListItem>
                                                            ))}
                                                        </ul>
                                                    </NavigationMenuContent>
                                                </>
                                            ) : (
                                                <NavigationMenuLink asChild>
                                                    <Link 
                                                        href={route('category.show', category.slug)} 
                                                        className={cn(navigationMenuTriggerStyle(), "bg-transparent h-9 px-4 text-sm font-semibold text-muted-foreground hover:text-foreground")}
                                                    >
                                                        {category.name}
                                                    </Link>
                                                </NavigationMenuLink>
                                            )}
                                        </NavigationMenuItem>
                                    ))}
                                </NavigationMenuList>
                            </NavigationMenu>
                        </div>
                    </div>
                </div>
            </header>

            <main className="flex-grow">{children}</main>

            {stickyAd && stickyAd.is_active && showStickyAd && (
                <div className="fixed bottom-0 left-0 right-0 z-40 bg-background border-t border-border md:hidden shadow-2xl animate-in slide-in-from-bottom-full duration-500 pb-safe">
                    <button 
                        type="button"
                        onClick={() => setShowStickyAd(false)}
                        className="absolute -top-7 right-2 bg-background border border-border rounded-t-md px-2 py-1 text-xs text-muted-foreground shadow-sm flex items-center gap-1 hover:text-foreground hover:bg-muted transition-colors rtl:left-2 rtl:right-auto"
                    >
                        {t('_close', 'Close')} <X className="w-3 h-3" />
                    </button>
                    
                    <div className="flex justify-center py-2 px-4">
                        <AdSlot ad={stickyAd} className="w-full max-w-[320px] mx-auto" />
                    </div>
                </div>
            )}

            <Toaster />
        </div>
    );
}