<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { postService } from '../services/postService'
import { aiService } from '../services/aiService'
import { useConfirm } from 'primevue/useconfirm'
import { useToast } from 'primevue/usetoast'
import Button from 'primevue/button'
import Dialog from 'primevue/dialog'
import InputText from 'primevue/inputtext'
import DatePicker from 'primevue/datepicker'
import ConfirmDialog from 'primevue/confirmdialog'
import Toast from 'primevue/toast'
import JSZip from 'jszip'

const confirm = useConfirm()
const toast = useToast()

const API_URL = import.meta.env.VITE_API_URL || ''

// --- Timezone helpers ---
// Normalize a date to noon local time before converting to ISO
// This prevents day-shift when UTC offset crosses midnight
function toLocalNoonISO(date) {
    const d = new Date(date)
    d.setHours(12, 0, 0, 0)
    return d.toISOString()
}

// Parse date string from API — ensure it's treated as UTC
// Server may return "2026-02-16T21:00:00" without Z, which browsers
// would interpret as local time. We append Z to force UTC parsing.
function parseUTCDate(dateStr) {
    if (typeof dateStr === 'string' && !dateStr.endsWith('Z') && !/[+-]\d{2}(:\d{2})?$/.test(dateStr)) {
        return new Date(dateStr + 'Z')
    }
    return new Date(dateStr)
}

// --- Calendar state ---
const currentDate = ref(new Date()) // tracks currently viewed month
const viewMode = ref('month') // 'month' | 'week' | 'day'
const selectedDay = ref(null)
const posts = ref([])
const loading = ref(false)

// --- New/Edit post dialog ---
const showPostDialog = ref(false)
const editingPost = ref(null) // null = create, object = edit
const postForm = ref({ date: new Date(), topic: '' })

// --- Day names (Monday first) ---
const dayNames = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
const monthNames = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']

// --- Computeds ---
const currentMonthName = computed(() => monthNames[currentDate.value.getMonth()])
const currentYear = computed(() => currentDate.value.getFullYear())

const headerTitle = computed(() => {
    if (viewMode.value === 'day' && selectedDay.value) {
        const d = selectedDay.value
        return `${d.getDate()} ${monthNames[d.getMonth()]} ${d.getFullYear()}`
    }
    if (viewMode.value === 'week' && selectedDay.value) {
        const ws = getWeekStart(selectedDay.value)
        const we = new Date(ws)
        we.setDate(we.getDate() + 6)
        const m1 = monthNames[ws.getMonth()].substring(0, 3)
        const m2 = monthNames[we.getMonth()].substring(0, 3)
        if (ws.getMonth() === we.getMonth()) {
            return `${ws.getDate()} – ${we.getDate()} ${m1} ${ws.getFullYear()}`
        }
        return `${ws.getDate()} ${m1} – ${we.getDate()} ${m2} ${we.getFullYear()}`
    }
    return `${currentMonthName.value} ${currentYear.value}`
})

// Get Monday of the week containing a date
function getWeekStart(date) {
    const d = new Date(date)
    const day = d.getDay()
    const diff = d.getDate() - day + (day === 0 ? -6 : 1) // Monday
    d.setDate(diff)
    d.setHours(0, 0, 0, 0)
    return d
}

// Calendar grid cells for month view
const calendarDays = computed(() => {
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth()

    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)

    // Day of week for first day (0=Sun, we want Mon=0)
    let startDow = firstDay.getDay() - 1
    if (startDow < 0) startDow = 6

    const days = []

    // Previous month padding
    for (let i = startDow - 1; i >= 0; i--) {
        const d = new Date(year, month, -i)
        days.push({ date: d, isOtherMonth: true })
    }

    // Current month
    for (let i = 1; i <= lastDay.getDate(); i++) {
        const d = new Date(year, month, i)
        days.push({ date: d, isOtherMonth: false })
    }

    // Next month padding (fill to 42 cells = 6 rows)
    const remaining = 42 - days.length
    for (let i = 1; i <= remaining; i++) {
        const d = new Date(year, month + 1, i)
        days.push({ date: d, isOtherMonth: true })
    }

    return days
})

// Week view days
const weekDays = computed(() => {
    const start = selectedDay.value ? getWeekStart(selectedDay.value) : getWeekStart(new Date())
    const days = []
    for (let i = 0; i < 7; i++) {
        const d = new Date(start)
        d.setDate(d.getDate() + i)
        days.push({ date: d, isOtherMonth: false })
    }
    return days
})

// Today check
const isToday = (date) => {
    const today = new Date()
    return date.getDate() === today.getDate() &&
        date.getMonth() === today.getMonth() &&
        date.getFullYear() === today.getFullYear()
}

const isSameDay = (a, b) => {
    if (!a || !b) return false
    return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear()
}

