'use client'

// PBI-74 / Story 9 / T-880: useSprintWorkspaceResync.
//
// Trigger resyncActiveScopes bij:
// - hidden→visible (browser-throttled events kunnen gemist zijn)
// - online (netwerk hersteld na disconnect)
//
// Hoort gemount te worden naast useSprintRealtime in SprintHydrationWrapper.

import { useEffect } from 'react'
import { useSprintWorkspaceStore } from '@/stores/sprint-workspace/store'

export function useSprintWorkspaceResync(): void {
  useEffect(() => {
    if (typeof document === 'undefined') return

    const onVisibility = () => {
      if (document.visibilityState === 'visible') {
        void useSprintWorkspaceStore.getState().resyncActiveScopes('visible')
      }
    }

    const onOnline = () => {
      void useSprintWorkspaceStore.getState().resyncActiveScopes('reconnect')
    }

    document.addEventListener('visibilitychange', onVisibility)
    window.addEventListener('online', onOnline)

    return () => {
      document.removeEventListener('visibilitychange', onVisibility)
      window.removeEventListener('online', onOnline)
    }
  }, [])
}
