"use client";

import React, { Fragment, useEffect, useRef, useState } from "react";
import style from "../styles/HeaderStyle.module.scss";
import search_icon from "../assets/search_icon.svg";

import union from "../assets/union.svg";
import { toast } from "react-toastify";
import NotificationIcon from "../assets/wishlist.svg";
import msg from "../assets/msg.png";
import toggle from "../assets/toggle.svg";
import logo from "../assets/reservitt_logo_image.svg";
import mobilelogo from "../assets/mobileLogo.svg";
import userLogin from "../assets/loginUser.jpg";

import currencyLogo from "../assets/currrency.png";
import loginUser from "../assets/user.svg";
import { useRouter, useSearchParams } from "next/navigation";
import { fetchExchangeRatesIfNeeded } from "../utils/fetchExchangeRate";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../store";
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import Pusher from "pusher-js";
import Image from "next/image";
import Cookies from "js-cookie";
import {
  Menu,
  Transition,
  Dialog,
  DialogPanel,
  DialogTitle,
  TransitionChild,
} from "@headlessui/react";
import { TOKEN_STORAGE_KEY } from "../constants";
import {
  logout,
  searchListing,
  profileBuyer,
  fetchAllWishlist,
  messageCount,
  ticketNotification,
  getTickets,
  readNotificationData,
} from "../api/api";
import { updateLogoutState } from "../slice/LoginSlice";
import { setSelectedCurrency } from "../slice/currencySlice";
import { clearObjects } from "../slice/ImageSlice";
import { XMarkIcon } from "@heroicons/react/24/outline";
import getJWT from "../api/api";
import dynamic from "next/dynamic";

const LocationSearchComponent = dynamic(
  () =>
    import(
      "../components/bayerProfile/pages/components/LocationSearchComponent"
    )
);

const Popup = dynamic(() => import("./ConfirmationPopUp"));

// Icons
const AiOutlineHome = dynamic(() =>
  import("react-icons/ai").then((mod) => mod.AiOutlineHome)
);

const MdPostAdd = dynamic(() =>
  import("react-icons/md").then((mod) => mod.MdPostAdd)
);

const BsChatSquareDots = dynamic(() =>
  import("react-icons/bs").then((mod) => mod.BsChatSquareDots)
);

const FaChevronDown = dynamic(() =>
  import("react-icons/fa").then((mod) => mod.FaChevronDown)
);

const MdPerson = dynamic(() =>
  import("react-icons/md").then((mod) => mod.MdPerson)
);

