<script setup>
import { API_CONFIG } from '@/config/api';
import MarketingV3Service from '@/service/MarketingV3Service';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import Divider from 'primevue/divider';
import Slider from 'primevue/slider';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const toast = useToast();

const analysisId = computed(() => route.query.analysisId || '');
const strategyId = ref(null);

// Statuses: PREVIEW, QUEUED, PROCESSING, FAILED, COMPLETED
const status = ref('PREVIEW');

// Preview Phase Data
const previewLoading = ref(true);
const previewData = ref(null);

// Form Data
const formData = ref({
    durationWeeks: 4,
    priorityPlatforms: ['Instagram']
});

const platformOptions = [
    { label: 'Instagram', value: 'Instagram' },
    { label: 'TikTok', value: 'TikTok' },
    { label: 'YouTube Shorts', value: 'YouTube' },
    { label: 'LinkedIn', value: 'LinkedIn' },
    { label: 'VK', value: 'VK' },
    { label: 'Telegram', value: 'Telegram' }
];

// Logo Upload Logic
const fileInput = ref(null);
const logoFile = ref(null);
const logoPreviewUrl = ref(null);
const isDragging = ref(false);

const triggerFileInput = () => fileInput.value?.click();

const handleFileSelect = (event) => {
    const file = event.target.files[0];
    if (file) processLogo(file);
};

const handleDrop = (event) => {
    isDragging.value = false;
    const file = event.dataTransfer.files[0];
    if (file) processLogo(file);
};

