<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useIdeaStore } from '../stores/ideas'
import { storeToRefs } from 'pinia'
import { dataService } from '../services/dataService'
import Skeleton from 'primevue/skeleton'
import Dialog from 'primevue/dialog'
import InputText from 'primevue/inputtext'
import Textarea from 'primevue/textarea'
import Button from 'primevue/button'
import Image from 'primevue/image'
import Dropdown from 'primevue/dropdown'
import Checkbox from 'primevue/checkbox'

const router = useRouter()
const ideaStore = useIdeaStore()
const { ideas, loading, inspirations } = storeToRefs(ideaStore)

const showCreateDialog = ref(false)
const newIdea = ref({ name: '', description: '' })
const submitting = ref(false)
const API_URL = import.meta.env.VITE_API_URL || '/api'
const isSettingsVisible = ref(localStorage.getItem('ideas_view_settings_visible') !== 'false')

watch(isSettingsVisible, (val) => {
    localStorage.setItem('ideas_view_settings_visible', val)
})

// --- Rename Idea ---
const showRenameDialog = ref(false)
const ideaToRename = ref(null)
const newName = ref('')
const renaming = ref(false)

const openRenameDialog = (idea) => {
    ideaToRename.value = idea
    newName.value = idea.name
    showRenameDialog.value = true
}

const handleRename = async () => {
    if (!newName.value.trim() || newName.value === ideaToRename.value.name) {
        showRenameDialog.value = false
        return
    }

    renaming.value = true
    try {
        await ideaStore.updateIdea(ideaToRename.value.id, {
            name: newName.value.trim()
        })
        showRenameDialog.value = false
    } finally {
        renaming.value = false
    }
}

// --- Inspirations Logic ---
const showInspirationDialog = ref(false)
const newInspirationLink = ref('')
const creatingInspiration = ref(false)
const downloadingInspirations = ref(new Set())

// Preview Logic
const showPreviewDialog = ref(false)
const previewInspiration = ref(null)
const previewAsset = ref(null)
const loadingPreview = ref(false)

const openPreview = async (insp) => {
    if (!insp || !insp.asset_id) return
    previewInspiration.value = insp
    showPreviewDialog.value = true
    loadingPreview.value = true
    previewAsset.value = null
    
    try {
        // Use HEAD request to get content-type without downloading body
        previewAsset.value = await dataService.getAssetMetadata(insp.asset_id)
    } catch (e) {
        console.error('Failed to load asset metadata', e)
        // Fallback: assume image if metadata fails, or let user try
        previewAsset.value = { content_type: 'image/jpeg' } 
    } finally {
        loadingPreview.value = false
    }
}

const getIdeaInspiration = (idea) => {
    if (idea.inspiration) return idea.inspiration
    if (idea.inspiration_id) {
        return inspirations.value.find(i => i.id === idea.inspiration_id)
    }
    return null
}

const handleCreateInspiration = async () => {
    if (!newInspirationLink.value) return
    creatingInspiration.value = true
    try {
        await ideaStore.createInspiration({ source_url: newInspirationLink.value })
        showInspirationDialog.value = false
        newInspirationLink.value = ''
    } finally {
        creatingInspiration.value = false
    }
}

const handleDeleteInspiration = async (id) => {
    if (confirm('Are you sure you want to delete this inspiration?')) {
        await ideaStore.deleteInspiration(id)
    }
}

const handleCompleteInspiration = async (id) => {
    await ideaStore.completeInspiration(id)
}

const handleDownloadInspiration = async (insp) => {
    if (!insp.asset_id) return
    
    downloadingInspirations.value.add(insp.id)
    try {
        // Use dataService which uses axios with correct headers (Auth, X-Project-ID)
        // Now returns full response object
        const response = await dataService.downloadAsset(insp.asset_id)
        const blob = response.data
        
        // Determine extension
        let ext = 'jpg'
        if (blob.type === 'video/mp4') ext = 'mp4'
        else if (blob.type === 'image/png') ext = 'png'
        else if (blob.type === 'image/jpeg') ext = 'jpg'
        else if (blob.type === 'image/webp') ext = 'webp'
        
        const fileName = `inspiration-${insp.id.substring(0, 8)}.${ext}`
        const file = new File([blob], fileName, { type: blob.type })

        // Check if mobile device
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

        if (isMobile && navigator.canShare && navigator.canShare({ files: [file] })) {
            try {
                await navigator.share({
                    files: [file],
                    title: 'Inspiration',
                    text: insp.caption || 'Check out this inspiration'
                })
            } catch (err) {
                if (err.name !== 'AbortError') {
                    console.error('Share failed', err)
                }
            }
        } else {
            // Desktop download (or fallback if share not supported)
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = fileName
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
        }
    } catch (e) {
        console.error('Download failed', e)
        // Try to extract a meaningful error message
        let msg = 'Failed to download asset'
        if (e.response) {
            msg += `: ${e.response.status} ${e.response.statusText}`
        } else if (e.message) {
            msg += `: ${e.message}`
        }
        alert(msg)
    } finally {
        downloadingInspirations.value.delete(insp.id)
    }
}

const startIdeaFromInspiration = (inspiration) => {
    selectedInspiration.value = inspiration
    isSettingsVisible.value = true
    // Optionally scroll to settings or highlight it
}


