import { useEffect, useState } from 'react'
import { useFeature } from 'src/lib/features'
import { AccountStore } from 'src/state/accountStore'
import { accountKeys, accountsStorage, appKeys, appStorage } from 'src/state/storage'

// Truth = RSVP is usable on the current instance.
//
// Two signals:
//   - `event_rsvp_bridge` feature flag from nodeinfo (authoritative when
//     the server answers the handshake)
//   - `app.rsvpMissing.<instance>` local escape hatch, flipped by
//     `useRsvpMutation.onError` when the RSVP endpoint 404s. Covers the
//     "nodeinfo claims the flag is on but the endpoint isn't wired" case.
export function useEventRsvpAvailable(): boolean {
  const flag = useFeature('event_rsvp_bridge')

  const readMissing = (): boolean => {
    const instance = AccountStore.activeAccount()?.instance
    if (!instance) return false
    return appStorage.getBoolean(appKeys.rsvpMissing(instance)) === true
  }

  const [missing, setMissing] = useState<boolean>(readMissing)

  useEffect(() => {
    const rsvpListener = appStorage.addOnValueChangedListener((changed) => {
      const instance = AccountStore.activeAccount()?.instance
      const watchKey = instance ? appKeys.rsvpMissing(instance) : null
      if (changed === watchKey) setMissing(readMissing())
    })
    // Switching accounts can swap which instance's escape-hatch we honour.
    const accountListener = accountsStorage.addOnValueChangedListener((changed) => {
      if (changed === accountKeys.activeId || changed === accountKeys.list) {
        setMissing(readMissing())
      }
    })
    return () => {
      rsvpListener.remove()
      accountListener.remove()
    }
  }, [])

  if (missing) return false
  // `useFeature` is strict-boolean: returns false when nodeinfo hasn't
  // advertised the flag. We honour that (the flag is the primary gate)
  // and let the 404 escape hatch above cover the "nodeinfo says yes but
  // endpoint isn't wired" edge case.
  return flag
}
