<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const photos = ref<string[]>([])
const layout = ref<'1x4' | '2x2'>('1x4')
const frame = ref<number>(0)
const shareUrl = ref('')
const qrCodeUrl = ref('')

onMounted(() => {
  // โหลดข้อมูลจาก localStorage
  const savedPhotos = localStorage.getItem('photobooth-photos')
  const savedLayout = localStorage.getItem('photobooth-layout')
  const savedFrame = localStorage.getItem('photobooth-frame')

  if (savedPhotos) {
    photos.value = JSON.parse(savedPhotos)
  }

  if (savedLayout) {
    layout.value = savedLayout as '1x4' | '2x2'
  }

  if (savedFrame) {
    frame.value = parseInt(savedFrame)
  }

  // สร้าง URL สำหรับแชร์ (ในโปรเจกต์จริงควรอัพโหลดขึ้น cloud)
  generateShareUrl()
})

const getGridStyle = computed(() => {
  if (layout.value === '1x4') {
    return {
      display: 'grid',
      gridTemplateColumns: '1fr',
      gridTemplateRows: 'repeat(4, 1fr)',
      gap: '8px',
      aspectRatio: '1/2' // ทำให้แต่ละภาพยาวขึ้น (1:2 aspect ratio รวม)
    }
  } else {
    return {
      display: 'grid',
      gridTemplateColumns: 'repeat(2, 1fr)',
      gridTemplateRows: 'repeat(2, 1fr)',
      gap: '8px',
      aspectRatio: '1/1' // 2x2 เป็น square
    }
  }
})

