import { useSyncExternalStore } from 'react'
import { Dimensions } from 'react-native'

// A single Dimensions listener shared by every caller. Each useWindowDimensions
// subscription creates its own RN listener and returns a fresh `{ width, height }`
// object on every change; a recycled FeedPost cell tree had three such
// subscriptions per post — ten posts on-screen meant thirty listeners.
//
// Consumers that only need width should read from here. The value updates on
// rotation via React's useSyncExternalStore, so the UI still reflows.

let cachedWidth = Dimensions.get('window').width
const listeners = new Set<() => void>()

Dimensions.addEventListener('change', ({ window }) => {
  if (window.width === cachedWidth) return
  cachedWidth = window.width
  for (const l of listeners) l()
})

const subscribe = (l: () => void) => {
  listeners.add(l)
  return () => {
    listeners.delete(l)
  }
}

const getSnapshot = () => cachedWidth

export function useWindowWidth(): number {
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
}

export function getWindowWidth(): number {
  return cachedWidth
}
