<template>
  <div ref="bannerElement" :class="getModifiersClass('c-banner', modifiers)" :data-video="videoUrl ?? videoId"
    :data-video-type="videoType">
    <div :class="getModifiersClass('c-banner__overlay', modifiers)"></div>
    <video v-if="showVideo && videoUrl" class="c-banner__background-video" v-bind="videoAttributes()" :src="videoUrl"
      preload="metadata">
    </video>
    <div v-else-if="showVideo && videoId" class="video-background">
      <div class="video-foreground">
        <div class="video-element"></div>
      </div>
    </div>
    <picture v-else class="c-banner__image">
      <img v-if="imageUrl" :src="imageUrl" :alt="alternativeText" />
    </picture>

    <div class="container-fluid d-flex">
      <div :class="getModifiersClass('c-banner__text', modifiers)">
        <slot />
        <div v-if="showVideoModal" class="c-banner__video-modal js-modal-trigger js-video-modal-trigger"
          :data-target="'#videoModal'" :data-video-type="videoUrl ? 'video' : 'youtube'"
          :data-video="videoUrl ?? videoId" tabindex="0">
          <span class="c-banner__video-modal__icon">{{ playVideoText }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ModifierItems } from './banner.config';
import useComponentModifiers from '../../composable/useComponentModifiers';
import { onMounted, onUnmounted, useTemplateRef } from 'vue';
import BannerVideo from './banner-video';

const { autoplay, videoUrl, videoId } = defineProps<{
  imageUrl?: string;
  alternativeText?: string;
  videoUrl?: string;
  autoplay?: boolean;
  showVideoModal?: boolean;
  showVideo?: boolean;
  playVideoText?: string;
  videoId?: string;
  videoType?: 'vimeo' | 'youtube' | 'video';
  modifiers?: ModifierItems;
}>();

const videoAttributes = () => {
  return {
    autoplay: autoplay,
    muted: autoplay,
    loop: autoplay,
    playsinline: true,
    'webkit-playsinline': true
  };
};

const bannerElement = useTemplateRef("bannerElement");
let bannerVideo: BannerVideo;

onMounted(() => {
  if (videoId || videoUrl) {
    bannerVideo = new BannerVideo(bannerElement.value as HTMLElement);
  }
});

onUnmounted(() => {
  if (bannerVideo) {
    bannerVideo.destroy();
  }
});

const { getModifiersClass } = useComponentModifiers();
</script>
