<?php
use App\Models\Settings;
use App\Services\TranslationService;
use App\Services\CurrencyService;

$storeName = Settings::get('store_name', 'Everest Büro Makinaları');
$currentLang = TranslationService::getCurrentLang();
$currentCurrency = CurrencyService::getCurrentCurrency();
$cart = (new \App\Core\Session())->getCart();
$cartCount = array_sum($cart);

if (!isset($categories)) {
    $categories = \App\Models\Category::all(['parent_slug' => null]);
}
?>
<?php
$theme = isset($_COOKIE['ev-theme']) ? $_COOKIE['ev-theme'] : 'light';
?>
<html lang="<?php echo $currentLang; ?>" class="<?php echo $theme === 'light' ? 'light-theme' : ''; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(isset($title) ? $title : $storeName); ?></title>

    <meta name="description" content="<?php echo htmlspecialchars(Settings::get('store_description', '')); ?>">
    <meta name="keywords" content="<?php echo htmlspecialchars(Settings::get('store_keywords', '')); ?>">
    <link rel="canonical" href="<?php echo $baseUrl . '/' . (isset($_GET['route']) ? $_GET['route'] : ''); ?>">

    <?php 
    $metaTags = Settings::get('meta_tags');
    if (!$metaTags) {
        $metaTags = [];
        if ($gsv = Settings::get('google_site_verification')) $metaTags[] = ['name' => 'google-site-verification', 'content' => $gsv];
        if ($yv = Settings::get('yandex_verification')) $metaTags[] = ['name' => 'yandex-verification', 'content' => $yv];
        if ($bv = Settings::get('bing_verification')) $metaTags[] = ['name' => 'msvalidate.01', 'content' => $bv];
    }
    
    if (is_array($metaTags)) {
        foreach ($metaTags as $meta) {
            if (!empty($meta['name']) && !empty($meta['content'])) {
                if (strpos($meta['content'], '<meta') !== false) {
                    echo $meta['content'] . "\n";
                } else {
                    echo '<meta name="' . htmlspecialchars($meta['name']) . '" content="' . htmlspecialchars($meta['content']) . '">' . "\n";
                }
            }
        }
    }
    ?>

    <link rel="manifest" href="<?php echo $baseUrl; ?>/manifest.json">
    <meta name="theme-color" content="#f97316">
    <link rel="apple-touch-icon" href="<?php echo $baseUrl; ?>/assets/images/logo.png">
    <link rel="icon" type="image/png" href="<?php echo $baseUrl; ?>/assets/images/logo.png">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="<?php echo $baseUrl; ?>/assets/css/style.css?v=20260709">

    <?php if ($headScripts = Settings::get('head_scripts')): ?>
    <?php echo $headScripts; ?>
    <?php endif; ?>

    <!-- Google Translate Widget -->
    <style>
        .goog-te-banner-frame { display: none !important; }
        .goog-te-banner-frame.skiptranslate { display: none !important; }
        .goog-te-banner-frame iframe { display: none !important; }
        .goog-te-spinner-pos { display: none !important; }
        .goog-te-spinner { display: none !important; }
        body { top: 0px !important; }
        .goog-te-gadget { color: transparent !important; font-size: 0 !important; height: 0 !important; overflow: hidden !important; }
        .goog-te-gadget-icon { display: none !important; }
        .goog-te-menu-frame { display: none !important; }
        .goog-te-menu2 { display: none !important; }
        .goog-te-menu-value { display: none !important; }
        iframe.skiptranslate { display: none !important; }
        div.skiptranslate { display: none !important; }
        #google_translate_element { display: none !important; }

        /* Custom dropdown styling */
        .dd-wrap {
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            cursor: pointer;
            border: 1px solid var(--border);
            border-radius: 6px;
            padding: 4px 8px;
            background: var(--surface-2);
            transition: border-color 0.2s;
            min-width: 80px;
        }
        .dd-wrap:hover { border-color: var(--orange); }
        .dd-wrap select {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
            font-size: 13px;
        }
        .dd-label {
            font-size: 13px;
            font-weight: 600;
            color: var(--text-1);
            white-space: nowrap;
            pointer-events: none;
        }
    </style>
    <script>
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({
                pageLanguage: 'tr',
                includedLanguages: 'tr,en,fr,de,ru',
                layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                autoDisplay: false
            }, 'google_translate_element');
            document.body.style.top = '0px';
            document.body.style.position = '';
        }
    </script>
    <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</head>
