<?php
// Seçim kartlarındaki küçük çizimler
$svg = fn($inner) => '<svg viewBox="0 0 64 36" class="h-10 w-full" fill="currentColor">' . $inner . '</svg>';
$bar = fn($x, $y, $w, $h = 3, $o = '.35') => '<rect x="' . $x . '" y="' . $y . '" width="' . $w . '" height="' . $h . '" rx="1.5" opacity="' . $o . '"/>';

$layouts = [
    'center'  => ['Logo ortada', $svg($bar(6, 16, 14) . $bar(24, 13, 16, 9, '1') . $bar(46, 16, 12))],
    'left'    => ['Logo solda', $svg($bar(6, 13, 14, 9, '1') . $bar(26, 16, 18) . $bar(50, 16, 8))],
    'stacked' => ['İki satır', $svg($bar(22, 6, 20, 8, '1') . '<rect x="4" y="19" width="56" height="1" opacity=".2"/>' . $bar(14, 25, 36))],
];
$ratios = [];
foreach (['4/5' => [16, 20], '3/4' => [15, 20], '2/3' => [13, 20], '1/1' => [20, 20]] as $ratio => [$w, $h]) {
    $ratios[$ratio] = [str_replace('/', ':', $ratio), $svg('<rect x="' . (32 - $w / 2) . '" y="' . (18 - $h / 2 - 4) . '" width="' . $w . '" height="' . ($h + 8) . '" rx="2"/>')];
}
$radius = [];
foreach (theme_radius_scales() as $key => [$label, $scale]) {
    $radius[$key] = [$label, $svg('<rect x="18" y="6" width="28" height="24" rx="' . round(9 * $scale, 1) . '" fill="none" stroke="currentColor" stroke-width="2.5"/>')];
}
$galleries = [
    'side'   => ['Yanda', $svg($bar(10, 6, 6, 6, '.5') . $bar(10, 14, 6, 6, '.5') . $bar(10, 22, 6, 6, '.5') . $bar(20, 6, 34, 24, '1'))],
    'bottom' => ['Altta', $svg($bar(14, 3, 36, 22, '1') . $bar(14, 28, 7, 5, '.5') . $bar(24, 28, 7, 5, '.5') . $bar(34, 28, 7, 5, '.5'))],
    'grid'   => ['Izgara', $svg($bar(12, 3, 40, 14, '1') . $bar(12, 19, 19, 14, '.6') . $bar(33, 19, 19, 14, '.6'))],
];
$footers = [
    'dark'  => ['Koyu', $svg('<rect x="6" y="6" width="52" height="24" rx="3"/>' . '<rect x="12" y="12" width="14" height="3" rx="1.5" fill="#fff" opacity=".7"/>')],
    'light' => ['Açık', $svg('<rect x="6" y="6" width="52" height="24" rx="3" opacity=".12"/>' . $bar(12, 12, 14, 3, '.6'))],
];
$buttons = [
    'solid'   => ['Dolu', $svg('<rect x="14" y="11" width="36" height="14" rx="4"/>')],
    'outline' => ['Çerçeveli', $svg('<rect x="15" y="12" width="34" height="12" rx="4" fill="none" stroke="currentColor" stroke-width="2.5"/>')],
];

