<script setup>
import { ref, computed, reactive } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    Cog6ToothIcon,
    CloudArrowDownIcon,
    ClockIcon,
    LockClosedIcon,
    BoltIcon,
    ArrowDownTrayIcon,
    ArrowUturnLeftIcon,
    PlayIcon,
    BellIcon,
    InformationCircleIcon,
    CheckCircleIcon,
    ExclamationTriangleIcon,
    ArchiveBoxArrowDownIcon,
    ChartBarIcon,
} from '@heroicons/vue/24/outline'
import { CheckIcon } from '@heroicons/vue/20/solid'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    grouped:              Object,
    current_state:        Object,
    compression_benchmark: Object,
})

// ── i18n ─────────────────────────────────────────────────────────────────────
const categoryLabels = {
    general:     'Genel',
    scope:       'Kapsam (Ne Yedeklensin)',
    retention:   'Saklama Süresi',
    performance: 'Performans & Throttling',
    encryption:  'Şifreleme',
}

const categoryIcons = {
    general:     BellIcon,
    scope:       ArchiveBoxArrowDownIcon,
    retention:   ClockIcon,
    performance: BoltIcon,
    encryption:  LockClosedIcon,
}

const integerUnits = {
    retain_daily_count:     'gün',
    retain_weekly_count:    'hafta',
    retain_monthly_count:   'ay',
    retain_yearly_count:    'yıl',
    compression_level:      '/ 9',
    max_concurrent_backups: 'iş',
    max_io_mbps:            'MB/s',
    nice_level:             '(-20 … 19)',
}

const stateLabels = {
    last_full_backup_at:      'Son tam yedek',
    next_scheduled_backup_at: 'Sonraki zamanlı yedek',
    running_now:              'Şu an çalışıyor',
    total_backups_stored:     'Toplam yedek sayısı',
    total_size_gb:            'Toplam boyut (GB)',
    oldest_backup_at:         'En eski yedek',
    failed_last_24h:          'Son 24s başarısız',
    enabled_accounts:         'Aktif hesap',
    disabled_accounts:        'Devre dışı hesap',
}

const cpuColors = {
    low:     'text-emerald-600 bg-emerald-50',
    medium:  'text-amber-600 bg-amber-50',
    high:    'text-red-600 bg-red-50',
    minimal: 'text-slate-600 bg-slate-50',
}

// Select options for enum-string keys
const selectOptions = {
    compression_type:  ['gzip', 'bzip2', 'xz', 'none'],
    encryption_method: ['gpg', 'openssl_aes'],
}

// ── form state ───────────────────────────────────────────────────────────────
const formValues = reactive({})
for (const rows of Object.values(props.grouped)) {
    for (const row of rows) {
        // json arrays: show as textarea (newline-separated)
        if (row.data_type === 'json') {
            try {
                const arr = JSON.parse(row.value || '[]')
                formValues[row.key] = Array.isArray(arr) ? arr.join('\n') : (row.value ?? '')
            } catch {
                formValues[row.key] = row.value ?? ''
            }
        } else {
            formValues[row.key] = row.value ?? ''
        }
    }
}

const processing = ref(false)
const collapsed   = reactive({})

// ── helpers ──────────────────────────────────────────────────────────────────
const getDefaultDisplay = (row) => {
    if (row.data_type === 'json') {
        try {
            const arr = JSON.parse(row.default_value || '[]')
            return Array.isArray(arr) ? arr.join('\n') : (row.default_value ?? '')
        } catch {
            return row.default_value ?? ''
        }
    }
    return row.default_value ?? ''
}

const isModified = (row) => formValues[row.key] !== getDefaultDisplay(row)

const resetField = (row) => {
    formValues[row.key] = getDefaultDisplay(row)
}

const modifiedCount = computed(() => {
    let n = 0
    for (const rows of Object.values(props.grouped)) {
        for (const row of rows) if (isModified(row)) n++
    }
    return n
})

const categoryModifiedCount = (category) =>
    (props.grouped[category] || []).filter(r => isModified(r)).length

// Get current compression_type value
const currentCompression = computed(() => formValues['compression_type'] || 'gzip')

// ── payload builder — convert json textarea back to JSON string ──────────────
const buildPayload = () => {
    const out = {}
    for (const rows of Object.values(props.grouped)) {
        for (const row of rows) {
            if (row.data_type === 'json') {
                const lines = (formValues[row.key] || '')
                    .split(/[\n,]+/)
                    .map(s => s.trim())
                    .filter(Boolean)
                out[row.key] = JSON.stringify(lines)
            } else {
                out[row.key] = formValues[row.key]
            }
        }
    }
    return out
}