<body data-base-url="<?php echo $baseUrl; ?>" data-sw-url="<?php echo $baseUrl; ?>/sw.js">
<?php if ($bodyScripts = Settings::get('body_scripts')): ?>
<?php echo $bodyScripts; ?>
<?php endif; ?>

<!-- ───────────────────────────────────────────────────────
     MOBILE DRAWER (hidden off-screen by default)
─────────────────────────────────────────────────────────── -->
<div class="drawer-backdrop" id="drawerBackdrop" onclick="closeDrawer()"></div>
<aside class="mobile-drawer" id="mobileDrawer">
    <div class="drawer-hdr">
        <span>MENÜ</span>
        <button onclick="closeDrawer()"><i class="fa fa-times"></i></button>
    </div>
    <nav class="drawer-body">
        <a href="<?php echo $baseUrl; ?>/" class="drawer-nav-item">
            <span><i class="fa fa-home" style="margin-right:10px;"></i>ANASAYFA</span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <?php $customer = (new \App\Core\Session())->get('customer_user'); ?>
        <?php if ($customer): ?>
        <a href="<?php echo $baseUrl; ?>/profile" class="drawer-nav-item" style="color: var(--orange);">
            <span><i class="fa fa-user" style="margin-right:10px;"></i>PROFİLİM (<?php echo htmlspecialchars(explode(' ', $customer['name'])[0]); ?>)</span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <a href="<?php echo $baseUrl; ?>/logout" class="drawer-nav-item" style="color: #ef4444;">
            <span><i class="fa fa-sign-out" style="margin-right:10px;"></i>ÇIKIŞ YAP</span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <?php else: ?>
        <a href="<?php echo $baseUrl; ?>/login" class="drawer-nav-item" style="color: var(--orange);">
            <span><i class="fa fa-user-circle-o" style="margin-right:10px;"></i>GİRİŞ YAP / KAYDOL</span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <?php endif; ?>
        <?php foreach ($categories as $cat): ?>
        <a href="<?php echo $baseUrl; ?>/<?php echo $cat->slug; ?>" class="drawer-nav-item">
            <span><?php echo htmlspecialchars($cat->name); ?></span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <?php endforeach; ?>
        <?php foreach (\App\Models\Page::all() as $p): ?>
        <a href="<?php echo $baseUrl; ?>/<?php echo htmlspecialchars($p->slug); ?>" class="drawer-nav-item">
            <span><?php echo htmlspecialchars($p->title); ?></span>
            <i class="fa fa-chevron-right"></i>
        </a>
        <?php endforeach; ?>
        <a href="<?php echo $baseUrl; ?>/contact" class="drawer-nav-item">
            <span>İletişim</span>
            <i class="fa fa-chevron-right"></i>
        </a>
    </nav>
</aside>

<!-- ───────────────────────────────────────────────────────
     MOBILE HEADER BAR