$panels = [
    'kimlik' => ['Site kimliği', 'home', 'Logo, ad, slogan ve sekme simgesi', [
        ['site_store_name', 'Mağaza adı', 'text'],
        ['site_store_tagline', 'Slogan', 'text', [], 'Arama sonuçlarında ve alt bilgide görünür.'],
        ['logo', 'Logo', 'image', [], 'Boş bırakırsanız mağaza adı yazı olarak görünür.'],
        ['logo_height', 'Logo yüksekliği', 'range', [20, 72, 2, 'px']],
        ['logo_light', 'Koyu zemin için logo', 'image', [], 'Koyu alt bilgide kullanılır.'],
        ['favicon', 'Sekme simgesi', 'image'],
    ]],
    'renkler' => ['Renkler', 'photo', 'Hazır paletler ve tüm renkler', [
        ['color_primary', 'Ana renk', 'color', [], 'Butonlar, başlıklar ve vurgular'],
        ['color_accent', 'Vurgu rengi', 'color', [], 'İndirimler, rozetler, sepet sayacı'],
        ['color_bg', 'Arka plan', 'color'],
        ['color_soft', 'Kutu zemini', 'color'],
        ['color_text', 'Metin', 'color'],
    ]],
    'yazi' => ['Yazı tipleri', 'document', 'Başlık ve metin fontları', [
        ['font_heading', 'Başlık fontu', 'font', theme_fonts()],
        ['heading_weight', 'Başlık kalınlığı', 'choice', ['500' => ['Orta', ''], '600' => ['Yarı kalın', ''], '700' => ['Kalın', ''], '800' => ['Çok kalın', '']]],
        ['font_body', 'Metin fontu', 'font', theme_fonts()],
        ['base_size', 'Yazı boyutu', 'range', [14, 18, 1, 'px']],
    ]],
    'duzen' => ['Genel görünüm', 'grid', 'Köşeler, butonlar, genişlik', [
        ['radius', 'Köşe yuvarlaklığı', 'choice', $radius],
        ['button_style', 'Buton stili', 'choice', $buttons],
        ['shadow', 'Gölgeler', 'choice', ['soft' => ['Yumuşak', ''], 'none' => ['Düz', '']]],
        ['container', 'Sayfa genişliği', 'range', [1100, 1800, 50, 'px']],
    ]],
    'header' => ['Üst bölüm', 'menu', 'Header düzeni ve duyuru bandı', [
        ['header_layout', 'Düzen', 'choice', $layouts],
        ['header_sticky', 'Kaydırınca üstte sabit kalsın', 'toggle'],
        ['site_announcement', 'Duyuru bandı yazısı', 'text', [], 'Boşsa ücretsiz kargo bilgisi gösterilir.'],
        ['announce_bg', 'Duyuru bandı zemini', 'color'],
        ['announce_text', 'Duyuru bandı yazı rengi', 'color'],
        ['header_menu_count', 'Otomatik menüde kategori sayısı', 'range', [2, 10, 1, '']],
    ]],
    'urunler' => ['Ürün kartları', 'cube', 'Oran, sütun ve rozetler', [
        ['card_ratio', 'Görsel oranı', 'choice', $ratios],
        ['card_columns', 'Satır başına ürün', 'choice', ['3' => ['3', ''], '4' => ['4', ''], '5' => ['5', '']]],
        ['card_hover_image', 'Üzerine gelince ikinci görsel', 'toggle'],
        ['card_quick_add', 'Hızlı sepete ekle', 'toggle'],
        ['card_rating', 'Puanı göster', 'toggle'],
        ['badge_new_days', '"Yeni" rozeti kaç gün', 'range', [0, 90, 5, ' gün']],
        ['badge_bestseller', '"Çok satan" için en az satış', 'range', [0, 100, 5, '']],
        ['badge_low_stock', '"Son ürünler" stok sınırı', 'range', [0, 20, 1, '']],
    ]],
    'urun' => ['Ürün sayfası', 'bag', 'Galeri ve açıklama düzeni', [
        ['gallery_layout', 'Galeri', 'choice', $galleries],
        ['product_tabs', 'Açıklama ve yorumlar', 'choice', ['tabs' => ['Sekmeli', ''], 'stack' => ['Alt alta', '']]],
        ['related_count', 'Benzer ürün sayısı', 'range', [0, 12, 1, '']],
    ]],
    'footer' => ['Alt bilgi', 'document', 'Footer görünümü', [
        ['footer_style', 'Görünüm', 'choice', $footers],
        ['trust_strip', 'Avantajlar şeridi (kargo, iade...)', 'toggle'],
        ['footer_text', 'Logonun altındaki metin', 'textarea'],
    ]],
];
$site_keys = ['store_name', 'store_tagline', 'announcement'];

// Özelleştiricideki bölüm listesi (AJAX ile yenilenir)
if (get('liste')) {
    echo render('customizer-sections', ['page' => get('liste')]);
    exit;
}

if (is_post()) {
    csrf_check();
    $action = post('action', 'save');

    if ($action === 'discard') {
        sess_forget('theme_draft');
        finish('Kaydedilmemiş değişiklikler silindi.', admin_url('tema'));
    }
    if ($action === 'reset') {
        setting_save(array_combine(array_map(fn($key) => 'theme_' . $key, array_keys(theme_defaults())), array_values(theme_defaults())));
        sess_forget('theme_draft');
        log_action('Temayı varsayılana döndürdü');
        finish('Tema varsayılan ayarlara döndü.', admin_url('tema'));
    }

    $values = array_map(fn($value) => is_string($value) ? trim($value) : '', (array) post('t', []));

    if ($action === 'preview') {
        sess_set('theme_draft', $values + (sess('theme_draft') ?? []));
        reply(true);
    }

    $error = null;
    section_apply_uploads($values, $error);
    theme_save(array_intersect_key($values, theme_defaults()));
    $site = [];
    foreach ($site_keys as $key) {
        if (array_key_exists('site_' . $key, $values)) {
            $site[$key] = $values['site_' . $key];
        }
    }
    if (isset($site['store_name']) && $site['store_name'] === '') {
        unset($site['store_name']);
    }
    setting_save($site);
    sess_forget('theme_draft');
    log_action('Temayı yayınladı');
    finish($error ? 'Yayınlandı, ancak bir görsel yüklenemedi: ' . $error : 'Değişiklikler yayınlandı.', admin_url('tema'));
}