// --- Generation Settings ---
const prompt = ref('')
const selectedModel = ref('flux-schnell')
const quality = ref({ key: 'TWOK', value: '2K' })
const aspectRatio = ref({ key: 'NINESIXTEEN', value: '9:16' })
const imageCount = ref(1)
const sendToTelegram = ref(false)
const telegramId = ref('')
const useProfileImage = ref(true)
const useEnvironment = ref(false)
const isSubmittingGen = ref(false)
const selectedInspiration = ref(null) // New state for selected inspiration

// Character & Assets
const characters = ref([])
const selectedCharacter = ref(null)
const environments = ref([])
const selectedEnvironment = ref(null)
const selectedAssets = ref([])
let _savedCharacterId = null
let _savedEnvironmentId = null

const loadEnvironments = async (charId) => {
    if (!charId) {
        environments.value = []
        selectedEnvironment.value = null
        return
    }
    try {
        const response = await dataService.getEnvironments(charId)
        environments.value = Array.isArray(response) ? response : (response.environments || [])
        
        if (_savedEnvironmentId) {
            selectedEnvironment.value = environments.value.find(e => (e.id === _savedEnvironmentId || e._id === _savedEnvironmentId)) || null
            _savedEnvironmentId = null
        }
    } catch (e) {
        console.error('Failed to load environments', e)
        environments.value = []
    }
}

watch(selectedCharacter, (newChar) => {
    loadEnvironments(newChar?.id || newChar?._id)
})

const qualityOptions = ref([
    { key: 'ONEK', value: '1K' },
    { key: 'TWOK', value: '2K' },
    { key: 'FOURK', value: '4K' }
])
const aspectRatioOptions = ref([
    { key: "ONEONE", value: "1:1" },
    { key: "TWOTHREE", value: "2:3" },
    { key: "THREETWO", value: "3:2" },
    { key: "THREEFOUR", value: "3:4" },
    { key: "FOURTHREE", value: "4:3" },
    { key: "FOURFIVE", value: "4:5" },
    { key: "FIVEFOUR", value: "5:4" },
    { key: "NINESIXTEEN", value: "9:16" },
    { key: "SIXTEENNINE", value: "16:9" },
    { key: "TWENTYONENINE", value: "21:9" }
])

// Restore settings
const SETTINGS_KEY = 'idea-gen-settings'
const restoreSettings = () => {
    const stored = localStorage.getItem(SETTINGS_KEY)
    if (!stored) return
    try {
        const s = JSON.parse(stored)
        if (s.prompt) prompt.value = s.prompt
        if (s.quality) quality.value = s.quality
        if (s.aspectRatio) aspectRatio.value = s.aspectRatio
        if (s.imageCount) imageCount.value = Math.min(s.imageCount, 4)
        if (s.selectedModel) selectedModel.value = s.selectedModel
        sendToTelegram.value = s.sendToTelegram || false
        telegramId.value = s.telegramId || localStorage.getItem('telegram_id') || ''
        if (s.useProfileImage !== undefined) useProfileImage.value = s.useProfileImage
        if (s.useEnvironment !== undefined) useEnvironment.value = s.useEnvironment
        _savedCharacterId = s.selectedCharacterId || null
        _savedEnvironmentId = s.selectedEnvironmentId || null
        if (s.selectedAssetIds && s.selectedAssetIds.length > 0) {
            selectedAssets.value = s.selectedAssetIds.map(id => ({
                id,
                url: `/assets/${id}`,
                name: 'Asset ' + id.substring(0, 4)
            }))
        }
        // Note: We don't restore selectedInspiration to avoid stale state, or we could if needed.
    } catch (e) {
        console.error('Failed to restore settings', e)
    }
}

const saveSettings = () => {
    const settings = {
        prompt: prompt.value,
        quality: quality.value,
        aspectRatio: aspectRatio.value,
        imageCount: imageCount.value,
        selectedModel: selectedModel.value,
        sendToTelegram: sendToTelegram.value,
        telegramId: telegramId.value,
        useProfileImage: useProfileImage.value,
        useEnvironment: useEnvironment.value,
        selectedCharacterId: selectedCharacter.value?.id || null,
        selectedEnvironmentId: selectedEnvironment.value?.id || null,
        selectedAssetIds: selectedAssets.value.map(a => a.id),
    }
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings))
    if (telegramId.value) localStorage.setItem('telegram_id', telegramId.value)
}

watch([prompt, quality, aspectRatio, imageCount, selectedModel, sendToTelegram, telegramId, useProfileImage, useEnvironment, selectedCharacter, selectedEnvironment, selectedAssets], saveSettings, { deep: true })

onMounted(async () => {
    restoreSettings()
    await Promise.all([
        ideaStore.fetchIdeas(),
        ideaStore.fetchInspirations(),
        loadCharacters()
    ])
})

const loadCharacters = async () => {
    try {
        characters.value = await dataService.getCharacters()
        if (_savedCharacterId && characters.value.length > 0) {
            const found = characters.value.find(c => (c.id === _savedCharacterId || c._id === _savedCharacterId))
            if (found) selectedCharacter.value = found
            _savedCharacterId = null
        }
    } catch (e) {
        console.error('Failed to load characters', e)
    }
}

const goToDetail = (id) => {
    router.push(`/ideas/${id}`) // Navigate to IdeaDetailView
}

