"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Link, usePathname, useTranslation } from "@/i18n/navigation";
import { getStoredUserEmail, pbLogout } from "@/app/lib/pocketbase";

interface MenuItem {
  labelKey: string;
  href: string;
  icon: string;
  new?: boolean;
  ad?: boolean;
}

interface MenuSection {
  titleKey: string;
  items: MenuItem[];
}

export default memo(function SiteMenu({
  isOpen,
  onClose,
  onLoginClick,
}: {
  isOpen: boolean;
  onClose: () => void;
  onLoginClick: () => void;
}) {
  const { t } = useTranslation("menu");
  const pathname = usePathname();
  const ref = useRef<HTMLDivElement>(null);
  const [userEmail, setUserEmail] = useState<string | null>(null);

  useEffect(() => {
    setUserEmail(getStoredUserEmail());
  }, []);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("keydown", handleEscape);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen, onClose]);

  const sections: MenuSection[] = [
    {
      titleKey: "community",
      items: [
        { labelKey: "messages", href: "/messages", icon: "🔔", new: true },
        { labelKey: "chat", href: "/join", icon: "💬" },
        { labelKey: "hostMeetup", href: "/meetups/host", icon: "🎤", new: true },
        { labelKey: "membersMap", href: "/map", icon: "🌐" },
      ],
    },
    {
      titleKey: "tools",
      items: [
        { labelKey: "climateFinder", href: "/tools", icon: "🌤️" },
        { labelKey: "fireCalculator", href: "/tools", icon: "🌱" },
        { labelKey: "costCalculator", href: "/tools", icon: "💱" },
        { labelKey: "aiAssistant", href: "/ai", icon: "🤖", new: true },
        { labelKey: "yearInReview", href: "/report", icon: "🥂" },
        { labelKey: "nomadStats", href: "/report/data", icon: "📊", new: true },
        { labelKey: "gigBoard", href: "/gigs", icon: "💰" },
      ],
    },
    {
      titleKey: "help",
      items: [
        { labelKey: "ideasBugs", href: "/feedback", icon: "💡" },
        { labelKey: "faq", href: "#", icon: "🆘" },
        { labelKey: "terms", href: "#", icon: "📄" },
        { labelKey: "changelog", href: "#", icon: "🚀" },
      ],
    },
    {
      titleKey: "other",
      items: [
        { labelKey: "digitalNomadGuide", href: process.env.NEXT_PUBLIC_DIGITAL_URL || "https://digital.hackrobot.cn/", icon: "📖" },
        { labelKey: "remoteJobs", href: "#", icon: "💼" },
        { labelKey: "coworking", href: "#", icon: "🏢" },
      ],
    },
  ];

  const profileItems: MenuItem[] = [
    { labelKey: "yourProfile", href: "/join", icon: "👤" },
    { labelKey: "settings", href: "/join", icon: "⚙️" },
    { labelKey: "favorites", href: "/", icon: "❤️" },
    { labelKey: "pricing", href: "/pricing", icon: "👑" },
    { labelKey: "nomadInsurance", href: "#", icon: "🛡️", ad: true },
  ];

  const filteredSections = sections;

  if (!isOpen) return null;

  return (
    <>
      <div className="fixed inset-0 z-40 bg-black/20 backdrop-blur-sm md:bg-transparent md:backdrop-blur-none" aria-hidden />
      <div
        ref={ref}
        className="fixed left-4 right-4 top-20 md:left-auto md:right-4 md:top-16 md:w-[480px] z-50 rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-2xl overflow-hidden"
      >
        {/* Profile links */}
        <div className="px-4 py-3 border-b border-gray-100 dark:border-gray-800 flex flex-wrap items-center gap-2">
          {profileItems.map((item) => (
            <Link
              key={item.labelKey}
              href={item.href}
              onClick={onClose}
              className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
            >
              <span>{item.icon}</span>
              <span>{t(item.labelKey)}</span>
            </Link>
          ))}
        </div>

        {/* Sections */}
        <div className="max-h-[60vh] overflow-y-auto p-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {filteredSections.map((section) => (
              <div key={section.titleKey}>
                <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-3">
                  {t(section.titleKey)}
                </h3>
                <ul className="space-y-1">
                  {section.items.map((item) => {
                    const isExternal = item.href.startsWith("http");
                    const linkClass = `flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
                      item.href !== "#" && !isExternal && (pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href)))
                        ? "bg-[#ff4d4f]/10 text-[#ff4d4f]"
                        : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800"
                    }`;
                    return (
                    <li key={item.labelKey}>
                      {isExternal ? (
                        <a
                          href={item.href}
                          target="_blank"
                          rel="noopener noreferrer"
                          onClick={onClose}
                          className={linkClass}
                        >
                        <span className="w-5 text-center">{item.icon}</span>
                        <span className="flex-1">{t(item.labelKey)}</span>
                        {item.new && (
                          <span className="px-2 py-0.5 rounded-full bg-[#ff4d4f] text-white text-[10px] font-medium">
                            NEW
                          </span>
                        )}
                        {item.ad && (
                          <span className="px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-[10px] text-gray-500">
                            Ad
                          </span>
                        )}
                      </a>
                      ) : (
                        <Link
                          href={item.href}
                          onClick={onClose}
                          className={linkClass}
                        >
                        <span className="w-5 text-center">{item.icon}</span>
                        <span className="flex-1">{t(item.labelKey)}</span>
                        {item.new && (
                          <span className="px-2 py-0.5 rounded-full bg-[#ff4d4f] text-white text-[10px] font-medium">
                            NEW
                          </span>
                        )}
                        {item.ad && (
                          <span className="px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-[10px] text-gray-500">
                            Ad
                          </span>
                        )}
                      </Link>
                      )}
                    </li>
                    );
                  })}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* Footer */}
        {userEmail && (
          <div className="p-4 border-t border-gray-100 dark:border-gray-800">
            <button
              onClick={() => {
                pbLogout();
                onClose();
              }}
              className="flex items-center gap-2 w-full px-3 py-2 rounded-lg text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
            >
              <span>🚪</span>
              <span>{t("logout")}</span>
            </button>
          </div>
        )}
      </div>
    </>
  );
});
