@extends('agency.layouts.standalone')

@section('title', 'Site Editörü')

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/agency/css/site-studio.css') }}?v={{ filemtime(public_path('assets/agency/css/site-studio.css')) }}">
@endpush

@section('content')
<div class="sx sxe">
    {{-- ── Komut şeridi ── --}}
    <div class="sxe-bar">
        <a href="{{ route('agency.site.index') }}" class="sxe-bar__back"><i class="fas fa-arrow-left"></i> Panel</a>
        <span class="sxe-bar__sep"></span>
        <span class="sxe-bar__brand">
            <b>Site Editörü</b>
            <small id="sxeLive">
                @if($site->isPublished())
                    <span class="sxe-live on"><i class="sx-dot"></i> Yayında</span>
                @else
                    <span class="sxe-live off"><i class="sx-dot"></i> Taslak</span>
                @endif
            </small>
        </span>

        <div class="sxe-pages" id="sxePageTabs"></div>

        <div class="sxe-dev">
            <button type="button" class="on" data-device="" title="Masaüstü"><i class="fas fa-desktop"></i></button>
            <button type="button" data-device="tablet" title="Tablet"><i class="fas fa-tablet-screen-button"></i></button>
            <button type="button" data-device="mobile" title="Mobil"><i class="fas fa-mobile-screen"></i></button>
        </div>

        <button type="button" class="sx-btn" id="sxeReload" title="Önizlemeyi yenile"><i class="fas fa-rotate"></i></button>
        <a href="{{ route('agency.site.preview', 'home') }}" target="_blank" rel="noopener" class="sx-btn">
            <i class="fas fa-eye"></i> Yeni sekmede
        </a>
        <button type="button" class="sx-btn sx-btn--primary" id="sxePublish">
            <i class="fas fa-arrow-up-from-bracket"></i> Yayınla
        </button>
    </div>

    <div class="sxe-body">
        {{-- ── İkon rayı ── --}}
        <div class="sxe-rail">
            <button type="button" class="on" data-panel="sections">
                <i class="fas fa-layer-group"></i><span class="sxe-rail__tip">Bölümler</span>
            </button>
            <button type="button" data-panel="pages">
                <i class="fas fa-file-lines"></i><span class="sxe-rail__tip">Sayfalar</span>
            </button>
            <button type="button" data-panel="site">
                <i class="fas fa-sliders"></i><span class="sxe-rail__tip">Site Ayarları</span>
            </button>
            <span class="sxe-rail__gap"></span>
            <a href="{{ route('agency.site.branding.edit') }}" target="_blank" rel="noopener">
                <i class="fas fa-palette"></i><span class="sxe-rail__tip">Marka & Logo</span>
            </a>
        </div>

        {{-- ── Panel ── --}}
        <div class="sxe-panel">
            {{-- Bölümler --}}
            <div data-panel-body="sections" style="display:flex;flex-direction:column;min-height:0;flex:1">
                <div class="sxe-panel__h">
                    <b>Bölümler</b>
                    <span class="sx-card__hint" id="sxeSectionCount"></span>
                </div>
                <div class="sxe-panel__c" id="sxeSectionList"></div>
                <div class="sxe-panel__f">
                    <button type="button" class="sx-btn sx-btn--dash sx-btn--block" id="sxeAddSection">
                        <i class="fas fa-plus"></i> Bölüm ekle
                    </button>
                </div>
            </div>

            {{-- Sayfalar --}}
            <div data-panel-body="pages" hidden style="flex-direction:column;min-height:0;flex:1">
                <div class="sxe-panel__h"><b>Sayfalar</b></div>
                <div class="sxe-panel__c" id="sxePageList"></div>
                <div class="sxe-panel__f">
                    <button type="button" class="sx-btn sx-btn--dash sx-btn--block" id="sxeAddPage">
                        <i class="fas fa-plus"></i> Özel sayfa ekle
                    </button>
                </div>
            </div>

            {{-- Site ayarları --}}
            <div data-panel-body="site" hidden style="flex-direction:column;min-height:0;flex:1">
                <div class="sxe-panel__h"><b>Site Ayarları</b></div>
                <div class="sxe-panel__c">
                    @foreach([
                        ['header', 'fa-window-maximize', 'Üst Menü', 'Logo, menü, telefon ve CTA'],
                        ['footer', 'fa-table-columns', 'Alt Bilgi', 'İletişim, sosyal medya, yasal linkler'],
                        ['chat', 'fa-comment-dots', 'Canlı Destek', 'Karşılama metni ve çalışma saatleri'],
                        ['advanced', 'fa-code', 'SEO & Gelişmiş', 'Meta bilgiler, özel CSS/JS, ölçüm kodları'],
                    ] as [$key, $icon, $label, $description])
                        <div class="sxe-sec" data-site-form="{{ $key }}">
                            <span class="sxe-sec__ic"><i class="fas {{ $icon }}"></i></span>
                            <span class="sxe-sec__b">
                                <span class="sxe-sec__t">{{ $label }}</span>
                                <span class="sxe-sec__s" style="text-transform:none;letter-spacing:0;font-weight:600">{{ $description }}</span>
                            </span>
                            <i class="fas fa-chevron-right" style="font-size:.6rem;color:var(--sx-mut-2)"></i>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        {{-- ── Sahne ── --}}
        <div class="sxe-stage">
            <div class="sxe-frame" id="sxeFrame">
                <iframe id="sxeIframe" src="" title="Site önizleme"></iframe>
            </div>
        </div>
    </div>
