<template>
<article :id="`tid/${thread.tid}`" class="card w-100">
    <header
        ref="stickyTitleEl"
        :class="{
            'viewport-topmost-post': !supportScrollState
                && viewportTopmostPostStore.viewportTopmostPost?.cursor === currentCursor
                && viewportTopmostPostStore.viewportTopmostPost.tid === thread.tid,
            'highlight-post': highlightPostStore.isHighlightingPost(thread, 'tid'),
            'not-match-query-thread': !thread.isMatchQuery
        }"
        class="thread-title shadow-sm card-header sticky-top">
        <div class="sticky-stuck-indicator" :data-cursor="currentCursor" :data-tid="thread.tid" />
        <div class="d-flex flex-wrap gap-2">
            <div class="thread-title-inline-start w-100 d-flex flex-nowrap align-items-baseline">
                <div class="thread-title-inline-start-title-wrapper col-auto flex-shrink-1 w-100 h-100 d-flex gap-1 align-items-start">
                    <NuxtLink :to="{ name: 'posts/fid', params: { fid: thread.fid } }" class="badge btn btn-primary">
                        {{ forums[thread.fid] }}吧
                    </NuxtLink>
                    <PostBadgeThread :thread="thread" />
                    <h6 class="thread-title-inline-start-title overflow-hidden text-nowrap">{{ thread.title }}</h6>
                </div>
                <div class="col-auto d-inline-flex align-items-center gap-1 badge bg-light fs-6 p-1 pt-0 pe-2" role="group">
                    <PostBadgeCommon :post="thread" postIDKey="tid" postTypeText="主题帖" />
                    <PostBadgeTime
                        postType="主题帖" currentPostIDKey="tid"
                        postTimeKey="postedAt" timestampType="发帖时间"
                        :previousPost="previousThread" :currentPost="thread" :nextPost="nextThread"
                        class="bg-success" />
                </div>
            </div>
            <div class="d-flex justify-content-between w-100">
                <div class="col-auto d-flex gap-1 align-items-center">
                    <span v-tippy="'回复量'" class="badge bg-secondary user-select-all">
                        <FontAwesome :icon="faCommentAlt" class="me-1" />{{ thread.replyCount }}
                    </span>
                    <span v-tippy="'浏览量'" class="badge bg-info user-select-all">
                        <FontAwesome :icon="faEye" class="me-1" />{{ thread.viewCount }}
                    </span>
                    <span
                        v-if="thread.shareCount !== 0"
                        v-tippy="'分享量'" class="badge bg-info user-select-all">
                        <FontAwesome :icon="faShareAlt" class="me-1" /> {{ thread.shareCount }}
                    </span>
                    <span v-tippy="'赞踩量'" class="badge bg-info user-select-all">
                        <FontAwesome :icon="faThumbsUp" class="me-1" /> {{ thread.agreeCount }}
                        <FontAwesome :icon="faThumbsDown" class="me-1" /> {{ thread.disagreeCount }}
                    </span>
                    <span
                        v-if="thread.zan !== null"
                        v-tippy="zanTippyContent(thread.zan)" class="badge bg-info user-select-all">
                        <FontAwesome :icon="faThumbsUp" class="me-1" /> 旧版客户端赞
                    </span>
                    <span
                        v-if="thread.geolocation !== null"
                        v-tippy="'发帖位置'" class="badge bg-info user-select-all">
                        <FontAwesome :icon="faLocationArrow" class="me-1" /> {{ thread.geolocation }}
                        <!-- todo: unknown json struct -->
                    </span>
                </div>
                <div class="col-auto d-inline-flex align-items-center gap-1 badge bg-light fs-6 p-1 pe-2" role="group">
                    <address class="d-inline-flex gap-2 fs-.75">
                        <PostBadgeThreadAuthorAndLatestReplier :thread="thread" />
                    </address>
                    <PostBadgeTime
                        postType="主题帖" currentPostIDKey="tid"
                        postTimeKey="latestReplyPostedAt" timestampType="最后回复时间"
                        :previousPost="previousThread" :currentPost="thread" :nextPost="nextThread"
                        class="bg-secondary" />
                </div>
            </div>
        </div>
    </header>
    <PostRendererListReply
        v-for="(reply, index) in thread.replies" :key="reply.pid"
        :previousReply="thread.replies[index - 1]" :reply="reply"
        :nextReply="thread.replies[index + 1]" :thread="thread" :replyElementRefs="replyElementRefs" />
