<template>
  <div class="chat-fullscreen">
    <!-- Close button (desktop: top-right pill) -->
    <div class="chat-mode-pill flex">
      <button class="chat-close-btn" :aria-label="t('chat.closeAssistant')" @click="closeChat">
        <svg class="w-4 h-4" aria-hidden="true" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
        <span class="text-xs font-medium">{{ t('chat.close') }}</span>
      </button>
    </div>

    <!-- Loading indicator while checking availability -->
    <Transition name="fade">
      <div v-if="aiuiAvailable === null" class="chat-loading" role="status" aria-live="polite">
        <div class="glass-card p-8 flex flex-col items-center gap-4">
          <div class="chat-loading-spinner" aria-hidden="true" />
          <p class="text-sm text-white/60">{{ t('chat.loadingAssistant') }}</p>
        </div>
      </div>
    </Transition>

    <!-- AIUI iframe — on mobile, leave room for close bar + tab bar at bottom -->
    <iframe
      v-if="aiuiUrl"
      ref="aiuiFrame"
      :src="aiuiUrl"
      :title="t('chat.aiAssistant')"
      class="chat-iframe chat-iframe-mobile"

      allow="microphone"
      style="background: transparent"
    />

    <!-- Fallback when AIUI is not deployed -->
    <div v-else-if="aiuiAvailable === false" class="chat-placeholder">
      <div class="chat-placeholder-inner">
        <div class="chat-placeholder-icon">
          <svg class="w-8 h-8 text-white/40" aria-hidden="true" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
          </svg>
        </div>
        <h2 class="text-2xl font-semibold text-white mb-2">{{ t('chat.aiAssistant') }}</h2>
        <p class="text-white/60 mb-4 leading-relaxed">
          {{ t('chat.notConfigured') }}
        </p>
        <p class="text-xs text-white/30">
          {{ t('chat.deployCta') }}
        </p>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ContextBroker } from '@/services/contextBroker'

const { t } = useI18n()

const router = useRouter()
const aiuiFrame = ref<HTMLIFrameElement | null>(null)
let broker: ContextBroker | null = null

const aiuiAvailable = ref<boolean | null>(null) // null = checking, true/false = result

const aiuiUrl = computed(() => {
  const envUrl = import.meta.env.VITE_AIUI_URL
  if (envUrl) return `${envUrl}?embedded=true&hideClose=true`
  // In production, only return the URL if we've confirmed AIUI files exist
  if (import.meta.env.PROD && aiuiAvailable.value === true) return `/aiui/?embedded=true&hideClose=true&v=${Date.now()}`
  return ''
})

/** Check if AIUI is actually deployed by fetching its index.html */
async function checkAiuiAvailable() {
  if (import.meta.env.VITE_AIUI_URL) {
    aiuiAvailable.value = true
    return
  }
  if (!import.meta.env.PROD) {
    aiuiAvailable.value = false
    return
  }
  try {
    const res = await fetch('/aiui/', { method: 'HEAD' })
    // If we get HTML back (200), AIUI is deployed. If 404/403, it's not.
    aiuiAvailable.value = res.ok
  } catch {
    aiuiAvailable.value = false
  }
}

function closeChat() {
  if (window.history.length > 1) {
    router.back()
  } else {
    router.push('/dashboard')
  }
}

function onAiuiMessage(event: MessageEvent) {
  if (!aiuiUrl.value) return
  // Validate origin — only accept messages from AIUI
  try {
    const expected = new URL(aiuiUrl.value, window.location.origin).origin
    if (event.origin !== expected) return
  } catch { return }
  // Listen for ready messages from AIUI iframe
  if (event.data?.type === 'ready') {
    // AIUI connected - could use for future features
  }
}

onMounted(async () => {
  window.addEventListener('message', onAiuiMessage)
  await checkAiuiAvailable()
  if (aiuiUrl.value) {
    broker = new ContextBroker(aiuiFrame, aiuiUrl.value)
    broker.start()
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('message', onAiuiMessage)
  broker?.stop()
  broker = null
})
</script>

<style scoped>
.chat-loading {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.chat-loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  border-top-color: #fb923c;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

</style>