const processLogo = (file) => {
    if (!['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)) {
        toast.add({ severity: 'error', summary: 'Формат', detail: 'Доступны только PNG и JPG', life: 3000 });
        return;
    }
    if (file.size > 5 * 1024 * 1024) {
        toast.add({ severity: 'error', summary: 'Размер', detail: 'Файл слишком тяжелый (макс 5МБ)', life: 3000 });
        return;
    }
    logoFile.value = file;
    logoPreviewUrl.value = URL.createObjectURL(file);
};

const removeLogo = () => {
    if (logoPreviewUrl.value) URL.revokeObjectURL(logoPreviewUrl.value);
    logoFile.value = null;
    logoPreviewUrl.value = null;
    if (fileInput.value) fileInput.value.value = '';
};

// Generation Logic
const generateLoading = ref(false);
const progressPercent = ref(0);
const loadingMessageIndex = ref(0);
const loadingMessages = [
    'Анализируем контекст ниши...',
    'Пишем продающие сценарии...',
    'Рендерим видео-ролики Veo...',
    'Генерируем креативы Imagen 3...',
    'Накладываем логотип на активы...',
    'Собираем контент-план...',
    'Финальная проверка качества...'
];
const currentLoadingMessage = computed(() => loadingMessages[loadingMessageIndex.value]);

let pollInterval = null;
let messageInterval = null;
const strategyData = ref(null);
const activeWeeks = ref([1]);

const toggleWeek = (week) => {
    if (activeWeeks.value.includes(week)) {
        activeWeeks.value = activeWeeks.value.filter((w) => w !== week);
    } else {
        activeWeeks.value.push(week);
    }
};

const startGeneration = async () => {
    if (!analysisId.value) return;

    try {
        generateLoading.value = true;
        const data = new FormData();

        const requestPayload = {
            durationWeeks: formData.value.durationWeeks,
            priorityPlatforms: formData.value.priorityPlatforms
        };

        // КАТЕГОРИЧЕСКИ ВАЖНО для Backend (Multipart RequestPart):
        data.append('request', new Blob([JSON.stringify(requestPayload)], { type: 'application/json' }), 'request.json');

        if (logoFile.value) {
            data.append('logo', logoFile.value);
        }

        const result = await MarketingV3Service.generateStrategy(analysisId.value, data);

        if (result && result.strategyId) {
            strategyId.value = result.strategyId;
            status.value = 'QUEUED';
            startPolling();
        }
    } catch (error) {
        toast.add({ severity: 'error', summary: 'Ошибка', detail: error.message || 'Не удалось запустить генерацию', life: 5000 });
    } finally {
        generateLoading.value = false;
    }
};

const startPolling = () => {
    progressPercent.value = 5;

    messageInterval = setInterval(() => {
        loadingMessageIndex.value = (loadingMessageIndex.value + 1) % loadingMessages.length;
        if (progressPercent.value < 90) progressPercent.value += Math.floor(Math.random() * 8) + 1;
    }, 4500);

    pollInterval = setInterval(async () => {
        try {
            const data = await MarketingV3Service.getStrategyStatus(strategyId.value);

            if (data.status === 'completed') {
                progressPercent.value = 100;
                strategyData.value = data;
                setTimeout(() => {
                    status.value = 'COMPLETED';
                    stopPolling();
                    toast.add({ severity: 'success', summary: 'Готово', detail: 'Ваша стратегия готова к внедрению!', life: 4000 });
                }, 1000);
            } else if (data.status === 'failed') {
                status.value = 'FAILED';
                stopPolling();
            } else {
                status.value = data.status.toUpperCase() === 'PROCESSING' ? 'PROCESSING' : 'QUEUED';
            }
        } catch (e) {
            console.error('Polling error', e);
        }
    }, 5000);
};

const stopPolling = () => {
    if (pollInterval) clearInterval(pollInterval);
    if (messageInterval) clearInterval(messageInterval);
};

// Helpers
const getPlatformIcon = (platform) => {
    const p = platform?.toLowerCase() || '';
    if (p.includes('insta')) return 'pi pi-instagram';
    if (p.includes('tik')) return 'pi pi-tiktok';
    if (p.includes('you')) return 'pi pi-youtube';
    if (p.includes('tg') || p.includes('tele')) return 'pi pi-telegram';
    if (p.includes('link')) return 'pi pi-linkedin';
    if (p.includes('vk')) return 'pi pi-vk';
    return 'pi pi-share-alt';
};

const formatDate = (dateStr) => {
    if (!dateStr) return '';
    return new Date(dateStr).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' });
};

const copyText = (text, hashtags) => {
    let fullText = text || '';
    if (hashtags?.length) fullText += '\n\n' + hashtags.map((t) => `#${t}`).join(' ');
    navigator.clipboard.writeText(fullText).then(() => {
        toast.add({ severity: 'success', summary: 'Копирование', detail: 'Текст в буфере обмена', life: 2000 });
    });
};

const getMediaUrl = (filename) => {
    if (!filename) return null;
    return `${API_CONFIG.BASE_URL}/api/marketing/v3/media/${filename}`;
};

// Media Preview Dialog
const mediaDialog = ref(false);
const activeMedia = ref(null);
const previewMedia = (post) => {
    activeMedia.value = post;
    mediaDialog.value = true;
};

// Lifecycle
const init = async () => {
    if (!analysisId.value) {
        router.push('/marketing-analysis/v3');
        return;
    }
    try {
        previewLoading.value = true;
        const res = await MarketingV3Service.getStrategyPreview(analysisId.value);
        previewData.value = res;
        if (res.recommendedPlatforms?.length) {
            formData.value.priorityPlatforms = res.recommendedPlatforms.filter((p) => platformOptions.some((o) => o.value === p));
        }
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Не удалось загрузить рекомендации', life: 5000 });
    } finally {
        previewLoading.value = false;
    }
};

onMounted(init);
onUnmounted(stopPolling);
</script>

<template>
    <div class="marketing-strategy-v3-page bg-slate-50 dark:bg-slate-950 min-h-screen p-4 md:p-8">
        <Toast />

        <div class="max-w-5xl mx-auto">
            <!-- 1. HEADER -->
            <div class="flex flex-col md:flex-row md:items-center justify-between mb-10 gap-4">
                <div>
                    <div class="flex items-center gap-2 mb-2">
                        <span class="px-2 py-1 rounded-md bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 text-[10px] font-bold tracking-wider uppercase">Content Factory V3</span>
                    </div>
                    <h1 class="text-3xl font-extrabold text-slate-900 dark:text-white tracking-tight">Генерация стратегии</h1>
                    <p class="text-slate-500 dark:text-slate-400 mt-1">Создание визуального и текстового контента на основе вашего анализа</p>
                </div>
                <Button label="К анализу" icon="pi pi-arrow-left" severity="secondary" text class="rounded-xl hover:bg-white dark:hover:bg-slate-900 shadow-sm border border-slate-200 dark:border-slate-800" @click="goBack" />
            </div>

            <!-- 2. STAGE: PREVIEW & SETUP -->
            <div v-if="status === 'PREVIEW'" class="space-y-8 animate-in fade-in duration-700">
                <!-- Recommendation Card -->
                <div class="relative overflow-hidden group">
                    <div v-if="previewLoading" class="card p-8 animate-pulse bg-emerald-50/50 dark:bg-emerald-900/10 border-emerald-100 dark:border-emerald-900/20">
                        <div class="flex items-start gap-4">
                            <div class="w-12 h-12 rounded-2xl bg-emerald-100 dark:bg-emerald-900/40"></div>
                            <div class="flex-1 space-y-4">
                                <div class="h-6 bg-emerald-100 dark:bg-emerald-900/40 rounded w-1/4"></div>
                                <div class="h-4 bg-emerald-50 dark:bg-emerald-900/20 rounded w-full"></div>
                                <div class="h-4 bg-emerald-50 dark:bg-emerald-900/20 rounded w-2/3"></div>
                            </div>
                        </div>
                    </div>

                    <div v-else-if="previewData" class="card relative p-8 bg-gradient-to-br from-emerald-500 to-emerald-600 dark:from-emerald-600 dark:to-emerald-800 border-none shadow-2xl shadow-emerald-200 dark:shadow-none overflow-hidden">
                        <!-- Abstract Background elements -->
                        <div class="absolute top-0 right-0 -mt-10 -mr-10 w-64 h-64 bg-white/10 blur-3xl rounded-full"></div>
                        <div class="absolute bottom-0 left-0 -mb-10 -ml-10 w-48 h-48 bg-black/5 blur-2xl rounded-full"></div>

                        <div class="flex flex-col md:flex-row items-start md:items-center gap-6 relative z-10 text-white">
                            <div class="p-4 bg-white/20 backdrop-blur-md rounded-2xl border border-white/30 shadow-inner">
                                <i class="pi pi-sparkles text-3xl animate-pulse" />
                            </div>
                            <div class="flex-1">
                                <h3 class="text-xl font-black mb-2 flex items-center gap-2">
                                    {{ previewData.modelTitle || 'Оптимальная стратегия' }}
                                    <i class="pi pi-info-circle text-xs opacity-60" />
                                </h3>
                                <p class="text-emerald-50/90 leading-relaxed font-medium">
                                    {{ previewData.description }}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Section -->
                <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                    <!-- Left: Duration & Platforms -->
                    <div class="lg:col-span-8 space-y-8">
                        <div class="card p-6 md:p-8 bg-white dark:bg-slate-900 border-slate-200/60 dark:border-slate-800 shadow-sm">
                            <h3 class="text-lg font-bold mb-8 flex items-center gap-2">
                                <span class="w-1.5 h-6 bg-emerald-500 rounded-full"></span>
                                Настройки кампании
                            </h3>

                            <div class="space-y-10">
                                <!-- Duration -->
                                <div>
                                    <div class="flex justify-between items-center mb-6">
                                        <label class="text-sm font-bold text-slate-700 dark:text-slate-300">Длительность в неделях</label>
                                        <span class="px-3 py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-lg text-lg font-black">{{ formData.durationWeeks }}</span>
                                    </div>
                                    <div class="px-1">
                                        <Slider v-model="formData.durationWeeks" :min="1" :max="12" :step="1" class="custom-slider" />
                                    </div>
                                    <div class="flex justify-between mt-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">
                                        <span>1 неделя</span>
                                        <span>4 недели</span>
                                        <span>12 недель</span>
                                    </div>
                                </div>

                                <Divider class="opacity-40" />

                                <!-- Platforms -->
                                <div>
                                    <label class="block text-sm font-bold text-slate-700 dark:text-slate-300 mb-6">Каналы продвижения</label>
                                    <div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
                                        <div v-for="platform in platformOptions" :key="platform.value" class="relative">
                                            <input type="checkbox" :id="platform.value" v-model="formData.priorityPlatforms" :value="platform.value" class="peer hidden" />
                                            <label
                                                :for="platform.value"
                                                class="flex items-center gap-3 p-4 rounded-2xl border-2 border-slate-100 dark:border-slate-800 bg-white dark:bg-slate-900 cursor-pointer transition-all peer-checked:border-emerald-500 peer-checked:bg-emerald-50/30 dark:peer-checked:bg-emerald-500/10 hover:border-emerald-200 dark:hover:border-emerald-800"
                                            >
                                                <div
                                                    class="w-6 h-6 rounded-full border-2 flex items-center justify-center transition-colors"
                                                    :class="formData.priorityPlatforms.includes(platform.value) ? 'bg-emerald-500 border-emerald-500 text-white' : 'border-slate-200 dark:border-slate-700'"
                                                >
                                                    <i class="pi pi-check text-[10px] font-bold" v-if="formData.priorityPlatforms.includes(platform.value)" />
                                                </div>
                                                <span class="text-sm font-bold text-slate-600 dark:text-slate-400 peer-checked:text-emerald-700 dark:peer-checked:text-emerald-400">
                                                    {{ platform.label }}
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right: Brand & Submit -->
                    <div class="lg:col-span-4 space-y-8">
                        <!-- Logo Upload -->
                        <div class="card p-6 bg-white dark:bg-slate-900 border-slate-200/60 dark:border-slate-800 shadow-sm">
                            <h3 class="text-sm font-bold mb-4 text-slate-400 uppercase tracking-wider">Интеграция бренда</h3>

                            <div
                                class="relative border-2 border-dashed rounded-2xl p-6 text-center transition-all bg-slate-50/50 dark:bg-slate-800/20"
                                :class="[isDragging ? 'border-emerald-500 bg-emerald-50/50' : 'border-slate-200 dark:border-slate-700', logoPreviewUrl ? 'p-2' : 'hover:border-emerald-300']"
                                @dragover.prevent="isDragging = true"
                                @dragleave.prevent="isDragging = false"
                                @drop.prevent="handleDrop"
                            >
                                <input type="file" id="logoUpload" accept="image/*" class="hidden" @change="handleFileSelect" ref="fileInput" />

                                <div v-if="logoPreviewUrl" class="relative group aspect-square rounded-xl overflow-hidden shadow-inner bg-white dark:bg-slate-900">
                                    <img :src="logoPreviewUrl" alt="Logo preview" class="w-full h-full object-contain p-4" />
                                    <div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity">
                                        <Button icon="pi pi-trash" rounded severity="danger" class="w-12 h-12" @click="removeLogo" />
                                    </div>
                                </div>

                                <div v-else class="py-4 cursor-pointer" @click="triggerFileInput">
                                    <div class="w-12 h-12 bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 flex items-center justify-center mx-auto mb-4 text-emerald-500">
                                        <i class="pi pi-upload text-xl" />
                                    </div>
                                    <h4 class="text-slate-900 dark:text-white font-bold text-sm mb-1">Логотип бренда</h4>
                                    <p class="text-slate-400 text-[10px] font-medium leading-relaxed">
                                        Кликните или перетащите <br />
                                        PNG, JPG до 5MB
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- General Submit -->
                        <button
                            @click="startGeneration"
                            class="w-full py-5 px-6 rounded-2xl bg-emerald-500 hover:bg-emerald-600 active:scale-[0.98] disabled:bg-slate-200 dark:disabled:bg-slate-800 disabled:text-slate-400 text-white font-black text-lg shadow-xl shadow-emerald-500/20 transition-all flex items-center justify-center gap-3 overflow-hidden group relative"
                            :disabled="!formData.priorityPlatforms.length || generateLoading"
                        >
                            <span v-if="!generateLoading" class="flex items-center gap-3"> ⚡ <span class="tracking-tight">Запустить Фабрику</span> </span>
                            <div v-else class="flex items-center gap-3">
                                <i class="pi pi-spin pi-spinner text-xl" />
                                <span>Подготовка...</span>
                            </div>
                            <!-- Subtle shine effect on hover -->
                            <div class="absolute top-0 -left-full w-full h-full bg-gradient-to-r from-transparent via-white/20 to-transparent group-hover:left-[200%] transition-all duration-1000 ease-in-out"></div>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 3. STAGE: POLLING SCREEN -->
            <div v-else-if="status === 'QUEUED' || status === 'PROCESSING'" class="card p-12 md:p-24 text-center bg-white dark:bg-slate-900 border-none shadow-xl animate-in zoom-in duration-500">
                <div class="max-w-md mx-auto">
                    <!-- Progress Circle -->
                    <div class="relative w-32 h-32 mx-auto mb-12">
                        <svg class="w-full h-full transform -rotate-90">
                            <circle cx="64" cy="64" r="58" stroke="currentColor" stroke-width="8" fill="transparent" class="text-slate-100 dark:text-slate-800" />
                            <circle
                                cx="64"
                                cy="64"
                                r="58"
                                stroke="currentColor"
                                stroke-width="8"
                                fill="transparent"
                                stroke-dasharray="364.4"
                                :stroke-dashoffset="364.4 - (364.4 * progressPercent) / 100"
                                class="text-emerald-500 transition-all duration-1000 ease-out"
                            />
                        </svg>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <i class="pi pi-bolt text-4xl text-emerald-500 animate-pulse" />
                        </div>
                    </div>

                    <h2 class="text-2xl font-black text-slate-900 dark:text-white mb-4">
                        {{ status === 'QUEUED' ? 'Запуск производства...' : 'Фабрика в работе' }}
                    </h2>

                    <div class="h-12 flex items-center justify-center mb-8">
                        <Transition name="slide-up" mode="out-in">
                            <p :key="loadingMessageIndex" class="text-slate-500 dark:text-slate-400 font-bold">
                                {{ currentLoadingMessage }}
                            </p>
                        </Transition>
                    </div>

                    <div class="bg-slate-100 dark:bg-slate-800 rounded-full h-1.5 overflow-hidden">
                        <div class="bg-emerald-500 h-full transition-all duration-1000" :style="{ width: `${progressPercent}%` }"></div>
                    </div>
                    <div class="mt-4 flex justify-between text-[10px] font-black text-slate-400 uppercase tracking-widest">
                        <span>Процесс</span>
                        <span class="text-emerald-500">{{ progressPercent }}%</span>
                    </div>
                </div>
            </div>

            <!-- 4. STAGE: COMPLETED (Result Display) -->
            <div v-else-if="status === 'COMPLETED' && strategyData" class="space-y-10 animate-in fade-in slide-in-from-bottom-5 duration-1000">
                <!-- Strategy Rationale Banner -->
                <div class="card p-8 md:p-12 bg-slate-900 dark:bg-black text-white relative overflow-hidden group">
                    <div class="absolute top-0 right-0 w-96 h-96 bg-emerald-500/20 blur-3xl rounded-full -mr-48 -mt-48 group-hover:bg-emerald-500/30 transition-colors duration-1000"></div>

                    <div class="relative z-10 flex flex-col md:flex-row gap-10 items-start">
                        <div class="flex-1">
                            <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/20 text-emerald-400 text-[10px] font-black uppercase tracking-wider border border-emerald-500/30 mb-6">
                                <span class="relative flex h-2 w-2">
                                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                    <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                                </span>
                                Готовый результат
                            </div>
                            <h2 class="text-3xl font-black mb-6 tracking-tight">Стратегическое обоснование</h2>
                            <p class="text-slate-400 leading-relaxed text-lg font-medium whitespace-pre-line">
                                {{ strategyData.strategyData?.rationale }}
                            </p>
                        </div>
                        <div class="w-full md:w-64 space-y-4">
                            <div class="p-5 rounded-2xl bg-white/5 border border-white/10 backdrop-blur-sm">
                                <p class="text-slate-500 text-[10px] font-black uppercase mb-2">Выбранная модель</p>
                                <p class="font-bold text-emerald-400">{{ strategyData.strategyData?.selectedModel || 'Адаптивная' }}</p>
                            </div>
                            <div class="p-5 rounded-2xl bg-white/5 border border-white/10 backdrop-blur-sm">
                                <p class="text-slate-500 text-[10px] font-black uppercase mb-2">Срок реализации</p>
                                <p class="font-bold text-slate-200">{{ strategyData.strategyData?.durationWeeks }} недель</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Weekly Sprints -->
                <div v-if="strategyData.weeklyPlans?.length">
                    <h3 class="text-xl font-black text-slate-900 dark:text-white mb-6 px-2 flex items-center gap-3">
                        <i class="pi pi-calendar text-emerald-500" />
                        План реализации (Спринты)
                    </h3>

                    <div class="space-y-4">
                        <div v-for="plan in strategyData.weeklyPlans" :key="plan.weekNumber" class="card overflow-hidden bg-white dark:bg-slate-900 border-slate-200/60 dark:border-slate-800 shadow-sm">
                            <div class="flex items-center justify-between p-6 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors" @click="toggleWeek(plan.weekNumber)">
                                <div class="flex items-center gap-4">
                                    <div class="w-10 h-10 rounded-xl bg-slate-900 dark:bg-emerald-500 text-white flex items-center justify-center font-black text-sm shadow-lg">
                                        {{ plan.weekNumber }}
                                    </div>
                                    <div>
                                        <h4 class="font-black text-slate-900 dark:text-white">Неделя {{ plan.weekNumber }}</h4>
                                        <div class="flex gap-2 mt-1">
                                            <span v-for="theme in plan.mainThemes?.slice(0, 2)" :key="theme" class="text-[10px] font-bold text-emerald-600 dark:text-emerald-400 uppercase tracking-tighter"> #{{ theme }} </span>
                                        </div>
                                    </div>
                                </div>
                                <i class="pi" :class="activeWeeks.includes(plan.weekNumber) ? 'pi-chevron-up' : 'pi-chevron-down'" />
                            </div>

                            <Transition name="expand">
                                <div v-if="activeWeeks.includes(plan.weekNumber)" class="p-6 pt-0 border-t border-slate-100 dark:border-slate-800/60 bg-slate-50/30 dark:bg-slate-900/40">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mt-6">
                                        <div>
                                            <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">Темы недели</p>
                                            <div class="flex flex-wrap gap-2">
                                                <Tag
                                                    v-for="theme in plan.mainThemes"
                                                    :key="theme"
                                                    :value="theme"
                                                    class="bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 font-bold border border-slate-200 dark:border-slate-700 rounded-lg px-3 py-1.5"
                                                />
                                            </div>
                                        </div>
                                        <div>
                                            <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">Инструкция по реализации</p>
                                            <div class="p-4 rounded-xl bg-emerald-50/50 dark:bg-emerald-950/20 border-l-4 border-emerald-500 text-slate-700 dark:text-slate-400 text-sm leading-relaxed whitespace-pre-line font-medium">
                                                {{ plan.contentRecommendations }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </Transition>
                        </div>
                    </div>
                </div>

                <!-- Content Calendar -->
                <div v-if="strategyData.postCalendar?.length">
                    <div class="flex items-center justify-between mb-8 px-2">
                        <h3 class="text-xl font-black text-slate-900 dark:text-white flex items-center gap-3">
                            <i class="pi pi-images text-emerald-500" />
                            Медиа-активы и посты
                        </h3>
                        <Button label="Скачать календарь" icon="pi pi-download" size="small" severity="secondary" rounded text class="font-bold" />
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                        <div
                            v-for="(post, idx) in strategyData.postCalendar"
                            :key="idx"
                            class="card p-0 overflow-hidden bg-white dark:bg-slate-900 border-none shadow-xl shadow-slate-200/50 dark:shadow-none hover:-translate-y-2 transition-transform duration-500 group"
                        >
                            <!-- Media Header -->
                            <div class="aspect-square relative bg-slate-100 dark:bg-slate-800 flex items-center justify-center overflow-hidden">
                                <template v-if="post.contentType === 'video' || post.contentType === 'reels'">
                                    <video v-if="getMediaUrl(post.mediaFilename)" :src="getMediaUrl(post.mediaFilename)" autoplay loop muted playsinline class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" />
                                    <div v-else class="text-center p-8 opacity-40">
                                        <i class="pi pi-video text-5xl mb-2" />
                                        <p class="text-[10px] font-bold uppercase">Видео в обработке</p>
                                    </div>
                                    <div class="absolute top-4 right-4 px-2 py-1 bg-black/60 rounded backdrop-blur-md text-[8px] font-black text-white uppercase tracking-tighter">Video Asset</div>
                                </template>
                                <template v-else>
                                    <img v-if="getMediaUrl(post.mediaFilename)" :src="getMediaUrl(post.mediaFilename)" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" />
                                    <div v-else class="text-center p-8 opacity-40">
                                        <i class="pi pi-image text-5xl mb-2" />
                                        <p class="text-[10px] font-bold uppercase tracking-widest">Генерация визуала...</p>
                                    </div>
                                </template>

                                <div class="absolute inset-0 bg-emerald-500/10 opacity-0 group-hover:opacity-100 transition-opacity"></div>
                                <div class="absolute top-4 left-4 flex gap-2">
                                    <div class="p-2 rounded-xl bg-white/90 dark:bg-slate-900/90 backdrop-blur-md shadow-lg">
                                        <i :class="getPlatformIcon(post.platform)" class="text-lg text-emerald-500" />
                                    </div>
                                </div>
                            </div>

                            <!-- Content Details -->
                            <div class="p-6">
                                <div class="flex justify-between items-start mb-4">
                                    <div>
                                        <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">{{ formatDate(post.publishDate) }}</p>
                                        <h4 class="font-black text-slate-900 dark:text-white line-clamp-1 h-5">{{ post.theme }}</h4>
                                    </div>
                                    <span class="text-[10px] font-black px-2 py-1 bg-slate-100 dark:bg-slate-800 rounded-lg text-slate-500 uppercase">{{ post.publishTime }}</span>
                                </div>

                                <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-800/40 border border-slate-100 dark:border-slate-800 mb-6 group-hover:bg-emerald-50/30 dark:group-hover:bg-emerald-900/10 transition-colors">
                                    <p class="text-xs text-slate-600 dark:text-slate-400 line-clamp-3 font-medium leading-relaxed">{{ post.postText }}</p>
                                </div>

                                <div class="flex items-center gap-2">
                                    <Button icon="pi pi-copy" label="Копировать" class="flex-1 text-[10px] font-black uppercase tracking-wider rounded-xl py-3" outlined severity="secondary" @click="copyText(post.postText, post.hashtags)" />
                                    <Button icon="pi pi-expand" class="w-12 h-12 rounded-xl" text severity="secondary" v-if="getMediaUrl(post.mediaFilename)" @click="previewMedia(post)" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Actions Footer -->
                <div class="flex flex-col md:flex-row gap-4 pt-10 border-t border-slate-200 dark:border-slate-800">
                    <Button label="Сохранить как PDF" icon="pi pi-file-pdf" severity="secondary" outlined class="flex-1 rounded-2xl font-black py-4" />
                    <Button label="Новая генерация" icon="pi pi-refresh" severity="secondary" class="flex-1 rounded-2xl font-black py-4" @click="status = 'PREVIEW'" />
                </div>
            </div>

            <!-- Stage: FAILED -->
            <div v-else-if="status === 'FAILED'" class="card p-12 text-center bg-white dark:bg-slate-900 border-none shadow-xl">
                <div class="w-20 h-20 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-6 text-red-500">
                    <i class="pi pi-exclamation-triangle text-3xl" />
                </div>
                <h2 class="text-2xl font-black mb-2">Генерация прервана</h2>
                <p class="text-slate-500 mb-8 max-w-sm mx-auto">Что-то пошло не так при работе искусственного интеллекта. Пожалуйста, попробуйте еще раз.</p>
                <div class="flex justify-center gap-4">
                    <Button label="Назад к настройкам" severity="secondary" text class="font-bold" @click="status = 'PREVIEW'" />
                    <Button label="Повторить попытку" icon="pi pi-refresh" severity="danger" class="font-bold rounded-xl" @click="startGeneration" />
                </div>
            </div>

            <!-- Media Modal -->
            <Dialog v-model:visible="mediaDialog" :modal="true" :showHeader="false" :dismissableMask="true" contentClass="p-0 bg-transparent shadow-none" class="w-full max-w-4xl m-4 border-none">
                <div class="relative rounded-3xl overflow-hidden bg-black/95 flex flex-col items-center justify-center p-2 group">
                    <Button icon="pi pi-times" rounded text class="absolute top-6 right-6 text-white/50 hover:text-white z-50 bg-white/10 hover:bg-white/20 backdrop-blur-md" @click="mediaDialog = false" />

                    <template v-if="activeMedia">
                        <video v-if="activeMedia.contentType === 'video' || activeMedia.contentType === 'reels'" :src="getMediaUrl(activeMedia.mediaFilename)" autoplay controls class="max-h-[90vh] w-auto max-w-full rounded-2xl overflow-hidden" />
                        <img v-else :src="getMediaUrl(activeMedia.mediaFilename)" alt="Full preview" class="max-h-[90vh] w-auto max-w-full rounded-2xl object-contain" />

                        <!-- Overlay Info in Modal -->
                        <div class="absolute bottom-6 left-6 right-6 p-6 rounded-2xl bg-black/60 backdrop-blur-xl border border-white/10 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                            <div class="flex items-center gap-2 mb-2">
                                <i :class="getPlatformIcon(activeMedia.platform)" class="text-emerald-400" />
                                <span class="text-[10px] font-black uppercase tracking-widest text-emerald-400">{{ activeMedia.platform }}</span>
                            </div>
                            <h4 class="text-lg font-black mb-3">{{ activeMedia.theme }}</h4>
                            <p class="text-sm text-slate-400 font-medium leading-relaxed">{{ activeMedia.postText }}</p>
                        </div>
                    </template>
                </div>
            </Dialog>
        </div>
    </div>
</template>

<style scoped>
.custom-slider :deep(.p-slider-handle) {
    background-color: #10b981;
    border-color: #10b981;
    width: 20px;
    height: 20px;
}
.custom-slider :deep(.p-slider-range) {
    background-color: #10b981;
}

/* Animations */
.slide-up-enter-active,
.slide-up-leave-active {
    transition: all 0.5s ease;
}
.slide-up-enter-from {
    opacity: 0;
    transform: translateY(20px);
}
.slide-up-leave-to {
    opacity: 0;
    transform: translateY(-20px);
}

.expand-enter-active,
.expand-leave-active {
    transition: all 0.3s ease-in-out;
    max-height: 500px;
    overflow: hidden;
}
.expand-enter-from,
.expand-leave-to {
    max-height: 0;
    opacity: 0;
}
</style>
