<template>
  <div class="min-h-screen bg-background text-foreground flex flex-col">
    <Header />
    <main class="flex-1 max-w-5xl mx-auto w-full px-6 py-24 sm:py-32 space-y-24">
      
      <!-- Hero -->
      <section 
        class="text-center space-y-8"
        v-motion
        :initial="{ opacity: 0, y: 20 }"
        :enter="{ opacity: 1, y: 0, transition: { duration: 600 } }"
      >
         <h1 class="text-4xl sm:text-7xl font-black tracking-tight leading-tight">
           {{ t('scanning.title').split(' ').slice(0, 2).join(' ') }}
           <span class="bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent block">
             {{ t('scanning.title').split(' ').slice(2).join(' ') }}
           </span>
         </h1>
         <p class="text-lg sm:text-xl text-muted-foreground max-w-3xl mx-auto leading-relaxed">
           {{ t('scanning.subtitle') }}
         </p>

         <div class="pt-8">
           <div class="relative group max-w-4xl mx-auto">
             <div class="absolute -inset-2 bg-gradient-to-r from-primary/20 to-primary/0 rounded-[3rem] blur opacity-25 group-hover:opacity-40 transition duration-1000"></div>
             <img 
               src="/images/scanning_hero.png" 
               alt="3D Scanning Digital Twin" 
               class="relative rounded-[2.5rem] border border-border/50 shadow-2xl"
             />
           </div>
         </div>
      </section>

      <!-- Workflow Steps -->
      <section class="space-y-12">
        <h2 class="text-3xl sm:text-4xl font-bold tracking-tight text-center">{{ t('scanning.workflow.title') }}</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div 
            v-for="(step, key) in ['scan', 'reverse', 'print']" 
            :key="key"
            class="relative group bg-card/40 border border-border/50 rounded-[2rem] p-8 space-y-6 backdrop-blur-sm hover:border-primary/30 transition-colors"
            v-motion
            :initial="{ opacity: 0, y: 30 }"
            :enter="{ opacity: 1, y: 0, transition: { delay: 200 + (key * 150), duration: 600 } }"
          >
            <div class="p-4 bg-primary/10 rounded-2xl w-fit">
              <component :is="getIcon(step)" class="w-8 h-8 text-primary" />
            </div>
            <h3 class="text-2xl font-bold leading-tight">{{ t(`scanning.workflow.${step}.title`) }}</h3>
            <p class="text-muted-foreground leading-relaxed">
              {{ t(`scanning.workflow.${step}.description`) }}
            </p>
            <div v-if="key < 2" class="hidden md:block absolute -right-6 top-1/2 -translate-y-1/2 z-10">
              <ChevronRight class="w-8 h-8 text-border" />
            </div>
          </div>
        </div>
      </section>

      <!-- Showcase Section (Interactive 3D Portfolio) -->
      <section class="space-y-12" id="scans-showcase">
        <div class="text-center space-y-4">
          <h2 class="text-3xl sm:text-5xl font-black tracking-tight">
            {{ t('scanning.portfolio.title').split(' ').slice(0, -1).join(' ') }}
            <span class="bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
              {{ t('scanning.portfolio.title').split(' ').slice(-1)[0] }}
            </span>
          </h2>
          <p class="text-muted-foreground max-w-2xl mx-auto leading-relaxed text-sm sm:text-base">
            {{ t('scanning.portfolio.subtitle') }}
          </p>
        </div>

        <div v-if="loading" class="flex flex-col items-center justify-center py-20 space-y-4">
          <RefreshCw class="w-10 h-10 text-primary animate-spin" />
          <p class="text-xs uppercase font-black tracking-widest text-muted-foreground">Loading portfolio...</p>
        </div>

        <div v-else-if="scans.length === 0" class="text-center py-16 bg-card/20 border border-border/40 rounded-3xl space-y-2">
          <Box class="w-12 h-12 text-muted-foreground/60 mx-auto" />
          <p class="text-sm font-bold text-muted-foreground">{{ t('scanning.portfolio.empty') }}</p>
        </div>

        <div v-else class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
          <!-- Active scan 3D viewer (Top on mobile, right on desktop) -->
          <div class="lg:col-span-7 lg:order-2 space-y-4">
            <!-- Toggle 3D vs Real Photo -->
            <div v-if="activeScan.has_photo" class="flex gap-1.5 p-1 bg-card/60 border border-border/40 rounded-2xl w-fit">
              <button 
                @click="showRealPhoto = false"
                class="px-4 py-1.5 rounded-xl text-xs font-black transition-all"
                :class="!showRealPhoto ? 'bg-primary text-primary-foreground shadow-lg shadow-primary/20' : 'text-muted-foreground hover:text-white'"
              >
                360° View
              </button>
              <button 
                @click="showRealPhoto = true"
                class="px-4 py-1.5 rounded-xl text-xs font-black transition-all"
                :class="showRealPhoto ? 'bg-primary text-primary-foreground shadow-lg shadow-primary/20' : 'text-muted-foreground hover:text-white'"
              >
                Original Photo
              </button>
            </div>

            <!-- Photorealistic Image Container -->
            <div v-if="showRealPhoto && activeScan.has_photo" class="relative group aspect-square lg:aspect-video rounded-[2.5rem] border border-border/50 bg-black/45 overflow-hidden flex items-center justify-center backdrop-blur-sm">
              <img 
                :src="`${RESOURCES_BASE_URL}/uploads/scans/${activeScan.folder_name}/photo.webp`"
                alt="Original physical object"
                class="max-w-full max-h-full object-contain"
              />
            </div>
            
            <ThreeSixtyViewer
              v-else
              :folder-name="activeScan.folder_name"
              :frames-count="activeScan.frames_count"
              :resources-base-url="RESOURCES_BASE_URL"
            />
            <div class="p-6 bg-card/30 border border-border/30 rounded-3xl space-y-2 backdrop-blur-sm">
              <h3 class="text-xl font-bold tracking-tight text-white">{{ getLocalizedTitle(activeScan) }}</h3>
              <p class="text-xs sm:text-sm text-muted-foreground leading-relaxed">{{ getLocalizedDescription(activeScan) }}</p>
            </div>
          </div>

          <!-- Selection List (Bottom on mobile, left on desktop) -->
          <div class="lg:col-span-5 lg:order-1 space-y-4">
            <div class="max-h-[420px] lg:max-h-[500px] overflow-y-auto pr-2 custom-scrollbar space-y-4">
              <button
                v-for="scan in scans"
                :key="scan.id"
                @click="activeScan = scan; showRealPhoto = false"
                class="w-full text-left p-4 rounded-2xl border transition-all duration-300 flex gap-4 bg-card/20 hover:bg-card/45"
                :class="activeScan.id === scan.id ? 'border-primary/50 bg-primary/5 shadow-lg shadow-primary/5' : 'border-border/35 hover:border-border/60'"
              >
                <!-- Thumbnail -->
                <div class="w-20 h-20 rounded-xl bg-black/60 border border-white/5 overflow-hidden flex-shrink-0 relative">
                  <img
                    :src="`${RESOURCES_BASE_URL}/uploads/scans/${scan.folder_name}/thumbnail.webp`"
                    class="w-full h-full object-cover"
                    alt="Scan thumbnail"
                  />
                </div>
                <!-- Text -->
                <div class="flex-1 min-w-0 flex flex-col justify-between py-1">
                  <div>
                    <h4 class="font-bold text-sm tracking-tight text-white truncate">{{ getLocalizedTitle(scan) }}</h4>
                    <p class="text-xs text-muted-foreground leading-snug line-clamp-2 mt-1">{{ getLocalizedDescription(scan) }}</p>
                  </div>
                  <div class="text-[10px] text-muted-foreground flex items-center gap-1 mt-2">
                    <span class="font-mono text-primary/70">{{ scan.frames_count }} frames</span>
                    <span>•</span>
                    <span>Interactive</span>
                  </div>
                </div>
              </button>
            </div>
            <!-- Pagination -->
            <div v-if="total > size" class="flex items-center justify-center gap-2 pt-2">
               <button v-for="p in Math.ceil(total / size)" :key="p" 
                 @click="changePage(p)" 
                 :class="['w-7 h-7 rounded-lg font-bold text-[10px] transition-all p-0 flex items-center justify-center border', page === p ? 'bg-primary text-black border-primary shadow-glow' : 'bg-card border border-border/50 text-muted-foreground hover:border-primary/50']">
                 {{ p }}
               </button>
            </div>
          </div>
        </div>
      </section>

      <!-- Use Cases -->
      <section class="bg-secondary/30 rounded-[3.5rem] p-8 sm:p-16 space-y-12">
        <h2 class="text-3xl sm:text-4xl font-bold tracking-tight text-center">{{ t('scanning.useCases.title') }}</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div 
            v-for="(useCase, key) in ['restoration', 'yachting', 'archiving']" 
            :key="key"
            class="space-y-4"
          >
            <div class="flex items-center gap-3">
              <div class="w-1.5 h-1.5 rounded-full bg-primary" />
              <h3 class="text-xl font-bold">{{ t(`scanning.useCases.${useCase}.title`) }}</h3>
            </div>
            <p class="text-muted-foreground leading-relaxed pl-4 border-l border-border">
              {{ t(`scanning.useCases.${useCase}.description`) }}
            </p>
          </div>
        </div>
      </section>

      <!-- Final CTA -->
      <section 
        class="text-center py-12 space-y-10"
        v-motion
        :initial="{ opacity: 0 }"
        :enter="{ opacity: 1, transition: { delay: 800 } }"
      >
        <p class="text-2xl sm:text-3xl font-medium max-w-2xl mx-auto leading-relaxed">
          {{ t('scanning.cta.text') }}
        </p>
        <RouterLink 
          :to="`/${locale}/contact`" 
          class="inline-flex items-center justify-center px-12 py-5 text-xl font-bold bg-primary text-primary-foreground hover:bg-primary/90 rounded-2xl transition-all hover:scale-105 shadow-xl shadow-primary/20"
        >
          {{ t('scanning.cta.button') }}
        </RouterLink>
      </section>
      
    </main>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useHead } from "@unhead/vue";
