import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  Menu as MenuIcon,
  X,
  Home,
  Tv,
  Film,
  Clapperboard,
  User,
  Settings,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { FocusableButton, FocusableSection } from "@/components/focusable";

/**
 * HeaderMenu — Hamburger button + side drawer.
 *
 * Replaces the old fixed BottomNav. The hamburger sits in the page
 * header (compact, gold ring on focus) and on tap opens a luxury
 * gold-on-dark side drawer with the main routes:
 *   • Home
 *   • Live TV
 *   • Movies
 *   • Series
 *   • Account / Settings
 *
 * Designed to be unobtrusive on TV (D-pad friendly) and to free the
 * bottom of the screen for the AdMob banner + InfoBar.
 */
type Item = {
  key: string;
  icon: typeof Home;
  route: string;
  fallback: string;
  i18nKey: string;
};

const ITEMS: Item[] = [
  { key: "home", icon: Home, route: "/", fallback: "Home", i18nKey: "menu.home" },
  { key: "live-tv", icon: Tv, route: "/live-tv", fallback: "Live TV", i18nKey: "menu.liveTv" },
  { key: "movies", icon: Film, route: "/movies", fallback: "Movies", i18nKey: "menu.movies" },
  { key: "series", icon: Clapperboard, route: "/series", fallback: "Series", i18nKey: "menu.series" },
  { key: "account", icon: User, route: "/account", fallback: "Account", i18nKey: "menu.account" },
];

