"use client";

import { useState, useEffect, useCallback } from 'react';
import { Search, User, Globe, ChevronDown, Menu, X } from 'lucide-react';
import * as React from 'react';
import SearchbarComponent from './SearchBar';
import MobileSidenav from './MobileSidenav';


// --- 1. Interface Definitions ---
export interface LinkItem { text: string; href: string; }
export interface Column { title: string; links: LinkItem[]; }
export interface NavItem { name: string; href: string; megaMenu?: { columns: Column[]; }; }

// --- 2. navItems Data Structure (Unchanged) ---
const navItems: NavItem[] = [
    {
        name: 'Who We Are',
        href: '#who',
        megaMenu: {
            columns: [
                {
                    title: 'Our Organization',
                    links: [
                        { text: 'Overview', href: '/overview' },
                        { text: 'Our History', href: '/our-history' },
                        { text: 'Our Mission & Vision', href: '/mision-vision' },
                        { text: 'Leadership', href: '/leadership' },
                        { text: 'Our Experts', href: '/our-experts' },
                        { text: 'Award & Recognations', href: '/award-recognations' },
                        { text: 'Clients & Feedback', href: '/clients-feedback' },
                        { text: 'Portfolio', href: '/portfolio' },
                    ],
                },
                {
                    title: 'Our Projects',
                    links: [
                        { text: 'Sudarshan 2.O', href: '/sudarshan' },
                        { text: 'Tree Stethosccope', href: '/tree-stethosccope' },
                        { text: 'M.E.R.A 1.0', href: '/mera' },
                    ],
                },
                {
                    title: 'Impact',
                    links: [
                        { text: '11 Rupey Me Graduate', href: '/11rupeyme' },
                        { text: 'Yoga Sceince', href: '/yoga-sceince' },
                        { text: 'Green Galaxy', href: '/green-galaxy' },
                        { text: 'Digital Awareness', href: '/digital-awareness' },
                        { text: 'DMH Wimraw', href: '/dmh-wimraw' },
                    ],
                },
            ],
        }
    },
    {
        name: 'What We Do',
        href: '#what',
        megaMenu: {
            columns: [
                {
                    title: 'Capabilities',
                    links: [
                        { text: 'Application Development and Maintenance', href: '/application ' },
                        { text: 'Cybersecurity', href: '/cybersecurity' },
                        { text: 'Artificial Intelligence', href: '/artificial-intelligence' },
                        { text: 'Robotics', href: '/robotics' },
                        { text: 'Consulting', href: '/consulting' },
                        { text: 'Digital Marketing', href: '/digital-marketing' },
                        { text: 'Learning', href: '/learning' },
                        { text: 'Broadcasting', href: '/broadcasting' },
                        { text: 'Cloud', href: '/cloud' },
                        { text: 'Deep Space Exploration', href: '/deep-space-exploration' },
                        { text: 'Research', href: '#forecasting' },
                        { text: 'IoT and Digital Engineering', href: '#forecasting' },
                        { text: 'Data & Analytics', href: '#forecasting' },
                        { text: 'Branding', href: '#forecasting' },
                    ],
                },
                {
                    title: 'Industries',
                    links: [
                        { text: 'Education', href: '/education' },
                        { text: 'Aerospace & Defence', href: '/aerospace-defence' },
                        { text: 'Agriculture', href: '/agricalture' },
                        { text: 'Software', href: '/software' },
                        { text: 'Communications Services', href: '/communications-services' },
                        { text: 'Banking & Finance', href: '/banking-finance' },
                        { text: 'Information Services & Publishing', href: '/information-services' },
                        { text: 'E-Commerce & Logistics', href: '/e-commerce-logistics' },
                        { text: 'Media and Entertainment', href: '/media-entertainment' },
                        { text: 'Healthcare', href: '/healthcare' },
                        { text: 'Security', href: '/security' },
                        { text: 'Consumer Packaged Goods and Distribution', href: '/consumer-packaged-goods' },
                    ],
                },
                {
                    title: 'Products',
                    links: [
                        { text: 'Panther Speaks', href: '/panther-speaks' },
                        { text: 'Suhagini Spices', href: '/suhagini-spices' },
                    ],
                },
                {
                    title: 'Platforms',
                    links: [
                        { text: 'Wimraw Institute', href: '#strategy' },
                        { text: 'Jhumle', href: '#risk' },
                        { text: 'NCSI', href: '#digital' },
                        { text: 'Web Expert', href: '#digital' },
                        { text: 'NECI', href: '#digital' },
                        { text: 'Black Cat News Network', href: '/blackcatnews-network' },
                        { text: 'Oibuild', href: '#digital' },
                        { text: 'Oifind', href: '#digital' },
                        { text: 'Oiearn', href: '#digital' },
                        { text: 'Wimraw Cloud', href: '#digital' },
                        { text: 'Aasiqui', href: '#digital' },
                    ],
                },
            ],
        }
    },
    {
        name: 'For You',
        href: '#for',
        megaMenu: {
            columns: [
                {
                    title: 'Careers',
                    links: [
                        { text: 'Work@ Wimraw', href: '/work-wimraw' },
                        { text: 'Apprenticeship & Internships', href: '/internships' },
                        { text: 'Research Fellowship', href: '/reserch-followship' }
                    ],
                },
                {
                    title: 'Opportunities',
                    links: [
                        { text: 'Corporate Collaboration', href: '/corporate-coilabration' },
                        { text: 'CSR', href: '/csr' },
                    ],
                },
            ],
        }
    },
    {
        name: 'For Press',
        href: '#press',
        megaMenu: {
            columns: [
                {
                    title: 'Press',
                    links: [
                        { text: 'Events', href: '/events' },
                        { text: 'Press Releases', href: '/press-release' },
                        { text: 'Stories', href: '/stories' },
                        { text: 'Media Resources', href: '/media-resourse' },

                    ],
                },
            ],
        }
    },
];