// Posts for a given date
const getPostsForDate = (date) => {
    return posts.value.filter(p => {
        const pd = parseUTCDate(p.date)
        return isSameDay(pd, date)
    })
}

// Day view posts
const dayPosts = computed(() => {
    if (!selectedDay.value) return []
    return getPostsForDate(selectedDay.value)
})

// --- API calls ---
async function fetchPosts() {
    loading.value = true
    try {
        const year = currentDate.value.getFullYear()
        const month = currentDate.value.getMonth()
        // Fetch the full visible range (prev month padding + next)
        const dateFrom = toLocalNoonISO(new Date(year, month - 1, 1))
        const dateTo = toLocalNoonISO(new Date(year, month + 2, 0))
        const result = await postService.getPosts(dateFrom, dateTo)
        posts.value = Array.isArray(result) ? result : []
    } catch (e) {
        console.error('Failed to fetch posts', e)
        posts.value = []
    } finally {
        loading.value = false
    }
}

// --- Navigation ---
function prevPeriod() {
    if (viewMode.value === 'month') {
        const d = new Date(currentDate.value)
        d.setMonth(d.getMonth() - 1)
        currentDate.value = d
    } else if (viewMode.value === 'week') {
        const d = new Date(selectedDay.value || new Date())
        d.setDate(d.getDate() - 7)
        selectedDay.value = d
        currentDate.value = new Date(d.getFullYear(), d.getMonth(), 1)
    } else {
        const d = new Date(selectedDay.value || new Date())
        d.setDate(d.getDate() - 1)
        selectedDay.value = d
        currentDate.value = new Date(d.getFullYear(), d.getMonth(), 1)
    }
}

function nextPeriod() {
    if (viewMode.value === 'month') {
        const d = new Date(currentDate.value)
        d.setMonth(d.getMonth() + 1)
        currentDate.value = d
    } else if (viewMode.value === 'week') {
        const d = new Date(selectedDay.value || new Date())
        d.setDate(d.getDate() + 7)
        selectedDay.value = d
        currentDate.value = new Date(d.getFullYear(), d.getMonth(), 1)
    } else {
        const d = new Date(selectedDay.value || new Date())
        d.setDate(d.getDate() + 1)
        selectedDay.value = d
        currentDate.value = new Date(d.getFullYear(), d.getMonth(), 1)
    }
}

function goToday() {
    const today = new Date()
    currentDate.value = new Date(today.getFullYear(), today.getMonth(), 1)
    selectedDay.value = today
}

function selectDay(dayObj) {
    selectedDay.value = dayObj.date
    if (viewMode.value === 'month') {
        viewMode.value = 'day'
    }
}

// --- Post CRUD ---
function openNewPostDialog(date) {
    editingPost.value = null
    postForm.value = {
        date: date ? new Date(date) : new Date(),
        topic: ''
    }
    showPostDialog.value = true
}

function openEditPostDialog(post) {
    editingPost.value = post
    postForm.value = {
        date: parseUTCDate(post.date),
        topic: post.topic
    }
    showPostDialog.value = true
}

async function savePost() {
    if (!postForm.value.topic.trim()) {
        toast.add({ severity: 'warn', summary: 'Тема обязательна', life: 2000 })
        return
    }
    try {
        if (editingPost.value) {
            await postService.updatePost(editingPost.value.id, {
                date: toLocalNoonISO(postForm.value.date),
                topic: postForm.value.topic
            })
            toast.add({ severity: 'success', summary: 'Пост обновлён', life: 2000 })
        } else {
            await postService.createPost({
                date: toLocalNoonISO(postForm.value.date),
                topic: postForm.value.topic,
                generation_ids: []
            })
            toast.add({ severity: 'success', summary: 'Пост создан', life: 2000 })
        }
        showPostDialog.value = false
        await fetchPosts()
    } catch (e) {
        console.error('Save post failed', e)
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Не удалось сохранить', life: 3000 })
    }
}

function deletePost(post) {
    confirm.require({
        message: `Удалить пост "${post.topic}"?`,
        header: 'Удаление поста',
        icon: 'pi pi-trash',
        acceptClass: 'p-button-danger',
        accept: async () => {
            try {
                await postService.deletePost(post.id)
                toast.add({ severity: 'info', summary: 'Удалено', life: 2000 })
                await fetchPosts()
            } catch (e) {
                console.error('Delete post failed', e)
            }
        }
    })
}

async function removeGenerationFromPost(post, genId) {
    try {
        await postService.removeGeneration(post.id, genId)
        // Optimistic update
        const idx = post.generation_ids.indexOf(genId)
        if (idx > -1) post.generation_ids.splice(idx, 1)
        toast.add({ severity: 'info', summary: 'Генерация удалена из поста', life: 2000 })
    } catch (e) {
        console.error(e)
    }
}