const HeaderMenu = ({ testId = "header-menu" }: { testId?: string }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { t, i18n } = useTranslation();
  const [open, setOpen] = useState(false);
  const isRtl = i18n.dir() === "rtl";

  // Close on route change
  useEffect(() => {
    setOpen(false);
  }, [location.pathname]);

  // Close on ESC
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const labelFor = (item: Item): string => {
    return t(item.i18nKey, { defaultValue: item.fallback });
  };

  return (
    <>
      <FocusableButton
        focusKey="header-menu-open"
        onEnter={() => setOpen(true)}
        onClick={() => setOpen(true)}
        aria-label={t("menu.open", { defaultValue: "Open menu" })}
        data-testid={`${testId}-button`}
        className="w-10 h-10 sm:w-11 sm:h-11 rounded-full glass flex items-center justify-center hover:border-primary/40 transition-colors outline-none"
      >
        <MenuIcon className="w-5 h-5 text-primary" strokeWidth={1.8} />
      </FocusableButton>

      <AnimatePresence>
        {open && (
          <>
            {/* Backdrop */}
            <motion.div
              key="backdrop"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              onClick={() => setOpen(false)}
              className="fixed inset-0 z-[60] bg-black/70 backdrop-blur-sm"
              data-testid={`${testId}-backdrop`}
            />

            {/* Drawer */}
            <FocusableSection
              focusKey="header-menu-drawer"
              autoFocus
              trap
              as="aside"
              className={`fixed top-0 ${isRtl ? "left-0" : "right-0"} bottom-0 z-[61] w-[88%] sm:w-[360px] glass-card flex flex-col`}
              style={{
                background:
                  "linear-gradient(180deg, hsla(200,30%,8%,0.95) 0%, hsla(200,30%,5%,0.97) 100%)",
                borderInlineStart: isRtl
                  ? undefined
                  : "1px solid hsla(40, 80%, 55%, 0.22)",
                borderInlineEnd: isRtl
                  ? "1px solid hsla(40, 80%, 55%, 0.22)"
                  : undefined,
                boxShadow: "0 0 60px hsla(40, 80%, 55%, 0.12)",
                paddingTop: "env(safe-area-inset-top, 0px)",
                paddingBottom: "env(safe-area-inset-bottom, 0px)",
              }}
              data-testid={`${testId}-drawer`}
            >
              {/* Drawer header */}
              <div className="flex items-center justify-between px-5 pt-5 pb-3">
                <div className="flex flex-col">
                  <span
                    className="font-display text-lg tracking-[0.3em] gold-text"
                    style={{ fontFamily: "Cinzel, serif" }}
                  >
                    NADIPLAYER
                  </span>
                  <span className="text-[10px] tracking-[0.25em] uppercase text-muted-foreground mt-0.5">
                    {t("menu.title", { defaultValue: "Menu" })}
                  </span>
                </div>
                <FocusableButton
                  focusKey="header-menu-close"
                  onEnter={() => setOpen(false)}
                  onClick={() => setOpen(false)}
                  aria-label={t("menu.close", { defaultValue: "Close menu" })}
                  data-testid={`${testId}-close`}
                  className="w-9 h-9 rounded-full glass flex items-center justify-center hover:border-primary/40"
                >
                  <X className="w-4 h-4 text-foreground" />
                </FocusableButton>
              </div>

              {/* Gold separator */}
              <div
                className="mx-5 h-px"
                style={{
                  background:
                    "linear-gradient(90deg, transparent, hsla(40,80%,55%,0.45), transparent)",
                }}
              />

              {/* Items */}
              <nav className="flex-1 overflow-y-auto px-3 py-4 flex flex-col gap-1.5">
                {ITEMS.map((item, i) => {
                  const active = location.pathname === item.route;
                  const Icon = item.icon;
                  return (
                    <FocusableButton
                      key={item.key}
                      focusKey={`header-menu-item-${item.key}`}
                      onEnter={() => {
                        setOpen(false);
                        navigate(item.route);
                      }}
                      onClick={() => {
                        setOpen(false);
                        navigate(item.route);
                      }}
                      data-testid={`${testId}-item-${item.key}`}
                      style={{
                        // Stagger the fade-in via inline animation delay
                        // since we're no longer using motion.button.
                        animationDelay: `${0.05 + i * 0.04}s`,
                      }}
                      className={`group relative flex items-center gap-4 rounded-xl px-4 py-3 text-start transition-all outline-none border border-transparent w-full overflow-hidden ${
                        active
                          ? "bg-primary/10 border-primary/40"
                          : "hover:bg-foreground/5 hover:border-primary/20"
                      }`}
                      focusClassName="bg-foreground/5 border-primary/40 ring-2 ring-primary/40"
                    >
                      {/* Gold "selected" rail — vertical bar pinned to
                          the inline-start edge so subscribers know
                          which route they'll land on before pressing
                          OK on the remote. */}
                      {active && (
                        <span
                          aria-hidden="true"
                          className={`absolute inset-y-1 ${
                            isRtl ? "right-0" : "left-0"
                          } w-[3px] rounded-full`}
                          style={{
                            background:
                              "linear-gradient(180deg, hsl(40 80% 65%) 0%, hsl(40 80% 45%) 100%)",
                            boxShadow: "0 0 10px hsla(40, 80%, 55%, 0.55)",
                          }}
                          data-testid={`${testId}-rail-${item.key}`}
                        />
                      )}
                      <span
                        className={`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${
                          active
                            ? "bg-primary/20 text-primary"
                            : "bg-foreground/5 text-muted-foreground group-hover:text-primary"
                        }`}
                      >
                        <Icon className="w-5 h-5" strokeWidth={1.6} />
                      </span>
                      <span
                        className={`flex-1 text-sm tracking-wide ${
                          active ? "text-primary font-medium" : "text-foreground/90"
                        }`}
                      >
                        {labelFor(item)}
                      </span>
                      {active && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary shadow-[0_0_8px_hsl(40,80%,55%)]" />
                      )}
                    </FocusableButton>
                  );
                })}
              </nav>

              {/* Footer (settings shortcut) */}
              <div className="px-3 pb-4 pt-2 border-t border-border/30">
                <FocusableButton
                  focusKey="header-menu-settings"
                  onEnter={() => {
                    setOpen(false);
                    navigate("/account");
                  }}
                  onClick={() => {
                    setOpen(false);
                    navigate("/account");
                  }}
                  data-testid={`${testId}-settings`}
                  className="w-full flex items-center gap-3 rounded-xl px-4 py-2.5 text-muted-foreground hover:text-primary hover:bg-foreground/5 transition-colors"
                  focusClassName="text-primary bg-foreground/5 ring-2 ring-primary/40"
                >
                  <Settings className="w-4 h-4" />
                  <span className="text-xs tracking-[0.2em] uppercase">
                    {t("menu.settings", { defaultValue: "Settings" })}
                  </span>
                </FocusableButton>
              </div>
            </FocusableSection>
          </>
        )}
      </AnimatePresence>
    </>
  );
};

export default HeaderMenu;
