import {
  type CSSProperties,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { createPortal } from "react-dom";
import { useNavigate, useParams } from "react-router";
import { t } from "@lingui/core/macro";
import { useCategories } from "../hooks/useCategories.ts";

/**
 * Header dropdown that switches the feed scope between "All" and a category,
 * preserving the active feed tab (e.g. /music/new → /cinema/new). Rendered as
 * the leading item of the feed-sort tab row so it reads as part of the bar.
 *
 * A custom popover (not a native <select>) keeps it on-theme; the menu uses
 * fixed positioning so the row's `overflow-x: auto` can't clip it. `~` is the
 * sentinel value for the all-categories feed. Hidden when no categories exist.
 */
export function CategorySwitcher() {
  const { categories } = useCategories();
  const navigate = useNavigate();
  const { categorySlug, feedTab } = useParams();

  const [open, setOpen] = useState(false);
  const [menuStyle, setMenuStyle] = useState<CSSProperties>({});
  const wrapRef = useRef<HTMLDivElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLUListElement>(null);

  // Close on outside click / Escape. The menu is portaled out of the wrapper,
  // so check it separately or selecting an option would close before navigating.
  useEffect(() => {
    if (!open) return;
    function onDown(e: MouseEvent) {
      const target = e.target as Node;
      if (
        wrapRef.current && !wrapRef.current.contains(target) &&
        menuRef.current && !menuRef.current.contains(target)
      ) {
        setOpen(false);
      }
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  // Anchor the fixed-position menu to the trigger; keep it aligned on scroll.
  useLayoutEffect(() => {
    if (!open) return;
    const update = () => {
      const r = btnRef.current?.getBoundingClientRect();
      if (r) setMenuStyle({ top: r.bottom + 6, left: r.left });
    };
    update();
    globalThis.addEventListener("scroll", update, true);
    globalThis.addEventListener("resize", update);
    return () => {
      globalThis.removeEventListener("scroll", update, true);
      globalThis.removeEventListener("resize", update);
    };
  }, [open]);

  if (categories.length === 0) return null;

  const value = categorySlug ?? "~";
  const tab = feedTab ?? "hot";
  const currentLabel = categorySlug
    ? categories.find((c) => c.slug === categorySlug)?.name ?? categorySlug
    : t`All`;

  const options = [
    { value: "~", label: t`All` },
    ...categories.map((c) => ({ value: c.slug, label: c.name })),
  ];

  function select(slug: string) {
    setOpen(false);
    navigate(`/${slug}/${tab}`);
  }

  return (
    <div className="category-switcher" ref={wrapRef}>
      <button
        ref={btnRef}
        type="button"
        className={`feed-sort-btn category-switcher-btn${
          open ? " category-switcher-btn--open" : ""
        }`}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        title={t`Category`}
      >
        <span className="category-switcher-label">{currentLabel}</span>
        <span className="category-switcher-caret" aria-hidden="true" />
      </button>

      {open && createPortal(
        <ul
          ref={menuRef}
          className="category-switcher-menu"
          role="listbox"
          style={menuStyle}
        >
          {options.map((o) => (
            <li key={o.value}>
              <button
                type="button"
                role="option"
                aria-selected={value === o.value}
                className={`category-switcher-option${
                  value === o.value ? " category-switcher-option--active" : ""
                }`}
                onClick={() => select(o.value)}
              >
                {o.label}
              </button>
            </li>
          ))}
        </ul>,
        document.body,
      )}

      <span className="feed-sort-sep" aria-hidden="true" />
    </div>
  );
}