─────────────────────────────────────────────────────────── -->
<div class="mobile-header-bar">
    <div class="mob-hdr-row">
        <button onclick="openDrawer()" style="width:40px;height:40px;border-radius:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text-2);display:flex;align-items:center;justify-content:center;font-size:18px;cursor:pointer;">
            <i class="fa fa-bars"></i>
        </button>
        <a href="<?php echo $baseUrl; ?>/" style="display:flex;align-items:center;gap:8px;text-decoration:none;">
            <img class="site-logo-img" src="<?php echo $baseUrl; ?>/assets/images/logo_transparent.png" alt="Everest Büro" style="height:30px;width:auto;display:block;">
        </a>
        <?php if ($customer): ?>
            <div style="position: relative;" class="mob-user-dropdown-wrapper">
                <a href="javascript:void(0)" style="width:40px;height:40px;border-radius:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text-2);display:flex;align-items:center;justify-content:center;font-size:18px;text-decoration:none;">
                    <?php if(!empty($customer['avatar'])): ?>
                        <img src="<?php echo htmlspecialchars($customer['avatar']); ?>" alt="Avatar" referrerpolicy="no-referrer" style="width: 24px; height: 24px; border-radius: 50%;">
                    <?php else: ?>
                        <i class="fa fa-user"></i>
                    <?php endif; ?>
                </a>
                <div class="mob-user-dropdown-menu" style="display: none; position: absolute; top: 100%; right: 0; background: var(--surface-2); border: 1px solid var(--border); box-shadow: var(--shadow-md); border-radius: var(--r-md); min-width: 200px; z-index: 9999; overflow: hidden; margin-top: 8px;">
                    <a href="<?php echo $baseUrl; ?>/profile" style="display: block; padding: 12px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600; border-bottom: 1px solid var(--border);"><i class="fa fa-user" style="margin-right: 8px; width: 16px; text-align: center; color: var(--primary);"></i> Hesap Bilgilerim</a>
                    <a href="<?php echo $baseUrl; ?>/profile/orders" style="display: block; padding: 12px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600; border-bottom: 1px solid var(--border);"><i class="fa fa-shopping-bag" style="margin-right: 8px; width: 16px; text-align: center; color: var(--orange);"></i> Siparişlerim</a>
                    <a href="<?php echo $baseUrl; ?>/cart" style="display: block; padding: 12px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600; border-bottom: 1px solid var(--border);"><i class="fa fa-shopping-cart" style="margin-right: 8px; width: 16px; text-align: center; color: var(--text-2);"></i> Sepetim</a>
                    <?php if(isset($customer['role']) && $customer['role'] === 'admin'): ?>
                    <a href="<?php echo $baseUrl; ?>/admin" style="display: block; padding: 12px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600; border-bottom: 1px solid var(--border);"><i class="fa fa-lock" style="margin-right: 8px; width: 16px; text-align: center; color: var(--text-2);"></i> Admin Paneli</a>
                    <?php endif; ?>
                    <a href="<?php echo $baseUrl; ?>/logout" style="display: block; padding: 12px 15px; color: #ef4444; text-decoration: none; font-size: 14px; font-weight: 600;"><i class="fa fa-sign-out" style="margin-right: 8px; width: 16px; text-align: center;"></i> Çıkış Yap</a>
                </div>
            </div>
            <script>
                document.querySelector('.mob-user-dropdown-wrapper').addEventListener('click', function(e) {
                    const menu = this.querySelector('.mob-user-dropdown-menu');
                    menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
                    e.stopPropagation();
                });
                document.addEventListener('click', function(e) {
                    const dropdown = document.querySelector('.mob-user-dropdown-wrapper');
                    if (dropdown && !e.target.closest('.mob-user-dropdown-wrapper')) {
                        const menu = dropdown.querySelector('.mob-user-dropdown-menu');
                        if (menu) menu.style.display = 'none';
                    }
                });
            </script>
        <?php else: ?>
            <a href="<?php echo $baseUrl; ?>/login" style="width:40px;height:40px;border-radius:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text-2);display:flex;align-items:center;justify-content:center;font-size:18px;text-decoration:none;">
                <i class="fa fa-user-circle-o"></i>
            </a>
        <?php endif; ?>
    </div>
    <div class="mob-hdr-row">
        <form action="<?php echo $baseUrl; ?>/search" method="GET" class="mob-hdr-search" style="flex:1;">
            <input type="text" name="q" value="<?php echo htmlspecialchars(isset($_GET['q']) ? $_GET['q'] : ''); ?>" placeholder="Ürün, marka veya model ara…">
        </form>
    </div>
</div>

<!-- ───────────────────────────────────────────────────────
     DESKTOP TOP UTILITY BAR
