<script setup lang="ts">
import { ChevronRight, ChevronLeft } from "lucide-vue-next";
interface Image {
  Url: string;
  Alt: string;
}
interface Page {
  name: string;
  link?: string;
}

const { locale, t } = useI18n();
const dir = computed(() => (locale.value === "ar" ? "rtl" : "ltr"));

// Video optimization states
const videoRef = ref<HTMLVideoElement>();
const isVideoVisible = ref(true);
const shouldPlayVideo = ref(true);

const props = defineProps<{
  pages: Page[];
  videoUrl?: string;
  image?: Image;
}>();

useBreadcrumbSchema(props.pages);

// Intersection Observer to pause video when not visible
onMounted(() => {
  if (props.videoUrl && videoRef.value) {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          isVideoVisible.value = entry.isIntersecting;

          if (entry.isIntersecting && shouldPlayVideo.value) {
            videoRef.value?.play();
          } else {
            videoRef.value?.pause();
          }
        });
      },
      { threshold: 0.1 },
    );

    observer.observe(videoRef.value);

    onUnmounted(() => {
      observer.disconnect();
    });
  }
});

// Pause video during scroll for better performance
let scrollTimeout: NodeJS.Timeout;
const handleScroll = () => {
  if (!videoRef.value) return;

  // Pause video during scroll
  shouldPlayVideo.value = false;
  videoRef.value.pause();

  clearTimeout(scrollTimeout);
  scrollTimeout = setTimeout(() => {
    // Resume video after scroll ends
    shouldPlayVideo.value = true;
    if (isVideoVisible.value) {
      videoRef.value?.play();
    }
  }, 150);
};

onMounted(() => {
  if (props.videoUrl) {
    window.addEventListener("scroll", handleScroll, { passive: true });

    onUnmounted(() => {
      window.removeEventListener("scroll", handleScroll);
      clearTimeout(scrollTimeout);
    });
  }
});
</script>
<template>
  <section
    class="hero -mt-header relative grid min-h-[500px] w-full items-center"
  >
    <!-- Background elements container with fixed positioning to prevent layout shift -->
    <div class="absolute inset-0 overflow-hidden">
      <video
        v-if="props.videoUrl"
        ref="videoRef"
        autoplay
        muted
        loop
        playsinline
        preload="metadata"
        class="absolute inset-0 h-full w-full object-cover will-change-auto"
        :poster="props.image?.Url"
        style="filter: contrast(1.05) brightness(0.95)"
        @loadstart="() => {}"
        @error="
          () => {
            shouldPlayVideo = false;
          }
        "
        @canplay="
          () => {
            if (isVideoVisible && shouldPlayVideo) videoRef?.play();
          }
        "
      >
        <source :src="props.videoUrl" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
      <NuxtImg
        v-if="image?.Url"
        :src="image?.Url"
        class="absolute inset-0 block h-full w-full object-cover"
        :alt="image?.Alt"
        width="1920"
        height="500"
        sizes="100vw"
      />
      <div class="bg-hero-bg absolute inset-0 z-[1]" />
    </div>
    <div
      class="relative z-[2] container mx-auto grid place-items-center px-4 py-[40px] lg:pt-[80px]"
    >
      <div class="mb-[60px]">
        <Breadcrumb>
          <BreadcrumbList class="text-primary flex items-center gap-1">
            <BreadcrumbItem>
              <BreadcrumbLink as-child>
                <NuxtLinkLocale to="/"> {{ t("home") }} </NuxtLinkLocale>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <template v-for="(page, index) in pages" :key="index">
              <BreadcrumbSeparator>
                <component
                  :is="dir === 'ltr' ? ChevronRight : ChevronLeft"
                  :size="20"
                />
              </BreadcrumbSeparator>
              <BreadcrumbItem>
                <template v-if="page.link && index !== pages.length - 1">
                  <BreadcrumbLink as-child>
                    <NuxtLinkLocale :to="page.link">
                      {{ page.name }}
                    </NuxtLinkLocale>
                  </BreadcrumbLink>
                </template>
                <BreadcrumbPage
                  v-else
                  :class="
                    index === pages.length - 1
                      ? 'text-accent font-semibold'
                      : ''
                  "
                >
                  <span
                    :class="
                      index === pages.length - 1
                        ? 'xs:inline xs:w-auto block max-w-[130px] truncate'
                        : ''
                    "
                  >
                    {{ page.name }}
                  </span>
                </BreadcrumbPage>
              </BreadcrumbItem>
            </template>
          </BreadcrumbList>
        </Breadcrumb>
      </div>
      <div
        class="title dark-text-gradient mb-6 max-w-[800px] text-center text-2xl leading-10 font-semibold text-pretty md:text-4xl md:leading-14 2xl:text-5xl 2xl:leading-16"
      >
        <slot name="title" />
      </div>
      <div class="button flex min-h-[48px] items-center justify-center">
        <slot name="button" />
      </div>
    </div>
  </section>
</template>
<style scoped>
/* Video performance optimizations */
video {
  /* Optimize video rendering */
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;

  /* Reduce repaints during scroll */
  will-change: auto;

  /* Hardware acceleration */
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}

/* Optimize the background container */
.absolute.inset-0.overflow-hidden {
  /* Contain layout changes */
  contain: layout style paint;

  /* Optimize compositing */
  isolation: isolate;
}

/* Optimize the hero section */
.hero {
  /* Contain layout and paint operations */
  contain: layout;

  /* Optimize repaints */
  will-change: auto;
}
</style>
