<script setup>
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
import { usePage } from '@inertiajs/vue3'
import {
    CpuChipIcon,
    CircleStackIcon,
    ClockIcon,
    BoltIcon,
    ArrowUpIcon,
    ArrowDownIcon,
    MinusIcon,
} from '@heroicons/vue/24/outline'

const page = usePage()

// Inertia shared prop'tan ilk değer, sonra 5sn polling ile JSON refresh
const sysinfo = ref(page.props.system_info)
const previousLoad = ref(null)
let pollTimer = null

async function refresh() {
    try {
        const res = await fetch('/admin/system-info.json', {
            headers: { 'Accept': 'application/json' },
            credentials: 'include',
        })
        if (!res.ok) return
        const json = await res.json()
        if (sysinfo.value?.load_average) {
            previousLoad.value = sysinfo.value.load_average['1m']
        }
        sysinfo.value = json.data
    } catch (e) {
        // Sessiz başarısızlık — ağ sorunu, polling devam
    }
}

onMounted(() => {
    pollTimer = setInterval(refresh, 5000)
})

onBeforeUnmount(() => {
    if (pollTimer) clearInterval(pollTimer)
})

const loadTrend = computed(() => {
    const curr = sysinfo.value?.load_average?.['1m']
    const prev = previousLoad.value
    if (curr == null || prev == null) return 'flat'
    if (curr > prev + 0.05) return 'up'
    if (curr < prev - 0.05) return 'down'
    return 'flat'
})

const loadColor = (load, cores) => {
    if (load == null || !cores) return 'text-slate-500'
    const ratio = load / cores
    if (ratio < 0.7) return 'text-emerald-500'
    if (ratio < 1.0) return 'text-amber-500'
    return 'text-red-500'
}

const usageColor = (pct) => {
    if (pct == null) return 'text-slate-500'
    if (pct < 70) return 'text-emerald-500'
    if (pct < 85) return 'text-amber-500'
    return 'text-red-500'
}

const formatRam = (mb) => {
    if (!mb) return '—'
    if (mb >= 1024) return (mb / 1024).toFixed(1) + ' GB'
    return mb + ' MB'
}

const user = computed(() => page.props.auth?.user)
</script>

<template>
    <div v-if="sysinfo" class="hidden lg:flex items-center gap-4 text-xs font-medium">
        <!-- Username + Hostname + OS info -->
        <div class="flex items-center gap-3">
            <div class="text-[10px] leading-tight">
                <div class="text-slate-400 uppercase tracking-wider">User</div>
                <div class="font-semibold text-slate-700 dark:text-slate-200">{{ user?.email?.split('@')[0] || 'admin' }}</div>
            </div>
            <div class="text-[10px] leading-tight">
                <div class="text-slate-400 uppercase tracking-wider">Hostname</div>
                <div class="font-semibold text-slate-700 dark:text-slate-200 max-w-[180px] truncate">{{ sysinfo.hostname }}</div>
            </div>
            <div class="text-[10px] leading-tight">
                <div class="text-slate-400 uppercase tracking-wider">OS</div>
                <div class="font-semibold text-slate-700 dark:text-slate-200 max-w-[140px] truncate" :title="sysinfo.os.name">{{ sysinfo.os.name }}</div>
            </div>
        </div>

        <!-- Live Load + RAM + Disk + Uptime — auto-refresh 5sn -->
        <div class="flex items-center gap-3 border-l border-slate-200 pl-3 dark:border-slate-700">
            <!-- Load with trend arrow + 1m/5m/15m -->
            <div class="flex items-center gap-1 text-[10px] leading-tight" :title="`Load 1m / 5m / 15m · ${sysinfo.cpu.cores} core`">
                <BoltIcon class="h-3.5 w-3.5 text-slate-400" />
                <div>
                    <div class="text-slate-400 uppercase tracking-wider">Load</div>
                    <div :class="['font-semibold flex items-center gap-1', loadColor(sysinfo.load_average['1m'], sysinfo.cpu.cores)]">
                        <ArrowUpIcon v-if="loadTrend === 'up'" class="h-2.5 w-2.5" />
                        <ArrowDownIcon v-else-if="loadTrend === 'down'" class="h-2.5 w-2.5" />
                        <MinusIcon v-else class="h-2.5 w-2.5 opacity-30" />
                        <span>{{ sysinfo.load_average['1m'] !== null ? sysinfo.load_average['1m'].toFixed(2) : '—' }}</span>
                        <span class="text-slate-400 font-normal">{{ sysinfo.load_average['5m'] !== null ? sysinfo.load_average['5m'].toFixed(2) : '—' }}</span>
                        <span class="text-slate-400 font-normal">{{ sysinfo.load_average['15m'] !== null ? sysinfo.load_average['15m'].toFixed(2) : '—' }}</span>
                    </div>
                </div>
            </div>

            <!-- RAM -->
            <div class="flex items-center gap-1 text-[10px] leading-tight" :title="`${formatRam(sysinfo.memory.used_mb)} / ${formatRam(sysinfo.memory.total_mb)}`">
                <CpuChipIcon class="h-3.5 w-3.5 text-slate-400" />
                <div>
                    <div class="text-slate-400 uppercase tracking-wider">RAM</div>
                    <div :class="['font-semibold', usageColor(sysinfo.memory.usage_pct)]">
                        {{ sysinfo.memory.usage_pct !== null ? sysinfo.memory.usage_pct + '%' : '—' }}
                    </div>
                </div>
            </div>

            <!-- Disk -->
            <div class="flex items-center gap-1 text-[10px] leading-tight" :title="`${sysinfo.disk.used_gb} / ${sysinfo.disk.total_gb} GB`">
                <CircleStackIcon class="h-3.5 w-3.5 text-slate-400" />
                <div>
                    <div class="text-slate-400 uppercase tracking-wider">Disk</div>
                    <div :class="['font-semibold', usageColor(sysinfo.disk.usage_pct)]">
                        {{ sysinfo.disk.usage_pct !== null ? sysinfo.disk.usage_pct + '%' : '—' }}
                    </div>
                </div>
            </div>

            <!-- Uptime -->
            <div class="flex items-center gap-1 text-[10px] leading-tight" :title="`${sysinfo.uptime.days} gün`">
                <ClockIcon class="h-3.5 w-3.5 text-slate-400" />
                <div>
                    <div class="text-slate-400 uppercase tracking-wider">Uptime</div>
                    <div class="font-semibold text-slate-700 dark:text-slate-200">{{ sysinfo.uptime.human }}</div>
                </div>
            </div>
        </div>
    </div>
</template>
