<template>
  <div class="catalog-show-page">
    <header class="hero-section-gradient from-purple-700 to-indigo-800 py-12 md:py-20">
      <div class="hero-container">
        <nav class="mb-8">
          <RouterLink to="/catalog" class="catalog-back-link">
            <i class="fa-solid fa-arrow-left"></i> {{ t('catalogShow.back') }}
          </RouterLink>
        </nav>

        <div v-if="software" class="catalog-header-content">
          <div class="flex-grow">
            <div class="catalog-badges-group">
              <span :class="`status-badge status-${software.status} px-3 py-1`">{{ t(`common.status.${software.status}`) }}</span>
              <PlatformBadge :platform="software.platform" />
            </div>
            <h1 class="catalog-title">{{ software.title }}</h1>
            <p class="catalog-subtitle">{{ software.desc }}</p>
          </div>
        </div>
      </div>
    </header>

    <main v-if="software" class="main-container -mt-10">
      <div class="catalog-layout">
        <!-- Sidebar Info -->
        <div class="catalog-sidebar">
          <div class="catalog-card">
            <div v-if="defaultImageUrl" class="mb-6">
              <div class="flex justify-center">
                <img
                  :src="defaultImageUrl"
                  :alt="software.title"
                  :class="['catalog-featured-image', softwareImages.length > 0 ? 'cursor-pointer hover:opacity-80 transition-opacity' : '']"
                  @click="openLightbox(defaultImageIndex)"
                />
              </div>
              <div v-if="softwareImages.length > 1" class="catalog-thumbs">
                <img
                  v-for="(img, idx) in softwareImages"
                  :key="idx"
                  :src="img.url"
                  :alt="`${software.title} ${idx + 1}`"
                  :class="['catalog-thumb', img.isDefault ? 'border-purple-400' : 'border-gray-200 hover:border-purple-300']"
                  @click="openLightbox(idx)"
                />
              </div>
            </div>
            <h2 class="catalog-section-heading">
              <i class="fa-solid fa-circle-info text-purple-600"></i> {{ t('catalogShow.projectInfo') }}
            </h2>
            <dl class="space-y-4">
              <div>
                <dt class="catalog-info-label">{{ t('catalogShow.author') }}</dt>
                <dd class="catalog-info-value">{{ software.author }}</dd>
              </div>
              <div>
                <dt class="catalog-info-label">{{ t('catalogShow.platform') }}</dt>
                <dd><PlatformBadge :platform="software.platform" /></dd>
              </div>
              <div v-if="software.license">
                <dt class="catalog-info-label">{{ t('catalogShow.license') }}</dt>
                <dd class="catalog-info-value">{{ software.license }}</dd>
              </div>
              <div v-if="software.externalLinks?.length">
                <dt class="catalog-info-label">{{ t('catalogShow.links') }}</dt>
                <dd class="flex flex-col gap-1.5">
                  <a v-for="link in software.externalLinks" :key="link.url" :href="link.url" target="_blank" class="catalog-external-link">
                    {{ link.label }} <i class="fa-solid fa-up-right-from-square text-xs"></i>
                  </a>
                </dd>
              </div>
              <div v-if="software.platformLinks?.length">
                <dt class="catalog-info-label">{{ t('catalogShow.platformLinks') }}</dt>
                <dd class="flex flex-col gap-1.5">
                  <a v-for="pl in software.platformLinks" :key="pl.url" :href="pl.url" target="_blank" class="catalog-external-link">
                    {{ pl.name }} <i class="fa-solid fa-up-right-from-square text-xs"></i>
                  </a>
                </dd>
              </div>
            </dl>
          </div>
        </div>

        <!-- Main Content Area -->
        <div class="catalog-main">
          <div v-if="software.story" class="catalog-card">
            <h2 class="catalog-about-title">{{ t('catalogShow.about') }}</h2>
            <p class="catalog-about-text">{{ software.story }}</p>
          </div>

          <div v-if="latestStable" class="latest-release-card">
            <div class="latest-release-header">
              <div>
                <div class="latest-release-label-row">
                  <span class="latest-release-badge">{{ t('catalogShow.latestStable') }}</span>
                </div>
                <h2 class="latest-release-version">{{ latestStable.version }}</h2>
                <p class="latest-release-date"><i class="fa-solid fa-calendar mr-1"></i>{{ t('catalogShow.released') }} {{ formatDateTime(latestStable.updatedAt) }}</p>
              </div>

              <a v-if="latestStable.htmlFolderPath" :href="latestStable.htmlFolderPath" target="_blank" class="latest-release-play-btn"><i class="fa-solid fa-play mr-2"></i>{{ t('catalogShow.playNow') }}</a>
            </div>

            <div v-if="tableAssets(latestStable).length" class="latest-release-assets">
              <div class="assets-section-label">{{ t('catalogShow.assetsTitle') }}</div>
              <!-- Desktop asset table -->
              <table class="asset-table-desktop">
                <tbody>
                  <tr v-for="asset in tableAssets(latestStable)" :key="asset.kind" class="asset-table-row-light">
                    <td class="asset-kind-col-light"><i :class="assetKindIcon(asset.kind)" class="w-4 text-center"></i> {{ t('catalogShow.assetKind.' + asset.kind) }}</td>
                    <td class="asset-path-col-light">{{ assetFileName(asset.path) }}</td>
                    <td class="asset-action-col">
                      <a v-if="asset.kind === 'docs'" :href="asset.path" target="_blank" class="asset-link-white">{{ t('catalogShow.assetOpen') }}</a>
                      <a v-else :href="downloadUrl(asset.path)" class="asset-link-white">{{ t('catalogShow.assetDownload') }}</a>
                    </td>
                  </tr>
                </tbody>
              </table>
              <!-- Mobile asset list -->
              <div class="asset-mobile-list">
                <div v-for="asset in tableAssets(latestStable)" :key="asset.kind" class="asset-mobile-item-light">
                  <div class="asset-mobile-row">
                    <span class="asset-mobile-kind-light"><i :class="assetKindIcon(asset.kind)" class="w-4 text-center"></i> {{ t('catalogShow.assetKind.' + asset.kind) }}</span>
                    <a v-if="asset.kind === 'docs'" :href="asset.path" target="_blank" class="asset-mobile-link-white">{{ t('catalogShow.assetOpen') }}</a>
                    <a v-else :href="downloadUrl(asset.path)" class="asset-mobile-link-white">{{ t('catalogShow.assetDownload') }}</a>
                  </div>
                  <div class="asset-mobile-path-light">{{ assetFileName(asset.path) }}</div>
                </div>
              </div>
            </div>
          </div>

          <div class="releases-card">
            <div class="releases-header">
              <h2 class="releases-title">{{ t('catalogShow.allReleases') }}</h2>
            </div>
            <div class="p-0">
              <!-- Desktop Table -->
              <div class="hidden md:block">
                <table class="w-full text-left">
                  <thead class="release-table-head">
                    <tr>
                      <th class="px-8 py-4">{{ t('catalogShow.version') }}</th>
                      <th class="px-8 py-4">{{ t('catalogShow.releaseDate') }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    <template v-for="release in stableReleases" :key="release.version">
                      <tr class="release-table-row">
                        <td class="px-8 py-4">
                          <div class="release-version-row">
                            <span class="release-version">{{ release.version }}</span>
                            <span v-if="release.downloadCount" class="release-download-count"><i class="fa-solid fa-download text-[10px]"></i> {{ release.downloadCount }}</span>
                          </div>
                          <a v-if="release.htmlFolderPath" :href="release.htmlFolderPath" target="_blank" class="release-play-link">{{ t('catalogShow.play') }}</a>
                        </td>
                        <td class="release-date-col">{{ formatDateTime(release.updatedAt) }}</td>
                      </tr>
                      <tr v-if="tableAssets(release).length">
                        <td colspan="2" class="px-8 pb-4 pt-0">
                          <table class="w-full text-sm">
                            <tbody>
                              <tr v-for="asset in tableAssets(release)" :key="asset.kind" class="release-asset-row">
                                <td class="release-asset-kind"><i :class="assetKindIcon(asset.kind)" class="w-4 text-center"></i> {{ t('catalogShow.assetKind.' + asset.kind) }}</td>
                                <td class="release-asset-path">{{ assetFileName(asset.path) }}</td>
                                <td class="release-asset-action">
                                  <a v-if="asset.kind === 'docs'" :href="asset.path" target="_blank" class="release-asset-link">{{ t('catalogShow.assetOpen') }}</a>
                                  <a v-else :href="downloadUrl(asset.path)" class="release-asset-link">{{ t('catalogShow.assetDownload') }}</a>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </td>
                      </tr>
                    </template>

                    <tr v-if="devReleases.length > 0" class="dev-versions-header">
                      <td colspan="2" class="dev-versions-label">{{ t('catalogShow.devVersions') }}</td>
                    </tr>

                    <template v-for="release in devReleases" :key="release.version">
                      <tr class="dev-release-row">
                        <td class="px-8 py-4">
                          <div class="dev-release-version">{{ release.version }}</div>
                          <a v-if="release.htmlFolderPath" :href="release.htmlFolderPath" target="_blank" class="release-play-link">{{ t('catalogShow.play') }}</a>
                        </td>
                        <td class="release-date-col">{{ formatDateTime(release.updatedAt) }}</td>
                      </tr>
                      <tr v-if="tableAssets(release).length" class="bg-yellow-50/10">
                        <td colspan="2" class="px-8 pb-4 pt-0">
                          <table class="w-full text-sm">
                            <tbody>
                              <tr v-for="asset in tableAssets(release)" :key="asset.kind" class="release-asset-row">
                                <td class="release-asset-kind"><i :class="assetKindIcon(asset.kind)" class="w-4 text-center"></i> {{ t('catalogShow.assetKind.' + asset.kind) }}</td>
                                <td class="release-asset-path">{{ assetFileName(asset.path) }}</td>
                                <td class="release-asset-action">
                                  <a v-if="asset.kind === 'docs'" :href="asset.path" target="_blank" class="release-asset-link">{{ t('catalogShow.assetOpen') }}</a>
                                  <a v-else :href="downloadUrl(asset.path)" class="release-asset-link">{{ t('catalogShow.assetDownload') }}</a>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </div>

              <!-- Mobile View -->
              <div class="md:hidden divide-y divide-gray-100">
                <div
                  v-for="release in allReleases"
                  :key="release.version"
                  :class="['p-6', release.version.startsWith('dev-') ? 'bg-yellow-50/20' : '']"
                >
                  <div class="mobile-release-header">
                    <div>
                      <div class="mobile-release-version">{{ release.version }}</div>
                      <div class="mobile-release-date">{{ formatDateTime(release.updatedAt) }}</div>
                    </div>
                    <span v-if="release.version.startsWith('dev-')" class="dev-badge">Dev</span>
                  </div>
                  <a v-if="release.htmlFolderPath" :href="release.htmlFolderPath" target="_blank" class="mobile-play-btn">{{ t('catalogShow.play') }}</a>
                  <div v-if="tableAssets(release).length" class="mt-3 space-y-1">
                    <div v-for="asset in tableAssets(release)" :key="asset.kind" class="asset-mobile-item">
                      <div class="asset-mobile-row">
                        <span class="asset-mobile-kind"><i :class="assetKindIcon(asset.kind)" class="w-4 text-center"></i> {{ t('catalogShow.assetKind.' + asset.kind) }}</span>
                        <a v-if="asset.kind === 'docs'" :href="asset.path" target="_blank" class="asset-mobile-link">{{ t('catalogShow.assetOpen') }}</a>
                        <a v-else :href="downloadUrl(asset.path)" class="asset-mobile-link">{{ t('catalogShow.assetDownload') }}</a>
                      </div>
                      <div class="asset-mobile-path">{{ assetFileName(asset.path) }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <main v-else class="main-container -mt-10">
      <div class="loading-card">
        {{ error || t('catalogShow.loading') }}
      </div>
    </main>

    <ImageLightbox
      :images="softwareImages"
      :is-open="lightboxOpen"
      :start-index="lightboxStartIndex"
      @close="lightboxOpen = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { formatDateTime } from '../../lib/dateFormat'
import { useSoftwareStore } from '../../stores/software.store'
import { filterStableReleases, filterDevReleases } from '../../lib/softwareUtils'
import type { Release, Software, SoftwareImage } from '../../lib/interfaces/software.interface'
import ImageLightbox from './ImageLightbox.vue'
import PlatformBadge from '../../components/PlatformBadge.vue'

const { t } = useI18n()
const route = useRoute()
const store = useSoftwareStore()

const software = ref<Software | null>(null)
const releases = ref<Release[]>([])
const error = ref<string | null>(null)
const lightboxOpen = ref(false)
const lightboxStartIndex = ref(0)

const softwareImages = computed<SoftwareImage[]>(() => {
  if (software.value?.images?.length) {
    return [...software.value.images].sort((a, b) => a.position - b.position)
  }
  if (software.value?.imageUrl) {
    return [{ url: software.value.imageUrl, isDefault: true, position: 0 }]
  }
  return []
})

const defaultImageIndex = computed(() => {
  const idx = softwareImages.value.findIndex(i => i.isDefault)
  return idx >= 0 ? idx : 0
})

const defaultImageUrl = computed(() =>
  softwareImages.value[defaultImageIndex.value]?.url ?? null
)

function openLightbox(index: number) {
  if (softwareImages.value.length === 0) return
  lightboxStartIndex.value = index
  lightboxOpen.value = true
}

const stableReleases = computed(() => filterStableReleases(releases.value))
const devReleases = computed(() => filterDevReleases(releases.value))

const allReleases = computed(() => [...stableReleases.value, ...devReleases.value])
const latestStable = computed(() => stableReleases.value[0] ?? null)

const downloadUrl = (path: string) =>
  `/api/download?path=${encodeURIComponent(path.replace('/file/', ''))}`

// az asset-táblázat sorai és sorrendjük; a html nem letöltés, azt a Play gomb viszi
const TABLE_KIND_ORDER = [
  'cartridge', 'source', 'docs',
  'win_x64', 'win_x86', 'linux_x64', 'linux_arm64', 'linux_x86',
  'mac_universal', 'mac_arm64', 'mac_x64',
]

const tableAssets = (release: Release) =>
  (release.assets ?? [])
    .filter(a => TABLE_KIND_ORDER.includes(a.kind))
    .sort((a, b) => TABLE_KIND_ORDER.indexOf(a.kind) - TABLE_KIND_ORDER.indexOf(b.kind))

const assetFileName = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? ''

const assetKindIcon = (kind: string) =>
  kind.startsWith('win_') ? 'fa-brands fa-windows'
    : kind.startsWith('linux_') ? 'fa-brands fa-linux'
      : kind.startsWith('mac_') ? 'fa-brands fa-apple'
        : kind === 'cartridge' ? 'fa-solid fa-gamepad'
          : kind === 'source' ? 'fa-solid fa-code'
            : kind === 'docs' ? 'fa-solid fa-book'
              : ''

onMounted(async () => {
  try {
    await store.fetch()
    const item = store.findByName(route.params.name as string)
    if (item) {
      software.value = item.software
      releases.value = item.releases
    } else {
      error.value = t('catalogShow.notFound')
    }
  } catch (e) {
    error.value = `${t('catalogShow.failedToLoad')} ${e instanceof Error ? e.message : String(e)}`
  }
})
</script>

<style scoped>
/* Page */
.catalog-show-page { @apply bg-gray-50 min-h-screen pb-20; }
.catalog-back-link { @apply text-purple-200 hover:text-white transition-colors flex items-center gap-2 font-medium; }
.catalog-header-content { @apply flex flex-col md:flex-row md:items-end justify-between gap-6; }
.catalog-badges-group { @apply flex items-center justify-center gap-3 mb-4; }
.catalog-title { @apply text-4xl md:text-6xl font-black text-white mb-4 leading-tight; }
.catalog-subtitle { @apply text-xl text-purple-100 max-w-3xl mx-auto leading-relaxed; }

/* Layout */
.catalog-layout { @apply grid grid-cols-1 lg:grid-cols-3 gap-8; }
.catalog-sidebar { @apply lg:col-span-1 space-y-6; }
.catalog-main { @apply lg:col-span-2 space-y-8; }
.catalog-card { @apply bg-white rounded-3xl shadow-xl p-8 border border-gray-100; }

/* Sidebar */
.catalog-featured-image { @apply max-h-48 w-auto object-contain border-4 border-gray-100 shadow-sm; }
.catalog-thumbs { @apply flex gap-2 mt-3 justify-center; }
.catalog-thumb { @apply w-12 h-12 object-cover rounded border-2 cursor-pointer transition-all; }
.catalog-section-heading { @apply text-xl font-bold text-gray-900 mb-6 flex items-center gap-2; }
.catalog-info-label { @apply text-xs font-bold text-gray-400 uppercase tracking-widest mb-1; }
.catalog-info-value { @apply text-gray-900 font-medium; }
.catalog-external-link { @apply text-purple-600 hover:text-purple-800 font-bold inline-flex items-center gap-1; }

/* About */
.catalog-about-title { @apply text-xl font-bold text-gray-900 mb-4; }
.catalog-about-text { @apply text-gray-700 leading-relaxed whitespace-pre-line; }

/* Latest Release */
.latest-release-card { @apply bg-gradient-to-br from-indigo-600 to-purple-700 rounded-3xl shadow-xl p-8 text-white; }
.latest-release-header { @apply flex flex-col md:flex-row justify-between items-start md:items-center gap-6; }
.latest-release-label-row { @apply flex items-center gap-2 mb-2; }
.latest-release-badge { @apply px-2 py-0.5 bg-white/20 text-white text-[10px] font-black uppercase rounded tracking-widest; }
.latest-release-version { @apply text-4xl font-black mb-1; }
.latest-release-date { @apply text-indigo-100 text-sm; }
.latest-release-play-btn { @apply flex items-center justify-center py-3 px-6 bg-white text-indigo-900 font-bold rounded-xl transition-all hover:bg-indigo-50 shadow-lg shadow-black/10 text-sm whitespace-nowrap; }
.latest-release-assets { @apply mt-6 pt-6 border-t border-white/15; }
.assets-section-label { @apply text-[10px] font-black uppercase tracking-widest text-indigo-200 mb-3; }

/* Asset table - light (hero) */
.asset-table-desktop { @apply hidden md:table w-full text-sm; }
.asset-table-row-light { @apply border-b border-white/10 last:border-0; }
.asset-kind-col-light { @apply py-1.5 pr-6 text-indigo-100 whitespace-nowrap; }
.asset-path-col-light { @apply py-1.5 pr-6 w-full font-mono text-xs text-indigo-200/80 break-all; }
.asset-action-col { @apply py-1.5 text-right whitespace-nowrap; }
.asset-link-white { @apply text-white font-bold hover:underline; }

/* Asset mobile - light (hero) */
.asset-mobile-list { @apply md:hidden space-y-2; }
.asset-mobile-item-light { @apply flex flex-col gap-0.5 py-2 border-b border-white/10 last:border-0; }
.asset-mobile-row { @apply flex justify-between items-center; }
.asset-mobile-kind-light { @apply text-indigo-100 text-sm whitespace-nowrap; }
.asset-mobile-link-white { @apply text-white font-bold text-sm hover:underline ml-4 shrink-0; }
.asset-mobile-path-light { @apply font-mono text-xs text-indigo-200/80 truncate; }

/* Releases section */
.releases-card { @apply bg-white rounded-3xl shadow-xl overflow-hidden border border-gray-100; }
.releases-header { @apply p-8 border-b border-gray-100; }
.releases-title { @apply text-2xl font-bold text-gray-900; }
.release-table-head { @apply bg-gray-50 text-gray-500 text-xs font-bold uppercase tracking-widest; }
.release-table-row { @apply border-t border-gray-100 first:border-t-0 hover:bg-gray-50/50 transition-colors; }
.release-version-row { @apply flex items-center gap-2 mb-2; }
.release-version { @apply font-bold text-gray-900 text-lg; }
.release-download-count { @apply text-xs text-gray-400 font-medium; }
.release-play-link { @apply text-purple-600 hover:text-purple-900 font-bold text-sm; }
.release-date-col { @apply px-8 py-4 text-gray-500 align-top pt-5; }

/* Release asset table */
.release-asset-row { @apply border-b border-gray-100 last:border-0; }
.release-asset-kind { @apply py-1 pr-6 text-gray-500 whitespace-nowrap; }
.release-asset-path { @apply py-1 pr-6 w-full font-mono text-xs text-gray-400 break-all; }
.release-asset-action { @apply py-1 text-right whitespace-nowrap; }
.release-asset-link { @apply text-blue-600 hover:text-blue-900 font-bold; }

/* Dev versions */
.dev-versions-header { @apply border-t border-gray-100 bg-yellow-50/30; }
.dev-versions-label { @apply px-8 py-3 text-[10px] font-black text-yellow-700 uppercase tracking-tighter; }
.dev-release-row { @apply border-t border-gray-100 bg-yellow-50/10 hover:bg-yellow-50/30 transition-colors; }
.dev-release-version { @apply font-bold text-yellow-800 text-lg mb-2; }

/* Mobile releases */
.mobile-release-header { @apply flex justify-between items-start mb-4; }
.mobile-release-version { @apply font-bold text-gray-900 text-lg; }
.mobile-release-date { @apply text-gray-500 text-xs mt-1; }
.dev-badge { @apply px-2 py-0.5 bg-yellow-100 text-yellow-800 text-[10px] font-black uppercase rounded; }
.mobile-play-btn { @apply flex items-center justify-center py-2 bg-purple-100 text-purple-700 font-bold rounded-lg text-sm; }

/* Asset mobile - dark (releases) */
.asset-mobile-item { @apply flex flex-col gap-0.5 py-1.5 border-b border-gray-100 last:border-0; }
.asset-mobile-kind { @apply text-gray-500 text-sm whitespace-nowrap; }
.asset-mobile-link { @apply text-blue-600 font-bold text-sm ml-4 shrink-0; }
.asset-mobile-path { @apply font-mono text-xs text-gray-400 truncate; }

/* Status badges */
.status-badge { @apply rounded text-[10px] font-black uppercase tracking-wider; }
.status-released { @apply bg-green-500 text-white shadow-lg shadow-green-500/20; }
.status-demo { @apply bg-blue-500 text-white shadow-lg shadow-blue-500/20; }
.status-development { @apply bg-yellow-500 text-white shadow-lg shadow-yellow-500/20; }
.status-archived { @apply bg-gray-500 text-white shadow-lg shadow-gray-500/20; }

/* Loading */
.loading-card { @apply bg-white rounded-3xl shadow-xl p-12 text-center text-gray-400; }
</style>
