<template>
	<MkStickyContainer>
		<template #header>
			<MkPageHeader :actions="[]" :tabs="[]" :display-back-button="true" />
		</template>
		<MkSpacer :content-max="1100">
			<div class="karaoke-home">
				<header class="serviceHeader">
					<div class="serviceTitle">
						<i class="ph-microphone-stage ph-bold ph-lg"></i>
						<div>
							<h1>KaraokeService</h1>
							<p>#KaraokeService songs with accompaniment, timed lyrics, pitch, and scoring data</p>
						</div>
					</div>
					<nav class="serviceNav">
						<MkA
							v-for="service in services"
							:key="service.kind"
							:to="service.to"
							class="serviceNavItem"
							:class="{ active: service.kind === 'karaoke' }"
						>
							<i :class="service.icon"></i>
							<span>{{ service.label }}</span>
						</MkA>
					</nav>
					<div class="uploadActions">
						<MkButton primary @click="composeKaraokePost">
							<i class="ph-upload-simple ph-bold"></i>
							Upload song kit
						</MkButton>
					</div>
				</header>

				<section class="searchPanel">
					<form class="searchForm" @submit.prevent="runSearch">
						<MkInput v-model="searchQuery">
							<template #prefix><i class="ph-magnifying-glass ph-bold"></i></template>
							<template #label>Search</template>
						</MkInput>
						<MkButton primary type="submit">Search</MkButton>
					</form>
				</section>

				<section class="contentSection">
					<div class="sectionHead">
						<h2>{{ searchQuery.trim() ? "Search results" : "Latest" }}</h2>
						<button class="_button refresh" :disabled="loading" @click="runSearch">
							<i class="ph-arrow-clockwise ph-bold"></i>
						</button>
					</div>
					<div v-if="loading" class="loading"><MkLoading /></div>
					<div v-else-if="results.length === 0" class="_fullinfo">
						<div>No karaoke songs</div>
					</div>
					<div v-else class="songGrid">
						<MkA
							v-for="item in results"
							:key="item.id"
							class="songCard"
							:to="`/karaoke-service/${item.id}`"
						>
							<div class="thumb">
								<video
									v-if="getVideoUrl(item)"
									:src="getVideoUrl(item)"
									muted
									playsinline
								></video>
								<i v-else class="ph-microphone-stage ph-bold ph-lg"></i>
							</div>
							<div class="cardBody">
								<div class="cardTitle">{{ getNoteTitle(item) }}</div>
								<div v-if="getNoteDescription(item)" class="cardDescription">
									{{ getNoteDescription(item) }}
								</div>
								<div class="cardMeta">
									<span>@{{ item.user.username }}</span>
									<span v-if="item.viewCount != null">
										<i class="ph-eye ph-bold"></i>
										{{ item.viewCount }}
									</span>
								</div>
							</div>
						</MkA>
					</div>
				</section>
			</div>
		</MkSpacer>
	</MkStickyContainer>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import * as misskey from "iceshrimp-sdk";
import MkButton from "@/components/MkButton.vue";
import MkInput from "@/components/form/input.vue";
import * as os from "@/os";
import { definePageMetadata } from "@/scripts/page-metadata";
import { selectFiles } from "@/scripts/select-file";

const searchQuery = ref("");
const loading = ref(false);
const results = ref<misskey.entities.Note[]>([]);
const services = [
	{ kind: "video", label: "VideoService", icon: "ph-video ph-bold", to: "/video-service" },
	{ kind: "audio", label: "AudioService", icon: "ph-music-notes ph-bold", to: "/audio-service" },
	{ kind: "image", label: "ImageService", icon: "ph-image ph-bold", to: "/image-service" },
	{ kind: "karaoke", label: "KaraokeService", icon: "ph-microphone-stage ph-bold", to: "/karaoke-service" },
] as const;

