"use client";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import React, { useState, useEffect, useLayoutEffect, useRef } from "react";
import {
    clearStoredLocale,
    DEFAULT_LOCALE,
    getDefaultLocale,
    getMergedLanguageSectionLabel,
    getMergedUserMenuLabels,
    getStoredLocale,
    getStoredLocaleRaw,
    LOCALE_CHANGE_EVENT,
    localeConfigEntryIsDefault,
    mapApiCodeToLocaleCode,
    refreshStorefrontSwitcherFromApi,
    resolveLocaleCodeFromRaw,
    setStoredLocaleTag,
    STOREFRONT_SWITCHER_UPDATE_EVENT,
    type LocaleCode,
} from "@/i18n/localeSwitcher";
import {
    Disclosure,
    DisclosureButton,
    DisclosurePanel,
} from "@headlessui/react";

const IconHamburger = () => {
    return (
        <svg width="27" height="21" viewBox="0 0 27 21" fill="none" xmlns="http://www.w3.org/2000/svg">
            <line x1="1.5" y1="-1.5" x2="20.5" y2="-1.5" transform="matrix(1 0 0 -1 5 0)" stroke="black" strokeWidth="3" strokeLinecap="round" />
            <line x1="6.5" y1="19.5" x2="25.5" y2="19.5" stroke="black" strokeWidth="3" strokeLinecap="round" />
            <line x1="1.5" y1="10.5" x2="25.5" y2="10.5" stroke="black" strokeWidth="3" strokeLinecap="round" />
        </svg>

    );
}
const IconClose = () => {
    return (
        <svg width="23" height="23" viewBox="0 0 23 23" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.728489 22.2696C0.801464 22.3426 0.888123 22.4006 0.983511 22.4401C1.0789 22.4796 1.18115 22.5 1.28441 22.5C1.38766 22.5 1.48991 22.4796 1.5853 22.4401C1.68069 22.4006 1.76735 22.3426 1.84032 22.2696L11.4971 12.6136L21.1579 22.2696C21.3053 22.417 21.5053 22.4998 21.7138 22.4998C21.9223 22.4998 22.1223 22.417 22.2697 22.2696C22.4172 22.1221 22.5 21.9222 22.5 21.7137C22.5 21.5052 22.4172 21.3053 22.2697 21.1578L12.609 11.5019L22.2658 1.84198C22.4132 1.69455 22.4961 1.4946 22.4961 1.28611C22.4961 1.07762 22.4132 0.877672 22.2658 0.730247C22.1184 0.582822 21.9184 0.5 21.7099 0.5C21.5014 0.5 21.3014 0.582822 21.154 0.730247L11.4971 10.3901L1.83639 0.734176C1.68608 0.605461 1.49272 0.538202 1.29497 0.54584C1.09722 0.553478 0.909628 0.635449 0.769691 0.775374C0.629754 0.915299 0.547775 1.10287 0.540137 1.30061C0.532499 1.49834 0.599763 1.69168 0.728489 1.84198L10.3853 11.5019L0.728489 21.1618C0.582143 21.309 0.5 21.5081 0.5 21.7157C0.5 21.9232 0.582143 22.1224 0.728489 22.2696Z" fill="black" stroke="black" />
        </svg>

    );
}

const IconProfileMenu = () => {
    return (
        <svg width="5" height="21" viewBox="0 0 5 21" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="2.5" cy="2.5" r="2.5" fill="#282828" />
            <circle cx="2.5" cy="10.5" r="2.5" fill="#282828" />
            <circle cx="2.5" cy="18.5" r="2.5" fill="#282828" />
        </svg>

    );
}

const IconProfile = () => (
    <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 26 26" fill="none">
        <path d="M13 0C10.4288 0 7.91543 0.762437 5.77759 2.19089C3.63975 3.61935 1.97351 5.64967 0.989572 8.02511C0.0056327 10.4006 -0.251811 13.0144 0.249797 15.5362C0.751405 18.0579 1.98953 20.3743 3.80762 22.1924C5.6257 24.0105 7.94208 25.2486 10.4638 25.7502C12.9856 26.2518 15.5994 25.9944 17.9749 25.0104C20.3503 24.0265 22.3806 22.3602 23.8091 20.2224C25.2376 18.0846 26 15.5712 26 13C25.9964 9.5533 24.6256 6.24881 22.1884 3.81163C19.7512 1.37445 16.4467 0.00363977 13 0ZM6.26 21.6875C6.98342 20.5561 7.98001 19.625 9.15791 18.9801C10.3358 18.3351 11.6571 17.9971 13 17.9971C14.3429 17.9971 15.6642 18.3351 16.8421 18.9801C18.02 19.625 19.0166 20.5561 19.74 21.6875C17.8129 23.1862 15.4413 23.9999 13 23.9999C10.5587 23.9999 8.18708 23.1862 6.26 21.6875ZM9 12C9 11.2089 9.2346 10.4355 9.67413 9.77772C10.1137 9.11992 10.7384 8.60723 11.4693 8.30448C12.2002 8.00173 13.0044 7.92252 13.7804 8.07686C14.5563 8.2312 15.269 8.61216 15.8284 9.17157C16.3878 9.73098 16.7688 10.4437 16.9231 11.2196C17.0775 11.9956 16.9983 12.7998 16.6955 13.5307C16.3928 14.2616 15.8801 14.8863 15.2223 15.3259C14.5645 15.7654 13.7911 16 13 16C11.9391 16 10.9217 15.5786 10.1716 14.8284C9.42143 14.0783 9 13.0609 9 12ZM21.22 20.3012C20.1047 18.6851 18.5365 17.4348 16.7125 16.7075C17.6923 15.9358 18.4072 14.878 18.7579 13.6811C19.1086 12.4843 19.0776 11.2079 18.6693 10.0294C18.2609 8.851 17.4955 7.8291 16.4794 7.10586C15.4634 6.38262 14.2472 5.99397 13 5.99397C11.7528 5.99397 10.5366 6.38262 9.52058 7.10586C8.50452 7.8291 7.73909 8.851 7.33074 10.0294C6.92238 11.2079 6.8914 12.4843 7.24209 13.6811C7.59279 14.878 8.30773 15.9358 9.2875 16.7075C7.46353 17.4348 5.89529 18.6851 4.78 20.3012C3.37072 18.7165 2.44959 16.7581 2.12756 14.6619C1.80553 12.5657 2.09631 10.4211 2.9649 8.48637C3.83349 6.55163 5.24285 4.90922 7.02326 3.75692C8.80367 2.60462 10.8792 1.99156 13 1.99156C15.1208 1.99156 17.1963 2.60462 18.9767 3.75692C20.7572 4.90922 22.1665 6.55163 23.0351 8.48637C23.9037 10.4211 24.1945 12.5657 23.8724 14.6619C23.5504 16.7581 22.6293 18.7165 21.22 20.3012Z" fill="#053F31" />
    </svg>
);

