'use client'

import { createContext, useEffect, type ReactNode } from 'react'
import { useSyncExternalStore } from 'react'

export const DeviceIdContext = createContext<undefined>(undefined)

const LOCAL_STORAGE_KEY = 'deviceId'

const getSnapshot = () => {
  const storedDeviceId = localStorage.getItem(LOCAL_STORAGE_KEY)
  return storedDeviceId ? storedDeviceId : undefined
}

const subscribe = (callback: () => void) => {
  const handleStorageChange = (event: StorageEvent) => {
    if (event.key === LOCAL_STORAGE_KEY) callback()
  }
  window.addEventListener('storage', handleStorageChange)
  return () => window.removeEventListener('storage', handleStorageChange)
}

export function useDeviceId() {
  const deviceId = useSyncExternalStore(subscribe, () =>
    getSnapshot(),
    () => undefined
  )

  const setDeviceId = (deviceId: string) => {
    localStorage.setItem(LOCAL_STORAGE_KEY, deviceId)
    window.dispatchEvent(
      new StorageEvent('storage', { key: LOCAL_STORAGE_KEY })
    )
  }

  return { deviceId, setDeviceId }
}

export const DeviceIdProdvider = ({ children }: { children: ReactNode }) => {
  const { setDeviceId } = useDeviceId()

  useEffect(() => {
    const device_id = (new URLSearchParams(location.search)).get('device_id')
    if (device_id) {
      setDeviceId(device_id)
    }
  }, [setDeviceId])

  return (
    <DeviceIdContext.Provider value={undefined}>
      {children}
    </DeviceIdContext.Provider>
  )
}