async function composeKaraokePost(ev: MouseEvent) {
	const files = await selectFiles(ev.currentTarget ?? ev.target, "KaraokeService files: accompaniment, lyrics, pitch, scoring");
	const hasAudio = files.some((file) => file.type.startsWith("audio/"));
	const hasLyrics = files.some((file) => {
		const name = file.name.toLowerCase();
		const text = `${file.name} ${file.comment ?? ""}`.toLowerCase();
		return name.endsWith(".lrc") || text.includes("lyrics") || text.includes("lyric") || text.includes("歌詞");
	});
	const hasPitch = files.some((file) => {
		const name = file.name.toLowerCase();
		const text = `${file.name} ${file.comment ?? ""}`.toLowerCase();
		return name.endsWith(".mid") || name.endsWith(".midi") || text.includes("pitch") || text.includes("音程");
	});
	const hasScoring = files.some((file) => {
		const text = `${file.name} ${file.comment ?? ""}`.toLowerCase();
		return text.includes("score") || text.includes("scoring") || text.includes("採点");
	});
	if (!hasAudio || !hasLyrics || !hasPitch || !hasScoring) {
		await os.alert({
			type: "warning",
			title: "Check karaoke files",
			text: "KaraokeService needs accompaniment audio, lyrics, pitch data, and scoring data. You can still adjust attachments before posting.",
		});
	}
	os.post({
		initialText: "#KaraokeService",
		initialFiles: files,
		instant: true,
	});
}

async function runSearch() {
	loading.value = true;
	try {
		results.value = (await (os.api as any)("notes/karaoke-service-search", {
			query: searchQuery.value,
			limit: 48,
		})) as misskey.entities.Note[];
	} finally {
		loading.value = false;
	}
}

function splitNoteText(target: misskey.entities.Note): string[] {
	return (target.text ?? "").replace(/\r\n/g, "\n").split("\n");
}

function getNoteTitle(target: misskey.entities.Note): string {
	return splitNoteText(target)[0]?.trim() || "(no title)";
}

function getNoteDescription(target: misskey.entities.Note): string {
	return splitNoteText(target).slice(1).join("\n").trim();
}

function getVideoUrl(target: misskey.entities.Note): string | null {
	const video = target.files?.find((item) => item.type.startsWith("video/"));
	return video?.thumbnailUrl ?? video?.url ?? null;
}

runSearch();

definePageMetadata(
	computed(() => ({
		title: "KaraokeService",
		icon: "ph-microphone-stage ph-bold ph-lg",
	})),
);
</script>

<style lang="scss" scoped>
.karaoke-home {
	display: grid;
	gap: 20px;
}

.serviceHeader,
.searchPanel,
.contentSection {
	padding: 16px;
	border-radius: 8px;
	background: var(--panel);
	border: solid 1px var(--divider);
}

.serviceTitle {
	display: flex;
	gap: 14px;
	align-items: center;
}

.serviceTitle > i {
	display: grid;
	place-items: center;
	width: 48px;
	height: 48px;
	border-radius: 8px;
	color: var(--accent);
	background: var(--accentedBg);
}

.serviceTitle h1 {
	margin: 0;
	font-size: 1.35rem;
	line-height: 1.2;
}

.serviceTitle p {
	margin: 4px 0 0;
	color: var(--fgTransparentWeak);
}

.serviceNav {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.uploadActions {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.serviceNavItem {
	display: inline-flex;
	align-items: center;
	gap: 8px;
	padding: 8px 12px;
	border-radius: 8px;
	background: var(--buttonBg);
	color: var(--fg);
}

.serviceNavItem.active {
	color: var(--accent);
	background: var(--accentedBg);
}

.searchForm {
	display: grid;
	grid-template-columns: 1fr auto;
	gap: 12px;
	align-items: end;
}

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

.sectionHead h2 {
	margin: 0;
	font-size: 1rem;
}

.refresh {
	width: 36px;
	height: 36px;
	border-radius: 8px;
	background: var(--buttonBg);
}

.loading {
	padding: 24px;
}

.songGrid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
	gap: 12px;
}

.songCard {
	display: grid;
	grid-template-rows: 130px 1fr;
	overflow: hidden;
	border-radius: 8px;
	background: var(--bg);
	border: solid 1px var(--divider);
	color: var(--fg);
}

.thumb {
	display: grid;
	place-items: center;
	background: #111;
	color: #fff;
}

.thumb video {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.cardBody {
	display: grid;
	gap: 6px;
	padding: 12px;
}

.cardTitle {
	font-weight: 700;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.cardDescription {
	color: var(--fgTransparentWeak);
	font-size: 0.9em;
	line-height: 1.35;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.cardMeta {
	display: flex;
	gap: 10px;
	color: var(--fgTransparentWeak);
	font-size: 0.85em;
}
</style>
