/**
 * TVBackButton — persistent on-screen BACK button shown on Samsung
 * Tizen / LG webOS only.
 *
 * Why a visible button at all when we already wire the remote BACK key?
 *   - On many older 2018–2020 Samsung TV remotes the BACK button is
 *     tiny / unlabeled / hidden under a flap. Users genuinely cannot
 *     find it. A visible top-left "←" gives them an unmistakable
 *     escape hatch they can reach via the arrow keys + OK.
 *   - QA testers (Samsung Seller Office) look for an obvious back
 *     affordance during the review — its absence has been flagged on
 *     other IPTV apps before.
 *
 * Visibility rules — button is shown iff ALL true:
 *   - Running on Tizen or webOS (isSmartTV())
 *   - NOT on a root page (/, /welcome, /login, /splash) — those pages
 *     have no in-app history to pop and rendering "←" there is
 *     misleading.
 *
 * Focus behaviour:
 *   - Registered with norigin-spatial-navigation so it joins the
 *     arrow-key focus ring naturally.
 *   - focusKey="tv-back-button" — pages can call setFocus() on this
 *     key if they want to land focus here on mount.
 */
import { useLocation, useNavigate } from "react-router-dom";
import { ArrowLeft } from "lucide-react";

import { FocusableButton } from "@/components/focusable/FocusableButton";
import { isSmartTV } from "@/lib/platform";

const ROOT_PATHS = new Set(["/", "/welcome", "/login", "/splash"]);

const TVBackButton = () => {
  const navigate = useNavigate();
  const location = useLocation();

  if (!isSmartTV()) return null;
  if (ROOT_PATHS.has(location.pathname)) return null;

  const goBack = () => {
    // Prefer real history pop (keeps scroll + state).
    // Fall back to / if history is empty (cold start / restored
    // process) — matches BackButtonHandler's logic exactly so the
    // remote BACK key and the on-screen button behave identically.
    if (window.history.length > 1) {
      navigate(-1);
    } else {
      navigate("/", { replace: true });
    }
  };

  return (
    <FocusableButton
      focusKey="tv-back-button"
      onEnter={goBack}
      onClick={goBack}
      data-testid="tv-back-button"
      aria-label="Back"
      className="fixed top-4 left-4 z-[70] flex items-center justify-center w-12 h-12 rounded-full glass border border-primary/30 text-primary hover:border-primary/60 transition-colors backdrop-blur-md"
      focusClassName="ring-2 ring-primary shadow-[0_0_30px_hsla(40,80%,55%,0.45)] scale-105 border-primary/80"
      style={{
        background: "hsla(200, 40%, 8%, 0.78)",
        boxShadow: "0 0 22px hsla(40, 80%, 55%, 0.20)",
      }}
    >
      <ArrowLeft className="w-5 h-5" strokeWidth={2.2} />
    </FocusableButton>
  );
};

export default TVBackButton;
