"use client";

import { useState, useEffect } from 'react';
import { Capacitor } from '@capacitor/core';
import { Network } from '@capacitor/network';
import { WifiOff } from 'lucide-react';
import { useSettings } from '@/contexts/settings-context';
import { cn } from '@/lib/utils';

export const NetworkStatusIndicator = () => {
    const { t } = useSettings();
    const [isOnline, setIsOnline] = useState(true);

    useEffect(() => {
        const handleStatusChange = (status: { connected: boolean }) => {
            setIsOnline(status.connected);
        };

        if (Capacitor.getPlatform() !== 'web') {
            Network.getStatus().then(handleStatusChange);
            const listener = Network.addListener('networkStatusChange', handleStatusChange);
            return () => {
                listener.remove();
            };
        } else {
            const updateOnlineStatus = () => setIsOnline(navigator.onLine);
            window.addEventListener('online', updateOnlineStatus);
            window.addEventListener('offline', updateOnlineStatus);
            updateOnlineStatus(); // initial check
            return () => {
                window.removeEventListener('online', updateOnlineStatus);
                window.removeEventListener('offline', updateOnlineStatus);
            };
        }
    }, []);

    if (isOnline) {
        return null;
    }

    return (
        <div className="fixed top-0 left-0 right-0 bg-destructive text-destructive-foreground p-2 text-center text-sm z-[200] flex items-center justify-center gap-2 animate-in fade-in">
            <WifiOff className="h-4 w-4" />
            <span>{t('youAreOffline', { defaultValue: "You are currently offline. Some features may be unavailable." })}</span>
        </div>
    );
};
