<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/Forum/Show.vue
//  Location: resources/js/Pages/Member/Forum/Show.vue
//
//  Full post reading experience. Structure:
//    1. Post header — hub badge, status, title, author, tags
//    2. Post body (markdown rendered)
//    3. Post actions — like post, close thread (owner), delete (owner)
//    4. Reply composer — always visible
//    5. Best Answer — pinned to top if marked
//    6. Reply thread — each reply with likes, star rating, best answer mark
//
//  Rules:
//    - All actions (like, rate, best answer) via fetch PATCH/POST — no page reload
//    - Star ratings use Unicode ★ (not icon font — Tabler is outline only)
//    - Privacy enforced — nickname always shown, never real name
//    - Both themes automatic via CSS variables
//    - Bilingual inline
//    - marked.js renders post body markdown
// ══════════════════════════════════════════════════════════════════

import { ref, computed }      from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { useAuthStore }       from '@/Stores/useAuthStore';
import AppLayout              from '@/Layouts/AppLayout.vue';
import { marked }             from 'marked';

marked.setOptions({ breaks: true, gfm: true });

const props = defineProps({
    post:        { type: Object,  required: true },
    replies:     { type: Array,   default: () => [] },
    is_owner:    { type: Boolean, default: false },
    i_liked_post:{ type: Boolean, default: false },
});

const authStore = useAuthStore();
const locale    = computed(() => authStore.locale);

// ── Post body rendered ────────────────────────────────────────────
const postBodyHtml = computed(() => marked.parse(props.post.body ?? ''));

// ── Post state ────────────────────────────────────────────────────
const postStatus   = ref(props.post.status);
const postLiked    = ref(props.i_liked_post);
const postLikes    = ref(props.post.like_count ?? 0);
const isLikingPost = ref(false);
const isClosing    = ref(false);
const showDeleteConfirm = ref(false);

// ── Replies state ─────────────────────────────────────────────────
const repliesList   = ref(props.replies.map(r => ({ ...r, showReply: false })));
const replyBody     = ref('');
const replyNick     = ref(true);
const replyError    = ref('');
const isSubmitting  = ref(false);

// Editing a reply
const editingReplyId   = ref(null);
const editingBody      = ref('');
const isUpdatingReply  = ref(false);

// ── Badge helpers ─────────────────────────────────────────────────
function badgeLabel(badge) {
    if (!badge) return '';
    const map = {
        field_expert:    locale.value === 'ar' ? 'خبير ميداني'     : 'Field Expert',
        trusted_advisor: locale.value === 'ar' ? 'مستشار موثوق'    : 'Trusted Advisor',
        helpful_voice:   locale.value === 'ar' ? 'صوت مساعد'       : 'Helpful Voice',
    };
    return map[badge.key] ?? '';
}

// ── Stars helper ──────────────────────────────────────────────────
function starClass(replyId, star) {
    const reply = repliesList.value.find(r => r.id === replyId);
    const myRating = reply?.my_rating ?? 0;
    return myRating >= star ? 'star--filled' : 'star--empty';
}

// ── CSRF helper ───────────────────────────────────────────────────
function csrf() {
    return document.querySelector('meta[name="csrf-token"]')?.content ?? '';
}

// ── Like post ─────────────────────────────────────────────────────
async function likePost() {
    if (isLikingPost.value) return;
    isLikingPost.value = true;

    try {
        const res = await fetch(route('member.forum.post.like', props.post.id), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
        });
        if (res.ok) {
            const data = await res.json();
            postLiked.value = data.liked;
            postLikes.value = data.like_count;
        }
    } finally {
        isLikingPost.value = false;
    }
}

// ── Close thread ──────────────────────────────────────────────────
async function closeThread() {
    if (isClosing.value) return;
    isClosing.value = true;

    try {
        const res = await fetch(route('member.forum.close', props.post.id), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
        });
        if (res.ok) postStatus.value = 'closed';
    } finally {
        isClosing.value = false;
    }
}

// ── Submit reply ──────────────────────────────────────────────────
async function submitReply(parentId = null) {
    if (isSubmitting.value) return;
    replyError.value = '';

    if (replyBody.value.trim().length < 10) {
        replyError.value = locale.value === 'ar'
            ? 'الرد يجب أن يكون 10 أحرف على الأقل'
            : 'Reply must be at least 10 characters.';
        return;
    }

    isSubmitting.value = true;

    try {
        const res = await fetch(route('member.forum.reply.store', props.post.id), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
            body: JSON.stringify({
                body:               replyBody.value,
                posted_as_nickname: replyNick.value,
                parent_reply_id:    parentId,
            }),
        });

        if (res.ok) {
            const data = await res.json();
            const newReply = { ...data.reply, showReply: false, children: [] };

            if (parentId) {
                const parent = repliesList.value.find(r => r.id === parentId);
                if (parent) parent.children.push(newReply);
            } else {
                repliesList.value.push(newReply);
            }
            replyBody.value = '';
        } else {
            const err = await res.json();
            replyError.value = err.errors?.body?.[0] ?? (locale.value === 'ar' ? 'حدث خطأ' : 'Something went wrong.');
        }
    } finally {
        isSubmitting.value = false;
    }
}

