<template>
	<MkStickyContainer>
		<template #header>
			<MkPageHeader :actions="[]" :tabs="[]" :display-back-button="true" />
		</template>
		<MkSpacer :content-max="1100">
			<div class="media-home">
				<header class="serviceHeader">
					<div class="serviceTitle">
						<i :class="icon"></i>
						<div>
							<h1>{{ title }}</h1>
							<p>{{ subtitle }}</p>
						</div>
					</div>
					<nav class="serviceNav">
						<MkA
							v-for="service in services"
							:key="service.kind"
							:to="`/${service.kind}-service`"
							class="serviceNavItem"
							:class="{ active: service.kind === kind }"
						>
							<i :class="service.icon"></i>
							<span>{{ service.label }}</span>
						</MkA>
					</nav>
					<div class="uploadActions">
						<MkButton primary @click="composeMediaPost">
							<i class="ph-upload-simple ph-bold"></i>
							Upload {{ mediaLabel }}
						</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 media posts</div>
					</div>
					<div v-else class="mediaGrid">
						<MkA
							v-for="item in results"
							:key="item.id"
							class="mediaCard"
							:to="`/${kind}-service/${item.id}`"
						>
							<div class="thumb">
								<img
									v-if="getThumbnailUrl(item)"
									:src="getThumbnailUrl(item)"
									alt=""
								/>
								<i v-else :class="icon"></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>
									<span>👍 {{ item.reactions?.["👍"] ?? 0 }}</span>
									<span>👎 {{ item.reactions?.["👎"] ?? 0 }}</span>
								</div>
							</div>
						</MkA>
					</div>
				</section>
			</div>
		</MkSpacer>
	</MkStickyContainer>
</template>

<script lang="ts" setup>
import { computed, ref, watch } 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 props = defineProps<{
	kind: "video" | "audio" | "image";
}>();

const services = [
	{ kind: "video", label: "VideoService", icon: "ph-video ph-bold" },
	{ kind: "audio", label: "AudioService", icon: "ph-music-notes ph-bold" },
	{ kind: "image", label: "ImageService", icon: "ph-image ph-bold" },
	{ kind: "karaoke", label: "KaraokeService", icon: "ph-microphone-stage ph-bold" },
] as const;

const searchQuery = ref("");
const loading = ref(false);
const results = ref<misskey.entities.Note[]>([]);
const current = computed(() => services.find((service) => service.kind === props.kind)!);
const title = computed(() => current.value.label);
const icon = computed(() => `${current.value.icon} ph-lg`);
const mediaLabel = computed(() =>
	props.kind === "video" ? "video" : props.kind === "audio" ? "audio" : "image",
);
const serviceTag = computed(() =>
	props.kind === "video" ? "#VideoService" : props.kind === "audio" ? "#AudioService" : "#ImageService",
);
const subtitle = computed(() =>
	props.kind === "video"
		? "#VideoService posts with visible video"
		: props.kind === "audio"
		? "#AudioService posts with visible audio"
		: "#ImageService posts with visible image",
);

async function composeMediaPost(ev: MouseEvent) {
	const files = await selectFiles(ev.currentTarget ?? ev.target, `${title.value} media`);
	const hasPrimary = files.some((file) => file.type.startsWith(`${props.kind}/`));
	if (!hasPrimary) {
		await os.alert({
			type: "warning",
			title: "Missing media",
			text: `Attach at least one ${mediaLabel.value} file for ${title.value}.`,
		});
	}
	os.post({
		initialText: serviceTag.value,
		initialFiles: files,
		instant: true,
	});
}

async function runSearch() {
	loading.value = true;
	try {
		results.value = (await (os.api as any)("notes/media-service-search", {
			kind: props.kind,
			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 getPrimaryFile(target: misskey.entities.Note) {
	return target.files?.find((item) => item.type.startsWith(`${props.kind}/`)) ?? null;
}

function getThumbnailImage(target: misskey.entities.Note) {
	return target.files?.find((item) => item.type.startsWith("image/")) ?? null;
}

function getThumbnailUrl(target: misskey.entities.Note): string | null {
	const thumbnail = props.kind === "video" || props.kind === "audio"
		? getThumbnailImage(target)
		: null;
	const primary = getPrimaryFile(target);
	return thumbnail?.thumbnailUrl ?? thumbnail?.url ?? primary?.thumbnailUrl ?? primary?.url ?? null;
}

watch(
	() => props.kind,
	() => {
		searchQuery.value = "";
		runSearch();
	},
	{ immediate: true },
);

definePageMetadata(
	computed(() => ({
		title: title.value,
		icon: icon.value,
	})),
);
</script>

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

.serviceHeader {
	display: grid;
	gap: 16px;
	padding: 20px;
	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);
}

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

.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;
}

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

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

.thumb {
	aspect-ratio: 16 / 9;
	display: grid;
	place-items: center;
	background: var(--acrylicBg);
	color: var(--accent);
}

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

.cardBody {
	padding: 12px;
}

.cardTitle {
	font-weight: 700;
	overflow: hidden;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.cardDescription {
	min-height: 2.6em;
	margin-top: 4px;
	color: var(--fgTransparentWeak);
	overflow: hidden;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.cardMeta {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-top: 8px;
	color: var(--fgTransparentWeak);
	font-size: 0.88em;
}

@media (max-width: 600px) {
	.searchForm {
		grid-template-columns: 1fr;
	}
}
</style>
