import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Home, Tv, Film, Clapperboard, User, Trophy } from "lucide-react";
import { isTizen, isWebOS } from "@/lib/platform";

// Samsung Tizen + LG webOS QA v1.4.3 — World-Cup tab hidden from the
// bottom nav until store approval (mirrors the dashboard-card guard
// in Index.tsx). Re-enable by removing the runtime `.filter()` below.
const HIDE_WC_ON_TV = isTizen() || isWebOS();
import { FocusableButton, FocusableSection } from "@/components/focusable";
import { useIsMobile } from "@/hooks/use-mobile";

type Tab = {
  key: string;
  label: string;
  route: string;
  icon: typeof Home;
};

const TABS: Tab[] = [
  { key: "home", label: "Home", route: "/", icon: Home },
  { key: "live", label: "Live TV", route: "/live-tv", icon: Tv },
  { key: "movies", label: "Movies", route: "/movies", icon: Film },
  { key: "series", label: "Series", route: "/series", icon: Clapperboard },
  ...(HIDE_WC_ON_TV
    ? []
    : [{ key: "worldcup", label: "World Cup", route: "/world-cup", icon: Trophy } as Tab]),
  { key: "account", label: "Account", route: "/account", icon: User },
];

// Pages where the bottom nav should be shown
const SHOW_ON = new Set([
  "/",
  "/live-tv",
  "/movies",
  "/series",
  ...(HIDE_WC_ON_TV ? [] : ["/world-cup"]),
  "/account",
]);

/**
 * Watches the viewport orientation. Returns true when the device is in
 * landscape AND the viewport height is short enough that an on-screen bar
 * would meaningfully eat into video playback (≤ 500px). This is what we
 * use to fully hide the bottom nav while watching a stream sideways.
 */
const useLandscapePhone = () => {
  const [landscape, setLandscape] = useState(false);
  useEffect(() => {
    const mql = window.matchMedia(
      "(orientation: landscape) and (max-height: 500px)",
    );
    const onChange = () => setLandscape(mql.matches);
    onChange();
    // Safari < 14 fallback
    if (mql.addEventListener) mql.addEventListener("change", onChange);
    else mql.addListener(onChange);
    return () => {
      if (mql.removeEventListener) mql.removeEventListener("change", onChange);
      else mql.removeListener(onChange);
    };
  }, []);
  return landscape;
};

const BottomNav = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const isMobile = useIsMobile();
  const isLandscapePhone = useLandscapePhone();

  if (!SHOW_ON.has(location.pathname)) return null;

  // Phone in landscape → give the screen back to the video. The user can
  // still navigate via the in-page back arrow / gestures.
  if (isMobile && isLandscapePhone) return null;

  // ── Sizing tokens ──────────────────────────────────────────────
  // Icon-only bar (no labels) — keep it slim and pushed all the way to
  // the device edge. Mobile uses near-zero padding; on TV/desktop we
  // also keep it tight so it reads as a thin icon strip.
  const navStyle: React.CSSProperties = isMobile
    ? {
        // Sit at the very edge (only the system safe-area, no extra pad).
        paddingBottom: "env(safe-area-inset-bottom, 0px)",
      }
    : { paddingBottom: "env(safe-area-inset-bottom, 0px)" };

  return (
    <nav
      className="fixed bottom-0 left-0 right-0 z-50 border-t border-border/60 bg-background/85 backdrop-blur-xl"
      style={navStyle}
      data-testid="bottom-nav"
      data-mobile={isMobile ? "1" : "0"}
    >
      <FocusableSection
        focusKey="bottom-nav"
        className={
          isMobile
            ? "flex items-stretch justify-around px-1 py-1"
            : "flex items-stretch justify-around px-1 py-2"
        }
      >
        {TABS.map((tab) => {
          const active = location.pathname === tab.route;
          const Icon = tab.icon;
          return (
            <FocusableButton
              key={tab.key}
              focusKey={`nav-${tab.key}`}
              onEnter={() => navigate(tab.route)}
              onClick={() => navigate(tab.route)}
              subtle
              data-testid={`nav-${tab.key}`}
              aria-label={tab.label}
              className={`flex flex-1 flex-col items-center justify-center rounded-lg transition-colors border-transparent ${
                isMobile ? "py-1" : "py-2"
              } ${
                active
                  ? "text-primary"
                  : "text-muted-foreground hover:text-foreground"
              }`}
              focusClassName="!border-primary/50"
            >
              <Icon
                className={`${isMobile ? "h-5 w-5" : "h-6 w-6"} ${active ? "" : "opacity-60"}`}
                strokeWidth={active ? 2.2 : 1.6}
              />
            </FocusableButton>
          );
        })}
      </FocusableSection>
    </nav>
  );
};

export default BottomNav;