// ── submit ───────────────────────────────────────────────────────────────────
const submit = () => {
    processing.value = true
    router.patch(route('admin.backups.config.update'), { settings: buildPayload() }, {
        preserveScroll: true,
        preserveState:  false,
        onFinish:       () => { processing.value = false },
    })
}

// ── apply to all modal ───────────────────────────────────────────────────────
const showApplyModal   = ref(false)
const applyConfirmText = ref('')
const applyProcessing  = ref(false)

const doApplyAll = () => {
    if (applyConfirmText.value !== 'TUMUNE UYGULA') return
    applyProcessing.value = true
    router.post(route('admin.backups.config.apply-all'),
        { confirm_string: applyConfirmText.value },
        {
            preserveScroll: true,
            onFinish: () => {
                applyProcessing.value = false
                showApplyModal.value  = false
                applyConfirmText.value = ''
            },
        })
}

// ── reset to defaults ────────────────────────────────────────────────────────
const doReset = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Tüm ayarlar varsayılan değerlere sıfırlanacak. Emin misiniz?',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.backups.config.reset'), {}, { preserveScroll: true })
}

// ── run now ──────────────────────────────────────────────────────────────────
const doRunNow = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Tüm hesaplar için manuel backup başlatılsın mı? Bu işlem disk ve CPU yoğun olabilir.',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.backups.config.run-now'), {}, { preserveScroll: true })
}

// ── export url ───────────────────────────────────────────────────────────────
const exportUrl = computed(() => route('admin.backups.config.export'))

// ── date formatter ───────────────────────────────────────────────────────────
const formatDate = (iso) => {
    if (!iso) return '—'
    return new Date(iso).toLocaleString('tr-TR', { dateStyle: 'medium', timeStyle: 'short' })
}
</script>