</div>

{{-- Bölüm kütüphanesi: solda liste, sağda bölümün gerçek şablonla örneği --}}
<div class="modal fade sxe-modal" id="sxeAddModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content sx">
            <div class="modal-header">
                <h6 class="modal-title"><i class="fas fa-shapes" style="color:var(--sx-acc)"></i> Bölüm Kütüphanesi</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" style="padding:0">
                <div class="sxe-lib">
                    <div class="sxe-lib__side">
                        <div class="sxe-lib__search">
                            <div class="sxe-search" style="margin:0">
                                <i class="fas fa-magnifying-glass"></i>
                                <input type="text" id="sxeAddSearch" placeholder="Bölüm ara…" autocomplete="off">
                            </div>
                        </div>
                        <div class="sxe-lib__list" id="sxeAddList"></div>
                    </div>

                    <div class="sxe-lib__main">
                        <div class="sxe-lib__head">
                            <b id="sxeLibName">Bölüm seçin</b>
                            <small id="sxeLibDesc">Soldan bir bölüme tıklayın; örneği burada görünür.</small>
                            <span class="sx-seg">
                                <button type="button" class="on" data-lib-device="desktop" title="Masaüstü"><i class="fas fa-desktop"></i></button>
                                <button type="button" data-lib-device="mobile" title="Mobil"><i class="fas fa-mobile-screen"></i></button>
                            </span>
                            <button type="button" class="sx-btn sx-btn--primary is-off" id="sxeLibAdd">
                                <i class="fas fa-plus"></i> Sayfaya ekle
                            </button>
                        </div>
                        <div class="sxe-lib__stage">
                            <div class="sxe-lib__frame" id="sxeLibFrame">
                                <iframe id="sxeLibIframe" src="" title="Bölüm örneği"></iframe>
                            </div>
                        </div>
                    </div>

                    <div class="sxe-lib__src">
                        <div class="sx-sec-h" style="padding:0 0 .55rem">
                            <i class="fas fa-database"></i><span>Veriyi nereden çeker?</span>
                        </div>
                        <div class="sx-src" id="sxeLibSource">
                            <p class="sx-help" style="margin:0">Soldan bir bölüm seçin.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Düzenleme çekmecesi --}}
<div class="offcanvas offcanvas-end sxe-drawer sx" tabindex="-1" id="sxeDrawer" data-bs-backdrop="false" data-bs-scroll="true">
    <div class="offcanvas-header">
        <h6 class="offcanvas-title" id="sxeDrawerTitle">Düzenle</h6>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body" id="sxeDrawerBody"></div>
    <div class="sxe-drawer__f">
        <button type="button" class="sx-btn sx-btn--primary" style="flex:1" id="sxeDrawerSave">
            <i class="fas fa-floppy-disk"></i> Kaydet
        </button>
        <button type="button" class="sx-btn" data-bs-dismiss="offcanvas">Vazgeç</button>
    </div>
</div>
@endsection

