<script setup lang="ts">
import { Browser } from '@capacitor/browser'

const { t } = useI18n()
const { signInSocial } = useAuth()
const localePath = useLocalePath()
const log = useLogger('OAuth')

defineProps<{
  availableProviders: readonly string[]
  isRegisterPage?: boolean
}>()

// Provider configuration for display (reactive so per-provider loading updates are tracked)
type ProviderEntry = { name: string, icon: string, color: 'neutral' | 'primary' | 'error', loading: boolean }
const providerConfig = reactive<Record<string, ProviderEntry>>({
  github: {
    name: t('auth.github'),
    icon: 'i-simple-icons-github',
    color: 'neutral',
    loading: false
  },
  google: {
    name: t('auth.google'),
    icon: 'i-simple-icons-google',
    color: 'error',
    loading: false
  }
})

const getProviderConfig = (providerId: string) => {
  if (!providerConfig[providerId]) {
    providerConfig[providerId] = {
      name: providerId.charAt(0).toUpperCase() + providerId.slice(1),
      icon: useSolarIcon('link'),
      color: 'neutral',
      loading: false
    }
  }
  return providerConfig[providerId]
}

const emit = defineEmits<{
  (e: 'sign-in'): boolean
}>()
const loading = ref(false)

async function signIn(provider: string) {
  getProviderConfig(provider).loading = true
  loading.value = true
  emit('sign-in')

  const apiBaseUrl = useApiBaseUrl()
  const isCapacitorApp = apiBaseUrl !== null && apiBaseUrl !== undefined && apiBaseUrl !== ''

  if (isCapacitorApp) {
    // Capacitor: Start OAuth in system browser via a helper page on Vercel
    const startUrl = `${useApiBaseUrl()}/auth/start-social?provider=${encodeURIComponent(provider)}`
    await Browser.open({ url: startUrl, windowName: '_blank' })
    // The flow will return to the app via App Link -> callback -> token handoff
  } else {
    // Web browser: Use standard Better Auth OAuth flow
    signInSocial({ provider, callbackURL: localePath('/dashboard') })
  }
}

// Clean up listeners when component unmounts
onUnmounted(() => {
  log.debug('Component unmounting, listeners will be cleaned up')
})
</script>

<template>
  <div>
    <UButton
      v-for="provider in availableProviders"
      :key="provider"
      :loading="getProviderConfig(provider).loading"
      :icon="getProviderConfig(provider).icon"
      :color="getProviderConfig(provider).color"
      variant="subtle"
      block
      class="cursor-pointer mb-3"
      :class="{ 'z-40 relative active': getProviderConfig(provider).loading }"
      @click="signIn(provider)"
    >
      {{ isRegisterPage ? t('auth.signUpWith') : t('auth.authenticateWith') }} {{ getProviderConfig(provider).name }}
    </UButton>
  </div>
</template>
