<script setup>
import { computed } from 'vue'
import { Head } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ChartBarIcon,
    CircleStackIcon,
    GlobeAltIcon,
    EnvelopeIcon,
    ArrowsRightLeftIcon,
    FolderIcon,
    CpuChipIcon,
    BoltIcon,
    SignalIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    usage:   { type: Object, default: () => ({}) },
    live:    { type: Object, default: () => ({}) },
    limits:  { type: Object, default: () => ({}) },
    package: { type: Object, default: null },
    history: { type: Array,  default: () => [] },
})

const formatBytes = (b) => {
    if (b === null || b === undefined) return '—'
    if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`
    return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`
}

const usageColor = (percent) => {
    if (percent === null) return 'bg-emerald-500'
    if (percent > 90) return 'bg-red-500'
    if (percent > 70) return 'bg-amber-500'
    return 'bg-emerald-500'
}

// ─── History stats (24 h, 5-min granular) ────────────────────────────────────
const memLimitMb = computed(() => props.live?.memory_limit_mb || 0)

const cpuStats = computed(() => {
    if (!props.history.length) return { current: 0, avg: 0, peak: 0 }
    const vals = props.history.map(h => h.cpu_percent || 0)
    return {
        current: props.live?.cpu_percent ?? vals[vals.length - 1] ?? 0,
        avg: Math.round((vals.reduce((s, v) => s + v, 0) / vals.length) * 10) / 10,
        peak: Math.max(...vals),
    }
})

const memStats = computed(() => {
    if (!props.history.length) return { current: 0, peak: 0 }
    const vals = props.history.map(h => h.memory_mb || 0)
    return {
        current: props.live?.memory_used_mb ?? vals[vals.length - 1] ?? 0,
        peak: Math.max(...vals),
    }
})

const maxCpu = computed(() => Math.max(1, ...props.history.map(h => h.cpu_percent || 0)))
const maxMem = computed(() => Math.max(1, ...props.history.map(h => h.memory_mb || 0), memLimitMb.value))

// Chart point helpers — area under curve
const chartW = 800
const chartH = 120
const padX = 4
const padY = 4