import { Scan, FileCode, Printer, ChevronRight, RefreshCw, Box } from "lucide-vue-next";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import { useI18n } from "vue-i18n";
import { getPublicScans, RESOURCES_BASE_URL } from "@/lib/api";
import ThreeSixtyViewer from "@/components/ThreeSixtyViewer.vue";

const { t, locale } = useI18n();

const scans = ref<any[]>([]);
const activeScan = ref<any>(null);
const showRealPhoto = ref(false);
const loading = ref(true);
const page = ref(1);
const total = ref(0);
const size = ref(10);

const getIcon = (step: string) => {
  switch (step) {
    case 'scan': return Scan;
    case 'reverse': return FileCode;
    case 'print': return Printer;
    default: return Scan;
  }
};

const getLocalizedTitle = (scan: any) => {
  if (!scan) return "";
  if (locale.value === 'ru') return scan.title_ru || scan.title_en;
  if (locale.value === 'me') return scan.title_me || scan.title_en;
  if (locale.value === 'ua') return scan.title_ua || scan.title_en;
  return scan.title_en;
};

const getLocalizedDescription = (scan: any) => {
  if (!scan) return "";
  if (locale.value === 'ru') return scan.description_ru || scan.description_en;
  if (locale.value === 'me') return scan.description_me || scan.description_en;
  if (locale.value === 'ua') return scan.description_ua || scan.description_en;
  return scan.description_en;
};

const fetchScansList = async () => {
  loading.value = true;
  try {
    const fetched = await getPublicScans(page.value, size.value);
    scans.value = fetched.scans || [];
    total.value = fetched.total || 0;
    if (scans.value.length > 0) {
      const exists = scans.value.some(s => s.id === activeScan.value?.id);
      if (!exists) {
        activeScan.value = scans.value[0];
      }
    } else {
      activeScan.value = null;
    }
  } catch (error) {
    console.error("Failed to load public scans portfolio:", error);
  } finally {
    loading.value = false;
  }
};

const changePage = (p: number) => {
  page.value = p;
  fetchScansList();
};

onMounted(() => {
  fetchScansList();
});

useHead({
  title: computed(() => `${t('scanning.title')} | Radionica 3D`),
  meta: [
    { name: "description", content: computed(() => t('scanning.subtitle')) }
  ]
});
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
  width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.02);
  border-radius: 2px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: var(--primary, #66fcf1);
}
</style>
