<script setup lang="ts">
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
}>()

import { onBeforeUnmount, onMounted } from 'vue'

const iframe = $ref<HTMLIFrameElement>()

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

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

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

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

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

defineExpose({ contentWindow })
</script>

<template>
	<iframe
		ref="iframe"
		:src
		:title
		frameborder="none"
		:width
		:height
		allowpaymentrequest="true"
		:marginwidth
		:marginheight
		:csp
		:scrolling
		:srcset
		@load="$event => emit('load', $event)"
	/>
</template>
