// "use client";

// import Link from "next/link";
// import {
//     Drawer,
//     Accordion,
//     AccordionSummary,
//     AccordionDetails,
//     IconButton,
// } from "@mui/material";
// import MenuIcon from "@mui/icons-material/Menu";
// import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
// import CloseIcon from "@mui/icons-material/Close";
// import { useState } from "react";
// import Image from "next/image";
// import { routes } from "@/src/config/routes";
// import CountrySelect from "./country-dropdown";
// import CurrencySelect from "./currency-select";
// import { createSlug } from "@/src/utils/helpers";

// type MenuItem = {
//     title: string;
//     href: string;
//     children?: MenuItem[];
//     relation?: any;
// };

// type NavItem = {
//     title: string;
//     href: string;
//     submenu?: MenuItem[];
// };

// function RecursiveMenu({
//     items,
//     onClose,
// }: {
//     items: MenuItem[];
//     onClose: () => void;
// }) {
//     return (
//         <>
//             {items.map((item) =>
//                 item.children?.length ? (
//                     <Accordion
//                         key={item.title}
//                         disableGutters
//                         elevation={0}
//                         sx={{ boxShadow: "none" }}
//                     >
//                         <AccordionSummary expandIcon={<ExpandMoreIcon />}>
//                             {item.title}
//                         </AccordionSummary>

//                         <AccordionDetails sx={{ pl: 2 }}>
//                             <RecursiveMenu
//                                 items={item.children}
//                                 onClose={onClose}
//                             />
//                         </AccordionDetails>
//                     </Accordion>
//                 ) : (
//                     <Link
//                         key={item.title}
//                         href={
//                             item?.relation?.[0]?.targets?.[0]?.slug
//                                 ? routes.industries(
//                                     item.relation[0].targets[0].slug
//                                 )
//                                 : {
//                                     pathname: item?.href || "/",
//                                     query: {
//                                         category: createSlug(item?.title),
//                                     },
//                                 }
//                         }
//                         onClick={onClose}
//                         className="block py-3 text-sm text-gray-700"
//                     >
//                         {item.title}
//                     </Link>
//                 )
//             )}
//         </>
//     );
// }

// export default function MobileDrawer({
//     navItems,
// }: {
//     navItems: NavItem[];
// }) {
//     const [open, setOpen] = useState(false);

//     return (
//         <>
//             <IconButton
//                 className="xl:hidden lg:hidden"
//                 onClick={() => setOpen(true)}
//             >
//                 <MenuIcon />
//             </IconButton>

//             <Drawer
//                 anchor="left"
//                 open={open}
//                 onClose={() => setOpen(false)}
//             >
//                 <div className="w-[320px]">

//                     <div className="flex items-center justify-between p-5 border-b">
//                         <Link href={routes.home}>
//                             <Image
//                                 src="/images/logo.png"
//                                 alt="Dynatech"
//                                 width={180}
//                                 height={55}
//                                 priority
//                                 className="w-[130px] sm:w-[160px] lg:w-[190px]"
//                             />
//                         </Link>
//                         <IconButton onClick={() => setOpen(false)}>
//                             <CloseIcon />
//                         </IconButton>
//                     </div>
//                     {/* <div className="flex items-center justify-between gap-3 px-5 py-4 border-b">
//                         <div className="flex-1">
//                             <CountrySelect />
//                         </div>

//                         <div className="flex-1">
//                             <CurrencySelect />
//                         </div>
//                     </div> */}


//                     <div className="p-2">
//                         <div className="p-2">
//                             {navItems?.map((item) =>
//                                 item?.submenu && item.submenu.length > 0 ? (
//                                     <Accordion
//                                         key={item.title}
//                                         disableGutters
//                                         elevation={0}
//                                         sx={{ boxShadow: "none" }}
//                                     >
//                                         <AccordionSummary
//                                             expandIcon={<ExpandMoreIcon />}
//                                         >
//                                             {item.title}
//                                         </AccordionSummary>

//                                         <AccordionDetails>
//                                             <RecursiveMenu items={item.submenu} onClose={() => setOpen(false)} />
//                                         </AccordionDetails>
//                                     </Accordion>
//                                 ) : (
//                                     <Link
//                                         key={item.title}
//                                         href={item.href || "#"}
//                                         onClick={() => setOpen(false)}
//                                         className="block py-4 px-4 text-gray-700"
//                                     >
//                                         {item.title}
//                                     </Link>
//                                 )
//                             )}
//                         </div>

//                     </div>
//                 </div>
//             </Drawer>
//         </>
//     );
// }

"use client";

import Link from "next/link";
import {
    Drawer,
    Accordion,
    AccordionSummary,
    AccordionDetails,
    IconButton,
} from "@mui/material";
import MenuIcon from "@mui/icons-material/Menu";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import CloseIcon from "@mui/icons-material/Close";
import { useState } from "react";
import Image from "next/image";

import { routes } from "@/src/config/routes";
import CountryCurrencySelect from "./country-currency-select";

type MenuItem = {
    id: number | string;
    title: string;
    href: string;
    enableRelation: boolean;
    relation: any[];
    menuType: string;
    linkedMenuItemId: string | number | null;
    linkedMenuItemName: string | null;
    megaMenu: boolean;
    submenu: MenuItem[];
    children?: MenuItem[];
    customLink?: string | null;
};

type NavItem = {
    title: string;
    href: string;
    submenu?: MenuItem[];
};

const slugify = (value: string) => {
    return value
        ?.trim()
        .toLowerCase()
        .replace(/&/g, "and")
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "");
};