$values = theme_all();
foreach ($site_keys as $key) {
    $values['site_' . $key] = site_setting($key, '');
}
$draft = theme_draft() !== null;
$all_fonts = 'https://fonts.googleapis.com/css2?' . implode('&', array_map(fn($font) => 'family=' . str_replace(' ', '+', $font) . ':wght@500', theme_fonts())) . '&display=swap';
$section_pages = section_pages() + ['contact' => 'İletişim sayfası'];
$open_section = get_int('bolum') ? db_find('sections', get_int('bolum')) : null;
$current_page = $open_section['page'] ?? (array_key_exists(get('sayfa', 'home'), $section_pages) ? get('sayfa', 'home') : 'home');
$page_url = fn($key) => $key === 'contact' ? url('iletisim') : section_page_url($key);
$open_panel = $open_section ? 'bolum' : (in_array(get('panel'), array_merge(array_keys($panels), ['bolumler']), true) ? get('panel') : '');
$radius_scales = array_map(fn($row) => $row[1], theme_radius_scales());
?>
<!doctype html>
<html lang="tr">
<head>
    <?php tailwind_head() ?>
    <link href="<?= e($all_fonts) ?>" rel="stylesheet">
    <title>Özelleştir · <?= e(store_name()) ?></title>
</head>
<body class="flex h-dvh overflow-hidden bg-zinc-100 font-sans text-zinc-900 antialiased">