const linePath = (key, max) => {
    if (!props.history.length) return ''
    const n = props.history.length
    const step = n > 1 ? (chartW - padX * 2) / (n - 1) : 0
    return props.history.map((row, i) => {
        const x = padX + i * step
        const y = padY + (chartH - padY * 2) - ((row[key] || 0) / max) * (chartH - padY * 2)
        return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`
    }).join(' ')
}

const areaPath = (key, max) => {
    if (!props.history.length) return ''
    const n = props.history.length
    const step = n > 1 ? (chartW - padX * 2) / (n - 1) : 0
    const lastX = padX + (n - 1) * step
    let path = props.history.map((row, i) => {
        const x = padX + i * step
        const y = padY + (chartH - padY * 2) - ((row[key] || 0) / max) * (chartH - padY * 2)
        return `${i === 0 ? `M ${x.toFixed(1)} ${(chartH - padY).toFixed(1)} L` : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`
    }).join(' ')
    path += ` L ${lastX.toFixed(1)} ${(chartH - padY).toFixed(1)} Z`
    return path
}
</script>

<template>
    <Head title="Kaynak Kullanımı" />
    <CustomerLayout>
        <template #header>Kaynak Kullanımı</template>

        <!-- Package summary -->
        <div v-if="package" class="mb-6 rounded-xl bg-gradient-to-br from-indigo-600 to-purple-700 p-6 text-white shadow-lg">
            <p class="text-sm text-indigo-100">Mevcut Paket</p>
            <h2 class="text-3xl font-bold">{{ package.name }}</h2>
        </div>

        <!-- Resource cards -->
        <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <!-- Disk -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">Disk Kullanımı</h3>
                    <FolderIcon class="h-5 w-5 text-cyan-500" />
                </div>
                <p class="text-2xl font-bold text-slate-900">{{ formatBytes(usage.disk_bytes) }}</p>
                <p class="text-xs text-slate-500">/ {{ formatBytes(usage.disk_quota_bytes) }}</p>
                <div v-if="usage.disk_percent !== null" class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200">
                    <div :class="['h-full', usageColor(usage.disk_percent)]" :style="{ width: Math.min(usage.disk_percent, 100) + '%' }"></div>
                </div>
                <p v-if="usage.disk_percent !== null" class="mt-1 text-right text-xs text-slate-500">%{{ usage.disk_percent }}</p>
            </div>

            <!-- Domain -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">Alan Adları</h3>
                    <GlobeAltIcon class="h-5 w-5 text-purple-500" />
                </div>
                <p class="text-2xl font-bold text-slate-900">
                    {{ usage.domain_count }}
                    <span class="text-base font-normal text-slate-500">/ {{ limits.domain_count ?? 'sınırsız' }}</span>
                </p>
                <p class="mt-3 text-xs text-slate-500">Ana + ek + park</p>
            </div>

            <!-- Database -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">Veritabanları</h3>
                    <CircleStackIcon class="h-5 w-5 text-cyan-500" />
                </div>
                <p class="text-2xl font-bold text-slate-900">
                    {{ usage.database_count }}
                    <span class="text-base font-normal text-slate-500">/ {{ limits.db_count ?? 'sınırsız' }}</span>
                </p>
            </div>

            <!-- FTP -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">FTP Hesapları</h3>
                    <ArrowsRightLeftIcon class="h-5 w-5 text-blue-500" />
                </div>
                <p class="text-2xl font-bold text-slate-900">
                    {{ usage.ftp_count }}
                    <span class="text-base font-normal text-slate-500">/ {{ limits.ftp_account_count ?? 'sınırsız' }}</span>
                </p>
            </div>

            <!-- Email -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">E-posta Hesapları</h3>
                    <EnvelopeIcon class="h-5 w-5 text-rose-500" />
                </div>
                <p class="text-2xl font-bold text-slate-900">
                    {{ usage.email_count }}
                    <span class="text-base font-normal text-slate-500">/ {{ limits.email_account_count ?? '∞' }}</span>
                </p>
            </div>

            <!-- PHP -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-semibold text-slate-900">PHP Sürümleri</h3>
                    <ChartBarIcon class="h-5 w-5 text-amber-500" />
                </div>
                <div v-if="limits.php_versions" class="flex flex-wrap gap-1">
                    <span v-for="v in limits.php_versions" :key="v" class="rounded bg-slate-100 px-2 py-0.5 text-xs font-mono">PHP {{ v }}</span>
                </div>
            </div>
        </div>

        <!-- ───── Live performance (24h history) ─────────────────────────── -->
        <div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <CpuChipIcon class="h-5 w-5 text-indigo-500" />
                    <span class="text-[10px] uppercase tracking-wide text-slate-400">Anlık CPU</span>
                </div>
                <div class="text-2xl font-bold text-slate-900">{{ cpuStats.current.toFixed(1) }}%</div>
                <div class="text-xs text-slate-500">son ölçüm</div>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <ChartBarIcon class="h-5 w-5 text-emerald-500" />
                    <span class="text-[10px] uppercase tracking-wide text-slate-400">24s Ortalama</span>
                </div>
                <div class="text-2xl font-bold text-slate-900">{{ cpuStats.avg.toFixed(1) }}%</div>
                <div class="text-xs text-slate-500">CPU</div>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <BoltIcon class="h-5 w-5 text-amber-500" />
                    <span class="text-[10px] uppercase tracking-wide text-slate-400">24s Tepe</span>
                </div>
                <div class="text-2xl font-bold text-slate-900">{{ cpuStats.peak.toFixed(1) }}%</div>
                <div class="text-xs text-slate-500">en yüksek CPU</div>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <SignalIcon class="h-5 w-5 text-purple-500" />
                    <span class="text-[10px] uppercase tracking-wide text-slate-400">Bellek Tepe</span>
                </div>
                <div class="text-2xl font-bold text-slate-900">{{ memStats.peak.toLocaleString('tr-TR') }} MB</div>
                <div class="text-xs text-slate-500">
                    <span v-if="memLimitMb">/ {{ memLimitMb.toLocaleString('tr-TR') }} MB limit</span>
                    <span v-else>24s pik</span>
                </div>
            </div>
        </div>

        <!-- ───── 24h area chart: CPU % + Memory MB ────────────────────────── -->
        <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 class="mb-4 flex items-center gap-2 text-sm font-semibold text-slate-700">
                <ChartBarIcon class="h-4 w-4 text-indigo-500" />
                Son 24 Saat CPU & Bellek
            </h3>

            <div v-if="history.length" class="space-y-4">
                <!-- CPU area -->
                <div>
                    <div class="mb-1 flex items-center justify-between text-xs">
                        <span class="flex items-center gap-1.5 text-slate-600">
                            <span class="inline-block h-2 w-3 rounded bg-indigo-500"></span>
                            CPU %
                        </span>
                        <span class="font-mono text-slate-500">peak {{ maxCpu.toFixed(1) }}%</span>
                    </div>
                    <svg :viewBox="`0 0 ${chartW} ${chartH}`" class="w-full" preserveAspectRatio="none" style="height: 100px">
                        <path :d="areaPath('cpu_percent', maxCpu)" fill="rgba(99, 102, 241, 0.15)" />
                        <path :d="linePath('cpu_percent', maxCpu)" stroke="#6366f1" stroke-width="1.5" fill="none" />
                    </svg>
                </div>

                <!-- Memory area -->
                <div>
                    <div class="mb-1 flex items-center justify-between text-xs">
                        <span class="flex items-center gap-1.5 text-slate-600">
                            <span class="inline-block h-2 w-3 rounded bg-emerald-500"></span>
                            Bellek MB
                        </span>
                        <span class="font-mono text-slate-500">peak {{ memStats.peak.toLocaleString('tr-TR') }} MB</span>
                    </div>
                    <svg :viewBox="`0 0 ${chartW} ${chartH}`" class="w-full" preserveAspectRatio="none" style="height: 100px">
                        <path :d="areaPath('memory_mb', maxMem)" fill="rgba(16, 185, 129, 0.15)" />
                        <path :d="linePath('memory_mb', maxMem)" stroke="#10b981" stroke-width="1.5" fill="none" />
                    </svg>
                </div>
            </div>
            <div v-else class="flex h-40 items-center justify-center text-sm text-slate-400">
                Henüz yeterli ölçüm yok. Cgroup snapshot job (5 dk aralık) ilk verisini topladıktan sonra
                grafik dolacak.
            </div>

            <div v-if="history.length" class="mt-3 flex justify-between text-[10px] text-slate-400">
                <span>{{ new Date(history[0].ts).toLocaleString('tr-TR', { hour: '2-digit', minute: '2-digit' }) }}</span>
                <span>{{ new Date(history[history.length - 1].ts).toLocaleString('tr-TR', { hour: '2-digit', minute: '2-digit' }) }}</span>
            </div>

            <div v-if="live?.processes" class="mt-4 flex items-center gap-2 rounded-lg border border-slate-100 bg-slate-50 px-3 py-2 text-xs text-slate-600">
                <SignalIcon class="h-3.5 w-3.5 text-slate-400" />
                <span><b>{{ live.processes }}</b> aktif işlem<span v-if="live.process_limit"> / {{ live.process_limit }} limit</span></span>
            </div>
        </div>
    </CustomerLayout>
</template>