// ── Delete reply ──────────────────────────────────────────────────
async function deleteReply(reply) {
    try {
        const res = await fetch(route('member.forum.reply.destroy', [props.post.id, reply.id]), {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
        });
        if (res.ok) {
            const idx = repliesList.value.findIndex(r => r.id === reply.id);
            if (idx !== -1) repliesList.value.splice(idx, 1);
        }
    } catch (e) { /* silent */ }
}

// ── Start editing reply ───────────────────────────────────────────
function startEdit(reply) {
    editingReplyId.value = reply.id;
    editingBody.value    = reply.body;
}

function cancelEdit() {
    editingReplyId.value = null;
    editingBody.value    = '';
}

async function saveEdit(reply) {
    if (isUpdatingReply.value) return;
    isUpdatingReply.value = true;

    try {
        const res = await fetch(route('member.forum.reply.update', [props.post.id, reply.id]), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
            body: JSON.stringify({ body: editingBody.value }),
        });
        if (res.ok) {
            const data = await res.json();
            const idx = repliesList.value.findIndex(r => r.id === reply.id);
            if (idx !== -1) repliesList.value[idx] = { ...repliesList.value[idx], ...data.reply };
            cancelEdit();
        }
    } finally {
        isUpdatingReply.value = false;
    }
}

// ── Like reply ────────────────────────────────────────────────────
async function likeReply(reply) {
    try {
        const res = await fetch(route('member.forum.reply.like', [props.post.id, reply.id]), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
        });
        if (res.ok) {
            const data = await res.json();
            reply.i_liked    = data.liked;
            reply.like_count = data.like_count;
        }
    } catch (e) { /* silent */ }
}

// ── Rate reply ────────────────────────────────────────────────────
async function rateReply(reply, rating) {
    if (reply.is_mine) return; // cannot rate own reply
    try {
        const res = await fetch(route('member.forum.reply.rate', [props.post.id, reply.id]), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
            body: JSON.stringify({ rating }),
        });
        if (res.ok) {
            const data = await res.json();
            reply.avg_rating    = data.avg_rating;
            reply.ratings_count = data.ratings_count;
            reply.my_rating     = data.my_rating;
            if (data.badge) reply.author.badge = data.badge;
        }
    } catch (e) { /* silent */ }
}

// ── Mark best answer ──────────────────────────────────────────────
async function markBestAnswer(reply) {
    if (!props.is_owner) return;
    try {
        const res = await fetch(route('member.forum.best-answer', [props.post.id, reply.id]), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
        });
        if (res.ok) {
            // Clear all existing best answers, then set this one
            repliesList.value.forEach(r => { r.is_best_answer = false; });
            reply.is_best_answer = true;
        }
    } catch (e) { /* silent */ }
}

// ── Best answer pinned reply ──────────────────────────────────────
const bestAnswer = computed(() =>
    repliesList.value.find(r => r.is_best_answer) ?? null
);

const otherReplies = computed(() =>
    repliesList.value.filter(r => !r.is_best_answer)
);
</script>

