<!--
SPDX-FileCopyrightText: syuilo and misskey-project
SPDX-License-Identifier: AGPL-3.0-only
-->

<template>
<component
	:is="'MkA'" v-if="self" ref="el" style="word-break: break-all;" class="_link" :to="url.substring(local.length)" :rel="rel ?? 'nofollow noopener'" :target="target"
	:behavior="props.navigationBehavior"
	:title="url"
	@click.stop
>
	<slot></slot>
	<i v-if="target === '_blank'" class="ti ti-external-link" :class="$style.icon"></i>
</component>
<component
	:is="'a'" v-else ref="el" style="word-break: break-all;" class="_link" :rel="rel ?? 'nofollow noopener popup=false'" :target="target"
	:behavior="props.navigationBehavior"
	:title="url"
	@click="promptConfirm()"
	@click.stop
>
	<slot></slot>
	<i v-if="target === '_blank'" class="ti ti-external-link" :class="$style.icon"></i>
</component>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, ref } from 'vue';
import { url as local } from '@/config.js';
import { useTooltip } from '@/scripts/use-tooltip.js';
import * as os from '@/os.js';
import { isEnabledUrlPreview } from '@/instance.js';
import { MkABehavior } from '@/components/global/MkA.vue';
import { i18n } from '@/i18n.js';

const props = withDefaults(defineProps<{
	url: string;
	rel?: null | string;
	navigationBehavior?: MkABehavior;
}>(), {
});

const self = props.url.startsWith(local);
const target = self ? null : '_blank';

const el = ref<HTMLElement | { $el: HTMLElement }>();

if (isEnabledUrlPreview.value) {
	useTooltip(el, (showing) => {
		const { dispose } = os.popup(defineAsyncComponent(() => import('@/components/MkUrlPreviewPopup.vue')), {
			showing,
			url: props.url,
			source: el.value instanceof HTMLElement ? el.value : el.value?.$el,
		}, {
			closed: () => dispose(),
		});
	});
}

async function promptConfirm() {
	const { canceled } = await os.confirm({
		type: 'question',
		text: i18n.tsx.confirmRemoteUrl({ x: props.url }),
		plain: true,
	});
	if (canceled) return;
	window.open(props.url, '_blank', 'nofollow noopener popup=false');
}
</script>

<style lang="scss" module>
.icon {
	padding-left: 2px;
	font-size: .9em;
}
</style>
