// تشخیص اینکه کاربر اپلیکیشن/وب‌اپ را نصب کرده یا داخل خود اپ است،
// تا گزینه‌های دانلود دیگر به او نمایش داده نشود.
const STORAGE_KEY = 'app-installed'

export const useAppInstalled = () => {
    const installed = useState<boolean>('app-installed', () => false)

    const isStandalone = () => {
        if (typeof window === 'undefined') return false

        return (
            window.matchMedia?.('(display-mode: standalone)')?.matches ||
            window.matchMedia?.('(display-mode: fullscreen)')?.matches ||
            window.matchMedia?.('(display-mode: minimal-ui)')?.matches ||
            // iOS legacy
            (window.navigator as any).standalone === true
        )
    }

    // WebView اندروید (یعنی کاربر داخل خود اپ است)
    const isAndroidWebView = () => {
        if (typeof navigator === 'undefined') return false

        const ua = navigator.userAgent || ''
        const isAndroid = /Android/i.test(ua)
        const hasWv = /\bwv\b/.test(ua)
        const hasVersion = /Version\/\d+\.\d+/i.test(ua)

        return isAndroid && (hasWv || hasVersion)
    }

    const readFlag = () => {
        try {
            return localStorage.getItem(STORAGE_KEY) === '1'
        } catch (e) {
            return false
        }
    }

    const markInstalled = () => {
        installed.value = true
        try {
            localStorage.setItem(STORAGE_KEY, '1')
        } catch (e) {
            // اگر ذخیره‌سازی در دسترس نبود، فقط همین نشست اعمال می‌شود
        }
    }

    const detect = async () => {
        if (typeof window === 'undefined') return

        if (isStandalone() || isAndroidWebView() || readFlag()) {
            installed.value = true
            return
        }

        // اگر مرورگر پشتیبانی کند، اپ‌های نصب‌شده‌ی مرتبط را می‌پرسیم
        try {
            const getInstalled = (navigator as any).getInstalledRelatedApps

            if (typeof getInstalled === 'function') {
                const apps = await getInstalled.call(navigator)

                if (Array.isArray(apps) && apps.length > 0) {
                    markInstalled()
                }
            }
        } catch (e) {
            // این API در همه‌ی مرورگرها نیست؛ نبودش مشکلی ایجاد نمی‌کند
        }
    }

    // وقتی کاربر همین حالا نصب کرد، بلافاصله گزینه‌ها مخفی شوند
    const listen = () => {
        if (typeof window === 'undefined') return () => {}

        const onInstalled = () => markInstalled()
        window.addEventListener('appinstalled', onInstalled)

        return () => window.removeEventListener('appinstalled', onInstalled)
    }

    return { installed, detect, listen, markInstalled }
}
