<script setup>
import { ref, computed, watch } from 'vue';
import { Head, useForm, router, usePage } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';

const props = defineProps({
    pdfSettings: Object,
    documentTypes: Object,
    globalSettings: Object,
});

// Flash messages
const page = usePage();
const showSuccess = ref(false);
const showError = ref(false);
const successMessage = ref('');
const errorMessage = ref('');

// Watch for flash messages
watch(() => page.props.flash, (flash) => {
    if (flash?.success) {
        successMessage.value = flash.success;
        showSuccess.value = true;
        setTimeout(() => { showSuccess.value = false; }, 4000);
    }
    if (flash?.error) {
        errorMessage.value = flash.error;
        showError.value = true;
        setTimeout(() => { showError.value = false; }, 4000);
    }
}, { deep: true, immediate: true });

// Active tab
const activeDocType = ref('meal_plan');

// Get current settings for active document type
const currentSettings = computed(() => {
    return props.pdfSettings[activeDocType.value] || {};
});

// Form for current document type
const form = useForm({
    primary_color: '',
    secondary_color: '',
    accent_color: '',
    header_title: '',
    header_subtitle: '',
    show_logo: true,
    show_date: true,
    show_page_numbers: true,
    footer_text: '',
    footer_note: '',
    footer_website: '',
    footer_email: '',
    footer_phone: '',
    show_coach_info: true,
    show_coach_photo: false,
    show_coach_credentials: true,
    show_coach_contact: true,
    paper_size: 'a4',
    orientation: 'portrait',
    margin_top: 20,
    margin_bottom: 20,
    margin_left: 15,
    margin_right: 15,
    font_family: 'DejaVu Sans',
    font_size_base: 11,
    font_size_header: 24,
    custom_css: '',
    watermark_text: '',
    watermark_enabled: false,
    is_active: true,
});

// File input ref (no longer needed but kept for reference)
const logoInput = ref(null);

// Copy settings form
const copyForm = useForm({
    source_type: '',
    target_type: '',
});

// Load settings when tab changes
function loadSettings(docType) {
    activeDocType.value = docType;
    const settings = props.pdfSettings[docType] || {};
    
    form.primary_color = settings.primary_color || '#3B82F6';
    form.secondary_color = settings.secondary_color || '#F97316';
    form.accent_color = settings.accent_color || '#10B981';
    form.header_title = settings.header_title || '';
    form.header_subtitle = settings.header_subtitle || '';
    form.show_logo = settings.show_logo ?? true;
    form.show_date = settings.show_date ?? true;
    form.show_page_numbers = settings.show_page_numbers ?? true;
    form.footer_text = settings.footer_text || '';
    form.footer_note = settings.footer_note || '';
    form.footer_website = settings.footer_website || '';
    form.footer_email = settings.footer_email || '';
    form.footer_phone = settings.footer_phone || '';
    form.show_coach_info = settings.show_coach_info ?? true;
    form.show_coach_photo = settings.show_coach_photo ?? false;
    form.show_coach_credentials = settings.show_coach_credentials ?? true;
    form.show_coach_contact = settings.show_coach_contact ?? true;
    form.paper_size = settings.paper_size || 'a4';
    form.orientation = settings.orientation || 'portrait';
    form.margin_top = settings.margin_top || 20;
    form.margin_bottom = settings.margin_bottom || 20;
    form.margin_left = settings.margin_left || 15;
    form.margin_right = settings.margin_right || 15;
    form.font_family = settings.font_family || 'DejaVu Sans';
    form.font_size_base = settings.font_size_base || 11;
    form.font_size_header = settings.font_size_header || 24;
    form.custom_css = settings.custom_css || '';
    form.watermark_text = settings.watermark_text || '';
    form.watermark_enabled = settings.watermark_enabled ?? false;
    form.is_active = settings.is_active ?? true;
}

// Initialize with workout settings
loadSettings('workout');

// Save settings
function saveSettings() {
    form.post(route('admin.pdf-settings.update', activeDocType.value), {
        preserveScroll: true,
        onSuccess: () => {
            // Show success message
        },
    });
}

