<template>
  <!-- Login Modal -->
  <LoginModal
    :show="showLogin"
    @close="closeAllModals"
    @showSignup="switchToSignup"
    @success="handleAuthSuccess"
  />

  <!-- Signup Modal -->
  <SignupModal
    :show="showSignup"
    @close="closeAllModals"
    @showLogin="switchToLogin"
    @success="handleAuthSuccess"
  />
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import LoginModal from './LoginModal.vue'
import SignupModal from './SignupModal.vue'

interface Props {
  show?: boolean
  initialMode?: 'login' | 'signup'
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  initialMode: 'login',
})

const emit = defineEmits<{
  close: []
  success: []
}>()

// Initialize reactive state
const showLogin = ref(false)
const showSignup = ref(false)

// Define helper functions with explicit function declarations to avoid hoisting issues
function closeAllModals() {
  showLogin.value = false
  showSignup.value = false
  emit('close')
}

function switchToLogin() {
  showSignup.value = false
  showLogin.value = true
}

function switchToSignup() {
  showLogin.value = false
  showSignup.value = true
}

function handleAuthSuccess() {
  closeAllModals()
  emit('success')
}

// Watch for prop changes to show the appropriate modal
watch(
  () => props.show,
  (shouldShow) => {
    if (shouldShow) {
      if (props.initialMode === 'signup') {
        switchToSignup()
      } else {
        switchToLogin()
      }
    } else {
      closeAllModals()
    }
  },
  { immediate: true },
)
</script>
