<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import InlineEdit from '@/Components/InlineEdit.vue'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()
import {
    ArrowLeftIcon,
    PowerIcon,
    PauseIcon,
    PlayIcon,
    TrashIcon,
    FolderIcon,
    GlobeAltIcon,
    CubeIcon,
    UserIcon,
    CpuChipIcon,
    ExclamationTriangleIcon,
    InformationCircleIcon,
    CircleStackIcon,
    EnvelopeIcon,
    ServerIcon,
    LockClosedIcon,
    ArchiveBoxIcon,
    ClipboardDocumentListIcon,
    BoltIcon,
    PlusIcon,
    UserCircleIcon,
    KeyIcon,
    ArrowsRightLeftIcon,
    BuildingStorefrontIcon,
    XMarkIcon,
    ClipboardIcon,
    SparklesIcon,
    CloudArrowUpIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    account: Object,
    domains: Array,
    databases: Array,
    emails: Array,
    ftps: Array,
    ssls: Array,
    backups: Array,
    audit_log: Array,
    resource_override: Object,
    resource_faults: Array,
    packages_list: { type: Array, default: () => [] },
    owners_list: { type: Array, default: () => [] },
})

// Tab state — URL hash ile senkron
const activeTab = ref(window.location.hash.replace('#', '') || 'overview')
const setTab = (t) => {
    activeTab.value = t
    window.history.replaceState(null, '', '#' + t)
}

const tabs = [
    { id: 'overview',  label: 'Genel',              icon: InformationCircleIcon, count: null },
    { id: 'domains',   label: 'Domainler',          icon: GlobeAltIcon,           count: () => props.domains?.length || 0 },
    { id: 'databases', label: 'Veritabanları',      icon: CircleStackIcon,        count: () => props.databases?.length || 0 },
    { id: 'emails',    label: 'E-posta',            icon: EnvelopeIcon,           count: () => props.emails?.length || 0 },
    { id: 'ftps',      label: 'FTP',                icon: ServerIcon,             count: () => props.ftps?.length || 0 },
    { id: 'ssls',      label: 'SSL',                icon: LockClosedIcon,         count: () => props.ssls?.length || 0 },
    { id: 'backups',   label: 'Yedekler',           icon: ArchiveBoxIcon,         count: () => props.backups?.length || 0 },
    { id: 'resources', label: 'Kaynak Kontrolü',    icon: BoltIcon,               count: null },
    { id: 'audit',     label: 'Denetim Kaydı',      icon: ClipboardDocumentListIcon, count: () => props.audit_log?.length || 0 },
]

// ─── Resource override form ────────────────────────────────────────────────
const overrideForm = useForm({
    cpu_limit_percent:     props.resource_override?.cpu_limit_percent     ?? null,
    memory_limit_mb:       props.resource_override?.memory_limit_mb       ?? null,
    io_read_mbps:          props.resource_override?.io_read_mbps          ?? null,
    io_write_mbps:         props.resource_override?.io_write_mbps         ?? null,
    entry_processes_limit: props.resource_override?.entry_processes_limit ?? null,
    nproc_limit:           props.resource_override?.nproc_limit           ?? null,
    reason:                props.resource_override?.reason                ?? '',
    expires_at:            props.resource_override?.expires_at            ?? '',
})

const submitOverride = () => {
    overrideForm.post(route('admin.accounts.resource-override.set', props.account.id), {
        preserveScroll: true,
    })
}

const clearOverride = async () => {
    const ok = await ask({
        title: 'Kaynak override\'ını kaldır',
        message: 'Override kaldırılacak. Paket varsayılan limitleri tekrar geçerli olacak.',
        variant: 'warning',
        confirmText: 'Kaldır',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.accounts.resource-override.clear', props.account.id), {
        preserveScroll: true,
    })
}

const faultLabels = {
    cpu_limit:   'CPU Limiti',
    memory_oom:  'Bellek OOM',
    io_limit:    'IO Limiti',
    pmem_limit:  'Fiziksel Bellek',
    ep_limit:    'Giriş Süreci',
    nproc_limit: 'İşlem Sayısı',
}

const statusBadge = (color) => {
    const map = {
        green: 'bg-emerald-100 text-emerald-700 ring-emerald-200',
        amber: 'bg-amber-100 text-amber-700 ring-amber-200',
        orange: 'bg-orange-100 text-orange-700 ring-orange-200',
        red: 'bg-red-100 text-red-700 ring-red-200',
    }
    return map[color] || map.green
}