// --- Download Post Assets ---
const isDownloading = ref(false)

async function downloadPostAssets(post) {
    const ids = post.generation_ids || []
    if (ids.length === 0) return
    isDownloading.value = true
    try {
        const user = JSON.parse(localStorage.getItem('user'))
        const headers = {}
        if (user && user.access_token) headers['Authorization'] = `Bearer ${user.access_token}`
        else if (user && user.token) headers['Authorization'] = `${user.tokenType} ${user.token}`
        const projectId = localStorage.getItem('active_project_id')
        if (projectId) headers['X-Project-ID'] = projectId

        // Multi-file ZIP (if > 1)
        if (ids.length > 1) {
            const zip = new JSZip()
            // Sanitize topic for filename
            const safeTopic = (post.topic || 'post').replace(/[^a-z0-9_\-а-яё ]/gi, '').trim().replace(/\s+/g, '_')
            const folderName = `${safeTopic}_assets`

            let successCount = 0

            await Promise.all(ids.map(async (assetId) => {
                try {
                    const url = API_URL + '/assets/' + assetId
                    const resp = await fetch(url, { headers })
                    if (!resp.ok) return
                    const blob = await resp.blob()
                    const mime = blob.type
                    const ext = mime.split('/')[1] || 'png'
                    zip.file(`${assetId}.${ext}`, blob)
                    successCount++
                } catch (err) {
                    console.error('Failed to zip asset', assetId, err)
                }
            }))

            if (successCount === 0) throw new Error('No images available for zip')

            const content = await zip.generateAsync({ type: 'blob' })
            const filename = `${folderName}.zip`

            const a = document.createElement('a')
            a.href = URL.createObjectURL(content)
            a.download = filename
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(a.href)

            toast.add({ severity: 'success', summary: 'Архив создан', detail: `Скачано ${successCount} файлов`, life: 3000 })

        } else {
            // Single File
            const assetId = ids[0]
            const url = API_URL + '/assets/' + assetId
            const resp = await fetch(url, { headers })
            const blob = await resp.blob()

            const file = new File([blob], assetId + '.png', { type: blob.type || 'image/png' })
            const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent) || navigator.maxTouchPoints > 1
            if (isMobile && navigator.canShare && navigator.canShare({ files: [file] })) {
                await navigator.share({ files: [file] })
            } else {
                const a = document.createElement('a')
                a.href = URL.createObjectURL(file)
                a.download = file.name
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
                URL.revokeObjectURL(a.href)
            }
            toast.add({ severity: 'success', summary: 'Скачано', detail: `Файл сохранен`, life: 2000 })
        }
    } catch (e) {
        console.error('Download failed', e)
        toast.add({ severity: 'error', summary: 'Ошибка скачивания', life: 3000 })
    } finally {
        isDownloading.value = false
    }
}

// --- Watchers ---
watch(currentDate, fetchPosts)

onMounted(() => {
    selectedDay.value = new Date()
    fetchPosts()
})

// --- Generation Picker ---
const showGenPicker = ref(false)
const genPickerPost = ref(null)
const availableGenerations = ref([])
const selectedGenIds = ref(new Set())
const genLoading = ref(false)
const genLoadingMore = ref(false)
const genOffset = ref(0)
const genHasMore = ref(true)
const GEN_LIMIT = 30

function openGenPicker(post) {
    genPickerPost.value = post
    selectedGenIds.value = new Set()
    availableGenerations.value = []
    genOffset.value = 0
    genHasMore.value = true
    showGenPicker.value = true
    loadGenerations(true)
}

async function loadGenerations(initial = false) {
    if (initial) {
        genLoading.value = true
        genOffset.value = 0
    } else {
        genLoadingMore.value = true
    }
    try {
        const response = await aiService.getGenerations(GEN_LIMIT, genOffset.value)
        const list = response && response.generations ? response.generations : (Array.isArray(response) ? response : [])
        if (initial) {
            availableGenerations.value = list
        } else {
            availableGenerations.value.push(...list)
        }
        genOffset.value += list.length
        genHasMore.value = list.length >= GEN_LIMIT
    } catch (e) {
        console.error('Load generations failed', e)
    } finally {
        genLoading.value = false
        genLoadingMore.value = false
    }
}

function toggleGenSelection(assetId) {
    const s = new Set(selectedGenIds.value)
    if (s.has(assetId)) s.delete(assetId)
    else s.add(assetId)
    selectedGenIds.value = s
}

