import { useEffect } from "react";
import {
  init as initSpatial,
  FocusContext,
  useFocusable,
} from "@noriginmedia/norigin-spatial-navigation";
import { preloadSounds } from "@/lib/navSounds";
import { registerTizenRemoteKeys } from "@/native/tizenRemote";

/**
 * Global initialiser for norigin-spatial-navigation.
 *
 * Sits at the root of the app (mounted once from App.tsx). It boots the
 * library, exposes a top-level <FocusContext.Provider> so that any
 * descendant can opt-in to spatial navigation, and registers a no-op
 * focusable root that acts as the default container.
 *
 * Visual-debug can be flipped on from localStorage (`nadiplay_sn_debug="1"`)
 * without a rebuild — handy for diagnosing focus traps on TV / remote.
 */
let initialised = false;

const bootSpatial = () => {
  if (initialised) return;
  initialised = true;

  // Preload navigation sounds
  preloadSounds();

  // Samsung Tizen — tell the OS to forward every remote-control key
  // (colour buttons, media keys, number pad, channel up/down…) to the
  // WebView, otherwise keydown events never reach the spatial-nav
  // library and arrows "work on the OS, fail inside the app".
  registerTizenRemoteKeys();
  
  const debug = (() => {
    try {
      return localStorage.getItem("nadiplay_sn_debug") === "1";
    } catch {
      return false;
    }
  })();
  initSpatial({
    debug,
    visualDebug: debug,
    // When `true`, the library throttles key events — keeps the focus ring
    // smooth on long arrow holds (remote auto-repeat).
    throttle: 80,
    throttleKeypresses: true,
  });
};

export const FocusProvider = ({ children }: { children: React.ReactNode }) => {
  useEffect(() => {
    bootSpatial();
  }, []);

  // A root focusable keeps the context tree rooted and gives the library
  // a predictable boundary for the initial focus search.
  const { ref, focusKey } = useFocusable({
    focusable: false,
    trackChildren: true,
    isFocusBoundary: false,
  });

  return (
    <FocusContext.Provider value={focusKey}>
      <div ref={ref} style={{ display: "contents" }}>
        {children}
      </div>
    </FocusContext.Provider>
  );
};
