/**
 * Detect popular in-app WebViews that block file downloads or ignore
 * `Content-Disposition: attachment`, so the UI can show an "open in external
 * browser" guide instead of silently opening the file inline.
 */

function ua(): string {
  if (typeof navigator === "undefined") return "";
  return navigator.userAgent || "";
}

const PATTERNS: Array<{ re: RegExp; name: string }> = [
  { re: /MicroMessenger/i, name: "WeChat" },
  { re: /TokenPocket/i, name: "TokenPocket" },
  { re: /imToken/i, name: "imToken" },
  { re: /Trust(Wallet|Browser)/i, name: "Trust Wallet" },
  { re: /MetaMask/i, name: "MetaMask" },
  { re: /Telegram/i, name: "Telegram" },
  { re: /\bLine\//i, name: "LINE" },
  { re: /FBAN|FBAV/i, name: "Facebook" },
  { re: /Instagram/i, name: "Instagram" },
  { re: /Twitter|\bX\//i, name: "Twitter/X" },
  { re: /Weibo/i, name: "Weibo" },
  { re: /MQQBrowser/i, name: "QQ Browser" },
  { re: /\bQQ\//i, name: "QQ" },
  { re: /MiuiBrowser/i, name: "Mi Browser" },
  { re: /Snapchat/i, name: "Snapchat" },
];

export function isInAppBrowser(): boolean {
  const agent = ua();
  if (!agent) return false;
  return PATTERNS.some(({ re }) => re.test(agent));
}

export function inAppBrowserName(): string | null {
  const agent = ua();
  if (!agent) return null;
  for (const { re, name } of PATTERNS) {
    if (re.test(agent)) return name;
  }
  return null;
}