// ─── ACTION: Etkinleştir (pending → active veya suspended → active) ─────────
const activate = async () => {
    const ok = await ask({
        title: 'Hesabı Etkinleştir',
        message: props.account.status === 'pending'
            ? `'${props.account.username}' Linux user'ı oluşturulacak (sysapi user-add). Devam edilsin mi?`
            : `'${props.account.username}' askıdan çıkarılacak. Devam edilsin mi?`,
        variant: 'success',
        confirmText: 'Etkinleştir',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.accounts.activate', props.account.id), {}, { preserveScroll: true })
}

// ─── ACTION: Giriş Yap (impersonate) ─────────────────────────────────────────
const impersonate = async () => {
    if (!props.account.owner_user_id) {
        return
    }
    const ok = await ask({
        title: 'Müşteri olarak panele gir',
        message: `'${props.account.email}' hesabıyla panele giriş yapılacak. Tüm aksiyonlar audit log'a yazılır.`,
        variant: 'info',
        confirmText: 'Geç',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.view-account', props.account.id))
}

// ─── ACTION: Suspend (mevcut) ────────────────────────────────────────────────
const suspendModal = ref(false)
const suspendForm = useForm({ reason: '' })
const submitSuspend = () => {
    suspendForm.post(route('admin.accounts.suspend', props.account.id), {
        onSuccess: () => { suspendModal.value = false; suspendForm.reset() },
        preserveScroll: true,
    })
}

// ─── ACTION: Terminate (çift onay) ───────────────────────────────────────────
const terminateForm = useForm({ delete_data: true, backup_first: true })
const submitTerminate = async () => {
    const ok = await ask({
        title: 'Hesabı sonlandır',
        message: `'${props.account.username}' hesabı KALICI olarak sonlandırılacak. Tüm dosyalar, veritabanları ve e-posta hesapları silinecek. Bu işlem geri alınamaz.`,
        variant: 'danger',
        confirmText: 'Sonlandır',
        cancelText: 'İptal',
    })
    if (!ok) return
    terminateForm.post(route('admin.accounts.terminate', props.account.id))
}

// ─── ACTION: Şifre Sıfırla ───────────────────────────────────────────────────
const passwordModal = ref(false)
const passwordForm = useForm({
    mode: 'random',
    password: '',
    scope: 'all',
    send_email: true,
})

const generatePassword = () => {
    // Tarayıcı CSPRNG — Math.random() ASLA değil
    const alphabet = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    const bytes = new Uint8Array(20)
    window.crypto.getRandomValues(bytes)
    passwordForm.password = Array.from(bytes).map(b => alphabet[b % alphabet.length]).join('')
}

const copyPassword = async () => {
    if (!passwordForm.password) return
    try {
        await navigator.clipboard.writeText(passwordForm.password)
    } catch (e) {
        // sessizce yok say — clipboard API user-gesture gerektirebilir
    }
}

const submitPasswordReset = () => {
    passwordForm.post(route('admin.accounts.reset-password', props.account.id), {
        preserveScroll: true,
        onSuccess: () => { passwordModal.value = false; passwordForm.reset(); passwordForm.mode = 'random'; passwordForm.scope = 'all'; passwordForm.send_email = true },
    })
}

// ─── ACTION: Paket Değiştir ──────────────────────────────────────────────────
const packageModal = ref(false)
const packageForm = useForm({
    package_id: props.account.package_id ?? null,
    override_quota_mb: null,
    notify_customer: false,
})

const selectedPackage = computed(() => props.packages_list?.find(p => p.id === packageForm.package_id))

const submitPackageChange = () => {
    packageForm.patch(route('admin.accounts.change-package', props.account.id), {
        preserveScroll: true,
        onSuccess: () => { packageModal.value = false },
    })
}

// ─── ACTION: Sahip Değiştir ──────────────────────────────────────────────────
const ownerModal = ref(false)
const ownerForm = useForm({
    owner_user_id: props.account.owner_user_id ?? null,
    reason: '',
})

const submitOwnerChange = () => {
    ownerForm.patch(route('admin.accounts.change-owner', props.account.id), {
        preserveScroll: true,
        onSuccess: () => { ownerModal.value = false; ownerForm.reset() },
    })
}

// ─── ACTION: Yedek Al ────────────────────────────────────────────────────────
const triggerBackup = async () => {
    const ok = await ask({
        title: 'Manuel Yedek Başlat',
        message: `'${props.account.username}' için full yedek başlatılacak. İşlem dakikalar sürebilir; tamamlanınca yedekler sekmesinde görünür.`,
        variant: 'info',
        confirmText: 'Başlat',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.accounts.backup', props.account.id), { type: 'full' }, {
        preserveScroll: true,
    })
}

// ─── Helpers ─────────────────────────────────────────────────────────────────
const unsuspend = () => router.post(route('admin.accounts.unsuspend', props.account.id), {}, { preserveScroll: true })

const formatBytes = (b) => {
    if (b === null) return 'sınırsız'
    if (b < 1024) return `${b} B`
    if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`
    if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`
    return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`
}

// Visibility helpers — durum bazlı butonlar
const canActivate = computed(() => ['pending', 'suspended'].includes(props.account.status))
const canSuspend = computed(() => props.account.status === 'active')
const canTerminate = computed(() => props.account.status !== 'terminated')
const canBackup = computed(() => props.account.is_provisioned && props.account.status !== 'terminated')
</script>

<template>
    <Head :title="account.username" />

    <AdminLayout>
        <template #header>
            <Link :href="route('admin.accounts.index')" class="mr-2 inline-flex items-center text-slate-500 hover:text-slate-700">
                <ArrowLeftIcon class="h-5 w-5" />
            </Link>
            <span class="font-mono">{{ account.username }}</span>
            <span :class="['ml-3 inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset', statusBadge(account.status_color)]">
                {{ account.status_label }}
            </span>
        </template>

        <!-- ─── WHM Account Functions muadili Action Bar ─── -->
        <div class="mb-6 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 p-4 shadow-sm">
            <div class="mb-2 flex items-center gap-2 text-xs uppercase tracking-wider text-slate-500 dark:text-slate-400">
                <BoltIcon class="h-3.5 w-3.5" />
                Hesap Aksiyonları
            </div>
            <div class="flex flex-wrap gap-2">
                <!-- Giriş Yap (impersonate) — owner varsa görünür -->
                <button
                    v-if="account.owner_user_id"
                    @click="impersonate"
                    class="inline-flex items-center gap-2 rounded-lg bg-purple-600 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-purple-700"
                    title="Müşteri panelini görüntüle"
                >
                    <UserCircleIcon class="h-4 w-4" /> Giriş Yap
                </button>

                <!-- Etkinleştir — pending veya suspended iken görünür -->
                <button
                    v-if="canActivate"
                    @click="activate"
                    class="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-emerald-700"
                    :title="account.status === 'pending' ? 'Linux user oluştur (provision)' : 'Askıdan çıkar'"
                >
                    <PowerIcon class="h-4 w-4" />
                    {{ account.status === 'pending' ? 'Etkinleştir' : 'Yeniden Aktif Et' }}
                </button>

                <!-- Şifre Sıfırla — provision edilmişse görünür -->
                <button
                    v-if="account.is_provisioned"
                    @click="passwordModal = true"
                    class="inline-flex items-center gap-2 rounded-lg bg-amber-500 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-amber-600"
                    title="Linux/FTP/Webdisk parolasını değiştir"
                >
                    <KeyIcon class="h-4 w-4" /> Şifre Sıfırla
                </button>

                <!-- Paket Değiştir -->
                <button
                    @click="packageModal = true"
                    class="inline-flex items-center gap-2 rounded-lg bg-sky-600 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-sky-700"
                    title="Hosting paketini değiştir"
                >
                    <CubeIcon class="h-4 w-4" /> Paket Değiştir
                </button>

                <!-- Sahip Değiştir -->
                <button
                    @click="ownerModal = true"
                    class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-3.5 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700"
                    title="Bayi/Admin sahip ataması"
                >
                    <ArrowsRightLeftIcon class="h-4 w-4" /> Sahip Değiştir
                </button>

                <!-- Yedek Al Şimdi -->
                <button
                    v-if="canBackup"
                    @click="triggerBackup"
                    class="inline-flex items-center gap-2 rounded-lg bg-cyan-600 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-cyan-700"
                    title="Şimdi manuel full backup başlat"
                >
                    <CloudArrowUpIcon class="h-4 w-4" /> Yedek Al
                </button>

                <!-- Askıya Al -->
                <button
                    v-if="canSuspend"
                    @click="suspendModal = true"
                    class="inline-flex items-center gap-2 rounded-lg bg-orange-500 px-3.5 py-2 text-sm font-medium text-white shadow-sm hover:bg-orange-600"
                    title="Hesabı askıya al"
                >
                    <PauseIcon class="h-4 w-4" /> Askıya Al
                </button>

                <!-- Sonlandır — terminated dışında her zaman -->
                <button
                    v-if="canTerminate"
                    @click="submitTerminate"
                    class="ml-auto inline-flex items-center gap-2 rounded-lg border border-red-300 bg-red-50 px-3.5 py-2 text-sm font-medium text-red-700 hover:bg-red-100 dark:border-red-800 dark:bg-red-950/30 dark:text-red-300"
                    title="Hesabı kalıcı olarak sil"
                >
                    <TrashIcon class="h-4 w-4" /> Sonlandır
                </button>
            </div>
        </div>

        <!-- Tab navigation -->
        <div class="mb-6 border-b border-slate-200 dark:border-slate-700">
            <nav class="-mb-px flex overflow-x-auto" aria-label="Tabs">
                <button v-for="t in tabs" :key="t.id"
                        @click="setTab(t.id)"
                        :class="[
                            'group inline-flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-3 text-sm font-medium transition',
                            activeTab === t.id
                                ? 'border-indigo-500 text-indigo-700 dark:text-indigo-300'
                                : 'border-transparent text-slate-500 hover:border-slate-300 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200'
                        ]">
                    <component :is="t.icon" class="h-4 w-4" />
                    {{ t.label }}
                    <span v-if="t.count" class="ml-1 rounded-full bg-slate-100 dark:bg-slate-700 px-2 py-0.5 text-[10px] font-semibold text-slate-700 dark:text-slate-200">
                        {{ t.count() }}
                    </span>
                </button>
            </nav>
        </div>

        <!-- TAB: Veritabanları -->
        <div v-if="activeTab === 'databases'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">Veritabanları ({{ databases?.length || 0 }})</h3>
                <Link
                    :href="`/admin/databases/create?account_id=${account.id}`"
                    class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700"
                >
                    <PlusIcon class="h-3.5 w-3.5" /> Yeni Veritabanı
                </Link>
            </div>
            <div v-if="!databases || databases.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Henüz veritabanı yok. <Link :href="`/admin/databases/create?account_id=${account.id}`" class="text-indigo-600 hover:underline">İlk veritabanını ekle →</Link>
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">İsim</th><th class="px-4 py-2">Gerçek Ad</th><th class="px-4 py-2">Charset</th><th class="px-4 py-2">Boyut</th><th class="px-4 py-2">Durum</th><th class="px-4 py-2">Oluşturma</th><th class="px-4 py-2 text-right">Aksiyon</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="d in databases" :key="d.id">
                        <td class="px-4 py-2 font-mono text-xs">{{ d.name }}</td>
                        <td class="px-4 py-2 font-mono text-xs text-slate-500">{{ d.real_db_name }}</td>
                        <td class="px-4 py-2 text-xs">{{ d.charset }} / {{ d.collation }}</td>
                        <td class="px-4 py-2 text-xs">{{ d.size_mb }} MB</td>
                        <td class="px-4 py-2"><span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">{{ d.status }}</span></td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ d.created_at }}</td>
                        <td class="px-4 py-2 text-right">
                            <a :href="`/admin/databases/${d.id}/phpmyadmin`" target="_blank"
                               class="text-xs text-indigo-600 hover:underline">phpMyAdmin →</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- TAB: E-posta hesapları -->
        <div v-if="activeTab === 'emails'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">E-posta Hesapları ({{ emails?.length || 0 }})</h3>
                <Link
                    :href="`/admin/email-accounts/create?account_id=${account.id}`"
                    class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700"
                >
                    <PlusIcon class="h-3.5 w-3.5" /> Yeni E-posta
                </Link>
            </div>
            <div v-if="!emails || emails.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Henüz e-posta hesabı yok.
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">Adres</th><th class="px-4 py-2">Kullanım</th><th class="px-4 py-2">Quota</th><th class="px-4 py-2">Durum</th><th class="px-4 py-2">Oluşturma</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="e in emails" :key="e.id">
                        <td class="px-4 py-2 font-mono text-xs">{{ e.address }}</td>
                        <td class="px-4 py-2 text-xs">{{ e.usage_mb }} MB</td>
                        <td class="px-4 py-2 text-xs">{{ e.quota_mb }} MB</td>
                        <td class="px-4 py-2"><span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">{{ e.status }}</span></td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ e.created_at }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- TAB: FTP kullanıcıları -->
        <div v-if="activeTab === 'ftps'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">FTP Kullanıcıları ({{ ftps?.length || 0 }})</h3>
                <Link
                    :href="`/admin/ftp-users/create?account_id=${account.id}`"
                    class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700"
                >
                    <PlusIcon class="h-3.5 w-3.5" /> Yeni FTP Kullanıcısı
                </Link>
            </div>
            <div v-if="!ftps || ftps.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Henüz FTP kullanıcısı yok.
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">Kullanıcı</th><th class="px-4 py-2">Home</th><th class="px-4 py-2">Quota</th><th class="px-4 py-2">Oluşturma</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="f in ftps" :key="f.id">
                        <td class="px-4 py-2 font-mono text-xs">{{ f.username }}</td>
                        <td class="px-4 py-2 font-mono text-xs text-slate-500">{{ f.home_dir }}</td>
                        <td class="px-4 py-2 text-xs">{{ f.quota_mb }} MB</td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ f.created_at }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- TAB: SSL sertifikaları -->
        <div v-if="activeTab === 'ssls'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">SSL Sertifikaları ({{ ssls?.length || 0 }})</h3>
            </div>
            <div v-if="!ssls || ssls.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Henüz SSL sertifikası yok.
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">Domain ID</th><th class="px-4 py-2">İssuer</th><th class="px-4 py-2">Süre</th><th class="px-4 py-2">Yenileme</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="s in ssls" :key="s.id">
                        <td class="px-4 py-2 text-xs">#{{ s.domain_id }}</td>
                        <td class="px-4 py-2 text-xs">{{ s.issuer }}</td>
                        <td class="px-4 py-2 text-xs">{{ s.expires_at }} ({{ s.days_until_expiry }}g)</td>
                        <td class="px-4 py-2"><span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs">{{ s.renewal_status }}</span></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- TAB: Yedekler -->
        <div v-if="activeTab === 'backups'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">Yedekler ({{ backups?.length || 0 }})</h3>
                <button
                    v-if="canBackup"
                    @click="triggerBackup"
                    class="inline-flex items-center gap-1.5 rounded-lg bg-cyan-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-cyan-700"
                >
                    <CloudArrowUpIcon class="h-3.5 w-3.5" /> Şimdi Yedek Al
                </button>
            </div>
            <div v-if="!backups || backups.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Henüz yedek yok. <button v-if="canBackup" @click="triggerBackup" class="text-cyan-600 hover:underline">İlk yedeği başlat →</button>
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">Tip</th><th class="px-4 py-2">Dosya</th><th class="px-4 py-2">Boyut</th><th class="px-4 py-2">Durum</th><th class="px-4 py-2">Tarih</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="b in backups" :key="b.id">
                        <td class="px-4 py-2 text-xs">{{ b.type }}</td>
                        <td class="px-4 py-2 font-mono text-[10px] text-slate-500 truncate max-w-[300px]">{{ b.file_path }}</td>
                        <td class="px-4 py-2 text-xs">{{ b.size_mb }} MB</td>
                        <td class="px-4 py-2"><span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">{{ b.status }}</span></td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ b.created_at }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- TAB: Denetim Kaydı -->
        <div v-if="activeTab === 'audit'" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-base font-semibold">Son Aksiyonlar ({{ audit_log?.length || 0 }})</h3>
            </div>
            <div v-if="!audit_log || audit_log.length === 0" class="rounded-lg border border-dashed p-8 text-center text-sm text-slate-500">
                Bu hesap için audit kaydı yok.
            </div>
            <table v-else class="w-full text-sm">
                <thead class="bg-slate-50 dark:bg-slate-900/50 text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
                    <tr><th class="px-4 py-2">Aksiyon</th><th class="px-4 py-2">Sonuç</th><th class="px-4 py-2">User</th><th class="px-4 py-2">IP</th><th class="px-4 py-2">Tarih</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                    <tr v-for="a in audit_log" :key="a.id">
                        <td class="px-4 py-2 font-mono text-xs">{{ a.action }}</td>
                        <td class="px-4 py-2"><span :class="['rounded-full px-2 py-0.5 text-xs', a.outcome === 'success' ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700']">{{ a.outcome }}</span></td>
                        <td class="px-4 py-2 text-xs">{{ a.user_id || '—' }}</td>
                        <td class="px-4 py-2 font-mono text-xs text-slate-500">{{ a.ip_address || '—' }}</td>
                        <td class="px-4 py-2 text-xs text-slate-500">{{ a.created_at }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div v-show="['overview','domains','resources'].includes(activeTab)" class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- Left: details -->
            <div class="space-y-6 lg:col-span-2">
                <!-- Info card -->
                <div class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
                    <h3 class="mb-4 text-base font-semibold text-slate-900 dark:text-slate-100">Hesap Bilgileri</h3>
                    <dl class="grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
                        <div>
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">E-posta</dt>
                            <dd class="mt-0.5">
                                <InlineEdit
                                    :model-value="account.email"
                                    :patch-url="route('admin.accounts.update', account.id)"
                                    field="email"
                                    type="email"
                                    label="E-posta"
                                />
                            </dd>
                        </div>
                        <div>
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Birincil Domain</dt>
                            <dd class="mt-0.5">
                                <InlineEdit
                                    :model-value="account.primary_domain"
                                    :patch-url="route('admin.accounts.update', account.id)"
                                    field="primary_domain"
                                    placeholder="örn: example.com"
                                    nullable
                                    label="Birincil Domain"
                                />
                            </dd>
                        </div>
                        <div>
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Linux UID</dt>
                            <dd class="mt-0.5 font-mono text-sm text-slate-900 dark:text-slate-100">
                                <span v-if="account.linux_uid">{{ account.linux_uid }}</span>
                                <span v-else class="text-slate-400">henüz provision değil</span>
                            </dd>
                        </div>
                        <div>
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Home Klasörü</dt>
                            <dd class="mt-0.5 font-mono text-sm text-slate-900 dark:text-slate-100">{{ account.home_directory }}</dd>
                        </div>
                        <div v-if="account.owner">
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Sahip</dt>
                            <dd class="mt-0.5 text-sm text-slate-900 dark:text-slate-100">{{ account.owner.name || account.owner.email }}</dd>
                        </div>
                        <div>
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Oluşturma</dt>
                            <dd class="mt-0.5 text-sm text-slate-900 dark:text-slate-100">{{ account.created_at }}</dd>
                        </div>
                        <div v-if="account.provisioned_at">
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Provisioning</dt>
                            <dd class="mt-0.5 text-sm text-slate-900 dark:text-slate-100">{{ account.provisioned_at }}</dd>
                        </div>
                        <div v-if="account.suspended_at">
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Askıya Alma</dt>
                            <dd class="mt-0.5 text-sm text-slate-900 dark:text-slate-100">
                                {{ account.suspended_at }}
                                <span v-if="account.suspended_reason" class="block text-xs text-slate-500">— {{ account.suspended_reason }}</span>
                            </dd>
                        </div>
                        <div class="sm:col-span-2">
                            <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Admin Notları</dt>
                            <dd class="mt-1">
                                <InlineEdit
                                    :model-value="account.admin_notes"
                                    :patch-url="route('admin.accounts.update', account.id)"
                                    field="admin_notes"
                                    type="textarea"
                                    placeholder="Bu hesap hakkında özel notlar... (sadece adminler görür)"
                                    nullable
                                    label="Admin Notları"
                                />
                            </dd>
                        </div>
                    </dl>
                </div>

                <!-- Domains -->
                <div class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
                    <div class="mb-4 flex items-center justify-between">
                        <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">
                            <GlobeAltIcon class="mr-1 inline h-5 w-5 text-slate-400" />
                            Domainler ({{ domains.length }})
                        </h3>
                    </div>

                    <div v-if="domains.length === 0" class="rounded-lg border border-dashed border-slate-200 p-6 text-center text-sm text-slate-500">
                        Bu hesaba henüz domain eklenmemiş.
                    </div>

                    <table v-else class="min-w-full divide-y divide-slate-200 dark:divide-slate-700">
                        <thead>
                            <tr>
                                <th class="px-3 py-2 text-left text-xs font-medium uppercase text-slate-500">Domain</th>
                                <th class="px-3 py-2 text-left text-xs font-medium uppercase text-slate-500">Tip</th>
                                <th class="px-3 py-2 text-left text-xs font-medium uppercase text-slate-500">PHP</th>
                                <th class="px-3 py-2 text-left text-xs font-medium uppercase text-slate-500">SSL</th>
                                <th class="px-3 py-2 text-left text-xs font-medium uppercase text-slate-500">Durum</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-700">
                            <tr v-for="d in domains" :key="d.id">
                                <td class="px-3 py-2 font-mono text-sm text-slate-900 dark:text-slate-100">
                                    {{ d.name }}
                                    <span v-if="d.parent" class="block text-xs text-slate-400">← {{ d.parent }}</span>
                                </td>
                                <td class="px-3 py-2 text-sm text-slate-600 dark:text-slate-300">{{ d.type_label }}</td>
                                <td class="px-3 py-2 text-sm text-slate-600 dark:text-slate-300">{{ d.php_version }}</td>
                                <td class="px-3 py-2 text-sm">
                                    <span v-if="d.ssl_enabled" class="text-emerald-600">✓ Aktif</span>
                                    <span v-else class="text-slate-400">—</span>
                                </td>
                                <td class="px-3 py-2 text-sm">{{ d.status_label }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Right: package + usage -->
            <div class="space-y-6">
                <div v-if="account.package" class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
                    <div class="mb-4 flex items-center justify-between">
                        <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">
                            <CubeIcon class="mr-1 inline h-5 w-5 text-amber-500" />
                            Paket: {{ account.package.name }}
                        </h3>
                        <button @click="packageModal = true" class="text-xs text-indigo-600 hover:underline">Değiştir →</button>
                    </div>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between border-b border-slate-100 dark:border-slate-700 py-1">
                            <span class="text-slate-500">Disk</span>
                            <span class="font-medium">
                                <template v-if="account.package.limits.disk_mb">{{ account.package.limits.disk_mb }} MB</template>
                                <template v-else>sınırsız</template>
                            </span>
                        </div>
                        <div class="flex justify-between border-b border-slate-100 dark:border-slate-700 py-1">
                            <span class="text-slate-500">Veritabanı</span>
                            <span class="font-medium">{{ account.package.limits.db_count ?? 'sınırsız' }}</span>
                        </div>
                        <div class="flex justify-between border-b border-slate-100 dark:border-slate-700 py-1">
                            <span class="text-slate-500">FTP Hesap</span>
                            <span class="font-medium">{{ account.package.limits.ftp_account_count ?? 'sınırsız' }}</span>
                        </div>
                        <div class="flex justify-between border-b border-slate-100 dark:border-slate-700 py-1">
                            <span class="text-slate-500">Ek Domain</span>
                            <span class="font-medium">{{ account.package.limits.addon_domain_count ?? 'sınırsız' }}</span>
                        </div>
                        <div class="flex justify-between py-1">
                            <span class="text-slate-500">Alt Domain</span>
                            <span class="font-medium">{{ account.package.limits.subdomain_count ?? 'sınırsız' }}</span>
                        </div>
                    </div>
                </div>

                <!-- Disk usage -->
                <div class="rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 p-6 shadow-sm">
                    <h3 class="mb-3 text-base font-semibold text-slate-900 dark:text-slate-100">
                        <FolderIcon class="mr-1 inline h-5 w-5 text-cyan-500" />
                        Disk Kullanımı
                    </h3>
                    <div class="space-y-2">
                        <div class="flex justify-between text-sm">
                            <span class="text-slate-500">Kullanılan</span>
                            <span class="font-medium">{{ formatBytes(account.disk_usage_bytes) }}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-slate-500">Kota</span>
                            <span class="font-medium">{{ formatBytes(account.quota_bytes) }}</span>
                        </div>
                        <div v-if="account.disk_usage_percent !== null" class="mt-3">
                            <div class="h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
                                <div
                                    :class="[
                                        'h-full',
                                        account.disk_usage_percent > 90 ? 'bg-red-500' : account.disk_usage_percent > 70 ? 'bg-amber-500' : 'bg-emerald-500',
                                    ]"
                                    :style="{ width: Math.min(account.disk_usage_percent, 100) + '%' }"
                                ></div>
                            </div>
                            <p class="mt-1 text-right text-xs text-slate-500">%{{ account.disk_usage_percent }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Resource Limits Section -->
        <div class="mt-8 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 shadow-sm">
            <div class="flex items-center gap-2 border-b border-slate-100 dark:border-slate-700 p-5">
                <CpuChipIcon class="h-5 w-5 text-indigo-500" />
                <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">Kaynak Limitleri (cgroups v2)</h3>
                <span v-if="resource_override" class="ml-auto inline-flex items-center rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-medium text-amber-800 dark:bg-amber-900/40 dark:text-amber-300">
                    Override Aktif
                </span>
                <span v-else class="ml-auto inline-flex items-center rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-400">
                    Paket Varsayılanı
                </span>
            </div>

            <div class="p-5">
                <!-- Package defaults info -->
                <div v-if="account.package" class="mb-4 rounded-lg border border-slate-100 bg-slate-50 px-4 py-3 text-xs text-slate-600 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400">
                    <span class="font-medium">Paket ({{ account.package.name }}) varsayılanları:</span>
                    CPU {{ account.package.cpu_limit_percent ?? 100 }}% &bull;
                    RAM {{ account.package.memory_limit_mb ?? 1024 }} MB &bull;
                    IO {{ account.package.io_read_mbps ?? 50 }}/{{ account.package.io_write_mbps ?? 30 }} MB/s &bull;
                    EP {{ account.package.entry_processes_limit ?? 20 }} &bull;
                    nProc {{ account.package.nproc_limit ?? 100 }}
                </div>

                <form @submit.prevent="submitOverride" class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            CPU Limit (%)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.cpu_limit_percent ?? 100 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.cpu_limit_percent"
                            type="number" min="10" max="1000"
                            :placeholder="account.package?.cpu_limit_percent ?? 100"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.cpu_limit_percent" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.cpu_limit_percent }}</p>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            Bellek Limiti (MB)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.memory_limit_mb ?? 1024 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.memory_limit_mb"
                            type="number" min="128" max="65536"
                            :placeholder="account.package?.memory_limit_mb ?? 1024"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.memory_limit_mb" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.memory_limit_mb }}</p>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            IO Okuma (MB/s)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.io_read_mbps ?? 50 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.io_read_mbps"
                            type="number" min="10" max="10000"
                            :placeholder="account.package?.io_read_mbps ?? 50"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.io_read_mbps" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.io_read_mbps }}</p>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            IO Yazma (MB/s)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.io_write_mbps ?? 30 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.io_write_mbps"
                            type="number" min="10" max="10000"
                            :placeholder="account.package?.io_write_mbps ?? 30"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.io_write_mbps" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.io_write_mbps }}</p>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            Giriş Süreci (EP)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.entry_processes_limit ?? 20 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.entry_processes_limit"
                            type="number" min="5" max="500"
                            :placeholder="account.package?.entry_processes_limit ?? 20"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.entry_processes_limit" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.entry_processes_limit }}</p>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">
                            Max Süreç (nProc)
                            <span class="ml-1 text-slate-400">paket: {{ account.package?.nproc_limit ?? 100 }}</span>
                        </label>
                        <input
                            v-model.number="overrideForm.nproc_limit"
                            type="number" min="20" max="2000"
                            :placeholder="account.package?.nproc_limit ?? 100"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.nproc_limit" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.nproc_limit }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">Sebep (opsiyonel)</label>
                        <input
                            v-model="overrideForm.reason"
                            type="text" maxlength="500"
                            placeholder="Örn: Yoğun trafik dönemi için geçici artış"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-slate-600 dark:text-slate-400">Override Bitiş Tarihi (opsiyonel)</label>
                        <input
                            v-model="overrideForm.expires_at"
                            type="datetime-local"
                            class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                        />
                        <p v-if="overrideForm.errors.expires_at" class="mt-1 text-xs text-red-600">{{ overrideForm.errors.expires_at }}</p>
                    </div>

                    <div class="flex items-end gap-2 sm:col-span-2 lg:col-span-3">
                        <button
                            type="submit"
                            :disabled="overrideForm.processing"
                            class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                        >
                            <CpuChipIcon class="h-4 w-4" />
                            Override Kaydet &amp; Uygula
                        </button>
                        <button
                            v-if="resource_override"
                            type="button"
                            @click="clearOverride"
                            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"
                        >
                            Override Kaldır
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Resource faults table -->
        <div v-if="resource_faults && resource_faults.length > 0" class="mt-6 rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800 shadow-sm">
            <div class="flex items-center gap-2 border-b border-slate-100 dark:border-slate-700 p-5">
                <ExclamationTriangleIcon class="h-5 w-5 text-amber-500" />
                <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100">Son Limit Aşımları</h3>
            </div>
            <table class="min-w-full divide-y divide-slate-100 dark:divide-slate-700">
                <thead>
                    <tr class="bg-slate-50 dark:bg-slate-800/50">
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Tip</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Limit</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Gerçek</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Zaman</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                    <tr v-for="f in resource_faults" :key="f.id">
                        <td class="px-4 py-3">
                            <span class="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800">
                                {{ faultLabels[f.fault_type] ?? f.fault_type }}
                            </span>
                        </td>
                        <td class="px-4 py-3 font-mono text-sm text-slate-700 dark:text-slate-300">{{ f.limit_value }}</td>
                        <td class="px-4 py-3 font-mono text-sm text-red-600">{{ f.actual_value ?? '—' }}</td>
                        <td class="px-4 py-3 text-sm text-slate-500">{{ f.occurred_at }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- ─── Suspend modal ─── -->
        <div v-if="suspendModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl">
                <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100">Hesabı Askıya Al</h3>
                <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                    <span class="font-mono font-medium">{{ account.username }}</span> askıya alınacak.
                    Sebep audit log'a kaydedilir.
                </p>
                <form @submit.prevent="submitSuspend" class="mt-4">
                    <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">Sebep <span class="text-red-500">*</span></label>
                    <textarea
                        v-model="suspendForm.reason"
                        rows="3"
                        class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                        placeholder="Örn: Ödeme gecikti, AUP ihlali..."
                    ></textarea>
                    <p v-if="suspendForm.errors.reason" class="mt-1 text-xs text-red-600">{{ suspendForm.errors.reason }}</p>

                    <div class="mt-4 flex justify-end gap-2">
                        <button
                            type="button"
                            @click="suspendModal = false"
                            class="rounded-lg border border-slate-300 bg-white dark:bg-slate-900 dark:border-slate-600 dark:text-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
                        >
                            İptal
                        </button>
                        <button
                            type="submit"
                            :disabled="suspendForm.processing"
                            class="rounded-lg bg-orange-600 px-4 py-2 text-sm font-medium text-white hover:bg-orange-700 disabled:opacity-50"
                        >
                            Askıya Al
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ─── Şifre Sıfırla modal ─── -->
        <div v-if="passwordModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl">
                <div class="flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-lg font-semibold text-slate-900 dark:text-slate-100">
                        <KeyIcon class="h-5 w-5 text-amber-500" />
                        Şifre Sıfırla
                    </h3>
                    <button @click="passwordModal = false" class="text-slate-400 hover:text-slate-600"><XMarkIcon class="h-5 w-5" /></button>
                </div>
                <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                    <span class="font-mono font-medium">{{ account.username }}</span> için Linux/FTP/Webdisk parolası değişecek.
                </p>

                <form @submit.prevent="submitPasswordReset" class="mt-4 space-y-4">
                    <!-- Mode toggle -->
                    <div class="grid grid-cols-2 gap-2">
                        <label :class="['flex items-center gap-2 rounded-lg border-2 p-2.5 cursor-pointer text-sm',
                            passwordForm.mode === 'random' ? 'border-indigo-500 bg-indigo-50 dark:bg-indigo-950/30' : 'border-slate-200 dark:border-slate-700']">
                            <input v-model="passwordForm.mode" value="random" type="radio" />
                            <SparklesIcon class="h-4 w-4 text-indigo-500" />
                            <span>Rastgele üret</span>
                        </label>
                        <label :class="['flex items-center gap-2 rounded-lg border-2 p-2.5 cursor-pointer text-sm',
                            passwordForm.mode === 'manual' ? 'border-indigo-500 bg-indigo-50 dark:bg-indigo-950/30' : 'border-slate-200 dark:border-slate-700']">
                            <input v-model="passwordForm.mode" value="manual" type="radio" />
                            <KeyIcon class="h-4 w-4 text-indigo-500" />
                            <span>Manuel</span>
                        </label>
                    </div>

                    <!-- Password field -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">
                            Parola
                            <span v-if="passwordForm.mode === 'manual'" class="text-red-500">*</span>
                        </label>
                        <div class="mt-1 flex gap-2">
                            <input
                                v-model="passwordForm.password"
                                type="text"
                                :readonly="passwordForm.mode === 'random' && !passwordForm.password"
                                placeholder="Min 12 karakter veya 'Üret'e bas"
                                class="flex-1 rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 font-mono text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                            />
                            <button type="button" @click="generatePassword"
                                    class="inline-flex items-center gap-1 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 px-2.5 py-2 text-xs hover:bg-slate-50 dark:hover:bg-slate-700"
                                    title="Güvenli rastgele parola üret">
                                <SparklesIcon class="h-3.5 w-3.5" />
                            </button>
                            <button type="button" @click="copyPassword" :disabled="!passwordForm.password"
                                    class="inline-flex items-center gap-1 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 px-2.5 py-2 text-xs hover:bg-slate-50 dark:hover:bg-slate-700 disabled:opacity-50"
                                    title="Kopyala">
                                <ClipboardIcon class="h-3.5 w-3.5" />
                            </button>
                        </div>
                        <p v-if="passwordForm.errors.password" class="mt-1 text-xs text-red-600">{{ passwordForm.errors.password }}</p>
                    </div>

                    <!-- Scope -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">Kapsam</label>
                        <select v-model="passwordForm.scope"
                                class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm">
                            <option value="all">Hepsi (Linux + FTP + Webdisk)</option>
                            <option value="linux">Sadece Linux user</option>
                            <option value="ftp">Sadece FTP</option>
                            <option value="webdisk">Sadece Webdisk</option>
                        </select>
                    </div>

                    <!-- Send email toggle -->
                    <label class="flex items-start gap-2 rounded-lg border border-slate-200 dark:border-slate-700 p-3 cursor-pointer">
                        <input v-model="passwordForm.send_email" type="checkbox" class="mt-0.5" />
                        <div class="text-sm">
                            <p class="font-medium text-slate-900 dark:text-slate-100">Müşteriye e-posta gönder</p>
                            <p class="text-xs text-slate-500 dark:text-slate-400">
                                {{ account.email || 'E-posta yok' }} adresine "şifre değişti" bildirimi (parola gönderilmez, sadece bilgi).
                            </p>
                        </div>
                    </label>

                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="passwordModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 dark:text-slate-200 px-4 py-2 text-sm font-medium hover:bg-slate-50">
                            İptal
                        </button>
                        <button type="submit" :disabled="passwordForm.processing"
                                class="rounded-lg bg-amber-500 px-4 py-2 text-sm font-medium text-white hover:bg-amber-600 disabled:opacity-50">
                            Parolayı Değiştir
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ─── Paket Değiştir modal ─── -->
        <div v-if="packageModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-lg rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl">
                <div class="flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-lg font-semibold text-slate-900 dark:text-slate-100">
                        <CubeIcon class="h-5 w-5 text-sky-500" />
                        Paket Değiştir
                    </h3>
                    <button @click="packageModal = false" class="text-slate-400 hover:text-slate-600"><XMarkIcon class="h-5 w-5" /></button>
                </div>

                <form @submit.prevent="submitPackageChange" class="mt-4 space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">Yeni Paket</label>
                        <select v-model.number="packageForm.package_id"
                                class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm">
                            <option :value="null" disabled>Paket seç...</option>
                            <option v-for="p in packages_list" :key="p.id" :value="p.id">
                                {{ p.name }} ({{ p.disk_mb ? `${p.disk_mb} MB disk` : 'sınırsız' }})
                            </option>
                        </select>
                        <p v-if="packageForm.errors.package_id" class="mt-1 text-xs text-red-600">{{ packageForm.errors.package_id }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">
                            Disk Quota Override (MB)
                            <span class="ml-1 text-xs text-slate-400">opsiyonel — boş bırakılırsa paket default'u kullanılır</span>
                        </label>
                        <input v-model.number="packageForm.override_quota_mb" type="number" min="0"
                               :placeholder="selectedPackage?.disk_mb ?? 'sınırsız'"
                               class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm" />
                    </div>

                    <label class="flex items-start gap-2 rounded-lg border border-slate-200 dark:border-slate-700 p-3 cursor-pointer">
                        <input v-model="packageForm.notify_customer" type="checkbox" class="mt-0.5" />
                        <div class="text-sm">
                            <p class="font-medium text-slate-900 dark:text-slate-100">Müşteriye e-posta gönder</p>
                            <p class="text-xs text-slate-500 dark:text-slate-400">Paket yükseltme/düşürme bildirimi {{ account.email || '—' }} adresine.</p>
                        </div>
                    </label>

                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="packageModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 dark:text-slate-200 px-4 py-2 text-sm font-medium hover:bg-slate-50">
                            İptal
                        </button>
                        <button type="submit" :disabled="packageForm.processing || !packageForm.package_id"
                                class="rounded-lg bg-sky-600 px-4 py-2 text-sm font-medium text-white hover:bg-sky-700 disabled:opacity-50">
                            Değiştir
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ─── Sahip Değiştir modal ─── -->
        <div v-if="ownerModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-lg rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl">
                <div class="flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-lg font-semibold text-slate-900 dark:text-slate-100">
                        <ArrowsRightLeftIcon class="h-5 w-5 text-slate-500" />
                        Sahip Değiştir
                    </h3>
                    <button @click="ownerModal = false" class="text-slate-400 hover:text-slate-600"><XMarkIcon class="h-5 w-5" /></button>
                </div>

                <form @submit.prevent="submitOwnerChange" class="mt-4 space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">Yeni Sahip</label>
                        <select v-model.number="ownerForm.owner_user_id"
                                class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm">
                            <option :value="null" disabled>Sahip seç...</option>
                            <optgroup label="Adminler">
                                <option v-for="o in owners_list.filter(o => !o.is_reseller)" :key="o.id" :value="o.id">
                                    {{ o.name }} ({{ o.email }})
                                </option>
                            </optgroup>
                            <optgroup label="Bayiler">
                                <option v-for="o in owners_list.filter(o => o.is_reseller)" :key="o.id" :value="o.id">
                                    {{ o.brand_name || o.name }} ({{ o.email }})
                                </option>
                            </optgroup>
                        </select>
                        <p v-if="ownerForm.errors.owner_user_id" class="mt-1 text-xs text-red-600">{{ ownerForm.errors.owner_user_id }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300">Sebep (opsiyonel)</label>
                        <textarea v-model="ownerForm.reason" rows="2"
                                  class="mt-1 w-full rounded-lg border border-slate-300 dark:border-slate-600 dark:bg-slate-900 px-3 py-2 text-sm"
                                  placeholder="Örn: Bayi transferi, müşteri talebi..."></textarea>
                    </div>

                    <div class="rounded-lg border border-amber-200 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/30 p-3 flex items-start gap-2 text-xs text-amber-900 dark:text-amber-200">
                        <InformationCircleIcon class="h-4 w-4 shrink-0 mt-0.5" />
                        <div>
                            Sahip değişikliği audit log'a yazılır. Müşterinin panele giriş yetkisi yeni sahibe geçer.
                        </div>
                    </div>

                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="ownerModal = false"
                                class="rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 dark:text-slate-200 px-4 py-2 text-sm font-medium hover:bg-slate-50">
                            İptal
                        </button>
                        <button type="submit" :disabled="ownerForm.processing || !ownerForm.owner_user_id"
                                class="rounded-lg bg-slate-700 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-50">
                            Sahibi Değiştir
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