// --- 3. Utility Function ---
const getGridClass = (count: number): string => {
    if (count < 1) return 'sm:grid-cols-1';
    if (count < 1) return 'sm:grid-cols-3';
    if (count > 4) return 'sm:grid-cols-4';
    return `sm:grid-cols-${count}`;
}

// --- 4. MegaMenuItem Component (Desktop Dropdown) ---
const MegaMenuItem: React.FC<{ item: NavItem, index: number }> = ({ item, index }) => {
    const hasMegaMenu = !!item.megaMenu;

    const alignmentClass = 'left-1/2 transform -translate-x-1/2';

    const actualColumnCount = item.megaMenu?.columns.length || 0;

    let dynamicWidthClass = 'w-[500px]';

    if (actualColumnCount === 1) {
        dynamicWidthClass = 'w-[300px]';
    } else if (actualColumnCount === 3) {
        dynamicWidthClass = 'w-[900px]';
    } else if (actualColumnCount >= 4) {
        dynamicWidthClass = 'w-[1100px]';
    }

    const internalGridColumns = getGridClass(actualColumnCount);

    return (
        <div className="relative group h-full flex items-center">
            <a
                href={item.href}
                className="flex items-center space-x-1 p-3 text-sm font-medium transition duration-150 ease-in-out text-white hover:text-indigo-400"
            >
                <span>{item.name}</span>
                {hasMegaMenu && <ChevronDown size={14} className="mt-0.5 group-hover:rotate-180 transition-transform" />}
            </a>

            {/* Mega Menu Panel */}
            {hasMegaMenu && (
                <div className={`absolute ${alignmentClass} top-full ${dynamicWidthClass}
                             opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none group-hover:pointer-events-auto z-50`}>

                    {/* Mega Menu Background: #020024 */}
                    <div className='overflow-hidden shadow-2xl backdrop-blur-xl ring-1 ring-white/10' style={{ backgroundColor: '#020024' }}>
                        <div className="p-8 grid grid-cols-1 gap-8">

                            {/* Column Container with Dynamic Grid Class */}
                            <div className={`grid grid-cols-1 gap-8 ${internalGridColumns}`}>
                                {item.megaMenu?.columns.map((column, colIndex, arr) => (
                                    <div
                                        key={column.title}
                                        className={`min-w-0 ${colIndex < arr.length - 1 ? 'pr-4 border-r border-white/10' : ''}`}
                                    >
                                        <h3 className="text-base font-semibold text-indigo-400 mb-3 uppercase tracking-wider">{column.title}</h3>
                                        <ul className="space-y-2">
                                            {column.links.map((link) => (
                                                <li key={link.text}>
                                                    {/* mega-link + mega-text classes provide the dash + shift behavior */}
                                                    <a href={link.href} className="mega-link">
                                                        <span className="mega-text text-sm text-white/80">{link.text}</span>
                                                    </a>
                                                </li>
                                            ))}
                                        </ul>

                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};


// --- 5. Mobile Menu Toggle Icon (Hamburger) ---
interface MobileMenuToggleProps { isOpen: boolean; onClick: () => void; }

const MobileMenuToggle: React.FC<MobileMenuToggleProps> = ({ isOpen, onClick }) => {
    return (
        <button
            className="p-2 rounded-full hover:bg-white/10 transition-colors lg:hidden relative"
            onClick={onClick}
            aria-expanded={isOpen}
            aria-label={isOpen ? "Close menu" : "Open menu"}
        >
            <div className="relative w-6 h-6">
                <Menu
                    size={24}
                    className={`absolute inset-0 transition-opacity duration-300 ${isOpen ? 'opacity-0 rotate-90' : 'opacity-100 rotate-0'}`}
                />
                <X
                    size={24}
                    className={`absolute inset-0 transition-opacity duration-300 ${isOpen ? 'opacity-100 rotate-0' : 'opacity-0 -rotate-90'}`}
                />
            </div>
        </button>
    );
};


// --- 6. Main Navbar Component ---
// logo
const Logo: React.FC = () => (
    <a href="/" className="flex items-center space-x-3 py-2">
        <img src={'/img/logo/logo-white.png'} className='h-14' alt="Company Logo" />
    </a>
);

const StickyTransparentNavbar: React.FC = () => {
    const [isScrolled, setIsScrolled] = useState(false);
    const [isSearchOpen, setIsSearchOpen] = useState(false);
    const [isSidenavOpen, setIsSidenavOpen] = useState(false); // Mobile Menu State

    // Scroll handling logic
    const handleScroll = useCallback(() => {
        setIsScrolled(window.scrollY > 80);
    }, []);

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        handleScroll();
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, [handleScroll]);

    // Sticky Navbar Gradient Style
    const gradientStyle = 'linear-gradient(251deg, rgba(2, 0, 36, 1) 0%, rgba(74, 0, 224, 1) 100%)';

    const headerClasses = `
    fixed w-full top-0 z-[100] transition-all duration-300 ease-in-out 
    ${isScrolled
            ? 'backdrop-blur-md shadow-2xl border-b border-indigo-700/50'
            : 'bg-transparent'
        }
    text-white
  `;

    return (
        <>
            <header
                className={headerClasses}
                style={isScrolled ? { background: gradientStyle } : { background: 'transparent' }}
            >
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    <div className="flex items-center justify-between h-16">

                        {/* Logo/Branding (Left side) */}
                        <div className="shrink-0">
                            <Logo />
                        </div>

                        {/* Desktop Navigation (Center Menu) */}
                        <nav className="hidden lg:flex lg:ml-6 lg:space-x-1 h-full relative z-101">
                            <div className="flex space-x-1 h-full">
                                {navItems.map((item, index) => (
                                    <MegaMenuItem key={item.name} item={item} index={index} />
                                ))}
                            </div>
                        </nav>

                        {/* Utility Icons (Right Side) */}
                        <div className="flex items-center space-x-4">

                            {/* Search Icon */}
                            <button
                                onClick={() => setIsSearchOpen(true)}
                                className="p-2 rounded-full hover:bg-white/10 transition-colors animate-shake-on-hover"
                                aria-label="Open search"
                            >
                                <Search size={20} />
                            </button>

                            {/* User Icon */}
                            <a
                                href="/sign-in"
                                className="p-2 rounded-full hover:bg-white/10 transition-colors hidden sm:block animate-shake-on-hover"
                            >
                                <User size={20} />
                            </a>

                            {/* Language Dropdown */}
                            <div className="relative group hidden sm:flex items-center">
                                {/* Trigger */}
                                <button
                                    type="button"
                                    className="flex items-center gap-2 px-3 py-2 rounded-lg  bg-white/5 hover:bg-white/10 transition-colors text-sm font-medium text-slate-200"
                                    aria-haspopup="true"
                                    aria-expanded="false"
                                >
                                    <Globe size={18} />
                                    <span>English</span>
                                    <ChevronDown
                                        size={14}
                                        className="transition-transform duration-300 group-hover:rotate-180"
                                    />
                                </button>

                                {/* Dropdown */}
                                <div
                                    className="absolute right-0 top-full mt-2 w-44 origin-top-right scale-95 opacity-0 invisible group-hover:visible group-hover:opacity-100 group-hover:scale-100 transition-all duration-200 ease-out rounded-xl bg-black/90 backdrop-blur-md ring-1 ring-white/10 shadow-2xl z-50 overflow-hidden"
                                >
                                    <a
                                        href="#lang-en"
                                        className="flex items-center justify-between px-4 py-2.5 text-sm text-white/80 hover:text-white hover:bg-indigo-600/40 transition-colors"
                                    >
                                        Default English
                                    </a>

                                    <a
                                        href="#lang-hi"
                                        className="block px-4 py-2.5 text-sm text-white/80 hover:text-white  hover:bg-indigo-600/40 transition-colors"
                                    >
                                        India (Hindi)
                                    </a>
                                </div>
                            </div>


                            {/* Mobile Menu Toggle Icon */}
                            <MobileMenuToggle
                                isOpen={isSidenavOpen}
                                onClick={() => setIsSidenavOpen(!isSidenavOpen)}
                            />

                        </div>
                    </div>
                </div>
            </header>

            {/* Render the Search Overlay component */}
            <SearchbarComponent
                isOpen={isSearchOpen}
                onClose={() => setIsSearchOpen(false)}
            />

            {/* NEW: Render the Mobile Sidenav */}
            <MobileSidenav
                isOpen={isSidenavOpen}
                onClose={() => setIsSidenavOpen(false)}
            />
        </>
    );
}

export default StickyTransparentNavbar;