const createIdea = async () => {
    if (!newIdea.value.name) return
    submitting.value = true
    try {
        await ideaStore.createIdea(newIdea.value)
        showCreateDialog.value = false
        newIdea.value = { name: '', description: '' }
    } finally {
        submitting.value = false
    }
}

// Auto-generation flow
const handleGenerate = async () => {
    if (!prompt.value) return

    isSubmittingGen.value = true
    try {
        // 1. Create a random name idea
        const randomName = 'Session ' + new Date().toLocaleString()
        const ideaData = {
            name: randomName,
            description: 'Auto-generated from quick start'
        }
        
        // Pass inspiration ID if selected
        if (selectedInspiration.value) {
            ideaData.inspiration_id = selectedInspiration.value.id
        }

        const newIdea = await ideaStore.createIdea(ideaData)

        // 2. Save settings (already handled by watch, but ensure latest)
        saveSettings()

        // 3. Navigate with autostart param
        router.push({ path: `/ideas/${newIdea.id}`, query: { autostart: 'true' } })
        
        // Clear inspiration after use
        selectedInspiration.value = null

    } catch (e) {
        console.error('Failed to start session', e)
    } finally {
        isSubmittingGen.value = false
    }
}

const pastePrompt = async () => {
    try {
        const text = await navigator.clipboard.readText()
        if (text) prompt.value = text
    } catch (err) {
        console.error('Failed to read clipboard', err)
    }
}

// --- Asset Picker Logic ---
const isAssetPickerVisible = ref(false)
const assetPickerTab = ref('all') // 'all', 'uploaded', 'generated'
const modalAssets = ref([])
const isModalLoading = ref(false)
const tempSelectedAssets = ref([])
const assetPickerFileInput = ref(null)

const loadModalAssets = async () => {
    isModalLoading.value = true
    try {
        const typeParam = assetPickerTab.value === 'all' ? undefined : assetPickerTab.value
        const response = await dataService.getAssets(100, 0, typeParam)
        if (response && response.assets) {
            modalAssets.value = response.assets
        } else {
            modalAssets.value = Array.isArray(response) ? response : []
        }
    } catch (e) {
        console.error('Failed to load modal assets', e)
        modalAssets.value = []
    } finally {
        isModalLoading.value = false
    }
}

const openAssetPicker = () => {
    tempSelectedAssets.value = [...selectedAssets.value]
    isAssetPickerVisible.value = true
    loadModalAssets()
}

const toggleAssetSelection = (asset) => {
    const index = tempSelectedAssets.value.findIndex(a => a.id === asset.id)
    if (index === -1) {
        tempSelectedAssets.value.push(asset)
    } else {
        tempSelectedAssets.value.splice(index, 1)
    }
}

const confirmAssetSelection = () => {
    selectedAssets.value = [...tempSelectedAssets.value]
    isAssetPickerVisible.value = false
}

const removeAsset = (asset) => {
    selectedAssets.value = selectedAssets.value.filter(a => a.id !== asset.id)
}

watch(assetPickerTab, () => {
    if (isAssetPickerVisible.value) {
        loadModalAssets()
    }
})

const triggerAssetPickerUpload = () => {
    assetPickerFileInput.value?.click()
}

const handleAssetPickerUpload = async (event) => {
    const target = event.target
    if (target.files && target.files[0]) {
        const file = target.files[0]
        try {
            isModalLoading.value = true
            await dataService.uploadAsset(file)
            assetPickerTab.value = 'uploaded'
            loadModalAssets()
        } catch (e) {
            console.error('Failed to upload asset', e)
        } finally {
            isModalLoading.value = false
            target.value = ''
        }
    }
}
</script>