async function confirmAddGenerations() {
    if (!genPickerPost.value || selectedGenIds.value.size === 0) return
    try {
        await postService.addGenerations(genPickerPost.value.id, [...selectedGenIds.value])
        toast.add({ severity: 'success', summary: `Добавлено ${selectedGenIds.value.size} изображений`, life: 2000 })
        showGenPicker.value = false
        await fetchPosts()
    } catch (e) {
        console.error('Add generations failed', e)
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Не удалось добавить', life: 3000 })
    }
}

function onGenPickerScroll(e) {
    const el = e.target
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 100 && genHasMore.value && !genLoadingMore.value) {
        loadGenerations(false)
    }
}

// --- Image Preview ---
const previewVisible = ref(false)
const previewImages = ref([])
const previewIndex = ref(0)

const previewCurrent = computed(() => previewImages.value[previewIndex.value] || null)

function openPreview(assetIds, clickedId) {
    previewImages.value = assetIds.map(id => API_URL + '/assets/' + id)
    const idx = assetIds.indexOf(clickedId)
    previewIndex.value = idx >= 0 ? idx : 0
    previewVisible.value = true
}

function previewNav(dir) {
    if (previewImages.value.length === 0) return
    let i = previewIndex.value + dir
    if (i < 0) i = previewImages.value.length - 1
    if (i >= previewImages.value.length) i = 0
    previewIndex.value = i
}

function onPreviewKey(e) {
    if (!previewVisible.value) return
    if (e.key === 'ArrowLeft') { e.preventDefault(); previewNav(-1) }
    else if (e.key === 'ArrowRight') { e.preventDefault(); previewNav(1) }
    else if (e.key === 'Escape') { previewVisible.value = false }
}

watch(previewVisible, (v) => {
    if (v) window.addEventListener('keydown', onPreviewKey)
    else window.removeEventListener('keydown', onPreviewKey)
})

onBeforeUnmount(() => {
    window.removeEventListener('keydown', onPreviewKey)
})
</script>

