'use client'

// PBI-74 / T-863: useWorkspaceResync hook.
//
// Trigger resyncActiveScopes bij:
// - hidden→visible (browser-throttled events kunnen gemist zijn)
// - online (netwerk hersteld na disconnect)
//
// Hoort gemount te worden naast useBacklogRealtime in BacklogHydrationWrapper.

import { useEffect } from 'react'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'

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

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

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

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

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