import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { App } from '@/app/App'
import { LocalBudgetRepository } from '@/data/local-repository'
import { connectRepository } from '@/store/budget-store'
import { flushSync, initSync } from '@/store/sync-store'
import './styles/index.css'

const flush = await connectRepository(new LocalBudgetRepository())
const flushAll = () => {
  flush()
  flushSync()
}
window.addEventListener('pagehide', flushAll)
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') flushAll()
})
// Cloud sync (when configured) starts after the local budget is on screen.
initSync().catch((error) => console.error('Starting sync failed', error))

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
