<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { Head, router, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ServerStackIcon,
    ArrowLeftIcon,
    SignalIcon,
    ExclamationTriangleIcon,
    CheckCircleIcon,
    XCircleIcon,
    ClockIcon,
    ArrowPathIcon,
    XMarkIcon,
    KeyIcon,
    CommandLineIcon,
    ClipboardDocumentIcon,
    BoltIcon,
    ShieldCheckIcon,
    PlayIcon,
    CpuChipIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    node: Object,
    jobs: Array,
    heartbeats: Array,
    other_nodes: { type: Array, default: () => [] },
    extras: { type: Object, default: () => ({}) },
})

const showInstallModal = ref(false)
const installSecret = ref('')
const installCmd = ref('')
const copied = ref(false)

// ── Token Rotation Modal ──────────────────────────────────────────────────────
const showRotateModal = ref(false)
const rotatedSecret = ref('')
const rotatedFingerprint = ref('')
const rotateJobId = ref(null)

// ── Manual Exec Form ──────────────────────────────────────────────────────────
const showExecForm = ref(false)
const execAction = ref('')
const execArgsJson = ref('{}')
const execBusy = ref(false)
const execLastResult = ref(null)

// Whitelist'ten subset — yaygın admin action'ları
const commonActions = [
    'service-status', 'service-restart', 'service-reload',
    'apache-reload', 'fpm-reload', 'postfix-reload',
    'system-info-collect', 'check-updates', 'log-tail',
    'mariadb-slave-status', 'pdns-promote',
]

const runExec = async () => {
    let parsedArgs = {}
    try {
        parsedArgs = execArgsJson.value ? JSON.parse(execArgsJson.value) : {}
    } catch {
        execLastResult.value = { ok: false, error: 'args JSON parse hatası' }
        return
    }
    execBusy.value = true
    execLastResult.value = null
    try {
        const res = await fetch(route('admin.cluster.exec', props.node.id), {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            body: JSON.stringify({ action: execAction.value, args: parsedArgs }),
        })
        const data = await res.json()
        execLastResult.value = res.ok
            ? { ok: true, data }
            : { ok: false, error: data.error || `HTTP ${res.status}` }
        if (res.ok) {
            // Yeni job kuyruğa girdi — sayfayı yenile job geçmişine düşsün
            setTimeout(() => router.reload({ only: ['jobs'] }), 1500)
        }
    } catch (e) {
        execLastResult.value = { ok: false, error: e.message }
    } finally {
        execBusy.value = false
    }
}

// ── Live polling — node detayı için her 10sn job + heartbeat refresh ──────────
let detailTimer = null
onMounted(() => {
    detailTimer = setInterval(() => {
        router.reload({ only: ['jobs', 'heartbeats', 'node', 'extras'], preserveScroll: true })
    }, 10_000)
})
onBeforeUnmount(() => {
    if (detailTimer) clearInterval(detailTimer)
})

const rotateToken = async () => {
    const ok = await ask({
        title: 'Token Rotate',
        message: 'Yeni HMAC secret üretilecek. Slave agent bir sonraki heartbeat\'te (≤60sn) adapt eder; 60sn grace period sonunda eski secret geçersiz olur. Devam?',
        variant: 'warning',
        confirmText: 'Rotate',
        cancelText: 'İptal',
    })
    if (!ok) return

    try {
        const res = await fetch(route('admin.cluster.rotate-token', props.node.id), {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
        })
        const data = await res.json()
        if (!res.ok) {
            alert(data.error || `HTTP ${res.status}`)
            return
        }
        rotatedSecret.value = data.secret
        rotatedFingerprint.value = data.fingerprint
        rotateJobId.value = data.job_id
        showRotateModal.value = true
    } catch (e) {
        alert(e.message)
    }
}

