<template>
  <div id="bg-mount" ref="bgMount"></div>

  <template v-if="!state.photoFrameMode">
    <SingleLayout v-if="state.layout === 'single'" />
    <MultiLayout v-else />
  </template>

  <PhotoFrame />

  <div id="author">绝尘</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { state, loadInitialData } from './composables/useOverlayState'
import SingleLayout from './components/SingleLayout.vue'
import MultiLayout from './components/MultiLayout.vue'
import PhotoFrame from './components/PhotoFrame.vue'
import './overlay.css'

const bgMount = ref<HTMLElement>()

function mountBackground(html: string) {
  const el = bgMount.value
  if (!el) return
  el.innerHTML = html

  // v-html skips <script>; manually execute them
  el.querySelectorAll('script').forEach(old => {
    const ns = document.createElement('script')
    if (old.src) ns.src = old.src
    else ns.textContent = old.textContent
    // copy attributes
    for (const attr of old.attributes) {
      ns.setAttribute(attr.name, attr.value)
    }
    old.parentNode?.replaceChild(ns, old)
  })
}

onMounted(() => {
  loadInitialData()
  if (state.backgroundHtml && state.wallpaperVisible) {
    mountBackground(state.backgroundHtml)
  }
})

watch(() => state.backgroundHtml, (html) => {
  if (state.wallpaperVisible) mountBackground(html)
})

watch(() => state.wallpaperVisible, (visible) => {
  const el = bgMount.value
  if (!el) return
  if (visible && state.backgroundHtml) mountBackground(state.backgroundHtml)
  else el.innerHTML = ''
})
</script>
