<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Link, router, usePage } from '@inertiajs/vue3'
import axios from 'axios'
import {
    BellIcon,
    CheckCircleIcon,
    ShieldCheckIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    CreditCardIcon,
    Cog6ToothIcon,
    EnvelopeIcon,
    XMarkIcon,
    InboxIcon,
} from '@heroicons/vue/24/outline'

const open = ref(false)
const recent = ref([])
const loading = ref(false)
const page = usePage()

const unreadCount = computed(() => page.props.notifications?.unread_count || 0)

const fetchRecent = async () => {
    if (loading.value) return
    loading.value = true
    try {
        const { data } = await axios.get(route('notifications.recent'))
        recent.value = data.notifications
    } catch (e) {
        // silent fail
    } finally {
        loading.value = false
    }
}

const toggle = () => {
    open.value = !open.value
    if (open.value) fetchRecent()
}

const markRead = (id) => {
    router.post(route('notifications.read', id), {}, {
        preserveScroll: true,
        preserveState: true,
        onSuccess: () => fetchRecent(),
    })
}

const markAllRead = () => {
    router.post(route('notifications.read-all'), {}, {
        preserveScroll: true,
        preserveState: true,
        onSuccess: () => { fetchRecent(); open.value = false },
    })
}

const handleClick = (n) => {
    if (!n.is_read) markRead(n.id)
    open.value = false
    if (n.link) router.visit(n.link)
}

const categoryIcon = (cat) => ({
    security: ShieldCheckIcon,
    billing: CreditCardIcon,
    system: Cog6ToothIcon,
    warning: ExclamationTriangleIcon,
    error: ExclamationTriangleIcon,
    success: CheckCircleIcon,
    info: InformationCircleIcon,
}[cat] || BellIcon)

const categoryColor = (cat) => ({
    security: 'text-purple-600 bg-purple-50',
    billing: 'text-blue-600 bg-blue-50',
    system: 'text-slate-600 bg-slate-50',
    warning: 'text-amber-600 bg-amber-50',
    error: 'text-red-600 bg-red-50',
    success: 'text-emerald-600 bg-emerald-50',
    info: 'text-indigo-600 bg-indigo-50',
}[cat] || 'text-slate-600 bg-slate-50')

// Auto-refresh every 60s
let interval
onMounted(() => {
    interval = setInterval(() => {
        // Only refresh if page is visible
        if (!document.hidden) {
            router.reload({ only: ['notifications'] })
        }
    }, 60_000)
})
onUnmounted(() => clearInterval(interval))
</script>

<template>
    <div class="relative">
        <button @click="toggle" class="relative rounded-lg p-2 text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="Bildirimler">
            <BellIcon class="h-5 w-5" />
            <span v-if="unreadCount > 0"
                  class="absolute -top-0.5 -right-0.5 flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white">
                {{ unreadCount > 99 ? '99+' : unreadCount }}
            </span>
        </button>

        <div v-if="open" @click.away="open = false"
             class="absolute right-0 mt-2 w-80 rounded-xl border border-slate-200 bg-white shadow-xl z-30 dark:border-slate-700 dark:bg-slate-800">
            <div class="flex items-center justify-between border-b border-slate-200 px-4 py-3">
                <div>
                    <h3 class="text-sm font-semibold">Bildirimler</h3>
                    <p v-if="unreadCount > 0" class="text-xs text-slate-500">{{ unreadCount }} okunmamış</p>
                </div>
                <button v-if="unreadCount > 0" @click="markAllRead" class="text-xs font-medium text-indigo-600 hover:text-indigo-700">
                    Tümünü okundu işaretle
                </button>
            </div>

            <div v-if="loading" class="px-4 py-8 text-center text-sm text-slate-500">
                <BellIcon class="mx-auto mb-2 h-8 w-8 animate-pulse text-slate-300" />
                Yükleniyor...
            </div>

            <div v-else-if="recent.length === 0" class="px-4 py-8 text-center text-sm text-slate-500">
                <InboxIcon class="mx-auto mb-2 h-10 w-10 text-slate-300" />
                Henüz bildirim yok
            </div>

            <div v-else class="max-h-96 overflow-y-auto divide-y divide-slate-100">
                <button v-for="n in recent" :key="n.id" @click="handleClick(n)"
                        :class="['w-full text-left px-4 py-3 hover:bg-slate-50 transition', !n.is_read && 'bg-indigo-50/30']">
                    <div class="flex gap-3">
                        <div :class="['flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg', categoryColor(n.category)]">
                            <component :is="categoryIcon(n.category)" class="h-5 w-5" />
                        </div>
                        <div class="flex-1 min-w-0">
                            <p :class="['text-sm', n.is_read ? 'text-slate-700' : 'font-semibold text-slate-900']">
                                {{ n.title }}
                                <span v-if="!n.is_read" class="ml-1 inline-block h-1.5 w-1.5 rounded-full bg-indigo-500"></span>
                            </p>
                            <p class="text-xs text-slate-500 line-clamp-2">{{ n.body }}</p>
                            <p class="text-xs text-slate-400 mt-1">{{ n.created_at_diff }}</p>
                        </div>
                    </div>
                </button>
            </div>

            <Link :href="route('notifications.index')" @click="open = false"
                  class="block border-t border-slate-200 px-4 py-2.5 text-center text-sm font-medium text-indigo-600 hover:bg-indigo-50">
                Tüm bildirimleri görüntüle →
            </Link>
        </div>
    </div>
</template>

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