// https://github.com/f2etw/detect-inapp/blob/master/src/inapp.js

import { findKey } from "lodash";

const BROWSER = {
  messenger: /\bFB[\w_]+\/(Messenger|MESSENGER)/,
  facebook: /\bFB[\w_]+\//,
  twitter: /\bTwitter/i,
  line: /\bLine\//i,
  wechat: /\bMicroMessenger\//i,
  puffin: /\bPuffin/i,
  miui: /\bMiuiBrowser\//i,
  instagram: /\bInstagram/i,
  chrome: /\bCrMo\b|CriOS|Android.*Chrome\/[.0-9]* (Mobile)?/,
  safari: /Version.*Mobile.*Safari|Safari.*Mobile|MobileSafari/,
  ie: /IEMobile|MSIEMobile/,
  firefox:
    /fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS/,
};

export const useInAppBrowser = (): boolean => {
  const userAgent =
    navigator.userAgent ||
    navigator.vendor ||
    (window as unknown as { opera: string }).opera;

  const rules = ["WebView", "(iPhone|iPod|iPad)(?!.*Safari/)", "Android.*(wv)"];
  const regex = new RegExp(`(${rules.join("|")})`, "ig");

  return (
    Boolean(userAgent.match(regex)) &&
    findKey(BROWSER, (regex) => regex.test(userAgent)) !== undefined
  );
};