// Upload logo
function uploadLogo(event) {
    const file = event.target.files[0];
    if (!file) {
        return;
    }
    
    
    // Validate file
    if (!file.type.startsWith('image/')) {
        alert('Por favor selecciona una imagen válida (PNG, JPG)');
        event.target.value = '';
        return;
    }
    
    if (file.size > 5 * 1024 * 1024) {
        alert('El archivo es demasiado grande. Máximo 5MB.');
        event.target.value = '';
        return;
    }
    
    // Use a fresh form for file upload to ensure proper multipart encoding
    const formData = useForm({
        logo: file,
    });
    
    formData.post(route('admin.pdf-settings.logo', activeDocType.value), {
        preserveScroll: true,
        forceFormData: true,
        onSuccess: () => {
            // Clear the input
            event.target.value = '';
            // Show success message (flash will handle this)
        },
        onError: (errors) => {
            alert('Error al subir el logo: ' + (errors.logo || Object.values(errors).join(', ') || 'Error desconocido'));
            event.target.value = '';
        },
        onFinish: () => {
        },
    });
}

// Remove logo
function removeLogo() {
    if (!confirm('¿Estás seguro de que deseas eliminar el logo?')) return;
    
    router.delete(route('admin.pdf-settings.logo.remove', activeDocType.value), {
        preserveScroll: true,
    });
}

// Reset to defaults
function resetSettings() {
    if (!confirm('¿Estás seguro de que deseas restablecer la configuración a los valores predeterminados?')) return;
    
    router.post(route('admin.pdf-settings.reset', activeDocType.value), {}, {
        preserveScroll: true,
        onSuccess: () => {
            loadSettings(activeDocType.value);
        },
    });
}

// Copy settings
function copySettings() {
    if (!copyForm.source_type || !copyForm.target_type) {
        alert('Selecciona el origen y destino');
        return;
    }
    
    if (copyForm.source_type === copyForm.target_type) {
        alert('El origen y destino no pueden ser iguales');
        return;
    }
    
    if (!confirm(`¿Copiar configuración de ${props.documentTypes[copyForm.source_type]} a ${props.documentTypes[copyForm.target_type]}?`)) return;
    
    copyForm.post(route('admin.pdf-settings.copy'), {
        preserveScroll: true,
    });
}

// Document type icons
const docTypeIcons = {
    invoice: '📄',
    workout: '🏋️',
    meal_plan: '🥗',
    statistics: '📊',
};

// Document type descriptions for better UX
const docTypeDescriptions = {
    invoice: 'Personaliza las facturas que se generan para tus clientes.',
    workout: 'Diseña las rutinas de entrenamiento en formato PDF.',
    meal_plan: 'Configura el diseño de los planes de alimentación.',
    statistics: 'Ajusta los reportes de estadísticas y progreso.',
};

// Font options
const fontOptions = [
    { value: 'DejaVu Sans', label: 'DejaVu Sans (Predeterminado)' },
    { value: 'Helvetica', label: 'Helvetica' },
    { value: 'Times New Roman', label: 'Times New Roman' },
    { value: 'Courier', label: 'Courier' },
];

// Get logo URL
const logoUrl = computed(() => {
    const settings = props.pdfSettings[activeDocType.value];
    if (settings?.logo) {
        return `/storage/${settings.logo}`;
    }
    return null;
});

// Preview PDF (open in new tab)
function previewPdf() {
    // For meal plan, we need a sample client/meal plan - this would typically come from a test route
    const previewUrls = {
        meal_plan: '/coach/clients/1/meal-plans/1/pdf/preview',
        workout: '/coach/clients/1/workouts/1/pdf/preview',
        invoice: '/admin/invoices/1/pdf/preview',
        statistics: '/coach/clients/1/statistics/pdf/preview',
    };
    
    // Just show an alert for now since we don't have real preview data
    alert(`Para previsualizar el PDF de "${props.documentTypes[activeDocType.value]}", ve a un documento real y haz clic en "Descargar PDF".`);
}

// Generate sample PDF preview
const isGeneratingPreview = ref(false);
const previewUrl = ref(null);

async function generateSamplePreview() {
    isGeneratingPreview.value = true;
    try {
        // Call sample endpoint
        const response = await fetch(route('admin.pdf-settings.sample', activeDocType.value));
        const data = await response.json();
        // For now we just show info
        alert(`Configuración guardada para: ${props.documentTypes[activeDocType.value]}\n\nPara ver el PDF generado, ve a cualquier ${activeDocType.value === 'meal_plan' ? 'plan de alimentación' : activeDocType.value === 'workout' ? 'rutina' : 'documento'} y descarga el PDF.`);
    } catch (error) {
    } finally {
        isGeneratingPreview.value = false;
    }
}

