<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'

interface Message {
	mesage: string
	type: string
}
defineProps<{
	src: string
	title?: string
	height?: string
	width?: string
	name?: string
	sandbox?: string
	allow?: string
	allowfullscreen?: boolean
	loading?: 'eager' | 'lazy'
	referrerpolicy?: string
	marginwidth?: number
	marginheight?: number
	scrolling?: 'yes' | 'no' | 'auto'
	csp?: string
	srcset?: string
}>()

const emit = defineEmits<{
	(message: 'message', payload: Message): void
	(load: 'load', payload: Event): void
}>()

const iframe = ref<HTMLIFrameElement>()

function handleMessage(event: MessageEvent) {
	emit('message', event.data as Message)
}

function handleMessageWrapper(event: MessageEvent) {
	if (event.source === iframe.value?.contentWindow) {
		handleMessage(event)
	}
}

onMounted(() => {
	window.addEventListener('message', handleMessageWrapper)
})

onBeforeUnmount(() => {
	window.removeEventListener('message', handleMessageWrapper)
})

const contentWindow = () => iframe.value?.contentWindow as Window | null

/** The underlying <iframe> element (e.g. for getBoundingClientRect). */
const element = () => iframe.value ?? null

defineExpose({ contentWindow, element })
</script>

<template>
	<iframe
		ref="iframe"
		:src
		:title
		frameborder="0"
		:width="width ?? '100%'"
		:height="height ?? '100%'"
		allowpaymentrequest="true"
		:marginwidth
		:marginheight
		:csp
		:scrolling
		:srcset
		style="display:block; border:none;"
		@load="$event => emit('load', $event)"
	/>
</template>