const generateShareUrl = () => {
  // ในโปรเจกต์จริง ควรอัพโหลดรูปขึ้น cloud และสร้าง URL
  // ตัวอย่างนี้ใช้ data URL ชั่วคราว
  const photoData = {
    photos: photos.value,
    layout: layout.value,
    frame: frame.value,
    timestamp: Date.now()
  }

  // เข้ารหัสข้อมูลเป็น base64 และสร้าง URL
  const encodedData = btoa(JSON.stringify(photoData))
  shareUrl.value = `${window.location.origin}/share/${encodedData}`

  // สร้าง QR code URL (ใช้ service ภายนอก)
  qrCodeUrl.value = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(shareUrl.value)}`
}

const downloadImage = async () => {
  if (photos.value.length === 0) return

  // สร้าง canvas สำหรับรวมรูป
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')

  if (!context) return

  // ขนาดรูปแต่ละภาพ (720x960 = 3:4)
  const photoWidth = 720
  const photoHeight = 960
  const gap = 20 // ระยะห่างระหว่างรูป

  let canvasWidth, canvasHeight

  if (layout.value === '1x4') {
    // 1x4: 1 คอลัมน์ 4 แถว
    canvasWidth = photoWidth
    canvasHeight = (photoHeight * 4) + (gap * 3)
  } else {
    // 2x2: 2 คอลัมน์ 2 แถว
    canvasWidth = (photoWidth * 2) + gap
    canvasHeight = (photoHeight * 2) + gap
  }

  canvas.width = canvasWidth
  canvas.height = canvasHeight

  // วาด background ตาม frame
  drawFrameBackground(context, canvasWidth, canvasHeight, frame.value)

  // วาดรูปภาพ
  for (let i = 0; i < photos.value.length; i++) {
    const img = new Image()
    img.src = photos.value[i]

    await new Promise((resolve) => {
      img.onload = () => {
        let x, y

        if (layout.value === '1x4') {
          // 1x4 layout
          x = 0
          y = i * (photoHeight + gap)
        } else {
          // 2x2 layout
          const col = i % 2
          const row = Math.floor(i / 2)
          x = col * (photoWidth + gap)
          y = row * (photoHeight + gap)
        }

        // วาดรูปภาพ
        context.drawImage(img, x, y, photoWidth, photoHeight)
        resolve(void 0)
      }
    })
  }

  // สร้าง PNG และ download
  canvas.toBlob((blob) => {
    if (blob) {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `photobooth-${Date.now()}.png`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  }, 'image/png')
}

const drawFrameBackground = (context: CanvasRenderingContext2D, width: number, height: number, frameType: number) => {
  // วาด background ตาม frame type
  switch (frameType) {
    case 0: // Classic - white
      context.fillStyle = '#ffffff'
      break
    case 1: // Modern - gradient
      const gradient1 = context.createLinearGradient(0, 0, width, height)
      gradient1.addColorStop(0, '#667eea')
      gradient1.addColorStop(1, '#764ba2')
      context.fillStyle = gradient1
      break
    case 2: // Vintage - gradient
      const gradient2 = context.createLinearGradient(0, 0, width, height)
      gradient2.addColorStop(0, '#f093fb')
      gradient2.addColorStop(1, '#f5576c')
      context.fillStyle = gradient2
      break
    case 3: // Colorful - gradient
      const gradient3 = context.createLinearGradient(0, 0, width, height)
      gradient3.addColorStop(0, '#4facfe')
      gradient3.addColorStop(1, '#00f2fe')
      context.fillStyle = gradient3
      break
    case 4: // Minimal - light gray
      context.fillStyle = '#f8f9fa'
      break
    default:
      context.fillStyle = '#ffffff'
  }

  context.fillRect(0, 0, width, height)
}

const shareImage = async () => {
  if (navigator.share) {
    try {
      await navigator.share({
        title: 'รูปถ่ายจาก DekThai Photobooth',
        text: 'ดูรูปถ่ายสุดพิเศษที่ฉันสร้าง!',
        url: shareUrl.value
      })
    } catch (error) {
      console.log('Error sharing:', error)
      copyToClipboard()
    }
  } else {
    copyToClipboard()
  }
}

const copyToClipboard = () => {
  navigator.clipboard.writeText(shareUrl.value).then(() => {
    alert('คัดลอกลิงก์แล้ว! สามารถแชร์ให้เพื่อนได้')
  })
}

const startOver = () => {
  // เคลียร์ข้อมูลและกลับไปหน้าแรก
  localStorage.removeItem('photobooth-photos')
  localStorage.removeItem('photobooth-layout')
  localStorage.removeItem('photobooth-frame')
  router.push('/')
}
</script>

<template>
  <div class="pickup-container">
    <header class="header">
      <h1>รูปถ่ายเสร็จแล้ว!</h1>
      <p>ดาวน์โหลดหรือแชร์รูปถ่ายของคุณ</p>
    </header>

    <section class="result-section">
      <div class="photo-result">
        <div class="photo-frame" :class="`frame-${frame}`">
          <div class="photo-grid" :style="getGridStyle">
            <div
              v-for="(photo, index) in photos"
              :key="index"
              class="photo-cell"
            >
              <img :src="photo" :alt="`Photo ${index + 1}`" />
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="actions-section">
      <div class="action-buttons">
        <button @click="downloadImage" class="download-button">
          <span class="button-icon">📥</span>
          ดาวน์โหลด
        </button>

        <button @click="shareImage" class="share-button">
          <span class="button-icon">📤</span>
          แชร์
        </button>
      </div>
    </section>

    <section class="qr-section">
      <h3>สแกน QR Code เพื่อดูรูป</h3>
      <div class="qr-container">
        <img :src="qrCodeUrl" alt="QR Code" class="qr-code" />
        <p class="qr-text">{{ shareUrl }}</p>
        <button @click="copyToClipboard" class="copy-link-button">
          คัดลอกลิงก์
        </button>
      </div>
    </section>

    <section class="footer-section">
      <button @click="startOver" class="start-over-button">
        สร้างรูปใหม่
      </button>
    </section>
  </div>
</template>

<style scoped>
.pickup-container {
  min-height: 100vh;
  padding: 2rem;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
}

.header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 0.5rem;
}

.header p {
  color: #666;
  font-size: 1.1rem;
}

.result-section {
  margin-bottom: 2rem;
}

.photo-result {
  display: flex;
  justify-content: center;
}

.photo-frame {
  background: white;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  max-width: 400px;
  width: 100%;
}

.photo-grid {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
}

.photo-cell {
  overflow: hidden;
  border-radius: 6px;
}

.photo-cell img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.actions-section {
  margin-bottom: 2rem;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.download-button, .share-button {
  background: #007bff;
  color: white;
  border: none;
  padding: 1rem 2rem;
  font-size: 1.1rem;
  font-weight: bold;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: 0 4px 15px rgba(0,123,255,0.3);
}

.share-button {
  background: #28a745;
  box-shadow: 0 4px 15px rgba(40,167,69,0.3);
}

.download-button:hover {
  background: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,123,255,0.4);
}

.share-button:hover {
  background: #218838;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(40,167,69,0.4);
}

.button-icon {
  font-size: 1.2rem;
}

.qr-section {
  text-align: center;
  margin-bottom: 2rem;
}

.qr-section h3 {
  color: #333;
  margin-bottom: 1rem;
}

.qr-container {
  background: white;
  padding: 2rem;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  max-width: 300px;
  margin: 0 auto;
}

.qr-code {
  width: 150px;
  height: 150px;
  margin-bottom: 1rem;
}

.qr-text {
  font-size: 0.9rem;
  color: #666;
  word-break: break-all;
  margin-bottom: 1rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.copy-link-button {
  background: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.copy-link-button:hover {
  background: #5a6268;
}

.footer-section {
  margin-top: 2rem;
}

.start-over-button {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 1rem 2rem;
  font-size: 1.1rem;
  font-weight: bold;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255,107,107,0.3);
}

.start-over-button:hover {
  background: #ff5252;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255,107,107,0.4);
}

/* Frame styles */
.frame-0 {
  /* Classic frame - default white */
}

.frame-1 {
  /* Modern frame */
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
}

.frame-2 {
  /* Vintage frame */
  background: linear-gradient(45deg, #f093fb, #f5576c);
}

.frame-3 {
  /* Colorful frame */
  background: linear-gradient(45deg, #4facfe, #00f2fe);
}

.frame-4 {
  /* Minimal frame */
  background: #f8f9fa;
  border: 2px solid #dee2e6;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .download-button, .share-button {
    width: 200px;
    justify-content: center;
  }

  .photo-frame {
    max-width: 300px;
  }
}
</style>