import { useRouter } from 'expo-router'
import { useEffect } from 'react'
import { useIsHalflightServer } from 'src/lib/features'
import { useAuth } from 'src/state/AuthProvider'

// Mastodon Pass Phase 4 §5.3 — guard for Pixelfed-only screens (Stories,
// Collections, Admin, Pixelfed-shaped DMs). Phase 4 hides every entry point
// that leads to these screens when the active account is Mastodon, but a
// deep link, a back-navigation from a now-orphaned screen, or a
// notification tap that pre-dates the active-account flip can still land a
// Mastodon-active session on a Pixelfed-only route. This hook is the
// belt-and-braces fallback: when the active account isn't Pixelfed, redirect
// back to the home tab synchronously.
//
// Used by the screen-level component (not by reusable subcomponents) so the
// redirect fires once per mount and the underlying screen's hooks (queries,
// effects) never run for the wrong account type.
export function useRequirePixelfed(): void {
  const { user, isLoading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (isLoading) return
    if (user && user.type !== 'pixelfed') {
      router.replace('/(auth)/(tabs)/home')
    }
  }, [user, isLoading, router])
}

// Halflight-only variant for screens that depend on the Halflight fork's
// server-side patches (e.g. newsroom mark-as-read CSRF carve-out). Composes
// the Pixelfed check with the nodeinfo `metadata.halflight` beacon — vanilla
// Pixelfed accounts hit the same home-tab fallback as Mastodon ones.
export function useRequireHalflight(): void {
  const { user, isLoading } = useAuth()
  const isHalflight = useIsHalflightServer()
  const router = useRouter()

  useEffect(() => {
    if (isLoading) return
    if (!user) return
    if (user.type !== 'pixelfed' || !isHalflight) {
      router.replace('/(auth)/(tabs)/home')
    }
  }, [user, isLoading, isHalflight, router])
}
