<script setup>
import { computed, nextTick, ref } from 'vue'
import html2canvas from 'html2canvas'
import { STRIP_BASE_SIZE } from '../data/stripThemes'

const props = defineProps({
  targetRef: { type: Object, default: null },
  filename: { type: String, default: 'photobooth-strip.png' },
  width: { type: Number, default: STRIP_BASE_SIZE.width },
  height: { type: Number, default: STRIP_BASE_SIZE.height },
})

const emit = defineEmits(['render-start', 'render-end', 'rendered'])

const isWorking = ref(false)
const errorMessage = ref('')
const isReady = computed(() => Boolean(props.targetRef?.value))

function canvasToBlob(canvas) {
  return new Promise((resolve) => {
    canvas.toBlob((blob) => resolve(blob), 'image/png')
  })
}

async function handleDownload() {
  if (isWorking.value) return
  if (!props.targetRef?.value) {
    errorMessage.value = 'Strip not ready yet. Please try again in a moment.'
    return
  }

  isWorking.value = true
  errorMessage.value = ''
  emit('render-start')

  await nextTick()

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

    const blob = await canvasToBlob(canvas)
    if (blob) {
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = props.filename
      document.body.appendChild(link)
      link.click()
      link.remove()
      URL.revokeObjectURL(url)
      emit('rendered', canvas.toDataURL('image/png'))
      return
    }

    const dataUrl = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.href = dataUrl
    link.download = props.filename
    document.body.appendChild(link)
    link.click()
    link.remove()
    emit('rendered', dataUrl)
  } catch (error) {
    errorMessage.value = error?.message || 'Download failed. Please try again.'
  } finally {
    emit('render-end')
    isWorking.value = false
  }
}
</script>

<template>
  <div class="download-block">
    <button class="download-btn" :disabled="!isReady || isWorking" @click="handleDownload">
      <span v-motion :initial="{ scale: 1 }" :enter="{ scale: 1 }" :hovered="{ scale: 1.05 }">
        Download strip
      </span>
    </button>
    <p v-if="errorMessage" class="download-error">{{ errorMessage }}</p>
  </div>
</template>

<style scoped>
.download-block {
  display: grid;
  gap: 8px;
}

.download-btn {
  border: none;
  border-radius: 999px;
  padding: 12px 24px;
  background: #c85a7c;
  color: #fff;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 16px 30px rgba(200, 90, 124, 0.3);
  transition: transform 0.2s ease;
}

.download-btn:hover {
  transform: translateY(-1px);
}

.download-error {
  margin: 0;
  color: #a13b56;
  font-size: 0.9rem;
}
</style>
