import { BrowserDetector, PlatformDetector } from "@/utils";

import type { KeyboardAdaptEnvironment } from "./types";
import { getVirtualKeyboard } from "./virtual-keyboard";

export function getKeyboardAdaptEnvironment(
  ua: string | null = null,
): KeyboardAdaptEnvironment {
  const platform = PlatformDetector.getPlatformInfo(ua);
  const browser = BrowserDetector.getBrowserInfo(ua);
  const isXiaomiFamilyDevice = PlatformDetector.isXiaomiFamilyDevice(ua);
  const isFacebookInAppBrowser = BrowserDetector.isFacebookInAppBrowser(ua);

  return {
    platform: platform.platform,
    osName: platform.osName,
    osVersion: platform.osVersion,
    deviceVendor: platform.deviceVendor,
    deviceModel: platform.deviceModel,
    isAndroid: platform.isAndroid,
    isIOS: platform.isIOS,
    isMobile: platform.isMobile,
    browserName: browser.name,
    browserVersion: browser.version,
    isInAppBrowser: browser.isInAppBrowser,
    inAppBrowserName: browser.inAppBrowserName,
    isXiaomiFamilyDevice,
    isFacebookInAppBrowser,
    hasVisualViewport:
      typeof window !== "undefined" && window.visualViewport != null,
    hasVirtualKeyboard: getVirtualKeyboard() != null,
    usesXiaomiFacebookFallback:
      platform.isAndroid && isXiaomiFamilyDevice && isFacebookInAppBrowser,
  };
}

export function shouldEnableKeyboardAdaptation(
  environment: KeyboardAdaptEnvironment,
): boolean {
  return environment.isInAppBrowser;
}

export function shouldUseInAppKeyboardFallback(): boolean {
  if (typeof navigator === "undefined") return false;
  return getKeyboardAdaptEnvironment(navigator.userAgent).usesXiaomiFacebookFallback;
}
