@php
    $currentLocale = session('store_locale', app()->getLocale() ?: 'ar');
    $isEnglish = $currentLocale === 'en';
    $pageDir = $isEnglish ? 'ltr' : 'rtl';
    $siteSettings = \App\Models\SiteSetting::current();
    $siteName = $isEnglish ? $siteSettings->site_name_en : $siteSettings->site_name_ar;
    $siteLogo = $siteSettings->logo_path ?: 'images/brand/raseednow-logo.png';
    $cartCount = array_sum(session('raseednow_cart', []));
    $isAccountMode = $accountMode ?? false;
    $headerUser = auth()->user();
    $headerWalletBalance = ($headerUser?->wallet?->balance_minor ?? 0) / 100;
    $headerAvatar = mb_strtoupper(mb_substr($headerUser?->display_name ?: $headerUser?->name ?: 'U', 0, 1));
    $headerUnreadCount = $headerUser ? $headerUser->customerNotifications()->whereNull('read_at')->count() : 0;
    $socialLinks = collect([
        'facebook' => ['label' => 'Facebook', 'url' => $siteSettings->facebook_url, 'image' => 'images/social/facebook.png'],
        'instagram' => ['label' => 'Instagram', 'url' => $siteSettings->instagram_url, 'image' => 'images/social/instagram.png'],
        'tiktok' => ['label' => 'TikTok', 'url' => $siteSettings->tiktok_url, 'image' => 'images/social/tiktok.png'],
        'youtube' => ['label' => 'YouTube', 'url' => $siteSettings->youtube_url, 'image' => 'images/social/youtube.png'],
        'whatsapp' => ['label' => 'WhatsApp', 'url' => $siteSettings->whatsapp_url, 'image' => 'images/social/whatsapp.png'],
    ])->filter(fn ($item) => filled($item['url']));
