<template>
	<MkSpacer :content-max="700">
		<div v-if="group" class="_panel root">
			<img v-if="group.iconUrl" class="icon" :src="group.iconUrl" alt="" />
			<div v-else class="icon placeholder">
				<i class="ph-users-three ph-bold ph-lg"></i>
			</div>
			<div class="body">
				<h1>{{ group.name }}</h1>
				<div v-if="group.username" class="_monospace acct">@@{{ group.username }}</div>
				<div class="meta">{{ group.userIds.length }} members</div>
				<MkButton v-if="group.allowCalls" inline primary @click="callGroup">
					<i class="ph-phone ph-bold ph-lg"></i>
					Call
				</MkButton>
			</div>
		</div>
		<MkError v-else-if="error" @retry="fetchGroup" />
		<MkLoading v-else />
	</MkSpacer>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import MkButton from "@/components/MkButton.vue";
import MkError from "@/pages/_error_.vue";
import * as os from "@/os";
import { definePageMetadata } from "@/scripts/page-metadata";
import { useRouter } from "@/router";

const props = defineProps<{ groupName: string }>();
const router = useRouter();
const group = ref<any>(null);
const error = ref(false);

async function fetchGroup() {
	error.value = false;
	group.value = null;
	try {
		group.value = await os.api("users/groups/show-by-username", {
			username: props.groupName,
		});
	} catch {
		error.value = true;
	}
}

function callGroup() {
	router.push(`/calls?to=@@${group.value.username}`);
}

watch(() => props.groupName, fetchGroup);
onMounted(fetchGroup);

definePageMetadata({
	title: group.value?.name ?? `@@${props.groupName}`,
	icon: "ph-users-three ph-bold ph-lg",
});
</script>

<style lang="scss" scoped>
.root {
	display: flex;
	gap: 16px;
	padding: 18px;
	border-radius: 8px;
}

.icon {
	width: 72px;
	height: 72px;
	object-fit: cover;
	border-radius: 8px;
	flex: 0 0 auto;
}

.placeholder {
	display: grid;
	place-items: center;
	background: var(--panelHighlight);
}

h1 {
	margin: 0;
	font-size: 1.4rem;
}

.acct,
.meta {
	color: var(--fgTransparentWeak);
	margin: 4px 0 12px;
}
</style>
