import { useEffect } from 'react';
import { Cloud, CloudOff, RefreshCw, WifiOff } from 'lucide-react';
import { cloudUsername } from '@/lib/cloud/client';
import { useConnectivityStore } from '@/stores/connectivityStore';
import { cn } from '@/lib/cn';

/**
 * Compact shell indicator for connectivity + cloud sync. Shows "Offline" when
 * the browser is offline, otherwise the autosave state (saving / saved / failed)
 * while signed into the cloud. Renders nothing when online and not using cloud,
 * to keep the bar quiet. Also owns the online/offline event wiring.
 */
export function SyncStatusIndicator() {
  const online = useConnectivityStore((s) => s.online);
  const cloudSync = useConnectivityStore((s) => s.cloudSync);
  const setOnline = useConnectivityStore((s) => s.setOnline);
  const signedIn = !!cloudUsername();

  useEffect(() => {
    const on = () => setOnline(true);
    const off = () => setOnline(false);
    window.addEventListener('online', on);
    window.addEventListener('offline', off);
    setOnline(navigator.onLine);
    return () => { window.removeEventListener('online', on); window.removeEventListener('offline', off); };
  }, [setOnline]);

  if (!online) {
    return (
      <span className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-warning" title="You're offline — changes are saved locally and will sync when you reconnect." role="status">
        <WifiOff size={14} aria-hidden /> <span className="hidden sm:inline">Offline</span>
      </span>
    );
  }

  if (!signedIn) return null;

  const map = {
    idle: null,
    saving: { Icon: RefreshCw, text: 'Saving…', cls: 'text-muted', spin: true, title: 'Saving your campaign to the cloud…' },
    saved: { Icon: Cloud, text: 'Saved', cls: 'text-success', spin: false, title: 'Your campaign is backed up to the cloud.' },
    error: { Icon: CloudOff, text: 'Sync failed', cls: 'text-danger', spin: false, title: 'Cloud sync failed — your data is safe locally and will retry on the next change.' },
  } as const;
  const s = map[cloudSync];
  if (!s) return null;

  return (
    <span className={cn('flex items-center gap-1 rounded-md px-2 py-1 text-xs', s.cls)} title={s.title} role="status" aria-live="polite">
      <s.Icon size={14} aria-hidden className={s.spin ? 'animate-spin' : undefined} />
      <span className="hidden sm:inline">{s.text}</span>
    </span>
  );
}