const Header: React.FC = () => {
  const dispatch: AppDispatch = useDispatch<any>();
  const router = useRouter();
  const searchParams = useSearchParams();
  const keyword = searchParams.get("keyword") || "";
  const [open, setOpen] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const getToken = getJWT();
  const dropdownRef = useRef<any>(null);
  const [query, setQuery] = useState(keyword || "");
  const [categoryId, setSelectedCategoryId] = useState<number | null>(null);
  const [isNotificationOpen, setIsNotificationOpen] = useState(false);
  const [userToken, setUserToken] = useState<string | null>(null);
  const currency = useSelector(
    (state: RootState) => state.CurrencyReducer.selectedCurrency
  );
  const [selectedCurrencyValue, setSelectedCurrencyValue] = useState(currency); // Default value

  const { isLoggedIn, userData } = useSelector(
    (state: RootState) => state.loginReducer
  );

  const { ticketsNotificationData } = useSelector(
    (state: RootState) => state.TicketsReducer
  );
  const user = userData?.data?.user;
  const userId = userData?.data?.user?.id;
  const { longitudeData, latitudeData } = useSelector(
    (state: RootState) => state.IpAddressReducer
  );
  const { state, country } = useSelector(
    (state: RootState) => state.locationReducer
  );
  const { image, letter } = useSelector(
    (state: RootState) => state.imageReducer
  );
  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );
  const data = useSelector((state: RootState) => state.AllWishlistReducer);
  const wishlistData = data?.data?.data?.wishlists;
  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );

  const AuctionSellerFee = incrementData?.data?.auctionFee[0]?.seller_fee;

  const { cashWalletHistoryData } = useSelector(
    (state: RootState) => state.WalletReducer
  );
  const WalletBalance = cashWalletHistoryData?.wallet_balance;

  const lastFetched = useSelector(
    (state: RootState) => state.CurrencyExchangeRateReducer.lastFetched
  );

  useEffect(() => {
    const routesToPrefetch = [
      "/post-ad",
      "/profile/wallet/transaction",
      "/auth/login",
      "/auth/register",
      "/",
      "/profile/wishlist",
      "/profile/chat",
      "/profile/listing",
      "/profile/edits",
      "/profile/seller/listing",
    ];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  useEffect(() => {
    if (keyword == "") {
      setQuery("");
    }
  }, [keyword]);

  useEffect(() => {
    const token = localStorage.getItem(TOKEN_STORAGE_KEY);
    setUserToken(token);
  }, []);
  // Sync currency state with Redux on client side
  useEffect(() => {
    setSelectedCurrencyValue(currency);
  }, [currency]);

  useEffect(() => {
    fetchExchangeRatesIfNeeded(dispatch, lastFetched);
  }, [dispatch, lastFetched]);

  const handleCategoryClick = async (id: number, name: string) => {
    setSelectedCategoryId(id);

    if (query.trim() || id) {
      const categoryId = id;
      const categoryName = name
        .replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      try {
        const subLocation = ["USA", "Canada"].includes(state) ? "" : state;
        const actionResult = await dispatch(
          searchListing({
            keyword: query,
            category_id: categoryId,
            location:
              country === "CAN" ? "Canada" : country === "US" ? "USA" : "",
            sub_location: subLocation || "",
          })
        ).unwrap();
        router.push(`/${categoryId}/${categoryName}`);

        if (actionResult?.data?.listings?.length > 0) {
          router.push(`/${categoryId}/${categoryName}`);
        }
      } catch {
        // console.error("Search failed:", err);
        return null;
      }
    }
  };

  // console.log("countData--------", countData);
  function classNames(...classes: any) {
    return classes.filter(Boolean).join(" ");
  }

  const navigateToAddWallet = () => {
    router.push("/profile/wallet/transaction");
  };

  const handleLogout = async () => {
    try {
      if (!userToken) {
        dispatch(updateLogoutState());
        dispatch(clearObjects());
        localStorage.clear();
        Cookies.remove("token");
        router.push("/auth/login");
        return;
      }

      const response = await dispatch(logout()).unwrap();

      if (response?.status_code === 200) {
        dispatch(updateLogoutState());
        dispatch(clearObjects());
        localStorage.clear();
        toast.success("Logged out successfully.");
        setTimeout(() => router.push("/"), 1000);
        setOpen(false);
      } else {
        toast.error("Failed to log out. Redirecting to login...");
        localStorage.clear();
        router.push("/auth/login");
      }
    } catch (error: any) {
      // console.error("Logout error:", error);

      if (error?.response?.status === 401) {
        toast.error("Session expired. Redirecting to login...");
      } else {
        toast.error("An error occurred during logout.");
      }
      dispatch(clearObjects());
      dispatch(updateLogoutState());
      localStorage.clear();
      router.push("/auth/login");
    }
  };

  const getPrefetchUrl = () => {
    if (!query.trim() && !categoryId) return null;

    let url = `/searchlist?keyword=${encodeURIComponent(query)}`;
    if (categoryId !== null) {
      url += `&category=${categoryId}`;
    }
    return url;
  };

  const handlePrefetch = () => {
    const url = getPrefetchUrl();
    if (url) {
      router.prefetch(url);
    }
  };

  const handleSearch = async () => {
    let latitude: string;
    let longitude: string;
    // let location: string;

    if (isLoggedIn && userToken) {
      latitude = userData?.data?.user?.location_latitude;
      longitude = userData?.data?.user?.location_longitude;
      // location = userData?.data?.user?.location;
    } else {
      latitude = latitudeData;
      longitude = longitudeData;
      // location = locationData;
    }

    if (query.trim() || categoryId) {
      try {
        const subLocation = ["USA", "Canada"].includes(state) ? "" : state;
        await dispatch(
          searchListing({
            keyword: query,
            category_id: categoryId,
            location_latitude: latitude,
            location_longitude: longitude,
            location:
              country === "CAN" ? "Canada" : country === "US" ? "USA" : "",
            sub_location: subLocation || "",
          })
        ).unwrap();

        let url = `/searchlist?keyword=${encodeURIComponent(query)}`;
        if (categoryId !== null) {
          url += `&category=${categoryId}`;
        }

        router.push(url);
      } catch {
        // console.error("Search failed:", err);
        return null;
      }
    }
  };

  const handlePostAdd = () => {
    setOpen(false);

    if (getToken) {
      const wallet: number =
        typeof WalletBalance === "string"
          ? parseFloat(WalletBalance)
          : WalletBalance;
      const fee: number =
        typeof AuctionSellerFee === "string"
          ? parseFloat(AuctionSellerFee)
          : AuctionSellerFee;
      // console.log("wallet====", wallet, "fee==========", fee);
      if (!isNaN(wallet) && !isNaN(fee) && wallet > fee) {
        router.push("/post-ad");
      } else {
        setShowModal(true);
      }
    } else {
      router.push("/auth/login");
    }
  };

  const handleProfile = () => {
    router.push("/profile/edits");
    setOpen(false);
  };
  const handleHome = () => {
    router.push("/");
    setOpen(false);
  };

  const handleReadNotification = (id: any) => {
    dispatch(readNotificationData(id))
      .unwrap()
      .then(() => {
        toast.success("Notification marked as read.");
        // Refresh counts / list
        dispatch(ticketNotification());
        dispatch(getTickets());
      })
      .catch(() => {
        toast.error("Failed to mark notification as read.");
      });
  };

  const loginHandle = () => {
    router.push("/auth/login");
    setOpen(false);
  };

  const handleCurrency = async (currency: any) => {
    try {
      setSelectedCurrencyValue(currency); // local state update
      dispatch(setSelectedCurrency(currency)); // redux update
    } catch {
      // console.error("Currency change failed:", error);
      return null;
    }
  };

  useEffect(() => {
    function handleClickOutside(event: any) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsNotificationOpen(false);
      }
    }

    if (isNotificationOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isNotificationOpen, setIsNotificationOpen]);

  useEffect(() => {
    if (isNotificationOpen) {
      dispatch(fetchAllWishlist());
    }
  }, [isNotificationOpen, dispatch]);

  // Pusher for real-time chat notifications

  useEffect(() => {
    const appKey = process.env.NEXT_PUBLIC_PUSHER_APP_KEY || "";
    const cluster = process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER || "";

    if (!user?.id) return;

    const pusher = new Pusher(appKey, {
      cluster,
      forceTLS: true,
    });

    const channel = pusher.subscribe(`chat.${user.id}`);

    const handleNewMessage = (data: any) => {
      // console.log("chek pusher new message", data);
      const newMessage = data?.message?.message;
      toast.info(`📩 ${newMessage}`);
      dispatch(messageCount());
    };

    channel.bind("App\\Events\\MessageSent", handleNewMessage);

    const handleDisconnect = () => {
      console.warn("Pusher connection lost.");
    };

    pusher.connection.bind("disconnected", handleDisconnect);

    return () => {
      channel.unbind("App\\Events\\MessageSent", handleNewMessage);
      pusher.unsubscribe(`chat.${user.id}`);
      pusher.disconnect();
    };
  }, [user?.id, dispatch]);

  // Pusher for real-time  notifications
  useEffect(() => {
    if (!userId) return;
    const appKey = process.env.NEXT_PUBLIC_PUSHER_APP_KEY!;
    const cluster = process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER!;

    let pusher = new Pusher(appKey, {
      cluster,
      forceTLS: true,
    });

    const reconnectPusher = () => {
      console.warn("🔄 Reconnecting Pusher...");
      pusher.unsubscribe(`system-notifications.${userId}`);
      pusher.disconnect();
      pusher = new Pusher(appKey, { cluster, forceTLS: true });
      subscribeNotificationEvents();
    };

    const subscribeNotificationEvents = () => {
      const channel = pusher.subscribe(`system-notifications.${userId}`);
      channel.bind("App\\Events\\SystemNotificationCreated", (data: any) => {
        console.log("📩 New system notification received!", data);
        dispatch(ticketNotification());
        dispatch(getTickets());
      });
    };

    subscribeNotificationEvents();

    // Debug logs for connection states
    pusher.connection.bind("connected", () => {
      console.log("✅ Pusher connected!");
    });

    pusher.connection.bind("connecting", () => {
      console.log("⏳ Pusher is connecting...");
    });

    pusher.connection.bind("disconnected", () => {
      console.warn("❌ Pusher disconnected. Attempting to reconnect...");
      reconnectPusher();
    });

    pusher.connection.bind("error", (err: any) => {
      console.error("⚠️ Pusher connection error:", err);
    });

    // Cleanup
    return () => {
      console.log("🧹 Cleaning up Notification Pusher...");
      pusher.unsubscribe(`private-notifications.${userId}`);
      pusher.disconnect();
    };
  }, [userId, dispatch]);

  return (
    <>
      {/* large screen header */}
      <header className="bg-white pt-4 lg:block hidden">
        {/* main header section */}
        <div className="flex max-w-7xl mx-auto justify-between pb-2 xl:gap-4 xl:justify-center">
          {/* left section */}
          <div className="flex items-center gap-3">
            {/* logo section */}
            <section>
              <p onClick={() => router.push("/")} className="cursor-pointer">
                <Image
                  unoptimized
                  src={logo}
                  className="w-[15rem] h-[auto]"
                  alt="Logo"
                  width={240}
                  height={60}
                  priority
                />
              </p>
            </section>

            {/* input section */}
            <section
              style={{
                boxShadow: "0 0 6px 2px rgba(0.1, 0.1, 0.1, 0.1)",
              }}
              className="relative h-[44px] shadow-2xl md:inline-block hidden rounded-sm"
            >
              <div className="absolute">
                <Menu
                  as="div"
                  className="absolute hidden text-left md:inline-block right-0 font-system font-semibold"
                >
                  <Menu.Button className="p-0 w-10 h-8 text-center border-none focus:outline-none focus-visible:outline-none">
                    {/* Your content here */}
                  </Menu.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-100"
                    enterFrom="transform opacity-0 scale-95"
                    enterTo="transform opacity-100 scale-100"
                    leave="transition ease-in duration-75"
                    leaveFrom="transform opacity-100 scale-100"
                    leaveTo="transform opacity-0 scale-95"
                  >
                    <Menu.Items className="absolute left-0 z-20 mt-2 w-56 origin-top-right divide-y divide-gray-200 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
                      {categories?.data?.map((item: any, index: any) => (
                        <div className="" key={index}>
                          <Menu.Item>
                            {({ active }) => {
                              const categoryName = item.name
                                .replace(/[^a-zA-Z0-9\s]/g, "")
                                .replace(/\s+/g, "-")
                                .toLowerCase();

                              const route = `/${item.id}/${categoryName}`;

                              return (
                                <div
                                  className={classNames(
                                    active
                                      ? "bg-navy text-white dark:bg-gray-600"
                                      : "text-gray-900 dark:text-black",
                                    "group items-center px-4 py-4 text-sm flex justify-between cursor-pointer"
                                  )}
                                  onClick={() =>
                                    handleCategoryClick(item.id, item.name)
                                  }
                                  onMouseEnter={() => router.prefetch(route)}
                                >
                                  {item.name}
                                </div>
                              );
                            }}
                          </Menu.Item>
                        </div>
                      ))}
                    </Menu.Items>
                  </Transition>
                </Menu>
                <button
                  className="bg-navy flex mt-1 ml-2 marker:font-system text-white gap-1 items-center text-sm border-none top-1 px-2"
                  aria-label="Select category"
                >
                  <Image
                    unoptimized
                    src={union}
                    alt="category selection-img"
                    width={18}
                    height={18}
                    aria-hidden="true"
                  />
                </button>
              </div>
              <div className="ml-12">
                <input
                  type="text"
                  placeholder="What are you looking for?"
                  className={`bg-white text-black mt-1 font-semibold rounded-md focus:outline-none focus:ring-0 focus:shadow-none pr-16 px-2 font-system text-sm border-none ${style.customInput}`}
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  onFocus={handlePrefetch}
                  onKeyPress={(e) => {
                    if (e.key === "Enter") {
                      handleSearch();
                    }
                  }}
                />
              </div>

              <div className="flex gap-2 items-center justify-center absolute right-1 top-1 rounded bg-[#F8CB1F] h-9 w-9">
                <Image
                  unoptimized
                  src={search_icon}
                  onClick={handleSearch}
                  onMouseEnter={handlePrefetch}
                  className="cursor-pointer top-2"
                  width={20}
                  height={20}
                  alt="Search"
                />
              </div>
            </section>
          </div>

          {/* right section */}
          <div
            className={`xs:hidden sm:hidden xs:gap-8 lg:gap-2 md:hidden lg:flex items-center font-system ${style.customRightHeaderGap}`}
          >
            <div className="text-left flex gap-3">
              <LocationSearchComponent />
            </div>
            <div>
              <Menu as="div" className="relative inline-block text-left">
                <div>
                  <Menu.Button
                    style={{
                      boxShadow: "0 0 6px 2px rgba(0.1, 0.1, 0.1, 0.1)",
                    }}
                    className="inline-flex justify-center w-20 rounded-sm h-[44px] px-3 py-[10px] text-sm font-semibold text-black shadow-2xl focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-black dark:border-gray-600 dark:hover:bg-gray-600"
                  >
                    {selectedCurrencyValue}
                    <ChevronDownIcon
                      className="-mr-1 ml-1 h-5 w-5"
                      aria-hidden="true"
                    />
                  </Menu.Button>
                </div>

                <Menu.Items className="absolute right-0 z-20 mt-2 w-20 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-700 dark:ring-gray-600 overflow-hidden">
                  <div className="">
                    <Menu.Item>
                      {({ active }) => (
                        <div
                          onClick={() => handleCurrency("USD")}
                          className={`${
                            active
                              ? "bg-navy text-white dark:bg-gray-600"
                              : "text-gray-900 dark:text-black"
                          } block w-full px-4 py-2 text-sm font-semibold cursor-pointer border-b`}
                        >
                          USD
                        </div>
                      )}
                    </Menu.Item>
                    <Menu.Item>
                      {({ active }) => (
                        <div
                          onClick={() => handleCurrency("CAD")}
                          className={`${
                            active
                              ? "bg-navy text-white dark:bg-gray-600"
                              : "text-gray-900 dark:text-black"
                          } block w-full px-4 py-2 text-sm cursor-pointer font-semibold`}
                        >
                          CAD
                        </div>
                      )}
                    </Menu.Item>
                  </div>
                </Menu.Items>
              </Menu>
            </div>
            {isLoggedIn && localStorage.getItem(TOKEN_STORAGE_KEY) ? (
              <>
                <button
                  className="text-lg text-black bg-[#F8CB1F] rounded py-2 px-6 font-medium font-system transition ease-in-out hover:-translate-y-1 hover:scale-110 duration-300"
                  onClick={() => handlePostAdd()}
                >
                  Post Ad
                </button>

                <div className="flex items-center">
                  <Menu as="div" className="relative">
                    <Menu.Button
                      onClick={() => dispatch(fetchAllWishlist())}
                      className="focus:outline-none"
                    >
                      <Image
                        unoptimized
                        src={NotificationIcon}
                        alt="Notifications"
                        className="h-8 w-8 cursor-pointer"
                        width={32}
                        height={32}
                      />
                    </Menu.Button>

                    <Transition
                      as={Fragment}
                      enter="transition ease-out duration-100"
                      enterFrom="transform opacity-0 scale-95"
                      enterTo="transform opacity-100 scale-100"
                      leave="transition ease-in duration-75"
                      leaveFrom="transform opacity-100 scale-100"
                      leaveTo="transform opacity-0 scale-95"
                    >
                      <Menu.Items className="absolute  -left-28  w-72 bg-white border border-gray-200 rounded-lg shadow-lg z-50 overflow-auto max-h-60">
                        <div className=" text-black text-xl text-center px-2 py-3 font-semibold border-b">
                          Wishlist
                        </div>

                        {wishlistData?.length > 0 ? (
                          wishlistData.map((notification: any) => (
                            <Menu.Item key={notification.id}>
                              {({ active }) => (
                                <div className=" border-b-[1px]">
                                  <div
                                    onClick={() =>
                                      router.push("/profile/wishlist")
                                    }
                                    className={`block px-4 py-2 w-full text-sm font-medium rounded-none border-b ${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-black"
                                    }`}
                                  >
                                    <div className="flex items-center gap-2 cursor-pointer">
                                      <Image
                                        unoptimized
                                        className="h-10 w-10 rounded-md object-cover"
                                        src={notification?.listing?.images[0]}
                                        alt={
                                          notification?.listing?.product_name
                                        }
                                        width={40}
                                        height={40}
                                      />

                                      <span className="text-sm font-semibold">
                                        {notification?.listing?.product_name}
                                      </span>
                                    </div>
                                  </div>
                                </div>
                              )}
                            </Menu.Item>
                          ))
                        ) : (
                          <div className="px-4 py-3 text-black text-sm text-center">
                            No wishlist available.
                          </div>
                        )}
                      </Menu.Items>
                    </Transition>
                  </Menu>

                  <Menu as="div" className="relative inline-block text-left">
                    <Menu.Button className="relative flex items-center focus:outline-none p-0">
                      <Image
                        unoptimized
                        className="h-8"
                        src={msg}
                        alt="msg"
                        width={32}
                        height={32}
                      />
                      {ticketsNotificationData?.data?.total_unread > 0 && (
                        <span className="absolute -top-1 -right-1 bg-yellow-400 text-black text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                          {ticketsNotificationData?.data?.total_unread}
                        </span>
                      )}
                    </Menu.Button>

                    <Transition
                      as={Fragment}
                      enter="transition ease-out duration-100"
                      enterFrom="transform opacity-0 scale-95"
                      enterTo="transform opacity-100 scale-100"
                      leave="transition ease-in duration-75"
                      leaveFrom="transform opacity-100 scale-100"
                      leaveTo="transform opacity-0 scale-95"
                    >
                      <Menu.Items className="absolute right-0 mt-2 w-80 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none z-50 overflow-hidden">
                        <div className="flex items-center justify-between px-4 py-3 border-b">
                          <p className="text-black font-semibold">
                            System Notifications
                          </p>
                          <button
                            className="text-xs text-blue-600 hover:underline"
                            onClick={() => router.push("/profile/chat")}
                          >
                            View all
                          </button>
                        </div>

                        <div className="max-h-80 overflow-y-auto">
                          {ticketsNotificationData?.data?.notifications
                            ?.length ? (
                            ticketsNotificationData?.data?.notifications
                              .slice(0, 5)
                              .map((notif: any) => (
                                <Menu.Item key={notif?.id}>
                                  {({ active }) => (
                                    <div
                                      className={`px-4 py-3 text-sm cursor-pointer border-b last:border-b-0 transition-colors ${
                                        active ? "bg-gray-100" : "bg-white"
                                      } ${
                                        notif.is_read === 0
                                          ? "bg-yellow-50"
                                          : "bg-white"
                                      }`}
                                    >
                                      <div className="mt-1 flex align-start justify-between gap-3">
                                        <p className="text-black font-medium line-clamp-2">
                                          {notif.message}
                                        </p>
                                        {notif.is_read === 0 && (
                                          <div
                                            className="text-[10px] font-semibold text-blue-600 hover:underline whitespace-nowrap"
                                            onClick={(e) => {
                                              e.stopPropagation();
                                              handleReadNotification(notif.id);
                                            }}
                                          >
                                            Mark as read
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                  )}
                                </Menu.Item>
                              ))
                          ) : (
                            <div className="px-4 py-4 text-center text-sm text-gray-500">
                              No notifications available.
                            </div>
                          )}
                        </div>
                      </Menu.Items>
                    </Transition>
                  </Menu>
                  <Menu as="div" className="relative inline-block text-left">
                    {({ open }) => (
                      <>
                        <Menu.Button className="flex items-center gap-2 cursor-pointer focus:outline-none focus:ring-0">
                          {letter ? (
                            <span className="font-bold bg-gray-200 py-3 px-4 rounded-full">
                              {letter}
                            </span>
                          ) : (
                            <Image
                              unoptimized
                              src={image}
                              alt="Profile"
                              className="w-10 h-10 rounded-full border border-gray-300"
                              width={40}
                              height={40}
                            />
                          )}
                          <FaChevronDown
                            className={`transition-transform duration-300 text-black ${
                              open ? "rotate-180" : "rotate-0"
                            }`}
                          />
                        </Menu.Button>

                        <Transition
                          as={Fragment}
                          enter="transition ease-out duration-200"
                          enterFrom="opacity-0 translate-y-2"
                          enterTo="opacity-100 translate-y-0"
                          leave="transition ease-in duration-150"
                          leaveFrom="opacity-100 translate-y-0"
                          leaveTo="opacity-0 translate-y-2"
                        >
                          <Menu.Items className="absolute z-40 right-3 w-56 origin-top-right bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none rounded-md overflow-hidden">
                            <div className="border-b-[1px]">
                              <Menu.Item>
                                {({ active }) => (
                                  <button
                                    className={`${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-black"
                                    } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                    onClick={() => {
                                      dispatch(profileBuyer());
                                      router.push("/profile/edits");
                                    }}
                                  >
                                    My Profile
                                  </button>
                                )}
                              </Menu.Item>
                            </div>

                            <div className="border-b-[1px]">
                              <Menu.Item>
                                {({ active }) => (
                                  <button
                                    className={`${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-black"
                                    } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                    onClick={() =>
                                      router.push("/profile/seller/listing")
                                    }
                                  >
                                    My Ads
                                  </button>
                                )}
                              </Menu.Item>
                            </div>

                            <div className="border-b-[1px]">
                              <Menu.Item>
                                {({ active }) => (
                                  <button
                                    className={`${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-black"
                                    } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                    onClick={() =>
                                      router.push("/profile/listing")
                                    }
                                  >
                                    My Purchased
                                  </button>
                                )}
                              </Menu.Item>
                            </div>

                            <div className="">
                              <Menu.Item>
                                {({ active }) => (
                                  <button
                                    className={`${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-black"
                                    } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                    onClick={handleLogout}
                                  >
                                    Log Out
                                  </button>
                                )}
                              </Menu.Item>
                            </div>
                          </Menu.Items>
                        </Transition>
                      </>
                    )}
                  </Menu>
                </div>
              </>
            ) : (
              <>
                <button
                  className="text-lg text-black bg-[#F8CB1F] rounded py-2 px-6 font-medium font-system transition ease-in-out hover:-translate-y-1 hover:scale-105 duration-300"
                  onClick={handlePostAdd}
                >
                  Post Ad
                </button>

                <button className="text-black text-lg bg-[#F8CB1F] gap-1 rounded py-2 px-6 font-medium font-system transition ease-in-out hover:-translate-y-1 hover:scale-105 duration-300 flex justify-center items-center">
                  <Image
                    unoptimized
                    className="h-4"
                    src={loginUser}
                    alt="user"
                    width={18}
                    height={18}
                  />
                  <p
                    onClick={() => router.push("/auth/login")}
                    className="cursor-pointer"
                  >
                    Sign In
                  </p>{" "}
                  /{" "}
                  <p
                    onClick={() => router.push("/auth/register")}
                    className="cursor-pointer"
                  >
                    Register
                  </p>
                </button>
              </>
            )}
          </div>

          <div className="xs:flex sm:flex md:flex lg:hidden">
            <button id="nav-toggle" className="block focus:outline-none">
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M4 6h16M4 12h16M4 18h16"
                ></path>
              </svg>
            </button>
          </div>
        </div>

        <section className="relative xs:inline-block md:hidden">
          <input
            type="text"
            placeholder="What are you looking for?"
            className={`bg-gray-200 font-semibold text-black py-3 rounded-md focus:outline-none focus:ring-0 focus:shadow-none pr-48 px-2 font-system text-sm border-none ${style.customInput}`}
          />
          <div className="flex gap-2 items-center w-fit absolute right-0 top-0.5">
            <div className="h-8 w-0.5 bg-gray-300"></div>
            <Image
              unoptimized
              src={search_icon}
              className="cursor-pointer top-2"
              alt="Search"
              width={16}
              height={16}
            />
            <button
              className="bg-black flex font-system text-white gap-1 items-center text-sm border-none top-0 py-2.5 px-2.5"
              aria-label="Select category"
            >
              <Image
                unoptimized
                src={union}
                className="category selection-img"
                alt="Categories"
                width={16}
                height={16}
                aria-hidden="true"
              />
              <span>All categories</span>
            </button>
          </div>
        </section>
        <hr className="mt-3"></hr>
      </header>

      {/* small screen header */}
      <header className="bg-white pt-4 pb-2 lg:hidden block">
        <div className="flex justify-around">
          <div>
            <div
              className={`${
                isLoggedIn && localStorage.getItem(TOKEN_STORAGE_KEY)
                  ? ""
                  : "w-full"
              }`}
            >
              <button className="p-0">
                <Image
                  unoptimized
                  src={toggle}
                  onClick={() => setOpen(true)}
                  alt="Menu Toggle"
                  width={30}
                  height={36}
                />
                <Transition show={open}>
                  <Dialog className="relative z-50" onClose={setOpen}>
                    <div className="fixed inset-0 bg-black bg-opacity-50 transition-opacity" />

                    <div className="fixed inset-0 overflow-hidden">
                      <div className="absolute inset-0 overflow-hidden">
                        <div className="pointer-events-none fixed inset-y-0 left-0 flex max-w-full">
                          <TransitionChild
                            enter="transform transition ease-in-out duration-500"
                            enterFrom="-translate-x-full"
                            enterTo="translate-x-0"
                            leave="transform transition ease-in-out duration-500"
                            leaveFrom="translate-x-0"
                            leaveTo="-translate-x-full"
                          >
                            <DialogPanel className="pointer-events-auto w-72 sm:w-60 font-system bg-white shadow-2xl rounded-r-lg">
                              <div className="flex items-center justify-between px-5 py-4 bg-gradient-to-r from-[#0a1931] to-[#001f3f] rounded-t-lg shadow-md">
                                <DialogTitle className="text-xl font-semibold text-yellow-400 capitalize">
                                  {userData?.data?.user?.name ? (
                                    <>{userData?.data?.user?.name}</>
                                  ) : (
                                    <p
                                      onClick={() => router.push("/")}
                                      className="cursor-pointer"
                                    >
                                      <Image
                                        unoptimized
                                        src={mobilelogo}
                                        className="h-41px w-41px"
                                        alt="Logo"
                                        width={41}
                                        height={41}
                                        priority
                                      />
                                    </p>
                                  )}
                                </DialogTitle>
                                <button
                                  type="button"
                                  className="rounded-full bg-yellow-400 p-2 text-[#0a1931] hover:bg-yellow-300 hover:scale-105 transition-all shadow-md"
                                  onClick={() => setOpen(false)}
                                  aria-label="Close panel"
                                >
                                  <XMarkIcon
                                    className="h-5 w-5"
                                    aria-hidden="true"
                                  />
                                </button>
                              </div>

                              <div className="flex flex-col space-y-4 px-6 py-5 text-black">
                                <p
                                  onClick={handleHome}
                                  className="flex items-center cursor-pointer text-black text-lg font-medium hover:text-yellow-400 transition-all duration-200"
                                >
                                  <AiOutlineHome className="mr-3 text-xl" />
                                  Home
                                </p>
                                {isLoggedIn && (
                                  <button
                                    onClick={handleProfile}
                                    className="flex p-0 items-center text-black text-lg font-medium hover:text-yellow-400 transition-all duration-200"
                                  >
                                    <MdPerson className="mr-3 text-xl" />
                                    Profile
                                  </button>
                                )}

                                <button
                                  onClick={handlePostAdd}
                                  className="flex p-0 items-center text-black text-lg font-medium hover:text-yellow-400 transition-all duration-200"
                                >
                                  <MdPostAdd className="mr-3 text-xl" />
                                  Post Ad
                                </button>
                                <p
                                  onClick={() => {
                                    router.push("/profile/wishlist");
                                    setOpen(false);
                                  }}
                                  className="flex items-center cursor-pointer text-black text-lg font-medium hover:text-yellow-400 transition-all duration-200"
                                >
                                  <Image
                                    unoptimized
                                    src={NotificationIcon}
                                    alt="wishlist"
                                    className="mr-3 h-5 w-5"
                                    width={20}
                                    height={20}
                                  />
                                  Wishlist
                                </p>
                                <p
                                  onClick={() => {
                                    router.push("/profile/chat");
                                    setOpen(false);
                                  }}
                                  className="flex text-black cursor-pointer items-center text-lg font-medium hover:text-yellow-400 transition-all duration-200"
                                >
                                  <BsChatSquareDots className="mr-3 text-xl" />
                                  Chat
                                </p>
                                <div className="flex items-center">
                                  <Image
                                    unoptimized
                                    src={currencyLogo}
                                    alt="Logo"
                                    width={30}
                                    height={30}
                                    priority
                                    className="h-[20px] w-[20px] mr-3"
                                  />

                                  <Menu
                                    as="div"
                                    className="relative inline-block text-left"
                                  >
                                    <div>
                                      <Menu.Button className="inline-flex justify-center items-center w-[58px] rounded-sm p-0 h-[34px]  text-lg font-medium text-black shadow-2xl focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-black dark:border-gray-600 dark:hover:bg-gray-600">
                                        {selectedCurrencyValue}
                                        <ChevronDownIcon
                                          className="-mr-1 ml-1 h-5 w-5"
                                          aria-hidden="true"
                                        />
                                      </Menu.Button>
                                    </div>

                                    <Menu.Items className="absolute right-0 z-10 mt-2 w-[58px] origin-top-right font-medium rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-700 dark:ring-gray-600 overflow-hidden">
                                      <div className="">
                                        <Menu.Item>
                                          {({ active }) => (
                                            <div
                                              onClick={() =>
                                                handleCurrency("USD")
                                              }
                                              className={`${
                                                active
                                                  ? " text-black dark:bg-gray-600"
                                                  : "text-gray-900 dark:text-black"
                                              } px-3 py-2 block w-full text-sm font-semibold border-b-2 cursor-pointer`}
                                            >
                                              USD
                                            </div>
                                          )}
                                        </Menu.Item>
                                        <Menu.Item>
                                          {({ active }) => (
                                            <div
                                              onClick={() =>
                                                handleCurrency("CAD")
                                              }
                                              className={`${
                                                active
                                                  ? " text-black dark:bg-gray-600"
                                                  : "text-gray-900 dark:text-black"
                                              } px-3 py-2 block w-full cursor-pointer text-sm font-semibold `}
                                            >
                                              CAD
                                            </div>
                                          )}
                                        </Menu.Item>
                                      </div>
                                    </Menu.Items>
                                  </Menu>
                                </div>
                              </div>

                              {isLoggedIn &&
                              localStorage.getItem(TOKEN_STORAGE_KEY) ? (
                                <div className="px-6 py-5 mt-auto">
                                  <button
                                    className="w-full text-white bg-[#0a1931] rounded-lg py-2 px-4 font-bold transition-all duration-300 hover:bg-yellow-400 hover:text-[#0a1931] hover:scale-105"
                                    onClick={handleLogout}
                                  >
                                    Logout
                                  </button>
                                </div>
                              ) : (
                                <div className="px-6 py-5 mt-auto">
                                  <button
                                    className="flex justify-center items-center w-full text-black bg-[#F8CB1F] rounded-lg py-2 px-4 font-bold transition-all duration-300 hover:bg-yellow-400 hover:text-[#0a1931] hover:scale-105"
                                    onClick={loginHandle}
                                  >
                                    <Image
                                      unoptimized
                                      className="h-4 mr-2"
                                      src={loginUser}
                                      alt="user"
                                      width={16}
                                      height={16}
                                    />
                                    Login
                                  </button>
                                </div>
                              )}
                            </DialogPanel>
                          </TransitionChild>
                        </div>
                      </div>
                    </div>
                  </Dialog>
                </Transition>
              </button>
            </div>
          </div>
          <div>
            <section
              className="relative h-[34px] w-40  rounded-sm"
              style={{ boxShadow: "0 0 6px 2px rgba(0.1, 0.1, 0.1, 0.1)" }}
            >
              <div className="absolute">
                <Menu
                  as="div"
                  className="absolute text-left md:inline-block right-0 font-system font-semibold"
                >
                  <Menu.Button className="p-0 w-7 h-7 text-center border-none focus:outline-none focus-visible:outline-none">
                    {/* Your content here */}
                  </Menu.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-100"
                    enterFrom="transform opacity-0 scale-95"
                    enterTo="transform opacity-100 scale-100"
                    leave="transition ease-in duration-75"
                    leaveFrom="transform opacity-100 scale-100"
                    leaveTo="transform opacity-0 scale-95"
                  >
                    <Menu.Items className="absolute left-0 z-50 mt-2 w-56 origin-top-right divide-y divide-gray-200 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden text-gray-900 dark:text-white">
                      {categories?.data?.map((item: any, index: any) => (
                        <div className="" key={index}>
                          <Menu.Item>
                            {({ active }) => {
                              const categoryName = item.name
                                .replace(/[^a-zA-Z0-9\s]/g, "")
                                .replace(/\s+/g, "-")
                                .toLowerCase();

                              const route = `/${item.id}/${categoryName}`;

                              return (
                                <div
                                  className={classNames(
                                    active
                                      ? "bg-navy text-white dark:bg-gray-600"
                                      : "text-gray-900 dark:text-black",
                                    "group items-center px-4 py-4 text-sm flex justify-between cursor-pointer"
                                  )}
                                  onClick={() =>
                                    handleCategoryClick(item.id, item.name)
                                  }
                                  onMouseEnter={() => router.prefetch(route)}
                                >
                                  {item.name}
                                </div>
                              );
                            }}
                          </Menu.Item>
                        </div>
                      ))}
                    </Menu.Items>
                  </Transition>
                </Menu>
                <button
                  className="bg-navy flex mt-[6px] ml-2 marker:font-system text-white gap-1 items-center text-sm border-none top-1 p-[5px]"
                  aria-label="Select category"
                >
                  <Image
                    unoptimized
                    src={union}
                    alt="category selection-img"
                    width={12}
                    height={12}
                    aria-hidden="true"
                  />
                </button>
              </div>
              <div className="absolute top-1 left-8">
                <div className="">
                  <input
                    type="text"
                    placeholder="Search"
                    className={`bg-white text-black w-9/12 overflow-hidden p-0 pl-2 rounded-md focus:outline-none focus:ring-0 focus:shadow-none font-system text-sm border-none`}
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    onFocus={handlePrefetch}
                    onKeyPress={(e) => {
                      if (e.key === "Enter") {
                        handleSearch();
                      }
                    }}
                  />
                </div>

                <div className="absolute right-3 top-2 h-3 w-3">
                  <Image
                    unoptimized
                    src={search_icon}
                    alt="search_icon"
                    onClick={handleSearch}
                    onMouseEnter={handlePrefetch}
                    className="cursor-pointer top-2"
                    width={12}
                    height={12}
                  />
                </div>
              </div>
            </section>
          </div>

          <LocationSearchComponent />
          <Menu as="div" className="relative inline-block text-left">
            {({ open }) => (
              <>
                <Menu.Button className="flex items-center gap-0 cursor-pointer focus:outline-none focus:ring-0 p-0">
                  {isLoggedIn && localStorage.getItem(TOKEN_STORAGE_KEY) ? (
                    <>
                      {letter ? (
                        <div className="font-bold bg-gray-200 h-8 w-8 rounded-full flex items-center justify-center text-xs">
                          {letter}
                        </div>
                      ) : (
                        <Image
                          unoptimized
                          src={image}
                          alt="Profile"
                          className="w-10 h-10 rounded-full "
                          width={40}
                          height={40}
                        />
                      )}
                      <FaChevronDown
                        className={`transition-transform duration-300 text-black h-[10px] ${
                          open ? "rotate-180" : "rotate-0"
                        }`}
                      />
                    </>
                  ) : (
                    <>
                      <Image
                        unoptimized
                        src={userLogin}
                        alt="Login"
                        className="w-10 h-10 rounded-full"
                        width={40}
                        height={40}
                      />
                      <FaChevronDown
                        className={`transition-transform duration-300 text-black h-3 ${
                          open ? "rotate-180" : "rotate-0"
                        }`}
                      />
                    </>
                  )}
                </Menu.Button>

                <Transition
                  as={Fragment}
                  enter="transition ease-out duration-200"
                  enterFrom="opacity-0 translate-y-2"
                  enterTo="opacity-100 translate-y-0"
                  leave="transition ease-in duration-150"
                  leaveFrom="opacity-100 translate-y-0"
                  leaveTo="opacity-0 translate-y-2"
                >
                  <Menu.Items className="absolute z-40 right-1 w-56 top-10 bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none rounded-md overflow-hidden text-gray-900 dark:text-white">
                    {isLoggedIn && localStorage.getItem(TOKEN_STORAGE_KEY) ? (
                      <>
                        <div className="border-b-[1px]">
                          <Menu.Item>
                            {({ active }) => (
                              <button
                                className={`${
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600 dark:text-black"
                                    : "text-gray-900 dark:text-black "
                                } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                onClick={() => {
                                  dispatch(profileBuyer());
                                  router.push("/profile/edits");
                                }}
                              >
                                My Profile
                              </button>
                            )}
                          </Menu.Item>
                        </div>

                        <div className="border-b-[1px]">
                          <Menu.Item>
                            {({ active }) => (
                              <button
                                className={`${
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600"
                                    : "text-gray-900 dark:text-black"
                                } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                onClick={() =>
                                  router.push("/profile/seller/listing")
                                }
                              >
                                My Ads
                              </button>
                            )}
                          </Menu.Item>
                        </div>

                        <div className="border-b-[1px]">
                          <Menu.Item>
                            {({ active }) => (
                              <button
                                className={`${
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600"
                                    : "text-gray-900 dark:text-black"
                                } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                onClick={() => router.push("/profile/listing")}
                              >
                                My Purchased
                              </button>
                            )}
                          </Menu.Item>
                        </div>

                        <div className="">
                          <Menu.Item>
                            {({ active }) => (
                              <button
                                className={`${
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600"
                                    : "text-gray-900 dark:text-black"
                                } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                onClick={handleLogout}
                              >
                                Log Out
                              </button>
                            )}
                          </Menu.Item>
                        </div>
                      </>
                    ) : (
                      <div className="">
                        <Menu.Item>
                          {({ active }) => (
                            <button
                              className={`${
                                active
                                  ? "bg-navy text-white dark:bg-gray-600"
                                  : "text-gray-900 dark:text-black"
                              } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full `}
                              onClick={() => router.push("/auth/login")}
                            >
                              Login
                            </button>
                          )}
                        </Menu.Item>
                      </div>
                    )}
                  </Menu.Items>
                </Transition>
              </>
            )}
          </Menu>
        </div>
      </header>
      <Popup
        showPopup={showModal}
        message={
          <div>
            <p className="text-red-600">Insufficient wallet balance</p>
            <div className="mt-2 text-gray-600">
              You might need to add funds to your wallet. Minimum required
              wallet balance is {AuctionSellerFee}
            </div>
          </div>
        }
        onClose={() => {
          setShowModal(false);
        }}
        onConfirm={() => setShowModal(false)}
        onAddWallet={() => {
          setShowModal(false);
          navigateToAddWallet();
        }}
        showAddWalletButton={true}
      />
    </>
  );
};

export default Header;
