/**
 * Platform detection utilities for Smart TV environments.
 * Detects webOS (LG), Tizen (Samsung), and standard web/Capacitor.
 */

export type Platform = "webos" | "tizen" | "capacitor" | "web";

/**
 * Detects the current platform based on global objects injected by the TV OS.
 * - webOS: window.webOS exists
 * - Tizen: window.tizen exists
 * - Capacitor: window.Capacitor exists (Android/iOS native)
 * - web: fallback for browsers
 */
export function getPlatform(): Platform {
  if (typeof window === "undefined") return "web";

  // LG webOS injects `webOS` global
  if ((window as any).webOS) return "webos";

  // Samsung Tizen injects `tizen` global
  if ((window as any).tizen) return "tizen";

  // Capacitor native (Android/iOS)
  if ((window as any).Capacitor?.isNativePlatform?.()) return "capacitor";

  return "web";
}

/**
 * Returns true if running on a Smart TV platform (webOS or Tizen).
 */
export function isSmartTV(): boolean {
  const platform = getPlatform();
  return platform === "webos" || platform === "tizen";
}

/**
 * Returns true if running on LG webOS.
 */
export function isWebOS(): boolean {
  return getPlatform() === "webos";
}

/**
 * Returns true if running on Samsung Tizen.
 */
export function isTizen(): boolean {
  return getPlatform() === "tizen";
}

/**
 * Returns true if running inside Capacitor native shell.
 */
export function isCapacitor(): boolean {
  return getPlatform() === "capacitor";
}

/**
 * FEATURE (2026-01) — true for Capacitor APKs running on phones / tablets
 * (Android, iOS), false for Smart-TV builds (Tizen, WebOS) and web.
 *
 * Used by BottomLeftBar / BottomRightBar to HIDE the time / weather /
 * location chips on mobile (screen space is precious) while keeping
 * them visible on the 16:9 TV / desktop estate where they add ambience.
 *
 * Capacitor reports the actual underlying OS via `getPlatform()` even
 * inside its native WebView, so a Tizen `.wgt` (`getPlatform() === "web"`)
 * correctly returns false here.
 */
export function isMobileNative(): boolean {
  if (typeof window === "undefined") return false;
  // SmartTV WebView could theoretically be wrapped in Capacitor in some
  // exotic distribution; explicitly exclude TV identifiers first so the
  // chips never disappear on living-room screens.
  if (isSmartTV()) return false;
  const cap = (window as any).Capacitor;
  if (!cap?.isNativePlatform?.()) return false;
  const p = (cap.getPlatform?.() || "").toLowerCase();
  return p === "android" || p === "ios";
}

/**
 * webOS-specific exit function. Routes through the official
 * `platformBack()` API which webOS interprets as "user pressed
 * BACK on a root screen" — the OS then returns the user to the
 * launcher / home dashboard.
 *
 * We try every flavour of the API surface that ships across
 * webOS 4 / 5 / 6 / 22 so the call works on any TV the app is
 * installed on:
 *   1. `window.webOS.platformBack()`        — classic SDK (webOS ≤ 5)
 *   2. `window.webOSSystem.platformBack()`  — newer split namespace
 *   3. `window.webOSDev.platformBack()`     — `webOSTV-dev.js` helper
 *   4. `window.PalmSystem.platformBack()`   — legacy Palm/HP webOS
 *
 * No-ops on every non-webOS platform.
 */
export function exitWebOS(): void {
  const w = window as any;
  const candidates = [
    w.webOS?.platformBack,
    w.webOSSystem?.platformBack,
    w.webOSDev?.platformBack,
    w.PalmSystem?.platformBack,
  ];
  for (const fn of candidates) {
    if (typeof fn === "function") {
      try {
        fn();
        return;
      } catch (e) {
        console.warn("[exitWebOS] candidate failed, trying next:", e);
      }
    }
  }
}

/**
 * Tizen-specific exit function. Calls tizen.application.getCurrentApplication().exit().
 */
export function exitTizen(): void {
  const tizen = (window as any).tizen;
  if (tizen?.application?.getCurrentApplication) {
    try {
      tizen.application.getCurrentApplication().exit();
    } catch (e) {
      console.warn("Tizen exit failed:", e);
    }
  }
}

/**
 * Universal exit function that works on all platforms.
 */
export function exitApp(): void {
  const platform = getPlatform();
  switch (platform) {
    case "webos":
      exitWebOS();
      break;
    case "tizen":
      exitTizen();
      break;
    case "capacitor":
      // Handled by Capacitor's App.exitApp()
      import("@capacitor/app").then(({ App }) => App.exitApp());
      break;
    default:
      // Web: can't really exit, maybe close tab
      window.close();
  }
}