<form method="post" enctype="multipart/form-data" data-no-pjax data-customizer class="relative flex w-full shrink-0 flex-col border-r border-zinc-200 bg-white sm:w-[380px]">
    <?= csrf_field() ?>

    <div class="flex h-14 shrink-0 items-center gap-2 border-b border-zinc-200 px-3">
        <a href="<?= admin_url() ?>" class="flex size-9 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-100 hover:text-ink" title="Yönetime dön"><?= icon('x', 'size-5', '2') ?></a>
        <div class="min-w-0 flex-1">
            <p class="text-[11px] text-zinc-500">Özelleştiriyorsunuz</p>
            <p class="truncate text-sm font-semibold"><?= e(store_name()) ?></p>
        </div>
        <button data-publish class="btn-primary btn-sm px-4 disabled:opacity-40" <?= $draft ? '' : 'disabled' ?>><?= $draft ? 'Yayınla' : 'Yayınlandı' ?></button>
    </div>

    <div class="relative min-h-0 flex-1 overflow-hidden">
        <div data-panel-root class="absolute inset-0 overflow-y-auto [scrollbar-width:none] transition duration-300 ease-out-soft [&::-webkit-scrollbar]:hidden">
            <?php if ($draft): ?>
                <div class="m-3 flex items-center justify-between gap-2 rounded-xl bg-amber-50 px-3 py-2.5 text-xs text-amber-900">
                    Yayınlanmamış değişiklikler var.
                    <button name="action" value="discard" class="font-semibold underline" formnovalidate>Geri al</button>
                </div>
            <?php endif ?>

            <p class="px-5 pt-5 pb-2 text-[11px] font-semibold tracking-[.14em] text-zinc-400 uppercase">Sayfalar</p>
            <button type="button" data-open-panel="bolumler" class="group flex w-full items-center gap-3 border-y border-zinc-100 bg-zinc-50/60 px-5 py-4 text-left transition hover:bg-zinc-50">
                <span class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink text-white"><?= icon('slides', 'size-[18px]') ?></span>
                <span class="min-w-0 flex-1">
                    <span class="block text-sm font-semibold">Sayfa bölümleri</span>
                    <span class="block truncate text-xs text-zinc-500">Slider, vitrinler, bannerlar, metinler</span>
                </span>
                <?= icon('right', 'size-4 text-zinc-300 transition group-hover:translate-x-0.5 group-hover:text-ink', '2') ?>
            </button>

            <p class="px-5 pt-6 pb-2 text-[11px] font-semibold tracking-[.14em] text-zinc-400 uppercase">Tasarım</p>
            <nav>
                <?php foreach ($panels as $key => [$label, $name, $text]): ?>
                    <button type="button" data-open-panel="<?= $key ?>" class="group flex w-full items-center gap-3 border-b border-zinc-100 px-5 py-3.5 text-left transition hover:bg-zinc-50">
                        <span class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-zinc-100 text-zinc-500 transition group-hover:bg-ink group-hover:text-white"><?= icon($name, 'size-[18px]') ?></span>
                        <span class="min-w-0 flex-1">
                            <span class="block text-sm font-semibold"><?= $label ?></span>
                            <span class="block truncate text-xs text-zinc-500"><?= $text ?></span>
                        </span>
                        <?= icon('right', 'size-4 text-zinc-300 transition group-hover:translate-x-0.5 group-hover:text-ink', '2') ?>
                    </button>
                <?php endforeach ?>
            </nav>

            <p class="px-5 pt-6 pb-2 text-[11px] font-semibold tracking-[.14em] text-zinc-400 uppercase">Diğer</p>
            <?php foreach ([['menuler', 'Menüler', 'menu', 'Üst menü ve alt bilgi sütunları'], ['ayarlar?sekme=popup', 'Popup ve çerez bandı', 'chat', 'Kampanya penceresi']] as [$link, $label, $name, $text]): ?>
                <a href="<?= admin_url($link) ?>" class="group flex items-center gap-3 border-b border-zinc-100 px-5 py-3.5 transition hover:bg-zinc-50">
                    <span class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-zinc-100 text-zinc-500"><?= icon($name, 'size-[18px]') ?></span>
                    <span class="min-w-0 flex-1"><span class="block text-sm font-semibold"><?= $label ?></span><span class="block truncate text-xs text-zinc-500"><?= $text ?></span></span>
                    <?= icon('external', 'size-4 text-zinc-300') ?>
                </a>
            <?php endforeach ?>

            <div class="p-5">
                <button name="action" value="reset" data-confirm="Tüm tema ayarları varsayılana dönsün mü?" class="text-xs font-medium text-zinc-500 underline underline-offset-4 hover:text-rose-600" formnovalidate>Temayı varsayılana döndür</button>
            </div>
        </div>

        <?php foreach ($panels as $key => [$label, $name, $text, $fields]): ?>
            <div data-panel="<?= $key ?>" class="invisible absolute inset-0 flex translate-x-full flex-col bg-white transition duration-300 ease-out-soft data-open:visible data-open:translate-x-0">
                <div class="flex shrink-0 items-center gap-2 border-b border-zinc-100 px-3 py-3">
                    <button type="button" data-close-panel class="flex size-9 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-100 hover:text-ink" title="Geri"><?= icon('left', 'size-5', '2') ?></button>
                    <div>
                        <p class="text-[11px] text-zinc-500">Özelleştiriyorsunuz ›</p>
                        <p class="text-sm font-semibold"><?= $label ?></p>
                    </div>
                </div>
                <div class="flex-1 space-y-5 overflow-y-auto [scrollbar-width:none] p-5 [&::-webkit-scrollbar]:hidden">
                    <?php if ($key === 'renkler'): ?>
                        <div>
                            <p class="label">Hazır paletler</p>
                            <div class="grid grid-cols-3 gap-2">
                                <?php foreach (theme_palettes() as $palette_name => $palette): ?>
                                    <button type="button" data-palette='<?= e(json_encode($palette)) ?>' class="group rounded-xl border border-zinc-200 p-1.5 text-left transition hover:border-ink">
                                        <span class="flex h-7 overflow-hidden rounded-lg">
                                            <span class="flex-1" style="background: <?= $palette['color_primary'] ?>"></span>
                                            <span class="flex-1" style="background: <?= $palette['color_accent'] ?>"></span>
                                            <span class="flex-1" style="background: <?= $palette['color_soft'] ?>"></span>
                                        </span>
                                        <span class="mt-1 block text-[11px] font-medium text-zinc-600"><?= e($palette_name) ?></span>
                                    </button>
                                <?php endforeach ?>
                            </div>
                        </div>
                    <?php endif ?>
                    <?php foreach ($fields as $field): ?>
                        <?php admin_field($field, $values[$field[0]] ?? '', 't[' . $field[0] . ']', $field[0]) ?>
                    <?php endforeach ?>
                </div>
            </div>
        <?php endforeach ?>

        <div data-panel="bolumler" class="invisible absolute inset-0 flex translate-x-full flex-col bg-white transition duration-300 ease-out-soft data-open:visible data-open:translate-x-0">
            <div class="flex shrink-0 items-center gap-2 border-b border-zinc-100 px-3 py-3">
                <button type="button" data-close-panel class="flex size-9 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-100 hover:text-ink" title="Geri"><?= icon('left', 'size-5', '2') ?></button>
                <div>
                    <p class="text-[11px] text-zinc-500">Özelleştiriyorsunuz ›</p>
                    <p class="text-sm font-semibold">Sayfa bölümleri</p>
                </div>
            </div>
            <div class="flex-1 space-y-4 overflow-y-auto [scrollbar-width:none] p-4 [&::-webkit-scrollbar]:hidden">
                <select data-section-page class="input py-2.5">
                    <?php foreach ($section_pages as $key => $label): ?>
                        <option value="<?= e($key) ?>" data-url="<?= e($page_url($key)) ?>" <?= $current_page === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                    <?php endforeach ?>
                </select>
                <p class="text-xs text-zinc-500">Sürükleyerek sıralayın, düzenlemek için tıklayın ya da önizlemede bir bölümün üzerine gelip kaleme basın.</p>
                <div data-section-list><?= render('customizer-sections', ['page' => $current_page]) ?></div>
                <button type="button" data-toggle="#section-types" class="btn-light w-full"><?= icon('plus', 'size-4', '2') ?>Bölüm ekle</button>
                <div id="section-types" class="hidden grid grid-cols-2 gap-2">
                    <?php foreach (section_types() as $type => $info): ?>
                        <button type="button" data-add-section="<?= e($type) ?>" class="group flex flex-col items-start gap-2 rounded-xl border border-zinc-200 p-3 text-left transition hover:border-ink">
                            <span class="flex size-8 items-center justify-center rounded-lg bg-zinc-100 text-zinc-600 transition group-hover:bg-ink group-hover:text-white"><?= icon($info['icon'], 'size-4') ?></span>
                            <span class="text-xs font-semibold"><?= e($info['label']) ?></span>
                        </button>
                    <?php endforeach ?>
                </div>
            </div>
        </div>

        <div data-panel="bolum" class="invisible absolute inset-0 flex translate-x-full flex-col bg-white transition duration-300 ease-out-soft data-open:visible data-open:translate-x-0">
            <div class="flex shrink-0 items-center gap-2 border-b border-zinc-100 px-3 py-3">
                <button type="button" data-back-to="bolumler" class="flex size-9 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-100 hover:text-ink" title="Geri"><?= icon('left', 'size-5', '2') ?></button>
                <div class="min-w-0">
                    <p class="text-[11px] text-zinc-500">Sayfa bölümleri ›</p>
                    <p data-section-heading class="truncate text-sm font-semibold"><?= e($open_section ? section_type($open_section['type'])['label'] : 'Bölüm') ?></p>
                </div>
            </div>
            <iframe data-section-frame class="min-h-0 w-full flex-1" title="Bölüm düzenleyici" <?= $open_section ? 'src="' . e(admin_url('bolum?id=' . $open_section['id'] . '&embed=1')) . '"' : '' ?>></iframe>
        </div>
    </div>

    <div class="flex shrink-0 items-center justify-between gap-2 border-t border-zinc-200 px-4 py-2.5">
        <span data-save-state class="text-xs text-zinc-400"><?= $draft ? 'Önizlemede' : 'Kaydedildi' ?></span>
        <div class="flex gap-1">
            <?php foreach (['100%' => ['Masaüstü', 'M3 5h18v11H3zM8 20h8M12 16v4'], '768px' => ['Tablet', 'M6 3h12v18H6zM11 18h2'], '390px' => ['Mobil', 'M8 3h8v18H8zM11 18h2']] as $width => [$label, $path]): ?>
                <button type="button" data-device="<?= $width ?>" <?= $width === '100%' ? 'data-active' : '' ?> title="<?= $label ?>" class="flex size-8 items-center justify-center rounded-lg text-zinc-400 transition hover:text-ink data-active:bg-zinc-100 data-active:text-ink">
                    <svg class="size-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.6"><path stroke-linecap="round" stroke-linejoin="round" d="<?= $path ?>"/></svg>
                </button>
            <?php endforeach ?>
        </div>
    </div>
