<script setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import { useClipboard, useShare, useWindowSize } from '@vueuse/core'
import { useRouter } from 'vue-router'
import { useMotion } from '@vueuse/motion'
import html2canvas from 'html2canvas'

import { usePhotoboothStore } from '../stores/photoboothStore'
import { DEFAULT_STRIP_THEME_ID, STRIP_THEME_MAP } from '../data/stripThemes'
import PhotoStrip from '../components/PhotoStrip.vue'

const store = usePhotoboothStore()
const router = useRouter()
const stripRef = ref(null)
const wrapperRef = ref(null)
const isExporting = ref(false)
const stripDataUrl = ref('')
const stripSize = computed(() => {
  const theme = STRIP_THEME_MAP[store.stripTheme] || STRIP_THEME_MAP[DEFAULT_STRIP_THEME_ID]
  return theme.size
})

const { width } = useWindowSize()
const { share, isSupported: shareSupported } = useShare()
const { copy, copied } = useClipboard()

const stripScale = computed(() => {
  if (isExporting.value) return 1
  return Math.min(1, Math.max(0.45, (width.value - 48) / stripSize.value.width))
})

useMotion(wrapperRef, {
  initial: { opacity: 0, y: 40, scale: 0.96 },
  enter: { opacity: 1, y: 0, scale: 1, transition: { type: 'spring', stiffness: 140 } },
})

onMounted(() => {
  store.setStep(3)
})

async function renderStrip() {
  if (!stripRef.value) return ''

  isExporting.value = true

  await nextTick()

  try {
    const canvas = await html2canvas(stripRef.value, {
      backgroundColor: null,
      useCORS: true,
      allowTaint: true,
      scale: 2,
      width: stripSize.value.width,
      height: stripSize.value.height,
    })

    const dataUrl = canvas.toDataURL('image/png')
    stripDataUrl.value = dataUrl
    return dataUrl
  } finally {
    isExporting.value = false
  }
}

async function handleShare() {
  const dataUrl = stripDataUrl.value || (await renderStrip())
  if (!dataUrl || !shareSupported.value) return

  await share({
    title: 'Photobooth strip',
    text: 'Made with Luna Photobooth',
    url: dataUrl,
  })
}

async function handleCopy() {
  const dataUrl = stripDataUrl.value || (await renderStrip())
  if (!dataUrl) return
  await copy(dataUrl)
}

async function handleDownload() {
  const dataUrl = stripDataUrl.value || (await renderStrip())
  if (!dataUrl) return

  const link = document.createElement('a')
  link.href = dataUrl
  link.download = 'photobooth-strip.png'
  document.body.appendChild(link)
  link.click()
  link.remove()
}

function startOver() {
  store.resetSession()
  router.push('/')
}
</script>

<template>
  <main class="result">
    <section class="strip-panel">
      <div ref="wrapperRef" class="strip-wrapper" :style="{ transform: `scale(${stripScale})` }">
        <div ref="stripRef">
          <PhotoStrip :photos="store.photos" :theme="store.stripTheme" />
        </div>
      </div>
    </section>

    <section class="action-panel">
      <h1>Your strip is ready</h1>
      <p>Download, share, or copy your finished photobooth strip.</p>
      <div class="actions">
        <button class="primary" :disabled="isExporting" @click="handleDownload">
          Download strip
        </button>
        <button class="ghost-button" :disabled="!shareSupported" @click="handleShare">Share</button>
        <button class="ghost-button" @click="handleCopy">
          {{ copied ? 'Copied!' : 'Copy to clipboard' }}
        </button>
        <button class="ghost-button" @click="startOver">Start over</button>
      </div>
    </section>
  </main>
</template>

<style scoped>
.result {
  display: grid;
  grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
  gap: 28px;
  align-items: start;
}

.strip-panel {
  padding: 28px;
  border-radius: 32px;
  background: rgba(255, 255, 255, 0.85);
  box-shadow: var(--soft-shadow);
  display: flex;
  justify-content: center;
}

.strip-wrapper {
  transform-origin: top center;
}

.action-panel {
  padding: 28px;
  border-radius: 32px;
  background: rgba(255, 255, 255, 0.85);
  box-shadow: var(--soft-shadow);
  display: grid;
  gap: 16px;
}

.action-panel h1 {
  margin: 0;
}

.action-panel p {
  margin: 0;
  color: var(--muted);
}

.actions {
  display: grid;
  gap: 12px;
}

.primary {
  border: none;
  border-radius: 999px;
  padding: 12px 20px;
  background: #c85a7c;
  color: #fff;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 16px 30px rgba(200, 90, 124, 0.3);
}

.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.ghost-button {
  border: 1px solid rgba(200, 90, 124, 0.3);
  background: rgba(255, 255, 255, 0.85);
  color: #7c3b54;
  padding: 10px 16px;
  border-radius: 999px;
  cursor: pointer;
  font-weight: 600;
}

@media (max-width: 900px) {
  .result {
    grid-template-columns: 1fr;
  }
}
</style>