const getProductCategoryUrl = (item: MenuItem) => {
    const linkedName = item?.linkedMenuItemName;

    if (linkedName) {
        const categories = linkedName
            .split("=>")
            .map((part) => slugify(part))
            .filter(Boolean);

        if (categories.length > 0) {
            return `/product-category/${categories.join("/")}`;
        }
    }

    // Fallback if linkedMenuItemName is unavailable
    if (
        item?.linkedMenuItemId !== null &&
        item?.linkedMenuItemId !== undefined
    ) {
        const linkedId = String(item.linkedMenuItemId);

        const categories = linkedId
            .split("-")
            .filter(Boolean)
            .map((part) => slugify(part));

        if (categories.length > 0) {
            return `/product-category/${categories.join("/")}`;
        }
    }

    return item?.href || "#";
};

/**
 * Get the correct URL for any menu item.
 */
const getMenuItemUrl = (item: MenuItem) => {
    // Industry relation
    const relationSlug = item?.relation?.[0]?.targets?.[0]?.slug;

    if (relationSlug) {
        return routes.industries(relationSlug);
    }

    // Product category
    if (
        item?.linkedMenuItemName ||
        item?.linkedMenuItemId ||
        item?.href === "/product-category"
    ) {
        return getProductCategoryUrl(item);
    }

    if (item?.customLink?.trim()) {
        return item.customLink;
    }

    return item?.href || "#";
};

function RecursiveMenu({
    items,
    onClose,
}: {
    items: MenuItem[];
    onClose: () => void;
}) {
    return (
        <>
            {items?.map((item) => {
                const children =
                    item?.submenu?.length
                        ? item.submenu
                        : item?.children?.length
                            ? item.children
                            : [];

                const hasChildren = children.length > 0;

                return hasChildren ? (
                    <Accordion
                        key={`${item.title}-${item.linkedMenuItemId || ""}`}
                        disableGutters
                        elevation={0}
                        sx={{
                            boxShadow: "none",
                            "&:before": {
                                display: "none",
                            },
                        }}
                    >
                        <AccordionSummary
                            expandIcon={<ExpandMoreIcon />}
                            sx={{
                                px: 1,
                                minHeight: "48px",
                            }}
                        >
                            <span className="text-sm text-gray-700">
                                {item.title}
                            </span>
                        </AccordionSummary>

                        <AccordionDetails
                            sx={{
                                pl: 2,
                                pr: 0,
                                pb: 0,
                            }}
                        >
                            <RecursiveMenu
                                items={children}
                                onClose={onClose}
                            />
                        </AccordionDetails>
                    </Accordion>
                ) : (
                    <Link
                        key={`${item.title}-${item.linkedMenuItemId || ""}`}
                        href={getMenuItemUrl(item)}
                        onClick={onClose}
                        className="block py-3 text-sm text-gray-700 hover:text-secondary"
                    >
                        {item.title}
                    </Link>
                );
            })}
        </>
    );
}

export default function MobileDrawer({
    navItems,
    isTransparentHeader = false,
}: {
    navItems: NavItem[];
    isTransparentHeader?: boolean;
}) {
    const [open, setOpen] = useState(false);

    const closeDrawer = () => {
        setOpen(false);
    };

    return (
        <>
            <IconButton
                className="xl:hidden lg:hidden"
                onClick={() => setOpen(true)}
            >
                <MenuIcon sx={{ color: isTransparentHeader ? "#ffffff" : "#000000" }} />
            </IconButton>

            <Drawer
                anchor="left"
                open={open}
                onClose={closeDrawer}
            >
                <div className="w-[320px] max-w-[85vw]">

                    {/* Header */}
                    <div className="flex items-center justify-between border-b p-5">
                        <Link
                            href={routes.home}
                            onClick={closeDrawer}
                        >
                            <Image
                                src="/images/logo.png"
                                alt="Dynatech"
                                width={180}
                                height={55}
                                priority
                                className="w-[130px] sm:w-[160px] lg:w-[190px]"
                            />
                        </Link>

                        <IconButton onClick={closeDrawer}>
                            <CloseIcon />
                        </IconButton>
                    </div>

                    {/* Navigation */}
                    <div className="p-2">
                        {navItems?.map((item) => {
                            const children = item?.submenu || [];
                            const hasChildren = children.length > 0;

                            return hasChildren ? (
                                <Accordion
                                    key={item.title}
                                    disableGutters
                                    elevation={0}
                                    sx={{
                                        boxShadow: "none",
                                        "&:before": {
                                            display: "none",
                                        },
                                    }}
                                >
                                    <AccordionSummary
                                        expandIcon={<ExpandMoreIcon />}
                                    >
                                        <span className="text-sm font-medium text-primary">
                                            {item.title}
                                        </span>
                                    </AccordionSummary>

                                    <AccordionDetails>
                                        <RecursiveMenu
                                            items={children}
                                            onClose={closeDrawer}
                                        />
                                    </AccordionDetails>
                                </Accordion>
                            ) : (
                                <Link
                                    key={item.title}
                                    href={item.href || "#"}
                                    onClick={closeDrawer}
                                    className="block px-4 py-4 text-gray-700 hover:text-secondary"
                                >
                                    {item.title}
                                </Link>
                            );
                        })}
                    </div>

                    <div className="border-t border-gray-100 p-4 mt-2">
                        <CountryCurrencySelect />
                    </div>
                </div>
            </Drawer>
        </>
    );
}

