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

// Mastodon Pass Phase 4 §5.3 — guard for Pixelfed-only screens (Stories,
// Collections, Newsroom, 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])
}