</article>
</template>

<script setup lang="ts">
import type { TemplateRefsList } from '@vueuse/core';
import { faCommentAlt, faEye, faLocationArrow, faShareAlt, faThumbsDown, faThumbsUp } from '@fortawesome/free-solid-svg-icons';
import { DateTime } from 'luxon';

const { thread } = defineProps<{
    previousThread?: ThreadWithGroupedSubReplies,
    thread: ThreadWithGroupedSubReplies,
    nextThread?: ThreadWithGroupedSubReplies,
    forums: ApiPosts['response']['forums'],
    replyElementRefs: TemplateRefsList<HTMLElement | null>
}>();
const hydrationStore = useHydrationStore();
const highlightPostStore = useHighlightPostStore();
const { currentCursor } = usePostPageProvision().inject();
const viewportTopmostPostStore = useViewportTopmostPostStore();
const { stickyTitleEl } = await viewportTopmostPostStore.observe({ cursor: currentCursor.value, tid: thread.tid });

// todo: fetch users info in zan.userIdList
const zanTippyContent = (zan: NonNullable<Thread['zan']>) => () => {
    const latestTimeText = () => {
        const dateTime = DateTime.fromSeconds(Number(zan.lastTime));
        if (hydrationStore.isHydratingOrSSR) {
            return setDateTimeZoneAndLocale()(dateTime)
                .toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS);
        }
        const locale = dateTime.toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS);
        if (import.meta.server)
            return locale;
        const relative = dateTime.toRelative({ round: false });

        return `
            <span class="user-select-all">${relative}</span>
            <span class="user-select-all">${locale}</span>`;
    };

    return `
        点赞量：<span class="user-select-all">${String(zan.num)}</span><br>
        最后点赞时间：${latestTimeText()}<br>
        近期点赞用户：<span class="user-select-all">${JSON.stringify(zan.userIdList)}</span>`;
};
</script>

<style scoped>
:deep(.highlight-post) {
    background-color: antiquewhite !important;
}
:deep(.fs-\.75) {
    font-size: .75rem;
}

.thread-title {
    block-size: v-bind('replyTitleStyle.insetBlockStart.remString');
    padding: .75rem 1rem .5rem;
    background-color: #f2f2f2;
    /* https://stackoverflow.com/questions/25308823/targeting-positionsticky-elements-that-are-currently-in-a-stuck-state/79471060#79471060 */
    container: thread-title / scroll-state;
}
.thread-title-inline-start {
    max-block-size: 1.6rem;
}
.thread-title-inline-start-title-wrapper {
    padding-block-start: .2rem;
}
.thread-title-inline-start-title {
    text-overflow: ellipsis;
    flex-basis: 100%;
    inline-size: 0;
}

/*
 * selecting children as a workaround to selectors in container query can only select children of the container that has set `container-type`
 * https://stackoverflow.com/questions/74602394/container-queries-why-cant-i-style-the-container-selector-in-the-container-que
 * https://github.com/w3c/csswg-drafts/issues/5979#issuecomment-2597218725
 */
.not-match-query-thread > * {
    opacity: .5;
}
:is(.not-match-query-thread:hover, .not-match-query-thread.viewport-topmost-post) > * {
    opacity: unset;
}
@media (prefers-reduced-transparency) {
    .not-match-query-thread > * {
        opacity: unset;
    }
}

@container thread-title scroll-state(stuck: block-start) {
    .not-match-query-thread > * {
        opacity: unset;
    }
    .sticky-stuck-indicator {
        --is-stuck: 'true';
    }
}
@container thread-title scroll-state(stuck: none) {
    .sticky-stuck-indicator {
        --is-stuck: 'false';
    }
}
</style>
