<template>
  <div @click="$emit('open')" class="beforeafter-preview">
    <div v-if="hasImages" class="beforeafter-preview__images">
      <img
        v-if="imageAfterUrl"
        :src="imageAfterUrl"
        class="beforeafter-preview__image beforeafter-preview__image--after"
        alt="Après"
      />
      <img
        v-if="imageBeforeUrl"
        :src="imageBeforeUrl"
        class="beforeafter-preview__image beforeafter-preview__image--before"
        alt="Avant"
      />
      <div v-if="imageBeforeUrl && imageAfterUrl" class="beforeafter-preview__divider"></div>
    </div>

    <p v-if="content.caption" class="beforeafter-preview__caption">
      {{ content.caption }}
    </p>

    <div v-if="!hasImages" class="beforeafter-preview__empty">
      Cliquer pour ajouter des images
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  content: Object,
  endpoints: Object
});

const imageBeforeUrl = computed(() => {
  // Attention: la clé est en minuscules dans Kirby
  if (!props.content?.imagebefore || !props.content.imagebefore.length) {
    return null;
  }
  const file = props.content.imagebefore[0];
  return file?.url || null;
});

const imageAfterUrl = computed(() => {
  // Attention: la clé est en minuscules dans Kirby
  if (!props.content?.imageafter || !props.content.imageafter.length) {
    return null;
  }
  const file = props.content.imageafter[0];
  return file?.url || null;
});

const hasImages = computed(() => {
  return imageBeforeUrl.value || imageAfterUrl.value;
});
</script>

<style scoped>
.beforeafter-preview {
  cursor: pointer;
  border-radius: var(--rounded);
  overflow: hidden;
  background: var(--color-background);
}

.beforeafter-preview__images {
  position: relative;
  width: 100%;
  height: 200px;
  background: var(--color-gray-200);
}

.beforeafter-preview__image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.beforeafter-preview__image--before {
  clip-path: polygon(0 0, 50% 0, 50% 100%, 0 100%);
}

.beforeafter-preview__divider {
  position: absolute;
  left: 50%;
  top: 0;
  bottom: 0;
  width: 2px;
  background: white;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  transform: translateX(-1px);
}

.beforeafter-preview__caption {
  padding: 0.75rem;
  font-size: var(--text-sm);
  color: var(--color-gray-600);
  font-style: italic;
  background: var(--color-background);
  margin: 0;
}

.beforeafter-preview__empty {
  padding: 3rem 1rem;
  text-align: center;
  color: var(--color-gray-500);
  font-size: var(--text-sm);
}

.beforeafter-preview:hover .beforeafter-preview__images {
  opacity: 0.9;
}
</style>
