/**
 * Offline Sync Provider
 * 
 * This component integrates the useOfflineSync hook into the application.
 * It monitors network status and automatically syncs offline operations
 * when the connection is restored.
 * 
 * This is a client component that wraps the application to provide
 * offline sync functionality globally.
 * 
 * Requirements: REQ-5.5.3, REQ-5.5.4
 */

'use client';

import React, { useEffect, useMemo } from 'react';
import { useOfflineSync } from '@/lib/hooks/useOfflineSync';
import { ConflictResolver } from '@/components/canvas/ConflictResolver';
import { logger } from '@/lib/utils/logger';

interface OfflineSyncProviderProps {
  children: React.ReactNode;
}

/**
 * Offline Sync Provider Component
 * 
 * Integrates offline sync functionality into the application.
 * This component should be placed in the root layout to enable
 * automatic synchronization throughout the app.
 * 
 * Features:
 * - Monitors network status
 * - Automatically syncs when online
 * - Logs sync events for debugging
 * - Handles sync errors gracefully
 * 
 * @example
 * ```tsx
 * // In app/layout.tsx
 * export default function RootLayout({ children }) {
 *   return (
 *     <html>
 *       <body>
 *         <OfflineSyncProvider>
 *           {children}
 *         </OfflineSyncProvider>
 *       </body>
 *     </html>
 *   );
 * }
 * ```
 */
export function OfflineSyncProvider({ children }: OfflineSyncProviderProps) {
  const log = useMemo(() => logger.namespace('OfflineSyncProvider'), []);

  const {
    isOnline,
    isSyncing,
    syncStatus,
    queueSize,
    syncError,
    currentConflict,
    resolveConflict,
  } = useOfflineSync({
    autoSync: true,
    syncDelay: 1000,
    onSyncStart: () => {
      log.log('Sync started');
    },
    onSyncSuccess: () => {
      log.log('Sync completed successfully');
    },
    onSyncError: (error) => {
      log.error('Sync failed:', error);
    },
  });

  // Log network status changes
  useEffect(() => {
    log.log(`Network status: ${isOnline ? 'online' : 'offline'}`);
  }, [isOnline, log]);

  // Log sync status changes
  useEffect(() => {
    if (isSyncing) {
      log.log(`Syncing ${queueSize} operations...`);
    }
  }, [isSyncing, queueSize, log]);

  // Log sync errors
  useEffect(() => {
    if (syncError) {
      log.error(`Sync error: ${syncError}`);
    }
  }, [syncError, log]);

  // Log sync status changes
  useEffect(() => {
    if (syncStatus === 'success') {
      log.log('All operations synced successfully');
    }
  }, [syncStatus, log]);

  // The provider doesn't render any UI, it just provides the sync functionality
  // UI components like OfflineIndicator can be added separately where needed
  // However, we do render the ConflictResolver when a conflict is detected
  return (
    <>
      {children}
      
      {/* Conflict Resolver Dialog */}
      <ConflictResolver
        conflict={currentConflict}
        open={!!currentConflict}
        onClose={() => {
          // User cancelled - resolve with server version
          if (currentConflict) {
            resolveConflict({ choice: 'server' });
          }
        }}
        onResolve={(conflictId, choice, mergedData) => {
          resolveConflict({ choice, mergedData });
        }}
      />
    </>
  );
}
