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

// True iff the active account's server returns the full Mastodon-parity
// recursive thread tree on `/api/v1/statuses/{id}/context`. Gates UI
// affordances (nested rendering, async-refresh polling) so they don't fire
// against pre-deploy Pixelfed instances or sub-4.5 Mastodon servers.
//
//   - Pixelfed: nodeinfo flag `recursive_thread_context` (default on for
//     Halflight-patched servers, absent on upstream).
//   - Mastodon: always walks the full tree on `/context`; the gate only
//     guards the *async-refresh header awareness*, which is a 4.5+ delta.
export function useRecursiveThreadContext(): boolean {
  const pixelfedFlag = useFeature('recursive_thread_context')
  const caps = useInstanceCapabilities()

  const readType = () => AccountStore.activeAccount()?.type ?? null
  const [type, setType] = useState<ReturnType<typeof readType>>(readType)

  useEffect(() => {
    const accountListener = accountsStorage.addOnValueChangedListener((changed) => {
      if (changed === accountKeys.activeId || changed === accountKeys.list) {
        setType(readType())
      }
    })
    return () => {
      accountListener.remove()
    }
  }, [])

  if (type === 'mastodon') {
    return (
      caps.apiVersionsMastodon !== null &&
      caps.apiVersionsMastodon >= MASTODON_API_VERSION_AT_4_5_0
    )
  }
  return pixelfedFlag
}
