<script setup>
import { ref, computed } from 'vue'
import { Head, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    BoltIcon,
    ArrowsRightLeftIcon,
    ClockIcon,
    InformationCircleIcon,
    CheckCircleIcon,
    PlusIcon,
    XMarkIcon,
    ServerIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    settings: { type: Object, default: null },
    default_mimes: { type: Array, default: () => [] },
})

const s = props.settings ?? {}

const form = useForm({
    mode:                  s.mode                  ?? 'disabled',
    compress_mimes:        s.compress_mimes        ?? [],
    brotli_enabled:        s.brotli_enabled        ?? false,
    cache_enabled:         s.cache_enabled         ?? false,
    cache_default_seconds: s.cache_default_seconds ?? 86400,
    cache_html_seconds:    s.cache_html_seconds    ?? 0,
    cache_css_js_seconds:  s.cache_css_js_seconds  ?? 604800,
    cache_images_seconds:  s.cache_images_seconds  ?? 2592000,
    cache_fonts_seconds:   s.cache_fonts_seconds   ?? 31536000,
})

const mimeInput = ref('')

const addMime = () => {
    const v = mimeInput.value.trim()
    if (v && !form.compress_mimes.includes(v)) {
        form.compress_mimes.push(v)
    }
    mimeInput.value = ''
}

const removeMime = (mime) => {
    form.compress_mimes = form.compress_mimes.filter(m => m !== mime)
}

const loadDefaults = () => {
    props.default_mimes.forEach(m => {
        if (!form.compress_mimes.includes(m)) form.compress_mimes.push(m)
    })
}

const applyPreset = (preset) => {
    if (preset === 'recommended') {
        form.cache_html_seconds    = 0
        form.cache_css_js_seconds  = 31536000
        form.cache_images_seconds  = 31536000
        form.cache_fonts_seconds   = 31536000
        form.cache_default_seconds = 86400
    } else if (preset === 'dev') {
        form.cache_html_seconds    = 0
        form.cache_css_js_seconds  = 0
        form.cache_images_seconds  = 0
        form.cache_fonts_seconds   = 0
        form.cache_default_seconds = 0
    } else if (preset === 'aggressive') {
        form.cache_html_seconds    = 31536000
        form.cache_css_js_seconds  = 31536000
        form.cache_images_seconds  = 31536000
        form.cache_fonts_seconds   = 31536000
        form.cache_default_seconds = 31536000
    }
}

const htaccessPreview = computed(() => {
    const lines = []

    if (form.mode !== 'disabled') {
        lines.push('<IfModule mod_deflate.c>')
        lines.push('    AddOutputFilterByType DEFLATE \\')
        const mimes = form.mode === 'all_content'
            ? ['text/plain', 'text/html', 'text/css', 'application/javascript', 'application/json', 'image/svg+xml']
            : form.compress_mimes
        mimes.forEach(m => lines.push(`        ${m} \\`))
        if (form.brotli_enabled) {
            lines.push('</IfModule>')
            lines.push('<IfModule mod_brotli.c>')
            lines.push('    AddOutputFilterByType BROTLI_COMPRESS \\')
            mimes.forEach(m => lines.push(`        ${m} \\`))
        }
        lines.push('</IfModule>')
    }

    if (form.cache_enabled) {
        lines.push('')
        lines.push('<IfModule mod_expires.c>')
        lines.push('    ExpiresActive On')
        if (form.cache_default_seconds > 0)
            lines.push(`    ExpiresDefault "access plus ${form.cache_default_seconds} seconds"`)
        if (form.cache_html_seconds > 0)
            lines.push(`    ExpiresByType text/html "access plus ${form.cache_html_seconds} seconds"`)
        if (form.cache_css_js_seconds > 0) {
            lines.push(`    ExpiresByType text/css "access plus ${form.cache_css_js_seconds} seconds"`)
            lines.push(`    ExpiresByType application/javascript "access plus ${form.cache_css_js_seconds} seconds"`)
        }
        if (form.cache_images_seconds > 0) {
            lines.push(`    ExpiresByType image/jpeg "access plus ${form.cache_images_seconds} seconds"`)
            lines.push(`    ExpiresByType image/png "access plus ${form.cache_images_seconds} seconds"`)
            lines.push(`    ExpiresByType image/webp "access plus ${form.cache_images_seconds} seconds"`)
        }
        if (form.cache_fonts_seconds > 0) {
            lines.push(`    ExpiresByType font/woff2 "access plus ${form.cache_fonts_seconds} seconds"`)
            lines.push(`    ExpiresByType font/woff "access plus ${form.cache_fonts_seconds} seconds"`)
        }
        lines.push('</IfModule>')
    }

    return lines.length ? lines.join('\n') : '# Optimizasyon devre dışı'
})

const submit = () => form.patch(route('customer.optimize.update'), { preserveScroll: true })
</script>