@push('scripts')
@include('agency.site.partials._section-sources')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
(function () {
    'use strict';

    /* ---------- Sunucudan gelen durum ---------- */
    const SITE = @json($site);
    const MANIFEST = @json($availableSections);
    const HEADER_FIELDS = @json($headerFields);
    const FOOTER_FIELDS = @json($footerFields);
    const CHAT_FIELDS = @json($chatFields);
    const ADVANCED_FIELDS = @json($advancedFields);
    const DISK_FOLDERS = @json($diskFolders);
    const CSRF = '{{ csrf_token() }}';
    const BASE = '{{ url('agency/site') }}';
    const PREVIEW_BASE = '{{ url('agency/site/preview') }}';
    const STORAGE = '{{ asset('storage') }}';

    let pages = SITE.pages || [];
    let currentPageId = (pages.find((page) => page.type === 'home') || pages[0] || {}).id;
    let drawerContext = null;              // {kind:'section'|'page'|'site', …}
    let sectionSortable = null;

    const frame = document.getElementById('sxeIframe');
    const drawer = new bootstrap.Offcanvas(document.getElementById('sxeDrawer'));
    const addModal = new bootstrap.Modal(document.getElementById('sxeAddModal'));

    /* ---------- Yardımcılar ---------- */
    async function api(method, url, body) {
        const options = { method, headers: { 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' } };
        if (body instanceof FormData) {
            options.body = body;
        } else if (body !== undefined) {
            options.headers['Content-Type'] = 'application/json';
            options.body = JSON.stringify(body);
        }
        const response = await fetch(url, options);
        const data = await response.json().catch(() => ({}));
        if (!response.ok || data.success === false) throw new Error(data.message || 'İşlem tamamlanamadı.');
        return data;
    }
    const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
    const fail = (error) => appToast({ icon: 'error', title: error.message });
    const currentPage = () => pages.find((page) => page.id === currentPageId);
    const pageKey = (page) => page.type === 'home' ? 'home' : (page.type === 'contact' ? 'contact' : page.slug);
    const isEditable = (page) => ['home', 'contact', 'custom'].includes(page.type);

    function reloadFrame(scrollToSectionId) {
        const page = currentPage();
        if (!page || !isEditable(page)) { frame.src = 'about:blank'; return; }
        frame.src = PREVIEW_BASE + '/' + encodeURIComponent(pageKey(page)) + '?editor=1&_=' + Date.now();
        if (scrollToSectionId) {
            frame.addEventListener('load', function once() {
                frame.removeEventListener('load', once);
                setTimeout(() => frame.contentWindow.postMessage({ type: 'v-scroll-to-section', id: scrollToSectionId }, '*'), 250);
            });
        }
    }

    /* ---------- Sayfa sekmeleri ---------- */
    function renderPageTabs() {
        const holder = document.getElementById('sxePageTabs');
        holder.innerHTML = '';
        pages.slice().sort((a, b) => a.nav_order - b.nav_order).forEach((page) => {
            const button = document.createElement('button');
            button.className = 'sxe-page' + (page.id === currentPageId ? ' on' : '');
            button.innerHTML = esc(page.nav_label || page.title) + (isEditable(page) ? '' : ' <i class="fas fa-lock"></i>');
            button.addEventListener('click', () => {
                if (!isEditable(page)) {
                    appToast({ icon: 'info', title: 'Tur sayfaları otomatik oluşur; içerik tur kayıtlarından gelir.' });
                    return;
                }
                currentPageId = page.id;
                renderPageTabs(); renderSections(); reloadFrame();
            });
            holder.appendChild(button);
        });
    }

    /* ---------- Bölüm listesi ---------- */
    function renderSections(activeSectionId) {
        const holder = document.getElementById('sxeSectionList');
        const page = currentPage();
        holder.innerHTML = '';
        if (!page) return;

        const sections = (page.sections || []).slice().sort((a, b) => a.sort_order - b.sort_order);
        document.getElementById('sxeSectionCount').textContent = sections.length + ' bölüm';

        if (!sections.length) {
            holder.innerHTML = '<div class="sxe-empty"><i class="fas fa-shapes"></i>' +
                '<b>Bu sayfa boş</b><small>Aşağıdaki "Bölüm ekle" ile hero, tur vitrini veya iletişim formu ekleyin.</small></div>';
            return;
        }

        sections.forEach((section) => {
            const definition = MANIFEST[section.section_type] || { name: section.section_type, icon: 'fa-cube', category: '' };
            const card = document.createElement('div');
            card.className = 'sxe-sec' + (section.is_active ? '' : ' off') + (section.id === activeSectionId ? ' on' : '');
            card.dataset.id = section.id;
            card.innerHTML =
                '<i class="fas fa-grip-vertical sxe-sec__drag"></i>' +
                '<span class="sxe-sec__ic"><i class="fas ' + definition.icon + '"></i></span>' +
                '<span class="sxe-sec__b">' +
                    '<span class="sxe-sec__t">' + esc(definition.name) + '</span>' +
                    '<span class="sxe-sec__s">' + esc(section.is_active ? (definition.category || '') : 'gizli') + '</span>' +
                '</span>' +
                '<span class="sxe-sec__a">' +
                    '<button type="button" data-act="toggle" title="' + (section.is_active ? 'Gizle' : 'Göster') + '"><i class="fas ' + (section.is_active ? 'fa-eye' : 'fa-eye-slash') + '"></i></button>' +
                    '<button type="button" data-act="duplicate" title="Kopyala"><i class="fas fa-copy"></i></button>' +
                    '<button type="button" data-act="delete" class="danger" title="Sil"><i class="fas fa-trash"></i></button>' +
                '</span>';

            card.addEventListener('click', (event) => {
                const actionButton = event.target.closest('[data-act]');
                if (actionButton) { handleSectionAction(actionButton.dataset.act, section); return; }
                openSectionDrawer(section);
                frame.contentWindow?.postMessage({ type: 'v-scroll-to-section', id: section.id }, '*');
            });
            holder.appendChild(card);
        });

        if (sectionSortable) sectionSortable.destroy();
        sectionSortable = new Sortable(holder, {
            handle: '.sxe-sec__drag', animation: 150, ghostClass: 'sxe-ghost',
            onEnd: async () => {
                const ids = Array.from(holder.children).map((element) => parseInt(element.dataset.id, 10));
                try {
                    await api('POST', BASE + '/sections/reorder', { page_id: currentPageId, ids });
                    ids.forEach((id, order) => {
                        const section = currentPage().sections.find((item) => item.id === id);
                        if (section) section.sort_order = order;
                    });
                    reloadFrame();
                } catch (error) { fail(error); }
            },
        });
    }

    async function handleSectionAction(action, section) {
        const page = currentPage();
        try {
            if (action === 'toggle') {
                const data = await api('PUT', BASE + '/sections/' + section.id, { is_active: !section.is_active });
                Object.assign(section, data.section);
                renderSections(); reloadFrame(section.id);
            } else if (action === 'duplicate') {
                const data = await api('POST', BASE + '/sections/' + section.id + '/duplicate');
                page.sections.push(data.section);
                page.sections.forEach((item) => {
                    if (item.id !== data.section.id && item.sort_order > section.sort_order) item.sort_order++;
                });
                renderSections(data.section.id); reloadFrame(data.section.id);
                appToast({ icon: 'success', title: 'Bölüm kopyalandı.' });
            } else if (action === 'delete') {
                const ok = await appConfirm({ title: 'Bölüm silinsin mi?', text: 'Bu işlem geri alınamaz.', confirmButtonText: 'Sil' });
                if (!ok) return;
                await api('DELETE', BASE + '/sections/' + section.id);
                page.sections = page.sections.filter((item) => item.id !== section.id);
                renderSections(); reloadFrame();
                appToast({ icon: 'success', title: 'Bölüm silindi.' });
            }
        } catch (error) { fail(error); }
    }

    /* ---------- Bölüm kütüphanesi: liste + canlı örnek ---------- */
    const SECTION_PREVIEW = '{{ url('agency/site/preview/sections') }}';
    let libType = null;

    function renderAddList(query) {
        const list = document.getElementById('sxeAddList');
        const term = (query || '').toLocaleLowerCase('tr');
        const groups = {};

        Object.entries(MANIFEST).forEach(([type, definition]) => {
            const haystack = (definition.name + ' ' + (definition.description || '')).toLocaleLowerCase('tr');
            if (term && !haystack.includes(term)) return;
            (groups[definition.category || 'Diğer'] ||= []).push([type, definition]);
        });

        list.innerHTML = '';
        const entries = Object.entries(groups);

        if (!entries.length) {
            list.innerHTML = '<div class="sxe-empty"><i class="fas fa-magnifying-glass"></i><b>Sonuç yok</b>' +
                '<small>Aramanızla eşleşen bölüm bulunamadı.</small></div>';
            return;
        }

        entries.forEach(([category, items]) => {
            const heading = document.createElement('div');
            heading.className = 'sxe-catrow';
            heading.innerHTML = '<b>' + esc(category) + '</b><hr>';
            list.appendChild(heading);

            items.forEach(([type, definition]) => {
                const row = document.createElement('button');
                row.type = 'button';
                row.className = 'sxe-lib__row' + (type === libType ? ' on' : '');
                row.dataset.type = type;
                row.innerHTML = '<i class="ic fas ' + definition.icon + '"></i><b>' + esc(definition.name) + '</b>';
                row.addEventListener('click', () => showLibrarySample(type));
                row.addEventListener('dblclick', () => addSection(type));
                list.appendChild(row);
            });
        });

        // Arama sonrası seçili bölüm listeden düştüyse ilk sonucu göster
        if (!list.querySelector('.sxe-lib__row.on')) {
            const first = list.querySelector('.sxe-lib__row');
            if (first) showLibrarySample(first.dataset.type);
        }
    }

    function showLibrarySample(type) {
        const definition = MANIFEST[type];
        if (!definition) return;
        libType = type;

        document.querySelectorAll('.sxe-lib__row').forEach((row) => row.classList.toggle('on', row.dataset.type === type));
        document.getElementById('sxeLibName').textContent = definition.name;
        document.getElementById('sxeLibDesc').textContent = definition.description || '';
        document.getElementById('sxeLibAdd').classList.remove('is-off');
        document.getElementById('sxeLibSource').innerHTML = window.sxSourceHtml(type);
        document.getElementById('sxeLibIframe').src = SECTION_PREVIEW + '/' + encodeURIComponent(type);
    }

    async function addSection(type) {
        try {
            const data = await api('POST', BASE + '/sections', { page_id: currentPageId, section_type: type });
            currentPage().sections.push(data.section);
            addModal.hide();
            renderSections(data.section.id);
            reloadFrame(data.section.id);
            openSectionDrawer(data.section);
        } catch (error) { fail(error); }
    }

    document.getElementById('sxeAddSection').addEventListener('click', () => {
        document.getElementById('sxeAddSearch').value = '';
        libType = null;
        renderAddList('');
        addModal.show();
    });
    document.getElementById('sxeAddSearch').addEventListener('input', (event) => renderAddList(event.target.value));
    document.getElementById('sxeLibAdd').addEventListener('click', () => { if (libType) addSection(libType); });

    document.querySelectorAll('[data-lib-device]').forEach((button) => {
        button.addEventListener('click', () => {
            document.querySelectorAll('[data-lib-device]').forEach((other) => other.classList.remove('on'));
            button.classList.add('on');
            document.getElementById('sxeLibFrame').style.width = button.dataset.libDevice === 'mobile' ? '400px' : '100%';
        });
    });

    // Kip kapanınca önizleme boşaltılır: arkada çalışan bir iframe kalmasın
    document.getElementById('sxeAddModal').addEventListener('hidden.bs.modal', () => {
        document.getElementById('sxeLibIframe').src = 'about:blank';
    });

    /* ---------- Form üretimi (şemadan) ---------- */
    function fieldValue(section, field) {
        const bucket = (field.target === 'settings') ? (section.settings || {}) : (section.data || {});
        return bucket[field.key] ?? field.default ?? '';
    }

    function renderField(field, value) {
        const id = 'sxf_' + field.key.replace(/\./g, '_');
        let html = '<div class="sxe-fld" data-field-key="' + esc(field.key) + '" data-field-target="' + esc(field.target || 'data') + '" data-field-type="' + esc(field.type) + '">';
        if (field.type !== 'toggle') html += '<label for="' + id + '">' + esc(field.label) + '</label>';

        if (field.type === 'text') {
            html += '<input type="text" id="' + id + '" value="' + esc(value) + '">';
        } else if (field.type === 'number') {
            html += '<input type="number" id="' + id + '" value="' + esc(value) + '"' +
                (field.min !== undefined ? ' min="' + field.min + '"' : '') +
                (field.max !== undefined ? ' max="' + field.max + '"' : '') + '>';
        } else if (field.type === 'textarea') {
            html += '<textarea id="' + id + '" class="' + (field.code ? 'code' : '') + '" rows="' + (field.rows || 3) + '">' + esc(value) + '</textarea>';
        } else if (field.type === 'select') {
            html += '<select id="' + id + '">';
            Object.entries(field.options || {}).forEach(([key, label]) => {
                html += '<option value="' + esc(key) + '"' + (String(value) === String(key) ? ' selected' : '') + '>' + esc(label) + '</option>';
            });
            html += '</select>';
        } else if (field.type === 'toggle') {
            html += '<label class="sx-switch"><input type="checkbox" id="' + id + '"' + (value ? ' checked' : '') + '>' +
                '<span class="sx-switch__t"></span><span class="sx-switch__l">' + esc(field.label) + '</span></label>';
        } else if (field.type === 'disk_folder') {
            html += '<select id="' + id + '"><option value="">Klasör seçin…</option>';
            DISK_FOLDERS.forEach((folder) => {
                html += '<option value="' + folder.id + '"' + (String(value) === String(folder.id) ? ' selected' : '') + '>' + esc(folder.name) + '</option>';
            });
            html += '</select>';
        } else if (field.type === 'image') {
            html += '<div class="sxe-img">' + (value ? '<img src="' + STORAGE + '/' + esc(value) + '" alt="">' : '<span>Görsel seçilmedi</span>') + '</div>' +
                '<input type="hidden" class="sxe-img-path" value="' + esc(value) + '">' +
                '<input type="file" class="sxe-img-file" accept="image/*">';
        } else if (field.type === 'repeater') {
            html += '<div class="sxe-rep" data-scalar="' + (field.scalar ? '1' : '0') + '">';
            (Array.isArray(value) ? value : []).forEach((item) => { html += renderRepeaterItem(field, item); });
            html += '</div><button type="button" class="sx-btn sx-btn--dash sx-btn--sm sx-btn--block sxe-rep-add">' +
                '<i class="fas fa-plus"></i> Satır ekle</button>';
        }
        return html + '</div>';
    }

    function renderRepeaterItem(field, item) {
        let html = '<div class="sxe-rep__i"><button type="button" class="rm"><i class="fas fa-xmark"></i></button>';
        (field.item_fields || []).forEach((sub) => {
            const value = field.scalar ? item : ((item || {})[sub.key] ?? '');
            html += '<div><label>' + esc(sub.label) + '</label>';
            html += sub.type === 'textarea'
                ? '<textarea data-sub-key="' + esc(sub.key) + '" rows="2">' + esc(value) + '</textarea>'
                : '<input type="' + (sub.type === 'number' ? 'number' : 'text') + '" data-sub-key="' + esc(sub.key) + '" value="' + esc(value) + '">';
            html += '</div>';
        });
        return html + '</div>';
    }

    function collectFields(container) {
        const data = {}; const settings = {};
        container.querySelectorAll(':scope .sxe-fld').forEach((fieldElement) => {
            const key = fieldElement.dataset.fieldKey;
            const target = fieldElement.dataset.fieldTarget === 'settings' ? settings : data;
            const type = fieldElement.dataset.fieldType;
            let value;

            if (type === 'toggle') {
                value = fieldElement.querySelector('input[type="checkbox"]').checked;
            } else if (type === 'image') {
                value = fieldElement.querySelector('.sxe-img-path').value || null;
            } else if (type === 'repeater') {
                const scalar = fieldElement.querySelector('.sxe-rep').dataset.scalar === '1';
                value = Array.from(fieldElement.querySelectorAll('.sxe-rep__i')).map((item) => {
                    if (scalar) return item.querySelector('[data-sub-key]').value;
                    const object = {};
                    item.querySelectorAll('[data-sub-key]').forEach((input) => { object[input.dataset.subKey] = input.value; });
                    return object;
                }).filter((item) => scalar ? String(item).trim() !== '' : Object.values(item).some((x) => String(x).trim() !== ''));
            } else {
                value = fieldElement.querySelector('input, textarea, select').value;
                if (type === 'number' && value !== '') value = parseFloat(value);
            }

            // Nokta notasyonu (seo_defaults.meta_description) → iç içe nesne
            const parts = key.split('.');
            let cursor = target;
            parts.forEach((part, index) => {
                if (index === parts.length - 1) { cursor[part] = value; }
                else { cursor[part] = cursor[part] || {}; cursor = cursor[part]; }
            });
        });
        return { data, settings };
    }

    /* ---------- Çekmeceler ---------- */
    function setDrawerTitle(icon, text, badge) {
        document.getElementById('sxeDrawerTitle').innerHTML =
            '<i class="fas ' + icon + '" style="color:var(--sx-acc)"></i> ' + esc(text) +
            (badge ? ' <span class="sx-tag">' + esc(badge) + '</span>' : '');
    }

    function openSectionDrawer(section) {
        const definition = MANIFEST[section.section_type] || { name: section.section_type, fields: [] };
        drawerContext = { kind: 'section', section };
        setDrawerTitle(definition.icon || 'fa-cube', definition.name, definition.category);

        const body = document.getElementById('sxeDrawerBody');
        body.innerHTML = (definition.fields && definition.fields.length)
            ? definition.fields.map((field) => renderField(field, fieldValue(section, field))).join('')
            : '<div class="sxe-empty"><i class="fas fa-wand-magic-sparkles"></i><b>Ayar gerekmiyor</b>' +
              '<small>Bu bölümün içeriği CRM verilerinizden otomatik oluşur.</small></div>';

        bindDynamicInputs(body, definition.fields || [], section);
        renderSections(section.id);
        drawer.show();
    }

    function openPageDrawer(page) {
        drawerContext = { kind: 'page', page };
        setDrawerTitle('fa-file-lines', page.title);

        const meta = page.meta || {};
        const isProtected = ['home', 'contact'].includes(page.type);

        document.getElementById('sxeDrawerBody').innerHTML =
            '<div class="sxe-fld"><label>Sayfa başlığı</label><input type="text" id="pf_title" value="' + esc(page.title) + '"></div>' +
            '<div class="sxe-fld"><label>Menü etiketi</label><input type="text" id="pf_nav_label" value="' + esc(page.nav_label || '') + '"></div>' +
            (page.type === 'custom'
                ? '<div class="sxe-fld"><label>Adres</label><div class="sx-affix"><span class="sx-affix__tag sx-affix__tag--pre">/p/</span>' +
                  '<input type="text" id="pf_slug" value="' + esc(page.slug || '') + '"></div></div>'
                : '') +
            '<div class="sxe-fld"><label class="sx-switch"><input type="checkbox" id="pf_show_in_nav"' + (page.show_in_nav ? ' checked' : '') + '>' +
                '<span class="sx-switch__t"></span><span class="sx-switch__l">Menüde görünsün</span></label></div>' +
            (!isProtected
                ? '<div class="sxe-fld"><label class="sx-switch"><input type="checkbox" id="pf_is_active"' + (page.is_active ? ' checked' : '') + '>' +
                  '<span class="sx-switch__t"></span><span class="sx-switch__l">Sayfa aktif</span></label></div>'
                : '') +
            '<div class="sxe-catrow"><b>Arama Motoru</b><hr></div>' +
            '<div class="sxe-fld"><label>Meta başlık</label><input type="text" id="pf_meta_title" maxlength="70" value="' + esc(meta.meta_title || '') + '"></div>' +
            '<div class="sxe-fld"><label>Meta açıklama</label><textarea id="pf_meta_description" rows="3" maxlength="170">' + esc(meta.meta_description || '') + '</textarea></div>';

        drawer.show();
    }

    function openSiteDrawer(which) {
        const map = {
            header: { title: 'Üst Menü', icon: 'fa-window-maximize', fields: HEADER_FIELDS, source: SITE.header_config || {} },
            footer: { title: 'Alt Bilgi', icon: 'fa-table-columns', fields: FOOTER_FIELDS, source: SITE.footer_config || {} },
            chat: { title: 'Canlı Destek', icon: 'fa-comment-dots', fields: CHAT_FIELDS, source: SITE.chat_config || {} },
            advanced: {
                title: 'SEO & Gelişmiş', icon: 'fa-code', fields: ADVANCED_FIELDS,
                source: {
                    seo_defaults: SITE.seo_defaults || {},
                    head_scripts: SITE.head_scripts, body_scripts: SITE.body_scripts,
                    custom_css: SITE.custom_css, custom_js: SITE.custom_js,
                },
            },
        };
        const config = map[which];
        drawerContext = { kind: 'site', which };
        setDrawerTitle(config.icon, config.title);

        const body = document.getElementById('sxeDrawerBody');
        body.innerHTML = config.fields.map((field) => {
            const value = field.key.split('.').reduce((accumulator, key) => (accumulator || {})[key], config.source) ?? field.default ?? '';
            return renderField(field, value);
        }).join('');

        bindDynamicInputs(body, config.fields, null);
        drawer.show();
    }

    function bindDynamicInputs(body, fields, section) {
        body.querySelectorAll('.sxe-rep-add').forEach((button) => {
            button.addEventListener('click', () => {
                const fieldElement = button.closest('.sxe-fld');
                const field = fields.find((item) => item.key === fieldElement.dataset.fieldKey);
                const wrapper = document.createElement('div');
                wrapper.innerHTML = renderRepeaterItem(field, field.scalar ? '' : {});
                fieldElement.querySelector('.sxe-rep').appendChild(wrapper.firstChild);
            });
        });

        body.addEventListener('click', (event) => {
            const remove = event.target.closest('.sxe-rep__i .rm');
            if (remove) remove.closest('.sxe-rep__i').remove();
        });

        body.querySelectorAll('.sxe-img-file').forEach((input) => {
            input.addEventListener('change', async () => {
                if (!input.files[0] || !section) return;
                const formData = new FormData();
                formData.append('image', input.files[0]);
                try {
                    const data = await api('POST', BASE + '/sections/' + section.id + '/image', formData);
                    const fieldElement = input.closest('.sxe-fld');
                    fieldElement.querySelector('.sxe-img-path').value = data.path;
                    fieldElement.querySelector('.sxe-img').innerHTML = '<img src="' + data.url + '" alt="">';
                    appToast({ icon: 'success', title: 'Görsel yüklendi.' });
                } catch (error) { fail(error); }
            });
        });
    }

    /* ---------- Çekmece kaydet ---------- */
    document.getElementById('sxeDrawerSave').addEventListener('click', async (event) => {
        if (!drawerContext) return;
        const button = event.currentTarget;
        const original = button.innerHTML;
        const body = document.getElementById('sxeDrawerBody');
        button.disabled = true;
        button.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Kaydediliyor';

        try {
            if (drawerContext.kind === 'section') {
                const { data, settings } = collectFields(body);
                const result = await api('PUT', BASE + '/sections/' + drawerContext.section.id, { data, settings });
                Object.assign(drawerContext.section, result.section);
                reloadFrame(drawerContext.section.id);
                appToast({ icon: 'success', title: 'Bölüm güncellendi.' });
            } else if (drawerContext.kind === 'page') {
                const page = drawerContext.page;
                const payload = {
                    title: document.getElementById('pf_title').value,
                    nav_label: document.getElementById('pf_nav_label').value,
                    show_in_nav: document.getElementById('pf_show_in_nav').checked,
                    meta_title: document.getElementById('pf_meta_title').value,
                    meta_description: document.getElementById('pf_meta_description').value,
                };
                const slugInput = document.getElementById('pf_slug');
                if (slugInput) payload.slug = slugInput.value;
                const activeInput = document.getElementById('pf_is_active');
                if (activeInput) payload.is_active = activeInput.checked;

                const result = await api('PUT', BASE + '/pages/' + page.id, payload);
                Object.assign(page, result.page);
                renderPageTabs(); renderPageList(); reloadFrame();
                appToast({ icon: 'success', title: 'Sayfa güncellendi.' });
            } else if (drawerContext.kind === 'site') {
                const { data } = collectFields(body);
                let payload;
                if (drawerContext.which === 'header') { payload = { header_config: data }; SITE.header_config = Object.assign(SITE.header_config || {}, data); }
                else if (drawerContext.which === 'footer') { payload = { footer_config: data }; SITE.footer_config = Object.assign(SITE.footer_config || {}, data); }
                else if (drawerContext.which === 'chat') { payload = { chat_config: data }; SITE.chat_config = Object.assign(SITE.chat_config || {}, data); }
                else {
                    payload = {
                        seo_defaults: data.seo_defaults || {},
                        head_scripts: data.head_scripts || null, body_scripts: data.body_scripts || null,
                        custom_css: data.custom_css || null, custom_js: data.custom_js || null,
                    };
                    Object.assign(SITE, payload);
                }
                await api('PUT', BASE + '/settings', payload);
                reloadFrame();
                appToast({ icon: 'success', title: 'Ayarlar kaydedildi.' });
            }
            drawer.hide();
        } catch (error) { fail(error); }

        button.disabled = false;
        button.innerHTML = original;
    });

    /* ---------- Sayfa listesi ---------- */
    function renderPageList() {
        const holder = document.getElementById('sxePageList');
        const typeLabels = { home: 'Ana Sayfa', contact: 'İletişim', tours: 'Tur Listesi', tour_detail: 'Tur Detay', custom: 'Özel' };
        holder.innerHTML = '';

        pages.slice().sort((a, b) => a.nav_order - b.nav_order).forEach((page) => {
            const row = document.createElement('div');
            row.className = 'sxe-page-row';
            row.dataset.id = page.id;
            row.innerHTML =
                '<i class="fas fa-grip-vertical sxe-sec__drag"></i>' +
                '<span class="sxe-page-row__t">' + esc(page.title) + '</span>' +
                (page.is_active ? '' : '<span class="sx-tag sx-tag--warn">Pasif</span>') +
                '<span class="sx-tag">' + esc(typeLabels[page.type] || page.type) + '</span>' +
                (isEditable(page) ? '<button type="button" class="sx-ib" data-act="edit" title="Ayarlar"><i class="fas fa-sliders"></i></button>' : '') +
                (page.type === 'custom' ? '<button type="button" class="sx-ib danger" data-act="delete" title="Sil"><i class="fas fa-trash"></i></button>' : '');

            row.querySelector('[data-act="edit"]')?.addEventListener('click', () => openPageDrawer(page));
            row.querySelector('[data-act="delete"]')?.addEventListener('click', async () => {
                const ok = await appConfirm({ title: 'Sayfa silinsin mi?', text: 'Sayfa ve içindeki tüm bölümler silinir.', confirmButtonText: 'Sil' });
                if (!ok) return;
                try {
                    await api('DELETE', BASE + '/pages/' + page.id);
                    pages = pages.filter((item) => item.id !== page.id);
                    if (currentPageId === page.id) currentPageId = pages.find((item) => item.type === 'home')?.id;
                    renderPageTabs(); renderPageList(); renderSections(); reloadFrame();
                } catch (error) { fail(error); }
            });
            holder.appendChild(row);
        });

        new Sortable(holder, {
            handle: '.sxe-sec__drag', animation: 150, ghostClass: 'sxe-ghost',
            onEnd: async () => {
                const ids = Array.from(holder.children).map((element) => parseInt(element.dataset.id, 10));
                try {
                    await api('POST', BASE + '/pages/reorder', { ids });
                    ids.forEach((id, order) => {
                        const page = pages.find((item) => item.id === id);
                        if (page) page.nav_order = order;
                    });
                    renderPageTabs(); reloadFrame();
                } catch (error) { fail(error); }
            },
        });
    }

    document.getElementById('sxeAddPage').addEventListener('click', async () => {
        try {
            const data = await api('POST', BASE + '/pages', { title: 'Yeni Sayfa' });
            data.page.sections = [];
            pages.push(data.page);
            renderPageTabs(); renderPageList();
            openPageDrawer(data.page);   // başlık ve adres çekmecede düzenlenir
        } catch (error) { fail(error); }
    });

    /* ---------- Ray / cihaz / yayın ---------- */
    document.querySelectorAll('[data-panel]').forEach((button) => {
        button.addEventListener('click', () => {
            document.querySelectorAll('[data-panel]').forEach((other) => other.classList.remove('on'));
            button.classList.add('on');
            document.querySelectorAll('[data-panel-body]').forEach((body) => {
                const visible = body.dataset.panelBody === button.dataset.panel;
                body.hidden = !visible;
                body.style.display = visible ? 'flex' : '';
            });
        });
    });

    document.querySelectorAll('.sxe-dev button').forEach((button) => {
        button.addEventListener('click', () => {
            document.querySelectorAll('.sxe-dev button').forEach((other) => other.classList.remove('on'));
            button.classList.add('on');
            document.getElementById('sxeFrame').className = 'sxe-frame ' + button.dataset.device;
        });
    });

    document.querySelectorAll('[data-site-form]').forEach((button) => {
        button.addEventListener('click', () => openSiteDrawer(button.dataset.siteForm));
    });

    document.getElementById('sxeReload').addEventListener('click', () => reloadFrame());

    document.getElementById('sxePublish').addEventListener('click', async (event) => {
        const button = event.currentTarget;
        const original = button.innerHTML;
        button.disabled = true;
        button.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Yayınlanıyor';
        try {
            const data = await api('POST', BASE + '/publish');
            appToast({ icon: 'success', title: data.message || 'Siteniz yayına alındı.' });
            document.getElementById('sxeLive').innerHTML = '<span class="sxe-live on"><i class="sx-dot"></i> Yayında</span>';
        } catch (error) { fail(error); }
        button.disabled = false;
        button.innerHTML = original;
    });

    /* ---------- Önizlemeden bölüm seçimi ---------- */
    window.addEventListener('message', (event) => {
        const message = event.data || {};
        if (message.type === 'v-section-click') {
            const section = (currentPage().sections || []).find((item) => item.id === message.id);
            if (section) openSectionDrawer(section);
        }
    });

    /* ---------- Başlat ---------- */
    renderPageTabs();
    renderPageList();
    renderSections();
    reloadFrame();
})();
</script>
@endpush
