<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useDevicesList, useFullscreen, useWindowSize } from '@vueuse/core'
import { useRouter } from 'vue-router'
import { usePhotoboothStore } from '../stores/photoboothStore'
import CameraCapture from '../components/CameraCapture.vue'
import CountdownTimer from '../components/CountdownTimer.vue'

const store = usePhotoboothStore()
const router = useRouter()

const { width } = useWindowSize()
const isCompact = computed(() => width.value < 860)

const cameraRef = ref(null)
const stageRef = ref(null)
const cameraError = ref('')

const { devices } = useDevicesList({ requestPermissions: true })
const videoInputs = computed(() => devices.value.filter((device) => device.kind === 'videoinput'))
const selectedDeviceId = ref('')

const {
  isSupported: fullscreenSupported,
  toggle: toggleFullscreen,
  isFullscreen,
} = useFullscreen(stageRef)

const countdownActive = ref(false)
const isRunning = ref(false)

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

function setCameraError(error) {
  cameraError.value = error?.message || 'Camera access failed.'
}

function pickDefaultDevice() {
  if (selectedDeviceId.value || videoInputs.value.length === 0) return
  selectedDeviceId.value = videoInputs.value[0].deviceId
}

watch(videoInputs, pickDefaultDevice, { immediate: true })

async function startSequence() {
  if (isRunning.value) return

  store.resetSession()
  store.setSessionActive(true)
  isRunning.value = true
  countdownActive.value = true
}

function retake() {
  store.resetSession()
  countdownActive.value = false
  isRunning.value = false
}

async function handleCountdownFinished() {
  countdownActive.value = false

  const snapshot = cameraRef.value?.takeSnapshot()
  if (snapshot) {
    store.addPhoto(snapshot)
  }

  if (store.photos.length < 3) {
    await new Promise((resolve) => setTimeout(resolve, 700))
    countdownActive.value = true
    return
  }

  isRunning.value = false
}

function goNext() {
  if (store.photos.length < 3) return
  router.push('/customize')
}
</script>

<template>
  <main class="capture" :class="{ compact: isCompact }">
    <section class="capture-panel">
      <div class="panel-header">
        <div>
          <h1>Capture your shots</h1>
          <p>Get ready for three timed captures.</p>
        </div>
        <button v-if="fullscreenSupported" class="ghost-button" @click="toggleFullscreen">
          {{ isFullscreen ? 'Exit fullscreen' : 'Go fullscreen' }}
        </button>
      </div>

      <div class="camera-stage" ref="stageRef">
        <CameraCapture ref="cameraRef" :device-id="selectedDeviceId" @error="setCameraError" />
        <CountdownTimer :active="countdownActive" @finished="handleCountdownFinished" />
      </div>

      <div class="capture-controls">
        <div class="device-select">
          <label for="camera">Camera</label>
          <select id="camera" v-model="selectedDeviceId" @change="pickDefaultDevice">
            <option v-for="device in videoInputs" :key="device.deviceId" :value="device.deviceId">
              {{ device.label || 'Camera' }}
            </option>
          </select>
        </div>

        <div class="buttons">
          <button class="primary" @click="startSequence">Start countdown</button>
          <button class="ghost-button" @click="retake">Retake</button>
          <button class="primary" :class="{ disabled: store.photos.length < 3 }" @click="goNext">
            Next
          </button>
        </div>
      </div>

      <p v-if="cameraError" class="error">{{ cameraError }}</p>
    </section>

    <section class="thumb-panel">
      <h2>Shots</h2>
      <div class="thumbs">
        <div v-for="index in 3" :key="index" class="thumb">
          <img v-if="store.photos[index - 1]" :src="store.photos[index - 1].preview || store.photos[index - 1].src || store.photos[index - 1]" alt="Captured" />
          <span v-else>Shot {{ index }}</span>
        </div>
      </div>
    </section>
  </main>
</template>

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

.capture.compact {
  grid-template-columns: 1fr;
}

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

.panel-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.panel-header h1 {
  margin: 0;
}

.panel-header p {
  margin: 6px 0 0;
  color: var(--muted);
}

.camera-stage {
  position: relative;
}

.capture-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: space-between;
}

.device-select {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.device-select select {
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(200, 90, 124, 0.3);
  background: #fff;
}

.buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.primary,
.ghost-button {
  border: none;
  border-radius: 999px;
  padding: 10px 20px;
  font-weight: 600;
  cursor: pointer;
  text-align: center;
}

.primary {
  background: #c85a7c;
  color: #fff;
  box-shadow: 0 12px 24px rgba(200, 90, 124, 0.25);
}

.primary.disabled {
  pointer-events: none;
  opacity: 0.5;
}

.ghost-button {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(200, 90, 124, 0.3);
  color: #7c3b54;
}

.error {
  margin: 0;
  color: #a13b56;
}

.thumb-panel {
  padding: 24px;
  border-radius: 28px;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: var(--soft-shadow);
}

.thumb-panel h2 {
  margin-top: 0;
}

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

.thumb {
  width: 100%;
  aspect-ratio: 4 / 3;
  border-radius: 18px;
  background: rgba(255, 236, 243, 0.7);
  border: 2px dashed rgba(200, 90, 124, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--muted);
  overflow: hidden;
}

.thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