<template>
    <AppLayout :title="post.title">
        <Head :title="post.title" />

        <div class="forum-show">

            <!-- ① POST ──────────────────────────────────────────── -->
            <article class="post-article">

                <!-- Hub + status row -->
                <div class="post-meta-top">
                    <span class="hub-badge"
                          :style="{ background: (post.hub?.color ?? '#1D9E75') + '18', color: post.hub?.color ?? '#1D9E75' }">
                        {{ locale === 'ar' ? post.hub?.name_ar : post.hub?.name_en }}
                    </span>
                    <span class="status-chip"
                          :class="postStatus === 'closed' ? 'status-chip--closed' : 'status-chip--open'">
                        {{ postStatus === 'closed'
                            ? (locale === 'ar' ? 'مغلق' : 'Thread Closed')
                            : (locale === 'ar' ? 'مفتوح' : 'Open') }}
                    </span>
                    <span v-if="post.is_pinned" class="pinned-chip">
                        <i class="ti ti-pin" aria-hidden="true"></i>
                        {{ locale === 'ar' ? 'مثبّت' : 'Pinned' }}
                    </span>
                    <Link :href="route('member.forum.index')" class="back-link">
                        <i class="ti ti-arrow-left" aria-hidden="true"></i>
                        {{ locale === 'ar' ? 'العودة' : 'Back' }}
                    </Link>
                </div>

                <!-- Title -->
                <h1 class="post-title">{{ post.title }}</h1>

                <!-- Author -->
                <div class="post-author">
                    <div class="author-avatar">
                        {{ post.author?.nickname?.charAt(0)?.toUpperCase() ?? '?' }}
                    </div>
                    <div class="author-info">
                        <div class="author-name">
                            {{ post.author?.nickname }}
                            <span v-if="post.author?.badge" class="badge-pill"
                                  :title="badgeLabel(post.author.badge)">
                                {{ post.author.badge.icon }} {{ badgeLabel(post.author.badge) }}
                            </span>
                        </div>
                        <div class="author-sub">{{ post.author?.profession }} · {{ post.created_at_full }}</div>
                    </div>
                </div>

                <!-- Tags -->
                <div v-if="post.tags?.length" class="post-tags">
                    <span v-for="tag in post.tags" :key="tag" class="tag-chip">{{ tag }}</span>
                </div>

                <!-- Body -->
                <div class="post-body md-content" v-html="postBodyHtml"></div>

                <!-- Actions row -->
                <div class="post-actions">
                    <!-- Like post -->
                    <button class="action-btn" :class="{ 'action-btn--liked': postLiked }" @click="likePost">
                        <i class="ti ti-heart" aria-hidden="true"></i>
                        {{ postLikes }}
                        {{ locale === 'ar' ? 'إعجاب' : 'Likes' }}
                    </button>

                    <!-- View count -->
                    <span class="action-stat">
                        <i class="ti ti-eye" aria-hidden="true"></i>
                        {{ post.view_count }}
                        {{ locale === 'ar' ? 'مشاهدة' : 'views' }}
                    </span>

                    <!-- Owner actions -->
                    <template v-if="is_owner">
                        <button v-if="postStatus === 'active'"
                                class="action-btn action-btn--close"
                                :disabled="isClosing"
                                @click="closeThread">
                            <i class="ti ti-lock" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'إغلاق الموضوع' : 'Close Thread' }}
                        </button>
                        <button class="action-btn action-btn--delete"
                                @click="showDeleteConfirm = true">
                            <i class="ti ti-trash" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'حذف' : 'Delete' }}
                        </button>
                    </template>
                </div>

            </article>

            <!-- ② REPLY COMPOSER ─────────────────────────────── -->
            <div v-if="postStatus === 'active'" class="composer-card">
                <p class="composer-label">
                    <i class="ti ti-message-plus" aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'شارك برأيك' : 'Share Your Opinion' }}
                </p>
                <textarea
                    v-model="replyBody"
                    class="composer-textarea"
                    :placeholder="locale === 'ar'
                        ? 'اكتب ردك هنا — شارك تجربتك أو نصيحتك...'
                        : 'Write your reply here — share your experience or advice...'"
                    rows="4"
                ></textarea>
                <p v-if="replyError" class="composer-error">{{ replyError }}</p>
                <div class="composer-footer">
                    <label class="nick-toggle">
                        <input type="checkbox" v-model="replyNick" />
                        {{ locale === 'ar' ? 'النشر بالاسم المستعار' : 'Post as nickname' }}
                    </label>
                    <button class="submit-btn"
                            :disabled="isSubmitting"
                            @click="submitReply(null)">
                        <i class="ti ti-send" aria-hidden="true"></i>
                        {{ isSubmitting
                            ? (locale === 'ar' ? 'جارٍ الإرسال...' : 'Posting...')
                            : (locale === 'ar' ? 'أرسل الرد' : 'Post Reply') }}
                    </button>
                </div>
            </div>

            <div v-else class="thread-closed-notice">
                <i class="ti ti-lock" aria-hidden="true"></i>
                {{ locale === 'ar' ? 'هذا الموضوع مغلق — لا يمكن إضافة ردود جديدة' : 'This thread is closed — no new replies allowed' }}
            </div>

            <!-- ③ REPLY COUNT HEADER ────────────────────────── -->
            <div class="replies-header">
                <span class="replies-title">
                    {{ locale === 'ar' ? 'الردود' : 'Replies' }}
                </span>
                <span class="replies-count">{{ repliesList.length }}</span>
            </div>

            <!-- ④ BEST ANSWER — pinned first ───────────────── -->
            <div v-if="bestAnswer" class="best-answer-block">
                <div class="best-answer-label">
                    <i class="ti ti-circle-check" aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'أفضل إجابة' : 'Best Answer' }}
                </div>
                <div class="reply-card reply-card--best">
                    <div class="reply-author">
                        <div class="reply-avatar">
                            {{ bestAnswer.author?.nickname?.charAt(0)?.toUpperCase() ?? '?' }}
                        </div>
                        <div class="reply-author-info">
                            <div class="reply-nick">
                                {{ bestAnswer.author?.nickname }}
                                <span v-if="bestAnswer.author?.badge" class="badge-pill"
                                      :title="badgeLabel(bestAnswer.author.badge)">
                                    {{ bestAnswer.author.badge.icon }} {{ badgeLabel(bestAnswer.author.badge) }}
                                </span>
                            </div>
                            <div class="reply-sub">{{ bestAnswer.author?.profession }} · {{ bestAnswer.created_at }}</div>
                        </div>
                    </div>
                    <div class="reply-body">{{ bestAnswer.body }}</div>
                    <div class="reply-actions">
                        <button class="action-btn action-btn--sm"
                                :class="{ 'action-btn--liked': bestAnswer.i_liked }"
                                @click="likeReply(bestAnswer)">
                            <i class="ti ti-heart" aria-hidden="true"></i>
                            {{ bestAnswer.like_count }}
                        </button>
                        <!-- Star rating -->
                        <div v-if="!bestAnswer.is_mine" class="star-row">
                            <button v-for="s in 5" :key="s"
                                    class="star-btn"
                                    :class="starClass(bestAnswer.id, s)"
                                    @click="rateReply(bestAnswer, s)">★</button>
                            <span v-if="bestAnswer.avg_rating > 0" class="avg-rating">
                                {{ bestAnswer.avg_rating }}
                                <span class="rating-count">({{ bestAnswer.ratings_count }})</span>
                            </span>
                        </div>
                        <span v-else-if="bestAnswer.avg_rating > 0" class="avg-rating">
                            ★ {{ bestAnswer.avg_rating }}
                            <span class="rating-count">({{ bestAnswer.ratings_count }})</span>
                        </span>
                    </div>
                </div>
            </div>

            <!-- ⑤ OTHER REPLIES ─────────────────────────────── -->
            <div v-if="otherReplies.length" class="replies-list">
                <div v-for="reply in otherReplies" :key="reply.id" class="reply-card">

                    <!-- Author row -->
                    <div class="reply-author">
                        <div class="reply-avatar">
                            {{ reply.author?.nickname?.charAt(0)?.toUpperCase() ?? '?' }}
                        </div>
                        <div class="reply-author-info">
                            <div class="reply-nick">
                                {{ reply.author?.nickname }}
                                <span v-if="reply.author?.badge" class="badge-pill"
                                      :title="badgeLabel(reply.author.badge)">
                                    {{ reply.author.badge.icon }} {{ badgeLabel(reply.author.badge) }}
                                </span>
                                <span v-if="reply.was_edited" class="edited-chip">
                                    {{ locale === 'ar' ? '(عُدِّل)' : '(edited)' }}
                                </span>
                            </div>
                            <div class="reply-sub">{{ reply.author?.profession }} · {{ reply.created_at }}</div>
                        </div>
                    </div>

                    <!-- Body or edit form -->
                    <template v-if="editingReplyId === reply.id">
                        <textarea v-model="editingBody" class="edit-textarea" rows="3"></textarea>
                        <div class="edit-actions">
                            <button class="cancel-btn" @click="cancelEdit">
                                {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                            </button>
                            <button class="submit-btn submit-btn--sm"
                                    :disabled="isUpdatingReply"
                                    @click="saveEdit(reply)">
                                {{ locale === 'ar' ? 'حفظ' : 'Save' }}
                            </button>
                        </div>
                    </template>
                    <div v-else class="reply-body">{{ reply.body }}</div>

                    <!-- Actions -->
                    <div class="reply-actions">
                        <!-- Like -->
                        <button class="action-btn action-btn--sm"
                                :class="{ 'action-btn--liked': reply.i_liked }"
                                @click="likeReply(reply)">
                            <i class="ti ti-heart" aria-hidden="true"></i>
                            {{ reply.like_count }}
                        </button>

                        <!-- Star rating — hidden for own replies -->
                        <div v-if="!reply.is_mine" class="star-row">
                            <button v-for="s in 5" :key="s"
                                    class="star-btn"
                                    :class="starClass(reply.id, s)"
                                    @click="rateReply(reply, s)">★</button>
                            <span v-if="reply.avg_rating > 0" class="avg-rating">
                                {{ reply.avg_rating }}
                                <span class="rating-count">({{ reply.ratings_count }})</span>
                            </span>
                        </div>
                        <span v-else-if="reply.avg_rating > 0" class="avg-rating">
                            ★ {{ reply.avg_rating }}
                            <span class="rating-count">({{ reply.ratings_count }})</span>
                        </span>

                        <!-- Reply to this reply button -->
                        <button v-if="postStatus === 'active'"
                                class="action-btn action-btn--sm action-btn--ghost"
                                @click="reply.showReply = !reply.showReply">
                            <i class="ti ti-message-circle" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'رد' : 'Reply' }}
                        </button>

                        <!-- Mark best answer (post owner) -->
                        <button v-if="is_owner && postStatus === 'active' && !reply.is_best_answer"
                                class="action-btn action-btn--sm action-btn--best"
                                @click="markBestAnswer(reply)">
                            <i class="ti ti-circle-check" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'أفضل إجابة' : 'Mark Best' }}
                        </button>

                        <!-- Own reply: edit + delete -->
                        <template v-if="reply.is_mine">
                            <button class="action-btn action-btn--sm action-btn--ghost"
                                    @click="startEdit(reply)">
                                <i class="ti ti-pencil" aria-hidden="true"></i>
                                {{ locale === 'ar' ? 'تعديل' : 'Edit' }}
                            </button>
                            <button class="action-btn action-btn--sm action-btn--delete"
                                    @click="deleteReply(reply)">
                                <i class="ti ti-trash" aria-hidden="true"></i>
                            </button>
                        </template>
                    </div>

                    <!-- Inline reply composer for nested replies -->
                    <div v-if="reply.showReply" class="nested-composer">
                        <textarea
                            v-model="replyBody"
                            class="composer-textarea composer-textarea--sm"
                            :placeholder="locale === 'ar' ? 'ردك على هذه الإجابة...' : 'Your reply to this...'"
                            rows="2"
                        ></textarea>
                        <div class="nested-composer-actions">
                            <button class="cancel-btn" @click="reply.showReply = false">
                                {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                            </button>
                            <button class="submit-btn submit-btn--sm"
                                    :disabled="isSubmitting"
                                    @click="submitReply(reply.id); reply.showReply = false">
                                {{ locale === 'ar' ? 'أرسل' : 'Reply' }}
                            </button>
                        </div>
                    </div>

                    <!-- Nested children (one level) -->
                    <div v-if="reply.children?.length" class="children-list">
                        <div v-for="child in reply.children" :key="child.id" class="reply-card reply-card--child">
                            <div class="reply-author">
                                <div class="reply-avatar reply-avatar--sm">
                                    {{ child.author?.nickname?.charAt(0)?.toUpperCase() ?? '?' }}
                                </div>
                                <div class="reply-author-info">
                                    <div class="reply-nick">{{ child.author?.nickname }}</div>
                                    <div class="reply-sub">{{ child.created_at }}</div>
                                </div>
                            </div>
                            <div class="reply-body">{{ child.body }}</div>
                            <div class="reply-actions">
                                <button class="action-btn action-btn--sm"
                                        :class="{ 'action-btn--liked': child.i_liked }"
                                        @click="likeReply(child)">
                                    <i class="ti ti-heart" aria-hidden="true"></i>
                                    {{ child.like_count }}
                                </button>
                                <div v-if="!child.is_mine" class="star-row">
                                    <button v-for="s in 5" :key="s"
                                            class="star-btn"
                                            :class="(child.my_rating ?? 0) >= s ? 'star--filled' : 'star--empty'"
                                            @click="rateReply(child, s)">★</button>
                                    <span v-if="child.avg_rating > 0" class="avg-rating">
                                        {{ child.avg_rating }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Empty replies -->
            <div v-if="!repliesList.length" class="no-replies">
                <i class="ti ti-message-dots" aria-hidden="true"></i>
                <p>{{ locale === 'ar' ? 'لا توجد ردود بعد — كن أول من يشارك' : 'No replies yet — be the first to share' }}</p>
            </div>

        </div>

        <!-- Delete post confirmation modal -->
        <Transition name="modal">
            <div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
                <div class="modal-box" @click.stop>
                    <div class="modal-icon">🗑️</div>
                    <p class="modal-title">
                        {{ locale === 'ar' ? 'حذف الموضوع؟' : 'Delete this post?' }}
                    </p>
                    <p class="modal-body">
                        {{ locale === 'ar'
                            ? 'سيتم حذف الموضوع وجميع الردود نهائياً.'
                            : 'The post and all replies will be permanently deleted.' }}
                    </p>
                    <div class="modal-actions">
                        <button class="modal-cancel" @click="showDeleteConfirm = false">
                            {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                        </button>
                        <Link :href="route('member.forum.destroy', post.id)"
                              method="delete" as="button"
                              class="modal-confirm">
                            {{ locale === 'ar' ? 'نعم، احذف' : 'Yes, Delete' }}
                        </Link>
                    </div>
                </div>
            </div>
        </Transition>

    </AppLayout>
</template>

<style scoped>
/* ── Layout ──────────────────────────────────────────────────── */
.forum-show {
    display: flex; flex-direction: column; gap: 12px;
    padding: 12px 12px 80px;
    max-width: 1250px;
    margin: 0 auto;
    width: 100%;
}

/* ── Post article ────────────────────────────────────────────── */
.post-article {
    background: var(--color-surface);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: 18px 16px;
    display: flex; flex-direction: column; gap: 12px;
}

.post-meta-top {
    display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
}

.hub-badge {
    font-size: 9px; font-weight: 700;
    padding: 2px 8px; border-radius: var(--radius-pill);
}

.status-chip {
    font-size: 9px; font-weight: 700;
    padding: 2px 8px; border-radius: var(--radius-pill);
}
.status-chip--open   { background: #dcfce7; color: #166534; }
.status-chip--closed { background: #f1f5f9; color: #64748b; }
[data-theme="dark"] .status-chip--open   { background: #052e16; color: #86efac; }
[data-theme="dark"] .status-chip--closed { background: #1e2937; color: #94a3b8; }

.pinned-chip {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 9px; font-weight: 700;
    color: var(--color-primary); background: var(--color-primary-soft);
    padding: 2px 7px; border-radius: var(--radius-pill);
}

.back-link {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: 11px; color: var(--color-text-muted); text-decoration: none;
    margin-left: auto; transition: color var(--transition-fast);
}
[dir="rtl"] .back-link { margin-left: 0; margin-right: auto; }
.back-link:hover { color: var(--color-primary); }

.post-title {
    font-size: 20px; font-weight: 800;
    color: var(--color-text-primary); line-height: 1.35; margin: 0;
}

.post-author {
    display: flex; align-items: center; gap: 10px;
}
.author-avatar {
    width: 36px; height: 36px; border-radius: 50%;
    background: var(--color-primary); color: #fff;
    font-size: 13px; font-weight: 800;
    display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.author-info { display: flex; flex-direction: column; gap: 2px; }
.author-name { font-size: 13px; font-weight: 700; color: var(--color-text-primary); display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.author-sub  { font-size: 11px; color: var(--color-text-muted); }

.badge-pill {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 9px; font-weight: 700;
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    padding: 1px 6px; border-radius: var(--radius-pill);
    color: var(--color-text-secondary);
}

.post-tags {
    display: flex; gap: 5px; flex-wrap: wrap;
}
.tag-chip {
    font-size: 10px; color: var(--color-text-muted);
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-pill); padding: 2px 8px;
}

/* ── Post body markdown ──────────────────────────────────────── */
.post-body {
    font-size: 14px; color: var(--color-text-secondary);
    line-height: 1.75;
}
.md-content :deep(h2), .md-content :deep(h3) { font-size: 15px; font-weight: 700; color: var(--color-text-primary); margin: 12px 0 6px; }
.md-content :deep(p)   { margin: 0 0 10px; }
.md-content :deep(ul), .md-content :deep(ol) { padding-left: 18px; margin: 8px 0; }
[dir="rtl"] .md-content :deep(ul), [dir="rtl"] .md-content :deep(ol) { padding-left: 0; padding-right: 18px; }
.md-content :deep(strong) { font-weight: 700; color: var(--color-text-primary); }
.md-content :deep(table) { width: 100%; border-collapse: collapse; font-size: 12px; overflow-x: auto; display: block; min-width: 400px; }
.md-content :deep(th), .md-content :deep(td) { padding: 7px 10px; border: 1px solid var(--color-border); text-align: left; }
[dir="rtl"] .md-content :deep(th), [dir="rtl"] .md-content :deep(td) { text-align: right; }
.md-content :deep(th) { background: var(--color-surface-alt); font-weight: 700; }

/* ── Post actions ────────────────────────────────────────────── */
.post-actions {
    display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
    padding-top: 8px; border-top: 1px solid var(--color-border-light);
}
.action-btn {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: 12px; font-weight: 600;
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); padding: 5px 10px;
    color: var(--color-text-secondary); cursor: pointer;
    transition: all var(--transition-fast);
}
.action-btn:hover { border-color: var(--color-primary); color: var(--color-primary); }
.action-btn--liked { color: #ef4444; border-color: #ef4444; background: #fef2f2; }
[data-theme="dark"] .action-btn--liked { background: #2d0000; }
.action-btn--close  { color: #b45309; }
.action-btn--delete { color: #dc2626; }
.action-btn--delete:hover { border-color: #dc2626; background: #fef2f2; }
.action-btn--ghost  { background: transparent; border-color: transparent; }
.action-btn--ghost:hover { background: var(--color-surface-alt); border-color: var(--color-border); }
.action-btn--best { color: #166534; border-color: #166534; }
.action-btn--sm { font-size: 11px; padding: 4px 8px; }
.action-stat {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 11px; color: var(--color-text-muted);
}

/* ── Composer ────────────────────────────────────────────────── */
.composer-card {
    background: var(--color-surface);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-lg); padding: 14px 16px;
    display: flex; flex-direction: column; gap: 10px;
}
.composer-label {
    font-size: 12px; font-weight: 700; color: var(--color-text-secondary);
    display: flex; align-items: center; gap: 5px; margin: 0;
}
.composer-textarea {
    width: 100%; padding: 10px 12px;
    font-size: 13px; line-height: 1.6;
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    color: var(--color-text-primary);
    resize: vertical; outline: none;
    transition: border-color var(--transition-fast);
    font-family: inherit;
}
.composer-textarea:focus { border-color: var(--color-primary); }
.composer-textarea--sm { font-size: 12px; }
.composer-error { font-size: 11px; color: #dc2626; margin: 0; }
.composer-footer {
    display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;
}
.nick-toggle {
    display: flex; align-items: center; gap: 6px;
    font-size: 11px; color: var(--color-text-muted); cursor: pointer;
}
.submit-btn {
    display: inline-flex; align-items: center; gap: 5px;
    background: var(--color-primary); color: #fff;
    font-size: 12px; font-weight: 700;
    padding: 8px 14px; border: none;
    border-radius: var(--radius-md); cursor: pointer;
    transition: background var(--transition-fast);
}
.submit-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.submit-btn:disabled { opacity: 0.55; cursor: not-allowed; }
.submit-btn--sm { padding: 5px 10px; font-size: 11px; }

/* ── Thread closed notice ────────────────────────────────────── */
.thread-closed-notice {
    display: flex; align-items: center; gap: 8px;
    background: var(--color-surface-alt);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-md); padding: 12px 14px;
    font-size: 12px; color: var(--color-text-muted);
}

/* ── Replies header ──────────────────────────────────────────── */
.replies-header {
    display: flex; align-items: center; gap: 8px;
    padding: 4px 0;
}
.replies-title {
    font-size: 13px; font-weight: 700; color: var(--color-text-secondary);
}
.replies-count {
    font-size: 10px; font-weight: 700;
    background: var(--color-primary-soft); color: var(--color-primary);
    padding: 1px 7px; border-radius: var(--radius-pill);
}

/* ── Best answer block ───────────────────────────────────────── */
.best-answer-block {
    display: flex; flex-direction: column; gap: 6px;
}
.best-answer-label {
    display: inline-flex; align-items: center; gap: 5px;
    font-size: 11px; font-weight: 700; color: #166534;
}
[data-theme="dark"] .best-answer-label { color: #86efac; }

/* ── Reply cards ─────────────────────────────────────────────── */
.replies-list {
    display: flex; flex-direction: column; gap: 8px;
}

.reply-card {
    background: var(--color-surface);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-md); padding: 12px 14px;
    display: flex; flex-direction: column; gap: 8px;
}
.reply-card--best {
    border-color: #166534; background: #f0fdf4;
}
[data-theme="dark"] .reply-card--best { background: #052e16; border-color: #166534; }
.reply-card--child {
    background: var(--color-surface-alt);
    border-style: dashed;
    margin-left: 20px;
}
[dir="rtl"] .reply-card--child { margin-left: 0; margin-right: 20px; }

.reply-author {
    display: flex; align-items: center; gap: 8px;
}
.reply-avatar {
    width: 28px; height: 28px; border-radius: 50%;
    background: var(--color-primary); color: #fff;
    font-size: 10px; font-weight: 800;
    display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.reply-avatar--sm { width: 22px; height: 22px; font-size: 9px; }
.reply-author-info { display: flex; flex-direction: column; gap: 1px; }
.reply-nick {
    font-size: 12px; font-weight: 700; color: var(--color-text-primary);
    display: flex; align-items: center; gap: 5px; flex-wrap: wrap;
}
.reply-sub { font-size: 10px; color: var(--color-text-muted); }
.edited-chip { font-size: 9px; color: var(--color-text-muted); font-weight: 400; }

.reply-body {
    font-size: 13px; color: var(--color-text-secondary);
    line-height: 1.65; white-space: pre-wrap;
}

.reply-actions {
    display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
    padding-top: 4px; border-top: 1px solid var(--color-border-light);
}

/* ── Star rating ─────────────────────────────────────────────── */
.star-row {
    display: flex; align-items: center; gap: 2px;
}
.star-btn {
    font-size: 14px; line-height: 1;
    background: none; border: none; padding: 0;
    cursor: pointer; transition: transform 0.1s;
}
.star-btn:hover { transform: scale(1.2); }
.star--filled { color: #F5A623; }
.star--empty  { color: var(--color-border); }
.avg-rating {
    font-size: 11px; font-weight: 700; color: #F5A623; margin-left: 4px;
}
[dir="rtl"] .avg-rating { margin-left: 0; margin-right: 4px; }
.rating-count { font-size: 10px; color: var(--color-text-muted); font-weight: 400; }

/* ── Nested composer ─────────────────────────────────────────── */
.nested-composer {
    display: flex; flex-direction: column; gap: 6px;
    padding: 8px; background: var(--color-surface-alt);
    border-radius: var(--radius-sm);
}
.nested-composer-actions {
    display: flex; gap: 6px; justify-content: flex-end;
}
[dir="rtl"] .nested-composer-actions { justify-content: flex-start; }

.children-list {
    display: flex; flex-direction: column; gap: 6px;
}

/* ── Edit form ───────────────────────────────────────────────── */
.edit-textarea {
    width: 100%; padding: 8px 10px; font-size: 12px;
    background: var(--color-surface-alt); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); color: var(--color-text-primary);
    resize: vertical; outline: none; font-family: inherit;
}
.edit-textarea:focus { border-color: var(--color-primary); }
.edit-actions { display: flex; gap: 6px; justify-content: flex-end; }
[dir="rtl"] .edit-actions { justify-content: flex-start; }
.cancel-btn {
    padding: 5px 10px; font-size: 11px; font-weight: 600;
    background: var(--color-surface); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); color: var(--color-text-secondary); cursor: pointer;
}

/* ── No replies ──────────────────────────────────────────────── */
.no-replies {
    display: flex; flex-direction: column; align-items: center;
    text-align: center; gap: 6px; padding: 30px 16px;
    background: var(--color-surface); border: 0.5px solid var(--color-border);
    border-radius: var(--radius-md);
    color: var(--color-text-muted); font-size: 13px;
}
.no-replies i { font-size: 28px; }
.no-replies p { margin: 0; }

/* ── Delete modal ────────────────────────────────────────────── */
.modal-overlay {
    position: fixed; inset: 0; background: rgba(0,0,0,0.55);
    z-index: var(--z-modal);
    display: flex; align-items: center; justify-content: center; padding: 20px;
}
.modal-box {
    background: var(--color-surface); border-radius: var(--radius-lg);
    padding: 24px 20px; max-width: 340px; width: 100%;
    display: flex; flex-direction: column; gap: 10px;
    box-shadow: var(--shadow-float);
}
.modal-icon { font-size: 28px; text-align: center; }
.modal-title { font-size: 15px; font-weight: 700; color: var(--color-text-primary); text-align: center; margin: 0; }
.modal-body  { font-size: 12px; color: var(--color-text-secondary); text-align: center; margin: 0; line-height: 1.5; }
.modal-actions { display: flex; gap: 8px; margin-top: 4px; }
.modal-cancel {
    flex: 1; padding: 9px; font-size: 12px; font-weight: 600;
    background: var(--color-surface-alt); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); color: var(--color-text-secondary); cursor: pointer;
}
.modal-confirm {
    flex: 1; display: inline-flex; align-items: center; justify-content: center;
    padding: 9px; font-size: 12px; font-weight: 700;
    background: #dc2626; color: #fff; border: none;
    border-radius: var(--radius-sm); cursor: pointer; text-decoration: none;
}
.modal-confirm:hover { background: #b91c1c; }
.modal-enter-active, .modal-leave-active { transition: opacity 0.2s ease; }
.modal-enter-from, .modal-leave-to { opacity: 0; }

/* ── Desktop ─────────────────────────────────────────────────── */
@media (min-width: 768px) {
    .forum-show { padding: 24px 0; }
    .post-title { font-size: 24px; }
    .post-body  { font-size: 15px; }
}
</style>