<template>
    <Head title="Site Optimizasyon" />
    <CustomerLayout>
        <template #header>Site Optimizasyon</template>

        <!-- Info banner -->
        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                <div>
                    <strong>Optimize Website:</strong> Gzip/Brotli sıkıştırma ve tarayıcı önbelleği (Expires) ayarları.
                    'de DB'ye kaydedilir; 5'te .htaccess'e mod_deflate + mod_expires direktifleri yazılır.
                </div>
            </div>
        </div>

        <form @submit.prevent="submit" class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- Left: Settings -->
            <div class="space-y-5 lg:col-span-2">

                <!-- Compression mode -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <div class="mb-4 flex items-center gap-2">
                        <ArrowsRightLeftIcon class="h-5 w-5 text-indigo-600" />
                        <h3 class="font-semibold">Sıkıştırma Modu</h3>
                    </div>
                    <div class="space-y-3">
                        <label class="flex cursor-pointer items-start gap-3 rounded-lg border border-slate-200 p-3 hover:bg-slate-50"
                               :class="{ 'border-indigo-400 bg-indigo-50': form.mode === 'disabled' }">
                            <input v-model="form.mode" type="radio" value="disabled" class="mt-0.5" />
                            <div>
                                <div class="font-medium">Sıkıştırma kapalı</div>
                                <div class="text-xs text-slate-500">Herhangi bir içerik sıkıştırılmaz.</div>
                            </div>
                        </label>
                        <label class="flex cursor-pointer items-start gap-3 rounded-lg border border-slate-200 p-3 hover:bg-slate-50"
                               :class="{ 'border-indigo-400 bg-indigo-50': form.mode === 'all_content' }">
                            <input v-model="form.mode" type="radio" value="all_content" class="mt-0.5" />
                            <div>
                                <div class="font-medium">Tüm içeriği sıkıştır <span class="ml-1 rounded bg-emerald-100 px-1.5 py-0.5 text-xs font-semibold text-emerald-700">Önerilen</span></div>
                                <div class="text-xs text-slate-500">Metin, HTML, CSS, JS, JSON ve SVG otomatik sıkıştırılır.</div>
                            </div>
                        </label>
                        <label class="flex cursor-pointer items-start gap-3 rounded-lg border border-slate-200 p-3 hover:bg-slate-50"
                               :class="{ 'border-indigo-400 bg-indigo-50': form.mode === 'specified_mimes' }">
                            <input v-model="form.mode" type="radio" value="specified_mimes" class="mt-0.5" />
                            <div>
                                <div class="font-medium">Sadece belirli MIME tiplerini sıkıştır</div>
                                <div class="text-xs text-slate-500">Hangi MIME tiplerinin sıkıştırılacağını kendiniz seçin.</div>
                            </div>
                        </label>
                    </div>

                    <!-- MIME list (only when specified_mimes) -->
                    <div v-if="form.mode === 'specified_mimes'" class="mt-4 border-t pt-4">
                        <div class="mb-2 flex items-center justify-between">
                            <span class="text-sm font-medium">Sıkıştırılacak MIME Tipleri</span>
                            <button type="button" @click="loadDefaults"
                                    class="inline-flex items-center gap-1 rounded-lg border border-slate-300 px-3 py-1 text-xs hover:bg-slate-50">
                                <PlusIcon class="h-3 w-3" /> Varsayılanları Yükle
                            </button>
                        </div>
                        <div class="flex flex-wrap gap-2 mb-3">
                            <span v-for="mime in form.compress_mimes" :key="mime"
                                  class="inline-flex items-center gap-1 rounded-full bg-indigo-100 px-2.5 py-0.5 text-xs font-medium text-indigo-800">
                                {{ mime }}
                                <button type="button" @click="removeMime(mime)">
                                    <XMarkIcon class="h-3 w-3" />
                                </button>
                            </span>
                            <span v-if="form.compress_mimes.length === 0" class="text-xs text-slate-400">Henüz MIME tipi eklenmedi.</span>
                        </div>
                        <div class="flex gap-2">
                            <input v-model="mimeInput" type="text" placeholder="text/plain"
                                   @keydown.enter.prevent="addMime"
                                   class="flex-1 rounded-lg border border-slate-300 px-3 py-1.5 font-mono text-sm" />
                            <button type="button" @click="addMime"
                                    class="inline-flex items-center gap-1 rounded-lg bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-700">
                                <PlusIcon class="h-4 w-4" /> Ekle
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Brotli -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2">
                            <BoltIcon class="h-5 w-5 text-indigo-600" />
                            <div>
                                <div class="font-semibold">Brotli Sıkıştırma</div>
                                <div class="text-xs text-slate-500">Gzip'e kıyasla daha iyi sıkıştırma oranı. Modern tarayıcıların tamamı destekler.</div>
                            </div>
                        </div>
                        <label class="relative inline-flex cursor-pointer items-center">
                            <input v-model="form.brotli_enabled" type="checkbox" class="peer sr-only" />
                            <div class="peer h-6 w-11 rounded-full bg-slate-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white after:transition-all after:content-[''] peer-checked:bg-indigo-600 peer-checked:after:translate-x-full"></div>
                        </label>
                    </div>
                </div>

                <!-- Browser caching -->
                <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                    <div class="mb-4 flex items-center justify-between">
                        <div class="flex items-center gap-2">
                            <ClockIcon class="h-5 w-5 text-indigo-600" />
                            <h3 class="font-semibold">Tarayıcı Önbelleği (Expires)</h3>
                        </div>
                        <label class="relative inline-flex cursor-pointer items-center">
                            <input v-model="form.cache_enabled" type="checkbox" class="peer sr-only" />
                            <div class="peer h-6 w-11 rounded-full bg-slate-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white after:transition-all after:content-[''] peer-checked:bg-indigo-600 peer-checked:after:translate-x-full"></div>
                        </label>
                    </div>

                    <div v-if="form.cache_enabled">
                        <p class="mb-3 text-xs text-slate-500">
                            <InformationCircleIcon class="inline h-3.5 w-3.5" />
                            1 saat = 3600 sn &nbsp;|&nbsp; 1 gün = 86400 sn &nbsp;|&nbsp; 1 ay ≈ 2592000 sn &nbsp;|&nbsp; 1 yıl = 31536000 sn
                        </p>

                        <!-- Presets -->
                        <div class="mb-4 flex flex-wrap gap-2">
                            <span class="text-xs font-medium text-slate-500 self-center">Hızlı Önayar:</span>
                            <button type="button" @click="applyPreset('recommended')"
                                    class="rounded-lg border border-emerald-300 bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100">
                                Önerilen
                            </button>
                            <button type="button" @click="applyPreset('dev')"
                                    class="rounded-lg border border-amber-300 bg-amber-50 px-3 py-1 text-xs font-medium text-amber-700 hover:bg-amber-100">
                                Geliştirme
                            </button>
                            <button type="button" @click="applyPreset('aggressive')"
                                    class="rounded-lg border border-indigo-300 bg-indigo-50 px-3 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-100">
                                Saldırgan Cache
                            </button>
                        </div>

                        <div class="space-y-3">
                            <div class="grid grid-cols-2 items-center gap-3">
                                <label class="text-sm font-medium">HTML (saniye)</label>
                                <input v-model.number="form.cache_html_seconds" type="number" min="0" max="31536000"
                                       class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono" />
                            </div>
                            <div class="grid grid-cols-2 items-center gap-3">
                                <label class="text-sm font-medium">CSS / JS (saniye)</label>
                                <input v-model.number="form.cache_css_js_seconds" type="number" min="0"
                                       class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono" />
                            </div>
                            <div class="grid grid-cols-2 items-center gap-3">
                                <label class="text-sm font-medium">Görseller (saniye)</label>
                                <input v-model.number="form.cache_images_seconds" type="number" min="0"
                                       class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono" />
                            </div>
                            <div class="grid grid-cols-2 items-center gap-3">
                                <label class="text-sm font-medium">Yazı Tipleri (saniye)</label>
                                <input v-model.number="form.cache_fonts_seconds" type="number" min="0"
                                       class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono" />
                            </div>
                            <div class="grid grid-cols-2 items-center gap-3 border-t pt-3">
                                <label class="text-sm font-medium">Varsayılan (saniye)</label>
                                <input v-model.number="form.cache_default_seconds" type="number" min="0" max="31536000"
                                       class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono" />
                            </div>
                        </div>
                    </div>
                    <div v-else class="text-sm text-slate-400 italic">
                        Tarayıcı önbelleği devre dışı. Aktifleştirmek için yukarıdaki anahtarı açın.
                    </div>
                </div>

                <div class="flex justify-end">
                    <button type="submit" :disabled="form.processing"
                            class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-60">
                        <CheckCircleIcon class="h-4 w-4" />
                        Ayarları Kaydet
                    </button>
                </div>
            </div>

            <!-- Right: .htaccess preview -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm self-start sticky top-20">
                <div class="mb-3 flex items-center gap-2">
                    <ServerIcon class="h-5 w-5 text-slate-500" />
                    <h3 class="font-semibold text-sm">.htaccess Önizleme</h3>
                </div>
                <pre class="overflow-x-auto rounded-lg bg-slate-900 p-3 text-xs text-emerald-400 leading-relaxed whitespace-pre-wrap">{{ htaccessPreview }}</pre>
                <p class="mt-2 text-xs text-slate-400">5'te otomatik .htaccess'e yazılacaktır.</p>
            </div>
        </form>
    </CustomerLayout>
</template>
