import {Stack, useRouter} from 'expo-router'

import {AuthGate} from '@/components/auth-gate'
import {HeaderIconButton} from '@/components/ui/header-icon-button'
import {stackScreenOptions} from '@/components/ui/layout'

export default function ModalLayout() {
  return (
    <AuthGate>
      <Stack
        screenOptions={({navigation, route}) => {
          const isRoot =
            navigation.getState().routes[0]?.key === route.key
          return {
            ...stackScreenOptions,
            headerShown: true,
            headerLeft: isRoot ? CloseButton : undefined,
          }
        }}
      />
    </AuthGate>
  )
}

function CloseButton() {
  const router = useRouter()
  return (
    <HeaderIconButton
      icon="xmark"
      label="Close"
      onPress={() => router.dismissAll()}
    />
  )
}