</form>

<main class="hidden min-w-0 flex-1 p-4 sm:block">
    <div data-preview-box class="relative h-full w-full">
        <iframe data-preview-frame src="<?= e($page_url($current_page)) ?>" class="absolute inset-y-0 left-1/2 h-full w-full -translate-x-1/2 rounded-xl bg-white shadow-xl ring-1 ring-zinc-200 transition-opacity duration-200" title="Önizleme"></iframe>
        <div data-preview-loading class="pointer-events-none absolute top-3 left-1/2 z-10 flex -translate-x-1/2 items-center gap-2 rounded-full bg-zinc-900/90 px-3 py-1.5 text-xs font-medium text-white opacity-0 transition">
            <svg class="size-3.5 animate-spin" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="3" opacity=".25"/><path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" stroke-width="3" stroke-linecap="round"/></svg>
            Güncelleniyor
        </div>
    </div>
</main>

<script type="application/json" data-flashes><?= json_encode(flashes(), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) ?></script>
<div id="toasts" class="pointer-events-none fixed inset-x-0 bottom-6 z-[60] flex flex-col items-center gap-2 px-4"></div>
<?php include PARTS . '/admin-script.php' ?>

<script>
(() => {
    const { $, $$, post, toast, buttonLoading } = window.admin;
    const form = $('[data-customizer]');
    const box = $('[data-preview-box]');
    const publish = $('[data-publish]');
    const state = $('[data-save-state]');
    const loading = $('[data-preview-loading]');
    const root = $('[data-panel-root]');
    const sectionFrame = $('[data-section-frame]');
    const pageSelect = $('[data-section-page]');
    const duzenUrl = <?= json_encode(admin_url('duzen')) ?>;
    const temaUrl = <?= json_encode(admin_url('tema')) ?>;
    const sectionUrl = id => <?= json_encode(admin_url('bolum?embed=1&id=')) ?> + id;
    const radiusScales = <?= json_encode($radius_scales) ?>;
    const frame = () => $('[data-preview-frame]');
    const previewDoc = () => { try { return frame().contentDocument; } catch (error) { return null; } };

    JSON.parse($('[data-flashes]')?.textContent || '[]').forEach(item => toast(item.message, item.type !== 'error'));

    // ---------- Paneller ----------
    function openPanel(key) {
        const panel = $(`[data-panel="${key}"]`);
        if (!panel) return;
        $$('[data-panel][data-open]').forEach(item => item !== panel && item.removeAttribute('data-open'));
        panel.toggleAttribute('data-open', true);
        root.classList.add('-translate-x-1/3', 'opacity-0');
    }
    function closePanels() {
        $$('[data-panel][data-open]').forEach(panel => panel.removeAttribute('data-open'));
        root.classList.remove('-translate-x-1/3', 'opacity-0');
    }
    function openSection(id, title) {
        if (title) $('[data-section-heading]').textContent = title;
        const src = sectionUrl(id);
        if (!sectionFrame.src.endsWith(src.replace(location.origin, ''))) sectionFrame.src = src;
        openPanel('bolum');
        scrollToSection(id);
    }
    function scrollToSection(id) {
        previewDoc()?.getElementById('bolum-' + id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    // ---------- Titremesiz önizleme yenileme: yeni çerçeve arkada yüklenir, hazır olunca yer değiştirir ----------
    let pending = null;
    function refresh(sectionId = null) {
        const old = frame();
        let href = old.src;
        let scroll = 0;
        try { href = old.contentWindow.location.href; scroll = old.contentWindow.scrollY; } catch (error) {}
        pending?.remove();
        const next = old.cloneNode(false);
        next.removeAttribute('data-preview-frame');
        next.style.opacity = '0';
        next.src = href;
        loading.classList.remove('opacity-0');
        next.addEventListener('load', () => {
            try {
                const target = sectionId && next.contentDocument.getElementById('bolum-' + sectionId);
                target ? target.scrollIntoView({ block: 'start' }) : next.contentWindow.scrollTo(0, scroll);
            } catch (error) {}
            next.setAttribute('data-preview-frame', '');
            next.style.opacity = '1';
            old.remove();
            pending = null;
            loading.classList.add('opacity-0');
        }, { once: true });
        pending = next;
        old.after(next);
    }
    window.customizerReload = () => refresh();

    // ---------- Anında değişim: sayfa yenilenmeden önizlemeye uygulanır ----------
    const mix = (color, amount, other) => `color-mix(in oklab, ${color} ${amount}%, ${other})`;
    const loadedFonts = new Set();
    const ensureFont = (doc, font) => {
        const key = font + doc.URL;
        if (loadedFonts.has(key)) return;
        loadedFonts.add(key);
        const link = doc.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://fonts.googleapis.com/css2?family=' + font.replaceAll(' ', '+') + ':wght@400;500;600;700;800&display=swap';
        doc.head.append(link);
    };
    const isHex = value => /^#[0-9a-f]{6}$/i.test(value);
    const live = {
        color_primary: (value, doc) => isHex(value) && doc.documentElement.style.setProperty('--color-ink', value),
        color_bg: (value, doc) => isHex(value) && doc.documentElement.style.setProperty('--color-page', value),
        color_soft: (value, doc) => isHex(value) && doc.documentElement.style.setProperty('--color-soft', value),
        color_text: (value, doc) => isHex(value) && doc.documentElement.style.setProperty('--color-body', value),
        color_accent: (value, doc) => {
            if (!isHex(value)) return false;
            const style = doc.documentElement.style;
            style.setProperty('--color-accent-50', mix(value, 8, 'white'));
            style.setProperty('--color-accent-100', mix(value, 16, 'white'));
            style.setProperty('--color-accent-500', mix(value, 85, 'white'));
            style.setProperty('--color-accent-600', value);
            style.setProperty('--color-accent-700', mix(value, 82, 'black'));
            return true;
        },
        font_heading: (value, doc) => { ensureFont(doc, value); doc.documentElement.style.setProperty('--font-display', `"${value}", ui-sans-serif, system-ui, sans-serif`); return true; },
        font_body: (value, doc) => { ensureFont(doc, value); doc.documentElement.style.setProperty('--font-sans', `"${value}", ui-sans-serif, system-ui, sans-serif`); return true; },
        base_size: (value, doc) => { doc.documentElement.style.fontSize = value + 'px'; return true; },
        container: (value, doc) => { doc.documentElement.style.setProperty('--container-site', value + 'px'); return true; },
        radius: (value, doc) => {
            const scale = radiusScales[value];
            if (scale === undefined) return false;
            Object.entries({ md: .375, lg: .5, xl: .75, '2xl': 1, '3xl': 1.5, panel: 1.75 }).forEach(([name, rem]) => doc.documentElement.style.setProperty('--radius-' + name, (rem * scale) + 'rem'));
            return true;
        },
        logo_height: (value, doc) => { doc.querySelectorAll('[data-logo]').forEach(image => { image.style.height = value + 'px'; }); return true; },
        site_store_name: (value, doc) => { doc.querySelectorAll('[data-store-name]').forEach(element => { element.textContent = value; }); return true; },
        site_announcement: (value, doc) => { if (!value) return false; const bar = doc.querySelector('[data-announcement]'); if (bar) bar.textContent = value; return true; },
        announce_bg: (value, doc) => { if (!isHex(value)) return false; doc.querySelectorAll('[data-announcement-bar]').forEach(bar => { bar.style.backgroundColor = value; }); return true; },
        announce_text: (value, doc) => { if (!isHex(value)) return false; doc.querySelectorAll('[data-announcement-bar]').forEach(bar => { bar.style.color = value; }); return true; },
        header_sticky: (value, doc) => { const header = doc.querySelector('header[data-customize]'); if (!header) return false; header.classList.toggle('sticky', value === '1'); header.classList.toggle('top-0', value === '1'); header.classList.toggle('relative', value !== '1'); return true; },
    };
    const fieldKey = input => (input.name.match(/^t\[(.+)\]$/) || [])[1];
    const valueOf = key => {
        const checked = form.querySelector(`[name="t[${key}]"]:checked`);
        if (checked) return checked.value;
        const inputs = form.querySelectorAll(`[name="t[${key}]"]`);
        return inputs.length ? inputs[inputs.length - 1].value : '';
    };
    const applyLive = key => {
        const doc = previewDoc();
        if (!doc || !live[key]) return false;
        let value = valueOf(key);
        if (form.querySelector(`input[type=checkbox][name="t[${key}]"]`)) value = form.querySelector(`input[type=checkbox][name="t[${key}]"]`).checked ? '1' : '0';
        return live[key](value, doc) !== false;
    };

    // Taslak kaydı: yapısal değişikliklerde önizleme arkada yeniden yüklenir
    let timer;
    let needsReload = false;
    function schedule(reload) {
        needsReload = needsReload || reload;
        publish.disabled = false;
        publish.textContent = 'Yayınla';
        state.textContent = 'Kaydediliyor…';
        clearTimeout(timer);
        timer = setTimeout(async () => {
            const data = new FormData(form);
            data.set('action', 'preview');
            $$('input[type=file]', form).forEach(input => data.delete(input.name));
            await post(temaUrl, data);
            state.textContent = 'Önizlemede';
            if (needsReload) {
                needsReload = false;
                refresh();
            }
        }, reload ? 250 : 500);
    }

    const handleChange = event => {
        const target = event.target;
        if (!target.name || !target.name.startsWith('t[') || target.type === 'file') return;
        const key = fieldKey(target);
        schedule(!applyLive(key));
    };
    form.addEventListener('input', event => {
        if (['radio', 'checkbox'].includes(event.target.type)) return;
        handleChange(event);
    });
    form.addEventListener('change', event => {
        if (!['radio', 'checkbox', 'hidden'].includes(event.target.type) && event.target.tagName !== 'SELECT') return;
        handleChange(event);
    });
    form.addEventListener('change', event => {
        if (event.target.type === 'file' && event.target.files.length) {
            publish.disabled = false;
            publish.textContent = 'Yayınla';
            state.textContent = 'Görsel yayınlayınca yüklenir';
        }
    });

    // ---------- Tıklamalar ----------
    form.addEventListener('click', async event => {
        const opener = event.target.closest('[data-open-panel]');
        if (opener) openPanel(opener.dataset.openPanel);
        if (event.target.closest('[data-close-panel]')) closePanels();
        const back = event.target.closest('[data-back-to]');
        if (back) openPanel(back.dataset.backTo);

        const palette = event.target.closest('[data-palette]');
        if (palette) {
            Object.entries(JSON.parse(palette.dataset.palette)).forEach(([key, value]) => {
                const input = $(`[name="t[${key}]"]`);
                if (!input) return;
                input.value = value;
                const swatch = $(`[data-color-for="${input.id}"]`);
                if (swatch) swatch.value = value;
                applyLive(key);
            });
            schedule(true);
        }

        const edit = event.target.closest('[data-edit-section]');
        if (edit) openSection(edit.dataset.editSection, edit.dataset.sectionTitle);

        const add = event.target.closest('[data-add-section]');
        if (add) {
            const restore = buttonLoading(add);
            const json = await post(duzenUrl, { action: 'add', type: add.dataset.addSection, page: pageSelect.value });
            restore();
            const id = (json.redirect || '').match(/id=(\d+)/)?.[1];
            $('#section-types').classList.add('hidden');
            await refreshList();
            refresh(id);
            if (id) openSection(id, add.textContent.trim());
        }

        const action = event.target.closest('[data-section-action]');
        if (action) {
            if (action.dataset.sectionAction === 'delete' && !confirm('Bu bölüm silinsin mi?')) return;
            buttonLoading(action);
            await post(duzenUrl, { action: action.dataset.sectionAction, id: action.dataset.id });
            toast(action.dataset.sectionAction === 'delete' ? 'Bölüm silindi.' : 'Bölüm kopyalandı.');
            await refreshList();
            refresh();
        }
    });

    // Bölüm listesi ve sayfa seçimi
    async function refreshList() {
        const response = await fetch(temaUrl + '?liste=' + encodeURIComponent(pageSelect.value), { headers: { 'X-Requested-With': 'pjax' } });
        $('[data-section-list]').innerHTML = await response.text();
    }
    pageSelect.addEventListener('change', () => {
        refreshList();
        frame().src = pageSelect.selectedOptions[0].dataset.url;
    });

    // Önizlemedeki "düzenle" butonları ve gömülü bölüm editörünün kayıt bildirimi
    window.addEventListener('message', event => {
        if (event.origin !== location.origin || !event.data) return;
        const data = event.data;
        if (data.type === 'customize') {
            if (data.section) {
                const item = $(`[data-edit-section="${data.section}"]`);
                openSection(data.section, item?.dataset.sectionTitle);
            } else if (data.panel) {
                openPanel(data.panel);
            }
        }
        if (data.type === 'customize-saved') {
            refresh(data.section);
            refreshList();
        }
        // Bölüm editöründe yazarken: önizlemedeki bölüm yerinde değiştirilir (sayfa yenilenmez)
        if (data.type === 'section-preview') {
            const doc = previewDoc();
            const current = doc?.getElementById('bolum-' + data.id);
            if (!current || !data.html) return;
            const holder = doc.createElement('div');
            holder.innerHTML = data.html.trim();
            const next = holder.firstElementChild;
            if (!next) return;
            current.replaceWith(next);
            const box = next.getBoundingClientRect();
            if (box.bottom < 0 || box.top > doc.defaultView.innerHeight) next.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    });

    // Yayınla / geri al butonlarında dönen ikon
    form.addEventListener('submit', event => {
        if (!event.submitter) return;
        if (event.submitter.name) form.insertAdjacentHTML('beforeend', `<input type="hidden" name="${event.submitter.name}" value="${event.submitter.value}">`);
        buttonLoading(event.submitter);
    });

    // Adresten gelen panel / bölüm
    <?php if ($open_section): ?>
        openPanel('bolum');
        frame().addEventListener('load', () => scrollToSection(<?= (int) $open_section['id'] ?>), { once: true });
    <?php elseif ($open_panel): ?>
        openPanel(<?= json_encode($open_panel) ?>);
    <?php endif ?>
})();
</script>
</body>
</html>
