import { PlatformDetector } from "./platform-detect";

/**
 * URL 打开工具类
 *
 * 对齐 Flutter 端 `lib/utils/url_launcher_util.dart`：
 * - Android: 使用 Chrome Intent URL 尝试跳出应用内浏览器
 * - iOS: 使用 Safari URL scheme 尝试跳出应用内浏览器
 * - 其他平台: 使用普通新窗口打开，失败时回退到当前页跳转
 */
export type UrlQueryParams = Record<string, string>;

export class UrlLauncherUtil {
  private constructor() {}

  static openUrlWithExternalBrowser(
    url: string,
    options: { queryParams?: UrlQueryParams } = {},
  ): void {
    if (typeof window === "undefined") return;

    const finalUrl = UrlLauncherUtil.appendQueryParams(
      UrlLauncherUtil.toAbsoluteUrl(url),
      options.queryParams,
    );

    if (PlatformDetector.isAndroid()) {
      window.location.href = UrlLauncherUtil.buildIntentUrl(finalUrl);
      return;
    }

    if (PlatformDetector.isIOS()) {
      window.location.href = UrlLauncherUtil.buildSafariUrl(finalUrl);
      return;
    }

    UrlLauncherUtil.openUrl(finalUrl);
  }

  static openUrl(url: string): void {
    if (typeof window === "undefined") return;

    const finalUrl = UrlLauncherUtil.toAbsoluteUrl(url);
    const opened = window.open(finalUrl, "_blank", "noopener,noreferrer");
    if (!opened) {
      window.location.href = finalUrl;
    }
  }

  static appendQueryParams(
    url: string,
    queryParams?: UrlQueryParams,
  ): string {
    if (!queryParams || Object.keys(queryParams).length === 0) return url;

    const uri = new URL(url, UrlLauncherUtil.getBaseUrl());
    for (const [key, value] of Object.entries(queryParams)) {
      uri.searchParams.set(key, value);
    }
    return uri.toString();
  }

  static buildIntentUrl(url: string): string {
    const uri = new URL(url, UrlLauncherUtil.getBaseUrl());
    const scheme = uri.protocol.replace(":", "") || "https";
    const path = `${uri.pathname}${uri.search}`;
    return `intent://${uri.host}${path}#Intent;scheme=${scheme};package=com.android.chrome;end`;
  }

  static buildSafariUrl(url: string): string {
    const uri = new URL(url, UrlLauncherUtil.getBaseUrl());
    const path = `${uri.pathname}${uri.search}`;
    return `x-safari-https://${uri.host}${path}`;
  }

  private static toAbsoluteUrl(url: string): string {
    return new URL(url, UrlLauncherUtil.getBaseUrl()).toString();
  }

  private static getBaseUrl(): string {
    if (typeof window !== "undefined") return window.location.origin;
    return "https://cozsweet.com";
  }
}