const IconLogout = () => (
    <svg xmlns="http://www.w3.org/2000/svg" width="23" height="26" viewBox="0 0 23 26" fill="none">
        <path d="M17.3143 15.0991C16.8697 15.0991 16.5092 15.4628 16.5092 15.9115V19.0828C16.5092 19.6953 16.0155 20.1936 15.4085 20.1936H11.1869V7.50236C11.1869 6.49862 10.6929 5.63517 9.83148 5.13325L3.80962 1.62483H15.4085C16.0155 1.62483 16.5092 2.1231 16.5092 2.73561V6.35294C16.5092 6.80165 16.8697 7.16536 17.3143 7.16536C17.7589 7.16536 18.1194 6.80165 18.1194 6.35294V2.73561C18.1194 1.22721 16.9033 0 15.4085 0H2.71089C1.21612 0 0 1.22721 0 2.73561V19.8957C0 20.8995 0.494015 21.7629 1.35545 22.2648L7.12059 25.6236C7.55136 25.8745 8.01367 26.0001 8.47604 26C8.93835 26 9.40082 25.8745 9.83143 25.6236C10.6929 25.1218 11.1869 24.2583 11.1869 23.2545V21.8184H15.4084C16.9033 21.8184 18.1193 20.5912 18.1193 19.0828V15.9115C18.1194 15.4628 17.759 15.0991 17.3143 15.0991ZM9.57678 23.2545C9.57678 23.6681 9.38135 24.0097 9.02641 24.2164C8.67152 24.4232 8.28061 24.4232 7.92572 24.2164L2.16052 20.8577C1.80558 20.6509 1.61015 20.3092 1.61015 19.8957V2.73561C1.61015 2.57211 1.64532 2.41673 1.70847 2.27685L9.02641 6.54041C9.38135 6.74717 9.57678 7.08884 9.57678 7.50236V23.2545ZM22.7642 11.4837L20.1481 14.1236C19.9909 14.2823 19.7848 14.3616 19.5788 14.3616C19.3728 14.3616 19.1668 14.2823 19.0096 14.1236C18.6952 13.8064 18.6952 13.292 19.0096 12.9747L20.2514 11.7216H12.8547C12.4101 11.7216 12.0497 11.3579 12.0497 10.9092C12.0497 10.4605 12.4101 10.0968 12.8547 10.0968H20.2513L19.0096 8.84371C18.6952 8.52646 18.6952 8.01205 19.0096 7.6948C19.324 7.3775 19.8337 7.3775 20.1481 7.6948L22.7642 10.3347C23.0786 10.652 23.0786 11.1665 22.7642 11.4837Z" fill="#053F31" />
    </svg>
);

const IconDashboard = () => (
    <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path fillRule="evenodd" clipRule="evenodd" d="M11.7188 15.6241C11.7188 15.0022 11.4719 14.4061 11.032 13.9671C10.8145 13.7493 10.5562 13.5765 10.2719 13.4587C9.98757 13.3409 9.68279 13.2803 9.375 13.2804H3.90625C3.28438 13.2804 2.68828 13.5272 2.24922 13.9671C2.03143 14.1846 1.85867 14.4429 1.74083 14.7272C1.623 15.0115 1.5624 15.3163 1.5625 15.6241V21.0929C1.5625 21.7147 1.80938 22.3108 2.24922 22.7499C2.4667 22.9677 2.72501 23.1404 3.00934 23.2583C3.29368 23.3761 3.59846 23.4367 3.90625 23.4366H9.375C9.99687 23.4366 10.593 23.1897 11.032 22.7499C11.2498 22.5324 11.4226 22.2741 11.5404 21.9898C11.6583 21.7054 11.7189 21.4006 11.7188 21.0929V15.6241ZM23.4375 15.6241C23.4375 15.0022 23.1906 14.4061 22.7508 13.9671C22.5333 13.7493 22.275 13.5765 21.9907 13.4587C21.7063 13.3409 21.4015 13.2803 21.0938 13.2804H15.625C15.0031 13.2804 14.407 13.5272 13.968 13.9671C13.7502 14.1846 13.5774 14.4429 13.4596 14.7272C13.3417 15.0115 13.2811 15.3163 13.2812 15.6241V21.0929C13.2812 21.7147 13.5281 22.3108 13.968 22.7499C14.1855 22.9677 14.4438 23.1404 14.7281 23.2583C15.0124 23.3761 15.3172 23.4367 15.625 23.4366H21.0938C21.7156 23.4366 22.3117 23.1897 22.7508 22.7499C22.9686 22.5324 23.1413 22.2741 23.2592 21.9898C23.377 21.7054 23.4376 21.4006 23.4375 21.0929V15.6241ZM20.0164 11.5561L23.2758 8.29677C23.7152 7.85725 23.962 7.26121 23.962 6.63973C23.962 6.01826 23.7152 5.42222 23.2758 4.9827L20.0164 1.72333C19.5769 1.28394 18.9809 1.03711 18.3594 1.03711C17.7379 1.03711 17.1419 1.28394 16.7023 1.72333L13.443 4.9827C13.0036 5.42222 12.7568 6.01826 12.7568 6.63973C12.7568 7.26121 13.0036 7.85725 13.443 8.29677L16.7023 11.5561C17.1419 11.9955 17.7379 12.2424 18.3594 12.2424C18.9809 12.2424 19.5769 11.9955 20.0164 11.5561ZM11.7188 3.90536C11.7188 3.28348 11.4719 2.68739 11.032 2.24833C10.8145 2.03054 10.5562 1.85778 10.2719 1.73994C9.98757 1.62211 9.68279 1.5615 9.375 1.56161H3.90625C3.28438 1.56161 2.68828 1.80848 2.24922 2.24833C2.03143 2.46581 1.85867 2.72412 1.74083 3.00845C1.623 3.29279 1.5624 3.59757 1.5625 3.90536V9.37411C1.5625 9.99598 1.80938 10.5921 2.24922 11.0311C2.4667 11.2489 2.72501 11.4217 3.00934 11.5395C3.29368 11.6574 3.59846 11.718 3.90625 11.7179H9.375C9.99687 11.7179 10.593 11.471 11.032 11.0311C11.2498 10.8137 11.4226 10.5554 11.5404 10.271C11.6583 9.98668 11.7189 9.6819 11.7188 9.37411V3.90536Z" fill="#053F31" />
    </svg>

);

