import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { App as CapacitorApp } from "@capacitor/app";
import { isNativeApp } from "@/native/nativePlayer";
import { getPlatform, exitWebOS, exitTizen, isSmartTV } from "@/lib/platform";

/**
 * Wires the hardware BACK button for multiple platforms:
 *  - Android (Capacitor): hardware/gesture BACK
 *  - Samsung Tizen: keyCode 10009 (RemoteKey.BACK)
 *  - LG webOS: handled via webOS.platformBack()
 *
 * On root screens (/, /welcome, /login) → exit the app
 * Everywhere else → pop the in-app history stack
 */
const BackButtonHandler = () => {
  const navigate = useNavigate();
  const location = useLocation();

  // Roots from which the BACK button is allowed to terminate the app.
  // Everywhere else, BACK must pop the in-app history — never exit.
  // This is the v2.1 fix for the report:
  //   "back from live/movie/series force-closes the app"
  // The previous logic exited whenever Capacitor reported
  // canGoBack=false, which happens *frequently* on Android 14/15 if
  // the WebView was restored from saved state (process death) — even
  // though the user is clearly deep inside the app. Now we ignore
  // canGoBack outside the root list and always do an in-app pop.
  const rootPaths = ["/", "/welcome", "/login"];
  const atRoot = rootPaths.includes(location.pathname);

  // Handle back navigation
  const handleBack = (canGoBack: boolean) => {
    if (atRoot) {
      // Exit the app based on platform
      const platform = getPlatform();
      switch (platform) {
        case "webos":
          exitWebOS();
          break;
        case "tizen":
          exitTizen();
          break;
        case "capacitor":
          CapacitorApp.exitApp();
          break;
        default:
          // Web: can't exit, maybe close tab
          window.close();
      }
      return;
    }
    // NOT at root. Always stay in-app:
    //   • Prefer real history pop (preserves scroll + state)
    //   • If history is empty (cold start / restored process), fall
    //     back to the dashboard rather than exiting the app.
    if (canGoBack && window.history.length > 1) {
      navigate(-1);
    } else {
      navigate("/", { replace: true });
    }
  };

  // Capacitor (Android/iOS) back button
  useEffect(() => {
    if (!isNativeApp()) return;

    let remove: (() => void) | null = null;

    (async () => {
      const sub = await CapacitorApp.addListener(
        "backButton",
        ({ canGoBack }) => {
          handleBack(canGoBack);
        },
      );
      remove = () => sub.remove();
    })();

    return () => {
      if (remove) remove();
    };
  }, [navigate, location.pathname]);

  // Samsung Tizen back button (keyCode 10009) + webOS (461)
  // SAMSUNG QA v1.4.2 — registered at the WINDOW level with `capture=true`
  // so the handler runs BEFORE any nested component can call
  // preventDefault. This guarantees the BACK key remains active even
  // when the app is mid-async-request and React is paused on a
  // pending promise.
  useEffect(() => {
    if (!isSmartTV()) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      // Samsung Tizen: keyCode 10009 is the BACK key
      // LG webOS: keyCode 461 is the BACK key
      // Also support browser back (Escape) for testing
      if (e.keyCode === 10009 || e.keyCode === 461 || e.key === "Escape") {
        e.preventDefault();
        e.stopPropagation();
        handleBack(window.history.length > 1);
      }
    };

    // Register the remote control keys for Tizen
    const tizen = (window as any).tizen;
    if (tizen?.tvinputdevice) {
      try {
        // CRITICAL — register "Return" so keyCode 10009 reaches this
        // handler instead of the OS exiting the app on every press.
        tizen.tvinputdevice.registerKey("Return");
        tizen.tvinputdevice.registerKey("MediaPlayPause");
        tizen.tvinputdevice.registerKey("MediaPlay");
        tizen.tvinputdevice.registerKey("MediaPause");
        tizen.tvinputdevice.registerKey("MediaStop");
        tizen.tvinputdevice.registerKey("MediaRewind");
        tizen.tvinputdevice.registerKey("MediaFastForward");
      } catch (e) {
        console.warn("Failed to register Tizen keys:", e);
      }
    }

    document.addEventListener("keydown", handleKeyDown, true);
    // ALSO attach at window level so we win against React Router's
    // own keydown handlers. capture=true means we run BEFORE any
    // bubbling-phase handler can call e.stopPropagation().
    window.addEventListener("keydown", handleKeyDown, true);

    return () => {
      document.removeEventListener("keydown", handleKeyDown, true);
      window.removeEventListener("keydown", handleKeyDown, true);
    };
  }, [navigate, location.pathname]);

  return null;
};

export default BackButtonHandler;
