const STORAGE_KEY = 'collabs_pwa_install_dismissed_at';
const TTL_MS = 60 * 24 * 60 * 60 * 1000; // 60 days

/** @type {Event | null} */
let sharedDeferredPrompt = null;

function isStandalone() {
    return (
        window.matchMedia('(display-mode: standalone)').matches ||
        window.navigator.standalone === true
    );
}

function isIos() {
    return /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
}

function isMacSafari() {
    const ua = navigator.userAgent;
    return /Macintosh/.test(ua) && /Safari/.test(ua) && !/Chrome/.test(ua);
}

function dismissedRecently() {
    try {
        const raw = localStorage.getItem(STORAGE_KEY);
        if (!raw) {
            return false;
        }
        const at = parseInt(raw, 10);
        if (Number.isNaN(at)) {
            return false;
        }
        return Date.now() - at < TTL_MS;
    } catch {
        return false;
    }
}

function persistDismiss() {
    try {
        localStorage.setItem(STORAGE_KEY, String(Date.now()));
    } catch {
        //
    }
}

export function initInstallBanner() {
    const root = document.getElementById('pwa-install-banner');
    if (!root) {
        return;
    }

    if (isStandalone() || dismissedRecently()) {
        root.remove();
        return;
    }

    const btnClose = root.querySelector('[data-install-dismiss]');
    const btnChrome = root.querySelector('[data-install-chrome]');
    const chromeHint = root.querySelector('[data-install-chrome-hint]');
    const safariHint = root.querySelector('[data-install-safari-hint]');

    if (!window.__collabsPwaBipAttached) {
        window.__collabsPwaBipAttached = true;
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            sharedDeferredPrompt = e;
            document.querySelectorAll('[data-install-chrome-hint]').forEach((el) => el.classList.remove('hidden'));
            document.querySelectorAll('[data-install-safari-hint]').forEach((el) => el.classList.add('hidden'));
        });
    }

    if (sharedDeferredPrompt) {
        chromeHint?.classList.remove('hidden');
        safariHint?.classList.add('hidden');
    } else if (isIos() || isMacSafari()) {
        safariHint?.classList.remove('hidden');
        chromeHint?.classList.add('hidden');
    } else {
        chromeHint?.classList.remove('hidden');
        safariHint?.classList.add('hidden');
    }

    btnChrome?.addEventListener('click', async () => {
        if (!sharedDeferredPrompt) {
            return;
        }
        sharedDeferredPrompt.prompt();
        await sharedDeferredPrompt.userChoice;
        sharedDeferredPrompt = null;
        persistDismiss();
        root.remove();
    });

    btnClose?.addEventListener('click', () => {
        persistDismiss();
        root.remove();
    });
}