const MobileBgImage = () => {
    return (
        <img src="/nevigation_menu_bg_design.png" alt="bg_image" className="h-full w-full object-contain object-bottom" />
    );
}

function classNames(...classes: (string | boolean | undefined)[]): string {
    return classes.filter(Boolean).join(" ");
}

type StoreLocaleEntry = { code: string; name: string; is_default: boolean };

function isLocalePanelDefaultOption(opt: StoreLocaleEntry): boolean {
    if (!String(opt.code ?? "").trim()) return true;
    return String(opt.name ?? "").trim().toLowerCase() === "default";
}

function storeLocaleRowMatchesUiLocale(opt: StoreLocaleEntry, uiLocale: LocaleCode): boolean {
    const c = String(opt.code ?? "").trim();
    if (c === uiLocale) return true;
    return mapApiCodeToLocaleCode(c) === uiLocale;
}

function isStoreLocaleRowActive(opt: StoreLocaleEntry, list: StoreLocaleEntry[], uiLocale: LocaleCode): boolean {
    const sameUi = list.filter((o) => storeLocaleRowMatchesUiLocale(o, uiLocale));
    const listMatchesStored = sameUi.length > 0;

    if (listMatchesStored) {
        if (!storeLocaleRowMatchesUiLocale(opt, uiLocale)) return false;
        if (sameUi.length <= 1) return true;
        const defaultSibling = sameUi.find((o) => o.is_default);
        if (defaultSibling) return opt.code === defaultSibling.code;
        return opt.code === sameUi[0]!.code;
    }

    const defaults = list.filter((o) => o.is_default);
    if (defaults.length === 0) return false;
    if (defaults.length === 1) return opt.code === defaults[0]!.code;
    return opt.is_default;
}

/** Trigger label: API `name` for the active list row, else raw tag / UI locale. */
function localeSwitcherTriggerLabel(list: StoreLocaleEntry[], uiLocale: LocaleCode): string {
    const raw = getStoredLocaleRaw();
    const rawTrim = raw != null && String(raw).trim() ? String(raw).trim() : null;
    if (list.length > 0) {
        const activeRow = list.find((opt) => isStoreLocaleRowActive(opt, list, uiLocale));
        if (activeRow) {
            const display = String(activeRow.name ?? "").trim();
            return display || String(activeRow.code ?? "").trim();
        }
        if (rawTrim) {
            const byRaw = list.find((o) => String(o.code ?? "").trim() === rawTrim);
            if (byRaw) {
                const display = String(byRaw.name ?? "").trim();
                return display || rawTrim;
            }
        }
    }
    return (rawTrim ?? uiLocale).trim();
}

function LocaleCaretIcon() {
    return (
        <svg width="10" height="6" viewBox="0 0 10 6" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden className="shrink-0 text-current">
            <path d="M5 6L0 0H10L5 6Z" fill="currentColor" />
        </svg>
    );
}

type LocaleSwitcherPanelProps = {
    uiLocale: LocaleCode;
    open: boolean;
    onToggle: () => void;
    containerRef: React.RefObject<HTMLDivElement | null>;
    applyLocale: (code: LocaleCode | "", medusaStoreCode?: string) => void;
    languageListboxAriaLabel: string;
    rowAlignClass?: string;
    panelPosition?: "end" | "center";
    panelMatchTrigger?: boolean;
};