@endphp
<!doctype html>
<html lang="{{ $currentLocale }}" dir="{{ $pageDir }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ $title ?? $siteName }}</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="min-h-screen bg-[#f7f8fb] text-[#111827] antialiased {{ request()->routeIs('login', 'register', 'signup') ? 'rn-auth-body' : '' }} {{ $isAccountMode ? 'rn-account-body' : '' }}">
    @php
        $activeCurrencies = \App\Models\Currency::where('is_active', true)->orderByDesc('is_base')->orderBy('code')->get();
        $currentCurrencyCode = session('store_currency', 'EGP');
        $currentCurrency = $activeCurrencies->firstWhere('code', $currentCurrencyCode) ?? $activeCurrencies->firstWhere('code', 'EGP');
        $currencyFlagClasses = [
            'EGP' => 'kr-flag-eg',
            'USD' => 'kr-flag-us',
            'EUR' => 'kr-flag-eu',
            'SAR' => 'kr-flag-sa',
            'AED' => 'kr-flag-ae',
        ];
        $currencyFlagImages = [
            'EGP' => 'eg.png',
            'USD' => 'us.png',
            'EUR' => 'eu.png',
            'SAR' => 'sa.png',
            'AED' => 'ae.png',
        ];
    @endphp
    <header class="ks-header">
        <div class="ks-topbar">
            <a href="{{ route('home') }}" class="ks-brand" aria-label="{{ $siteName }}">
                <img class="ks-brand-logo" src="{{ asset($siteLogo) }}" alt="{{ $siteName }}">
            </a>

            <button type="button" class="rn-mobile-menu-trigger" data-rn-sidebar-open aria-label="فتح القائمة">
                <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
            </button>

            <nav class="ks-menu">
                <a href="{{ route('home') }}">{{ $isEnglish ? 'Home' : 'الرئيسية' }}</a>
                <a href="{{ route('home') }}" class="kr-all-cats-link">
                    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 4h6v6H4V4Zm10 0h6v6h-6V4ZM4 14h6v6H4v-6Zm10 0h6v6h-6v-6Z" stroke="currentColor" stroke-width="1.8"/></svg>
                    {{ $isEnglish ? 'All categories' : 'كل الفئات' }}
                </a>
            </nav>

            <form action="{{ route('home') }}" class="ks-search">
                <input name="q" value="{{ $query ?? '' }}" placeholder="{{ $isEnglish ? 'Search gift cards, eSIM and top-ups...' : 'ابحث عن بطاقات الهدايا وeSIM والشحن...' }}" aria-label="{{ $isEnglish ? 'Search' : 'بحث' }}">
                <button type="submit" aria-label="{{ $isEnglish ? 'Search' : 'بحث' }}">
                    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m21 21-4.2-4.2M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
                </button>
            </form>

            <nav class="ks-account-nav">
                @auth
                    @if($isAccountMode)
                        <details class="kd-user-menu ks-profile-menu">
                            <summary>
                                <b aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"><path d="M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10Z" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></svg></b>
                            </summary>
                            <div>
                                <a href="{{ route('account.dashboard') }}">حسابي</a>
                                <a href="{{ route('account.profile') }}">الإعدادات</a>
                                <a href="{{ route('account.wallet') }}">المحفظة</a>
                                <a href="{{ route('account.orders') }}">الطلبات</a>
                                <a href="{{ route('account.notifications') }}">الإشعارات</a>
                                <form method="POST" action="{{ route('logout') }}">
                                    @csrf
                                    <button type="submit">تسجيل الخروج</button>
                                </form>
                            </div>
                        </details>
                        <a href="{{ route('account.wallet') }}" class="kd-header-balance">
                            {{ number_format($headerWalletBalance, 2) }} {{ $currentCurrency?->symbol ?? 'ج.م' }}
                            <b>+</b>
                        </a>
                        <a href="{{ route('account.notifications') }}" class="kd-header-icon" aria-label="الإشعارات">
                            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M18 8a6 6 0 1 0-12 0c0 7-3 8-3 8h18s-3-1-3-8ZM10 20h4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
                            @if($headerUnreadCount > 0)
                                <span>{{ $headerUnreadCount }}</span>
                            @endif
                        </a>
                    @else
                        <a href="{{ route('cart.index') }}" class="ks-cart-link" aria-label="{{ $isEnglish ? 'Cart' : 'السلة' }}">
                            <svg class="ks-cart-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                                <path d="M7.3 8.5h12.1l-1.1 6.4a3 3 0 0 1-3 2.5H10a3 3 0 0 1-3-2.6L5.9 5.6H3.8" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>
                                <path d="M9.8 8.4a3.2 3.2 0 0 1 6.4 0" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>
                                <path d="M10.2 20.1h.01M17 20.1h.01" stroke="currentColor" stroke-width="2.8" stroke-linecap="round"/>
                            </svg>
                            <span data-rn-cart-count @hidden($cartCount <= 0)>{{ $cartCount }}</span>
                        </a>
                        <details class="kd-user-menu ks-profile-menu">
                            <summary>
                                <b aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"><path d="M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10Z" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></svg></b>
                            </summary>
                            <div>
                                <a href="{{ auth()->user()->isAdmin() ? route('admin.dashboard') : route('account.dashboard') }}">حسابي</a>
                                <a href="{{ route('account.profile') }}">الإعدادات</a>
                                <a href="{{ route('account.wallet') }}">المحفظة</a>
                                <a href="{{ route('account.orders') }}">الطلبات</a>
                                <a href="{{ route('account.notifications') }}">الإشعارات</a>
                                <form method="POST" action="{{ route('logout') }}">
                                    @csrf
                                    <button type="submit">تسجيل الخروج</button>
                                </form>
                            </div>
                        </details>
                    @endif
                @else
                    <a href="{{ route('cart.index') }}" class="ks-cart-link" aria-label="{{ $isEnglish ? 'Cart' : 'السلة' }}">
                        <svg class="ks-cart-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                            <path d="M7.3 8.5h12.1l-1.1 6.4a3 3 0 0 1-3 2.5H10a3 3 0 0 1-3-2.6L5.9 5.6H3.8" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M9.8 8.4a3.2 3.2 0 0 1 6.4 0" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>
                            <path d="M10.2 20.1h.01M17 20.1h.01" stroke="currentColor" stroke-width="2.8" stroke-linecap="round"/>
                        </svg>
                        <span data-rn-cart-count @hidden($cartCount <= 0)>{{ $cartCount }}</span>
                    </a>
                    <a href="{{ route('login') }}" class="ks-login-button">{{ $isEnglish ? 'Login / Sign up' : 'دخول / تسجيل' }}</a>
                @endauth
            </nav>

            <div class="ks-header-tools">
                <details class="kr-preference" data-rn-preference="currency">
                    <summary>
                        <b data-rn-current-currency-symbol>{{ $currentCurrency?->symbol ?? 'ج.م' }}</b>
                        <img class="kr-flag-img" data-rn-current-currency-flag src="{{ asset('images/flags/'.($currencyFlagImages[$currentCurrency?->code] ?? 'eg.png')) }}" alt="">
                    </summary>
                    <div class="kr-preference-menu">
                        @foreach($activeCurrencies as $currency)
                            <form method="POST" action="{{ route('preferences.currency') }}" data-rn-ajax-form>
                                @csrf
                                <input type="hidden" name="currency" value="{{ $currency->code }}">
                                <button type="submit" data-rn-preference-option="currency" data-rn-preference-value="{{ $currency->code }}" @class(['is-active' => $currentCurrencyCode === $currency->code])>
                                    {{ $currency->symbol }} {{ $currency->code }}
                                    <img class="kr-flag-img" src="{{ asset('images/flags/'.($currencyFlagImages[$currency->code] ?? 'eg.png')) }}" alt="">
                                </button>
                            </form>
                        @endforeach
                    </div>
                </details>

                <details class="kr-preference" data-rn-preference="locale">
                    <summary>
                        <b data-rn-current-locale-label>{{ $currentLocale === 'ar' ? 'عربي' : 'English' }}</b>
                        <img class="kr-flag-img" data-rn-current-locale-flag src="{{ asset('images/flags/'.($currentLocale === 'ar' ? 'sa.png' : 'us.png')) }}" alt="">
                    </summary>
                    <div class="kr-preference-menu">
                        @foreach(['ar' => 'عربي', 'en' => 'English'] as $localeCode => $localeLabel)
                            <form method="POST" action="{{ route('preferences.locale') }}" data-rn-ajax-form>
                                @csrf
                                <input type="hidden" name="locale" value="{{ $localeCode }}">
                                <button type="submit" data-rn-preference-option="locale" data-rn-preference-value="{{ $localeCode }}" @class(['is-active' => $currentLocale === $localeCode])>
                                    {{ $localeLabel }}
                                    <img class="kr-flag-img" src="{{ asset('images/flags/'.($localeCode === 'ar' ? 'sa.png' : 'us.png')) }}" alt="">
                                </button>
                            </form>
                        @endforeach
                    </div>
                </details>
            </div>

            <button type="button" class="rn-theme-toggle rn-theme-toggle-desktop" data-rn-theme-toggle aria-label="تبديل الوضع الليلي">
                <svg class="rn-theme-sun" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 4V2m0 20v-2m8-8h2M2 12h2m14.4-6.4 1.4-1.4M4.2 19.8l1.4-1.4m0-12.8L4.2 4.2m15.6 15.6-1.4-1.4M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                <svg class="rn-theme-moon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 15.5A8.5 8.5 0 0 1 8.5 4 8 8 0 1 0 20 15.5Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
            </button>
        </div>

        <form action="{{ route('home') }}" class="ks-mobile-search">
            <input name="q" value="{{ $query ?? '' }}" placeholder="{{ $isEnglish ? 'Search for a game or card' : 'ابحث عن لعبة أو بطاقة' }}">
        </form>
    </header>

    <main class="rn-main">
        @yield('content')
    </main>

    <div class="rn-sidebar-backdrop" data-rn-sidebar-close></div>
    <aside class="rn-mobile-sidebar" aria-label="قائمة الموبايل">
        <div class="rn-sidebar-head">
            <a href="{{ route('home') }}" class="ks-brand" aria-label="{{ $siteName }}">
                <img class="ks-brand-logo" src="{{ asset($siteLogo) }}" alt="{{ $siteName }}">
            </a>
            <button type="button" data-rn-sidebar-close aria-label="إغلاق القائمة">
                <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
            </button>
        </div>

        <form action="{{ route('home') }}" class="rn-sidebar-search">
            <input name="q" value="{{ $query ?? '' }}" placeholder="{{ $isEnglish ? 'Search for a game or card' : 'ابحث عن لعبة أو بطاقة' }}">
            <button type="submit" aria-label="{{ $isEnglish ? 'Search' : 'بحث' }}"><svg viewBox="0 0 24 24" fill="none"><path d="m21 21-4.2-4.2M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button>
        </form>

        <nav class="rn-sidebar-links">
            <a href="{{ route('home') }}"><svg viewBox="0 0 24 24" fill="none"><path d="M4 10.5 12 4l8 6.5V20H5v-9.5z" stroke="currentColor" stroke-width="1.8"/></svg> {{ $isEnglish ? 'Home' : 'الرئيسية' }}</a>
            <a href="{{ route('home', ['category' => 'games']) }}"><svg viewBox="0 0 24 24" fill="none"><path d="M7 8h10l3 8a3 3 0 0 1-5 3l-1.5-1.5h-3L9 19a3 3 0 0 1-5-3l3-8Z" stroke="currentColor" stroke-width="1.8"/></svg> {{ $isEnglish ? 'Game top-up' : 'شحن الألعاب' }}</a>
            <a href="{{ route('home', ['category' => 'gift-cards']) }}"><svg viewBox="0 0 24 24" fill="none"><path d="M20 12v8H4v-8m17-5H3v5h18V7ZM12 20V7m0 0H8.5a2.5 2.5 0 1 1 2.5-2.5V7Zm0 0h3.5A2.5 2.5 0 1 0 13 4.5V7Z" stroke="currentColor" stroke-width="1.8"/></svg> {{ $isEnglish ? 'Game cards' : 'بطاقات الألعاب' }}</a>
            <a href="{{ route('cart.index') }}"><svg viewBox="0 0 24 24" fill="none"><path d="M6 6h15l-2 8H8L6 3H3M9 20h.01M18 20h.01" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg> {{ $isEnglish ? 'Cart' : 'السلة' }}</a>
            <a href="{{ auth()->check() ? route('account.dashboard') : route('login') }}"><svg viewBox="0 0 24 24" fill="none"><path d="M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10Z" stroke="currentColor" stroke-width="1.8"/></svg> {{ $isEnglish ? 'Account' : 'حسابي' }}</a>
        </nav>

        <div class="rn-sidebar-panel">
            <span>{{ $isEnglish ? 'Theme' : 'الوضع' }}</span>
            <button type="button" class="rn-theme-toggle rn-theme-toggle-sidebar" data-rn-theme-toggle>
                <svg class="rn-theme-sun" viewBox="0 0 24 24" fill="none"><path d="M12 4V2m0 20v-2m8-8h2M2 12h2m14.4-6.4 1.4-1.4M4.2 19.8l1.4-1.4m0-12.8L4.2 4.2m15.6 15.6-1.4-1.4M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                <span>{{ $isEnglish ? 'Toggle light / dark' : 'تبديل النهار / الليل' }}</span>
                <svg class="rn-theme-moon" viewBox="0 0 24 24" fill="none"><path d="M20 15.5A8.5 8.5 0 0 1 8.5 4 8 8 0 1 0 20 15.5Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
            </button>
        </div>
    </aside>

    <footer class="ks-footer">
        <div class="ks-footer-inner">
            <div class="ks-footer-about">
                <a href="{{ route('home') }}" class="ks-brand ks-footer-brand" aria-label="{{ $siteName }}">
                    <img class="ks-brand-logo" src="{{ asset($siteLogo) }}" alt="{{ $siteName }}">
                </a>
                <p>{{ $isEnglish ? 'A trusted digital store for game top-ups, gift cards, and e-payment services with fast delivery and clear support.' : 'منصة موثوقة لشحن الألعاب وبطاقات الهدايا وخدمات الدفع الإلكتروني بتجربة سريعة، آمنة، ودعم واضح.' }}</p>

                @if($socialLinks->isNotEmpty())
                    <div class="ks-footer-social" aria-label="{{ $isEnglish ? 'Social links' : 'روابط التواصل' }}">
                        @foreach($socialLinks as $social)
                            <a href="{{ $social['url'] }}" target="_blank" rel="noopener noreferrer" aria-label="{{ $social['label'] }}">
                                <img src="{{ asset($social['image']) }}" alt="{{ $social['label'] }}">
                            </a>
                        @endforeach
                    </div>
                @endif
            </div>

            <div class="ks-footer-grid">
                <div>
                    <h3>{{ $isEnglish ? 'Categories' : 'الفئات' }}</h3>
                    <a href="{{ route('home', ['category' => 'games']) }}">{{ $isEnglish ? 'Game top-up' : 'شحن الألعاب' }}</a>
                    <a href="{{ route('home', ['category' => 'gift-cards']) }}">{{ $isEnglish ? 'Game cards' : 'بطاقات الألعاب' }}</a>
                    <a href="{{ route('home', ['category' => 'deals']) }}">{{ $isEnglish ? 'E-payment' : 'الدفع الإلكتروني' }}</a>
                    <a href="{{ route('home', ['category' => 'subscriptions']) }}">{{ $isEnglish ? 'Subscriptions' : 'اشتراكات' }}</a>
                </div>
                <div>
                    <h3>{{ $isEnglish ? 'Legal' : 'قانوني' }}</h3>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'About us' : 'من نحن' }}</a>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'Terms of service' : 'شروط الخدمة' }}</a>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'Privacy policy' : 'سياسة الخصوصية' }}</a>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'Refund policy' : 'سياسة الإرجاع' }}</a>
                </div>
                <div>
                    <h3>{{ $isEnglish ? 'Support' : 'الدعم' }}</h3>
                    <a href="{{ route('account.dashboard') }}">{{ $isEnglish ? 'My account' : 'حسابي' }}</a>
                    <a href="{{ route('cart.index') }}">{{ $isEnglish ? 'Cart' : 'السلة' }}</a>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'Help center' : 'مركز المساعدة' }}</a>
                    <a href="{{ route('home') }}">{{ $isEnglish ? 'Contact us' : 'تواصل معنا' }}</a>
                </div>
                <div>
                    <h3>{{ $isEnglish ? 'Payment methods' : 'طرق الدفع' }}</h3>
                    <div class="ks-payments">
                        <img src="{{ asset('images/payments/visa.png') }}" alt="Visa">
                        <img src="{{ asset('images/payments/mastercard.png') }}" alt="Mastercard">
                        <img src="{{ asset('images/payments/instapay.png') }}" alt="InstaPay">
                        <img src="{{ asset('images/payments/vodafone-cash.png') }}" alt="Vodafone Cash">
                        <img src="{{ asset('images/payments/wallets.png') }}" alt="Wallets">
                    </div>
                </div>
            </div>
            <p class="ks-copyright">© {{ now()->year }} {{ $isEnglish ? 'All rights reserved.' : 'جميع الحقوق محفوظة.' }} {{ $siteName }}</p>
        </div>
    </footer>

    <nav class="rn-mobile-nav ks-mobile-nav">
        <a href="{{ route('home') }}">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 10.5 12 4l8 6.5V20H5v-9.5z" stroke="currentColor" stroke-width="1.8"/></svg>
            الرئيسية
        </a>
        <a href="{{ route('home', ['category' => 'games']) }}">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M7 8h10l3 8a3 3 0 0 1-5 3l-1.5-1.5h-3L9 19a3 3 0 0 1-5-3l3-8z" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
            الألعاب
        </a>
            <a href="{{ auth()->check() && auth()->user()->isAdmin() ? route('admin.dashboard') : route('account.dashboard') }}">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 13h7V4H4v9zm9 7h7V4h-7v16zM4 20h7v-5H4v5z" stroke="currentColor" stroke-width="1.8"/></svg>
            الإدارة
        </a>
        <a href="{{ auth()->check() ? route('account.dashboard') : route('login') }}">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z" stroke="currentColor" stroke-width="1.8"/></svg>
            حسابي
        </a>
    </nav>

    @if(app()->isLocal() && request()->boolean('inspect'))
        <button type="button" class="rn-inspector-toggle" data-rn-inspector-toggle>تحديد عنصر</button>
        <div class="rn-inspector-toast" data-rn-inspector-toast>اختار عنصر من الصفحة</div>
        <script>
            (() => {
                const toggle = document.querySelector('[data-rn-inspector-toggle]');
                const toast = document.querySelector('[data-rn-inspector-toast]');
                let active = false;
                let highlighted = null;

                const setToast = (message) => {
                    toast.textContent = message;
                    toast.classList.add('is-visible');
                    window.clearTimeout(setToast.timer);
                    setToast.timer = window.setTimeout(() => toast.classList.remove('is-visible'), 2200);
                };

                const cssPath = (element) => {
                    const parts = [];
                    let node = element;
                    while (node && node.nodeType === Node.ELEMENT_NODE && node !== document.body) {
                        let part = node.tagName.toLowerCase();
                        if (node.id) {
                            part += `#${CSS.escape(node.id)}`;
                            parts.unshift(part);
                            break;
                        }
                        const classes = [...node.classList].filter((item) => item && item !== 'rn-inspector-highlight').slice(0, 3);
                        if (classes.length) {
                            part += `.${classes.map((item) => CSS.escape(item)).join('.')}`;
                        }
                        const parent = node.parentElement;
                        if (parent) {
                            const sameTag = [...parent.children].filter((child) => child.tagName === node.tagName);
                            if (sameTag.length > 1) {
                                part += `:nth-of-type(${sameTag.indexOf(node) + 1})`;
                            }
                        }
                        parts.unshift(part);
                        node = parent;
                    }
                    return parts.join(' > ');
                };

                const describePath = (element) => {
                    const items = [];
                    let node = element;
                    while (node && node.nodeType === Node.ELEMENT_NODE && items.length < 6) {
                    const classes = [...node.classList].filter((item) => item !== 'rn-inspector-highlight').slice(0, 4).join('.');
                        items.push(`${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}${classes ? `.${classes}` : ''}`);
                        node = node.parentElement;
                    }
                    return items;
                };

                const clearHighlight = () => {
                    if (highlighted) {
                        highlighted.classList.remove('rn-inspector-highlight');
                        highlighted = null;
                    }
                };

                toggle.addEventListener('click', () => {
                    active = !active;
                    document.documentElement.classList.toggle('rn-inspector-active', active);
                    toggle.classList.toggle('is-active', active);
                    setToast(active ? 'دوس على العنصر اللي عايز تعدله' : 'وضع التحديد اتقفل');
                    clearHighlight();
                });

                document.addEventListener('mouseover', (event) => {
                    if (!active || event.target.closest('[data-rn-inspector-toggle], [data-rn-inspector-toast]')) return;
                    clearHighlight();
                    highlighted = event.target;
                    highlighted.classList.add('rn-inspector-highlight');
                }, true);

                document.addEventListener('click', async (event) => {
                    if (!active || event.target.closest('[data-rn-inspector-toggle], [data-rn-inspector-toast]')) return;
                    event.preventDefault();
                    event.stopPropagation();

                    const element = event.target;
                    const rect = element.getBoundingClientRect();
                    const payload = {
                        url: window.location.href,
                        selector: cssPath(element),
                        tag: element.tagName.toLowerCase(),
                        id: element.id || null,
                        classes: [...element.classList].filter((item) => item !== 'rn-inspector-highlight'),
                        text: (element.innerText || element.textContent || '').trim().slice(0, 1200),
                        rect: {
                            x: Math.round(rect.x),
                            y: Math.round(rect.y),
                            width: Math.round(rect.width),
                            height: Math.round(rect.height),
                        },
                        path: describePath(element),
                    };

                    await fetch('{{ route('dev.inspect-selection') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        },
                        body: JSON.stringify(payload),
                    });

                    setToast('اتحدد. اكتبلي: عدّل ده');
                    active = false;
                    document.documentElement.classList.remove('rn-inspector-active');
                    toggle.classList.remove('is-active');
                    clearHighlight();
                }, true);
            })();
        </script>
    @endif
    <script>
        (() => {
            const root = document.documentElement;
            const storedTheme = localStorage.getItem('rn-theme');
            const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            const applyTheme = (theme) => {
                root.dataset.theme = theme;
                localStorage.setItem('rn-theme', theme);
            };

            applyTheme(storedTheme || (prefersDark ? 'dark' : 'light'));

            document.querySelectorAll('[data-rn-theme-toggle]').forEach((button) => {
                button.addEventListener('click', () => applyTheme(root.dataset.theme === 'dark' ? 'light' : 'dark'));
            });

            const openSidebar = () => {
                document.body.classList.add('rn-sidebar-open');
                document.body.style.overflow = 'hidden';
            };
            const closeSidebar = () => {
                document.body.classList.remove('rn-sidebar-open');
                document.body.style.overflow = '';
            };

            document.querySelectorAll('[data-rn-sidebar-open]').forEach((button) => button.addEventListener('click', openSidebar));
            document.querySelectorAll('[data-rn-sidebar-close]').forEach((button) => button.addEventListener('click', closeSidebar));
            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape') closeSidebar();
            });

            const bindHeaderControls = (scope = document) => {
                scope.querySelectorAll('[data-rn-theme-toggle]').forEach((button) => {
                    if (button.dataset.rnBound) return;
                    button.dataset.rnBound = 'true';
                    button.addEventListener('click', () => applyTheme(root.dataset.theme === 'dark' ? 'light' : 'dark'));
                });
                scope.querySelectorAll('[data-rn-sidebar-open]').forEach((button) => {
                    if (button.dataset.rnBound) return;
                    button.dataset.rnBound = 'true';
                    button.addEventListener('click', openSidebar);
                });
                scope.querySelectorAll('[data-rn-sidebar-close]').forEach((button) => {
                    if (button.dataset.rnBound) return;
                    button.dataset.rnBound = 'true';
                    button.addEventListener('click', closeSidebar);
                });
            };

            document.querySelectorAll('.rn-scroll-section').forEach((section) => {
                const track = section.querySelector('[data-rn-scroll-track]');
                const prev = section.querySelector('[data-rn-scroll-prev]');
                const next = section.querySelector('[data-rn-scroll-next]');
                if (!track || !prev || !next) return;

                const step = () => Math.max(180, Math.round(track.clientWidth * 0.78));
                prev.addEventListener('click', () => track.scrollBy({ left: -step(), behavior: 'smooth' }));
                next.addEventListener('click', () => track.scrollBy({ left: step(), behavior: 'smooth' }));
            });

            document.querySelectorAll('.kr-hero-carousel').forEach((carousel) => {
                const slides = [...carousel.querySelectorAll('.kr-hero-slide')];
                const dots = [...carousel.querySelectorAll('[data-rn-hero-dot]')];
                const prev = carousel.querySelector('[data-rn-hero-prev]');
                const next = carousel.querySelector('[data-rn-hero-next]');
                if (slides.length < 2) return;

                let activeIndex = Math.max(0, slides.findIndex((slide) => slide.classList.contains('is-active')));
                const showSlide = (index) => {
                    activeIndex = (index + slides.length) % slides.length;
                    slides.forEach((slide, slideIndex) => slide.classList.toggle('is-active', slideIndex === activeIndex));
                    dots.forEach((dot, dotIndex) => dot.classList.toggle('is-active', dotIndex === activeIndex));
                };

                prev?.addEventListener('click', () => showSlide(activeIndex - 1));
                next?.addEventListener('click', () => showSlide(activeIndex + 1));
                dots.forEach((dot, index) => dot.addEventListener('click', () => showSlide(index)));
            });

            document.querySelectorAll('[data-kd-modal-open]').forEach((button) => {
                button.addEventListener('click', () => {
                    const modal = document.querySelector(`[data-kd-modal="${button.dataset.kdModalOpen}"]`);
                    if (modal) modal.hidden = false;
                });
            });

            document.querySelectorAll('[data-kd-modal-close]').forEach((button) => {
                button.addEventListener('click', () => button.closest('[data-kd-modal]').hidden = true);
            });

            document.querySelectorAll('[data-kd-gateway-select]').forEach((select) => {
                const sync = () => {
                    const option = select.selectedOptions[0];
                    const modal = select.closest('[data-kd-modal]');
                    modal?.querySelector('[data-kd-gateway-number]') && (modal.querySelector('[data-kd-gateway-number]').textContent = option?.dataset.number || '');
                    modal?.querySelector('[data-kd-gateway-instructions]') && (modal.querySelector('[data-kd-gateway-instructions]').textContent = option?.dataset.instructions || '');
                };
                select.addEventListener('change', sync);
                sync();
            });

            document.querySelectorAll('[data-kd-copy]').forEach((button) => {
                button.addEventListener('click', async () => {
                    const value = button.closest('.kd-copy-box')?.querySelector('[data-kd-gateway-number]')?.textContent?.trim();
                    if (!value) return;
                    await navigator.clipboard?.writeText(value).catch(() => {});
                    const old = button.textContent;
                    button.textContent = 'تم النسخ';
                    setTimeout(() => button.textContent = old, 1400);
                });
            });

            const token = document.querySelector('meta[name="csrf-token"]')?.content;
            const getLiveToast = () => {
                let toast = document.querySelector('[data-rn-live-toast]');
                if (!toast) {
                    toast = document.createElement('div');
                    toast.className = 'rn-live-toast';
                    toast.dataset.rnLiveToast = 'true';
                    toast.setAttribute('role', 'status');
                    toast.setAttribute('aria-live', 'polite');
                    document.body.appendChild(toast);
                }
                return toast;
            };

            let toastTimer;
            const showToast = (message) => {
                if (!message) return;
                const toast = getLiveToast();
                toast.textContent = message;
                toast.classList.add('is-visible');
                clearTimeout(toastTimer);
                toastTimer = setTimeout(() => toast.classList.remove('is-visible'), 2200);
            };

            const wireDynamicWidgets = (scope = document) => {
                scope.querySelectorAll('.rn-scroll-section:not([data-rn-wired])').forEach((section) => {
                    section.dataset.rnWired = 'true';
                    const track = section.querySelector('[data-rn-scroll-track]');
                    const prev = section.querySelector('[data-rn-scroll-prev]');
                    const next = section.querySelector('[data-rn-scroll-next]');
                    if (!track || !prev || !next) return;
                    const step = () => Math.max(180, Math.round(track.clientWidth * 0.78));
                    prev.addEventListener('click', () => track.scrollBy({ left: -step(), behavior: 'smooth' }));
                    next.addEventListener('click', () => track.scrollBy({ left: step(), behavior: 'smooth' }));
                });

                scope.querySelectorAll('.kr-hero-carousel:not([data-rn-wired])').forEach((carousel) => {
                    carousel.dataset.rnWired = 'true';
                    const slides = [...carousel.querySelectorAll('.kr-hero-slide')];
                    const dots = [...carousel.querySelectorAll('[data-rn-hero-dot]')];
                    const prev = carousel.querySelector('[data-rn-hero-prev]');
                    const next = carousel.querySelector('[data-rn-hero-next]');
                    if (slides.length < 2) return;
                    let activeIndex = Math.max(0, slides.findIndex((slide) => slide.classList.contains('is-active')));
                    const showSlide = (index) => {
                        activeIndex = (index + slides.length) % slides.length;
                        slides.forEach((slide, slideIndex) => slide.classList.toggle('is-active', slideIndex === activeIndex));
                        dots.forEach((dot, dotIndex) => dot.classList.toggle('is-active', dotIndex === activeIndex));
                    };
                    prev?.addEventListener('click', () => showSlide(activeIndex - 1));
                    next?.addEventListener('click', () => showSlide(activeIndex + 1));
                    dots.forEach((dot, index) => dot.addEventListener('click', () => showSlide(index)));
                });
            };

            const formatLivePrice = (amount, currency) => {
                const safeRate = Math.max(Number(currency.exchange_rate) || 1, 0.0001);
                const converted = amount / safeRate;
                const formatted = new Intl.NumberFormat(document.documentElement.lang === 'en' ? 'en-US' : 'ar-EG', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                }).format(converted);
                const symbol = currency.symbol || currency.currency || '';

                return currency.symbol_position === 'before'
                    ? `${symbol}${formatted}`
                    : `${formatted} ${symbol}`.trim();
            };

            const updateLivePrices = (currency) => {
                document.querySelectorAll('[data-rn-price]').forEach((node) => {
                    const amount = Number(node.dataset.rnPriceAmount);
                    if (!Number.isFinite(amount)) return;
                    node.textContent = formatLivePrice(amount, currency);
                    node.classList.remove('is-price-updated');
                    window.requestAnimationFrame(() => node.classList.add('is-price-updated'));
                });
            };

            const refreshLiveContent = async () => {
                const response = await fetch(window.location.href, {
                    headers: {
                        'Accept': 'text/html',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });
                if (!response.ok) return;
                const html = await response.text();
                const doc = new DOMParser().parseFromString(html, 'text/html');
                const freshHeader = doc.querySelector('header.ks-header');
                const currentHeader = document.querySelector('header.ks-header');
                if (freshHeader && currentHeader) {
                    currentHeader.replaceWith(freshHeader);
                    bindHeaderControls(freshHeader);
                }
                const freshMain = doc.querySelector('main.rn-main');
                const currentMain = document.querySelector('main.rn-main');
                if (freshMain && currentMain) {
                    currentMain.replaceWith(freshMain);
                    wireDynamicWidgets(freshMain);
                }
                const freshFooter = doc.querySelector('footer.ks-footer');
                const currentFooter = document.querySelector('footer.ks-footer');
                if (freshFooter && currentFooter) currentFooter.replaceWith(freshFooter);
                document.title = doc.title || document.title;
            };

            const refreshCartBadge = (count) => {
                const safeCount = Number(count) || 0;
                document.querySelectorAll('.ks-cart-link').forEach((cartLink) => {
                    if (!cartLink.querySelector('[data-rn-cart-count]')) {
                        const badge = document.createElement('span');
                        badge.dataset.rnCartCount = 'true';
                        cartLink.appendChild(badge);
                    }
                });
                document.querySelectorAll('[data-rn-cart-count]').forEach((node) => {
                    node.textContent = safeCount;
                    node.hidden = safeCount <= 0;
                    node.classList.remove('is-bumping');
                    window.requestAnimationFrame(() => node.classList.add('is-bumping'));
                });
                document.querySelectorAll('.ks-cart-link').forEach((cartLink) => {
                    cartLink.classList.remove('is-cart-added');
                    window.requestAnimationFrame(() => cartLink.classList.add('is-cart-added'));
                });
            };

            const applyPreferenceUpdate = (data, form) => {
                const holder = form.closest('[data-rn-preference]');
                holder?.classList.remove('is-updating');

                if (data.type === 'currency') {
                    document.querySelectorAll('[data-rn-current-currency-symbol]').forEach((node) => {
                        node.textContent = data.symbol || data.currency;
                    });
                    document.querySelectorAll('[data-rn-current-currency-flag]').forEach((node) => {
                        if (data.flag) node.src = data.flag;
                    });
                    document.querySelectorAll('[data-rn-preference-option="currency"]').forEach((node) => {
                        node.classList.toggle('is-active', node.dataset.rnPreferenceValue === data.currency);
                    });
                    updateLivePrices(data);
                    holder?.removeAttribute('open');
                    showToast('تم تغيير العملة');
                    return true;
                }

                if (data.type === 'locale') {
                    document.documentElement.lang = data.locale || document.documentElement.lang;
                    if (data.dir) document.documentElement.dir = data.dir;
                    document.querySelectorAll('[data-rn-current-locale-label]').forEach((node) => {
                        node.textContent = data.label || data.locale;
                    });
                    document.querySelectorAll('[data-rn-current-locale-flag]').forEach((node) => {
                        if (data.flag) node.src = data.flag;
                    });
                    document.querySelectorAll('[data-rn-preference-option="locale"]').forEach((node) => {
                        node.classList.toggle('is-active', node.dataset.rnPreferenceValue === data.locale);
                    });
                    holder?.removeAttribute('open');
                    showToast('تم تغيير اللغة');
                    window.setTimeout(() => refreshLiveContent().catch(() => {}), 180);
                    return true;
                }

                return false;
            };

            document.querySelectorAll('[data-rn-preference-option]').forEach((node) => {
                const form = node.closest('form');
                const name = node.dataset.rnPreferenceOption;
                if (!form || !name) return;
                const input = form.querySelector(`[name="${name}"]`);
                if (!input) return;
                node.classList.toggle('is-active', input.value === node.dataset.rnPreferenceValue);
            });

            document.addEventListener('animationend', (event) => {
                if (event.target.matches('[data-rn-cart-count]')) event.target.classList.remove('is-bumping');
                if (event.target.matches('.ks-cart-link, .kd-header-icon[href*="cart"]')) event.target.classList.remove('is-cart-added');
            });

            document.addEventListener('click', (event) => {
                const option = event.target.closest('[data-rn-preference-option]');
                if (!option) return;
                const form = option.closest('form');
                const name = option.dataset.rnPreferenceOption;
                const input = form?.querySelector(`[name="${name}"]`);
                if (input) input.value = option.dataset.rnPreferenceValue || input.value;
            });

            document.addEventListener('toggle', (event) => {
                const details = event.target.closest?.('details[data-rn-preference], .ks-profile-menu');
                if (!details || !details.open) return;
                document.querySelectorAll('details[data-rn-preference], .ks-profile-menu').forEach((node) => {
                    if (node !== details) node.removeAttribute('open');
                });
            }, true);

            document.addEventListener('click', (event) => {
                if (event.target.closest('details[data-rn-preference], .ks-profile-menu')) return;
                document.querySelectorAll('details[data-rn-preference], .ks-profile-menu').forEach((node) => node.removeAttribute('open'));
            });

            document.querySelectorAll('[data-rn-cart-count]').forEach((node) => {
                node.hidden = Number(node.textContent || 0) <= 0;
            });

            const setFormLoading = (form, loading) => {
                form.classList.toggle('is-rn-loading', loading);
                form.closest('[data-rn-preference]')?.classList.toggle('is-updating', loading);
                form.querySelectorAll('button, input, select, textarea').forEach((field) => {
                    field.disabled = loading;
                });
            };

            document.addEventListener('submit', async (event) => {
                const form = event.target.closest('[data-rn-ajax-form]');
                if (!form) return;
                event.preventDefault();

                const label = form.querySelector('[data-rn-add-cart-label]');
                const oldLabel = label?.textContent;
                const methodInput = form.querySelector('input[name="_method"]');
                const method = (methodInput?.value || form.method || 'POST').toUpperCase();
                const body = method === 'GET' ? undefined : new FormData(form);
                setFormLoading(form, true);

                try {
                    const response = await fetch(form.action, {
                        method,
                        headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' },
                        body,
                    });
                    const data = await response.json().catch(() => ({}));

                    if (!response.ok || data.ok === false) {
                        showToast(data.message || 'حصلت مشكلة، جرّب تاني');
                        form.dispatchEvent(new CustomEvent('rn:ajax-complete', { bubbles: true, detail: data }));
                        return;
                    }

                    const preferenceHandled = applyPreferenceUpdate(data, form);
                    if (data.cart_count !== undefined) {
                        refreshCartBadge(data.cart_count);
                        showToast('اتضافت للسلة بنجاح');
                    }

                    if (data.reload && !preferenceHandled) window.location.reload();
                    if (data.redirect && !preferenceHandled) window.location.href = data.redirect;

                    if (label && data.ok) {
                        label.textContent = 'تمت الإضافة';
                        setTimeout(() => label.textContent = oldLabel, 1400);
                    }

                    form.dispatchEvent(new CustomEvent('rn:ajax-complete', { bubbles: true, detail: data }));
                } catch (error) {
                    showToast('الاتصال اتقطع، جرّب تاني');
                    form.dispatchEvent(new CustomEvent('rn:ajax-complete', { bubbles: true, detail: { ok: false, error } }));
                } finally {
                    setFormLoading(form, false);
                }
            });
        })();
    </script>
</body>
</html>
