@php
    $lang = \App\Models\Language::where('code', app()->getLocale())->first();
    $siteSettings = app(App\Services\SiteSettingService::class)->getSettings(app()->getLocale());
    $siteTitle = $siteSettings['site_title'] ?? '';
    $siteDescription = $siteSettings['site_description'] ?? '';
    $logo = $siteSettings['logo'] ?? '';
    $logoText = $siteSettings['logo_text'] ?? '';
    $footerText = $siteSettings['footer_text'] ?? 'تمامی حقوق برای اَلو ایران محفوظ است © ' . date('Y');
    $favicon = $siteSettings['favicon'] ?? '';
    $siteIcon = $siteSettings['site_icon'] ?? '';
@endphp
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" dir="{{ $lang && $lang->direction == 'rtl' ? 'rtl' : 'ltr' }}">
<head>
    <meta charset="UTF-8">
    <!-- Enhanced viewport for better mobile experience -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5, user-scalable=yes, viewport-fit=cover">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- Mobile-specific meta tags -->
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="{{ $siteTitle }}">
    <meta name="theme-color" content="#FFD700">
    <meta name="msapplication-TileColor" content="#FFD700">

    <title>{{ $siteTitle }}</title>
    <meta name="description" content="{{ $siteDescription }}">

    <!-- Enhanced SEO Meta Tags -->
    <meta name="keywords" content="مکان‌یابی, گردشگری ایران, راهنمای سفر, نقشه ایران, جاهای دیدنی, هتل, رستوران">
    <meta name="author" content="{{ config('app.name') }}">
    <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">
    <meta name="googlebot" content="index, follow">
    <meta name="bingbot" content="index, follow">
    <meta name="language" content="{{ app()->getLocale() }}">
    <meta name="geo.region" content="IR">
    <meta name="geo.country" content="Iran">
    <meta name="geo.placename" content="Iran">
    <meta name="ICBM" content="32.4279, 53.6880">
    <meta name="DC.title" content="{{ $siteTitle }}">

    <!-- Open Graph Meta Tags -->
    <meta property="og:type" content="website">
    <meta property="og:title" content="{{ $siteTitle }}">
    <meta property="og:description" content="{{ $siteDescription }}">
    <meta property="og:url" content="{{ url()->current() }}">
    <meta property="og:site_name" content="{{ config('app.name') }}">
    <meta property="og:locale" content="{{ app()->getLocale() === 'fa' ? 'fa_IR' : 'en_US' }}">
    <meta property="og:image" content="{{ asset('images/og-image.jpg') }}">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:type" content="image/jpeg">

    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{{ $siteTitle }}">
    <meta name="twitter:description" content="{{ $siteDescription }}">
    <meta name="twitter:image" content="{{ asset('images/twitter-card.jpg') }}">
    <meta name="twitter:site" content="@{{ config('app.name') }}">
    <meta name="twitter:creator" content="@{{ config('app.name') }}">

    <!-- Canonical URL -->
    <link rel="canonical" href="{{ url()->current() }}">

    <!-- Alternate Language Links -->
    <link rel="alternate" hreflang="fa" href="{{ url('/') }}">
    <link rel="alternate" hreflang="en" href="{{ url('/lang/en') }}">
    <link rel="alternate" hreflang="x-default" href="{{ url('/') }}">

    <!-- Favicon -->
    @if($favicon)
    <link rel="icon" type="image/x-icon" href="{{ asset($favicon) }}">
    <link rel="shortcut icon" type="image/x-icon" href="{{ asset($favicon) }}">
    @endif

    <!-- Site Icon -->
    @if($siteIcon)
    <link rel="apple-touch-icon" href="{{ asset($siteIcon) }}">
    <link rel="icon" type="image/png" href="{{ asset($siteIcon) }}">
    @endif

    <!-- PWA Manifest -->
    <link rel="manifest" href="{{ asset('manifest.json') }}">

    <!-- Additional mobile icons -->
    <link rel="apple-touch-icon" sizes="57x57" href="{{ asset('images/apple-icon-57x57.png') }}">
    <link rel="apple-touch-icon" sizes="60x60" href="{{ asset('images/apple-icon-60x60.png') }}">
    <link rel="apple-touch-icon" sizes="72x72" href="{{ asset('images/apple-icon-72x72.png') }}">
    <link rel="apple-touch-icon" sizes="76x76" href="{{ asset('images/apple-icon-76x76.png') }}">
    <link rel="apple-touch-icon" sizes="114x114" href="{{ asset('images/apple-icon-114x114.png') }}">
    <link rel="apple-touch-icon" sizes="120x120" href="{{ asset('images/apple-icon-120x120.png') }}">
    <link rel="apple-touch-icon" sizes="144x144" href="{{ asset('images/apple-icon-144x144.png') }}">
    <link rel="apple-touch-icon" sizes="152x152" href="{{ asset('images/apple-icon-152x152.png') }}">
    <link rel="apple-touch-icon" sizes="180x180" href="{{ asset('images/apple-icon-180x180.png') }}">
    <link rel="icon" type="image/png" sizes="192x192" href="{{ asset('images/android-icon-192x192.png') }}">
    <link rel="icon" type="image/png" sizes="32x32" href="{{ asset('images/favicon-32x32.png') }}">
    <link rel="icon" type="image/png" sizes="96x96" href="{{ asset('images/favicon-96x96.png') }}">
    <link rel="icon" type="image/png" sizes="16x16" href="{{ asset('images/favicon-16x16.png') }}">
    <meta name="msapplication-TileImage" content="{{ asset('images/ms-icon-144x144.png') }}">

    @stack('head')

    <!-- Preload critical resources -->
    <link rel="preload" href="{{ asset('css/fonts.css') }}" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

    <!-- Critical CSS inline for faster rendering -->
    <style>
        /* Critical CSS - inline for immediate rendering */
        body { font-family: 'IRANSans', Tahoma, Arial, sans-serif; background-color: #f8f9fc; margin: 0; }
        .navbar { background-color: #FFD700; padding: 0.6rem 1rem; }
        .container { max-width: 1200px; margin: 0 auto; padding: 0 15px; }
        .card { border-radius: 0.5rem; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1); border: none; margin-bottom: 25px; }
    </style>

    <!-- Non-critical CSS loaded asynchronously -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" media="print" onload="this.media='all'" />
    <link rel="stylesheet" href="{{ asset('css/all.css') }}" media="print" onload="this.media='all'" onerror="this.onerror=null;this.href='{{ asset('css/all.css') }}';">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/fonts.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/custom-map.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/map-icons.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/geo-filter.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/modern-filters.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/modern-category-filter.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/performance-optimized.css') }}" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="{{ asset('css/modern-base-template.css') }}" media="print" onload="this.media='all'">

    <!-- Fallback for browsers that don't support onload -->
    <noscript>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
        <link rel="stylesheet" href="{{ asset('css/all.css') }}">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/MarkerCluster.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css">
        <link rel="stylesheet" href="{{ asset('css/fonts.css') }}">
        <link rel="stylesheet" href="{{ asset('css/custom-map.css') }}">
        <link rel="stylesheet" href="{{ asset('css/map-icons.css') }}">
        <link rel="stylesheet" href="{{ asset('css/geo-filter.css') }}">
        <link rel="stylesheet" href="{{ asset('css/modern-filters.css') }}">
        <link rel="stylesheet" href="{{ asset('css/modern-category-filter.css') }}">
        <link rel="stylesheet" href="{{ asset('css/performance-optimized.css') }}">
        <link rel="stylesheet" href="{{ asset('css/modern-base-template.css') }}">
    </noscript>
    <style>
        body {
            font-family: 'IRANSans', Tahoma, Arial, sans-serif;
            background-color: #f8f9fc;
            min-height: 100vh;
        }
        /* جلوگیری از تغییر فونت آیکون‌ها توسط کلاس en-font یا ltr-page */
        .en-font .fa, .en-font .fas, .en-font .far, .en-font .fab,
        .ltr-page .fa, .ltr-page .fas, .ltr-page .far, .ltr-page .fab {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome', Arial, sans-serif !important;
            font-weight: 900 !important;
        }
        .en-font .fab, .ltr-page .fab {
            font-family: 'Font Awesome 6 Brands', 'FontAwesome', Arial, sans-serif !important;
            font-weight: 400 !important;
        }
        /* توضیح: این خطوط تضمین می‌کند که آیکون‌های Font Awesome در هر زبان و هر کلاس، فونت خود را از دست ندهند */

        /* Date and time bar at top */
        .date-time-bar {
            background-color: #212121;
            color: #ffffff;
            padding: 6px 0;
            font-size: 0.85rem;
        }

        .date-time-bar .container {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .shamsi-date {
            display: flex;
            align-items: center;
            white-space: nowrap;
        }

        .shamsi-date i {
            margin-left: 6px;
            color: #FFC107;
        }

        .current-time {
            display: flex;
            align-items: center;
            white-space: nowrap;
        }

        .current-time i {
            margin-left: 6px;
            color: #FFC107;
        }

        /* Text advertisement ticker */
        .text-ad-container {
            flex: 1;
            overflow: hidden;
            margin: 0 15px;
            position: relative;
            height: 24px;
            background-color: rgba(255, 255, 255, 0.05);
            border-radius: 4px;
            min-width: 200px; /* Ensure minimum width */
        }

        .text-ad-ticker {
            position: absolute;
            white-space: nowrap;
            padding: 0 15px;
            line-height: 24px;
            width: max-content;
            color: #FFC107; /* Default color - will be overridden by JS */
            /* Start position will be set by JavaScript based on direction */
            top: 0;
            opacity: 1; /* Ensure visibility */
            will-change: transform; /* Optimize for animation performance */
        }

        .text-ad-ticker:hover {
            animation-play-state: paused;
        }

        .text-ad-ticker i {
            margin-left: 8px;
            font-size: 0.9em;
        }

        /* Animation keyframes for RTL */
        @keyframes ticker-rtl {
            0% { right: -50%; left: auto; }
            100% { right: 100%; left: auto; }
        }

        /* Animation keyframes for LTR */
        @keyframes ticker-ltr {
            0% { left: -50%; right: auto; }
            100% { left: 100%; right: auto; }
        }

        /* Blink animation */
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
        }

        /* Fade animation */
        @keyframes fade {
            0%, 100% { opacity: 0.7; }
            50% { opacity: 1; }
        }

        /* Pulse animation */
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        /* Slide animation */
        @keyframes slide {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-3px); }
        }

        @media (max-width: 767.98px) {
            .text-ad-container {
                margin: 0 10px;
            }

            .shamsi-date span, .current-time span {
                font-size: 0.8rem;
            }
        }

        @media (max-width: 575.98px) {
            .date-time-bar .container {
                flex-wrap: wrap;
            }

            .shamsi-date, .current-time {
                width: 50%;
                justify-content: center;
                margin-bottom: 6px;
            }

            .text-ad-container {
                width: 100%;
                margin-top: 3px;
            }
        }

        /* Enhanced navbar styling with animations and better visual effects */
        .navbar {
            background-color: var(--primary-color, #FFD700 ); /* Use theme primary color */
            /* background-image: linear-gradient(90deg, #FFD700 0%, #FFC107 100%); */ /* Removed gradient for a solid color */
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            padding: 0.6rem 1rem;
            transition: all 0.3s ease;
            z-index: 1030;
            position: relative;
        }

        .navbar-brand,
        .compact-nav .nav-link,
        .navbar-search .form-control,
        .navbar-search .search-icon,
        .btn-auth {
            color: #fff; /* Change text color to white for better contrast */
        }

        .navbar-search .form-control {
            background-color: rgba(255, 255, 255, 0.15); /* Darken search input background */
        }

        .navbar-search .form-control::placeholder {
            color: rgba(255, 255, 255, 0.7);
        }

        .navbar-search .form-control:focus {
            background-color: rgba(255, 255, 255, 0.25);
        }

        .btn-add-place {
            background-color: var(--secondary-color, #6c757d); /* Use theme secondary color */
            color: white;
        }
        .btn-add-place:hover {
            background-color: var(--dark-color, #343a40);
        }

        /* Sticky header effect */
        .navbar.sticky {
            position: fixed;
            top: 0;
            width: 100%;
            animation: slideDown 0.5s forwards;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-100%);
            }
            to {
                transform: translateY(0);
            }
        }

        .navbar-brand {
            font-weight: 800;
            font-size: 1.5rem;
            color: #212121;
            display: flex;
            align-items: center;
        }

        .navbar-brand i {
            font-size: 1.3rem;
            margin-left: 6px;
        }

        /* Compact nav menu with icons on top */
        .compact-nav {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .compact-nav .nav-item {
            margin: 0 0.5rem;
            text-align: center;
        }

        .compact-nav .nav-link {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #212121;
            font-weight: 600;
            padding: 0.4rem 0.7rem;
            border-radius: 6px;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }

        .compact-nav .nav-link i {
            font-size: 1.2rem;
            margin-bottom: 4px;
            transition: transform 0.3s ease;
        }

        .compact-nav .nav-link:hover {
            transform: translateY(-3px);
        }

        .compact-nav .nav-link:hover i {
            transform: scale(1.2);
        }

        .compact-nav .nav-link.active {
            background-color: rgba(255, 255, 255, 0.25);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        }

        /* Improved search bar */
        .navbar-search {
            position: relative;
            width: 100%;
            max-width: 360px;
        }

        .navbar-search .form-control {
            background-color: rgba(255, 255, 255, 0.25);
            border: none;
            color: #212121;
            padding: 0.5rem 40px 0.5rem 12px;
            border-radius: 50px;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }

        .navbar-search .form-control:focus {
            background-color: rgba(255, 255, 255, 0.9);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
        }

        .navbar-search .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #212121;
            opacity: 0.7;
        }

        /* Action buttons */
        .navbar-action-buttons {
            display: flex;
            align-items: center;
        }

        .btn-auth {
            background-color: rgba(255, 255, 255, 0.2);
            border: none;
            color: #212121;
            border-radius: 50px;
            padding: 0.4rem 1rem;
            font-weight: 600;
            margin-right: 10px;
            transition: all 0.3s ease;
        }

        .btn-auth:hover {
            background-color: rgba(255, 255, 255, 0.3);
            transform: translateY(-3px);
        }

        .btn-auth i {
            margin-left: 5px;
        }

        .btn-add-place {
            background-color: #212121;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 0.45rem 1.2rem;
            display: flex;
            align-items: center;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-add-place:hover {
            background-color: #000;
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }

        .btn-add-place i {
            margin-left: 6px;
            font-size: 0.9rem;
        }

        /* Mobile responsive */
        @media (max-width: 991.98px) {
            .navbar-collapse {
                background-color: rgba(255, 215, 0, 0.98);
                padding: 15px;
                border-radius: 0 0 12px 12px;
                box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
                max-height: 80vh;
                overflow-y: auto;
            }

            .compact-nav {
                flex-wrap: wrap;
                justify-content: space-around;
            }

            .compact-nav .nav-item {
                width: 33.33%;
                margin: 5px 0;
            }

            .navbar-search {
                max-width: 100%;
                margin: 12px 0;
            }

            .navbar-action-buttons {
                margin-top: 15px;
                justify-content: center;
                flex-wrap: wrap;
            }

            .btn-auth, .btn-add-place {
                margin: 5px;
            }
        }

        @media (max-width: 575.98px) {
            .compact-nav .nav-item {
                width: 50%;
            }

            .navbar-brand {
                font-size: 1.2rem;
            }
        }

        .card {
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            border: none;
            border-radius: 0.5rem;
            margin-bottom: 25px;
        }

        .card-header {
            background-color: #f8f9fc;
            border-bottom: 1px solid #e3e6f0;
            padding: 15px 20px;
            font-weight: 700;
            color: #4e73df;
        }

        .card-body {
            padding: 20px;
        }

        .btn-primary {
            background-color: #4e73df;
            border-color: #4e73df;
        }

        .btn-primary:hover {
            background-color: #3a5ccc;
            border-color: #3a5ccc;
        }

        #map {
            height: 500px;
            width: 100%;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .category-filter-container {
            margin-bottom: 20px;
        }

        /* Add responsive columns for desktop */
        @media (min-width: 992px) {
            .category-filter-content {
                display: flex;
                flex-wrap: wrap;
                margin: 0 -5px; /* Negative margin to offset the padding */
            }

            .category-filter-item {
                width: calc(33.333% - 10px); /* Three columns with padding considered */
                padding: 0 5px;
                margin-bottom: 5px;
            }
        }

        .parent-category {
            font-weight: 600;
            cursor: pointer;
            padding: 10px 15px;
            border-radius: 0;
            margin-bottom: 1px;
            background-color: #f8f9fc;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 0.9rem;
            border-left: 3px solid transparent;
        }

        .parent-category::after {
            content: '\f107'; /* Font Awesome angle-down */
            font-family: 'Font Awesome 5 Free';
            font-weight: 900;
            transition: transform 0.3s ease;
            position: absolute;
            left: 15px;
        }

        .parent-category.expanded {
            background-color: #edf2ff;
            border-left: 3px solid #4e73df;
        }

        .parent-category.expanded::after {
            transform: rotate(180deg);
        }

        .parent-category.active, .child-category.active {
            background-color: #4a89dc;
            color: white;
        }

        .children-container {
            margin-bottom: 1px;
            overflow: hidden;
            transition: all 0.3s ease;
            background-color: #f8f9fc;
        }

        .children-container.hidden {
            display: none;
            max-height: 0;
        }

        /* Collapse/expand toggle for filter section */
        .filter-collapse-btn {
            display: flex;
            width: 100%;
            justify-content: space-between;
            align-items: center;
            text-align: right;
            padding: 10px 15px;
            background-color: #4e73df;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 10px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .filter-collapse-btn:hover {
            background-color: #3a5ccc;
        }

        .filter-section-collapsed .category-filter-content {
            display: none;
        }

        .child-category {
            padding: 8px 15px 8px 30px;
            margin-bottom: 1px;
            cursor: pointer;
            background-color: #f8f9fc;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 0.85rem;
        }

        .child-category:hover {
            background-color: #edf2ff;
        }

        .category-info {
            display: flex;
            align-items: center;
        }

        .category-count {
            background-color: #ddd;
            border-radius: 4px;
            padding: 1px 6px;
            font-size: 0.75em;
            min-width: 24px;
            text-align: center;
            display: inline-block;
            margin-left: 8px;
        }

        /* Fix for child category counts */
        .child-category .category-count {
            position: relative;
            left: auto;
        }

        .category-emoji {
            margin-left: 0;
            margin-right: 8px;
            font-size: 1.2em;
            width: 20px;
            text-align: center;
            display: inline-block;
        }

        .location-list {
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 8px;
        }

        .location-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }

        .location-item:hover {
            background-color: #f5f5f5;
        }

        .location-item.selected {
            background-color: #e5f0ff;
            border-right: 3px solid #4a89dc;
        }

        .footer {
            padding: 25px 0;
            background-color: #fff;
            border-top: 1px solid #e3e6f0;
            margin-top: auto;
        }

        /* Map error display */
        .map-error-container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            padding: 20px;
            background-color: #f8f9fc;
            border-radius: 8px;
        }

        .map-error-message {
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            text-align: center;
        }

        /* Language Switcher Styles */
        .language-switcher {
            display: flex;
            gap: 10px;
            align-items: center;
            margin: 0 15px;
        }

        .language-link {
            padding: 5px 10px;
            border-radius: 4px;
            text-decoration: none;
            color: #212121;
            font-weight: 500;
            transition: all 0.3s ease;
            background-color: rgba(255, 255, 255, 0.2);
        }

        .language-link:hover {
            background-color: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
        }

        .language-link.active {
            background-color: rgba(255, 255, 255, 0.4);
            color: #212121;
            font-weight: 600;
        }

        @media (max-width: 991.98px) {
            .language-switcher {
                margin: 10px 0;
                justify-content: center;
            }
        }

        .flag-emoji {
            font-size: 1.5em !important;
            line-height: 1 !important;
            display: inline-block !important;
            vertical-align: middle !important;
            font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', 'Arial', sans-serif !important;
            font-style: normal !important;
            font-weight: normal !important;
        }

        /* Enhanced Navbar Styles */
        .navbar .nav-link:hover {
            background: rgba(255,255,255,0.3) !important;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .navbar .nav-link.active {
            background: rgba(255,255,255,0.4) !important;
        }

        /* Navigation indicator */
        .nav-indicator {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 2px;
            background: #2c3e50;
            transition: width 0.3s ease;
        }

        .nav-link:hover .nav-indicator {
            width: 80%;
        }

        /* Dropdown enhancements */
        .dropdown-item:hover {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        /* Button hover effects */
        .btn:hover, .btn-auth:hover, .btn-add-place:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        /* Header Style Variations */
        .header-default .nav-link {
            color: #2c3e50 !important;
        }

        .header-modern .nav-link {
            color: #ffffff !important;
        }

        .header-minimal .nav-link {
            color: #495057 !important;
        }

        .header-minimal .navbar-brand {
            color: #495057 !important;
        }

        .header-minimal .btn-auth {
            background: #007bff !important;
            color: white !important;
        }

        .header-minimal .btn-add-place {
            background: #28a745 !important;
        }

        .header-minimal .nav-indicator {
            background: #007bff !important;
        }

        /* Mobile navbar improvements */
        @media (max-width: 991px) {
            .navbar-nav {
                padding: 1rem 0;
            }

            .nav-link {
                margin: 4px 0 !important;
                border-radius: 8px;
            }

            .navbar-collapse {
                background: rgba(255,255,255,0.95);
                border-radius: 12px;
                margin-top: 12px;
                padding: 1rem;
                box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            }
        }
    </style>
</head>
<body @if(app()->getLocale() === 'en') class="en-font ltr-page" @endif>
    <!-- Shamsi Date and Time Bar -->
    <div class="date-time-bar">
        <div class="container">
            <div class="shamsi-date">
                <i class="fas fa-calendar-alt"></i>
                <span id="shamsi-date">در حال بارگذاری تاریخ...</span>
            </div>

            <!-- Text Advertisement Ticker -->
            <div class="text-ad-container">
                <div class="text-ad-ticker" id="text-ad-ticker">
                    <i class="fas fa-bullhorn"></i>
                    <span id="ad-text">در حال بارگذاری تبلیغات...</span>
                </div>
            </div>

            <div class="current-time">
                <i class="fas fa-clock"></i>
                <span id="current-time">در حال بارگذاری ساعت...</span>
            </div>
        </div>
    </div>

    <!-- Enhanced Modern Navbar -->
    @php
        $headerStyleClass = '';
        $headerStyleInline = '';

        switch($header_style) {
            case 'modern':
                $headerStyleClass = 'header-modern';
                $headerStyleInline = 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); box-shadow: 0 4px 20px rgba(0,0,0,0.1);';
                break;
            case 'minimal':
                $headerStyleClass = 'header-minimal';
                $headerStyleInline = 'background: #ffffff; border-bottom: 2px solid #f8f9fa; box-shadow: 0 2px 4px rgba(0,0,0,0.05);';
                break;
            default:
                $headerStyleClass = 'header-default';
                $headerStyleInline = 'background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);';
                break;
        }
    @endphp
    <nav class="navbar navbar-expand-lg {{ $header_style === 'minimal' ? 'navbar-light' : 'navbar-dark' }} shadow-sm {{ $headerStyleClass }}" style="{{ $headerStyleInline }} {{ $is_sticky_header ? 'position: sticky; top: 0;' : '' }} z-index: 1000;">
        <div class="container">
            <!-- Brand with enhanced styling -->
            <a class="navbar-brand order-2 order-lg-1 ml-auto mx-lg-0 d-flex align-items-center gap-3" href="{{ url('/') }}" style="text-decoration: none;">
                @if($logo)
                    <div class="brand-logo-container" style="position: relative;">
                        <img src="{{ $logo }}" alt="لوگو" style="height:45px;max-width:130px;object-fit:contain; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    </div>
                @endif
                @if($logoText)
                    <span class="logo-text" style="font-weight:bold;font-size:1.3rem;color:#2c3e50; text-shadow: 0 1px 2px rgba(255,255,255,0.8);">{{ $logoText }}</span>
                @endif
            </a>

            <!-- Enhanced Language Switcher -->
            @if($show_language_switcher)
            <div class="order-3 order-lg-2">
                <div class="language-switcher-enhanced">
                    <x-language-switcher />
                </div>
            </div>
            @endif

            <!-- Enhanced Toggle button -->
            <button class="navbar-toggler order-1 border-0" type="button" data-bs-toggle="collapse"
                    data-bs-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent"
                    aria-expanded="false"
                    aria-label="Toggle navigation"
                    style="background: rgba(255,255,255,0.2); border-radius: 8px; padding: 8px 12px;">
                <span class="navbar-toggler-icon"></span>
            </button>

            <!-- Action buttons for mobile (right side) -->
            <div class="navbar-action-buttons order-3 d-flex d-lg-none">
                <a href="{{ url('/login') }}" class="btn-auth">
                    <i class="fas fa-sign-in-alt"></i>
                </a>
            </div>

            <div class="collapse navbar-collapse order-4 order-lg-2" id="navbarSupportedContent">
                <!-- Search form -->
                @if($show_search_box)
                <div class="search-container d-flex justify-content-center mb-3 mb-lg-0">
                    <form action="{{ url('/search') }}" method="GET" class="search-form d-flex" style="max-width: 400px; width: 100%;">
                        <div class="input-group">
                            <input type="text"
                                   name="q"
                                   class="form-control"
                                   placeholder="{{ $search_placeholder }}"
                                   value="{{ request('q') }}"
                                   style="border-radius: 25px 0 0 25px; border: 2px solid rgba(255,255,255,0.3); background: rgba(255,255,255,0.9);">
                            <button type="submit"
                                    class="btn btn-outline-light"
                                    style="border-radius: 0 25px 25px 0; border: 2px solid rgba(255,255,255,0.3); border-left: none; background: rgba(255,255,255,0.2);">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </form>
                </div>
                @endif

                <!-- Dynamic nav menu with modern styling -->
                <ul class="navbar-nav compact-nav mx-auto mb-2 mb-lg-0">
                    @foreach($site_menus as $menu)
                        @if($menu->is_active)
                            <li class="nav-item {{ $menu->hasChildren() ? 'dropdown' : '' }}">
                                @if($menu->hasChildren())
                                    <a class="nav-link dropdown-toggle position-relative" href="#" id="navbarDropdown{{ $menu->id }}" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="padding: 8px 16px; border-radius: 8px; transition: all 0.3s ease; margin: 0 4px;">
                                        @if($menu->icon)
                                            <i class="{{ $menu->icon }}" style="font-size: 1.1rem;"></i>
                                        @endif
                                        <span>{{ $menu->title }}</span>
                                        <span class="nav-indicator"></span>
                                    </a>
                                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown{{ $menu->id }}">
                                        @foreach($menu->children as $child)
                                            @if($child->is_active)
                                                <li>
                                                    <a class="dropdown-item" href="{{ $child->full_url }}" target="{{ $child->target }}">
                                                        @if($child->icon)
                                                            <i class="{{ $child->icon }}"></i>
                                                        @endif
                                                        {{ $child->title }}
                                                    </a>
                                                </li>
                                            @endif
                                        @endforeach
                                    </ul>
                                @else
                                    <a class="nav-link position-relative {{ request()->is(trim($menu->url, '/') . '*') ? 'active' : '' }}" href="{{ $menu->full_url }}" target="{{ $menu->target }}" style="padding: 8px 16px; border-radius: 8px; transition: all 0.3s ease; margin: 0 4px;">
                                        @if($menu->icon)
                                            <i class="{{ $menu->icon }}" style="font-size: 1.1rem;"></i>
                                        @endif
                                        <span>{{ $menu->title }}</span>
                                        <span class="nav-indicator"></span>
                                    </a>
                                @endif
                            </li>
                        @endif
                    @endforeach
                </ul>

                <!-- Enhanced Action buttons (Desktop) -->
                <div class="navbar-action-buttons d-none d-lg-flex ms-auto align-items-center gap-2">
                    <!-- Quick actions -->
                    <button class="btn btn-sm btn-outline-dark" onclick="scrollToTop()" style="border-radius: 20px; padding: 6px 12px; background: rgba(255,255,255,0.2); border: 1px solid rgba(0,0,0,0.2);" title="بازگشت به بالا">
                        <i class="fas fa-arrow-up"></i>
                    </button>



                    @if($show_user_menu ?? true)
                        @if (Route::has('login'))
                            @auth
                                <!-- User dropdown menu -->
                                <div class="dropdown">
                                    <button class="btn-auth dropdown-toggle d-flex align-items-center gap-2" type="button"
                                            id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false"
                                            style="background: rgba(255,255,255,0.2); border: none; color: #2c3e50; border-radius: 25px; padding: 8px 16px; font-weight: 600;">
                                        <i class="fas fa-user-circle" style="font-size: 1.2rem;"></i>
                                        <span>{{ auth()->user()->name ?? 'کاربر' }}</span>
                                        <i class="fas fa-chevron-down" style="font-size: 0.8rem;"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0" aria-labelledby="userDropdown" style="border-radius: 12px; overflow: hidden; margin-top: 8px;">
                                        @forelse($user_buttons->where('show_for_users', true)->where('is_visible', true)->where('button_key', '!=', 'add_location') as $button)
                                            <li>
                                                @if($button->button_key === 'logout')
                                                    <form method="POST" action="{{ $button->button_url }}">
                                                        @csrf
                                                        <button type="submit" class="dropdown-item d-flex align-items-center" style="padding: 12px 20px; transition: all 0.2s ease;">
                                                            @if($button->button_icon)
                                                                <i class="{{ $button->button_icon }} me-3 text-danger"></i>
                                                            @endif
                                                            {{ $button->button_text }}
                                                        </button>
                                                    </form>
                                                @else
                                                    <a class="dropdown-item d-flex align-items-center" href="{{ $button->full_url }}" style="padding: 12px 20px; transition: all 0.2s ease;">
                                                        @if($button->button_icon)
                                                            <i class="{{ $button->button_icon }} me-3 text-primary"></i>
                                                        @endif
                                                        {{ $button->button_text }}
                                                    </a>
                                                @endif
                                            </li>
                                        @empty
                                            <li><span class="dropdown-item">هیچ دکمه‌ای یافت نشد</span></li>
                                        @endforelse
                                    </ul>
                                </div>
                            @else
                                <!-- Guest buttons (excluding add_location) -->
                                @forelse($user_buttons->where('show_for_guests', true)->where('is_visible', true)->where('button_key', '!=', 'add_location') as $button)
                                    <a href="{{ $button->full_url }}" class="btn-auth d-flex align-items-center gap-2" style="background: rgba(255,255,255,0.2); border: none; color: #2c3e50; border-radius: 25px; padding: 8px 16px; font-weight: 600; text-decoration: none; margin: 0 2px;">
                                        @if($button->button_icon)
                                            <i class="{{ $button->button_icon }}"></i>
                                        @endif
                                        <span>{{ $button->button_text }}</span>
                                    </a>
                                @empty
                                    <!-- Fallback buttons if no buttons found -->
                                    <a href="/login" class="btn-auth d-flex align-items-center gap-2" style="background: rgba(255,255,255,0.2); border: none; color: #2c3e50; border-radius: 25px; padding: 8px 16px; font-weight: 600; text-decoration: none; margin: 0 2px;">
                                        <i class="fas fa-sign-in-alt"></i>
                                        <span>ورود</span>
                                    </a>
                                @endforelse
                            @endauth
                        @endif
                    @endif

                    <!-- Add location button (separate handling) -->
                    @php
                        $addLocationButton = $user_buttons->where('button_key', 'add_location')->first();
                    @endphp
                    @if($addLocationButton && $addLocationButton->is_visible && (($is_guest_user && $addLocationButton->show_for_guests) || (!$is_guest_user && $addLocationButton->show_for_users)))
                        <a href="{{ $addLocationButton->full_url }}" class="btn-add-place d-flex align-items-center gap-2" style="background: #2c3e50; color: white; border: none; border-radius: 25px; padding: 8px 16px; font-weight: 600; text-decoration: none;">
                            @if($addLocationButton->button_icon)
                                <i class="{{ $addLocationButton->button_icon }}"></i>
                            @endif
                            <span>{{ $addLocationButton->button_text }}</span>
                        </a>
                    @endif
                </div>
            </div>
        </div>
    </nav>

    <!-- Breadcrumb -->
    @if($show_breadcrumb && !request()->is('/'))
    <nav aria-label="breadcrumb" class="breadcrumb-container" style="background: rgba(255,255,255,0.9); border-bottom: 1px solid #e9ecef;">
        <div class="container">
            <ol class="breadcrumb mb-0 py-2">
                <li class="breadcrumb-item">
                    <a href="{{ url('/') }}" style="color: #6c757d; text-decoration: none;">
                        <i class="fas fa-home"></i> صفحه اصلی
                    </a>
                </li>
                @if(isset($breadcrumb) && is_array($breadcrumb))
                    @foreach($breadcrumb as $item)
                        @if($loop->last)
                            <li class="breadcrumb-item active" aria-current="page" style="color: #495057;">
                                {{ $item['title'] }}
                            </li>
                        @else
                            <li class="breadcrumb-item">
                                <a href="{{ $item['url'] }}" style="color: #6c757d; text-decoration: none;">
                                    {{ $item['title'] }}
                                </a>
                            </li>
                        @endif
                    @endforeach
                @else
                    <li class="breadcrumb-item active" aria-current="page" style="color: #495057;">
                        {{ $title ?? 'صفحه فعلی' }}
                    </li>
                @endif
            </ol>
        </div>
    </nav>
    @endif

    <main class="container py-4">
        @yield('content')
    </main>

    <footer class="footer">
        <div class="container">
            <div class="row">
                <div class="col-md-12 text-center">
                    <p class="copyright-text" style="font-weight: bold; text-align: center; margin: 0; padding: 10px 0;">{!! $footerText !!}</p>
                </div>
            </div>
        </div>
    </footer>

    <!-- Enhanced JavaScript Loading with Proper Dependencies -->
    <script>
        // Enhanced script loader with dependency management
        class ScriptLoader {
            constructor() {
                this.loadedScripts = new Set();
                this.loadingScripts = new Map();
            }

            loadScript(src, callback) {
                if (this.loadedScripts.has(src)) {
                    if (callback) callback();
                    return Promise.resolve();
                }

                if (this.loadingScripts.has(src)) {
                    return this.loadingScripts.get(src);
                }

                const promise = new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.src = src;
                    script.async = true;

                    script.onload = () => {
                        this.loadedScripts.add(src);
                        this.loadingScripts.delete(src);
                        if (callback) callback();
                        resolve();
                    };

                    script.onerror = () => {
                        this.loadingScripts.delete(src);
                        console.error(`Failed to load script: ${src}`);
                        reject(new Error(`Failed to load script: ${src}`));
                    };

                    document.head.appendChild(script);
                });

                this.loadingScripts.set(src, promise);
                return promise;
            }

            async loadScriptsSequentially(scripts) {
                for (const script of scripts) {
                    try {
                        if (typeof script === 'string') {
                            await this.loadScript(script);
                        } else {
                            await this.loadScript(script.src, script.callback);
                        }
                    } catch (error) {
                        console.error('Script loading error:', error);
                    }
                }
            }
        }

        // Initialize script loader
        const scriptLoader = new ScriptLoader();

        // Enhanced script loading with better error handling and dependency management
        async function loadCriticalScripts() {
            console.log('Starting critical script loading...');

            try {
                // Step 1: Load jQuery first and ensure it's properly initialized
                console.log('Loading jQuery...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js');

                // Wait for jQuery to be fully available
                let jQueryRetries = 0;
                while (typeof window.jQuery === 'undefined' && jQueryRetries < 10) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    jQueryRetries++;
                }

                if (typeof window.jQuery === 'undefined') {
                    throw new Error('jQuery failed to load after multiple attempts');
                }

                // Make $ available globally and ensure it's the same as jQuery
                window.$ = window.jQuery;
                console.log('jQuery loaded and initialized successfully');

                // Step 2: Load Bootstrap (doesn't depend on jQuery in v5)
                console.log('Loading Bootstrap...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js');
                console.log('Bootstrap loaded successfully');

                // Step 3: Load Select2 (depends on jQuery)
                console.log('Loading Select2...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js');

                // Verify Select2 is properly attached to jQuery
                let select2Retries = 0;
                while ((!window.$ || !window.$.fn.select2) && select2Retries < 10) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    select2Retries++;
                }

                if (!window.$ || !window.$.fn.select2) {
                    console.warn('Select2 may not have loaded properly');
                } else {
                    console.log('Select2 loaded successfully');
                }

                // Step 4: Load Leaflet
                console.log('Loading Leaflet...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js');

                // Verify Leaflet is available
                let leafletRetries = 0;
                while (typeof window.L === 'undefined' && leafletRetries < 10) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    leafletRetries++;
                }

                if (typeof window.L === 'undefined') {
                    console.warn('Leaflet may not have loaded properly');
                } else {
                    console.log('Leaflet loaded successfully');
                }

                // Step 4.5: Load Leaflet MarkerCluster (depends on Leaflet)
                console.log('Loading Leaflet MarkerCluster...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js');

                // Verify MarkerCluster is available
                let markerClusterRetries = 0;
                while ((!window.L || !window.L.markerClusterGroup) && markerClusterRetries < 10) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    markerClusterRetries++;
                }

                if (!window.L || !window.L.markerClusterGroup) {
                    console.warn('Leaflet MarkerCluster may not have loaded properly');
                } else {
                    console.log('Leaflet MarkerCluster loaded successfully');
                }

                // Step 5: Load SweetAlert2
                console.log('Loading SweetAlert2...');
                await scriptLoader.loadScript('https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.all.min.js');
                console.log('SweetAlert2 loaded successfully');

                // Final step: Trigger custom event when all scripts are loaded
                console.log('All critical scripts loaded successfully');
                window.dispatchEvent(new CustomEvent('scriptsLoaded', {
                    detail: {
                        jQuery: typeof window.$ !== 'undefined',
                        select2: typeof window.$ !== 'undefined' && typeof window.$.fn.select2 !== 'undefined',
                        leaflet: typeof window.L !== 'undefined',
                        bootstrap: typeof window.bootstrap !== 'undefined',
                        sweetAlert: typeof window.Swal !== 'undefined'
                    }
                }));

            } catch (error) {
                console.error('Error loading critical scripts:', error);
                // Fallback: try to load scripts synchronously
                loadFallbackScripts();
            }
        }

        // Enhanced fallback script loading
        function loadFallbackScripts() {
            console.log('Loading fallback scripts synchronously...');

            const scripts = [
                {
                    src: 'https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js',
                    test: () => typeof window.jQuery !== 'undefined'
                },
                {
                    src: 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js',
                    test: () => typeof window.bootstrap !== 'undefined'
                },
                {
                    src: 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js',
                    test: () => typeof window.$ !== 'undefined' && typeof window.$.fn.select2 !== 'undefined'
                },
                {
                    src: 'https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js',
                    test: () => typeof window.L !== 'undefined'
                },
                {
                    src: 'https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js',
                    test: () => typeof window.L !== 'undefined' && typeof window.L.markerClusterGroup !== 'undefined'
                },
                {
                    src: 'https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.all.min.js',
                    test: () => typeof window.Swal !== 'undefined'
                }
            ];

            let loadedCount = 0;

            scripts.forEach((scriptConfig, index) => {
                const script = document.createElement('script');
                script.src = scriptConfig.src;
                script.async = false; // Load in order

                script.onload = () => {
                    loadedCount++;
                    console.log(`Fallback script ${index + 1}/${scripts.length} loaded: ${scriptConfig.src}`);

                    // Test if the script loaded correctly
                    setTimeout(() => {
                        if (scriptConfig.test()) {
                            console.log(`Script ${index + 1} verified successfully`);
                        } else {
                            console.warn(`Script ${index + 1} loaded but verification failed`);
                        }

                        // If all scripts are loaded, trigger the event
                        if (loadedCount === scripts.length) {
                            setTimeout(() => {
                                window.dispatchEvent(new CustomEvent('scriptsLoaded', {
                                    detail: { fallback: true }
                                }));
                                console.log('All fallback scripts loaded');
                            }, 500);
                        }
                    }, 100);
                };

                script.onerror = () => {
                    console.error(`Failed to load fallback script: ${scriptConfig.src}`);
                    loadedCount++;
                };

                document.head.appendChild(script);
            });
        }

        // Start loading scripts with proper timing
        function initializeScriptLoading() {
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => {
                    setTimeout(loadCriticalScripts, 100);
                });
            } else {
                setTimeout(loadCriticalScripts, 100);
            }
        }

        // Initialize script loading
        initializeScriptLoading();
    </script>

    <!-- Error fixes script - Load first to handle errors -->
    <script src="{{ asset('js/error-fixes.js') }}" defer></script>

    <!-- Fallback for critical scripts -->
    <noscript>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.all.min.js"></script>
    </noscript>

    <!-- Text Advertisement Script -->
    <script>
        // Variables for advertisements
        let textAds = [];
        let currentAdIndex = 0;
        let adRotationInterval = null;

        // Function to load text advertisements
        function loadTextAdvertisements() {
            console.log('Loading text advertisements...');
            fetch('/api/advertisements/text')
                .then(response => {
                    console.log('API Response Status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Received data:', data);
                    if (data.success && data.ads && data.ads.length > 0) {
                        textAds = data.ads;
                        console.log('Loaded text ads:', textAds);
                        displayNextTextAd();
                    } else {
                        console.log('No ads found, using fallback');
                        textAds = [{
                            content: 'به اَلو ایران خوش آمدید! مرجع جامع معرفی مکان‌ها',
                            target_url: '#',
                            speed: 20,
                            direction: 'rtl',
                            animation_type: 'none',
                            text_color: '#FFC107'
                        }];
                        displayNextTextAd();
                    }
                })
                .catch(error => {
                    console.error('Error loading text advertisements:', error);
                    textAds = [{
                        content: 'به اَلو ایران خوش آمدید! مرجع جامع معرفی مکان‌ها',
                        target_url: '#',
                        speed: 20,
                        direction: 'rtl',
                        animation_type: 'none',
                        text_color: '#FFC107'
                    }];
                    displayNextTextAd();
                });
        }

        // Function to display the current ad
        function displayNextTextAd() {
            if (textAds.length === 0) return;

            const ad = textAds[currentAdIndex];

            // Update ticker with ad content
            document.getElementById('ad-text').textContent = ad.content;

            // Get ticker speed and adjust for faster appearance
            // Use a faster speed to ensure the ad appears quickly but doesn't move too fast
            const tickerSpeed = Math.min(ad.speed || 20, 20); // Cap at 20 seconds maximum
            const ticker = document.getElementById('text-ad-ticker');

            // Get the direction (default to rtl if not specified)
            const direction = ad.direction || 'rtl';
            const animationType = ad.animation_type || 'none';
            const textColor = ad.text_color || '#FFC107';

            // Set text color
            ticker.style.color = textColor;

            // Reset any previous animation and styling
            ticker.style.animation = 'none';
            ticker.style.right = 'auto';
            ticker.style.left = 'auto';
            ticker.querySelector('i').style.animation = 'none';

            // Force reflow to ensure animation restart
            void ticker.offsetWidth;

            // Apply direction-based animation
            let directionAnimation = '';
            if (direction === 'rtl') {
                directionAnimation = `ticker-rtl ${tickerSpeed}s linear infinite`;
            } else {
                directionAnimation = `ticker-ltr ${tickerSpeed}s linear infinite`;
            }

            // Apply animation type
            let effectAnimation = '';
            switch(animationType) {
                case 'blink':
                    effectAnimation = 'blink 1.5s infinite';
                    break;
                case 'fade':
                    effectAnimation = 'fade 2s infinite';
                    break;
                case 'pulse':
                    effectAnimation = 'pulse 1.5s infinite';
                    break;
                case 'slide':
                    effectAnimation = 'slide 1.5s infinite';
                    break;
                case 'none':
                default:
                    // No additional effect animation
                    break;
            }

            // Apply the main ticker animation
            ticker.style.animation = directionAnimation;

            // If we have an effect animation, apply it to the text span
            if (effectAnimation) {
                document.getElementById('ad-text').style.display = 'inline-block';
                document.getElementById('ad-text').style.animation = effectAnimation;
            } else {
                document.getElementById('ad-text').style.animation = 'none';
            }

            // Apply pulse animation to the icon
            ticker.querySelector('i').style.animation = 'pulse 1.5s infinite';

            // If there's a target URL, make the ticker clickable
            if (ad.target_url) {
                ticker.style.cursor = 'pointer';
                ticker.onclick = function() {
                    window.open(ad.target_url, '_blank');
                };
            } else {
                ticker.style.cursor = 'default';
                ticker.onclick = null;
            }
        }

        // Function to rotate to the next ad
        function rotateToNextAd() {
            if (textAds.length <= 1) return;

            currentAdIndex = (currentAdIndex + 1) % textAds.length;
            displayNextTextAd();
        }

        // Initialize advertisement display
        document.addEventListener('DOMContentLoaded', function() {
            loadTextAdvertisements();

            // Preload next advertisement if an ad is almost finished
            document.querySelector('.text-ad-ticker').addEventListener('animationiteration', function() {
                // This will fire each time the animation completes one iteration
                rotateToNextAd();
            });
        });
    </script>

    <!-- Jalali (Shamsi) Date Script -->
    <script>
        // Persian digits
        function toPersianNum(num) {
            const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
            return String(num).replace(/[0-9]/g, function(w) {
                return persianDigits[+w];
            });
        }

        // Function to convert Gregorian date to Jalali (Shamsi)
        function gregorianToJalali(gy, gm, gd) {
            var g_d_m, jy, jm, jd, gy2, days;
            g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
            gy2 = (gm > 2) ? (gy + 1) : gy;
            days = 355666 + (365 * gy) + ~~((gy2 + 3) / 4) - ~~((gy2 + 99) / 100) + ~~((gy2 + 399) / 400) + gd + g_d_m[gm - 1];
            jy = -1595 + (33 * ~~(days / 12053));
            days %= 12053;
            jy += 4 * ~~(days / 1461);
            days %= 1461;
            if (days > 365) {
                jy += ~~((days - 1) / 365);
                days = (days - 1) % 365;
            }
            if (days < 186) {
                jm = 1 + ~~(days / 31);
                jd = 1 + (days % 31);
            } else {
                jm = 7 + ~~((days - 186) / 30);
                jd = 1 + ((days - 186) % 30);
            }
            return [jy, jm, jd];
        }

        // Persian month names
        const persianMonths = [
            'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور',
            'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
        ];

        // Persian day names
        const persianDays = [
            'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنج‌شنبه', 'جمعه', 'شنبه'
        ];

        function updateDateTime() {
            const now = new Date();
            const dayIndex = now.getDay();
            const day = persianDays[dayIndex];

            // Convert to Jalali (Shamsi)
            const jalali = gregorianToJalali(now.getFullYear(), now.getMonth() + 1, now.getDate());
            const jalaliYear = jalali[0];
            const jalaliMonth = persianMonths[jalali[1] - 1];
            const jalaliDay = jalali[2];

            // Format hour, minute, second
            const hours = now.getHours();
            const minutes = now.getMinutes();
            const seconds = now.getSeconds();

            // Update date and time elements
            document.getElementById('shamsi-date').innerHTML =
                day + ' ' + toPersianNum(jalaliDay) + ' ' + jalaliMonth + ' ' + toPersianNum(jalaliYear);

            document.getElementById('current-time').innerHTML =
                toPersianNum(hours.toString().padStart(2, '0')) + ':' +
                toPersianNum(minutes.toString().padStart(2, '0')) + ':' +
                toPersianNum(seconds.toString().padStart(2, '0'));

            // Update every second
            setTimeout(updateDateTime, 1000);
        }

        // Initialize date and time display
        document.addEventListener('DOMContentLoaded', function() {
            updateDateTime();
        });
    </script>

    <!-- Enhanced Navigation and Accessibility Scripts -->
    <script>
        // Scroll to top function
        function scrollToTop() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }

        // Make navbar sticky on scroll with enhanced effects
        window.addEventListener('scroll', function() {
            const navbar = document.querySelector('.navbar');
            if (window.scrollY > 50) {
                navbar.classList.add('sticky');
                navbar.style.boxShadow = '0 4px 20px rgba(0,0,0,0.15)';
            } else {
                navbar.classList.remove('sticky');
                navbar.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.08)';
            }
        });

        // Enhanced dropdown behavior
        document.addEventListener('DOMContentLoaded', function() {
            // Fix dropdown behavior on mobile
            const dropdownLinks = document.querySelectorAll('.category-dropdown .dropdown-toggle');

            if (window.innerWidth < 992) {
                dropdownLinks.forEach(link => {
                    link.addEventListener('click', function(e) {
                        if (this.getAttribute('aria-expanded') === 'true') {
                            window.location.href = this.getAttribute('href');
                        }
                    });
                });
            }

            // Add keyboard navigation support
            document.addEventListener('keydown', function(e) {
                // Alt + H for Home
                if (e.altKey && e.key === 'h') {
                    e.preventDefault();
                    window.location.href = '{{ url("/") }}';
                }

                // Alt + M for Map
                if (e.altKey && e.key === 'm') {
                    e.preventDefault();
                    window.location.href = '{{ url("/map") }}';
                }

                // Alt + T for scroll to Top
                if (e.altKey && e.key === 't') {
                    e.preventDefault();
                    scrollToTop();
                }
            });

            // Add focus indicators for accessibility
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.addEventListener('focus', function() {
                    this.style.outline = '2px solid #667eea';
                    this.style.outlineOffset = '2px';
                });

                link.addEventListener('blur', function() {
                    this.style.outline = 'none';
                });
            });

            // Announce page changes for screen readers
            const pageTitle = document.title;
            const announcement = document.createElement('div');
            announcement.setAttribute('aria-live', 'polite');
            announcement.setAttribute('aria-atomic', 'true');
            announcement.className = 'sr-only';
            announcement.textContent = `صفحه ${pageTitle} بارگذاری شد`;
            document.body.appendChild(announcement);
        });

        // Add smooth scrolling to all anchor links
        document.addEventListener('DOMContentLoaded', function() {
            const anchorLinks = document.querySelectorAll('a[href^="#"]');
            anchorLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    const targetId = this.getAttribute('href').substring(1);
                    const targetElement = document.getElementById(targetId);

                    if (targetElement) {
                        e.preventDefault();
                        targetElement.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    }
                });
            });
        });
    </script>

    <!-- Advanced Filters Module -->
    <script src="{{ asset('js/advanced-filters.js') }}" defer></script>

    @yield('scripts')
</body>
</html>