<template>
  <div class="flex h-full flex-col gap-4 rounded-3xl border border-white/10 bg-white/5 p-4 text-white">
    <div class="flex items-center justify-between gap-2 text-xs uppercase tracking-[0.3em] text-slate-300">
      <span>Varianten</span>
      <button
        type="button"
        class="rounded-full border border-white/20 p-1 text-white/70 transition hover:border-rose-300 hover:text-rose-300"
        @click="$emit('close')"
        aria-label="Auswahl schließen"
      >
        <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6m-12 0 12 12" />
        </svg>
      </button>
    </div>

    <div ref="stylesContainer" class="flex-1 space-y-3 overflow-y-auto pr-1">
      <p v-if="isLoading" class="rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-center text-sm text-slate-300">
        Stile werden geladen …
      </p>
      <p v-else-if="loadError" class="rounded-2xl border border-rose-400/40 bg-rose-500/10 px-4 py-3 text-center text-sm text-rose-100">
        {{ loadError }}
      </p>
      <template v-else>
        <button
          v-for="style in styles"
          :key="style.id"
          type="button"
          class="group flex w-full items-center gap-4 rounded-2xl border border-white/10 bg-white/5 p-3 text-left transition hover:border-emerald-300"
          @click="selectStyle(style)"
        >
          <img
            v-if="style.preview_image"
            :data-src="'/storage/' + style.preview_image"
            class="h-24 w-24 flex-none rounded-2xl object-cover opacity-90 transition group-hover:opacity-100"
            alt="Style preview"
          />
          <div
            v-else
            class="flex h-24 w-24 flex-none items-center justify-center rounded-2xl border border-dashed border-white/20 text-[0.65rem] uppercase tracking-[0.4em] text-slate-400"
          >
            AI
          </div>
          <div class="flex flex-col">
            <p class="text-base font-semibold text-white">{{ style.title }}</p>
            <p class="text-sm text-slate-200">{{ style.description }}</p>
          </div>
        </button>
      </template>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { nextTick, onMounted, onUnmounted, ref } from 'vue';

const styles = ref([]);
const isLoading = ref(true);
const loadError = ref(null);
const stylesContainer = ref(null);
let observer = null;

const props = defineProps({
  image_id: {
    type: [Number, String],
    required: true,
  },
});

const emits = defineEmits(['styleSelected', 'close']);

const hydrateObserver = () => {
  if (!stylesContainer.value) {
    return;
  }

  if (observer) {
    observer.disconnect();
  }

  observer = new IntersectionObserver(
    (entries, obs) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          obs.unobserve(img);
        }
      });
    },
    { root: stylesContainer.value }
  );

  stylesContainer.value.querySelectorAll('img[data-src]').forEach((img) => observer.observe(img));
};

const fetchStyles = () => {
  isLoading.value = true;
  loadError.value = null;
  axios
    .get('/api/styles')
    .then((response) => {
      styles.value = response.data;
      nextTick(hydrateObserver);
    })
    .catch((error) => {
      console.error('Error fetching styles:', error);
      loadError.value = 'Stile konnten nicht geladen werden.';
    })
    .finally(() => {
      isLoading.value = false;
    });
};

const selectStyle = (style) => {
  emits('styleSelected', style, props.image_id);
};

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

onUnmounted(() => {
  if (observer) {
    observer.disconnect();
  }
});
</script>
