import { useRouter } from 'expo-router'
import { useCallback } from 'react'
import { type BackIntent, canonicalBack } from '../intents'
import { MenuIconButton } from '../MenuBar'
import type { IconName } from '../types'

// renderBack — canonical back intent. Icon morphs between arrow-left / x for
// dismiss mode. Routes through the shared canonicalBack helper so every
// screen gets the same dismiss-then-back-then-fallback semantics.

const FALLBACK_HREF = '/(auth)/(tabs)/home' as const

export function RenderBack({
  intent,
  reduceMotion,
  size,
  tint,
}: {
  intent: BackIntent
  reduceMotion?: boolean
  size?: number
  tint?: string
}) {
  const router = useRouter()

  const onPress = useCallback(() => {
    canonicalBack(intent, {
      canGoBack: () => router.canGoBack(),
      canDismiss: () => router.canDismiss(),
      back: () => router.back(),
      dismiss: () => router.dismiss(),
      replace: (href) => router.replace(href),
      fallbackHref: FALLBACK_HREF,
    })
  }, [intent, router])

  const icon: IconName = intent.dismissMode === 'close' ? 'x' : 'arrow-left'
  const label =
    intent.accessibilityLabel ?? (intent.dismissMode === 'close' ? 'Close' : 'Back')

  return (
    <MenuIconButton
      icon={icon}
      onPress={onPress}
      accessibilityLabel={label}
      accessibilityHint={intent.accessibilityHint}
      reduceMotion={reduceMotion}
      size={size}
      tint={tint}
    />
  )
}