<template>
    <div class="flex flex-col h-full font-sans relative">
        <!-- Content Area (Scrollable) -->
        <div class="flex-1 overflow-y-auto p-4 md:p-6 pb-48 custom-scrollbar">
            
            <div class="flex flex-col lg:flex-row gap-6">
                <!-- LEFT COLUMN: Ideas List -->
                <div class="flex-1 flex flex-col gap-4">
                     <!-- Top Bar -->
                    <header class="flex justify-between items-center gap-0 border-b border-white/5 pb-2">
                        <div class="flex flex-row items-center justify-between gap-2">
                            <h1 class="text-lg font-bold !m-0 bg-gradient-to-r from-violet-400 to-fuchsia-400 bg-clip-text text-transparent">
                                Ideas</h1>
                            <p class="mt-0.5 mb-0 text-[10px] text-slate-500">Your creative sessions</p>
                        </div>
                    </header>

                    <!-- Loading State -->
                    <div v-if="loading && ideas.length === 0" class="flex flex-col gap-4">
                        <div v-for="i in 6" :key="i" class="glass-panel rounded-2xl p-4 flex gap-4 items-center">
                            <Skeleton width="4rem" height="4rem" class="rounded-lg" />
                            <div class="flex-1">
                                <Skeleton width="40%" height="1.5rem" class="mb-2" />
                                <Skeleton width="60%" height="1rem" />
                            </div>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div v-else-if="ideas.length === 0"
                        class="flex flex-col items-center justify-center h-96 text-slate-400 bg-slate-900/30 rounded-3xl border border-dashed border-white/10">
                        <div class="w-20 h-20 rounded-full bg-violet-500/10 flex items-center justify-center mb-6">
                            <i class="pi pi-lightbulb text-4xl text-violet-400"></i>
                        </div>
                        <h3 class="text-xl font-semibold text-white mb-2">No ideas yet</h3>
                        <p class="text-slate-400 mb-6 max-w-sm text-center">Use the panel below to start a new creative session.
                        </p>
                    </div>

                    <!-- Ideas List (Vertical) -->
                    <div v-else class="flex flex-col gap-3">
                        <div v-for="idea in ideas" :key="idea.id"
                            class="glass-panel rounded-xl p-3 flex gap-4 items-center cursor-pointer border border-white/5 hover:bg-slate-800/80 hover:border-violet-500/30 group transition-all"
                            @click="goToDetail(idea.id)">

                            <!-- Thumbnail -->
                            <div
                                class="w-16 h-16 rounded-lg bg-slate-800 flex-shrink-0 overflow-hidden relative border border-white/10">
                                <img v-if="idea.last_generation && idea.last_generation.status == 'done' && idea.last_generation.result_list.length > 0"
                                    :src="API_URL + '/assets/' + idea.last_generation.result_list[0] + '?thumbnail=true'"
                                    class="w-full h-full object-cover" />
                                <div v-else class="w-full h-full flex items-center justify-center bg-slate-800 text-slate-600">
                                    <i class="pi pi-image text-xl"></i>
                                </div>
                            </div>

                            <!-- Details -->
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2">
                                    <h3
                                        class="m-0 text-lg font-bold text-slate-200 group-hover:text-violet-300 transition-colors truncate">
                                        {{ idea.name }}</h3>
                                    <Button icon="pi pi-pencil" text rounded size="small" 
                                        class="!w-6 !h-6 !text-slate-500 hover:!text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity"
                                        @click.stop="openRenameDialog(idea)"
                                    />
                                </div>
                                <p class="m-0 text-sm text-slate-500 truncate">{{ idea.description || 'No description' }}</p>
                            </div>

                            <!-- Meta -->
                            <div class="flex items-center gap-4 text-xs text-slate-500">
                                <div v-if="getIdeaInspiration(idea)" 
                                    class="flex items-center gap-1 bg-violet-500/20 border border-violet-500/30 px-2 py-1 rounded-md text-violet-300 hover:bg-violet-500/30 transition-colors cursor-pointer"
                                    @click.stop="openPreview(getIdeaInspiration(idea))">
                                    <i class="pi pi-bolt text-[10px]"></i>
                                    <span class="hidden sm:inline">Inspiration</span>
                                </div>

                                <div class="flex items-center gap-1 bg-slate-900/50 px-2 py-1 rounded-md">
                                    <i class="pi pi-images text-[10px]"></i>
                                    <span>{{ idea.generation_ids?.length || 0 }}</span>
                                </div>
                                <i class="pi pi-chevron-right text-slate-600 group-hover:text-white transition-colors"></i>
                            </div>

                        </div>
                    </div>
                </div>

                <!-- RIGHT COLUMN: Inspirations -->
                <div class="w-full lg:w-80 flex flex-col gap-4">
                    <header class="flex justify-between items-center gap-0 border-b border-white/5 pb-2">
                        <div class="flex flex-row items-center gap-2">
                            <h2 class="text-lg font-bold !m-0 text-slate-200">Inspirations</h2>
                        </div>
                        <Button icon="pi pi-plus" size="small" rounded text 
                            class="!w-8 !h-8 !text-violet-400 hover:!bg-violet-500/10"
                            @click="showInspirationDialog = true" />
                    </header>

                    <div v-if="inspirations.length === 0" class="flex flex-col items-center justify-center py-10 text-slate-500 bg-slate-900/20 rounded-xl border border-dashed border-white/5">
                        <i class="pi pi-bolt text-2xl mb-2 opacity-50"></i>
                        <p class="text-xs">No inspirations yet</p>
                    </div>

                    <div v-else class="flex flex-col gap-3">
                        <div v-for="insp in inspirations" :key="insp.id" 
                            class="glass-panel rounded-xl p-3 flex flex-col gap-2 border border-white/5 hover:border-white/10 transition-all relative group"
                            :class="{'opacity-50': insp.is_completed}">
                            
                            <!-- Content Preview (Text Only) -->
                            <div class="text-xs text-slate-300 break-all line-clamp-3 mb-1">
                                {{ insp.caption || insp.source_url }}
                            </div>
                            
                            <!-- Source Link -->
                            <div v-if="insp.source_url" class="flex items-center gap-1 mb-1">
                                <a :href="insp.source_url" target="_blank" class="text-[10px] text-violet-400 hover:underline truncate max-w-full flex items-center gap-1">
                                    <i class="pi pi-external-link text-[8px]"></i>
                                    Source
                                </a>
                            </div>

                            <!-- Actions -->
                            <div class="flex justify-end gap-1 mt-1 border-t border-white/5 pt-2">
                                <Button v-if="insp.asset_id" 
                                    icon="pi pi-eye" 
                                    text rounded size="small" 
                                    class="!w-7 !h-7 !text-slate-500 hover:!text-violet-400"
                                    @click="openPreview(insp)" 
                                    v-tooltip="'View Content'" />

                                <Button v-if="insp.asset_id" 
                                    :icon="downloadingInspirations.has(insp.id) ? 'pi pi-spin pi-spinner' : 'pi pi-download'" 
                                    text rounded size="small" 
                                    class="!w-7 !h-7 !text-slate-500 hover:!text-blue-400"
                                    @click="handleDownloadInspiration(insp)" 
                                    v-tooltip="'Download'" />

                                <Button icon="pi pi-trash" text rounded size="small" 
                                    class="!w-7 !h-7 !text-slate-500 hover:!text-red-400"
                                    @click="handleDeleteInspiration(insp.id)" 
                                    v-tooltip="'Delete'" />
                                
                                <Button v-if="!insp.is_completed" icon="pi pi-check" text rounded size="small" 
                                    class="!w-7 !h-7 !text-slate-500 hover:!text-green-400"
                                    @click="handleCompleteInspiration(insp.id)" 
                                    v-tooltip="'Mark Complete'" />
                                
                                <Button v-if="!insp.is_completed" icon="pi pi-sparkles" text rounded size="small" 
                                    class="!w-7 !h-7 !text-violet-400 hover:!bg-violet-500/20"
                                    @click="startIdeaFromInspiration(insp)" 
                                    v-tooltip="'Create Idea'" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rename Dialog -->
        <Dialog v-model:visible="showRenameDialog" header="Rename Idea" modal :style="{ width: '400px' }"
            :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">
                <div class="flex flex-col gap-1">
                    <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">New Name</label>
                    <InputText v-model="newName" class="w-full !bg-slate-700 !border-white/10 !text-white" autofocus @keyup.enter="handleRename" />
                </div>
                <div class="flex justify-end gap-2 mt-2">
                    <Button label="Cancel" text @click="showRenameDialog = false" class="!text-slate-400 hover:!text-white" />
                    <Button label="Save" :loading="renaming" @click="handleRename" class="!bg-violet-600 !border-none hover:!bg-violet-500" />
                </div>
            </div>
        </Dialog>

        <!-- Create Inspiration Dialog -->
        <Dialog v-model:visible="showInspirationDialog" header="Add Inspiration" modal :style="{ width: '400px' }"
            :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">
                <div class="flex flex-col gap-1">
                    <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Instagram Link / Content</label>
                    <InputText v-model="newInspirationLink" placeholder="https://instagram.com/..." class="w-full !bg-slate-700 !border-white/10 !text-white" autofocus @keyup.enter="handleCreateInspiration" />
                </div>
                <div class="flex justify-end gap-2 mt-2">
                    <Button label="Cancel" text @click="showInspirationDialog = false" class="!text-slate-400 hover:!text-white" />
                    <Button label="Add" :loading="creatingInspiration" @click="handleCreateInspiration" class="!bg-violet-600 !border-none hover:!bg-violet-500" />
                </div>
            </div>
        </Dialog>

        <!-- Preview Dialog -->
        <Dialog v-model:visible="showPreviewDialog" modal :header="previewInspiration?.caption || 'Preview'" 
            :style="{ width: '90vw', maxWidth: '800px' }"
            :pt="{ root: { class: '!bg-slate-900 !border !border-white/10' }, header: { class: '!bg-slate-900 !border-b !border-white/5 !text-white' }, content: { class: '!bg-slate-900 !p-0' }, closeButton: { class: '!text-slate-400 hover:!text-white' } }">
            <div class="flex flex-col items-center justify-center p-4 min-h-[300px]">
                <div v-if="loadingPreview" class="flex flex-col items-center gap-2">
                    <i class="pi pi-spin pi-spinner text-violet-500 text-2xl"></i>
                    <span class="text-slate-400 text-sm">Loading content...</span>
                </div>
                <div v-else-if="previewAsset" class="w-full h-full flex items-center justify-center">
                    <video v-if="previewAsset.content_type?.startsWith('video/')" 
                        :src="API_URL + '/assets/' + previewInspiration.asset_id" 
                        controls autoplay class="max-w-full max-h-[70vh] rounded-lg shadow-2xl">
                    </video>
                    <img v-else 
                        :src="API_URL + '/assets/' + previewInspiration.asset_id" 
                        class="max-w-full max-h-[70vh] rounded-lg shadow-2xl object-contain" />
                </div>
                <div v-else class="text-slate-500">
                    Failed to load content
                </div>
            </div>
        </Dialog>

        <!-- SETTINGS PANEL (Bottom - Persistent) -->
        <div v-if="isSettingsVisible"
            class="absolute bottom-4 left-1/2 -translate-x-1/2 w-[95%] max-w-4xl glass-panel border border-white/10 bg-slate-900/95 backdrop-blur-xl px-4 py-3 z-[60] !rounded-[2rem] shadow-2xl flex flex-col gap-1 max-h-[60vh] overflow-y-auto">

            <div class="w-full flex justify-center -mt-1 mb-1 cursor-pointer" @click="isSettingsVisible = false">
                <div class="w-12 h-1 bg-white/20 rounded-full hover:bg-white/40 transition-colors"></div>
            </div>

            <!-- Selected Inspiration Indicator -->
            <div v-if="selectedInspiration" class="flex items-center gap-2 bg-violet-500/20 border border-violet-500/30 rounded-lg px-3 py-2 mb-2 animate-in fade-in slide-in-from-bottom-2">
                <i class="pi pi-bolt text-violet-400 text-sm"></i>
                <span class="text-xs text-violet-200 truncate flex-1">Using inspiration: {{ selectedInspiration.caption || selectedInspiration.source_url }}</span>
                <Button icon="pi pi-times" text rounded size="small" class="!w-5 !h-5 !text-violet-300 hover:!text-white" @click="selectedInspiration = null" />
            </div>

            <div class="flex flex-col lg:flex-row gap-3">
                <!-- LEFT COLUMN: Prompt + Character + Assets -->
                <div class="flex-1 flex flex-col gap-2">
                    <!-- Prompt -->
                    <div class="flex flex-col gap-1">
                        <div class="flex justify-between items-center">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Prompt</label>
                            <div class="flex gap-1">
                                <Button icon="pi pi-clipboard" label="Paste" size="small" text
                                    class="!text-slate-400 hover:!text-white hover:!bg-white/10 !py-0 !px-1.5 !text-[9px] !h-5"
                                    @click="pastePrompt" />
                                <Button icon="pi pi-times" label="Clear" size="small" text
                                    class="!text-slate-400 hover:!text-white hover:!bg-white/10 !py-0 !px-1.5 !text-[9px] !h-5"
                                    @click="prompt = ''" />
                            </div>
                        </div>
                        <Textarea v-model="prompt" rows="2"
                            placeholder="Describe what you want to create... (Auto-starts new session)"
                            class="w-full !h-28 bg-slate-800 !text-[16px] border-white/10 text-white rounded-lg p-2 focus:border-violet-500 focus:ring-1 focus:ring-violet-500/50 transition-all resize-none shadow-inner" />
                    </div>

                    <!-- Character & Assets Row -->
                    <div class="flex flex-col md:flex-row gap-2">
                        <div class="flex-1 flex flex-col gap-1">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Character</label>
                            <Dropdown v-model="selectedCharacter" :options="characters" optionLabel="name"
                                placeholder="Select Character" filter showClear
                                class="w-full !bg-slate-800 !border-white/10 !text-white !rounded-xl" :pt="{
                                    root: { class: '!bg-slate-800' },
                                    input: { class: '!text-white' },
                                    trigger: { class: '!text-slate-400' },
                                    panel: { class: '!bg-slate-800 !border-white/10' },
                                    item: { class: '!text-slate-300 hover:!bg-white/10 hover:!text-white' }
                                }">
                                <template #value="slotProps">
                                    <div v-if="slotProps.value" class="flex items-center gap-2">
                                        <img v-if="slotProps.value.avatar_image"
                                            :src="API_URL + slotProps.value.avatar_image"
                                            class="w-6 h-6 rounded-full object-cover" />
                                        <span>{{ slotProps.value.name }}</span>
                                    </div>
                                    <span v-else>{{ slotProps.placeholder }}</span>
                                </template>
                                <template #option="slotProps">
                                    <div class="flex items-center gap-2">
                                        <img v-if="slotProps.option.avatar_image"
                                            :src="API_URL + slotProps.option.avatar_image"
                                            class="w-8 h-8 rounded-full object-cover" />
                                        <span>{{ slotProps.option.name }}</span>
                                    </div>
                                </template>
                            </Dropdown>

                                                                            <div v-if="selectedCharacter"
                                                                                class="flex flex-wrap items-center gap-x-4 gap-y-2 mt-2 px-1 animate-in fade-in slide-in-from-top-1">
                                                                                <div class="flex items-center gap-2">
                                                                                    <Checkbox v-model="useProfileImage" :binary="true" inputId="idea-use-profile-img"
                                                                                        class="!border-white/20" :pt="{
                                                                                            box: ({ props, state }) => ({
                                                                                                class: ['!bg-slate-800 !border-white/20', { '!bg-violet-600 !border-violet-600': props.modelValue }]
                                                                                            })
                                                                                        }" />
                                                                                    <label for="idea-use-profile-img"
                                                                                        class="text-xs text-slate-300 cursor-pointer select-none">Use Photo</label>
                                                                                </div>
                                                                                
                                                                                <div class="flex items-center gap-2">
                                                                                    <Checkbox v-model="useEnvironment" :binary="true" inputId="idea-use-env"
                                                                                        class="!border-white/20" :pt="{
                                                                                            box: ({ props, state }) => ({
                                                                                                class: ['!bg-slate-800 !border-white/20', { '!bg-violet-600 !border-violet-600': props.modelValue }]
                                                                                            })
                                                                                        }" />
                                                                                    <label for="idea-use-env"
                                                                                        class="text-xs text-slate-300 cursor-pointer select-none">Use Environment</label>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                
                                                                        <div class="flex-1 flex flex-col gap-1">
                                                                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Assets</label>
                                                                            <div @click="openAssetPicker"
                                                                                class="w-full bg-slate-800 border border-white/10 rounded-lg p-2 min-h-[38px] cursor-pointer hover:bg-slate-700/50 transition-colors flex flex-wrap gap-1.5">
                                                                                <span v-if="selectedAssets.length === 0" class="text-slate-400 text-sm py-0.5">Select
                                                                                    Assets</span>
                                                                                <div v-for="asset in selectedAssets" :key="asset.id"
                                                                                    class="px-2 py-1 bg-violet-600/30 border border-violet-500/30 text-violet-200 text-xs rounded-md flex items-center gap-2 animate-in fade-in zoom-in duration-200"
                                                                                    @click.stop>
                                                                                    <img v-if="asset.url" :src="API_URL + asset.url + '?thumbnail=true'"
                                                                                        class="w-4 h-4 rounded object-cover" />
                                                                                    <span class="truncate max-w-[100px]">{{ asset.name || 'Asset ' + (asset.id ?
                                                                                        asset.id.substring(0, 4) : '') }}</span>
                                                                                    <i class="pi pi-times cursor-pointer hover:text-white"
                                                                                        @click.stop="removeAsset(asset)"></i>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                
                                                                    <!-- Environment Row (Below) -->
                                                                    <div v-if="selectedCharacter && useEnvironment" class="flex flex-col gap-1 animate-in fade-in slide-in-from-top-1 mt-2">                        <div class="flex justify-between items-center">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Environment</label>
                            <Button v-if="selectedEnvironment" icon="pi pi-times" @click="selectedEnvironment = null" text size="small" 
                                class="!p-0 !h-4 !w-4 !text-[8px] text-slate-500 hover:text-white" />
                        </div>
                        
                        <div v-if="environments.length > 0" class="flex gap-2 overflow-x-auto pb-1 custom-scrollbar no-scrollbar">
                            <div v-for="env in environments" :key="env.id || env._id" 
                                @click="selectedEnvironment = env"
                                class="flex-shrink-0 flex items-center gap-2 px-2 py-1.5 rounded-lg border-2 transition-all cursor-pointer group bg-slate-800/40"
                                :class="[
                                    (selectedEnvironment?.id === (env.id || env._id) || selectedEnvironment?._id === (env.id || env._id))
                                    ? 'border-violet-500 bg-violet-500/10 shadow-[0_0_15px_rgba(124,58,237,0.1)]' 
                                    : 'border-white/5 hover:border-white/20'
                                ]"
                            >
                                <div class="w-6 h-6 rounded overflow-hidden flex-shrink-0 bg-slate-900 flex items-center justify-center border border-white/5">
                                    <img v-if="env.asset_ids?.length > 0" 
                                        :src="API_URL + '/assets/' + env.asset_ids[0] + '?thumbnail=true'" 
                                        class="w-full h-full object-cover" 
                                    />
                                    <i v-else class="pi pi-map-marker text-[10px]" 
                                        :class="(selectedEnvironment?.id === (env.id || env._id) || selectedEnvironment?._id === (env.id || env._id)) ? 'text-violet-400' : 'text-slate-500'"
                                    ></i>
                                </div>
                                <span class="text-[10px] whitespace-nowrap pr-1"
                                    :class="(selectedEnvironment?.id === (env.id || env._id) || selectedEnvironment?._id === (env.id || env._id)) ? 'text-violet-300 font-bold' : 'text-slate-400 group-hover:text-slate-200'"
                                >
                                    {{ env.name }}
                                </span>
                                <i v-if="(selectedEnvironment?.id === (env.id || env._id) || selectedEnvironment?._id === (env.id || env._id))" 
                                    class="pi pi-check text-violet-400 text-[8px]"></i>
                            </div>
                        </div>
                        <div v-else class="py-2 px-3 bg-slate-800/50 border border-white/5 rounded-xl text-center">
                            <p class="text-[9px] text-slate-600 uppercase m-0">No environments</p>
                        </div>
                    </div>                </div>

                <!-- RIGHT COLUMN: Settings & Button -->
                <div class="w-full lg:w-72 flex flex-col gap-2">
                    <div class="grid grid-cols-2 gap-2">
                        <div class="flex flex-col gap-1">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Quality</label>
                            <Dropdown v-model="quality" :options="qualityOptions" optionLabel="value"
                                class="w-full !bg-slate-800 !border-white/10 !text-white !rounded-xl"
                                :pt="{ input: { class: '!text-white' }, trigger: { class: '!text-slate-400' }, panel: { class: '!bg-slate-800 !border-white/10' }, item: { class: '!text-slate-300 hover:!bg-white/10 hover:!text-white' } }" />
                        </div>
                        <div class="flex flex-col gap-1">
                            <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Ratio</label>
                            <Dropdown v-model="aspectRatio" :options="aspectRatioOptions" optionLabel="value"
                                class="w-full !bg-slate-800 !border-white/10 !text-white !rounded-xl"
                                :pt="{ input: { class: '!text-white' }, trigger: { class: '!text-slate-400' }, panel: { class: '!bg-slate-800 !border-white/10' }, item: { class: '!text-slate-300 hover:!bg-white/10 hover:!text-white' } }" />
                        </div>
                    </div>

                    <!-- Generation Count -->
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Count</label>
                        <div class="flex items-center">
                            <div class="flex-1 flex bg-slate-800 rounded-lg border border-white/10 overflow-hidden">
                                <button v-for="n in 4" :key="n" @click="imageCount = n"
                                    class="flex-1 py-1 text-xs font-bold transition-all"
                                    :class="imageCount === n ? 'bg-violet-600 text-white' : 'text-slate-400 hover:text-white hover:bg-white/5'">
                                    {{ n }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Telegram (Copied from Detail View) -->
                    <div class="flex flex-col gap-1 bg-slate-800/50 p-2 rounded-lg border border-white/5">
                        <div class="flex items-center gap-2">
                            <Checkbox v-model="sendToTelegram" :binary="true" inputId="idea-tg-check" />
                            <label for="idea-tg-check" class="text-xs text-slate-300 cursor-pointer">Send to
                                Telegram</label>
                        </div>
                        <div v-if="sendToTelegram" class="animate-in fade-in slide-in-from-top-1">
                            <InputText v-model="telegramId" placeholder="Telegram ID"
                                class="w-full !text-[16px] !bg-slate-900 !border-white/10 !text-white !py-1.5" />
                        </div>
                    </div>


                    <div class="mt-auto">
                        <Button :label="isSubmittingGen ? 'Starting...' : 'Generate New Session'"
                            :icon="isSubmittingGen ? 'pi pi-spin pi-spinner' : 'pi pi-sparkles'"
                            :loading="isSubmittingGen" :disabled="isSubmittingGen || !prompt" @click="handleGenerate"
                            class="w-full !py-2 !text-sm !font-bold !bg-gradient-to-r from-violet-600 to-cyan-500 !border-none !rounded-lg !shadow-lg !shadow-violet-500/20 hover:!scale-[1.02] transition-all disabled:opacity-50 disabled:cursor-not-allowed" />
                    </div>
                </div>
            </div>
        </div>

        <transition name="fade">
            <div v-if="!isSettingsVisible" class="absolute bottom-24 md:bottom-8 left-1/2 -translate-x-1/2 z-10">
                <Button label="Open Controls" icon="pi pi-chevron-up" @click="isSettingsVisible = true" rounded
                    class="!bg-violet-600 !border-none !shadow-xl !font-bold shadow-violet-500/40 !px-6 !py-3" />
            </div>
        </transition>

        <Dialog v-model:visible="isAssetPickerVisible" modal header="Select Assets"
            :style="{ width: '80vw', maxWidth: '900px' }"
            :pt="{ root: { class: '!bg-slate-900 !border !border-white/10' }, header: { class: '!bg-slate-900 !border-b !border-white/5 !text-white' }, content: { class: '!bg-slate-900 !p-0' }, footer: { class: '!bg-slate-900 !border-t !border-white/5 !p-4' }, closeButton: { class: '!text-slate-400 hover:!text-white' } }">
            <div class="flex flex-col h-[70vh]">
                <!-- Tabs -->
                <div class="flex border-b border-white/5 px-4 items-center">
                    <button v-for="tab in ['all', 'uploaded', 'generated']" :key="tab" @click="assetPickerTab = tab"
                        class="px-4 py-3 text-sm font-medium border-b-2 transition-colors capitalize"
                        :class="assetPickerTab === tab ? 'border-violet-500 text-violet-400' : 'border-transparent text-slate-400 hover:text-slate-200'">
                        {{ tab }}
                    </button>
                    <!-- Upload Action -->
                    <div class="ml-auto flex items-center">
                        <input type="file" ref="assetPickerFileInput" @change="handleAssetPickerUpload" class="hidden"
                            accept="image/*" />
                        <Button icon="pi pi-upload" label="Upload" @click="triggerAssetPickerUpload"
                            class="!text-xs !bg-violet-600/20 !text-violet-300 hover:!bg-violet-600/40 !border-none !px-3 !py-1.5 !rounded-lg" />
                    </div>
                </div>

                <!-- Grid -->
                <div class="flex-1 overflow-y-auto p-4 custom-scrollbar">
                    <div v-if="isModalLoading" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
                        <Skeleton v-for="i in 10" :key="i" height="150px" class="!bg-slate-800 rounded-xl" />
                    </div>
                    <div v-else-if="modalAssets.length > 0"
                        class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
                        <div v-for="asset in modalAssets" :key="asset.id" @click="toggleAssetSelection(asset)"
                            class="relative aspect-square rounded-xl overflow-hidden cursor-pointer border-2 transition-all group"
                            :class="tempSelectedAssets.some(a => a.id === asset.id) ? 'border-violet-500 ring-2 ring-violet-500/30' : 'border-transparent hover:border-white/20'">
                            <img :src="API_URL + asset.url + '?thumbnail=true'" class="w-full h-full object-cover" />
                            <div class="absolute bottom-0 left-0 right-0 p-2 bg-black/60 backdrop-blur-sm">
                                <p class="text-[10px] text-white truncate">{{ asset.name || 'Asset ' + (asset.id ?
                                    asset.id.substring(0, 4) : '') }}</p>
                            </div>
                            <!-- Checkmark -->
                            <div v-if="tempSelectedAssets.some(a => a.id === asset.id)"
                                class="absolute top-2 right-2 w-6 h-6 bg-violet-500 rounded-full flex items-center justify-center shadow-lg animate-in zoom-in duration-200">
                                <i class="pi pi-check text-white text-xs"></i>
                            </div>
                        </div>
                    </div>
                    <div v-else class="flex flex-col items-center justify-center h-full text-slate-500">
                        <i class="pi pi-image text-4xl mb-2 opacity-50"></i>
                        <p>No assets found</p>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="flex justify-end gap-2">
                    <Button label="Cancel" @click="isAssetPickerVisible = false"
                        class="!text-slate-300 hover:!bg-white/5" text />
                    <Button :label="'Select (' + tempSelectedAssets.length + ')'" @click="confirmAssetSelection"
                        class="!bg-violet-600 !border-none hover:!bg-violet-500" />
                </div>
            </template>
        </Dialog>

    </div>
</template>

<style scoped>
.glass-panel {
    background: rgba(255, 255, 255, 0.03);
    backdrop-filter: blur(10px);
}

.custom-scrollbar::-webkit-scrollbar {
    width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.02);
}

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

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