<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useCasesStore } from '@/stores/cases'
import VueEasyLightbox from 'vue-easy-lightbox'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const casesStore = useCasesStore()

const showInfo = ref(true)
const activeCategoryIndex = ref(0)

// Lightbox state
const lightboxVisible = ref(false)
const lightboxIndex = ref(0)

const currentCase = computed(() => casesStore.currentCase)

const hasCategories = computed(() => {
  const c = currentCase.value
  if (!c) return false
  return c.categories.length > 1 || (c.categories.length === 1 && c.categories[0].name !== '')
})

const activeImages = computed(() => {
  const c = currentCase.value
  if (!c) return []
  if (hasCategories.value) {
    return c.categories[activeCategoryIndex.value]?.images || []
  }
  return c.categories[0]?.images || []
})

const lightboxImages = computed(() => activeImages.value)

function openLightbox(imageSrc: string) {
  const idx = activeImages.value.indexOf(imageSrc)
  lightboxIndex.value = idx >= 0 ? idx : 0
  lightboxVisible.value = true
}

function closeLightbox() {
  lightboxVisible.value = false
}

function loadCurrentCase() {
  const slug = route.params.slug as string
  if (!slug) return
  const found = casesStore.loadCase(slug)
  if (!found) {
    router.replace('/works')
  }
  activeCategoryIndex.value = 0
}

loadCurrentCase()

watch(() => route.params.slug, () => {
  loadCurrentCase()
})

onUnmounted(() => {
  casesStore.clearCurrent()
})

interface InfoRow {
  label: string
  value: string
}

const infoRows = computed<InfoRow[]>(() => {
  const c = currentCase.value
  if (!c?.description) return []

  return c.description
    .split(/\r?\n/)
    .filter((line) => line.trim() !== '' && !line.startsWith('#') && !line.startsWith('http'))
    .map((line) => {
      const idx = line.indexOf('：')
      if (idx > 0) {
        return { label: line.slice(0, idx + 1), value: line.slice(idx + 1) }
      }
      const colonIdx = line.indexOf(':')
      if (colonIdx > 0 && colonIdx < 20) {
        return { label: line.slice(0, colonIdx + 1), value: line.slice(colonIdx + 1) }
      }
      return { label: '', value: line }
    })
})
</script>

<template>
  <div v-if="currentCase">
    <!-- Title -->
    <h1 class="work-detail-title">{{ currentCase.title }}</h1>

    <!-- Info Toggle -->
    <button v-if="infoRows.length > 0" class="work-info-toggle" @click="showInfo = !showInfo">
      {{ showInfo ? t('work.hideInfo') : t('work.showInfo') }}
    </button>

    <!-- Structured Project Info -->
    <div v-if="showInfo && infoRows.length > 0" class="work-info-table">
      <div v-for="(row, i) in infoRows" :key="i" class="work-info-row">
        <span v-if="row.label" class="work-info-label">{{ row.label }}</span>
        <span class="work-info-value">{{ row.value }}</span>
      </div>
    </div>

    <!-- Category Tabs -->
    <div v-if="hasCategories" class="case-tabs">
      <button
        v-for="(cat, index) in currentCase.categories"
        :key="cat.name"
        class="case-tab"
        :class="{ active: index === activeCategoryIndex }"
        @click="activeCategoryIndex = index"
      >
        {{ cat.name }}
      </button>
    </div>

    <!-- Photo Grid -->
    <div class="photo-grid">
      <img
        v-for="(src, i) in activeImages"
        :key="i"
        :src="src"
        :alt="`${currentCase.title} - ${i + 1}`"
        loading="lazy"
        class="photo-grid-img"
        @click="openLightbox(src)"
      />
    </div>

    <!-- Lightbox -->
    <VueEasyLightbox
      :visible="lightboxVisible"
      :imgs="lightboxImages"
      :index="lightboxIndex"
      @hide="closeLightbox"
    />
  </div>

  <div v-else class="loading">{{ t('common.noData') }}</div>
</template>
