<template>
    <div
        class="min-h-screen bg-slate-50 dark:bg-slate-950 font-sans text-slate-900 dark:text-slate-200 selection:bg-blue-100 dark:selection:bg-blue-900 pb-12 transition-colors duration-300">

        <Transition enter-active-class="transition duration-200 ease-out" enter-from-class="opacity-0"
            enter-to-class="opacity-100" leave-active-class="transition duration-150 ease-in"
            leave-from-class="opacity-100" leave-to-class="opacity-0">
            <div v-if="selectedPost" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 overflow-y-auto"
                @click.self="selectedPost = null">

                <div class="min-h-screen px-4 py-8 flex items-start justify-center">
                    <Transition enter-active-class="transition duration-200 ease-out"
                        enter-from-class="opacity-0 scale-95 translate-y-4"
                        enter-to-class="opacity-100 scale-100 translate-y-0"
                        leave-active-class="transition duration-150 ease-in"
                        leave-from-class="opacity-100 scale-100 translate-y-0"
                        leave-to-class="opacity-0 scale-95 translate-y-4">

                        <div v-if="selectedPost"
                            class="w-full max-w-4xl bg-white dark:bg-gray-900 rounded-2xl shadow-2xl border dark:border-gray-800"
                            @click.stop>

                            <!-- Close Button Header -->
                            <div
                                class="sticky top-0 z-10 flex justify-between items-center p-4 bg-white/95 dark:bg-gray-900/95 backdrop-blur-sm border-b dark:border-gray-800 rounded-t-2xl">
                                <button
                                    class="flex items-center gap-2 text-sm font-bold text-blue-600 dark:text-blue-400 hover:underline"
                                    @click="selectedPost = null">
                                    ← BACK TO FEED
                                </button>

                                <button @click="selectedPost = null"
                                    class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                                    <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            <!-- Post Content - Same as main page -->
                            <article class="overflow-hidden">
                                <div
                                    class="relative bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-900 p-8 border-b dark:border-gray-800">
                                    <div
                                        class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-4">
                                        <span
                                            class="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider shadow-sm border border-blue-200 dark:border-blue-800">
                                            {{ selectedPost.type.replace('_', ' ') }}
                                        </span>
                                        <span
                                            class="text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2">
                                            <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                    d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                            </svg>
                                            {{ new Date(selectedPost.publicationDate ||
                                                selectedPost.publication_date).toLocaleDateString('en-US', {
                                                    year: 'numeric', month: 'long', day: 'numeric'
                                                }) }}
                                        </span>
                                    </div>

                                    <h1
                                        class="text-3xl md:text-4xl font-extrabold text-gray-900 dark:text-white mb-6 leading-tight">
                                        {{ selectedPost.title }}
                                    </h1>

                                    <div
                                        class="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 bg-white/50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700 backdrop-blur-sm">
                                        <div>
                                            <h4 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">
                                                Authors</h4>
                                            <div class="flex flex-wrap gap-2">
                                                <span v-for="(author, idx) in selectedPost.authors" :key="idx"
                                                    class="inline-flex items-center gap-1.5 text-sm font-semibold text-gray-700 dark:text-gray-200">
                                                    <span
                                                        class="w-6 h-6 rounded-full bg-indigo-100 text-indigo-600 dark:bg-indigo-900 dark:text-indigo-300 flex items-center justify-center text-xs">
                                                        {{ author.charAt(0) }}
                                                    </span>
                                                    {{ author }}
                                                </span>
                                            </div>
                                        </div>

                                        <div v-if="selectedPost.submitter">
                                            <h4 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">
                                                Submitted By</h4>
                                            <div class="flex items-center gap-3">
                                                <div
                                                    class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-xs">
                                                    {{ selectedPost.submitter.name.charAt(0) }}
                                                </div>
                                                <div>
                                                    <div class="text-sm font-bold text-gray-900 dark:text-white">{{
                                                        selectedPost.submitter.name }}</div>
                                                    <div class="text-xs text-gray-500">{{ selectedPost.submitter.role }}
                                                        • {{ selectedPost.submitter.email }}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="p-8 max-h-[60vh] overflow-y-auto">
                                    <div class="mb-10">
                                        <h3
                                            class="text-lg font-bold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                                            <svg class="w-5 h-5 text-blue-500" fill="none" viewBox="0 0 24 24"
                                                stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                    d="M4 6h16M4 12h16M4 18h7" />
                                            </svg>
                                            Abstract
                                        </h3>
                                        <p
                                            class="text-gray-700 dark:text-gray-300 leading-relaxed text-lg text-justify whitespace-pre-line">
                                            {{ selectedPost.abstractText || selectedPost.abstract }}
                                        </p>
                                    </div>

                                    <div
                                        class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8 pb-8 border-b dark:border-gray-800">
                                        <div v-if="selectedPost.tags && selectedPost.tags.length > 0">
                                            <h4 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">
                                                Tags</h4>
                                            <div class="flex flex-wrap gap-2">
                                                <span v-for="tag in selectedPost.tags" :key="tag.id"
                                                    class="px-3 py-1 rounded-lg bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 text-sm font-medium border border-gray-200 dark:border-gray-700">
                                                    #{{ tag.name }}
                                                </span>
                                            </div>
                                        </div>
                                        <div v-else class="text-sm text-gray-400 italic">No tags assigned</div>

                                        <div class="flex items-center gap-4">
                                            <div
                                                class="flex items-center bg-slate-100 dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-1.5 shadow-sm">
                                                <button @click.stop="votePost(selectedPost, 1)"
                                                    class="p-2 rounded-lg transition-all active:scale-90"
                                                    :class="selectedPost.my_vote === 'UP' ? 'text-orange-600 bg-orange-100 dark:bg-orange-900/30' : 'text-slate-400 hover:text-orange-500 hover:bg-white dark:hover:bg-slate-700'"
                                                    title="Upvote">
                                                    <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                                                        stroke="currentColor" stroke-width="2.5">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            d="M5 15l7-7 7 7" />
                                                    </svg>
                                                </button>
                                                <div class="min-w-[40px] text-center">
                                                    <span class="text-2xl font-black tracking-tight" :class="{
                                                        'text-orange-600': selectedPost.my_vote === 'UP',
                                                        'text-blue-600': selectedPost.my_vote === 'DOWN',
                                                        'text-slate-900 dark:text-white': !selectedPost.my_vote || selectedPost.my_vote === 'NONE'
                                                    }">
                                                        {{ selectedPost.rating }}
                                                    </span>
                                                </div>
                                                <button @click.stop="votePost(selectedPost, -1)"
                                                    class="p-2 rounded-lg transition-all active:scale-90"
                                                    :class="selectedPost.my_vote === 'DOWN' ? 'text-blue-600 bg-blue-100 dark:bg-blue-900/30' : 'text-slate-400 hover:text-blue-500 hover:bg-white dark:hover:bg-slate-700'"
                                                    title="Downvote">
                                                    <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                                                        stroke="currentColor" stroke-width="2.5">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            d="M19 9l-7 7-7-7" />
                                                    </svg>
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <div v-if="selectedPost.attachedFile || selectedPost.attached_file"
                                        class="mb-10 bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 rounded-xl p-5 hover:border-blue-400 transition-colors group">
                                        <div class="flex items-center justify-between">
                                            <div class="flex items-center gap-4">
                                                <div
                                                    class="p-3 bg-red-100 text-red-600 rounded-lg group-hover:scale-110 transition-transform">
                                                    <svg class="w-8 h-8" fill="none" viewBox="0 0 24 24"
                                                        stroke="currentColor">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            stroke-width="2"
                                                            d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <div class="font-bold text-gray-900 dark:text-white mb-0.5">
                                                        Attachment Available</div>
                                                    <div
                                                        class="text-xs text-gray-500 font-mono truncate max-w-[200px] md:max-w-md">
                                                        {{ getFileName(selectedPost.attachedFile ||
                                                            selectedPost.attached_file) }}
                                                    </div>
                                                </div>
                                            </div>
                                            <button @click.stop="downloadFile(selectedPost)"
                                                class="flex items-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-lg shadow-lg shadow-blue-500/30 transform hover:-translate-y-0.5 transition-all">
                                                <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24"
                                                    stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                                </svg>
                                                Download
                                            </button>
                                        </div>
                                    </div>

                                    <hr class="border-gray-100 dark:border-gray-800 mb-8">

                                    <section>
                                        <h3 class="text-xl font-bold mb-6 flex items-center gap-2">
                                            Comments
                                            <span
                                                class="bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 text-xs px-2 py-1 rounded-full">
                                                {{ selectedPost.comments?.length || 0 }}
                                            </span>
                                        </h3>
                                        <div class="space-y-3">
                                            <textarea v-model="newCommentContent" rows="3"
                                                class="w-full px-4 py-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-all text-sm"
                                                placeholder="What are your thoughts?" />
                                            <div class="flex justify-end">
                                                <button :disabled="!newCommentContent.trim()"
                                                    class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-bold px-6 py-2 rounded-lg shadow transition-all active:scale-95"
                                                    @click="submitComment">
                                                    COMMENT
                                                </button>
                                            </div>
                                        </div>

                                        <div class="mt-8 space-y-6">
                                            <div v-if="!selectedPost.comments || selectedPost.comments.length === 0"
                                                class="text-center py-8 text-gray-400 italic">
                                                Be the first to comment!
                                            </div>

                                            <div v-for="comment in selectedPost.comments" :key="comment.id"
                                                class="flex gap-4">
                                                <div
                                                    class="w-8 h-8 rounded-full bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-600 flex-shrink-0" />
                                                <div class="flex-1">
                                                    <div
                                                        class="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-xl rounded-tl-none border border-gray-100 dark:border-gray-800">
                                                        <div class="flex items-center justify-between mb-2">
                                                            <span
                                                                class="font-bold text-sm text-blue-600 dark:text-blue-400">{{
                                                                    comment.author.name }}</span>
                                                            <span class="text-[10px] text-gray-400 uppercase">{{ new
                                                                Date(comment.created_at).toLocaleDateString() }}</span>
                                                        </div>
                                                        <p
                                                            class="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">
                                                            {{ comment.content }}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </section>
                                </div>
                            </article>
                        </div>
                    </Transition>
                </div>
            </div>
        </Transition>

        <div class="container mx-auto max-w-7xl px-4 py-8 md:py-12">
            <div class="grid grid-cols-1 md:grid-cols-12 gap-8 lg:gap-12">

                <div class="md:col-span-4 lg:col-span-3 flex flex-col gap-6">

                    <div
                        class="bg-white dark:bg-slate-900 rounded-2xl p-6 shadow-sm border border-slate-200 dark:border-slate-800 transition-colors duration-300">
                        <div class="flex flex-col items-center text-center">
                            <div class="relative inline-block mb-4">
                                <div
                                    class="h-32 w-32 rounded-full border-4 border-white dark:border-slate-800 bg-slate-100 dark:bg-slate-800 overflow-hidden shadow-md ring-1 ring-slate-200 dark:ring-slate-700">
                                    <img :src="userProfile.avatarUrl" :alt="userProfile.name"
                                        class="h-full w-full object-cover transition-transform hover:scale-105">
                                </div>
                                <div class="absolute bottom-2 right-2 h-5 w-5 rounded-full border-[3px] border-white dark:border-slate-900 shadow-sm"
                                    :class="userProfile.is_active ? 'bg-emerald-500' : 'bg-gray-400'"
                                    title="Online Status" />
                            </div>

                            <h1 class="text-2xl font-bold text-slate-900 dark:text-white tracking-tight">{{
                                userProfile.name }}
                            </h1>
                            <p
                                class="text-sm font-semibold text-slate-500 dark:text-slate-400 mb-6 uppercase tracking-wide">
                                {{ userProfile.role }}
                            </p>

                            <div class="w-full space-y-3">
                                <button
                                    class="w-full py-2.5 px-4 bg-slate-900 dark:bg-blue-600 hover:bg-slate-800 dark:hover:bg-blue-500 text-white font-medium rounded-lg text-sm transition-all shadow-sm active:scale-95 cursor-pointer"
                                    @click=" activeTab = 'settings'">
                                    Edit Profile
                                </button>
                            </div>
                        </div>

                        <div class="mt-8 pt-6 border-t border-slate-100 dark:border-slate-800 space-y-4">
                            <div class="flex items-center gap-3 text-sm text-slate-600 dark:text-slate-400">
                                <svg class="w-4 h-4 text-slate-400 dark:text-slate-500 shrink-0" fill="none"
                                    viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                </svg>
                                <span class="truncate">{{ userProfile.email }}</span>
                            </div>
                            <div class="flex items-center gap-3 text-sm text-slate-600 dark:text-slate-400">
                                <svg class="w-4 h-4 text-slate-400 dark:text-slate-500 shrink-0" fill="none"
                                    viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                </svg>
                                <span>Polytechnic of Leiria</span>
                            </div>
                            <div class="flex items-center gap-3 text-sm text-slate-600 dark:text-slate-400">
                                <svg class="w-4 h-4 text-slate-400 dark:text-slate-500 shrink-0" fill="none"
                                    viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                </svg>
                                <span>Joined {{ formattedDate }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div
                            class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow-sm border border-slate-200 dark:border-slate-800 text-center hover:border-slate-300 dark:hover:border-slate-700 transition-colors">
                            <div class="text-2xl font-bold text-slate-900 dark:text-white">{{ totalCitations }}</div>
                            <div
                                class="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1">
                                Citations
                            </div>
                        </div>
                        <div
                            class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow-sm border border-slate-200 dark:border-slate-800 text-center hover:border-slate-300 dark:hover:border-slate-700 transition-colors">
                            <div class="text-2xl font-bold text-slate-900 dark:text-white">{{
                                userProfile.publications.length
                            }}</div>
                            <div
                                class="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1">
                                Papers
                            </div>
                        </div>
                    </div>
                </div>

                <div class="md:col-span-8 lg:col-span-9 space-y-6">

                    <div
                        class="bg-white dark:bg-slate-900 p-1.5 rounded-xl border border-slate-200 dark:border-slate-800 shadow-sm flex gap-1 overflow-x-auto transition-colors">
                        <button
                            :class="activeTab === 'overview' ? 'bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-white shadow-sm ring-1 ring-black/5 dark:ring-white/5' : 'text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-50 dark:hover:bg-slate-800'"
                            class="flex-1 min-w-[100px] py-2.5 px-4 rounded-lg text-lg font-semibold cursor-pointer transition-colors"
                            @click="activeTab = 'overview'">
                            Overview
                        </button>
                        <button
                            :class="activeTab === 'activity' ? 'bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-white shadow-sm ring-1 ring-black/5 dark:ring-white/5' : 'text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-50 dark:hover:bg-slate-800'"
                            class="flex-1 min-w-[100px] py-2.5 px-4 rounded-lg text-lg font-medium transition-colors cursor-pointer"
                            @click="activeTab = 'activity'">
                            Activity Log
                        </button>
                        <button
                            :class="activeTab === 'settings' ? 'bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-white shadow-sm ring-1 ring-black/5 dark:ring-white/5' : 'text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-50 dark:hover:bg-slate-800'"
                            class="flex-1 min-w-[100px] py-2.5 px-4 rounded-lg text-lg font-medium transition-colors cursor-pointer"
                            @click="activeTab = 'settings'">
                            Settings
                        </button>
                    </div>

                    <Transition mode="out-in" enter-active-class="transition duration-300 ease-out"
                        enter-from-class="transform opacity-0 translate-y-2"
                        enter-to-class="transform opacity-100 translate-y-0"
                        leave-active-class="transition duration-200 ease-in"
                        leave-from-class="transform opacity-100 translate-y-0"
                        leave-to-class="transform opacity-0 translate-y-2">
                        <div v-if="activeTab === 'overview'" key="overview" class="space-y-6">
                            <div class="flex items-center justify-between pt-2 px-1">
                                <h2 class="text-lg font-bold text-slate-900 dark:text-white flex items-center gap-2">
                                    Recent Publications
                                    <span
                                        class="bg-slate-200 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-xs font-bold px-2 py-0.5 rounded-full">
                                        {{ userProfile.publications.length }} Papers
                                    </span>
                                </h2>
                            </div>

                            <div class="flex flex-col gap-4">
                                <div
                                    class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                                    <div class="flex flex-wrap items-center gap-2 w-full sm:w-auto">
                                        <div class="relative flex-1 sm:flex-none">
                                            <input v-model="searchQuery" type="text" placeholder="Search posts..."
                                                class="w-full sm:w-48 bg-white dark:bg-gray-900 border dark:border-gray-800 rounded-lg pl-3 pr-3 py-2 text-xs font-bold outline-none focus:ring-2 focus:ring-blue-500">
                                        </div>
                                        <div class="flex items-center">
                                            <select v-model="sortBy"
                                                class="bg-white dark:bg-gray-900 border dark:border-gray-800 rounded-l-lg px-3 py-2 text-xs font-bold uppercase outline-none focus:ring-1 focus:ring-blue-500 cursor-pointer border-r-0">
                                                <option value="date">Date</option>
                                                <option value="votes">Rating</option>
                                                <option value="comments">Comments</option>
                                            </select>
                                            <button
                                                class="bg-white dark:bg-gray-900 border dark:border-gray-800 rounded-r-lg px-3 py-2 text-xs font-bold hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                                                :title="sortDesc ? 'Descending' : 'Ascending'"
                                                @click="sortDesc = !sortDesc">
                                                <span class="inline-block transition-transform duration-200"
                                                    :class="{ 'rotate-180': !sortDesc }">
                                                    ▼
                                                </span>
                                            </button>
                                        </div>

                                        <select v-model="filterType"
                                            class="bg-white dark:bg-gray-900 border dark:border-gray-800 rounded-lg px-3 py-2 text-xs font-bold uppercase outline-none focus:ring-1 focus:ring-blue-500 cursor-pointer">
                                            <option value="ALL">All Types</option>
                                            <option value="CONFERENCE_PAPER">Conference Paper</option>
                                            <option value="RESEARCH_POST">Research Post</option>
                                        </select>
                                    </div>
                                </div>

                                <div v-if="userProfile.publications.length === 0" class="...">
                                    <div
                                        class="relative overflow-hidden rounded-2xl border-2 border-dashed border-slate-300 dark:border-slate-700 bg-slate-50 dark:bg-slate-900/50 p-12 text-center hover:border-blue-400 dark:hover:border-blue-500 transition-all duration-300 group">
                                        <div class="relative z-10 flex flex-col items-center">
                                            <h3 class="text-lg font-bold text-slate-900 dark:text-white mb-1">No
                                                publications yet</h3>
                                            <button @click="goToCreatePost()"
                                                class="mt-4 inline-flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-xl shadow-lg transition-all cursor-pointer">
                                                Submit your first paper
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div v-for="post in userProfile.publications" :key="post.id"
                                    class="group bg-white dark:bg-gray-900 border dark:border-gray-800 rounded-xl p-5 shadow-sm hover:border-blue-500/50 transition-all cursor-pointer mb-4"
                                    @click="fetchPostDetail(post.id)">



                                    <div class="flex gap-4">
                                        <div
                                            class="flex flex-col items-center gap-1 text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50 p-2 rounded-lg h-fit">
                                            <button class="hover:text-blue-500 transition-colors text-lg"
                                                :class="{ 'text-orange-500': post.my_vote === 'UP' }"
                                                @click.stop="votePost(post, 1)">▲</button>
                                            <span class="text-xs font-bold">{{ post.rating }}</span>
                                            <button class="hover:text-red-500 transition-colors text-lg"
                                                :class="{ 'text-blue-500': post.my_vote === 'DOWN' }"
                                                @click.stop="votePost(post, -1)">▼</button>
                                        </div>
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2 mb-1">
                                                <span
                                                    class="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">
                                                    {{ post.type.replace('_', ' ') }}
                                                </span>
                                                <span class="text-xs text-gray-500">{{ post.publishedDate }}</span>
                                            </div>
                                            <h2 class="text-lg font-bold text-gray-800 dark:text-white mb-2">{{
                                                post.title }}</h2>
                                            <p class="text-sm text-gray-600 dark:text-gray-400 mb-4 line-clamp-2">By {{
                                                post.authors.join(', ') }}</p>
                                            <div
                                                class="flex items-center gap-4 text-xs font-bold text-gray-500 uppercase">
                                                <span>💬 {{ post.comment_count }} Comments</span>
                                                <div class="flex gap-2">
                                                    <span v-for="tag in post.tags" :key="tag.id"
                                                        class="text-blue-600 dark:text-blue-400">#{{ tag.name }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div
                                            class="flex items-center justify-end gap-2 group-hover/row:opacity-100 transition-opacity duration-200">
                                            <button
                                                class="p-2.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-all transform hover:scale-110 active:scale-95"
                                                title="Edit" @click.stop="openEditModal(user)">
                                                <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24"
                                                    stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                            </button>
                                            <button
                                                class="p-2.5 text-slate-400 hover:text-amber-600 hover:bg-white-50 dark:hover:bg-white-900/20 rounded-lg transition-all transform hover:scale-110 active:scale-95"
                                                title="Hide" @click.stop="confirmHide(post)">
                                                <svg width="16px" height="16px" viewBox="0 0 16 16"
                                                    xmlns="http://www.w3.org/2000/svg" fill="currentColor"
                                                    class="bi bi-eye">
                                                    <path
                                                        d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z" />
                                                    <path
                                                        d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <td class="p-6 pr-8 text-right">
                                <div
                                    class="flex items-center justify-end gap-2 opacity-0 group-hover/row:opacity-100 transition-opacity duration-200">
                                    <button
                                        class="p-2.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-all transform hover:scale-110 active:scale-95"
                                        title="Edit" @click.stop="openEditModal(user)">
                                        <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                        </svg>
                                    </button>
                                    <button
                                        class="p-2.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-all transform hover:scale-110 active:scale-95"
                                        title="Delete" @click.stop="confirmHide(user)">
                                        <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                </div>
                            </td>


                        </div>

                        <div v-else-if="activeTab === 'activity'" key="activity" class="space-y-4">
                            <h2 class="text-lg font-bold text-slate-900 dark:text-white px-1">User History</h2>

                            <div v-if="activityLog.length === 0"
                                class="text-center py-12 border border-dashed border-slate-200 dark:border-slate-800 rounded-xl">
                                <p class="text-slate-500">No activity recorded.</p>
                            </div>

                            <div
                                class="bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-800 overflow-hidden">
                                <div v-for="(item, index) in activityLog" :key="item.id"
                                    class="p-4 flex gap-4 border-b border-slate-100 dark:border-slate-800 last:border-0 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">

                                    <div class="flex flex-col items-center min-w-[80px] text-center pt-1">
                                        <span class="text-xs font-bold text-slate-500 uppercase">
                                            {{ new Date(item.timestamp).toLocaleDateString('en-US', {
                                                month: 'short',
                                                day: 'numeric'
                                            }) }}
                                        </span>
                                        <span class="text-[10px] text-slate-400">
                                            {{ new Date(item.timestamp).toLocaleTimeString([], {
                                                hour: '2-digit',
                                                minute: '2-digit'
                                            }) }}
                                        </span>
                                    </div>

                                    <div class="flex-1">
                                        <div class="flex items-center gap-2 mb-1">
                                            <span
                                                class="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide"
                                                :class="{
                                                    'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400': item.action.includes('UPLOAD'),
                                                    'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400': item.action.includes('COMMENT'),
                                                    'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400': item.action.includes('RATED') || item.action.includes('CORRECT'),
                                                    'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400': item.action.includes('TAG')
                                                }">
                                                {{ item.action.replace('_', ' ') }}
                                            </span>
                                            <span class="text-xs text-slate-400 font-medium">{{ item.target_type }} #{{
                                                item.target_id }}</span>
                                        </div>
                                        <p class="text-sm text-slate-700 dark:text-slate-300">
                                            {{ item.details }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div v-else-if="activeTab === 'settings'" key="settings"
                            class="bg-white dark:bg-slate-900 p-6 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800 transition-colors">
                            <h2
                                class="text-xs font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3">
                                Settings</h2>
                            <p class="text-sm text-slate-600 dark:text-slate-400">
                                Nothing here but chickens! Settings coming soon.
                            </p>
                        </div>
                    </Transition>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from "~/stores/auth-store.js";
import { storeToRefs } from "pinia";

// --- Config & Store ---
const config = useRuntimeConfig();
const api = config.public.apiBase;
const authStore = useAuthStore();
const { token } = storeToRefs(authStore);
const router = useRouter();

// --- Reactive Variables ---
const availableTags = ref<Tag[]>([]); // For tag select viewBox
const searchQuery = ref('');
const sortBy = ref('date'); // 'date' | 'votes' | 'comments'
const sortDesc = ref(true);
const filterType = ref('ALL'); // 'ALL' | 'CONFERENCE_PAPER' | 'RESEARCH_POST'
const page = ref(1);

// --- Interfaces ---
const selectedPost = ref(null);
const newCommentContent = ref('');

interface Tag {
    id: number;
    name: string;
}

// Matches response from EP12 (/api/v1/publications/my-submissions) [cite: 296]
interface ApiPublication {
    id: number;
    title: string;
    authors: string[];
    publication_date: string;
    type: string;
    rating: number; // Mapping this to citations for the UI
    comment_count: number;
    attached_file?: string;
    tags: Tag[];
    abstract?: string;
}

// Matches your UI requirements
interface UIPublication {
    id: number;
    title: string;
    abstract: string;
    publishedDate: string;
    publishedYear: string;
    citations: number;
    field: string;
}


// --- State ---
const loading = ref(true);
const activeTab = ref('overview'); // State to control visible tab
const activityLog = ref<ActivityItem[]>([]); // Store history data

const userProfile = ref({
    id: 0,
    name: 'Loading...',
    email: '',
    role: '',
    is_active: false,
    avatarUrl: '',
    biography: 'No biography provided.',
    joinDate: new Date().toISOString(),
    publications: [] as any[]
});

// --- API Actions ---
const getFileName = (fullPath: string) => {
    if (!fullPath) return null;
    return fullPath.split(/[/\\]/).pop();
};

const downloadFile = async (post: any) => {
    if (!post.attachedFile) return;
    const filename = getFileName(post.attachedFile);
    const downloadUrl = `${api}/publications/download/${filename}`; // Verifica se este endpoint existe no teu backend

    try {
        // Método simples para download (se o endpoint for público ou lidar com cookies)
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.setAttribute('download', filename || 'download');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (e) {
        console.error("Download error:", e);
    }
};

// Fetch Tags (EP23) - To populate the select box
async function fetchTags() {
    if (!token.value) return;
    try {
        const data = await $fetch<Tag[]>(`${api}/tags`, {
            method: 'GET',
            headers: { Authorization: `Bearer ${token.value}` }
        });
        availableTags.value = data || [];
    } catch (e) {
        console.error("Failed to fetch tags", e);
    }
}

const fetchPostDetail = async (id: number) => {
    loading.value = true;
    try {
        const postDetail = await $fetch(`${api}/publications/${id}`, {
            headers: { Authorization: `Bearer ${token.value}` }
        });

        selectedPost.value = postDetail;

        window.scrollTo({ top: 0, behavior: 'smooth' });

    } catch (err) {
        console.error("Failed to fetch post detail:", err);
    } finally {
        loading.value = false;
    }
};

// --- Computed ---
const totalCitations = computed(() =>
    userProfile.value.publications.reduce((sum, pub) => sum + (pub.citations || 0), 0)
);

const formattedDate = computed(() => {
    return new Date(userProfile.value.joinDate).toLocaleDateString('en-US', {
        month: 'long',
        year: 'numeric'
    });
});

// --- API Actions ---

// 1. Fetch Activity Log (EP06)
async function fetchActivityHistory() {
    if (!token.value) return;

    try {
        // GET /api/v1/me/history
        const data = await $fetch<ActivityItem[]>(`${api}/me/history`, {
            method: 'GET',
            headers: { Authorization: `Bearer ${token.value}` }
        });
        activityLog.value = data;
    } catch (error) {
        console.error("Error fetching history:", error);
    }
}

// 2. Fetch Main Profile Data (EP03 & EP12)
async function fetchProfileData() {
    if (!token.value) return;
    loading.value = true;

    try {
        const userData = await $fetch(`${api}/users/me`, {
            method: 'GET',
            headers: { Authorization: `Bearer ${token.value}` }
        });
        const publicationsData = await $fetch(`${api}/publications/me`, {
            method: 'GET',
            headers: { Authorization: `Bearer ${token.value}` },
            params: {
                page: page.value,
                sort: sortBy.value,
                order: sortDesc.value ? 'desc' : 'asc',
                type: filterType.value !== 'ALL' ? filterType.value : undefined
            }
        });

        userProfile.value = {
            ...userProfile.value,
            id: userData.id,
            name: userData.name,
            email: userData.email,
            role: userData.role,
            is_active: userData.is_active,
            avatarUrl: `https://ui-avatars.com/api/?name=${encodeURIComponent(userData.name)}&background=0D8ABC&color=fff`
        };

        userProfile.value.publications = (publicationsData as any[]).map(pub => {
            const pubDate = new Date(pub.publication_date);

            return {
                ...pub, // Manter todos os campos originais da API

                publishedDate: pubDate.toLocaleDateString(),
                publishedYear: pubDate.getFullYear().toString(),
                citations: pub.rating || 0,

                authors: pub.authors || [],
                tags: pub.tags || [],
                comment_count: pub.comment_count || 0,
                rating: pub.rating || 0
            };
        });

    } catch (error) {
        console.error("Error fetching profile:", error);
    } finally {
        loading.value = false;
    }
}

const votePost = async (targetPost, direction) => {
    if (!targetPost) return;

    let voteTypeToSend = 'NONE';
    const currentVote = targetPost.my_vote || 'NONE';

    if (direction === 1) {
        voteTypeToSend = currentVote === 'UP' ? 'NONE' : 'UP';
    } else if (direction === -1) {
        voteTypeToSend = currentVote === 'DOWN' ? 'NONE' : 'DOWN';
    }

    try {
        const response = await $fetch(`${api}/publications/${targetPost.id}/vote`, {
            method: 'PUT',
            headers: { Authorization: `Bearer ${token.value}` },
            body: { vote_type: voteTypeToSend }
        });

        targetPost.rating = response.score;
        targetPost.my_vote = response.my_vote;

        if (selectedPost.value && selectedPost.value.id === targetPost.id) {
            selectedPost.value.rating = response.score;
            selectedPost.value.my_vote = response.my_vote;
        }

    } catch (error) {
        console.error("Vote failed", error);
        alert("Failed to submit vote.");
    }
};

const confirmHide = async (post) => {
    if (!post) return;

    const confirmed = confirm(`Are you sure you want to hide the post titled "${post.title}"?`);

    if (!confirmed) return;

    try {
        await $fetch(`${api}/publications/${post.id}`, {
            method: 'DELETE',
            headers: { Authorization: `Bearer ${token.value}` }
        });

        userProfile.value.publications = userProfile.value.publications.filter(p => p.id !== post.id);

        alert("Post deleted successfully.");

    } catch (error) {
        console.error("Delete failed", error);
        alert("Failed to delete the post.");
    }
};

// --- Redirects ---
const goToCreatePost = () => {
    console.log("Navigating to create post modal...");
    router.push({
        path: '/',
        query: { openCreatePostModal: 'true' }
    });
};

// --- Lifecycle ---
onMounted(() => {
    fetchProfileData();
    fetchActivityHistory(); // Fetch history on mount
});
</script>

<style scoped>
@keyframes fadeInUp {

    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animate-fade-in-up {
    animation: fadeInUp 0.5s ease-out forwards;
}

.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>
