<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Head } from '@inertiajs/vue3'
import OnoxLogo from '@/Components/OnoxLogo.vue'

const props = defineProps({
    components:      { type: Object,  default: () => ({}) },   // grouped by category
    activeIncidents: { type: Array,   default: () => [] },
    pastIncidents:   { type: Array,   default: () => [] },
    maintenance:     { type: Array,   default: () => [] },
    overallStatus:   { type: String,  default: 'operational' },
})

// ── Auto-refresh every 60 s ──────────────────────────────────────────────────
let refreshTimer = null
onMounted(() => {
    refreshTimer = setInterval(() => {
        window.location.reload()
    }, 60_000)
})
onUnmounted(() => clearInterval(refreshTimer))

// ── Overall status display ───────────────────────────────────────────────────
const overallConfig = computed(() => {
    const map = {
        operational:    { label: 'Tüm Sistemler Operasyonel',     bg: 'bg-emerald-500',  text: 'text-white' },
        degraded:       { label: 'Servis Yavaşlaması Var',         bg: 'bg-yellow-500',   text: 'text-white' },
        partial_outage: { label: 'Kısmi Servis Kesintisi',         bg: 'bg-orange-500',   text: 'text-white' },
        major_outage:   { label: 'Büyük Servis Kesintisi',         bg: 'bg-red-600',      text: 'text-white' },
        maintenance:    { label: 'Planlı Bakım Devam Ediyor',      bg: 'bg-blue-500',     text: 'text-white' },
    }
    return map[props.overallStatus] ?? map.operational
})

// ── Component status helpers ─────────────────────────────────────────────────
const statusBadge = (status) => {
    const map = {
        operational:    { label: 'Operasyonel',    cls: 'bg-emerald-100 text-emerald-700 ring-emerald-600/20' },
        degraded:       { label: 'Yavaşlama',      cls: 'bg-yellow-100  text-yellow-700  ring-yellow-600/20' },
        partial_outage: { label: 'Kısmi Kesinti',  cls: 'bg-orange-100  text-orange-700  ring-orange-600/20' },
        major_outage:   { label: 'Büyük Kesinti',  cls: 'bg-red-100     text-red-700     ring-red-600/20' },
        maintenance:    { label: 'Bakımda',         cls: 'bg-blue-100    text-blue-700    ring-blue-600/20' },
    }
    return map[status] ?? { label: status, cls: 'bg-gray-100 text-gray-600 ring-gray-500/20' }
}

// ── 90-day bar color ─────────────────────────────────────────────────────────
const barColor = (uptime) => {
    if (uptime === null) return 'bg-slate-200'
    if (uptime >= 99)   return 'bg-emerald-500'
    if (uptime >= 95)   return 'bg-yellow-400'
    if (uptime >= 80)   return 'bg-orange-400'
    return 'bg-red-500'
}

const barTitle = (day) => {
    if (day.uptime === null) return `${day.date}: Veri yok`
    return `${day.date}: %${day.uptime} uptime`
}

// ── Category labels (TR) ─────────────────────────────────────────────────────
const categoryLabel = (key) => ({
    'infrastructure':    'Altyapı',
    'customer-facing':   'Müşteri Servisleri',
    'internal':          'Dahili Servisler',
}[key] ?? key)

// ── Incident helpers ─────────────────────────────────────────────────────────
const incidentImpactCls = (impact) => ({
    none:     'bg-gray-100  text-gray-600',
    minor:    'bg-yellow-100 text-yellow-700',
    major:    'bg-orange-100 text-orange-700',
    critical: 'bg-red-100   text-red-700',
}[impact] ?? 'bg-gray-100 text-gray-600')

const incidentImpactLabel = (impact) => ({
    none:     'Etkisiz',
    minor:    'Küçük Etki',
    major:    'Büyük Etki',
    critical: 'Kritik',
}[impact] ?? impact)

const incidentStatusLabel = (status) => ({
    investigating: 'İnceleniyor',
    identified:    'Tespit Edildi',
    monitoring:    'İzleniyor',
    resolved:      'Çözüldü',
    postmortem:    'Olay Raporu',
}[status] ?? status)

