import { useEffect, useState } from 'react';
import '../../css/notifications.css';

interface BeforeInstallPromptEvent extends Event {
    prompt: () => Promise<void>;
    userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>;
}

type NavigatorWithStandalone = Navigator & { standalone?: boolean };

const isStandalone = (): boolean => (
    typeof window !== 'undefined'
    && (window.matchMedia('(display-mode: standalone)').matches
        || Boolean((window.navigator as NavigatorWithStandalone).standalone))
);

const isIosSafari = (): boolean => {
    if (typeof navigator === 'undefined') return false;

    const userAgent = navigator.userAgent;
    const isIos = /iPad|iPhone|iPod/.test(userAgent)
        || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    const isSafari = /Safari/.test(userAgent) && !/CriOS|FxiOS|EdgiOS|OPiOS/.test(userAgent);

    return isIos && isSafari;
};

export default function PwaInstallPrompt() {
    const [installPrompt, setInstallPrompt] = useState<BeforeInstallPromptEvent | null>(null);
    const [dismissed, setDismissed] = useState(false);
    const [installed, setInstalled] = useState(isStandalone);
    const showIosInstructions = isIosSafari();

    useEffect(() => {
        const handleInstallPrompt = (event: Event) => {
            event.preventDefault();
            setInstallPrompt(event as BeforeInstallPromptEvent);
        };
        const handleInstalled = () => {
            setInstalled(true);
            setInstallPrompt(null);
        };

        window.addEventListener('beforeinstallprompt', handleInstallPrompt);
        window.addEventListener('appinstalled', handleInstalled);

        return () => {
            window.removeEventListener('beforeinstallprompt', handleInstallPrompt);
            window.removeEventListener('appinstalled', handleInstalled);
        };
    }, []);

    if (installed || dismissed || (!installPrompt && !showIosInstructions)) return null;

    const requestInstallation = async () => {
        if (!installPrompt) return;

        await installPrompt.prompt();
        const choice = await installPrompt.userChoice;
        setInstallPrompt(null);

        if (choice.outcome === 'accepted') setInstalled(true);
        else setDismissed(true);
    };

    return (
        <aside className="pwa-install-prompt" aria-labelledby="pwa-install-title">
            <div className="pwa-install-prompt__copy">
                <span className="pwa-install-prompt__eyebrow">Wedster auf deinem Gerät</span>
                <h2 id="pwa-install-title">Schneller zur Hochzeit</h2>
                <p>
                    {showIosInstructions && !installPrompt
                        ? 'Öffne im Browser „Teilen“ und wähle „Zum Home-Bildschirm“.'
                        : 'Installiere Wedster auf deinem Startbildschirm – ganz ohne App-Store.'}
                </p>
            </div>
            <div className="pwa-install-prompt__actions">
                {installPrompt && (
                    <button className="pwa-install-prompt__primary" type="button" onClick={() => void requestInstallation()}>
                        App installieren
                    </button>
                )}
                <button className="pwa-install-prompt__secondary" type="button" onClick={() => setDismissed(true)}>
                    Später
                </button>
            </div>
        </aside>
    );
}