<template>
    <Head title="Backup Konfigürasyon" />
    <AdminLayout>
        <template #header>Backup Konfigürasyon</template>

        <!-- Tab nav -->
        <div class="mb-5 flex flex-wrap gap-1 border-b border-slate-200">
            <Link :href="route('admin.backups.dashboard')"
                  class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">
                Genel
            </Link>
            <Link :href="route('admin.backups.schedules')"
                  class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">
                Schedules
            </Link>
            <Link :href="route('admin.backups.destinations')"
                  class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">
                Destinations
            </Link>
            <Link :href="route('admin.backups.history')"
                  class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">
                History
            </Link>
            <span class="border-b-2 border-indigo-600 px-4 py-2 text-sm font-semibold text-indigo-700">
                Konfigürasyon
            </span>
        </div>

        <!-- Sticky action bar -->
        <div class="sticky top-0 z-10 mb-5 flex items-center justify-between rounded-xl border border-slate-200 bg-white px-4 py-3 shadow-sm">
            <div class="flex items-center gap-3">
                <Cog6ToothIcon class="h-5 w-5 text-slate-400" />
                <span class="text-sm font-semibold text-slate-700">Sunucu Geneli Backup Politikası</span>
                <span v-if="modifiedCount > 0"
                      class="rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-semibold text-amber-700">
                    {{ modifiedCount }} varsayılandan farklı
                </span>
            </div>
            <button @click="submit" :disabled="processing"
                    class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 disabled:opacity-50">
                <CheckIcon class="h-4 w-4" />
                {{ processing ? 'Kaydediliyor…' : 'Tümünü Kaydet' }}
            </button>
        </div>

        <!-- Flash messages -->
        <div v-if="$page.props.flash?.success"
             class="mb-4 flex items-center gap-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">
            <CheckCircleIcon class="h-5 w-5 flex-shrink-0 text-emerald-500" />
            {{ $page.props.flash.success }}
        </div>
        <div v-if="$page.props.flash?.error"
             class="mb-4 flex items-center gap-3 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-800">
            <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-red-500" />
            {{ $page.props.flash.error }}
        </div>

        <!-- Main grid -->
        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">

            <!-- LEFT: config sections ──────────────────────────────────────────── -->
            <div class="space-y-4 lg:col-span-2">
                <div v-for="(rows, category) in grouped" :key="category"
                     class="rounded-xl border border-slate-200 bg-white shadow-sm">

                    <!-- Section header -->
                    <button type="button"
                            @click="collapsed[category] = !collapsed[category]"
                            class="flex w-full items-center justify-between px-5 py-3 text-left">
                        <div class="flex items-center gap-2">
                            <component :is="categoryIcons[category] ?? Cog6ToothIcon"
                                       class="h-4 w-4 text-indigo-400" />
                            <span class="font-semibold text-slate-800">
                                {{ categoryLabels[category] ?? category }}
                            </span>
                            <span v-if="categoryModifiedCount(category) > 0"
                                  class="rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-bold text-amber-700">
                                {{ categoryModifiedCount(category) }}
                            </span>
                        </div>
                        <svg :class="['h-4 w-4 text-slate-400 transition-transform', collapsed[category] ? '-rotate-90' : '']"
                             fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>

                    <!-- Rows -->
                    <div v-if="!collapsed[category]"
                         class="divide-y divide-slate-100 border-t border-slate-100">
                        <div v-for="row in rows" :key="row.key" class="px-5 py-4">
                            <div class="grid grid-cols-1 gap-3 md:grid-cols-2 md:items-start">

                                <!-- Label + description -->
                                <div>
                                    <div class="flex items-center gap-1.5">
                                        <span class="text-sm font-medium text-slate-800">{{ row.key }}</span>
                                        <span v-if="isModified(row)"
                                              title="Varsayılandan farklı"
                                              class="inline-block h-2 w-2 rounded-full bg-amber-400"></span>
                                    </div>
                                    <p v-if="row.description_tr"
                                       class="mt-0.5 text-xs leading-relaxed text-slate-500">
                                        {{ row.description_tr }}
                                    </p>
                                </div>

                                <!-- Input -->
                                <div class="flex flex-wrap items-center gap-2">

                                    <!-- boolean → toggle -->
                                    <template v-if="row.data_type === 'boolean'">
                                        <button type="button"
                                                @click="formValues[row.key] = formValues[row.key] === '1' ? '0' : '1'"
                                                :class="['relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition',
                                                          formValues[row.key] === '1' ? 'bg-indigo-600' : 'bg-slate-300']">
                                            <span :class="['inline-block h-4 w-4 transform rounded-full bg-white transition',
                                                            formValues[row.key] === '1' ? 'translate-x-6' : 'translate-x-1']"></span>
                                        </button>
                                        <span class="text-xs text-slate-600">
                                            {{ formValues[row.key] === '1' ? 'Açık' : 'Kapalı' }}
                                        </span>
                                    </template>

                                    <!-- integer → number input with unit suffix -->
                                    <template v-else-if="row.data_type === 'integer'">
                                        <div class="flex items-center gap-1.5">
                                            <input v-model="formValues[row.key]" type="number"
                                                   class="w-24 rounded-lg border border-slate-300 px-2.5 py-1.5 font-mono text-sm focus:border-indigo-400 focus:outline-none focus:ring-1 focus:ring-indigo-300" />
                                            <span v-if="integerUnits[row.key]"
                                                  class="text-xs text-slate-500">{{ integerUnits[row.key] }}</span>
                                        </div>
                                    </template>

                                    <!-- json → textarea (newline-separated patterns) -->
                                    <template v-else-if="row.data_type === 'json'">
                                        <div class="w-full">
                                            <textarea v-model="formValues[row.key]"
                                                      rows="3"
                                                      class="w-full rounded-lg border border-slate-300 px-2.5 py-1.5 font-mono text-xs focus:border-indigo-400 focus:outline-none focus:ring-1 focus:ring-indigo-300"
                                                      placeholder="Her satıra bir desen yazın"></textarea>
                                            <p class="mt-0.5 text-[10px] text-slate-400">Her satıra bir desen yazın. Glob formatı desteklenir: *.log, tmp/, node_modules</p>
                                        </div>
                                    </template>

                                    <!-- compression_type → select with benchmark badge -->
                                    <template v-else-if="row.key === 'compression_type'">
                                        <select v-model="formValues[row.key]"
                                                class="rounded-lg border border-slate-300 px-2.5 py-1.5 text-sm focus:border-indigo-400 focus:outline-none focus:ring-1 focus:ring-indigo-300">
                                            <option v-for="opt in selectOptions[row.key]" :key="opt" :value="opt">{{ opt }}</option>
                                        </select>
                                        <span v-if="compression_benchmark[formValues[row.key]]"
                                              class="rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700">
                                            {{ compression_benchmark[formValues[row.key]].ratio }}
                                        </span>
                                    </template>

                                    <!-- encryption_method → select -->
                                    <template v-else-if="row.key === 'encryption_method'">
                                        <select v-model="formValues[row.key]"
                                                class="rounded-lg border border-slate-300 px-2.5 py-1.5 text-sm focus:border-indigo-400 focus:outline-none focus:ring-1 focus:ring-indigo-300">
                                            <option v-for="opt in selectOptions[row.key]" :key="opt" :value="opt">{{ opt }}</option>
                                        </select>
                                    </template>

                                    <!-- string → text input -->
                                    <template v-else>
                                        <input v-model="formValues[row.key]" type="text"
                                               class="w-full max-w-xs rounded-lg border border-slate-300 px-2.5 py-1.5 text-sm focus:border-indigo-400 focus:outline-none focus:ring-1 focus:ring-indigo-300" />
                                    </template>

                                    <!-- Reset to default -->
                                    <button v-if="isModified(row)"
                                            type="button"
                                            @click="resetField(row)"
                                            class="inline-flex items-center gap-1 text-[11px] text-amber-600 hover:text-amber-800 hover:underline">
                                        <ArrowUturnLeftIcon class="h-3 w-3" />
                                        Varsayılan: <code class="ml-0.5 font-mono">{{ getDefaultDisplay(row) }}</code>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Per-category save -->
                    <div v-if="!collapsed[category]"
                         class="flex justify-end border-t border-slate-100 px-5 py-3">
                        <button type="button" @click="submit" :disabled="processing"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-slate-100 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-200 disabled:opacity-50">
                            <CheckIcon class="h-3.5 w-3.5 text-indigo-500" />
                            Kategoriyi Kaydet
                        </button>
                    </div>
                </div>
            </div>

            <!-- RIGHT: state + actions ──────────────────────────────────────────── -->
            <div class="lg:col-span-1">
                <div class="sticky top-20 space-y-4">

                    <!-- Current state card -->
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <h3 class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-800">
                            <CloudArrowDownIcon class="h-4 w-4 text-indigo-400" />
                            Anlık Durum
                            <span class="ml-auto rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500">mock</span>
                        </h3>
                        <dl class="space-y-2">
                            <div v-for="(val, key) in current_state" :key="key"
                                 class="flex items-start justify-between gap-2">
                                <dt class="text-xs text-slate-500">{{ stateLabels[key] ?? key }}</dt>
                                <dd class="text-right font-mono text-xs font-semibold"
                                    :class="{
                                        'text-red-600':     key === 'failed_last_24h' && val > 0,
                                        'text-emerald-600': key === 'enabled_accounts',
                                        'text-amber-600':   key === 'disabled_accounts' && val > 0,
                                        'text-blue-600':    key === 'total_size_gb',
                                        'text-slate-800':   !['failed_last_24h','enabled_accounts','disabled_accounts','total_size_gb'].includes(key),
                                    }">
                                    <template v-if="typeof val === 'boolean'">
                                        <span :class="val ? 'text-emerald-600' : 'text-slate-400'">{{ val ? 'Evet' : 'Hayır' }}</span>
                                    </template>
                                    <template v-else-if="(key === 'last_full_backup_at' || key === 'next_scheduled_backup_at' || key === 'oldest_backup_at')">
                                        {{ formatDate(val) }}
                                    </template>
                                    <template v-else-if="key === 'total_size_gb'">
                                        {{ val }} GB
                                    </template>
                                    <template v-else>{{ val }}</template>
                                </dd>
                            </div>
                        </dl>
                    </div>

                    <!-- Compression benchmark -->
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <h3 class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-800">
                            <ChartBarIcon class="h-4 w-4 text-indigo-400" />
                            Sıkıştırma Karşılaştırması
                        </h3>
                        <table class="w-full text-xs">
                            <thead>
                                <tr class="text-left text-slate-400">
                                    <th class="pb-1.5 font-medium">Algoritma</th>
                                    <th class="pb-1.5 font-medium">Oran</th>
                                    <th class="pb-1.5 font-medium">Hız</th>
                                    <th class="pb-1.5 font-medium">CPU</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-for="(info, algo) in compression_benchmark" :key="algo"
                                    :class="currentCompression === algo ? 'bg-blue-50' : ''">
                                    <td class="py-1.5 pr-2 font-mono font-semibold"
                                        :class="currentCompression === algo ? 'text-blue-700' : 'text-slate-700'">
                                        {{ algo }}
                                        <span v-if="currentCompression === algo"
                                              class="ml-1 rounded bg-blue-100 px-1 py-0.5 text-[9px] font-bold text-blue-600">aktif</span>
                                    </td>
                                    <td class="py-1.5 pr-2 text-slate-700">{{ info.ratio }}</td>
                                    <td class="py-1.5 pr-2 text-slate-700">{{ info.speed_mbps }} MB/s</td>
                                    <td class="py-1.5">
                                        <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold', cpuColors[info.cpu] ?? 'text-slate-600 bg-slate-50']">
                                            {{ info.cpu }}
                                        </span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Actions -->
                    <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                        <h3 class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-800">
                            <BoltIcon class="h-4 w-4 text-amber-400" />
                            İşlemler
                        </h3>
                        <div class="space-y-2">
                            <!-- Run now -->
                            <button type="button" @click="doRunNow"
                                    class="flex w-full items-center gap-2 rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2.5 text-sm font-medium text-indigo-700 hover:bg-indigo-100">
                                <PlayIcon class="h-4 w-4" />
                                Şimdi Çalıştır (Tüm Hesaplar)
                            </button>

                            <!-- Apply to all -->
                            <button type="button" @click="showApplyModal = true"
                                    class="flex w-full items-center gap-2 rounded-lg border border-purple-200 bg-purple-50 px-3 py-2.5 text-sm font-medium text-purple-700 hover:bg-purple-100">
                                <CheckCircleIcon class="h-4 w-4" />
                                Tüm Hesaplara Uygula
                            </button>

                            <!-- Export config -->
                            <a :href="exportUrl"
                               class="flex w-full items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-100">
                                <ArrowDownTrayIcon class="h-4 w-4 text-slate-500" />
                                Konfigürasyonu İndir (.conf)
                            </a>

                            <!-- Reset to defaults -->
                            <button type="button" @click="doReset"
                                    class="flex w-full items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5 text-sm font-medium text-amber-700 hover:bg-amber-100">
                                <ArrowUturnLeftIcon class="h-4 w-4" />
                                Varsayılana Sıfırla
                            </button>
                        </div>
                    </div>

                    <!-- Phase note -->
                    <div class="rounded-xl border border-blue-200 bg-blue-50 p-4">
                        <div class="flex gap-2">
                            <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-blue-500" />
                            <div class="text-xs leading-relaxed text-blue-800">
                                <p class="font-semibold">5'ta:</p>
                                <ul class="mt-1 list-disc space-y-0.5 pl-4">
                                    <li>Değişiklikler <code class="font-mono">/usr/local/onox/etc/backup.conf</code> dosyasına yazılır.</li>
                                    <li>Yeni oluşturulan hesaplar bu değerleri otomatik miras alır.</li>
                                    <li>"Tüm Hesaplara Uygula" gerçek per-account override sıfırlaması yapar.</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <!-- Apply-to-all confirm modal -->
        <Teleport to="body">
            <div v-if="showApplyModal"
                 class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
                <div class="w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-xl">
                    <div class="mb-4 flex items-center gap-3">
                        <ExclamationTriangleIcon class="h-6 w-6 text-amber-500" />
                        <h3 class="text-base font-semibold text-slate-800">Tüm Hesaplara Uygula</h3>
                    </div>
                    <p class="mb-4 text-sm text-slate-600">
                        Bu işlem, mevcut konfigürasyonu <strong>tüm hosting hesaplarına</strong> uygulayacak
                        ve per-account override ayarlarını sıfırlayacaktır. Bu işlem geri alınamaz.
                    </p>
                    <p class="mb-2 text-xs font-medium text-slate-700">
                        Onaylamak için aşağıya <code class="rounded bg-slate-100 px-1 font-mono text-red-600">TUMUNE UYGULA</code> yazın:
                    </p>
                    <input v-model="applyConfirmText"
                           type="text"
                           placeholder="TUMUNE UYGULA"
                           class="mb-4 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono focus:border-red-400 focus:outline-none focus:ring-1 focus:ring-red-300" />
                    <div class="flex justify-end gap-3">
                        <button type="button"
                                @click="showApplyModal = false; applyConfirmText = ''"
                                class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                            İptal
                        </button>
                        <button type="button"
                                @click="doApplyAll"
                                :disabled="applyConfirmText !== 'TUMUNE UYGULA' || applyProcessing"
                                class="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-40">
                            {{ applyProcessing ? 'Uygulanıyor…' : 'Uygula' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>

    </AdminLayout>
</template>