// ── Past incidents collapsible ───────────────────────────────────────────────
const pastExpanded = ref(false)

// ── Date formatting ──────────────────────────────────────────────────────────
const fmt = (iso) => {
    if (!iso) return ''
    return new Date(iso).toLocaleString('tr-TR', {
        day: '2-digit', month: 'long', year: 'numeric',
        hour: '2-digit', minute: '2-digit',
    })
}

const fmtDate = (iso) => {
    if (!iso) return ''
    return new Date(iso).toLocaleDateString('tr-TR', { day: '2-digit', month: 'long', year: 'numeric' })
}

// ── RSS / Subscribe ──────────────────────────────────────────────────────────
const subscribeOpen = ref(false)
</script>

<template>
    <Head title="Sistem Durumu — Onoxsoft Panel" />

    <div class="min-h-screen bg-slate-50 text-slate-800 font-sans">

        <!-- ── Nav ─────────────────────────────────────────────────────────── -->
        <nav class="border-b border-slate-200 bg-white">
            <div class="mx-auto max-w-5xl flex items-center justify-between px-4 py-4 sm:px-6">
                <a href="/" class="flex items-center gap-3">
                    <OnoxLogo variant="mark" theme="light" class="h-8 w-8" />
                    <div class="leading-none">
                        <div class="text-lg font-bold text-slate-900 tracking-tight">Onoxsoft Panel</div>
                        <div class="text-[10px] uppercase tracking-widest text-slate-400">Sistem Durumu</div>
                    </div>
                </a>
                <div class="flex items-center gap-3">
                    <a :href="route('status.rss')"
                       class="rounded-md border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50"
                       target="_blank">
                        RSS
                    </a>
                    <a :href="route('status.api')"
                       class="rounded-md border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50"
                       target="_blank">
                        JSON API
                    </a>
                    <button
                        @click="subscribeOpen = !subscribeOpen"
                        class="rounded-md bg-slate-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-slate-700">
                        Bildirim Al
                    </button>
                </div>
            </div>
        </nav>

        <!-- ── Subscribe panel ─────────────────────────────────────────────── -->
        <div v-if="subscribeOpen" class="border-b border-slate-200 bg-white px-4 py-4 sm:px-6">
            <div class="mx-auto max-w-5xl">
                <p class="mb-3 text-sm font-medium text-slate-700">Durum güncellemelerini takip et:</p>
                <div class="flex flex-wrap gap-3">
                    <a :href="route('status.rss')"
                       class="inline-flex items-center gap-2 rounded-lg border border-orange-200 bg-orange-50 px-4 py-2 text-sm font-medium text-orange-700 hover:bg-orange-100">
                        <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24"><path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19.01 7.38 20 6.18 20C4.98 20 4 19.01 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1z"/></svg>
                        RSS Feed'e Abone Ol
                    </a>
                    <a :href="route('status.api')"
                       class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100">
                        <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/></svg>
                        JSON API Entegrasyonu
                    </a>
                </div>
            </div>
        </div>

        <!-- ── Overall status banner ───────────────────────────────────────── -->
        <div :class="['py-10 sm:py-14 text-center', overallConfig.bg, overallConfig.text]">
            <div class="mx-auto max-w-5xl px-4 sm:px-6">
                <div class="inline-flex items-center gap-3">
                    <span class="relative flex h-4 w-4">
                        <span v-if="overallStatus === 'operational'"
                              class="animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-40"></span>
                        <span class="relative inline-flex h-4 w-4 rounded-full bg-white/80"></span>
                    </span>
                    <h1 class="text-xl font-semibold sm:text-2xl">{{ overallConfig.label }}</h1>
                </div>
                <p class="mt-2 text-sm opacity-80">
                    Son güncelleme: {{ new Date().toLocaleString('tr-TR') }}
                    <span class="ml-2 opacity-60">(her 60 saniyede otomatik yenilenir)</span>
                </p>
            </div>
        </div>

        <div class="mx-auto max-w-5xl px-4 py-10 sm:px-6 space-y-12">

            <!-- ── Active incidents ─────────────────────────────────────────── -->
            <section v-if="activeIncidents.length > 0">
                <h2 class="mb-4 text-base font-semibold text-slate-900">Aktif Olaylar</h2>
                <div class="space-y-4">
                    <div v-for="incident in activeIncidents" :key="incident.id"
                         class="rounded-xl border border-orange-200 bg-orange-50 p-5">
                        <div class="flex flex-wrap items-start justify-between gap-2">
                            <div>
                                <h3 class="font-semibold text-slate-900">{{ incident.title }}</h3>
                                <p class="mt-0.5 text-xs text-slate-500">{{ fmt(incident.started_at) }}</p>
                            </div>
                            <div class="flex gap-2">
                                <span :class="['rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset', incidentImpactCls(incident.impact)]">
                                    {{ incidentImpactLabel(incident.impact) }}
                                </span>
                                <span class="rounded-full bg-orange-100 px-2 py-0.5 text-[11px] font-semibold text-orange-700 ring-1 ring-inset ring-orange-600/20">
                                    {{ incidentStatusLabel(incident.status) }}
                                </span>
                            </div>
                        </div>
                        <p v-if="incident.description" class="mt-2 text-sm text-slate-700">{{ incident.description }}</p>

                        <!-- Updates timeline -->
                        <div v-if="incident.updates?.length" class="mt-4 space-y-3 border-t border-orange-200 pt-4">
                            <div v-for="upd in incident.updates" :key="upd.id"
                                 class="flex gap-3 text-sm">
                                <div class="mt-1 h-2 w-2 shrink-0 rounded-full bg-orange-400"></div>
                                <div>
                                    <span class="font-medium text-slate-700">{{ incidentStatusLabel(upd.status) }}</span>
                                    <span class="mx-1 text-slate-400">—</span>
                                    <span class="text-slate-600">{{ upd.message }}</span>
                                    <p class="text-xs text-slate-400 mt-0.5">{{ fmt(upd.posted_at) }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- ── Scheduled maintenance ────────────────────────────────────── -->
            <section v-if="maintenance.length > 0">
                <h2 class="mb-4 text-base font-semibold text-slate-900">Planlı Bakım</h2>
                <div class="space-y-3">
                    <div v-for="m in maintenance" :key="m.id"
                         class="rounded-xl border border-blue-200 bg-blue-50 p-5">
                        <div class="flex flex-wrap items-start justify-between gap-2">
                            <h3 class="font-semibold text-slate-900">{{ m.title }}</h3>
                            <span :class="[
                                'rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset',
                                m.status === 'in_progress' ? 'bg-blue-200 text-blue-800 ring-blue-600/20' : 'bg-blue-100 text-blue-700 ring-blue-600/20'
                            ]">
                                {{ m.status === 'in_progress' ? 'Devam Ediyor' : 'Planlandı' }}
                            </span>
                        </div>
                        <p class="mt-1 text-sm text-slate-600">{{ m.description }}</p>
                        <p class="mt-2 text-xs text-slate-500">
                            {{ fmt(m.scheduled_start_at) }} → {{ fmt(m.scheduled_end_at) }}
                        </p>
                    </div>
                </div>
            </section>

            <!-- ── Components by category ───────────────────────────────────── -->
            <section v-for="(items, category) in components" :key="category">
                <h2 class="mb-4 text-base font-semibold text-slate-900">{{ categoryLabel(category) }}</h2>
                <div class="divide-y divide-slate-100 rounded-xl border border-slate-200 bg-white overflow-hidden">
                    <div v-for="component in items" :key="component.id"
                         class="px-5 py-4">
                        <div class="flex flex-wrap items-center justify-between gap-3">
                            <div class="flex items-center gap-3">
                                <span :class="[
                                    'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset',
                                    statusBadge(component.current_status).cls
                                ]">
                                    {{ statusBadge(component.current_status).label }}
                                </span>
                                <div>
                                    <span class="font-medium text-slate-900 text-sm">{{ component.name }}</span>
                                    <p v-if="component.description" class="text-xs text-slate-500 mt-0.5">{{ component.description }}</p>
                                </div>
                            </div>
                            <div class="flex items-center gap-4 text-xs text-slate-500">
                                <span v-if="component.avg_response_ms">
                                    {{ component.avg_response_ms }}ms
                                </span>
                                <span class="font-medium">
                                    %{{ component.uptime_24h }} <span class="font-normal opacity-70">(24s)</span>
                                </span>
                                <span class="font-medium">
                                    %{{ component.uptime_30d }} <span class="font-normal opacity-70">(30g)</span>
                                </span>
                            </div>
                        </div>

                        <!-- 90-day bar chart -->
                        <div v-if="component.daily_uptime_90d?.length" class="mt-3">
                            <div class="flex items-end gap-px h-6">
                                <div
                                    v-for="day in component.daily_uptime_90d"
                                    :key="day.date"
                                    :class="['flex-1 rounded-sm transition-opacity hover:opacity-70 cursor-default', barColor(day.uptime)]"
                                    :style="{ height: day.uptime !== null ? Math.max(20, day.uptime) + '%' : '20%' }"
                                    :title="barTitle(day)"
                                ></div>
                            </div>
                            <div class="mt-1 flex justify-between text-[10px] text-slate-400">
                                <span>90 gün önce</span>
                                <span>Bugün</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- ── Past incidents ───────────────────────────────────────────── -->
            <section v-if="pastIncidents.length > 0">
                <button
                    @click="pastExpanded = !pastExpanded"
                    class="flex w-full items-center justify-between rounded-lg border border-slate-200 bg-white px-5 py-3 text-sm font-medium text-slate-700 hover:bg-slate-50">
                    Son 30 gündeki olaylar ({{ pastIncidents.length }})
                    <svg :class="['h-4 w-4 transition-transform', pastExpanded ? 'rotate-180' : '']"
                         fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                    </svg>
                </button>

                <div v-if="pastExpanded" class="mt-2 space-y-2">
                    <div v-for="incident in pastIncidents" :key="incident.id"
                         class="rounded-lg border border-slate-200 bg-white px-5 py-3">
                        <div class="flex flex-wrap items-center justify-between gap-2">
                            <div>
                                <span class="text-sm font-medium text-slate-800">{{ incident.title }}</span>
                                <p class="text-xs text-slate-500 mt-0.5">{{ fmtDate(incident.started_at) }}</p>
                            </div>
                            <div class="flex gap-2">
                                <span :class="['rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset', incidentImpactCls(incident.impact)]">
                                    {{ incidentImpactLabel(incident.impact) }}
                                </span>
                                <span class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 ring-1 ring-inset ring-emerald-600/20">
                                    Çözüldü
                                </span>
                            </div>
                        </div>
                        <p v-if="incident.description" class="mt-1 text-sm text-slate-600">{{ incident.description }}</p>
                    </div>
                </div>
            </section>

            <!-- ── No issues ────────────────────────────────────────────────── -->
            <section v-if="!activeIncidents.length && !maintenance.length">
                <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-6 py-8 text-center">
                    <svg class="mx-auto h-10 w-10 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    <p class="mt-3 text-base font-semibold text-emerald-800">Aktif olay veya planlı bakım yok.</p>
                    <p class="mt-1 text-sm text-emerald-600">Tüm sistemler normal şekilde çalışıyor.</p>
                </div>
            </section>
        </div>

        <!-- ── Footer ──────────────────────────────────────────────────────── -->
        <footer class="mt-16 border-t border-slate-200 bg-white py-6 text-center text-xs text-slate-400">
            <p>
                <a href="/" class="hover:text-slate-600">Onoxsoft Kontrol Paneli</a>
                &nbsp;·&nbsp;
                <a :href="route('status.rss')" class="hover:text-slate-600">RSS</a>
                &nbsp;·&nbsp;
                <a :href="route('status.api')" class="hover:text-slate-600">JSON API</a>
            </p>
        </footer>
    </div>
</template>
