/**
 * =====================================================================
 *  TV Platform detection (Samsung Tizen / LG webOS)
 * =====================================================================
 *  Capacitor (`isNativeApp()`) is FALSE on Smart TVs because Capacitor
 *  doesn't run there — the WGT/IPK is just a packaged web bundle. To
 *  pick the right hardware-accelerated player we sniff browser-level
 *  globals injected by the TV runtime:
 *
 *    Samsung Tizen → window.tizen + window.webapis.avplay
 *    LG webOS      → window.webOS or window.PalmSystem
 *
 *  Detection runs once at module load. UA fallback exists because the
 *  TizenWebView occasionally lazy-injects `webapis` *after* the first
 *  paint on cold boot.
 * =====================================================================
 */

declare global {
  interface Window {
    tizen?: unknown;
    webapis?: { avplay?: unknown };
    webOS?: unknown;
    webOSSystem?: unknown;
    PalmSystem?: unknown;
  }
}

export type TVPlatform = "tizen" | "webos" | "none";

const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";

const detectTV = (): TVPlatform => {
  if (typeof window === "undefined") return "none";

  // 1) Samsung Tizen — the WebApi global is the most reliable signal.
  if (typeof window.tizen !== "undefined") return "tizen";
  if (window.webapis && typeof window.webapis.avplay !== "undefined") return "tizen";
  if (/Tizen/i.test(ua) && /SmartTV/i.test(ua)) return "tizen";

  // 2) LG webOS — PalmSystem is the legacy global, webOS is current.
  if (typeof window.webOS !== "undefined") return "webos";
  if (typeof window.webOSSystem !== "undefined") return "webos";
  if (typeof window.PalmSystem !== "undefined") return "webos";
  if (/Web0S|webOS\.TV/i.test(ua)) return "webos";

  return "none";
};

let cached: TVPlatform | null = null;
export const tvPlatform = (): TVPlatform => {
  if (cached === null) cached = detectTV();
  return cached;
};

export const isTizenTV = (): boolean => tvPlatform() === "tizen";
export const isWebOSTV = (): boolean => tvPlatform() === "webos";
export const isSmartTV = (): boolean => tvPlatform() !== "none";