─────────────────────────────────────────────────────────── -->
<div class="topbar">
    <div class="topbar-inner">
        <div style="display:flex;align-items:center;gap:16px;">
            <?php $headerTopBar = Settings::get('header_top_bar', ''); if (!empty($headerTopBar)): ?>
                <span style="font-weight: 700; color: var(--orange); margin-right: 10px;"><?php echo htmlspecialchars($headerTopBar); ?></span>
                <span style="color:var(--border);">|</span>
            <?php endif; ?>
            <span><i class="fa fa-phone" style="color:var(--orange);margin-right:5px;"></i><?php echo htmlspecialchars(Settings::get('telephone', '')); ?></span>
            <span><i class="fa fa-envelope" style="color:var(--orange);margin-right:5px;"></i><?php echo htmlspecialchars(Settings::get('email', '')); ?></span>
        </div>
        <div style="display:flex;align-items:center;gap:14px;">
            <div class="dd-wrap">
                <select id="currency-select" onchange="this.parentElement.querySelector('.dd-label').innerHTML = this.options[this.selectedIndex].dataset.icon + ' ' + this.value; window.location='?currency='+this.value">
                    <?php foreach (CurrencyService::getAvailableCurrencies() as $cur):
                        $icons = ['TRY'=>'₺', 'USD'=>'$', 'EUR'=>'€', 'GBP'=>'£', 'RUB'=>'₽'];
                        $icon = isset($icons[$cur]) ? $icons[$cur] : $cur;
                    ?>
                    <option value="<?php echo $cur; ?>" data-icon="<?php echo $icon; ?>" <?php echo $currentCurrency === $cur ? 'selected' : ''; ?>><?php echo $icon; ?> <?php echo $cur; ?></option>
                    <?php endforeach; ?>
                </select>
                <span class="dd-label notranslate" translate="no"><?php
                    $curIcons = ['TRY'=>'₺', 'USD'=>'$', 'EUR'=>'€', 'GBP'=>'£', 'RUB'=>'₽'];
                    echo isset($curIcons[$currentCurrency]) ? $curIcons[$currentCurrency] . ' ' . $currentCurrency : $currentCurrency;
                ?></span>
                <i class="fa fa-chevron-down" style="font-size:9px;color:var(--text-3);"></i>
            </div>
            <div class="dd-wrap">
                <select id="lang-select">
                    <option value="tr" data-flag="🇹🇷">🇹🇷 TR</option>
                    <option value="en" data-flag="🇬🇧">🇬🇧 EN</option>
                    <option value="fr" data-flag="🇫🇷">🇫🇷 FR</option>
                    <option value="de" data-flag="🇩🇪">🇩🇪 DE</option>
                    <option value="ru" data-flag="🇷🇺">🇷🇺 RU</option>
                </select>
                <span class="dd-label notranslate" translate="no">🇹🇷 TR</span>
                <i class="fa fa-chevron-down" style="font-size:9px;color:var(--text-3);"></i>
            </div>
        </div>
    </div>
</div>

<!-- ───────────────────────────────────────────────────────
     DESKTOP MAIN HEADER