function LocaleSwitcherPanel({
    uiLocale,
    open,
    onToggle,
    containerRef,
    applyLocale,
    languageListboxAriaLabel,
    rowAlignClass = "items-end",
    panelPosition = "end",
    panelMatchTrigger = false,
}: LocaleSwitcherPanelProps) {
    const [menuFixedStyle, setMenuFixedStyle] = useState<React.CSSProperties | undefined>(undefined);
    const [storeLocales, setStoreLocales] = useState<StoreLocaleEntry[]>([]);
    const [localeTriggerHydrated, setLocaleTriggerHydrated] = useState(false);
    const [localeConfigReady, setLocaleConfigReady] = useState(false);

    useEffect(() => {
        setLocaleTriggerHydrated(true);
    }, []);

    useEffect(() => {
        let cancelled = false;
        const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        if (!base) {
            setLocaleConfigReady(true);
            return;
        }

        setLocaleConfigReady(false);

        const headerLocale = (getStoredLocaleRaw() ?? uiLocale).trim();

        (async () => {
            try {
                const res = await fetch(`${base}/store/locale-config`, {
                    method: "GET",
                    headers: {
                        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                        "x-medusa-locale": headerLocale,
                    },
                    cache: "no-store",
                });
                if (cancelled) return;
                if (!res.ok) {
                    if (!cancelled) setStoreLocales([]);
                    return;
                }
                const data = (await res.json()) as {
                    locales?: (StoreLocaleEntry & { isDefault?: boolean })[];
                    default_locale?: string | null;
                };
                const list = Array.isArray(data.locales)
                    ? data.locales.map((row) => ({
                          code: String(row.code ?? "").trim(),
                          name: String(row.name ?? "").trim(),
                          is_default: localeConfigEntryIsDefault(row),
                      }))
                    : [];
                if (!cancelled) setStoreLocales(list);
            } catch {
                if (!cancelled) setStoreLocales([]);
            } finally {
                if (!cancelled) setLocaleConfigReady(true);
            }
        })();

        return () => {
            cancelled = true;
        };
    }, [uiLocale]);

    useLayoutEffect(() => {
        if (!open || !localeConfigReady) {
            setMenuFixedStyle(undefined);
            return;
        }

        const update = () => {
            const root = containerRef.current;
            if (!root) return;
            const r = root.getBoundingClientRect();
            const top = r.bottom + 2;
            const minMenuWidth = Math.max(r.width + 36, 70);

            if (panelPosition === "center") {
                setMenuFixedStyle({
                    position: "fixed",
                    top,
                    left: (r.left + r.width / 2),
                    transform: "translateX(-50%)",
                    minWidth: minMenuWidth,
                    zIndex: 99999,
                });
                return;
            }

            if (panelMatchTrigger) {
                setMenuFixedStyle({
                    position: "fixed",
                    top,
                    left: r.left-30,
                    width: minMenuWidth,
                    zIndex: 99999,
                });
                return;
            }

            setMenuFixedStyle({
                position: "fixed",
                top,
                right: 310,
                minWidth: Math.max(r.width + 40, 100),
                zIndex: 99999,
            });
        };

        update();
        window.addEventListener("scroll", update, true);
        window.addEventListener("resize", update);
        return () => {
            window.removeEventListener("scroll", update, true);
            window.removeEventListener("resize", update);
        };
    }, [open, panelMatchTrigger, panelPosition, localeConfigReady]);

    return (
        <div
            className={classNames(
                "relative shrink-0 flex-col",
                !localeConfigReady && "hidden",
                panelMatchTrigger ? "inline-flex w-max" : "flex",
                rowAlignClass,
                open && "z-[200]",
            )}
            ref={containerRef}
        >
            <button
                type="button"
                onClick={onToggle}
                aria-expanded={open}
                aria-haspopup="listbox"
                className="inline-flex h-9 min-h-[36px] w-full min-w-[6.25rem] cursor-pointer items-center justify-between gap-2 rounded-[6px] border border-[#D1D5DB] bg-white px-3 py-2 font-outfit text-sm font-normal leading-none text-[#364742] shadow-none outline-none ring-offset-2 transition-colors hover:bg-neutral-50 focus-visible:ring-2 focus-visible:ring-[#053F31]/40 sm:h-10 sm:min-h-[40px] sm:px-3.5 sm:text-[15px]"
            >
                <span className="min-w-0 h-4 truncate text-left">
                    {localeTriggerHydrated ? localeSwitcherTriggerLabel(storeLocales, uiLocale) : uiLocale}
                </span>
                <LocaleCaretIcon />
            </button>
            {open && localeConfigReady && menuFixedStyle && (
                <div
                    className="pointer-events-auto flex justify-stretch border border-[#DDDDDD] bg-white py-1 shadow-sm"
                    style={menuFixedStyle}
                    role="listbox"
                    aria-label={languageListboxAriaLabel}
                >
                    <div
                        className={classNames(
                            "flex w-full flex-col",
                            panelMatchTrigger ? "min-w-0" : "min-w-[7rem] sm:min-w-[8rem]",
                        )}
                    >
                        {storeLocales.map((opt) => {
                            const rowKey = String(opt.code ?? "").trim() || `default-${opt.name}`;
                            const active = isStoreLocaleRowActive(opt, storeLocales, uiLocale);
                            return (
                                <button
                                    key={rowKey}
                                    type="button"
                                    role="option"
                                    aria-selected={active}
                                    onMouseDown={(e) => e.stopPropagation()}
                                    onClick={() => {
                                        if (isLocalePanelDefaultOption(opt)) {
                                            applyLocale("");
                                            return;
                                        }
                                        const raw = String(opt.code ?? "").trim();
                                        if (!raw) return;
                                        const mapped = mapApiCodeToLocaleCode(raw) ?? DEFAULT_LOCALE;
                                        applyLocale(mapped, raw);
                                    }}
                                    className={classNames(
                                        "font-outfit w-full px-5 py-2.5 text-center text-sm font-bold cursor-pointer transition-colors sm:px-6 sm:text-[15px]",
                                        active
                                            ? "bg-[#053F31] text-white"
                                            : "text-black hover:bg-[#053F31]/5",
                                    )}
                                >
                                    {opt.name}
                                </button>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
}

type User = {
    name?: string;
    fullName?: string;
    first_name?: string;
    last_name?: string;
    image_url?: string;
    company_business_name?: string;
    token?: string;
    email?: string;
} | null;

function getCookieUser(): User | null {
    if (typeof document === "undefined") return null;
    const cookieNames = ["currentUser", "biomket_user", "biomketUser"];
    for (const name of cookieNames) {
        const key = `${name}=`;
        const part = document.cookie
            .split("; ")
            .find((row) => row.startsWith(key));
        if (!part) continue;
        try {
            const rawValue = decodeURIComponent(part.slice(key.length));
            return rawValue ? (JSON.parse(rawValue) as User) : null;
        } catch {
            continue;
        }
    }
    return null;
}

function getStoredUser(): User | null {
    if (typeof window === "undefined") return null;
    try {
        const raw = localStorage.getItem("currentUser");
        const localUser = raw ? (JSON.parse(raw) as User) : null;
        const cookieUser = getCookieUser();
        if (!localUser && !cookieUser) return null;
        return {
            ...cookieUser,
            ...localUser,
            image_url: localUser?.image_url || cookieUser?.image_url,
            company_business_name: localUser?.company_business_name || cookieUser?.company_business_name,
        };
    } catch {
        return null;
    }
}

function getDisplayName(user: User): string {
    if (!user) return "User";
    const fullName = user.fullName || (user.first_name || user.last_name ? (user.first_name || "") + " " + (user.last_name || "") : "");
    return (fullName.trim() || user.name || "User").trim() || "User";
}

function getProfileAvatarSrc(user: User): string {
    const directAvatar =
        String(
            user?.image_url ??
            ""
        ).trim();
    if (directAvatar) return directAvatar;

    const name = String(
        `${user?.first_name || ""} ${user?.last_name || ""}`.trim() ||
        user?.company_business_name ||
        "User"
    ).trim();
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=053F31&color=ffffff&size=256`;
}

interface NavbarData {
    page: {
        sections: {
            id: string;
            name: string;
            key: string;
            position: number;
            components: {
                instance: {
                    data: any;
                };
            }[];
        }[];
    };
}

export default function Navbar() {
    const router = useRouter();
    const [user, setUser] = useState<User>(null);
    const [dropdownOpen, setDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const [localeMenuOpen, setLocaleMenuOpen] = useState(false);
    const localeDesktopRef = useRef<HTMLDivElement>(null);
    const localeMobileRef = useRef<HTMLDivElement>(null);
    const [profileLocaleMenuOpen, setProfileLocaleMenuOpen] = useState(false);
    const profileLocaleRef = useRef<HTMLDivElement>(null);
    const profileLocaleMobileRef = useRef<HTMLDivElement>(null);
    const pathname = usePathname();
    const [navbarData, setNavbarData] = useState<NavbarData | null>(null);
    const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);
    const [menuLabelsRev, setMenuLabelsRev] = useState(0);

    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const raw = getStoredLocaleRaw();
        setUiLocale(raw ? resolveLocaleCodeFromRaw(raw) : getStoredLocale());
    }, []);

    void menuLabelsRev;
    const mergedUserMenu = getMergedUserMenuLabels(uiLocale);
    const languageListboxAriaLabel = getMergedLanguageSectionLabel(uiLocale);

    const commitLocaleSelection = (code: LocaleCode | "", medusaStoreCode?: string) => {
        if (code === "") {
            clearStoredLocale();
            setUiLocale(getDefaultLocale());
            router.refresh();
            return;
        }
        const tag = (medusaStoreCode ?? code).trim();
        if (tag) setStoredLocaleTag(tag);
        setUiLocale(code);
        router.refresh();
    };

    const applyGuestLocale = (code: LocaleCode | "", medusaStoreCode?: string) => {
        commitLocaleSelection(code, medusaStoreCode);
        setLocaleMenuOpen(false);
    };

    const applyProfileLocale = (code: LocaleCode | "", medusaStoreCode?: string) => {
        commitLocaleSelection(code, medusaStoreCode);
        setProfileLocaleMenuOpen(false);
    };

    useEffect(() => {
        let isMounted = true;

        const fetchNavbarData = async () => {
            try {
                const res = await fetch(
                    `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/navbar`,
                    {
                        method: "GET",
                        headers: {
                            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                            "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
                        },
                        cache: "no-store"
                    }
                );

                if (!res.ok) return;
                const data = await res.json();
                if (isMounted) {
                    setNavbarData(data);
                }
            } catch (error) {
                if (error instanceof TypeError && /fetch/i.test(error.message)) return;
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchNavbarData();

        const onLocaleChange = () => {
            setUiLocale(getStoredLocale());
            void fetchNavbarData();
            void refreshStorefrontSwitcherFromApi();
        };
        if (typeof window !== "undefined") {
            window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
        }
        return () => {
            isMounted = false;
            if (typeof window !== "undefined") {
                window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
            }
        };
    }, [pathname]);

    useEffect(() => {
        const bump = () => setMenuLabelsRev((n) => n + 1);
        if (typeof window !== "undefined") {
            window.addEventListener(STOREFRONT_SWITCHER_UPDATE_EVENT, bump);
            void refreshStorefrontSwitcherFromApi();
        }
        return () => {
            if (typeof window !== "undefined") {
                window.removeEventListener(STOREFRONT_SWITCHER_UPDATE_EVENT, bump);
            }
        };
    }, [pathname]);

    useEffect(() => {
        const handleUserChange = () => {
            setUser(getStoredUser());
        };

        handleUserChange();

        window.addEventListener("storage", handleUserChange);
        window.addEventListener("auth-change", handleUserChange);

        return () => {
            window.removeEventListener("storage", handleUserChange);
            window.removeEventListener("auth-change", handleUserChange);
        };
    }, [pathname]);

    useEffect(() => {
        const syncProfile = async () => {
            const currentUser = getStoredUser();
            if (!currentUser || !currentUser.token) return;

            const displayName = getDisplayName(currentUser);
            const isEmailPrefix = currentUser.email && displayName === currentUser.email.split('@')[0];

            if (isEmailPrefix || !currentUser.fullName) {
                try {
                    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
                    const res = await fetch(`${base}/store/customers/profile`, {
                        method: "GET",
                        headers: {
                            "Content-Type": "application/json",
                            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                            "Authorization": `Bearer ${currentUser.token}`
                        },
                    });

                    if (res.ok) {
                        const data = await res.json();
                        const customer = data.profile || data;
                        if (customer.first_name || customer.last_name) {
                            const firstName = customer.first_name || "";
                            const lastName = customer.last_name || "";
                            const fullName = (firstName + " " + lastName).trim();
                            const imageUrl = customer.image_url || "";
                            const updatedUser = {
                                ...currentUser,
                                first_name: firstName,
                                last_name: lastName,
                                fullName: fullName,
                                name: fullName || currentUser.name,
                                image_url: imageUrl || "",
                            };
                            localStorage.setItem("currentUser", JSON.stringify(updatedUser));
                            setUser(updatedUser);
                        }
                    }
                } catch (err) {
                }
            }
        };

        if (user) {
            syncProfile();
        }
    }, [user?.token, pathname]);

    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            const t = event.target as Node;
            if (profileLocaleRef.current?.contains(t) || profileLocaleMobileRef.current?.contains(t)) {
                return;
            }
            if (dropdownRef.current && !dropdownRef.current.contains(t)) {
                setDropdownOpen(false);
                setProfileLocaleMenuOpen(false);
            }
        }
        if (dropdownOpen) {
            document.addEventListener("mousedown", handleClickOutside);
            return () => document.removeEventListener("mousedown", handleClickOutside);
        }
    }, [dropdownOpen]);

    useEffect(() => {
        function handleLocaleClickOutside(event: MouseEvent) {
            const t = event.target as Node;
            if (
                localeDesktopRef.current?.contains(t) ||
                localeMobileRef.current?.contains(t) ||
                profileLocaleRef.current?.contains(t) ||
                profileLocaleMobileRef.current?.contains(t)
            ) {
                return;
            }
            setLocaleMenuOpen(false);
            setProfileLocaleMenuOpen(false);
        }
        if (localeMenuOpen || profileLocaleMenuOpen) {
            document.addEventListener("mousedown", handleLocaleClickOutside);
            return () => document.removeEventListener("mousedown", handleLocaleClickOutside);
        }
    }, [localeMenuOpen, profileLocaleMenuOpen]);

    const isLoggedIn = !!(user && (user.fullName || user.name));
    const profileAvatarSrc = getProfileAvatarSrc(user);
    const showProfileMenuTrigger = isLoggedIn && navbarData != null;

    const pagePayload = (navbarData as any)?.page;
    const sections = pagePayload?.sections ?? (navbarData as any)?.sections;

    const firstComponentByType = (section: any, typeName: string) =>
        section?.components?.find((c: any) => c?.type?.name === typeName) ?? section?.components?.[0];

    const logoSection = sections?.find(
        (s: any) =>
            s.key === "logosection" ||
            s.name === "LogoSection" ||
            s.components?.some((c: any) => c?.type?.name === "image_and_link"),
    );
    const logoComponent = firstComponentByType(logoSection, "image_and_link");
    const logoData = logoComponent?.instance?.data;
    let logoUrl: string | undefined;
    if (typeof logoData?.image === "string" && logoData.image) logoUrl = logoData.image;
    else if (Array.isArray(logoData?.image) && logoData.image[0]) logoUrl = logoData.image[0];
    else if (logoData?.items?.[0]?.image) {
        const img = logoData.items[0].image;
        logoUrl = Array.isArray(img) ? img[0] : img;
    }
    const logoAlt =
        logoData?.image_alt_tag ||
        logoData?.items?.[0]?.image_alt_tag ||
        "biomket_logo";
    const logoLink = logoData?.link || logoData?.items?.[0]?.link || "/";

    const navSection = sections?.find(
        (s: any) =>
            s.key === "navlinksection" ||
            s.name === "NavLinkSection" ||
            s.components?.some((c: any) => c?.type?.name === "navigation"),
    );
    const navComponent = firstComponentByType(navSection, "navigation");
    const rawNavItems = navComponent?.instance?.data?.items;
    const navItems = Array.isArray(rawNavItems) ? rawNavItems : [];

    const authSection = sections?.find(
        (s: any) =>
            s.key === "authentication" ||
            s.name === "AuthSection" ||
            s.components?.some((c: any) => c?.type?.name === "logo_title_description"),
    );
    const authComponent = firstComponentByType(authSection, "logo_title_description");
    const authItems = authComponent?.instance?.data?.items;

    const handleLogout = () => {
        try {
            if (typeof window !== "undefined") {
                localStorage.removeItem("currentUser");
                localStorage.removeItem("biomket_user");
                window.dispatchEvent(new Event("auth-change"));
            }
            setUser(null);
            setDropdownOpen(false);
            router.push("/login");
        } catch { }
    };
    return (
        <div className="w-full bg-white">
            <div className="max-w-[1920px] mx-auto px-[20px] md:px-[40px] xl:px-[60px]">
                {navbarData && <Disclosure
                    as="nav"
                    className="relative bg-white py-[20px] border-b border-[#DDDDDD] font-outfit"
                >
                    {({ open }) => (
                        <>
                            <div className="w-full">
                                <div className="relative flex h-10 items-center justify-between">
                                    <div
                                        className={classNames(
                                            "absolute inset-y-0 right-0 flex items-center lg:hidden",
                                            open && "z-[70]",
                                        )}
                                    >
                                        <DisclosureButton
                                            type="button"
                                            className="group relative inline-flex items-center justify-center rounded-md text-gray-400 p-2"
                                        >
                                            <span className="sr-only">Open main menu</span>
                                            {!open && (
                                                <IconHamburger />
                                            )}
                                            {open && (
                                                <IconClose />
                                            )}
                                        </DisclosureButton>
                                    </div>

                                    <div className="flex h-16 items-center justify-between w-full">
                                        <div className="flex items-center shrink-0">
                                            <Link href={logoLink}>
                                                {logoUrl ? (
                                                    <img src={logoUrl} alt={logoAlt} className="h-[45px]" />
                                                ) : null}
                                            </Link>
                                        </div>

                                        <div className="hidden lg:flex space-x-[30px]">
                                            {navItems.map((item: any, idx: number) => {
                                                const href = item.link || item.href || "/";
                                                const name = item.name || item.title || `Menu ${idx}`;
                                                const isActive = href === "/" ? pathname === "/" : (pathname === href || pathname.startsWith(href + "/"));
                                                return (
                                                    <Link
                                                        key={`${name}-${idx}`}
                                                        href={href}
                                                        aria-current={isActive ? "page" : undefined}
                                                        className={classNames(
                                                            "text-[#000000] font-outfit text-[18px] leading-[150%] hover:font-medium",
                                                            isActive ? "font-medium!" : "font-extralight",
                                                        )}
                                                    >
                                                        {name}
                                                    </Link>
                                                );
                                            })}
                                        </div>

                                        {<div className="hidden lg:flex items-center text-emerald-700 font-outfit gap-[15px]">
                                            {isLoggedIn ? (
                                                <div className="flex items-center gap-[15px]">
                                                    <LocaleSwitcherPanel
                                                        uiLocale={uiLocale}
                                                        open={profileLocaleMenuOpen}
                                                        onToggle={() => setProfileLocaleMenuOpen((o) => !o)}
                                                        containerRef={profileLocaleRef}
                                                        applyLocale={applyProfileLocale}
                                                        languageListboxAriaLabel={languageListboxAriaLabel}
                                                        rowAlignClass="items-end"
                                                        panelPosition="end"
                                                        panelMatchTrigger
                                                    />
                                                    <div className="relative" ref={dropdownRef}>
                                                        {showProfileMenuTrigger ? (
                                                        <button
                                                            type="button"
                                                            onClick={() => setDropdownOpen((o) => !o)}
                                                            className="flex items-center gap-[10px] cursor-pointer rounded-md hover:opacity-90 transition-opacity"
                                                        >
                                                            <img src={profileAvatarSrc} alt="Avatar" className="h-9 w-9 rounded-full object-cover bg-[#DAE6DC]" />
                                                            <p className="font-outfit font-semibold text-[#053F31]">{getDisplayName(user)}</p>
                                                            <span className="text-[#053F31] font-bold pb-1"> <IconProfileMenu /> </span>
                                                        </button>
                                                        ) : null}

                                                        {dropdownOpen && showProfileMenuTrigger && (
                                                            <div className="absolute right-0 top-full z-50 pt-[10px]">
                                                                <div className="rounded-xl border border-[#DAE6DC] bg-[#DAE6DC] p-[20px] min-w-[180px] shadow-md flex flex-col gap-4">
                                                                    <Link href="/dashboard" onClick={() => setDropdownOpen(false)} className="flex items-center gap-[10px] font-semibold text-[#000000] hover:text-[#053F31] transition-colors">
                                                                        <IconDashboard /> {mergedUserMenu.dashboard}
                                                                    </Link>
                                                                    <Link href="/profile" onClick={() => setDropdownOpen(false)} className="flex items-center gap-[10px] font-semibold text-[#000000] hover:text-[#053F31] transition-colors">
                                                                        <IconProfile /> {mergedUserMenu.profile}
                                                                    </Link>
                                                                    <button onClick={handleLogout} className="flex w-full items-center gap-[10px] cursor-pointer font-semibold text-[#000000] hover:text-[#053F31] transition-colors text-left">
                                                                        <IconLogout /> {mergedUserMenu.logout}
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="flex min-w-0 flex-wrap items-center justify-end gap-[15px]">
                                                    <LocaleSwitcherPanel
                                                        uiLocale={uiLocale}
                                                        open={localeMenuOpen}
                                                        onToggle={() => setLocaleMenuOpen((o) => !o)}
                                                        containerRef={localeDesktopRef}
                                                        applyLocale={applyGuestLocale}
                                                        languageListboxAriaLabel={languageListboxAriaLabel}
                                                        rowAlignClass="items-end"
                                                        panelPosition="end"
                                                    />
                                                    {Array.isArray(authItems) &&
                                                        authItems.map((item: any, idx: number) => (
                                                            <React.Fragment key={item.title ?? idx}>
                                                                <Link
                                                                    href={item.description}
                                                                    className={classNames(
                                                                        "hover:text-emerald-900 text-[#053F31] inline-flex items-center gap-[15px]",
                                                                        idx === 0 ? "pr-3" : "ps-3",
                                                                    )}
                                                                >
                                                                    <span dangerouslySetInnerHTML={{ __html: item.svg }} />
                                                                    {item.title}
                                                                </Link>
                                                                {idx < authItems.length - 1 && <span className="px-1 text-gray-300">|</span>}
                                                            </React.Fragment>
                                                        ))}
                                                </div>
                                            )}
                                        </div>}
                                    </div>
                                </div>
                            </div>
                            <DisclosurePanel className="lg:hidden fixed inset-0 z-50 max-w-[100vw] px-[20px] md:px-[40px] xl:px-[60px] overflow-x-hidden overflow-y-auto bg-white">
                                <div className="relative flex h-full min-w-0 max-w-full flex-col overflow-x-hidden">
                                    <div className="absolute bottom-0 left-0 right-0 h-1/2 z-0 overflow-hidden pointer-events-none">
                                        <MobileBgImage />
                                    </div>
                                    <div className="relative z-[100] flex h-20 min-w-0 max-w-full items-center justify-between gap-3 border-b border-[#DDDDDD] bg-white py-5">
                                    <Link href={logoLink}>
                                                {logoUrl ? (
                                                    <img src={logoUrl} alt={logoAlt} className="h-[45px]" />
                                                ) : null}
                                            </Link>
                                        {/* {logoUrl ? <img src={logoUrl} alt={logoAlt} className="h-[35px] max-w-[min(200px,55vw)] shrink object-contain" /> : null} */}

                                        <DisclosureButton
                                            type="button"
                                            aria-label="Close menu"
                                            className="relative z-[100] inline-flex items-center justify-center rounded-md p-2 text-gray-800 hover:bg-black/5"
                                        >
                                            <IconClose />
                                        </DisclosureButton>
                                    </div>
                                    <div className="relative z-10 box-border flex min-h-0 min-w-0 w-full max-w-full flex-1 flex-col items-center justify-center overflow-x-hidden px-5 pt-8">
                                        <div className="w-full min-w-0 max-w-full space-y-[30px] overflow-x-hidden text-center">
                                            {navItems.map((item: any, idx: number) => {
                                                const href = item.link || item.href || "/";
                                                const name = item.name || item.title || `Menu ${idx}`;
                                                const isActive = href === "/" ? pathname === "/" : (pathname === href || pathname.startsWith(href + "/"));
                                                return (
                                                    <DisclosureButton
                                                        key={`${name}-${idx}`}
                                                        as={Link}
                                                        href={href}
                                                        className={classNames(
                                                            "mx-auto block w-full min-w-0 max-w-full overflow-hidden [overflow-wrap:anywhere] px-1 text-center font-outfit text-[18px] leading-[150%] text-[#000000] hover:font-medium",
                                                            isActive ? "font-medium!" : "font-extralight",
                                                        )}
                                                    >
                                                        {name}
                                                    </DisclosureButton>
                                                );
                                            })}
                                        </div>

                                        <div className="mt-5 box-border w-full min-w-0 max-w-full overflow-x-hidden border-t border-[#DDDDDD] pt-5 text-center font-outfit text-emerald-800">
                                            {isLoggedIn ? (
                                                <div className="flex w-full min-w-0 max-w-full flex-col items-center gap-4 text-center">
                                                    <div className="flex w-full min-w-0 max-w-full flex-wrap items-center justify-center gap-3">
                                                        <LocaleSwitcherPanel
                                                            uiLocale={uiLocale}
                                                            open={profileLocaleMenuOpen}
                                                            onToggle={() => setProfileLocaleMenuOpen((o) => !o)}
                                                            containerRef={profileLocaleMobileRef}
                                                            applyLocale={applyProfileLocale}
                                                            languageListboxAriaLabel={languageListboxAriaLabel}
                                                            rowAlignClass="items-center"
                                                            panelPosition="center"
                                                            panelMatchTrigger
                                                        />
                                                        {showProfileMenuTrigger ? (
                                                        <button
                                                            type="button"
                                                            onClick={() => setDropdownOpen((o) => !o)}
                                                            className="flex min-w-0 max-w-full items-center justify-center gap-2 font-bold text-[#053F31] cursor-pointer"
                                                        >
                                                            <img src={profileAvatarSrc} alt="Avatar" className="h-9 w-9 shrink-0 rounded-full object-cover bg-[#DAE6DC]" />
                                                            <span className="min-w-0 max-w-[calc(100%-2.5rem)] truncate">{getDisplayName(user)}</span>
                                                            <span className="text-[#053F31] font-bold pb-1"> <IconProfileMenu /> </span>
                                                        </button>
                                                        ) : null}
                                                    </div>
                                                    {dropdownOpen && showProfileMenuTrigger && (
                                                    <div className="w-full max-w-[18rem] rounded-xl border border-[#DAE6DC] bg-[#DAE6DC] p-[20px] shadow-md flex flex-col gap-4">
                                                        <DisclosureButton as={Link} href="/dashboard" className="flex items-center gap-[10px] font-semibold text-[#000000] hover:text-[#053F31] transition-colors">
                                                            <IconDashboard /> {mergedUserMenu.dashboard}
                                                        </DisclosureButton>
                                                        <DisclosureButton as={Link} href="/profile" className="flex items-center gap-[10px] font-semibold text-[#000000] hover:text-[#053F31] transition-colors">
                                                            <IconProfile /> {mergedUserMenu.profile}
                                                        </DisclosureButton>
                                                        <DisclosureButton as="button" onClick={handleLogout} className="flex w-full items-center gap-[10px] font-semibold text-[#000000] hover:text-[#053F31] transition-colors text-left">
                                                            <IconLogout /> {mergedUserMenu.logout}
                                                        </DisclosureButton>
                                                    </div>
                                                    )}
                                                </div>
                                            ) : (
                                                <div className="flex w-full min-w-0 max-w-full flex-col items-center gap-3">
                                                    {Array.isArray(authItems) &&
                                                        authItems.map((item: any, idx: number) => (
                                                            <DisclosureButton
                                                                key={item.title ?? idx}
                                                                as={Link}
                                                                href={item.description}
                                                                className="flex w-full min-w-0 max-w-[min(20rem,100%)] items-center justify-center gap-2 text-[#053F31] font-light hover:text-emerald-900"
                                                            >
                                                                <span className="shrink-0 [&_svg]:max-h-6 [&_svg]:max-w-6" dangerouslySetInnerHTML={{ __html: item.svg }} />
                                                                <span className="min-w-0">{item.title}</span>
                                                            </DisclosureButton>
                                                        ))}
                                                    <LocaleSwitcherPanel
                                                        uiLocale={uiLocale}
                                                        open={localeMenuOpen}
                                                        onToggle={() => setLocaleMenuOpen((o) => !o)}
                                                        containerRef={localeMobileRef}
                                                        applyLocale={applyGuestLocale}
                                                        languageListboxAriaLabel={languageListboxAriaLabel}
                                                        rowAlignClass="items-center"
                                                        panelPosition="center"
                                                    />
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </DisclosurePanel>
                        </>
                    )}
                </Disclosure>}
            </div> </div>
    );
}
