// useOfflineSync Hook - Lógica de sincronização offline
// Gerencia dados pendentes no localStorage

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

export const useOfflineSync = () => {
  const [pending, setPending] = useState([]);
  const [syncing, setSyncing] = useState(false);
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  const savePending = useCallback((type, data) => {
    const item = {
      id: Date.now().toString(),
      type,
      data,
      timestamp: new Date().toISOString()
    };
    
    const current = JSON.parse(localStorage.getItem('pending_sync') || '[]');
    current.push(item);
    localStorage.setItem('pending_sync', JSON.stringify(current));
    
    setPending(current);
    return item.id;
  }, []);

  const getPending = useCallback(() => {
    const items = JSON.parse(localStorage.getItem('pending_sync') || '[]');
    setPending(items);
    return items;
  }, []);

  const syncPending = useCallback(async () => {
    const items = getPending();
    if (items.length === 0) return { success: true, synced: 0 };

    setSyncing(true);
    
    try {
      // Aqui será a chamada real à API
      // Por enquanto, apenas simula sucesso
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      localStorage.setItem('pending_sync', '[]');
      setPending([]);
      
      return { success: true, synced: items.length };
    } catch (err) {
      console.error('Erro na sincronização:', err);
      throw new Error(`Erro na sincronização: ${err.message}`);
    } finally {
      setSyncing(false);
    }
  }, [getPending]);

  const clearPending = useCallback((id) => {
    const current = getPending();
    const filtered = id 
      ? current.filter(item => item.id !== id)
      : [];
    
    localStorage.setItem('pending_sync', JSON.stringify(filtered));
    setPending(filtered);
  }, [getPending]);

  useEffect(() => {
    getPending();
    
    // Listeners de status de rede
    const handleOnline = () => {
      setIsOnline(true);
      if (pending.length > 0) {
        syncPending();
      }
    };
    
    const handleOffline = () => {
      setIsOnline(false);
    };
    
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, [getPending, syncPending, pending.length]);

  return {
    pending,
    syncing,
    isOnline,
    savePending,
    syncPending,
    getPending,
    clearPending
  };
};
