<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { AppBskyActorDefs } from '@atcute/bluesky'

import Modal from '@/components/UI/BaseModal.vue'
import Button from '@/components/UI/BaseButton.vue'
import ProfileRow from '@/components/Profile/ProfileRow.vue'
import SkeletonLoader from '@/components/UI/SkeletonLoader.vue'

import { useInfiniteScroll } from '@/composables/useInfiniteScroll'

const props = defineProps<{
	title: string
	users: AppBskyActorDefs.ProfileView[]
	loading?: boolean
	onReachedBottom?: () => void
	hasMore?: boolean
}>()

const emit = defineEmits<{
	(e: 'close'): void
}>()

const sentinel = ref<HTMLElement | null>(null)

const { setup } = useInfiniteScroll(sentinel, () => {
	if (props.onReachedBottom && !props.loading) {
		props.onReachedBottom()
	}
})

onMounted(() => {
	setup()
})
</script>

<template>
	<Modal :title="title" width="640px" @close="emit('close')" edge-to-edge>
		<div class="user-list" role="list">
			<template v-if="loading && users.length === 0">
				<SkeletonLoader v-for="n in 6" :key="n" />
			</template>

			<ProfileRow v-for="user in users" :key="user.did" :profile="user" @click="emit('close')" />

			<div ref="sentinel" class="sentinel"></div>

			<div v-if="loading && users.length > 0" class="loading-more">
				<p>loading more...</p>
			</div>
			<div v-if="!hasMore && users.length > 0" class="loading-more">
				<p>that's all!</p>
			</div>
		</div>

		<template #footer>
			<Button variant="primary" @click="emit('close')">Close</Button>
		</template>
	</Modal>
</template>

<style lang="scss" scoped>
.user-list {
	display: flex;
	flex-direction: column;
	max-height: 60vh;
	overflow-y: auto;
}

.sentinel {
	height: 1px;
}

.loading-more {
	opacity: 0.6;
	text-align: center;
	padding: 1rem;
}
</style>
