<!DOCTYPE html>
<html lang="tr">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Sayfa Editörü - <?php echo e(auth()->user()?->agency?->name ?? 'Acente'); ?></title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <!-- Libraries -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/classic.min.css">

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary: #3B82F6;
            --primary-dark: #2563EB;
            --success: #10B981;
            --danger: #EF4444;
            --warning: #F59E0B;
            --gray-50: #F9FAFB;
            --gray-100: #F3F4F6;
            --gray-200: #E5E7EB;
            --gray-300: #D1D5DB;
            --gray-400: #9CA3AF;
            --gray-500: #6B7280;
            --gray-600: #4B5563;
            --gray-700: #374151;
            --gray-800: #1F2937;
            --gray-900: #111827;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--gray-50);
            color: var(--gray-700);
            line-height: 1.5;
        }

        /* Editor Header */
        .editor-header {
            background: white;
            border-bottom: 1px solid var(--gray-200);
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .editor-header-left {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .editor-logo {
            width: 36px;
            height: 36px;
            border-radius: 8px;
            object-fit: cover;
        }

        .editor-title h1 {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.25rem;
        }

        .editor-meta {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 0.875rem;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-badge.published {
            background: #D1FAE5;
            color: #065F46;
        }

        .status-badge.draft {
            background: #FEF3C7;
            color: #92400E;
        }

        .editor-actions {
            display: flex;
            gap: 0.75rem;
        }

        /* Buttons */
        .btn {
            padding: 0.625rem 1.25rem;
            border: none;
            border-radius: 8px;
            font-weight: 500;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-secondary {
            background: var(--gray-600);
            color: white;
        }

        .btn-light {
            background: white;
            color: var(--gray-700);
            border: 1px solid var(--gray-300);
        }

        .btn-light:hover {
            background: var(--gray-50);
        }

        /* History Button Special Style */
        .btn-history {
            position: relative;
            background: linear-gradient(135deg, #ffffff 0%, #f3f4f6 100%);
            color: var(--gray-700);
            border: 1px solid var(--gray-300);
            overflow: hidden;
        }

        .btn-history:hover {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-color: var(--primary);
            color: var(--primary);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.15);
        }

        .btn-history i {
            transition: transform 0.3s ease;
        }

        .btn-history:hover i {
            transform: rotate(-15deg);
        }

        /* Main Container */
        .editor-container {
            display: grid;
            grid-template-columns: 360px 1fr;
            height: calc(100vh - 73px);
            overflow: hidden;
        }

        /* Sidebar */
        .editor-sidebar {
            background: white;
            border-right: 1px solid var(--gray-200);
            overflow-y: auto;
            padding: 1.5rem;
        }

        .sidebar-section {
            margin-bottom: 2rem;
            padding-bottom: 2rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .sidebar-section:last-child {
            border-bottom: none;
        }

        .sidebar-title {
            font-size: 1rem;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 1rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-label {
            display: block;
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
        }

        .form-control {
            width: 100%;
            padding: 0.625rem 0.875rem;
            border: 1px solid var(--gray-300);
            border-radius: 6px;
            font-size: 0.875rem;
            transition: border-color 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        /* Main Content */
        .editor-main {
            background: var(--gray-50);
            overflow-y: auto;
            padding: 2rem;
        }

        .editor-panel {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .panel-header h2 {
            font-size: 1.125rem;
            font-weight: 600;
            color: var(--gray-900);
        }

        /* Sections */
        #sectionsList {
            min-height: 300px;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
        }

        .empty-state-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }

        .empty-state h3 {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: var(--gray-500);
            margin-bottom: 1.5rem;
        }

        /* Alerts */
        #alertContainer {
            position: fixed;
            top: 90px;
            right: 1.5rem;
            z-index: 9999;
            max-width: 400px;
        }

        .alert {
            padding: 1rem 1.25rem;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            font-size: 0.875rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.3s ease-out;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .alert-success {
            background: #D1FAE5;
            color: #065F46;
            border-left: 4px solid #10B981;
        }

        .alert-error {
            background: #FEE2E2;
            color: #991B1B;
            border-left: 4px solid #EF4444;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* Close Button */
        .btn-close {
            background: none;
            border: none;
            color: inherit;
            opacity: 0.5;
            cursor: pointer;
            font-size: 1.25rem;
            padding: 0;
            margin-left: auto;
        }

        .btn-close:hover {
            opacity: 1;
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .editor-container {
                grid-template-columns: 1fr;
            }

            .editor-sidebar {
                display: none;
            }
        }
    </style>

    <?php echo $__env->yieldPushContent('styles'); ?>
</head>

<body>
    <!-- Header -->
    <div class="editor-header">
        <div class="editor-header-left">
            <?php if(auth()->user()?->agency && auth()->user()->agency->logo): ?>
                <img src="<?php echo e(asset('storage/' . auth()->user()->agency->logo)); ?>" alt="Logo" class="editor-logo">
            <?php endif; ?>
            <div class="editor-title">
                <h1>Sayfa Editörü</h1>
                <div class="editor-meta">
                    <span class="status-badge <?php echo e($page->is_published ? 'published' : 'draft'); ?>">
                        <i class="fas fa-circle" style="font-size: 0.5rem;"></i>
                        <?php echo e($page->is_published ? 'Yayında' : 'Taslak'); ?>

                    </span>
                    <?php if($page->updated_at): ?>
                        <span style="color: var(--gray-500);">
                            <i class="fas fa-clock"></i>
                            <?php echo e($page->updated_at->diffForHumans()); ?>

                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="editor-actions">
            <a href="<?php echo e(route('agency.dashboard')); ?>" class="btn btn-light">
                <i class="fas fa-chart-pie"></i> Dashboard'a Dön
            </a>
            <button type="button" class="btn btn-light" onclick="window.close()">
                <i class="fas fa-times"></i> Kapat
            </button>
            <button type="button" class="btn btn-light" onclick="previewPage()">
                <i class="fas fa-eye"></i> Önizle
            </button>
            <button type="button" class="btn btn-primary" onclick="savePage()">
                <i class="fas fa-save"></i> Kaydet
            </button>
            <button type="button" class="btn <?php echo e($page->is_published ? 'btn-success' : 'btn-primary'); ?>"
                onclick="publishPage()">
                <i class="fas fa-rocket"></i> <?php echo e($page->is_published ? 'Değişiklikleri Yayınla' : 'Yayınla'); ?>

            </button>
            <?php if($page->is_published): ?>
                <button type="button" class="btn btn-secondary" onclick="unpublishPage()">
                    <i class="fas fa-eye-slash"></i> Yayından Kaldır
                </button>
            <?php endif; ?>
            <button type="button" class="btn btn-history" onclick="openRevisionsModal()">
                <i class="fas fa-history"></i> Geçmiş
            </button>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer"></div>

    <!-- Main Container -->
    <div class="editor-container">
        <!-- Sidebar -->
        <div class="editor-sidebar">
            <?php echo $__env->make('agency.page.partials.page-settings', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <?php echo $__env->make('agency.page.partials.theme-selector', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        </div>

        <!-- Main Content -->
        <div class="editor-main">
            <div class="editor-panel">
                <div class="panel-header">
                    <h2>İçerik Bölümleri</h2>
                    <button type="button" class="btn btn-primary" onclick="openAddSectionModal()">
                        <i class="fas fa-plus"></i> Bölüm Ekle
                    </button>
                </div>

                <div id="sectionsList">
                    <?php $__empty_1 = true; $__currentLoopData = $page->sections; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $section): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <?php echo $__env->make('agency.page.partials.section-card', ['section' => $section], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="empty-state">
                            <div class="empty-state-icon">📦</div>
                            <h3>Henüz bölüm eklenmemiş</h3>
                            <p>Sayfanıza içerik bölümleri ekleyerek başlayın</p>
                            <button type="button" class="btn btn-primary" onclick="openAddSectionModal()">
                                <i class="fas fa-plus"></i> İlk Bölümü Ekle
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Modals -->
    <?php echo $__env->make('agency.page.partials.add-section-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <?php echo $__env->make('agency.page.partials.edit-section-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <?php echo $__env->make('agency.page.partials.revisions-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        const pageData = <?php echo json_encode($page, 15, 512) ?>;
        const themes = <?php echo json_encode($themes, 15, 512) ?>;
        const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

        // Initialize Sortable
        const sectionsList = document.getElementById('sectionsList');
        if (sectionsList && !sectionsList.querySelector('.empty-state')) {
            new Sortable(sectionsList, {
                animation: 150,
                handle: '.drag-handle',
                ghostClass: 'dragging',
                onEnd: function (evt) {
                    reorderSections();
                }
            });
        }

        // Alert functions
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alertContainer');
            const iconMap = {
                success: 'fa-check-circle',
                error: 'fa-exclamation-circle'
            };

            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.innerHTML = `
            <i class="fas ${iconMap[type]}"></i>
            <span>${message}</span>
            <button class="btn-close" onclick="this.parentElement.remove()">×</button>
        `;
            alertContainer.appendChild(alert);

            setTimeout(() => alert.remove(), 5000);
        }

        // Page functions
        async function savePage() {
            try {
                const formData = new FormData(document.getElementById('pageSettingsForm'));
                await axios.put('<?php echo e(route("agency.page.update")); ?>',
                    Object.fromEntries(formData), {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Sayfa ayarları kaydedildi', 'success');
            } catch (error) {
                console.error(error);
                showAlert('Kayıt sırasında hata oluştu', 'error');
            }
        }

        async function publishPage() {
            if (!confirm('Sayfayı yayınlamak istediğinize emin misiniz?')) return;
            try {
                await axios.post('<?php echo e(route("agency.page.publish")); ?>', {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Sayfa yayınlandı', 'success');
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                showAlert('Yayınlama sırasında hata oluştu', 'error');
            }
        }

        async function unpublishPage() {
            if (!confirm('Sayfayı yayından kaldırmak istediğinize emin misiniz?')) return;
            try {
                await axios.post('<?php echo e(route("agency.page.unpublish")); ?>', {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Sayfa yayından kaldırıldı', 'success');
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                showAlert('İşlem sırasında hata oluştu', 'error');
            }
        }

        function previewPage() {
            window.open('<?php echo e(route("agency.page.preview")); ?>', '_blank');
        }

        async function reorderSections() {
            const sections = Array.from(sectionsList.children)
                .filter(el => el.classList.contains('section-card'))
                .map(el => parseInt(el.dataset.sectionId));

            try {
                await axios.post('<?php echo e(route("agency.page.sections.reorder")); ?>', {
                    sections: sections
                }, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Sıralama güncellendi', 'success');
            } catch (error) {
                showAlert('Sıralama güncellenirken hata oluştu', 'error');
            }
        }

        // Section Modal Functions
        async function openAddSectionModal() {
            const modal = document.getElementById('addSectionModal');
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';

            // Reset filters
            window.currentCategory = 'all';

            // Load available sections from API
            if (typeof loadAvailableSections === 'function') {
                await loadAvailableSections();
            }

            // Use setTimeout to ensure DOM is ready
            setTimeout(() => {
                const searchInput = document.getElementById('sectionSearchInput');
                if (searchInput) {
                    searchInput.value = '';
                }

                // Reset active tab
                document.querySelectorAll('.category-tab').forEach(tab => {
                    tab.classList.remove('active');
                    if (tab.dataset.category === 'all') {
                        tab.classList.add('active');
                    }
                });

                // Render all section types
                if (typeof renderSectionTypes === 'function') {
                    console.log('Calling renderSectionTypes with empty filter');
                    renderSectionTypes('');
                } else {
                    console.error('renderSectionTypes function not found');
                }
            }, 100);
        }

        function closeAddSectionModal() {
            document.getElementById('addSectionModal').style.display = 'none';
            const form = document.getElementById('addSectionForm');
            if (form) {
                form.reset();
            }
            document.body.style.overflow = '';
        }

        function openEditSectionModal() {
            document.getElementById('editSectionModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function closeEditSectionModal() {
            document.getElementById('editSectionModal').style.display = 'none';
            document.body.style.overflow = '';
        }

        // Add Section
        async function saveNewSection() {
            const form = document.getElementById('addSectionForm');

            const data = {
                section_type: document.getElementById('sectionType').value,
                title: document.getElementById('sectionTitle').value,
                subtitle: document.getElementById('sectionSubtitle').value,
                content: document.getElementById('sectionContent').value,
                show_on_mobile: document.getElementById('showOnMobile').checked,
                show_on_tablet: document.getElementById('showOnTablet').checked,
                show_on_desktop: document.getElementById('showOnDesktop').checked,
                is_active: true
            };

            if (!data.section_type) {
                showAlert('Lütfen bölüm tipi seçin', 'error');
                return;
            }

            try {
                const response = await axios.post('<?php echo e(route("agency.page.sections.store")); ?>', data, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });

                showAlert('Bölüm eklendi', 'success');
                closeAddSectionModal();
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                console.error(error);
                showAlert(error.response?.data?.message || 'Bölüm eklenirken hata oluştu', 'error');
            }
        }

        // Edit Section
        async function editSection(sectionId) {
            try {
                const response = await axios.get(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}`);
                const section = response.data.section;

                // Basic fields
                document.getElementById('editSectionId').value = section.id;
                document.getElementById('editSectionType').value = section.section_type;
                document.getElementById('editSectionTitle').value = section.title || '';
                document.getElementById('editSectionSubtitle').value = section.subtitle || '';
                document.getElementById('editSectionContent').value = section.content || '';
                document.getElementById('editIsActive').value = section.is_active ? '1' : '0';
                document.getElementById('editShowOnMobile').checked = section.show_on_mobile;
                document.getElementById('editShowOnTablet').checked = section.show_on_tablet;
                document.getElementById('editShowOnDesktop').checked = section.show_on_desktop;

                // Load config fields for this section type
                loadSectionConfigFields(section.section_type);

                // Wait for fields to be rendered, then populate config values
                setTimeout(() => {
                    populateConfigFields(section.settings || {});

                    // If team section, load team members from data
                    if (section.section_type === 'team' && section.data && section.data.team_members) {
                        window.teamMembers = [];
                        window.teamMemberIdCounter = 0;
                        section.data.team_members.forEach(member => {
                            const memberWithId = {
                                ...member,
                                id: ++window.teamMemberIdCounter
                            };
                            window.teamMembers.push(memberWithId);
                            addTeamMember(memberWithId);
                        });
                    }

                    // If hero section, load stats from data
                    if (section.section_type === 'hero' && section.data && section.data.stats) {
                        window.heroStats = [];
                        window.heroStatIdCounter = 0;
                        section.data.stats.forEach(stat => {
                            const statWithId = {
                                ...stat,
                                id: ++window.heroStatIdCounter
                            };
                            window.heroStats.push(statWithId);
                            addHeroStat(statWithId);
                        });
                    }
                }, 100);

                openEditSectionModal();
            } catch (error) {
                console.error(error);
                showAlert('Bölüm bilgileri yüklenirken hata oluştu', 'error');
            }
        }

        function populateConfigFields(settings) {
            Object.keys(settings).forEach(key => {
                const field = document.getElementById(`config_${key}`);
                if (field) {
                    if (field.type === 'checkbox') {
                        field.checked = settings[key] === true || settings[key] === 'true';
                    } else if (field.type === 'file') {
                        if (settings[key]) {
                            const onchangeAttr = field.getAttribute('onchange');
                            if (onchangeAttr) {
                                const match = onchangeAttr.match(/['"]([^'"]+)['"]/);
                                if (match) {
                                    const previewId = match[1];
                                    const preview = document.getElementById(previewId);
                                    if (preview) {
                                        preview.querySelector('img').src = '<?php echo e(asset("storage")); ?>/' + settings[key];
                                        preview.style.display = 'block';
                                    }
                                }
                            }
                        }
                    } else {
                        field.value = config[key] || '';
                    }
                }
            });
        }

        async function updateSection() {
            const sectionId = document.getElementById('editSectionId').value;
            const sectionType = document.getElementById('editSectionType').value;

            const data = {
                title: document.getElementById('editSectionTitle').value,
                subtitle: document.getElementById('editSectionSubtitle').value,
                content: document.getElementById('editSectionContent').value,
                is_active: document.getElementById('editIsActive').value === '1',
                show_on_mobile: document.getElementById('editShowOnMobile').checked,
                show_on_tablet: document.getElementById('editShowOnTablet').checked,
                show_on_desktop: document.getElementById('editShowOnDesktop').checked,
                settings: {},
                data: {}
            };

            // Handle team section
            if (sectionType === 'team') {
                console.log('Processing team section...');
                console.log('Team members before processing:', window.teamMembers);

                const teamMembersData = [];

                for (const member of window.teamMembers) {
                    // Read current values from DOM inputs
                    const nameInput = document.getElementById(`team_member_name_${member.id}`);
                    const positionInput = document.getElementById(`team_member_position_${member.id}`);
                    const photoInput = document.getElementById(`team_member_photo_${member.id}`);

                    const memberData = {
                        name: nameInput ? nameInput.value : (member.name || ''),
                        position: positionInput ? positionInput.value : (member.position || ''),
                        photo: member.photo || ''
                    };

                    // Upload photo if new file selected
                    if (photoInput && photoInput.files && photoInput.files[0]) {
                        console.log('Uploading photo for member:', member.id);
                        const uploadedPath = await uploadSectionImage(sectionId, photoInput.files[0], `team_member_${member.id}`);
                        if (uploadedPath) {
                            memberData.photo = uploadedPath;
                            console.log('Photo uploaded:', uploadedPath);
                        }
                    }

                    teamMembersData.push(memberData);
                    console.log('Member data added:', memberData);
                }

                data.data = {
                    team_members: teamMembersData
                };

                console.log('Team members data to be sent:', data.data);
            }

            // Handle hero section stats
            if (sectionType === 'hero' && window.heroStats && window.heroStats.length > 0) {
                console.log('Processing hero section stats...');
                console.log('Hero stats before processing:', window.heroStats);

                const heroStatsData = [];

                for (const stat of window.heroStats) {
                    const iconInput = document.getElementById(`hero_stat_icon_${stat.id}`);
                    const numberInput = document.getElementById(`hero_stat_number_${stat.id}`);
                    const labelInput = document.getElementById(`hero_stat_label_${stat.id}`);

                    const statData = {
                        icon: iconInput ? iconInput.value : (stat.icon || 'fas fa-star'),
                        number: numberInput ? numberInput.value : (stat.number || ''),
                        label: labelInput ? labelInput.value : (stat.label || '')
                    };

                    heroStatsData.push(statData);
                    console.log('Stat data added:', statData);
                }

                data.data = {
                    ...data.data,
                    stats: heroStatsData
                };

                console.log('Hero stats data to be sent:', data.data);
            }

            // Handle other config fields
            const configFields = document.querySelectorAll('[id^="config_"]');

            for (const field of configFields) {
                const key = field.id.replace('config_', '');

                if (field.type === 'checkbox') {
                    data.settings[key] = field.checked;
                } else if (field.type === 'file') {
                    if (field.files && field.files[0]) {
                        const uploadedPath = await uploadSectionImage(sectionId, field.files[0], key);
                        if (uploadedPath) {
                            data.settings[key] = uploadedPath;
                        }
                    }
                } else if (field.type === 'number') {
                    data.settings[key] = parseInt(field.value) || 0;
                } else {
                    data.settings[key] = field.value;
                }
            }

            try {
                console.log('Sending update request with data:', data);

                const response = await axios.put(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}`, data, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });

                console.log('Update response:', response.data);

                showAlert('Bölüm güncellendi', 'success');
                closeEditSectionModal();
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                console.error('Update error:', error);
                console.error('Error response:', error.response?.data);
                showAlert(error.response?.data?.message || 'Bölüm güncellenirken hata oluştu', 'error');
            }
        }

        async function uploadSectionImage(sectionId, file, key) {
            const formData = new FormData();
            formData.append('image', file);
            formData.append('key', key);

            try {
                const response = await axios.post(
                    `<?php echo e(url('agency/page/sections')); ?>/${sectionId}/upload-image`,
                    formData,
                    {
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                );

                return response.data.path;
            } catch (error) {
                console.error('Image upload error:', error);
                showAlert('Görsel yüklenirken hata oluştu', 'error');
                return null;
            }
        }

        // Section Actions
        async function toggleSection(sectionId) {
            try {
                await axios.post(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}/toggle`, {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Bölüm durumu güncellendi', 'success');
                setTimeout(() => window.location.reload(), 500);
            } catch (error) {
                showAlert('İşlem sırasında hata oluştu', 'error');
            }
        }

        async function duplicateSection(sectionId) {
            if (!confirm('Bu bölümü kopyalamak istediğinize emin misiniz?')) return;

            try {
                await axios.post(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}/duplicate`, {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Bölüm kopyalandı', 'success');
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                showAlert('Kopyalama sırasında hata oluştu', 'error');
            }
        }

        async function deleteSection(sectionId) {
            if (!confirm('Bu bölümü silmek istediğinize emin misiniz? Bu işlem geri alınamaz.')) return;

            try {
                await axios.delete(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}`, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                showAlert('Bölüm silindi', 'success');
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                showAlert('Silme sırasında hata oluştu', 'error');
            }
        }

        async function moveUp(sectionId) {
            try {
                await axios.post(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}/move-up`, {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                setTimeout(() => window.location.reload(), 500);
            } catch (error) {
                showAlert('İşlem sırasında hata oluştu', 'error');
            }
        }

        async function moveDown(sectionId) {
            try {
                await axios.post(`<?php echo e(url('agency/page/sections')); ?>/${sectionId}/move-down`, {}, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                setTimeout(() => window.location.reload(), 500);
            } catch (error) {
                showAlert('İşlem sırasında hata oluştu', 'error');
            }
        }

        function previewImage(input, previewId) {
            const preview = document.getElementById(previewId);

            if (input.files && input.files[0]) {
                const reader = new FileReader();

                reader.onload = function (e) {
                    preview.querySelector('img').src = e.target.result;
                    preview.style.display = 'block';
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

        // Section Config Field Templates
        const sectionConfigTemplates = {
            hero: `
        <div class="form-group">
            <label class="form-label">Arka Plan Görseli</label>
            <input type="file" id="config_background_image" class="form-control" accept="image/*" onchange="previewImage(this, 'hero_bg_preview')">
            <div id="hero_bg_preview" class="image-upload-preview" style="display: none;">
                <img src="" alt="Preview">
            </div>
        </div>

        <div class="form-group">
            <label class="form-label">Badge İkonu (Opsiyonel)</label>
            <input type="text" id="config_badge_icon" class="form-control" placeholder="✨ (emoji veya FontAwesome class)">
            <small class="form-text text-muted">Alt başlık yanında gösterilecek emoji veya ikon</small>
        </div>

        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">Ana Buton Metni</label>
                <input type="text" id="config_primary_button_text" class="form-control" placeholder="Keşfet">
            </div>
            <div class="form-group">
                <label class="form-label">Ana Buton Linki</label>
                <input type="text" id="config_primary_button_url" class="form-control" placeholder="#hizmetler">
            </div>
        </div>

        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">İkincil Buton Metni</label>
                <input type="text" id="config_secondary_button_text" class="form-control" placeholder="Bize Ulaşın">
            </div>
            <div class="form-group">
                <label class="form-label">İkincil Buton Linki</label>
                <input type="text" id="config_secondary_button_url" class="form-control" placeholder="#contact">
            </div>
        </div>

        <div class="form-group">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                <div>
                    <label class="form-label" style="margin: 0;">İstatistikler (Opsiyonel)</label>
                    <small class="form-text text-muted">Hero bölümünde gösterilecek istatistikler</small>
                </div>
                <button type="button" class="btn btn-primary" onclick="addHeroStat()" style="padding: 0.5rem 1rem; font-size: 0.813rem;">
                    <i class="fas fa-plus"></i> İstatistik Ekle
                </button>
            </div>
            <div id="heroStatsList" style="display: flex; flex-direction: column; gap: 1rem;">
                <!-- Hero stats will be added here -->
            </div>
        </div>
    `,

            team: `
        <div class="form-group">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                <label class="form-label" style="margin: 0;">Ekip Üyeleri</label>
                <button type="button" class="btn btn-primary" onclick="addTeamMember()" style="padding: 0.5rem 1rem; font-size: 0.813rem;">
                    <i class="fas fa-plus"></i> Ekip Üyesi Ekle
                </button>
            </div>
            <div id="teamMembersList" style="display: flex; flex-direction: column; gap: 1rem;">
                <!-- Team members will be added here -->
            </div>
        </div>
    `,

            tours_grid: `
        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">Gösterilecek Tur Sayısı</label>
                <input type="number" id="config_tour_limit" class="form-control" value="6" min="1" max="50">
            </div>
            <div class="form-group">
                <label class="form-label">Sıralama</label>
                <select id="config_sort_by" class="form-control">
                    <option value="created_at">En Yeni</option>
                    <option value="name">İsme Göre</option>
                    <option value="price">Fiyata Göre</option>
                    <option value="popular">Popülerlik</option>
                </select>
            </div>
        </div>
    `,

            tours_slider: `
        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">Gösterilecek Tur Sayısı</label>
                <input type="number" id="config_tour_limit" class="form-control" value="8" min="1" max="50">
            </div>
            <div class="form-group">
                <label class="form-label">Otomatik Kaydır</label>
                <select id="config_autoplay" class="form-control">
                    <option value="true">Evet</option>
                    <option value="false">Hayır</option>
                </select>
            </div>
        </div>
    `,

            categories: `
        <div class="form-group">
            <label class="form-label">Gösterilecek Kategori Sayısı</label>
            <input type="number" id="config_category_limit" class="form-control" value="8" min="1" max="20">
        </div>
    `,

            gallery: `
        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">Galeri Klasörü</label>
                <select id="config_gallery_folder_id" class="form-control">
                    <option value="">Tüm Görseller</option>
                    <!-- Will be populated dynamically -->
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">Görsel Sayısı</label>
                <input type="number" id="config_image_limit" class="form-control" value="12" min="1" max="50">
            </div>
        </div>
    `,

            cta: `
        <div class="form-group">
            <label class="form-label">İkon (Font Awesome)</label>
            <input type="text" id="config_icon" class="form-control" placeholder="fas fa-phone">
            <small style="color: #6B7280; font-size: 0.813rem;">Örnek: fas fa-phone, fas fa-envelope, fas fa-rocket</small>
        </div>

        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
            <div class="form-group">
                <label class="form-label">Ana Buton Metni</label>
                <input type="text" id="config_primary_button_text" class="form-control">
            </div>
            <div class="form-group">
                <label class="form-label">Ana Buton Linki</label>
                <input type="text" id="config_primary_button_url" class="form-control">
            </div>
        </div>

        <div class="form-group">
            <label class="form-label" style="display: flex; align-items: center; cursor: pointer;">
                <input type="checkbox" id="config_show_stats" style="margin-right: 0.5rem;" checked>
                İstatistikleri Göster
            </label>
        </div>

        <div id="stats_fields" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem;">
            <div class="form-group">
                <label class="form-label">İstatistik 1 Değer</label>
                <input type="text" id="config_stat1_value" class="form-control" placeholder="500+">
                <label class="form-label" style="margin-top: 0.5rem;">İstatistik 1 Etiket</label>
                <input type="text" id="config_stat1_label" class="form-control" placeholder="Mutlu Müşteri">
            </div>
            <div class="form-group">
                <label class="form-label">İstatistik 2 Değer</label>
                <input type="text" id="config_stat2_value" class="form-control" placeholder="50+">
                <label class="form-label" style="margin-top: 0.5rem;">İstatistik 2 Etiket</label>
                <input type="text" id="config_stat2_label" class="form-control" placeholder="Tur Rotası">
            </div>
            <div class="form-group">
                <label class="form-label">İstatistik 3 Değer</label>
                <input type="text" id="config_stat3_value" class="form-control" placeholder="20+">
                <label class="form-label" style="margin-top: 0.5rem;">İstatistik 3 Etiket</label>
                <input type="text" id="config_stat3_label" class="form-control" placeholder="Yıllık Tecrübe">
            </div>
        </div>
    `
        };

        function loadSectionConfigFields(sectionType) {
            const container = document.getElementById('sectionConfigFields');
            const template = sectionConfigTemplates[sectionType];

            if (template) {
                container.innerHTML = template;

                // If team section, initialize team members from data
                if (sectionType === 'team') {
                    window.teamMembers = [];
                    window.teamMemberIdCounter = 0;
                }

                // If hero section, initialize hero stats from data
                if (sectionType === 'hero') {
                    window.heroStats = [];
                    window.heroStatIdCounter = 0;
                }
            } else {
                container.innerHTML = '<p style="color: #6B7280; font-style: italic;">Bu bölüm tipi için özel ayar bulunmamaktadır.</p>';
            }
        }

        // Team Member Management
        window.teamMembers = [];
        window.teamMemberIdCounter = 0;

        function addTeamMember(member = null) {
            const memberId = member?.id || ++window.teamMemberIdCounter;
            const memberData = member || {
                id: memberId,
                name: '',
                position: '',
                photo: '',
                photo_file: null
            };

            // Always push to array, even if member is provided (for reloading)
            if (!member) {
                window.teamMembers.push(memberData);
            } else {
                // When loading existing member, add to array
                window.teamMembers.push(memberData);
            }

            console.log('Team member added:', memberData);
            console.log('Current team members:', window.teamMembers);

            const memberCard = document.createElement('div');
            memberCard.className = 'team-member-card';
            memberCard.id = `team-member-${memberId}`;
            memberCard.innerHTML = `
            <div style="background: #F9FAFB; border: 2px solid #E5E7EB; border-radius: 8px; padding: 1rem;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                    <h4 style="margin: 0; font-size: 0.938rem; font-weight: 600; color: #374151;">
                        <i class="fas fa-user"></i> Ekip Üyesi #${memberId}
                    </h4>
                    <button type="button" onclick="removeTeamMember(${memberId})"
                            style="background: #EF4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 6px; cursor: pointer; font-size: 0.813rem; transition: all 0.2s;">
                        <i class="fas fa-trash"></i> Sil
                    </button>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Ad Soyad</label>
                        <input type="text" id="team_member_name_${memberId}" class="form-control"
                               placeholder="Ahmet Yılmaz" value="${memberData.name}"
                               onchange="updateTeamMemberData(${memberId}, 'name', this.value)">
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Görev</label>
                        <input type="text" id="team_member_position_${memberId}" class="form-control"
                               placeholder="Genel Müdür" value="${memberData.position}"
                               onchange="updateTeamMemberData(${memberId}, 'position', this.value)">
                    </div>
                </div>

                <div class="form-group" style="margin-bottom: 0;">
                    <label class="form-label">Fotoğraf</label>
                    <input type="file" id="team_member_photo_${memberId}" class="form-control"
                           accept="image/*" onchange="previewTeamMemberPhoto(${memberId}, this)">
                    <div id="team_member_photo_preview_${memberId}" class="image-upload-preview" style="display: ${memberData.photo ? 'block' : 'none'}; margin-top: 0.5rem;">
                        <img src="${memberData.photo ? (memberData.photo.startsWith('http') ? memberData.photo : '<?php echo e(asset("storage")); ?>/' + memberData.photo) : ''}"
                             alt="Preview" style="max-width: 200px; border-radius: 8px;">
                    </div>
                </div>
            </div>
        `;

            const teamMembersList = document.getElementById('teamMembersList');
            if (!teamMembersList) {
                console.error('teamMembersList container not found!');
                return;
            }

            teamMembersList.appendChild(memberCard);
        }

        function removeTeamMember(memberId) {
            if (!confirm('Bu ekip üyesini silmek istediğinize emin misiniz?')) return;

            window.teamMembers = window.teamMembers.filter(m => m.id !== memberId);
            document.getElementById(`team-member-${memberId}`).remove();
        }

        function updateTeamMemberData(memberId, field, value) {
            const member = window.teamMembers.find(m => m.id === memberId);
            if (member) {
                member[field] = value;
            }
        }

        function previewTeamMemberPhoto(memberId, input) {
            const preview = document.getElementById(`team_member_photo_preview_${memberId}`);
            const member = window.teamMembers.find(m => m.id === memberId);

            if (input.files && input.files[0]) {
                const reader = new FileReader();

                if (member) {
                    member.photo_file = input.files[0];
                }

                reader.onload = function (e) {
                    preview.querySelector('img').src = e.target.result;
                    preview.style.display = 'block';
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

        // Hero Stats Management
        window.heroStats = [];
        window.heroStatIdCounter = 0;

        function addHeroStat(stat = null) {
            const statId = stat?.id || ++window.heroStatIdCounter;
            const statData = stat || {
                id: statId,
                icon: 'fas fa-star',
                number: '',
                label: ''
            };

            if (!stat) {
                window.heroStats.push(statData);
            } else {
                window.heroStats.push(statData);
            }

            const statCard = document.createElement('div');
            statCard.className = 'hero-stat-card';
            statCard.id = `hero-stat-${statId}`;
            statCard.innerHTML = `
            <div style="background: #F9FAFB; border: 2px solid #E5E7EB; border-radius: 8px; padding: 1rem;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                    <h4 style="margin: 0; font-size: 0.938rem; font-weight: 600; color: #374151;">
                        <i class="fas fa-chart-line"></i> İstatistik #${statId}
                    </h4>
                    <button type="button" onclick="removeHeroStat(${statId})"
                            style="background: #EF4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 6px; cursor: pointer; font-size: 0.813rem; transition: all 0.2s;">
                        <i class="fas fa-trash"></i> Sil
                    </button>
                </div>

                <div style="display: grid; grid-template-columns: 100px 1fr 1fr; gap: 1rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">İkon</label>
                        <input type="text" id="hero_stat_icon_${statId}" class="form-control"
                               placeholder="fas fa-star" value="${statData.icon}"
                               onchange="updateHeroStatData(${statId}, 'icon', this.value)">
                        <small class="form-text text-muted">FontAwesome class</small>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Sayı/Değer</label>
                        <input type="text" id="hero_stat_number_${statId}" class="form-control"
                               placeholder="10,000+" value="${statData.number}"
                               onchange="updateHeroStatData(${statId}, 'number', this.value)">
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Etiket</label>
                        <input type="text" id="hero_stat_label_${statId}" class="form-control"
                               placeholder="Mutlu Müşteri" value="${statData.label}"
                               onchange="updateHeroStatData(${statId}, 'label', this.value)">
                    </div>
                </div>
            </div>
        `;

            const heroStatsList = document.getElementById('heroStatsList');
            if (!heroStatsList) {
                console.error('heroStatsList container not found!');
                return;
            }

            heroStatsList.appendChild(statCard);
        }

        function removeHeroStat(statId) {
            if (!confirm('Bu istatistiği silmek istediğinize emin misiniz?')) return;

            window.heroStats = window.heroStats.filter(s => s.id !== statId);
            document.getElementById(`hero-stat-${statId}`).remove();
        }

        function updateHeroStatData(statId, field, value) {
            const stat = window.heroStats.find(s => s.id === statId);
            if (stat) {
                stat[field] = value;
            }
        }

        // Revisions Modal
        function openRevisionsModal() {
            document.getElementById('revisionsModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
            loadRevisions();
        }

        function closeRevisionsModal() {
            document.getElementById('revisionsModal').style.display = 'none';
            document.body.style.overflow = '';
        }

        async function loadRevisions() {
            const loadingEl = document.getElementById('revisionsLoading');
            const listEl = document.getElementById('revisionsList');

            loadingEl.style.display = 'block';
            listEl.innerHTML = '';

            try {
                const response = await axios.get('<?php echo e(route("agency.page.revisions")); ?>');
                const revisions = response.data.data;

                loadingEl.style.display = 'none';

                if (revisions.length === 0) {
                    listEl.innerHTML = `
                <div style="text-align: center; padding: 3rem; color: #6B7280;">
                    <i class="fas fa-history" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.3;"></i>
                    <p style="font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem;">Henüz Geçmiş Yok</p>
                    <p style="font-size: 0.938rem;">Sayfa değişiklikleri burada görünecek</p>
                </div>
            `;
                    return;
                }

                revisions.forEach((revision, index) => {
                    const isCurrent = index === 0;
                    const changes = revision.changes || {};
                    const changesList = Object.keys(changes).length > 0 ?
                        Object.entries(changes).map(([key, value]) => {
                            const icons = {
                                'title': 'fa-heading',
                                'meta_title': 'fa-tag',
                                'meta_description': 'fa-file-alt',
                                'theme_id': 'fa-palette',
                                'is_published': 'fa-globe',
                                'sections': 'fa-layer-group'
                            };
                            return `
                        <div class="revision-change-item">
                            <i class="fas ${icons[key] || 'fa-edit'}" style="color: var(--primary);"></i>
                            <span><strong>${translateKey(key)}</strong> güncellendi</span>
                        </div>
                    `;
                        }).join('') :
                        '<div class="revision-change-item"><i class="fas fa-info-circle" style="color: #6B7280;"></i><span>İlk versiyon</span></div>';

                    const statusBadge = isCurrent ?
                        '<span class="revision-badge current"><i class="fas fa-check"></i> Aktif Versiyon</span>' :
                        revision.is_published ?
                            '<span class="revision-badge published"><i class="fas fa-globe"></i> Yayınlandı</span>' :
                            '<span class="revision-badge draft"><i class="fas fa-file"></i> Taslak</span>';

                    const item = document.createElement('div');
                    item.className = `revision-item${isCurrent ? ' current' : ''}`;
                    item.innerHTML = `
                <div class="revision-header">
                    <div class="revision-info">
                        <div class="revision-meta">
                            <div class="revision-meta-item">
                                <i class="fas fa-clock"></i>
                                <span>${formatDate(revision.created_at)}</span>
                            </div>
                            <div class="revision-meta-item">
                                <i class="fas fa-user"></i>
                                <span>${revision.creator?.full_name || 'Bilinmeyen'}</span>
                            </div>
                            ${revision.note ? `
                                <div class="revision-meta-item">
                                    <i class="fas fa-sticky-note"></i>
                                    <span>${revision.note}</span>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                    ${statusBadge}
                </div>

                ${Object.keys(changes).length > 0 ? `
                    <div class="revision-changes">
                        <div class="revision-changes-title">
                            <i class="fas fa-list"></i> Değişiklikler
                        </div>
                        <div class="revision-changes-list">
                            ${changesList}
                        </div>
                    </div>
                ` : ''}

                <div class="revision-actions">
                    <button class="revision-compare-btn" onclick="compareRevision(${revision.id})">
                        <i class="fas fa-code-compare"></i>
                        Karşılaştır
                    </button>
                    ${!isCurrent ? `
                        <button class="revision-restore-btn" onclick="restoreRevision(${revision.id})">
                            <i class="fas fa-undo"></i>
                            Bu Versiyonu Geri Yükle
                        </button>
                    ` : ''}
                </div>
            `;

                    listEl.appendChild(item);
                });

            } catch (error) {
                console.error('Error loading revisions:', error);
                loadingEl.style.display = 'none';
                listEl.innerHTML = `
            <div style="text-align: center; padding: 3rem; color: #EF4444;">
                <i class="fas fa-exclamation-circle" style="font-size: 3rem; margin-bottom: 1rem;"></i>
                <p style="font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem;">Yükleme Hatası</p>
                <p style="font-size: 0.938rem;">Geçmiş yüklenirken bir hata oluştu</p>
            </div>
        `;
            }
        }

        async function restoreRevision(revisionId) {
            if (!confirm('Bu versiyonu geri yüklemek istediğinize emin misiniz? Mevcut değişiklikler kaybolacak.')) {
                return;
            }

            try {
                await axios.post('<?php echo e(route("agency.page.revisions.restore")); ?>', {
                    revision_id: revisionId
                }, {
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });

                showAlert('Versiyon geri yüklendi', 'success');
                closeRevisionsModal();
                setTimeout(() => window.location.reload(), 1000);
            } catch (error) {
                console.error(error);
                showAlert('Geri yükleme sırasında hata oluştu', 'error');
            }
        }

        function compareRevision(revisionId) {
            // TODO: Karşılaştırma modalı implementasyonu
            showAlert('Karşılaştırma özelliği yakında eklenecek', 'info');
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diff = now - date;
            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);

            if (minutes < 1) return 'Az önce';
            if (minutes < 60) return `${minutes} dakika önce`;
            if (hours < 24) return `${hours} saat önce`;
            if (days < 7) return `${days} gün önce`;

            return date.toLocaleDateString('tr-TR', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        function translateKey(key) {
            const translations = {
                'title': 'Sayfa Başlığı',
                'meta_title': 'SEO Başlığı',
                'meta_description': 'SEO Açıklaması',
                'meta_keywords': 'Anahtar Kelimeler',
                'theme_id': 'Tema',
                'is_published': 'Yayın Durumu',
                'sections': 'Bölümler',
                'theme_overrides': 'Tema Ayarları'
            };
            return translations[key] || key;
        }
    </script>

    <?php echo $__env->yieldPushContent('scripts'); ?>
</body>

</html><?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/page/editor.blade.php ENDPATH**/ ?>