<template>
  <div class="h-dvh flex flex-col" :class="currentTheme" :style="rootStyle">
    <RouterView />
    <ArticleOverlay />
    <PlayerBar v-if="!isMobile" />
    <PassphraseDialog
      :visible="showPassphrase"
      :is-creating="isCreatingPassphrase"
      @submit="handlePassphraseSubmit"
      @skip="showPassphrase = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { RouterView } from 'vue-router'
import { useTheme } from '@/composables/useTheme'
import { useArchy } from '@/composables/useArchy'
import { useVisualViewport } from '@/composables/useVisualViewport'
import ArticleOverlay from '@/components/content/ArticleOverlay.vue'
import PlayerBar from '@/components/player/PlayerBar.vue'
import PassphraseDialog from '@/components/ui/PassphraseDialog.vue'
import {
  isCryptoEnabled,
  deriveKey,
  generateSalt,
  setSessionKey,
} from '@/utils/crypto'

const { currentTheme, initTheme } = useTheme()
const archy = useArchy()

const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value < 1024)
const { viewportHeight, isKeyboardOpen } = useVisualViewport()
function onResize() { windowWidth.value = window.innerWidth }

// On mobile, bind height to visualViewport.height so the container
// actually shrinks when the keyboard opens (dvh doesn't do this reliably)
const rootStyle = computed(() => {
  if (isMobile.value && isKeyboardOpen.value) {
    return { height: `${viewportHeight.value}px`, overflow: 'hidden' }
  }
  return {}
})

const showPassphrase = ref(false)
const isCreatingPassphrase = ref(false)

const SALT_KEY = 'aiui-crypto-salt'

async function handlePassphraseSubmit(passphrase: string) {
  let saltHex = localStorage.getItem(SALT_KEY)
  let salt: Uint8Array

  if (saltHex) {
    salt = new Uint8Array(saltHex.match(/.{2}/g)!.map(b => parseInt(b, 16)))
  } else {
    salt = await generateSalt()
    saltHex = Array.from(salt).map(b => b.toString(16).padStart(2, '0')).join('')
    localStorage.setItem(SALT_KEY, saltHex)
  }

  const key = await deriveKey(passphrase, salt)
  setSessionKey(key, salt)
  showPassphrase.value = false
}

onMounted(() => {
  initTheme()
  window.addEventListener('resize', onResize)

  // Initialize Archy bridge when running embedded in Archipelago
  archy.init()

  // Skip encryption prompt when embedded in Archy — Archy handles auth
  if (isCryptoEnabled() && !archy.isEmbedded.value) {
    const hasSalt = !!localStorage.getItem(SALT_KEY)
    isCreatingPassphrase.value = !hasSalt
    showPassphrase.value = true
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', onResize)
  archy.destroy()
})
</script>
