'use client';

import React, { useState, useEffect } from 'react';
import { WifiOff, ShieldCheck, Loader2 } from 'lucide-react';

export default function OfflineIndicator() {
    const [isOffline, setIsOffline] = useState(false);
    const [isReady, setIsReady] = useState(false);
    const [progress, setProgress] = useState(0);

    useEffect(() => {
        setIsOffline(!navigator.onLine);

        // 🧼 Clean up legacy keys and check for ready state
        const checkLocalReady = () => {
            const ready = localStorage.getItem('whisky_offline_ready') === 'true' ||
                localStorage.getItem('whisky_bunker_ready') === 'true';
            if (ready) {
                setIsReady(true);
                // Standardize on the new key
                localStorage.setItem('whisky_offline_ready', 'true');
            }
        };
        checkLocalReady();

        const handleOnline = () => setIsOffline(false);
        const handleOffline = () => setIsOffline(true);

        const handleMessage = (event: MessageEvent) => {
            if (event.data?.type === 'OFFLINE_PROGRESS') {
                setProgress(event.data.progress);
            }
            if (event.data?.type === 'OFFLINE_READY' || event.data?.type === 'OFFLINE_STATUS_RESPONSE') {
                if (event.data?.type === 'OFFLINE_STATUS_RESPONSE') {
                    setProgress(event.data.progress || 0);
                    if (event.data.isReady) {
                        setIsReady(true);
                        localStorage.setItem('whisky_offline_ready', 'true');
                    }
                } else {
                    setIsReady(true);
                    localStorage.setItem('whisky_offline_ready', 'true');
                }
            }
        };

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);

        const queryStatus = async () => {
            if (!('serviceWorker' in navigator)) return;

            try {
                const registration = await navigator.serviceWorker.getRegistration();
                if (registration) {
                    // Try to talk to ANY available worker (installing, waiting, or active)
                    const sw = registration.installing || registration.waiting || registration.active;
                    if (sw) {
                        sw.postMessage({ type: 'CHECK_OFFLINE_STATUS' });
                    }
                }
            } catch (e) {
                console.error('PWA: Status query failed', e);
            }
        };

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.addEventListener('message', handleMessage);
            queryStatus();

            // 🔄 ROBUST POLLING: If not ready and progress is 0, query periodically
            // This handles cases where the SW was suspended or the first broadcast was missed.
            const interval = setInterval(() => {
                if (!isReady && progress < 100) {
                    queryStatus();
                }
            }, 3000);

            return () => {
                window.removeEventListener('online', handleOnline);
                window.removeEventListener('offline', handleOffline);
                navigator.serviceWorker.removeEventListener('message', handleMessage);
                clearInterval(interval);
            };
        }

        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, [isReady, progress]);

    if (isOffline) {
        return (
            <div className="flex items-center gap-1.5 px-2.5 py-1 bg-red-600/10 border border-red-600/20 rounded-full animate-pulse">
                <WifiOff size={10} className="text-red-600" />
                <span className="text-[9px] font-black uppercase tracking-widest text-red-600">Offline</span>
            </div>
        );
    }

    if (isReady) {
        return (
            <div className="flex items-center gap-1.5 px-2.5 py-1 bg-green-600/10 border border-green-600/20 rounded-full group cursor-help relative animate-in fade-in zoom-in duration-500">
                <ShieldCheck size={10} className="text-green-600" />
                <span className="text-[9px] font-bold uppercase tracking-widest text-green-600">Offline-Modus aktiv</span>
                <div className="absolute top-full left-1/2 -translate-x-1/2 mt-2 w-48 p-2 bg-zinc-900 text-[10px] text-zinc-400 rounded-xl border border-zinc-800 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50 shadow-2xl text-center">
                    Alle Funktionen sind vollständig offline verfügbar.
                </div>
            </div>
        );
    }

    return (
        <div className="flex items-center gap-1.5 px-2.5 py-1 bg-orange-600/10 border border-orange-600/20 rounded-full animate-in fade-in slide-in-from-right-2">
            <Loader2 size={10} className="text-orange-600 animate-spin" />
            <span className="text-[9px] font-bold uppercase tracking-widest text-orange-600">
                {progress > 0 ? `Vorbereitung... ${progress}%` : 'Warte auf System...'}
            </span>
        </div>
    );
}