const pingNow = async () => {
    try {
        const res = await fetch(route('admin.cluster.ping', props.node.id), {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json',
            },
        })
        const data = await res.json()
        alert(data.ok
            ? `Ping OK (${data.latency_ms ?? '?'}ms) — kaynak: ${data.source}`
            : `Ping başarısız: ${data.error ?? 'bilinmeyen'}`)
        router.reload({ only: ['node'] })
    } catch (e) {
        alert(e.message)
    }
}

const syncState = async () => {
    const ok = await ask({
        title: 'State Sync',
        message: 'Master DB state\'i bu slave\'e push edilecek (panel-sync job). Devam?',
        confirmText: 'Sync',
        cancelText: 'İptal',
    })
    if (!ok) return
    try {
        const res = await fetch(route('admin.cluster.sync', props.node.id), {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json',
            },
        })
        const data = await res.json()
        alert(data.note || `Job #${data.job_id} kuyruğa alındı.`)
        router.reload({ only: ['jobs'] })
    } catch (e) {
        alert(e.message)
    }
}

// ── Yük göstergeleri ──────────────────────────────────────────────────────────
const loadGauge = (pct, label) => {
    const val = pct ?? 0
    const color = val > 85 ? 'bg-red-500' : val > 65 ? 'bg-amber-500' : 'bg-emerald-500'
    return { val, color, label }
}

const gauges = computed(() => [
    loadGauge(props.node.current_load?.cpu_pct, 'CPU'),
    loadGauge(props.node.current_load?.mem_pct, 'RAM'),
    loadGauge(props.node.current_load?.disk_pct, 'Disk'),
])

// ── Heartbeat chart (son 24 saat, CSS bar chart) ──────────────────────────────
const chartBars = computed(() => {
    // Son 50 heartbeat'i göster
    const items = props.heartbeats.slice(-50)
    const maxCpu = Math.max(...items.map(h => h.cpu_pct), 1)
    return items.map(h => ({
        ...h,
        height: Math.round((h.cpu_pct / maxCpu) * 100),
        color: h.cpu_pct > 85 ? '#ef4444' : h.cpu_pct > 65 ? '#f59e0b' : '#10b981',
    }))
})

// ── Job durumu renk ───────────────────────────────────────────────────────────
const jobBadge = (status) => ({
    pending:   'bg-slate-100 text-slate-600',
    claimed:   'bg-blue-100 text-blue-700',
    running:   'bg-amber-100 text-amber-700',
    completed: 'bg-emerald-100 text-emerald-700',
    failed:    'bg-red-100 text-red-700',
    cancelled: 'bg-slate-200 text-slate-500',
}[status] ?? 'bg-slate-100 text-slate-600')

// ── Actions ───────────────────────────────────────────────────────────────────
const regenerateSecret = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Mevcut secret geçersiz hale gelecek. Slave agent yeniden kurulum gerekebilir. Devam?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return

    const res = await fetch(route('admin.cluster.regenerate-secret', props.node.id), {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
            'Content-Type': 'application/json',
        },
    })
    const data = await res.json()
    installSecret.value = data.secret
    installCmd.value = data.install_cmd
    showInstallModal.value = true
}

