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

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

export default function InstallPrompt() {
    const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);

    useEffect(() => {
        const handler = (e: Event) => {
            e.preventDefault();
            setDeferredPrompt(e as BeforeInstallPromptEvent);
        };
        window.addEventListener('beforeinstallprompt', handler);
        return () => window.removeEventListener('beforeinstallprompt', handler);
    }, []);

    const handleInstall = async () => {
        if (!deferredPrompt) return;
        deferredPrompt.prompt();
        const result = await deferredPrompt.userChoice;
        if (result.outcome === 'accepted') {
            setDeferredPrompt(null);
        }
    };

    if (!deferredPrompt) return null;

    return (
        <div className="fixed bottom-24 left-4 right-4 max-w-sm mx-auto z-50 animate-[slideUp_0.3s_ease-out]">
            <div className="bg-white/90 dark:bg-gray-800/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-4 flex items-center gap-3">
                <img src="/icons/icon-96x96.png" alt="App" className="w-10 h-10 rounded-xl shadow-sm" />
                <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-800 dark:text-gray-200">Install ExpenseTracker</p>
                    <p className="text-xs text-gray-400 truncate">Add to home screen for quick access</p>
                </div>
                <button onClick={handleInstall} className="bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium px-4 py-2 rounded-xl whitespace-nowrap transition-all active:scale-95 shadow-sm">
                    Install
                </button>
                <button onClick={() => setDeferredPrompt(null)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-lg p-1">✕</button>
            </div>
        </div>
    );
}