// Check if settings have been modified
const hasChanges = computed(() => {
    const current = props.pdfSettings[activeDocType.value] || {};
    return form.primary_color !== (current.primary_color || '#3B82F6') ||
           form.secondary_color !== (current.secondary_color || '#F97316') ||
           form.accent_color !== (current.accent_color || '#10B981') ||
           form.header_title !== (current.header_title || '') ||
           form.footer_text !== (current.footer_text || '');
});
</script>

<template>
    <Head title="Configuración de PDFs" />
    
    <AdminLayout>
        <div class="py-6">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <!-- Success/Error Notifications -->
                <Transition
                    enter-active-class="transition ease-out duration-300"
                    enter-from-class="opacity-0 translate-y-2"
                    enter-to-class="opacity-100 translate-y-0"
                    leave-active-class="transition ease-in duration-200"
                    leave-from-class="opacity-100 translate-y-0"
                    leave-to-class="opacity-0 translate-y-2"
                >
                    <div v-if="showSuccess" class="fixed top-4 right-4 z-50 flex items-center gap-3 px-5 py-4 bg-green-50 dark:bg-green-900/50 border border-green-200 dark:border-green-800 text-green-800 dark:text-green-200 rounded-xl shadow-lg">
                        <span class="text-2xl">✅</span>
                        <div>
                            <p class="font-medium">{{ successMessage }}</p>
                        </div>
                        <button @click="showSuccess = false" class="ml-4 text-green-600 hover:text-green-800">×</button>
                    </div>
                </Transition>
                
                <Transition
                    enter-active-class="transition ease-out duration-300"
                    enter-from-class="opacity-0 translate-y-2"
                    enter-to-class="opacity-100 translate-y-0"
                    leave-active-class="transition ease-in duration-200"
                    leave-from-class="opacity-100 translate-y-0"
                    leave-to-class="opacity-0 translate-y-2"
                >
                    <div v-if="showError" class="fixed top-4 right-4 z-50 flex items-center gap-3 px-5 py-4 bg-red-50 dark:bg-red-900/50 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 rounded-xl shadow-lg">
                        <span class="text-2xl">❌</span>
                        <div>
                            <p class="font-medium">{{ errorMessage }}</p>
                        </div>
                        <button @click="showError = false" class="ml-4 text-red-600 hover:text-red-800">×</button>
                    </div>
                </Transition>

                <!-- Header -->
                <div class="mb-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
                                ⚙️ Configuración de PDFs
                            </h1>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                Personaliza el diseño y contenido de los documentos PDF generados por la plataforma.
                            </p>
                        </div>
                        <a :href="route('admin.settings.index')" class="text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400">
                            ← Volver a Configuración
                        </a>
                    </div>
                </div>
                
                <!-- Document Type Tabs -->
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div class="border-b border-gray-200 dark:border-gray-700">
                        <nav class="flex -mb-px">
                            <button
                                v-for="(label, type) in documentTypes"
                                :key="type"
                                @click="loadSettings(type)"
                                :class="[
                                    'flex-1 px-6 py-4 text-center font-medium text-sm transition-all',
                                    activeDocType === type
                                        ? 'border-b-2 border-blue-500 text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20'
                                        : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50'
                                ]"
                            >
                                <span class="mr-2">{{ docTypeIcons[type] }}</span>
                                {{ label }}
                            </button>
                        </nav>
                    </div>
                    
                    <div class="p-6">
                        <!-- Description for current document type -->
                        <div class="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-100 dark:border-blue-900">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-3">
                                    <span class="text-2xl">{{ docTypeIcons[activeDocType] }}</span>
                                    <div>
                                        <h4 class="font-semibold text-blue-800 dark:text-blue-300">{{ documentTypes[activeDocType] }}</h4>
                                        <p class="text-sm text-blue-600 dark:text-blue-400">{{ docTypeDescriptions[activeDocType] }}</p>
                                    </div>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span v-if="hasChanges" class="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded-full">
                                        Sin guardar
                                    </span>
                                    <span v-else class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">
                                        ✓ Guardado
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Live Preview Card -->
                        <div class="mb-6 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
                            <div class="px-4 py-3 bg-gray-50 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
                                <h4 class="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                                    👁️ Vista Previa del Diseño
                                </h4>
                            </div>
                            <div class="p-4">
                                <!-- Mini preview of header -->
                                <div class="rounded-lg overflow-hidden shadow-sm border border-gray-200 dark:border-gray-600" style="max-width: 400px;">
                                    <!-- Header preview -->
                                    <div class="p-3 text-white text-xs" :style="{ background: `linear-gradient(135deg, ${form.primary_color}, ${form.secondary_color})` }">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <div class="font-bold text-sm">{{ form.header_title || 'Título del Documento' }}</div>
                                                <div class="opacity-75 text-xs">{{ form.header_subtitle || 'Subtítulo' }}</div>
                                            </div>
                                            <div v-if="form.show_logo" class="w-12 h-8 bg-white/20 rounded flex items-center justify-center text-xs">
                                                <span v-if="logoUrl">
                                                    <img :src="logoUrl" class="max-h-6 max-w-10" />
                                                </span>
                                                <span v-else>LOGO</span>
                                            </div>
                                        </div>
                                        <div v-if="form.show_coach_info" class="mt-2 pt-2 border-t border-white/20 text-xs opacity-75">
                                            👤 Nombre del Coach • 📧 email@ejemplo.com
                                        </div>
                                    </div>
                                    <!-- Content preview -->
                                    <div class="p-3 bg-white dark:bg-gray-800">
                                        <div class="h-16 bg-gray-100 dark:bg-gray-700 rounded mb-2 flex items-center justify-center text-gray-400 text-xs">
                                            Contenido del documento
                                        </div>
                                        <div class="flex gap-1">
                                            <div class="flex-1 h-8 rounded" :style="{ backgroundColor: form.primary_color + '20' }"></div>
                                            <div class="flex-1 h-8 rounded" :style="{ backgroundColor: form.secondary_color + '20' }"></div>
                                            <div class="flex-1 h-8 rounded" :style="{ backgroundColor: form.accent_color + '20' }"></div>
                                        </div>
                                    </div>
                                    <!-- Footer preview -->
                                    <div class="p-2 bg-gray-50 dark:bg-gray-700 border-t border-gray-200 dark:border-gray-600 text-xs text-gray-500 dark:text-gray-400 flex justify-between">
                                        <span>{{ form.footer_text || 'Pie de página' }}</span>
                                        <span v-if="form.show_page_numbers">Pág. 1</span>
                                    </div>
                                </div>
                                <p class="mt-3 text-xs text-gray-500">
                                    Esta es una vista previa simplificada. Para ver el PDF completo, genera uno desde la sección correspondiente.
                                </p>
                            </div>
                        </div>
                        
                        <form @submit.prevent="saveSettings" class="space-y-8">
                            <!-- Branding Section -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    🎨 Marca y Colores
                                </h3>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                                    <!-- Logo Upload -->
                                    <div class="lg:col-span-2">
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Logo del Documento (se mostrará a la derecha del encabezado)
                                        </label>
                                        <div class="flex items-center gap-4">
                                            <div class="w-24 h-24 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl flex items-center justify-center overflow-hidden bg-white dark:bg-gray-800">
                                                <img v-if="logoUrl" :src="logoUrl" alt="Logo" class="max-w-full max-h-full object-contain" />
                                                <span v-else class="text-gray-400 text-3xl">📷</span>
                                            </div>
                                            <div class="flex-1">
                                                <input 
                                                    type="file" 
                                                    accept="image/png,image/jpeg"
                                                    @change="uploadLogo"
                                                    class="hidden"
                                                    id="logo-upload"
                                                />
                                                <label 
                                                    for="logo-upload" 
                                                    class="inline-block px-4 py-2 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-700 transition text-sm"
                                                >
                                                    Subir Logo
                                                </label>
                                                <button 
                                                    v-if="logoUrl"
                                                    type="button"
                                                    @click="removeLogo"
                                                    class="ml-2 px-3 py-2 text-red-600 hover:text-red-800 text-sm"
                                                >
                                                    Eliminar
                                                </button>
                                                <p class="mt-1 text-xs text-gray-500">PNG o JPG, máx 5MB</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Color Pickers -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Color Primario
                                        </label>
                                        <div class="flex items-center gap-2">
                                            <input 
                                                type="color" 
                                                v-model="form.primary_color"
                                                class="w-12 h-10 rounded border-0 cursor-pointer"
                                            />
                                            <input 
                                                type="text" 
                                                v-model="form.primary_color"
                                                class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm"
                                                placeholder="#3B82F6"
                                            />
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Color Secundario
                                        </label>
                                        <div class="flex items-center gap-2">
                                            <input 
                                                type="color" 
                                                v-model="form.secondary_color"
                                                class="w-12 h-10 rounded border-0 cursor-pointer"
                                            />
                                            <input 
                                                type="text" 
                                                v-model="form.secondary_color"
                                                class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm"
                                                placeholder="#F97316"
                                            />
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Color de Acento
                                        </label>
                                        <div class="flex items-center gap-2">
                                            <input 
                                                type="color" 
                                                v-model="form.accent_color"
                                                class="w-12 h-10 rounded border-0 cursor-pointer"
                                            />
                                            <input 
                                                type="text" 
                                                v-model="form.accent_color"
                                                class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm"
                                                placeholder="#10B981"
                                            />
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Color Preview -->
                                <div class="mt-4 p-4 rounded-xl" :style="{ background: `linear-gradient(135deg, ${form.primary_color}, ${form.secondary_color})` }">
                                    <div class="text-white text-center">
                                        <span class="text-sm opacity-80">Vista previa del gradiente</span>
                                        <div class="mt-1 text-lg font-bold">{{ documentTypes[activeDocType] }}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Header & Footer Section -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    📝 Encabezado y Pie de Página
                                </h3>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Título del Encabezado
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.header_title"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="RUTINA DE ENTRENAMIENTO"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Subtítulo
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.header_subtitle"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="Plan personalizado"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Texto del Pie de Página
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.footer_text"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="© 2025 Tu Empresa"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Nota del Pie de Página
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.footer_note"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="Tu éxito es nuestra misión"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Sitio Web
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.footer_website"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="www.tuempresa.com"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Email de Contacto
                                        </label>
                                        <input 
                                            type="email" 
                                            v-model="form.footer_email"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="contacto@tuempresa.com"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Teléfono
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.footer_phone"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                            placeholder="+1 234 567 890"
                                        />
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Coach Info Section -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    👤 Información del Coach
                                </h3>
                                
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_coach_info" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Info Coach</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_coach_photo" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Foto Coach</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_coach_credentials" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Credenciales</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_coach_contact" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Contacto Coach</span>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Display Options -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    👁️ Opciones de Visualización
                                </h3>
                                
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_logo" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Logo</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_date" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Mostrar Fecha</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.show_page_numbers" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Números de Página</span>
                                    </label>
                                    
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.is_active" class="rounded border-gray-300 text-blue-600" />
                                        <span class="text-sm">Configuración Activa</span>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Layout Settings -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    📐 Diseño y Tipografía
                                </h3>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Tamaño de Papel
                                        </label>
                                        <select v-model="form.paper_size" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                                            <option value="a4">A4</option>
                                            <option value="letter">Letter</option>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Orientación
                                        </label>
                                        <select v-model="form.orientation" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                                            <option value="portrait">Vertical</option>
                                            <option value="landscape">Horizontal</option>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Fuente
                                        </label>
                                        <select v-model="form.font_family" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                                            <option v-for="font in fontOptions" :key="font.value" :value="font.value">
                                                {{ font.label }}
                                            </option>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Tamaño Texto Base (px)
                                        </label>
                                        <input 
                                            type="number" 
                                            v-model="form.font_size_base"
                                            min="8"
                                            max="16"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                        />
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Tamaño Encabezado (px)
                                        </label>
                                        <input 
                                            type="number" 
                                            v-model="form.font_size_header"
                                            min="16"
                                            max="36"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                                        />
                                    </div>
                                </div>
                                
                                <!-- Margins -->
                                <div class="mt-6">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                                        Márgenes (mm)
                                    </label>
                                    <div class="grid grid-cols-4 gap-4">
                                        <div>
                                            <label class="text-xs text-gray-500 dark:text-gray-400">Superior</label>
                                            <input 
                                                type="number" 
                                                v-model="form.margin_top"
                                                min="5"
                                                max="50"
                                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 mt-1"
                                            />
                                        </div>
                                        <div>
                                            <label class="text-xs text-gray-500 dark:text-gray-400">Inferior</label>
                                            <input 
                                                type="number" 
                                                v-model="form.margin_bottom"
                                                min="5"
                                                max="50"
                                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 mt-1"
                                            />
                                        </div>
                                        <div>
                                            <label class="text-xs text-gray-500 dark:text-gray-400">Izquierdo</label>
                                            <input 
                                                type="number" 
                                                v-model="form.margin_left"
                                                min="5"
                                                max="50"
                                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 mt-1"
                                            />
                                        </div>
                                        <div>
                                            <label class="text-xs text-gray-500 dark:text-gray-400">Derecho</label>
                                            <input 
                                                type="number" 
                                                v-model="form.margin_right"
                                                min="5"
                                                max="50"
                                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 mt-1"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Watermark -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    💧 Marca de Agua
                                </h3>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <label class="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600 cursor-pointer hover:border-blue-500 transition">
                                        <input type="checkbox" v-model="form.watermark_enabled" class="rounded border-gray-300 text-blue-600" />
                                        <span>Habilitar Marca de Agua</span>
                                    </label>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            Texto de la Marca de Agua
                                        </label>
                                        <input 
                                            type="text" 
                                            v-model="form.watermark_text"
                                            :disabled="!form.watermark_enabled"
                                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 disabled:opacity-50"
                                            placeholder="CONFIDENCIAL"
                                        />
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Custom CSS -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                                    💻 CSS Personalizado
                                    <span class="ml-2 text-xs font-normal text-gray-500">(Avanzado)</span>
                                </h3>
                                
                                <textarea 
                                    v-model="form.custom_css"
                                    rows="5"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 font-mono text-sm"
                                    placeholder="/* CSS personalizado para este tipo de documento */"
                                ></textarea>
                                <p class="mt-2 text-xs text-gray-500">
                                    Agrega estilos CSS adicionales para personalizar aún más el diseño del PDF.
                                </p>
                            </div>
                            
                            <!-- Actions -->
                            <div class="flex items-center justify-between pt-6 border-t border-gray-200 dark:border-gray-700">
                                <div class="flex items-center gap-4">
                                    <button 
                                        type="button"
                                        @click="resetSettings"
                                        class="px-4 py-2 text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 text-sm flex items-center gap-2"
                                    >
                                        🔄 Restablecer Valores
                                    </button>
                                    <button 
                                        type="button"
                                        @click="generateSamplePreview"
                                        :disabled="isGeneratingPreview"
                                        class="px-4 py-2 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200 text-sm flex items-center gap-2"
                                    >
                                        <span v-if="isGeneratingPreview">⏳</span>
                                        <span v-else>👁️</span>
                                        Ver Info Configuración
                                    </button>
                                </div>
                                
                                <div class="flex items-center gap-4">
                                    <span v-if="hasChanges" class="text-sm text-yellow-600 dark:text-yellow-400">
                                        ⚠️ Tienes cambios sin guardar
                                    </span>
                                    <button 
                                        type="submit"
                                        :disabled="form.processing"
                                        class="px-6 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition disabled:opacity-50 font-medium flex items-center gap-2"
                                    >
                                        <span v-if="form.processing">⏳</span>
                                        <span v-else>💾</span>
                                        {{ form.processing ? 'Guardando...' : 'Guardar Configuración' }}
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <!-- Copy Settings Section -->
                        <div class="mt-8 pt-8 border-t border-gray-200 dark:border-gray-700">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                📋 Copiar Configuración
                            </h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                                Copia la configuración de un tipo de documento a otro.
                            </p>
                            <div class="flex items-center gap-4">
                                <select v-model="copyForm.source_type" class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                                    <option value="">Origen...</option>
                                    <option v-for="(label, type) in documentTypes" :key="type" :value="type">
                                        {{ label }}
                                    </option>
                                </select>
                                <span class="text-gray-500">→</span>
                                <select v-model="copyForm.target_type" class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                                    <option value="">Destino...</option>
                                    <option v-for="(label, type) in documentTypes" :key="type" :value="type">
                                        {{ label }}
                                    </option>
                                </select>
                                <button 
                                    type="button"
                                    @click="copySettings"
                                    :disabled="copyForm.processing"
                                    class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition disabled:opacity-50"
                                >
                                    Copiar
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
