import { useMemo } from 'react';

import { useSearchParams } from 'react-router-dom';

const env: ImportMetaEnv =
    typeof import.meta !== 'undefined' ? (import.meta as any).env : undefined;

const GOOGLE_STORE_URL = env?.VITE_APP_GOOGLE_STORE_URL ?? '';
const APPLE_STORE_URL = env?.VITE_APP_APPLE_STORE_URL ?? '';
const APK_URL = env?.VITE_APP_APK_URL ?? '';
const MACOS_URL = env?.VITE_APP_MACOS_URL ?? '';
const WINDOWS_URL = env?.VITE_APP_WINDOWS_URL ?? '';

const DEEPLINK_URL = env?.VITE_APP_DEEPLINK_URL ?? '';

const REFERRER_PARAM = 'referrer';

function getDownloadUrlByPlatform(
    google: string,
    apple: string,
    apk: string,
    macos: string,
    windows: string,
    fallback: string
): string {
    if (typeof navigator === 'undefined' || !navigator.userAgent)
        return fallback || windows || apk || google || apple || macos;
    const ua = navigator.userAgent;
    const isIos =
        /iPad|iPhone|iPod/.test(ua) ||
        (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    const isAndroid = /Android/.test(ua);
    const isMac = !isIos && /Macintosh|Mac OS X/.test(ua);
    const isWindows = /Windows/.test(ua);
    if (isIos && apple) return apple;
    if (isAndroid) return google || apk;
    if (isMac && macos) return macos;
    if (isWindows && windows) return windows;
    return fallback || windows || apk || google || apple || macos;
}

export interface AppUrls {
    /** 前往 App 注册的 deeplink（含 URL 中的 referrer 参数），空则仅展示文案不跳转 */
    deeplinkUrl: string;
    /** Google Play 商店地址，未配置时为空 */
    googleStoreUrl: string;
    /** Apple App Store 地址，未配置时为空 */
    appleStoreUrl: string;
    /** APK 直链地址，未配置时为空 */
    apkUrl: string;
    /** macOS 客户端下载地址，未配置时为空 */
    macosUrl: string;
    /** Windows 客户端下载地址，未配置时为空 */
    windowsUrl: string;
    /** 根据当前用户平台自动选择的下载地址 */
    downloadUrlByPlatform: string;
}

/**
 * 统一获取 App 相关链接：注册 deeplink、下载地址等，均从环境变量与当前 URL 拼出。
 * 后续新增链接时在 AppUrls 与下方实现中扩展即可。
 */
export function useAppUrls(): AppUrls {
    const [searchParams] = useSearchParams();

    return useMemo<AppUrls>(() => {
        const referrer = searchParams.get(REFERRER_PARAM) || '';
        const referrerEnc = referrer.trim() ? encodeURIComponent(referrer.trim()) : '';

        const deeplinkUrl = (() => {
            if (!DEEPLINK_URL) return '';
            if (!referrerEnc) return DEEPLINK_URL;
            try {
                const sep = DEEPLINK_URL.includes('?') ? '&' : '?';
                return `${DEEPLINK_URL}${sep}${REFERRER_PARAM}=${referrerEnc}`;
            } catch {
                return '';
            }
        })();

        const googleStoreUrl = (() => {
            if (!GOOGLE_STORE_URL) return '';
            if (!referrerEnc) return GOOGLE_STORE_URL;
            try {
                const sep = GOOGLE_STORE_URL.includes('?') ? '&' : '?';
                return `${GOOGLE_STORE_URL}${sep}${REFERRER_PARAM}=${referrerEnc}`;
            } catch {
                return GOOGLE_STORE_URL;
            }
        })();

        const apkUrl = (() => {
            if (!APK_URL) return '';
            if (!referrerEnc) return APK_URL;
            try {
                const sep = APK_URL.includes('?') ? '&' : '?';
                return `${APK_URL}${sep}${REFERRER_PARAM}=${referrerEnc}`;
            } catch {
                return APK_URL;
            }
        })();

        const macosUrl = (() => {
            if (!MACOS_URL) return '';
            if (!referrerEnc) return MACOS_URL;
            try {
                const sep = MACOS_URL.includes('?') ? '&' : '?';
                return `${MACOS_URL}${sep}${REFERRER_PARAM}=${referrerEnc}`;
            } catch {
                return MACOS_URL;
            }
        })();

        const windowsUrl = (() => {
            if (!WINDOWS_URL) return '';
            if (!referrerEnc) return WINDOWS_URL;
            try {
                const sep = WINDOWS_URL.includes('?') ? '&' : '?';
                return `${WINDOWS_URL}${sep}${REFERRER_PARAM}=${referrerEnc}`;
            } catch {
                return WINDOWS_URL;
            }
        })();

        return {
            deeplinkUrl,
            googleStoreUrl,
            appleStoreUrl: APPLE_STORE_URL,
            apkUrl,
            macosUrl,
            windowsUrl,
            downloadUrlByPlatform: getDownloadUrlByPlatform(
                googleStoreUrl,
                APPLE_STORE_URL,
                apkUrl,
                macosUrl,
                windowsUrl,
                ''
            ),
        };
    }, [searchParams]);
}
