import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { initDB } from './lib/db';
import { syncEngine } from './lib/sync';
import { useOfflineQueue } from './lib/offlineQueue';
import { ToastProvider } from './components/Toast';
import { ConfirmationProvider } from './hooks/useConfirmation';
import './store/pwa'; // Initialize PWA installation listeners

// Initialize Offline Capabilities
initDB().then(() => {
  console.log('📦 Local Database Ready');
  // Hydrate the offline queue Zustand slice from localStorage so the
  // sidebar indicator shows the right count on app boot, even if a write
  // was queued in a previous session.
  useOfflineQueue.getState().hydrate();
  syncEngine.start();
}).catch(err => {
  console.error('Failed to initialize offline database', err);
});

// B.5 — flush the offline POST/PUT/DELETE queue when the browser reports
// the network is back. The queue replays each entry in FIFO order against
// the real /api/* server; 4xx entries are dropped, 5xx / network errors
// are kept for the next flush.
window.addEventListener('online', () => {
  console.log('🌐 Network back — flushing offline queue');
  useOfflineQueue
    .getState()
    .flush()
    .catch((err) => console.warn('Offline queue flush failed', err));
});

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <ToastProvider>
      <ConfirmationProvider>
        <App />
      </ConfirmationProvider>
    </ToastProvider>
  </React.StrictMode>,
);