<template>
	<div ref="html" v-sanitize="source" class="html" />
</template>

<script lang="ts">
import dompurify from 'dompurify'
import linkifyHtml from 'linkify-html'
import { mapActions } from 'pinia'
import { t } from '@nextcloud/l10n'
import { timeToSeconds } from '../../utils/time.ts'
import { usePlayer } from '../../store/player.ts'

export default {
	name: 'SafeHtml',
	directives: {
		sanitize: {
			mounted(el, binding) {
				el.innerHTML = dompurify
					.sanitize(
						linkifyHtml(binding.value, {
							nl2br: true,
							target: '_blank',
						}),
					)
					.replace(
						/(([0-9]?[0-9]):)?([0-5]?[0-9]):([0-5][0-9])/g,
						(
							match,
							noop: string,
							hours: string,
							minutes: string,
							seconds: string,
						) =>
							`<seekable time="${timeToSeconds(
								parseInt(hours),
								parseInt(minutes),
								parseInt(seconds),
							)}" title="${t('repod', 'Skip to {match}', { match })}">${
								match
							}</seekable>`,
					)
			},
		},
	},
	props: {
		source: {
			type: String,
			required: true,
		},
	},
	mounted() {
		const seekables = (this.$refs.html as HTMLElement).querySelectorAll(
			'seekable',
		)
		for (const seekable of seekables) {
			seekable.addEventListener('click', (event) => {
				this.seek(
					parseInt(
						(event.target as HTMLElement).getAttribute('time') || '',
					),
				)
				this.play()
			})
		}
	},
	methods: {
		...mapActions(usePlayer, ['play', 'seek']),
	},
}
</script>

<style>
.html a,
seekable {
	cursor: pointer;
	text-decoration: underline;
}
</style>