─────────────────────────────────────────────────────────── -->
<header class="site-header">
    <div class="header-inner">

        <!-- Logo -->
        <a href="<?php echo $baseUrl; ?>/" class="site-logo">
            <img class="site-logo-img" src="<?php echo $baseUrl; ?>/assets/images/logo_transparent.png" alt="Everest Büro" style="height:44px;width:auto;display:block;"
                 onerror="this.outerHTML='<span style=&quot;font-weight:900;font-size:18px;color:#f97316;&quot;>EVEREST BÜRO</span>'">
        </a>

        <!-- Search -->
        <form action="<?php echo $baseUrl; ?>/search" method="GET" class="header-search">
            <input type="text" name="q" value="<?php echo htmlspecialchars(isset($_GET['q']) ? $_GET['q'] : ''); ?>" placeholder="Ürün, marka veya model ara…" autocomplete="off">
        </form>

        <!-- Actions -->
        <div class="header-actions">
            <button id="theme-toggle" class="hdr-btn" title="Tema Değiştir">
                <i class="fa fa-sun-o" id="theme-icon"></i>
            </button>
            <?php $customer = (new \App\Core\Session())->get('customer_user'); ?>
            <?php if ($customer): ?>
                <div style="position: relative; display: inline-block;" class="user-dropdown-wrapper">
                    <a href="javascript:void(0)" class="hdr-btn" title="Profilim" style="border-radius: 20px; padding: 0 12px; gap: 8px; width: auto;">
                        <?php if(!empty($customer['avatar'])): ?>
                            <img src="<?php echo htmlspecialchars($customer['avatar']); ?>" alt="Avatar" referrerpolicy="no-referrer" style="width: 24px; height: 24px; border-radius: 50%;">
                        <?php else: ?>
                            <i class="fa fa-user-circle-o"></i>
                        <?php endif; ?>
                        <span style="font-size: 13px; font-weight: 600;"><?php echo htmlspecialchars(explode(' ', $customer['name'])[0]); ?></span>
                    </a>
                    <div class="user-dropdown-menu" style="display: none; position: absolute; top: 100%; right: 0; background: var(--surface-2); border: 1px solid var(--border); box-shadow: var(--shadow-md); border-radius: var(--r-md); min-width: 150px; z-index: 100; overflow: hidden; margin-top: 5px;">
                        <a href="<?php echo $baseUrl; ?>/profile" style="display: block; padding: 10px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600;"><i class="fa fa-user" style="margin-right: 8px;"></i> Profilim</a>
                        <?php if(isset($customer['role']) && $customer['role'] === 'admin'): ?>
                        <a href="<?php echo $baseUrl; ?>/admin" style="display: block; padding: 10px 15px; color: var(--text-1); text-decoration: none; font-size: 14px; font-weight: 600;"><i class="fa fa-lock" style="margin-right: 8px;"></i> Admin Paneli</a>
                        <?php endif; ?>
                        <a href="<?php echo $baseUrl; ?>/logout" style="display: block; padding: 10px 15px; color: #ef4444; text-decoration: none; font-size: 14px; font-weight: 600;"><i class="fa fa-sign-out" style="margin-right: 8px;"></i> Çıkış Yap</a>
                    </div>
                </div>
                <script>
                    document.querySelector('.user-dropdown-wrapper').addEventListener('click', function() {
                        const menu = this.querySelector('.user-dropdown-menu');
                        menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
                    });
                    document.addEventListener('click', function(e) {
                        if (!e.target.closest('.user-dropdown-wrapper')) {
                            const menu = document.querySelector('.user-dropdown-menu');
                            if (menu) menu.style.display = 'none';
                        }
                    });
                </script>
            <?php else: ?>
                <a href="<?php echo $baseUrl; ?>/login" class="hdr-btn" title="Giriş Yap / Kaydol" style="border-radius: 20px; padding: 0 16px; width: auto; font-size: 13px; font-weight: 600; gap: 6px;">
                    <i class="fa fa-user-circle-o" style="font-size: 16px;"></i> Giriş Yap
                </a>
            <?php endif; ?>
            <a href="<?php echo $baseUrl; ?>/cart" class="cart-btn">
                <i class="fa fa-shopping-bag"></i>
                <span>Sepet</span>
                <span class="cart-badge"><?php echo $cartCount; ?></span>
            </a>
        </div>

    </div>
</header>

<!-- ───────────────────────────────────────────────────────
     CATEGORY NAV BAR (desktop only)
─────────────────────────────────────────────────────────── -->
<nav class="cat-nav">
    <ul class="cat-nav-list">
        <li>
            <a href="<?php echo $baseUrl; ?>/"
               class="<?php echo (!isset($category) && (isset($_GET['route']) ? $_GET['route'] : '') === '') ? 'active' : ''; ?>">
                <i class="fa fa-home" style="margin-right:5px;"></i>Anasayfa
            </a>
        </li>
        <?php foreach (array_slice($categories, 0, 8) as $cat): ?>
        <li>
            <a href="<?php echo $baseUrl; ?>/<?php echo $cat->slug; ?>"
               class="<?php echo (isset($category) && $category->slug === $cat->slug) ? 'active' : ''; ?>">
                <?php echo htmlspecialchars($cat->name); ?>
            </a>
        </li>
        <?php endforeach; ?>
    </ul>