const cancelJob = async (job) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `Job #${job.id} (${job.action}) iptal edilecek?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.cluster.jobs.cancel', job.id), {}, { preserveScroll: true })
}

const retryJob = (job) => {
    router.post(route('admin.cluster.jobs.retry', job.id), {}, { preserveScroll: true })
}

const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text).then(() => {
        copied.value = true
        setTimeout(() => (copied.value = false), 2000)
    })
}

const statusBadge = (s) => ({
    active: 'bg-emerald-100 text-emerald-700',
    provisioning: 'bg-amber-100 text-amber-700',
    maintenance: 'bg-blue-100 text-blue-700',
    down: 'bg-red-100 text-red-700',
    decommissioned: 'bg-slate-100 text-slate-500',
}[s] ?? 'bg-slate-100 text-slate-700')
</script>

<template>
    <Head :title="`${node.name} — Cluster Node`" />
    <AdminLayout>
        <template #header>
            <div class="flex items-center gap-3">
                <Link :href="route('admin.cluster.index')" class="text-slate-400 hover:text-slate-600">
                    <ArrowLeftIcon class="h-5 w-5" />
                </Link>
                <span>{{ node.name }}</span>
                <span :class="['rounded px-2 py-0.5 text-xs font-semibold uppercase', statusBadge(node.status)]">
                    {{ node.status }}
                </span>
            </div>
        </template>

        <div class="space-y-6">

            <!-- ── Özet kartları ── -->
            <div class="grid grid-cols-2 gap-4 lg:grid-cols-4">
                <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs text-slate-500">Hostname</p>
                    <p class="mt-1 font-mono text-sm font-semibold">{{ node.hostname }}</p>
                    <p class="font-mono text-xs text-slate-400">{{ node.ip_address }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs text-slate-500">Hesaplar</p>
                    <p class="mt-1 text-2xl font-bold">{{ node.current_account_count }}</p>
                    <p class="text-xs text-slate-500">/ {{ node.max_account_count ?? '∞' }} maks.</p>
                </div>
                <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs text-slate-500">Son Heartbeat</p>
                    <div class="mt-1 flex items-center gap-1.5">
                        <component :is="node.is_healthy ? CheckCircleIcon : ExclamationTriangleIcon"
                            :class="['h-4 w-4', node.is_healthy ? 'text-emerald-500' : 'text-amber-500']" />
                        <span class="text-sm font-medium">{{ node.last_heartbeat_at ?? 'Yok' }}</span>
                    </div>
                    <p class="text-xs text-slate-500">Bekleyen job: {{ node.pending_jobs }}</p>
                </div>
                <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs text-slate-500">Versiyon</p>
                    <p class="mt-1 text-sm font-medium">{{ node.panel_version ?? '—' }}</p>
                    <p class="text-xs text-slate-500 truncate">{{ node.os_version ?? '—' }}</p>
                </div>
            </div>

            <!-- ── Yük göstergeleri ── -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="mb-4 text-sm font-semibold text-slate-700">Anlık Yük</h3>
                <div class="grid grid-cols-3 gap-6">
                    <div v-for="g in gauges" :key="g.label" class="space-y-1.5">
                        <div class="flex justify-between text-xs">
                            <span class="font-medium">{{ g.label }}</span>
                            <span :class="['font-bold', g.val > 85 ? 'text-red-600' : g.val > 65 ? 'text-amber-600' : 'text-emerald-600']">
                                {{ g.val }}%
                            </span>
                        </div>
                        <div class="h-3 overflow-hidden rounded-full bg-slate-100">
                            <div :class="['h-full rounded-full transition-all', g.color]"
                                :style="{ width: g.val + '%' }"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── Heartbeat grafiği (son 24 saat CSS bar chart) ── -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h3 class="mb-4 text-sm font-semibold text-slate-700">CPU Geçmişi (Son 24 Saat)</h3>
                <div v-if="chartBars.length === 0" class="py-6 text-center text-sm text-slate-400">
                    Henüz heartbeat verisi yok.
                </div>
                <div v-else class="flex h-24 items-end gap-px overflow-hidden">
                    <div
                        v-for="(bar, i) in chartBars"
                        :key="i"
                        :title="`${bar.time}: CPU ${bar.cpu_pct}%, RAM ${bar.mem_pct}%`"
                        :style="{ height: bar.height + '%', backgroundColor: bar.color }"
                        class="flex-1 min-w-0 rounded-t transition-all hover:opacity-75"
                    ></div>
                </div>
                <div class="mt-1 flex justify-between text-[10px] text-slate-400">
                    <span>{{ chartBars[0]?.time ?? '' }}</span>
                    <span>{{ chartBars[chartBars.length - 1]?.time ?? '' }}</span>
                </div>
            </div>

            <!-- ── Extras: Services / Network / Cpu Load (Phase N enriched payload) ── -->
            <div v-if="extras.services || extras.cpu_load_avg" class="grid grid-cols-1 gap-4 lg:grid-cols-3">
                <div v-if="extras.cpu_load_avg" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs font-semibold text-slate-600 mb-2 inline-flex items-center gap-1.5">
                        <CpuChipIcon class="h-3.5 w-3.5" /> Load Average
                    </p>
                    <div class="grid grid-cols-3 gap-2 text-center">
                        <div v-for="(label, i) in ['1m','5m','15m']" :key="label">
                            <div class="text-lg font-bold font-mono text-slate-800">
                                {{ Number(extras.cpu_load_avg[i] ?? 0).toFixed(2) }}
                            </div>
                            <div class="text-[10px] text-slate-500">{{ label }}</div>
                        </div>
                    </div>
                </div>
                <div v-if="extras.services" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs font-semibold text-slate-600 mb-2 inline-flex items-center gap-1.5">
                        <BoltIcon class="h-3.5 w-3.5" /> Servisler
                    </p>
                    <div class="space-y-1">
                        <div v-for="svc in extras.services" :key="svc.unit"
                            class="flex items-center justify-between text-xs">
                            <span class="font-mono text-slate-700">{{ svc.unit }}</span>
                            <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold',
                                svc.active ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700']">
                                {{ svc.active ? 'active' : 'inactive' }}
                            </span>
                        </div>
                    </div>
                </div>
                <div v-if="extras.network" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <p class="text-xs font-semibold text-slate-600 mb-2">Network</p>
                    <div class="space-y-1 text-xs">
                        <div class="flex justify-between"><span class="text-slate-500">iface</span><span class="font-mono">{{ extras.network.interface }}</span></div>
                        <div class="flex justify-between"><span class="text-slate-500">rx</span><span class="font-mono">{{ ((extras.network.rx_bytes ?? 0) / 1e9).toFixed(2) }} GB</span></div>
                        <div class="flex justify-between"><span class="text-slate-500">tx</span><span class="font-mono">{{ ((extras.network.tx_bytes ?? 0) / 1e9).toFixed(2) }} GB</span></div>
                        <div v-if="extras.agent_version" class="flex justify-between">
                            <span class="text-slate-500">agent</span><span class="font-mono">{{ extras.agent_version }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── Actions ── -->
            <div class="flex flex-wrap gap-2">
                <button @click="pingNow"
                    class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                    <SignalIcon class="h-4 w-4" /> Ping
                </button>
                <button @click="syncState"
                    class="inline-flex items-center gap-2 rounded-lg border border-indigo-300 bg-indigo-50 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-100">
                    <ArrowPathIcon class="h-4 w-4" /> State Sync
                </button>
                <button @click="showExecForm = !showExecForm"
                    class="inline-flex items-center gap-2 rounded-lg border border-violet-300 bg-violet-50 px-4 py-2 text-sm font-medium text-violet-700 hover:bg-violet-100">
                    <PlayIcon class="h-4 w-4" /> Manuel Komut Çalıştır
                </button>
                <button @click="regenerateSecret"
                    class="inline-flex items-center gap-2 rounded-lg border border-amber-300 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-700 hover:bg-amber-100">
                    <KeyIcon class="h-4 w-4" /> Secret Yenile
                </button>
                <button @click="rotateToken"
                    class="inline-flex items-center gap-2 rounded-lg border border-red-300 bg-red-50 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-100">
                    <ShieldCheckIcon class="h-4 w-4" /> Token Rotate
                </button>
            </div>

            <!-- ── Manual Exec Form ── -->
            <div v-if="showExecForm" class="rounded-xl border border-violet-200 bg-violet-50/50 p-4">
                <h3 class="mb-3 text-sm font-semibold text-slate-700 inline-flex items-center gap-1.5">
                    <CommandLineIcon class="h-4 w-4" /> Slave Node'da Sysapi Action Çalıştır
                </h3>
                <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div>
                        <label class="block text-xs font-medium text-slate-600">Action</label>
                        <input v-model="execAction" list="actions-dl" type="text"
                            placeholder="örn. service-status"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                        <datalist id="actions-dl">
                            <option v-for="a in commonActions" :key="a" :value="a"></option>
                        </datalist>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-slate-600">Args (JSON)</label>
                        <input v-model="execArgsJson" type="text"
                            placeholder='{"service":"httpd"}'
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs" />
                    </div>
                </div>
                <div class="mt-3 flex items-center justify-between gap-2">
                    <p class="text-[11px] text-slate-500">
                        Whitelisted sysapi action; cluster-blocked olanlar (panel-update/shutdown) reddedilir.
                    </p>
                    <button @click="runExec" :disabled="execBusy || !execAction"
                        class="inline-flex items-center gap-1.5 rounded-lg bg-violet-600 px-4 py-2 text-xs font-medium text-white disabled:opacity-50 hover:bg-violet-700">
                        <PlayIcon class="h-3.5 w-3.5" />
                        {{ execBusy ? 'Gönderiliyor…' : 'Çalıştır' }}
                    </button>
                </div>
                <div v-if="execLastResult" class="mt-3 rounded-lg p-3 text-xs font-mono"
                    :class="execLastResult.ok ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-red-50 text-red-700 border border-red-200'">
                    <div v-if="execLastResult.ok">Job #{{ execLastResult.data.job_id }} kuyruğa alındı.</div>
                    <div v-else>Hata: {{ execLastResult.error }}</div>
                </div>
            </div>

            <!-- ── Job geçmişi ── -->
            <div class="rounded-xl border border-slate-200 bg-white shadow-sm">
                <div class="border-b border-slate-100 px-5 py-3">
                    <h3 class="text-sm font-semibold text-slate-700">Job Geçmişi (Son 50)</h3>
                </div>

                <div v-if="jobs.length === 0" class="py-8 text-center text-sm text-slate-400">
                    Henüz job yok.
                </div>

                <table v-else class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100 text-xs text-slate-500">
                            <th class="px-5 py-2 text-left font-medium">ID</th>
                            <th class="px-5 py-2 text-left font-medium">Action</th>
                            <th class="px-5 py-2 text-left font-medium">Durum</th>
                            <th class="px-5 py-2 text-left font-medium">Süre</th>
                            <th class="px-5 py-2 text-left font-medium">Oluşturuldu</th>
                            <th class="px-5 py-2 text-left font-medium">İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="job in jobs" :key="job.id"
                            class="border-b border-slate-50 hover:bg-slate-50">
                            <td class="px-5 py-2.5 font-mono text-xs text-slate-500">#{{ job.id }}</td>
                            <td class="px-5 py-2.5 font-mono text-xs font-medium">{{ job.action }}</td>
                            <td class="px-5 py-2.5">
                                <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase', jobBadge(job.status)]">
                                    {{ job.status }}
                                </span>
                            </td>
                            <td class="px-5 py-2.5 font-mono text-xs text-slate-500">
                                {{ job.duration_ms != null ? job.duration_ms + 'ms' : '—' }}
                            </td>
                            <td class="px-5 py-2.5 text-xs text-slate-500">{{ job.created_at }}</td>
                            <td class="px-5 py-2.5">
                                <div class="flex gap-1.5">
                                    <button v-if="['pending','claimed','running'].includes(job.status)"
                                        @click="cancelJob(job)"
                                        class="rounded border border-red-200 px-2 py-0.5 text-[10px] font-medium text-red-600 hover:bg-red-50">
                                        İptal
                                    </button>
                                    <button v-if="['failed','cancelled'].includes(job.status)"
                                        @click="retryJob(job)"
                                        class="rounded border border-blue-200 px-2 py-0.5 text-[10px] font-medium text-blue-600 hover:bg-blue-50">
                                        Tekrar
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>

        <!-- ── Secret / Kurulum Modal ── -->
        <div v-if="showInstallModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4">
            <div class="w-full max-w-2xl rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-lg font-semibold">
                        <CommandLineIcon class="h-5 w-5 text-amber-500" />
                        Slave Node Kurulum Komutu
                    </h3>
                    <button @click="showInstallModal = false">
                        <XMarkIcon class="h-5 w-5 text-slate-400" />
                    </button>
                </div>

                <div class="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
                    <strong>Dikkat:</strong> Bu secret bir daha gösterilmeyecek. Hemen kopyala ve güvenli sakla.
                </div>

                <div class="mb-3">
                    <p class="mb-1 text-xs font-medium text-slate-600">API Secret</p>
                    <div class="flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
                        <code class="flex-1 break-all font-mono text-xs">{{ installSecret }}</code>
                        <button @click="copyToClipboard(installSecret)"
                            class="shrink-0 text-slate-400 hover:text-slate-600">
                            <ClipboardDocumentIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>

                <div>
                    <p class="mb-1 text-xs font-medium text-slate-600">Slave Node'da Çalıştır</p>
                    <div class="flex items-start gap-2 rounded-lg border border-slate-200 bg-slate-900 px-3 py-3">
                        <pre class="flex-1 overflow-x-auto whitespace-pre text-xs text-emerald-400">{{ installCmd }}</pre>
                        <button @click="copyToClipboard(installCmd)"
                            class="shrink-0 text-slate-500 hover:text-slate-300">
                            <ClipboardDocumentIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>

                <p v-if="copied" class="mt-2 text-center text-xs text-emerald-600">Panoya kopyalandı!</p>

                <div class="mt-4 flex justify-end">
                    <button @click="showInstallModal = false"
                        class="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700">
                        Anladım, Kapattım
                    </button>
                </div>
            </div>
        </div>

        <!-- ── Token Rotate Result Modal ── -->
        <div v-if="showRotateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4">
            <div class="w-full max-w-xl rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-lg font-semibold">
                        <ShieldCheckIcon class="h-5 w-5 text-red-500" />
                        Token Rotate Tamamlandı
                    </h3>
                    <button @click="showRotateModal = false">
                        <XMarkIcon class="h-5 w-5 text-slate-400" />
                    </button>
                </div>

                <div class="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
                    <strong>Dikkat:</strong> Yeni HMAC secret bir daha gösterilmeyecek.
                    Eski secret 60 saniye grace period sonunda iptal olacak —
                    slave-agent bu sürede yeni token'a geçiş yapmalı.
                </div>

                <div class="mb-3">
                    <p class="mb-1 text-xs font-medium text-slate-600">Yeni API Secret</p>
                    <div class="flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
                        <code class="flex-1 break-all font-mono text-xs">{{ rotatedSecret }}</code>
                        <button @click="copyToClipboard(rotatedSecret)"
                            class="shrink-0 text-slate-400 hover:text-slate-600">
                            <ClipboardDocumentIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-3 text-xs">
                    <div>
                        <p class="text-slate-500">Fingerprint</p>
                        <p class="font-mono">{{ rotatedFingerprint }}</p>
                    </div>
                    <div>
                        <p class="text-slate-500">Job ID</p>
                        <p class="font-mono">#{{ rotateJobId }}</p>
                    </div>
                </div>

                <p v-if="copied" class="mt-2 text-center text-xs text-emerald-600">Panoya kopyalandı!</p>

                <div class="mt-4 flex justify-end">
                    <button @click="showRotateModal = false"
                        class="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700">
                        Anladım, Kapattım
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
