<script setup lang="ts">
import { useIntersectionObserver } from '@vueuse/core'
import { computed, ref, watch } from 'vue'

type Autoplay = boolean | 'visible'
interface Props {
	src?: string
	autoplay?: Autoplay
	mute?: boolean
	aspectRatio?: string
	controls?: boolean
	loop?: boolean
	status?: string
	playsinline?: boolean
}

const props = defineProps<Props>()

const videoFormat = computed(() => props.src?.split('.').pop()?.split('?').shift()?.toLowerCase() ?? 'mp4')

const videoContainer = ref<HTMLElement | null>()

const isYoutubeShort = computed(() => {
	return props.src?.includes('youtube.com/shorts/') ?? false
})

const aspectRatio = computed(
	() => {
		if (isYoutubeShort.value) { return '9/16' } // Vertical aspect ratio for Shorts
		return props.aspectRatio?.replace(':', '/') ?? '16/9'
	}
)

const video = ref<HTMLVideoElement | null>()

function play() {
	video.value?.play()
}

function pause() {
	video.value?.pause()
}

// Setup intersection observer for autoplay="visible"
if (props.autoplay === 'visible') {
	useIntersectionObserver(
		videoContainer,
		([{ isIntersecting }]) => {
			if (isIntersecting) {
				play()
			} else {
				pause()
			}
		},
		{ threshold: 0.3 } // Start playing when 30% of the video is visible
	)
}

watch(() => props.status, (status) => {
	if (status === 'play') { play() }
	if (status === 'pause') { pause() }
})

defineExpose({ play, pause })

const embedType = computed<'YouTube' | 'Vimeo' | undefined>(() => {
	const youtubeRegex = /youtube\.com|youtu\.be/
	if (youtubeRegex.test(props.src ?? '')) { return 'YouTube' }
	const vimeoRegex = /(?:player\.)?vimeo\.com/
	if (vimeoRegex.test(props.src ?? '')) { return 'Vimeo' }
	return undefined
})

const videoUrl = computed(() => {
	if (embedType.value === 'YouTube') {
		// Extract video ID from YouTube regular or Shorts URL
		let videoId = ''
		if (props.src?.includes('youtube.com/shorts/') === true) {
			videoId = props.src.split('/shorts/')[1]?.split('?')[0] ?? ''
		} else {
			videoId = props.src?.split(/v=|youtu\.be\//)[1]?.split('&')?.[0] ?? ''
		}

		const queryParams = new URLSearchParams({
			autoplay: (props.autoplay === true || props.autoplay === 'visible') ? '1' : '0',
			controls: '0',
			showinfo: '0',
			modestbranding: '1'
		})
		return `https://www.youtube.com/embed/${videoId}?${queryParams}`
	}
	if (embedType.value === 'Vimeo') {
		// Handle both regular Vimeo URLs and player.vimeo.com embed URLs
		const playerVimeoRegex = /player\.vimeo\.com\/video\/(\d+)/
		const regularVimeoRegex = /vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/)?(\d+)(?:$|\/|\?)/

		const playerMatch = props.src?.match(playerVimeoRegex) ?? null
		const regularMatch = props.src?.match(regularVimeoRegex) ?? null

		const videoId = playerMatch?.[1] ?? regularMatch?.[3]
		console.log(videoId, { playerMatch, regularMatch })
		return `https://player.vimeo.com/video/${videoId}`
	}
	return props.src
})
</script>

<template>
	<div ref="videoContainer" class="bgl_vid" :class="{ vid_empty: !src, vid_short: isYoutubeShort }">
		<iframe
			v-if="embedType" :src="videoUrl" :style="{ aspectRatio }" frameborder="0" title="Video"
			allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
			referrerpolicy="strict-origin-when-cross-origin" allowfullscreen
		/>
		<video
			v-else-if="src" ref="video" :autoplay="autoplay === true" :muted="mute" :loop="loop"
			:style="{ aspectRatio }" :controls="controls" :playsinline="playsinline"
		>
			<source :src="src" :type="`video/${videoFormat}`">
		</video>
	</div>
</template>

<style scoped>
.bgl_vid iframe,
.bgl_vid video {
	width: 100%;
	height: auto;
	display: block;
	margin: auto;
	border-radius: var(--input-border-radius);
}

.bgl_vid.vid_empty {
	padding-top: 56.25%;
	background: var(--input-bg);
	border-radius: var(--input-border-radius);
}

.bgl_vid.vid_short {
	max-width: 56.25vh;
	/* Limit width for shorts to maintain aspect ratio */
	margin: 0 auto;
}
</style>