</nav>

<!-- ───────────────────────────────────────────────────────
     TOAST CONTAINER
─────────────────────────────────────────────────────────── -->
<div id="toast-container"></div>

<script>
/* ── Drawer ── */
function openDrawer() {
    document.getElementById('mobileDrawer').classList.add('open');
    document.getElementById('drawerBackdrop').classList.add('open');
    document.body.style.overflow = 'hidden';
}
function closeDrawer() {
    document.getElementById('mobileDrawer').classList.remove('open');
    document.getElementById('drawerBackdrop').classList.remove('open');
    document.body.style.overflow = '';
}

/* ── Theme toggle (class-based, CSS variables cascade automatically) ── */
(function() {
    var HTML = document.documentElement;

    function applyTheme(isLight) {
        if (isLight) {
            HTML.classList.add('light-theme');
        } else {
            HTML.classList.remove('light-theme');
        }
        var icon = document.getElementById('theme-icon');
        if (icon) icon.className = isLight ? 'fa fa-moon-o' : 'fa fa-sun-o';
    }

    // Restore saved theme before page renders
    var match = document.cookie.match(/ev-theme=(\w+)/);
    var saved = (match && match[1]) || localStorage.getItem('ev-theme') || 'light';
    applyTheme(saved === 'light');

    document.addEventListener('DOMContentLoaded', function() {
        var btn = document.getElementById('theme-toggle');
        if (!btn) return;
        btn.addEventListener('click', function() {
            var isNowLight = !HTML.classList.contains('light-theme');
            applyTheme(isNowLight);
            localStorage.setItem('ev-theme', isNowLight ? 'light' : 'dark');
            document.cookie = "ev-theme=" + (isNowLight ? "light" : "dark") + "; path=/; max-age=31536000";
        });
    });
})();

/* ── Toast ── */
function showToast(message, type) {
    type = type || 'info';
    var icons = { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle' };
    var container = document.getElementById('toast-container');
    var toast = document.createElement('div');
    toast.className = 'toast ' + type;
    toast.innerHTML = '<i class="fa ' + (icons[type] || icons.info) + ' ' + type + '"></i> ' + message;
    container.appendChild(toast);
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(40px)';
        toast.style.transition = 'all .3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}
</script>

<script>
/* ── Google Translate cookie-based language switch ── */
(function() {
    var sel = document.getElementById('lang-select');
    if (!sel) return;

    function setLanguage(lang) {
        if (lang === 'tr') {
            document.cookie = 'googtrans=/tr/tr; path=/;';
        } else {
            document.cookie = 'googtrans=/tr/' + lang + '; path=/;';
        }
        // Also try triggering Google's widget if loaded
        var combo = document.querySelector('.goog-te-combo');
        if (combo) {
            combo.value = lang;
            combo.dispatchEvent(new Event('change', { bubbles: true }));
        }
        location.reload();
    }

    sel.addEventListener('change', function() {
        var label = this.parentElement.querySelector('.dd-label');
        var opt = this.options[this.selectedIndex];
        label.innerHTML = opt.getAttribute('data-flag') + ' ' + opt.value.toUpperCase();
        setLanguage(this.value);
    });

    // Restore selected option and label on page load based on existing cookie
    var match = document.cookie.match(/googtrans=\/tr\/(\w+)/);
    if (match && match[1] && match[1] !== 'tr') {
        sel.value = match[1];
        var label = sel.parentElement.querySelector('.dd-label');
        var opt = sel.options[sel.selectedIndex];
        label.innerHTML = opt.getAttribute('data-flag') + ' ' + opt.value.toUpperCase();
    }

    // Nuke any Google Translate leftover elements
    function cleanGT() {
        document.body.style.top = '0px';
        document.body.style.position = '';
        var els = document.querySelectorAll('.goog-te-banner-frame, .skiptranslate iframe, .goog-te-spinner-pos');
        els.forEach(function(el) { el.style.display = 'none'; el.style.height = '0'; });
    }
    cleanGT();
    setInterval(cleanGT, 500);
})();
</script>