<template>
    <div class="flex flex-col h-full w-full bg-slate-900 text-slate-100 font-sans overflow-hidden">
        <ConfirmDialog />
        <Toast />

        <!-- Header -->
        <header
            class="h-16 border-b border-white/5 flex items-center justify-between px-6 bg-slate-900/80 backdrop-blur z-20 shrink-0">
            <div class="flex items-center gap-4">
                <h1 class="text-lg font-bold text-slate-200">📅 Content plan</h1>
            </div>

            <div class="flex items-center gap-3">
                <!-- Navigation Arrows -->
                <div class="flex items-center gap-1">
                    <button @click="prevPeriod"
                        class="w-8 h-8 rounded-lg bg-slate-800 border border-white/10 flex items-center justify-center text-slate-400 hover:text-white hover:bg-slate-700 transition-all">
                        <i class="pi pi-chevron-left text-xs"></i>
                    </button>
                    <button @click="goToday"
                        class="px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 border border-white/10 text-slate-400 hover:text-white hover:bg-slate-700 transition-all">
                        Сегодня
                    </button>
                    <button @click="nextPeriod"
                        class="w-8 h-8 rounded-lg bg-slate-800 border border-white/10 flex items-center justify-center text-slate-400 hover:text-white hover:bg-slate-700 transition-all">
                        <i class="pi pi-chevron-right text-xs"></i>
                    </button>
                </div>

                <!-- Period Title -->
                <span class="text-sm font-semibold text-slate-200 min-w-[180px] text-center hidden md:block">{{
                    headerTitle }}</span>

                <!-- View Toggle -->
                <div class="flex bg-slate-800 rounded-lg p-1 border border-white/5">
                    <button @click="viewMode = 'month'"
                        class="px-3 py-1.5 rounded-md text-xs font-medium transition-all"
                        :class="viewMode === 'month' ? 'bg-violet-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'">
                        Месяц
                    </button>
                    <button @click="viewMode = 'week'; if (!selectedDay) selectedDay = new Date()"
                        class="px-3 py-1.5 rounded-md text-xs font-medium transition-all"
                        :class="viewMode === 'week' ? 'bg-violet-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'">
                        Неделя
                    </button>
                    <button @click="viewMode = 'day'; if (!selectedDay) selectedDay = new Date()"
                        class="px-3 py-1.5 rounded-md text-xs font-medium transition-all"
                        :class="viewMode === 'day' ? 'bg-violet-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'">
                        День
                    </button>
                </div>
            </div>
        </header>

        <!-- Mobile Period Title -->
        <div class="md:hidden text-center py-2 text-sm font-semibold text-slate-200 border-b border-white/5">
            {{ headerTitle }}
        </div>

        <!-- Content Area -->
        <div class="flex-1 overflow-y-auto custom-scrollbar">

            <!-- ====== MONTH VIEW ====== -->
            <div v-if="viewMode === 'month'" class="h-full flex flex-col p-2 md:p-4">
                <!-- Day headers -->
                <div class="grid grid-cols-7 mb-1">
                    <div v-for="d in dayNames" :key="d"
                        class="text-center text-[10px] font-bold text-slate-500 uppercase tracking-wider py-2">
                        {{ d }}
                    </div>
                </div>

                <!-- Day cells -->
                <div class="grid grid-cols-7 flex-1 gap-px bg-white/5 rounded-xl overflow-hidden">
                    <div v-for="(dayObj, idx) in calendarDays" :key="idx" @click="selectDay(dayObj)" :class="[
                        'bg-slate-900 p-1.5 min-h-[80px] md:min-h-[100px] cursor-pointer transition-all hover:bg-slate-800/80 relative group',
                        dayObj.isOtherMonth ? 'opacity-30' : '',
                        isToday(dayObj.date) ? 'ring-1 ring-violet-500/50 ring-inset' : '',
                        isSameDay(dayObj.date, selectedDay) ? 'bg-violet-900/20' : ''
                    ]">
                        <!-- Day number -->
                        <div class="flex items-center justify-between mb-1">
                            <span :class="[
                                'text-xs font-bold w-6 h-6 flex items-center justify-center rounded-full',
                                isToday(dayObj.date) ? 'bg-violet-600 text-white' : 'text-slate-400'
                            ]">
                                {{ dayObj.date.getDate() }}
                            </span>
                            <!-- Add button (show on hover) -->
                            <button v-if="!dayObj.isOtherMonth" @click.stop="openNewPostDialog(dayObj.date)"
                                class="w-5 h-5 rounded-md bg-violet-600/30 text-violet-300 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-violet-600/50">
                                <i class="pi pi-plus" style="font-size: 8px"></i>
                            </button>
                        </div>

                        <!-- Posts in cell -->
                        <div class="flex flex-col gap-0.5 overflow-hidden">
                            <div v-for="post in getPostsForDate(dayObj.date)" :key="post.id"
                                @click.stop="openEditPostDialog(post)"
                                class="px-1.5 py-0.5 rounded text-[10px] font-medium truncate transition-all hover:scale-[1.02] cursor-pointer"
                                :class="post.generation_ids?.length > 0
                                    ? 'bg-violet-600/30 text-violet-200 border border-violet-500/20'
                                    : 'bg-slate-700/50 text-slate-300 border border-white/5'">
                                {{ post.topic }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ====== WEEK VIEW ====== -->
            <div v-else-if="viewMode === 'week'" class="h-full flex flex-col p-2 md:p-4">
                <!-- Day headers -->
                <div class="grid grid-cols-7 mb-1">
                    <div v-for="(dayObj, idx) in weekDays" :key="idx"
                        class="text-center text-[10px] font-bold uppercase tracking-wider py-2"
                        :class="isToday(dayObj.date) ? 'text-violet-400' : 'text-slate-500'">
                        {{ dayNames[idx] }} {{ dayObj.date.getDate() }}
                    </div>
                </div>

                <!-- Day columns -->
                <div class="grid grid-cols-7 flex-1 gap-px bg-white/5 rounded-xl overflow-hidden">
                    <div v-for="(dayObj, idx) in weekDays" :key="idx"
                        @click="selectedDay = dayObj.date; viewMode = 'day'" :class="[
                            'bg-slate-900 p-2 min-h-[300px] cursor-pointer transition-all hover:bg-slate-800/80 relative group',
                            isToday(dayObj.date) ? 'ring-1 ring-violet-500/50 ring-inset' : '',
                            isSameDay(dayObj.date, selectedDay) ? 'bg-violet-900/20' : ''
                        ]">
                        <!-- Add button -->
                        <button @click.stop="openNewPostDialog(dayObj.date)"
                            class="w-full mb-2 py-1 rounded-lg border border-dashed border-white/10 text-slate-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity hover:border-violet-500/30 hover:text-violet-400">
                            <i class="pi pi-plus mr-1" style="font-size: 9px"></i> Добавить
                        </button>

                        <!-- Posts -->
                        <div class="flex flex-col gap-2">
                            <div v-for="post in getPostsForDate(dayObj.date)" :key="post.id"
                                class="bg-slate-800/80 rounded-lg border border-white/5 p-2 hover:border-violet-500/30 transition-all cursor-pointer"
                                @click.stop="openEditPostDialog(post)">
                                <p class="text-xs font-semibold text-slate-200 mb-1 line-clamp-2">{{ post.topic }}</p>

                                <!-- Generation thumbnails -->
                                <div v-if="post.generation_ids?.length > 0" class="flex gap-1 flex-wrap">
                                    <img v-for="gid in post.generation_ids.slice(0, 4)" :key="gid"
                                        :src="API_URL + '/assets/' + gid + '?thumbnail=true'"
                                        class="w-8 h-8 rounded object-cover border border-white/10" />
                                    <span v-if="post.generation_ids.length > 4"
                                        class="w-8 h-8 rounded bg-slate-700 border border-white/10 flex items-center justify-center text-[10px] text-slate-400">
                                        +{{ post.generation_ids.length - 4 }}
                                    </span>
                                </div>

                                <!-- Actions -->
                                <div class="flex gap-1 mt-1.5 justify-end">
                                    <button @click.stop="openGenPicker(post)"
                                        class="w-5 h-5 rounded bg-violet-500/10 text-violet-400 flex items-center justify-center hover:bg-violet-500/20 transition-colors"
                                        title="Добавить изображения">
                                        <i class="pi pi-images" style="font-size: 9px"></i>
                                    </button>
                                    <button @click.stop="deletePost(post)"
                                        class="w-5 h-5 rounded bg-red-500/10 text-red-400 flex items-center justify-center hover:bg-red-500/20 transition-colors">
                                        <i class="pi pi-trash" style="font-size: 9px"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ====== DAY VIEW ====== -->
            <div v-else class="max-w-3xl mx-auto p-4 md:p-8">
                <!-- Add Post Button -->
                <button @click="openNewPostDialog(selectedDay)"
                    class="w-full mb-6 py-3 rounded-xl border-2 border-dashed border-white/10 text-slate-400 text-sm font-medium hover:border-violet-500/40 hover:text-violet-300 hover:bg-violet-500/5 transition-all">
                    <i class="pi pi-plus mr-2"></i> Новый пост
                </button>

                <!-- No posts -->
                <div v-if="dayPosts.length === 0 && !loading"
                    class="flex flex-col items-center justify-center py-20 text-slate-500 opacity-60">
                    <i class="pi pi-calendar text-5xl mb-4"></i>
                    <p>Нет постов на этот день</p>
                </div>

                <!-- Posts list -->
                <div class="flex flex-col gap-4">
                    <div v-for="post in dayPosts" :key="post.id"
                        class="bg-slate-800/60 rounded-2xl border border-white/5 p-5 hover:border-violet-500/20 transition-all">

                        <!-- Header: topic + date -->
                        <div class="flex items-start justify-between mb-3">
                            <div class="flex-1">
                                <h3 class="text-base font-bold text-slate-100 mb-1">{{ post.topic }}</h3>
                                <p class="text-xs text-slate-500">
                                    {{ parseUTCDate(post.date).toLocaleDateString('ru-RU', {
                                        weekday: 'long', day: 'numeric', month: 'long'
                                    }) }}
                                </p>
                            </div>
                            <button @click="deletePost(post)"
                                class="w-8 h-8 rounded-lg bg-slate-700/50 text-slate-400 flex items-center justify-center hover:bg-red-600/30 hover:text-red-300 transition-all"
                                title="Удалить">
                                <i class="pi pi-trash text-xs"></i>
                            </button>
                        </div>

                        <!-- Images section header with actions -->
                        <div class="flex items-center justify-between mb-2">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                                Изображения ({{ post.generation_ids?.length || 0 }})
                            </label>
                            <div class="flex gap-1">
                                <Button icon="pi pi-download" label="Скачать" size="small" text :loading="isDownloading"
                                    :disabled="!post.generation_ids?.length" @click="downloadPostAssets(post)"
                                    class="!text-slate-400 hover:!text-white !text-xs !py-1" />
                                <Button icon="pi pi-plus" label="Добавить" size="small" text
                                    @click="openGenPicker(post)"
                                    class="!text-violet-400 hover:!text-violet-300 !text-xs !py-1" />
                                <Button icon="pi pi-pencil" size="small" text @click="openEditPostDialog(post)"
                                    class="!text-slate-400 hover:!text-white !text-xs !py-1" title="Редактировать" />
                            </div>
                        </div>

                        <!-- Generation grid -->
                        <div v-if="post.generation_ids?.length > 0"
                            class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
                            <div v-for="gid in post.generation_ids" :key="gid"
                                class="aspect-square relative rounded-xl overflow-hidden bg-slate-900 border border-white/5 group/img">
                                <img :src="API_URL + '/assets/' + gid + '?thumbnail=true'"
                                    class="w-full h-full object-cover cursor-pointer"
                                    @click="openPreview(post.generation_ids, gid)" />
                                <button @click="removeGenerationFromPost(post, gid)"
                                    class="absolute top-1 right-1 w-5 h-5 rounded-md bg-red-600/80 text-white flex items-center justify-center opacity-0 group-hover/img:opacity-100 transition-opacity hover:bg-red-500">
                                    <i class="pi pi-times" style="font-size: 8px"></i>
                                </button>
                            </div>
                        </div>

                        <div v-else
                            class="py-6 text-center text-slate-600 text-xs border border-dashed border-white/5 rounded-xl cursor-pointer hover:border-violet-500/30 hover:text-violet-400 transition-all"
                            @click="openGenPicker(post)">
                            <i class="pi pi-images mr-1"></i> Нажмите, чтобы добавить изображения
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ====== NEW / EDIT POST DIALOG ====== -->
        <Dialog v-model:visible="showPostDialog" :header="editingPost ? 'Редактировать пост' : 'Новый пост'" modal
            :style="{ width: '600px', maxWidth: '95vw' }"
            :pt="{ root: { class: '!bg-slate-800 !border-white/10' }, header: { class: '!bg-slate-800' }, content: { class: '!bg-slate-800' } }">
            <div class="flex flex-col gap-4">
                <!-- Date & Topic row -->
                <div class="grid grid-cols-2 gap-3">
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Дата</label>
                        <DatePicker v-model="postForm.date" dateFormat="dd.mm.yy" showIcon class="w-full" :pt="{
                            root: { class: '!bg-slate-700 !border-white/10' },
                            pcInputText: { root: { class: '!bg-slate-700 !border-white/10 !text-white' } }
                        }" />
                    </div>
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Тема</label>
                        <InputText v-model="postForm.topic" placeholder="Тема поста..."
                            class="w-full !bg-slate-700 !border-white/10 !text-white" />
                    </div>
                </div>

                <!-- Attached Generations (edit mode only) -->
                <div v-if="editingPost">
                    <div class="flex items-center justify-between mb-2">
                        <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                            Изображения ({{ editingPost.generation_ids?.length || 0 }})
                        </label>
                        <div class="flex gap-1">
                            <Button icon="pi pi-download" label="Скачать" size="small" text :loading="isDownloading"
                                :disabled="!editingPost.generation_ids?.length" @click="downloadPostAssets(editingPost)"
                                class="!text-slate-400 hover:!text-white !text-xs !py-1" />
                            <Button icon="pi pi-plus" label="Добавить" size="small" text
                                @click="openGenPicker(editingPost)"
                                class="!text-violet-400 hover:!text-violet-300 !text-xs !py-1" />
                        </div>
                    </div>

                    <!-- Generation grid -->
                    <div v-if="editingPost.generation_ids?.length > 0" class="grid grid-cols-4 sm:grid-cols-5 gap-2">
                        <div v-for="gid in editingPost.generation_ids" :key="gid"
                            class="aspect-square relative rounded-xl overflow-hidden bg-slate-900 border border-white/5 group/img">
                            <img :src="API_URL + '/assets/' + gid + '?thumbnail=true'"
                                class="w-full h-full object-cover cursor-pointer"
                                @click="openPreview(editingPost.generation_ids, gid)" />
                            <button @click="removeGenerationFromPost(editingPost, gid)"
                                class="absolute top-1 right-1 w-5 h-5 rounded-md bg-red-600/80 text-white flex items-center justify-center opacity-0 group-hover/img:opacity-100 transition-opacity hover:bg-red-500">
                                <i class="pi pi-times" style="font-size: 8px"></i>
                            </button>
                        </div>
                    </div>

                    <div v-else
                        class="py-6 text-center text-slate-600 text-xs border border-dashed border-white/5 rounded-xl cursor-pointer hover:border-violet-500/30 hover:text-violet-400 transition-all"
                        @click="openGenPicker(editingPost)">
                        <i class="pi pi-images mr-1"></i> Нажмите, чтобы добавить изображения
                    </div>
                </div>

                <div class="flex justify-end gap-2 mt-2">
                    <Button label="Отмена" text @click="showPostDialog = false"
                        class="!text-slate-400 hover:!text-white" />
                    <Button :label="editingPost ? 'Сохранить' : 'Создать'" @click="savePost"
                        class="!bg-violet-600 !border-none hover:!bg-violet-500" />
                </div>
            </div>
        </Dialog>

        <!-- ====== GENERATION PICKER DIALOG ====== -->
        <Dialog v-model:visible="showGenPicker" header="Добавить изображения" modal
            :style="{ width: '700px', maxWidth: '95vw' }"
            :pt="{ root: { class: '!bg-slate-800 !border-white/10' }, header: { class: '!bg-slate-800' }, content: { class: '!bg-slate-800 !p-0' } }">

            <!-- Selected count bar -->
            <div v-if="selectedGenIds.size > 0"
                class="sticky top-0 z-10 flex items-center justify-between px-4 py-2 bg-violet-600/20 border-b border-violet-500/20">
                <span class="text-sm text-violet-200 font-medium">
                    <i class="pi pi-check-circle mr-1"></i> Выбрано: {{ selectedGenIds.size }}
                </span>
                <Button label="Добавить" icon="pi pi-plus" @click="confirmAddGenerations" size="small"
                    class="!bg-violet-600 !border-none hover:!bg-violet-500 !text-sm !py-1" />
            </div>

            <!-- Loading -->
            <div v-if="genLoading" class="flex items-center justify-center py-20">
                <i class="pi pi-spin pi-spinner text-3xl text-violet-400"></i>
            </div>

            <!-- Grid -->
            <div v-else class="p-4 max-h-[60vh] overflow-y-auto custom-scrollbar" @scroll="onGenPickerScroll">
                <div v-if="availableGenerations.length === 0"
                    class="flex flex-col items-center justify-center py-16 text-slate-500">
                    <i class="pi pi-image text-4xl mb-3"></i>
                    <p class="text-sm">Нет доступных генераций</p>
                </div>

                <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
                    <template v-for="gen in availableGenerations" :key="gen.id">
                        <div v-for="assetId in (gen.result_list || [])" :key="assetId"
                            @click="toggleGenSelection(assetId)"
                            class="aspect-square relative rounded-xl overflow-hidden cursor-pointer transition-all group/gen border-2"
                            :class="selectedGenIds.has(assetId)
                                ? 'border-violet-500 ring-2 ring-violet-500/30 scale-[0.95]'
                                : 'border-transparent hover:border-white/20'">
                            <img :src="API_URL + '/assets/' + assetId + '?thumbnail=true'"
                                class="w-full h-full object-cover" loading="lazy" />

                            <!-- Selection overlay -->
                            <div v-if="selectedGenIds.has(assetId)"
                                class="absolute inset-0 bg-violet-600/30 flex items-center justify-center">
                                <div
                                    class="w-7 h-7 rounded-full bg-violet-600 flex items-center justify-center shadow-lg">
                                    <i class="pi pi-check text-white" style="font-size: 12px"></i>
                                </div>
                            </div>

                            <!-- Hover overlay -->
                            <div v-else
                                class="absolute inset-0 bg-black/0 group-hover/gen:bg-black/20 transition-all flex items-center justify-center">
                                <div
                                    class="w-7 h-7 rounded-full border-2 border-white/40 opacity-0 group-hover/gen:opacity-100 transition-opacity">
                                </div>
                            </div>
                        </div>
                    </template>
                </div>

                <!-- Load more spinner -->
                <div v-if="genLoadingMore" class="flex justify-center py-4">
                    <i class="pi pi-spin pi-spinner text-xl text-slate-500"></i>
                </div>
            </div>

            <!-- Footer with action -->
            <div class="flex justify-end gap-2 px-4 py-3 border-t border-white/5">
                <Button label="Отмена" text @click="showGenPicker = false" class="!text-slate-400 hover:!text-white" />
                <Button label="Добавить" icon="pi pi-plus" :disabled="selectedGenIds.size === 0"
                    @click="confirmAddGenerations" class="!bg-violet-600 !border-none hover:!bg-violet-500" />
            </div>
        </Dialog>

        <!-- ====== FULLSCREEN IMAGE PREVIEW ====== -->
        <div v-if="previewVisible" class="fixed inset-0 z-[9999] bg-black/95 flex items-center justify-center"
            @click.self="previewVisible = false">

            <!-- Close -->
            <button @click="previewVisible = false"
                class="absolute top-4 right-4 w-10 h-10 rounded-full bg-white/10 text-white flex items-center justify-center hover:bg-white/20 transition-colors z-10">
                <i class="pi pi-times text-lg"></i>
            </button>

            <!-- Counter -->
            <div v-if="previewImages.length > 1"
                class="absolute top-4 left-1/2 -translate-x-1/2 text-white/60 text-sm bg-black/40 px-3 py-1 rounded-full">
                {{ previewIndex + 1 }} / {{ previewImages.length }}
            </div>

            <!-- Left arrow -->
            <button v-if="previewImages.length > 1" @click="previewNav(-1)"
                class="absolute left-3 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/10 text-white flex items-center justify-center hover:bg-white/20 transition-colors">
                <i class="pi pi-chevron-left"></i>
            </button>

            <!-- Image -->
            <img v-if="previewCurrent" :src="previewCurrent"
                class="max-h-[90vh] max-w-[90vw] object-contain rounded-lg shadow-2xl" />

            <!-- Right arrow -->
            <button v-if="previewImages.length > 1" @click="previewNav(1)"
                class="absolute right-3 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/10 text-white flex items-center justify-center hover:bg-white/20 transition-colors">
                <i class="pi pi-chevron-right"></i>
            </button>
        </div>
    </div>
</template>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
    width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.2);
}
</style>
