<template>
	<section v-if="visible" class="adPreroll _panel">
		<div class="head">
			<div class="label">
				<i class="ph-megaphone-simple-bold ph-lg"></i>
				<span>Advertisement</span>
			</div>
			<MkButton :disabled="remaining > 0" @click="finish">
				{{ remaining > 0 ? `${remaining}s` : "Skip" }}
			</MkButton>
		</div>
		<MkLoading v-if="loading" />
		<MkNote v-else-if="note" :note="note" />
	</section>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, ref, watch } from "vue";
import * as misskey from "iceshrimp-sdk";
import MkButton from "@/components/MkButton.vue";
import MkLoading from "@/components/global/MkLoading.vue";
import MkNote from "@/components/MkNote.vue";
import * as os from "@/os";
import { $i } from "@/account";
import { defaultStore } from "@/store";

const props = defineProps<{
	service: "video" | "audio" | "image" | "karaoke" | "lua4frozen";
	tag?: string | null;
}>();

const emit = defineEmits<{
	(ev: "done"): void;
}>();

const note = ref<misskey.entities.Note | null>(null);
const loading = ref(false);
const visible = ref(false);
const remaining = ref(5);
let timer: number | null = null;

function finish() {
	if (timer != null) window.clearInterval(timer);
	timer = null;
	visible.value = false;
	emit("done");
}

function startTimer() {
	remaining.value = 5;
	timer = window.setInterval(() => {
		remaining.value -= 1;
		if (remaining.value <= 0 && timer != null) {
			window.clearInterval(timer);
			timer = null;
		}
	}, 1000);
}

async function load() {
	loading.value = true;
	visible.value = true;
	try {
		note.value = (await (os.api as any)("promo/show", {
			service: props.service,
			tag: props.tag || null,
			hideExplicit: defaultStore.state.nsfw === "force",
		})) as misskey.entities.Note | null;

		if (!note.value) {
			finish();
			return;
		}

		if ($i) {
			await os.api("promo/read", { noteId: note.value.id });
		}
		startTimer();
	} finally {
		loading.value = false;
	}
}

watch(
	() => [props.service, props.tag],
	() => {
		if (timer != null) window.clearInterval(timer);
		load();
	},
	{ immediate: true },
);

onBeforeUnmount(() => {
	if (timer != null) window.clearInterval(timer);
});
</script>

<style lang="scss" scoped>
.adPreroll {
	padding: 16px;
	border-radius: 8px;
	border: solid 1px var(--divider);
}

.head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	margin-bottom: 12px;
}

.label {
	display: inline-flex;
	align-items: center;
	gap: 8px;
	font-weight: 700;
	color: var(--accent);
}
</style>
