import { useCallback, useEffect, useState } from 'react';

/** Événement natif du navigateur pour l’installation PWA (raccourci bureau / écran d’accueil). */
interface BeforeInstallPromptEvent extends Event {
    prompt(): Promise<void>;
    userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
}

declare global {
    interface WindowEventMap {
        beforeinstallprompt: BeforeInstallPromptEvent;
    }
}

export function usePwaInstall(): {
    canInstall: boolean;
    isInstalled: boolean;
    promptInstall: () => Promise<boolean>;
} {
    const [installEvent, setInstallEvent] = useState<BeforeInstallPromptEvent | null>(null);
    const [isInstalled, setIsInstalled] = useState(false);

    useEffect(() => {
        const isStandalone =
            typeof window !== 'undefined' &&
            (window.matchMedia('(display-mode: standalone)').matches ||
                (window.navigator as WindowNavigator & { standalone?: boolean }).standalone === true);
        if (isStandalone) {
            setIsInstalled(true);
            return;
        }

        const handleBeforeInstall = (e: BeforeInstallPromptEvent) => {
            e.preventDefault();
            setInstallEvent(e);
        };

        const handleAppInstalled = () => {
            setInstallEvent(null);
            setIsInstalled(true);
        };

        window.addEventListener('beforeinstallprompt', handleBeforeInstall);
        window.addEventListener('appinstalled', handleAppInstalled);
        return () => {
            window.removeEventListener('beforeinstallprompt', handleBeforeInstall);
            window.removeEventListener('appinstalled', handleAppInstalled);
        };
    }, []);

    const promptInstall = useCallback(async (): Promise<boolean> => {
        if (!installEvent) return false;
        await installEvent.prompt();
        const { outcome } = await installEvent.userChoice;
        if (outcome === 'accepted') setInstallEvent(null);
        return outcome === 'accepted';
    }, [installEvent]);

    return {
        canInstall: Boolean(installEvent),
        isInstalled,
        promptInstall,
    };
}
