/**
 * =====================================================================
 *  Samsung Tizen TV remote-key registration
 * =====================================================================
 *  Out of the box, Tizen only forwards Arrow keys, Enter and Back to
 *  the web app. Every OTHER remote button (colour keys, MediaPlay,
 *  MediaPause, volume, number pad, ChannelUp/Down, …) must be
 *  EXPLICITLY registered via `tizen.tvinputdevice.registerKey()` —
 *  otherwise the WebView swallows them at the OS level.
 *
 *  This is almost always the REAL reason "arrows work in Tizen OS
 *  but stop working inside my app" — the app focuses a random
 *  <object> or an unfocusable <div>, and the keydown never reaches
 *  React. Registering the whole key set forces Tizen to route every
 *  event through the WebView's keydown handler so the spatial
 *  navigation library can pick them up.
 *
 *  Called once from App.tsx at mount time.
 * =====================================================================
 */

interface TizenInputDevice {
  getSupportedKeys(): Array<{ name: string; code: number }>;
  registerKey(name: string): void;
  registerKeyBatch(names: string[]): void;
  unregisterKey(name: string): void;
}

interface TizenGlobal {
  tvinputdevice?: TizenInputDevice;
}

const REMOTE_KEYS = [
  // ── BACK key — CRITICAL on Tizen 4+ ──
  // Without this registration, the OS swallows the Return key BEFORE
  // it reaches the WebView's keydown handler and the app force-closes
  // instead of letting React Router pop the history stack. This was
  // the root cause of "remote back button exits the app" on every
  // 2018+ Samsung TV. Registering "Return" forces Tizen to route
  // keyCode 10009 to JavaScript so BackButtonHandler can intercept
  // it and do navigate(-1).
  "Return",
  // Some firmwares only know the name "Back" — register both so we
  // are bullet-proof against the rare older Tizen 2.x model.
  // (registerKey throws "NotFoundError" on unknown names, which we
  // catch silently — so this is safe even if "Back" isn't a valid
  // identifier on the current firmware.)
  "Back",
  // ── Media transport ──
  "MediaPlay",
  "MediaPause",
  "MediaStop",
  "MediaPlayPause",
  "MediaRewind",
  "MediaFastForward",
  "MediaTrackNext",
  "MediaTrackPrevious",
  "MediaRecord",
  // ── TV-specific ──
  "ChannelUp",
  "ChannelDown",
  "ColorF0Red",
  "ColorF1Green",
  "ColorF2Yellow",
  "ColorF3Blue",
  "Info",
  "Exit",
  "Source",
  "Menu",
  "Tools",
  // ── Number pad ──
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
] as const;

let registered = false;

export const registerTizenRemoteKeys = (): void => {
  if (registered) return;
  if (typeof window === "undefined") return;

  const tizen = (window as unknown as { tizen?: TizenGlobal }).tizen;
  const input = tizen?.tvinputdevice;
  if (!input) return; // Not on Tizen — nothing to do.

  try {
    // registerKeyBatch is faster on Tizen 4+; fall back to per-key calls.
    // We ALWAYS use per-key calls even when the batch API exists,
    // because the batch call aborts on the first unknown name. Older
    // firmwares might not know "MediaRecord", "Back", or one of the
    // colour keys — losing the rest of the batch over a single
    // unknown name would break the BACK button on those TVs.
    let okCount = 0;
    for (const name of REMOTE_KEYS) {
      try {
        input.registerKey(name);
        okCount += 1;
      } catch (e) {
        // NotFoundError = name not recognised on this firmware. Safe
        // to ignore — we registered as many as we could.
        console.warn(`[Tizen Remote] registerKey(${name}) failed`, e);
      }
    }
    registered = true;
    console.log(
      `[Tizen Remote] keys registered: ${okCount} / ${REMOTE_KEYS.length}`,
    );
  } catch (e) {
    console.error("[Tizen Remote] registration failed:", e);
  }
};
