<?php $__env->startSection('title', __('welcome.title')); ?>

<?php $__env->startPush('head'); ?>
<!-- Structured Data (JSON-LD) for SEO -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "WebSite",
  "name": "<?php echo e(config('app.name')); ?>",
  "description": "سامانه جامع مکان‌یابی و راهنمای گردشگری ایران",
  "url": "<?php echo e(url('/')); ?>",
  "potentialAction": {
    "@type": "SearchAction",
    "target": {
      "@type": "EntryPoint",
      "urlTemplate": "<?php echo e(url('/')); ?>?search={search_term_string}"
    },
    "query-input": "required name=search_term_string"
  },
  "publisher": {
    "@type": "Organization",
    "name": "<?php echo e(config('app.name')); ?>",
    "url": "<?php echo e(url('/')); ?>",
    "logo": {
      "@type": "ImageObject",
      "url": "<?php echo e(asset('images/logo.png')); ?>"
    }
  },
  "inLanguage": ["fa", "en"],
  "audience": {
    "@type": "Audience",
    "geographicArea": {
      "@type": "Country",
      "name": "Iran"
    }
  }
}
</script>

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "TravelAgency",
  "name": "<?php echo e(config('app.name')); ?>",
  "description": "راهنمای جامع مکان‌های گردشگری، هتل‌ها، رستوران‌ها و جاذبه‌های توریستی ایران",
  "url": "<?php echo e(url('/')); ?>",
  "address": {
    "@type": "PostalAddress",
    "addressCountry": "IR",
    "addressRegion": "Tehran",
    "addressLocality": "Tehran"
  },
  "geo": {
    "@type": "GeoCoordinates",
    "latitude": 35.6892,
    "longitude": 51.3890
  },
  "areaServed": {
    "@type": "Country",
    "name": "Iran"
  },
  "serviceType": [
    "مکان‌یابی",
    "راهنمای گردشگری",
    "اطلاعات هتل و رستوران",
    "نقشه و مسیریابی"
  ]
}
</script>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('styles'); ?>
    <link rel="stylesheet" href="<?php echo e(asset('css/fonts.css')); ?>">
    <!-- Performance optimization styles -->
    <style>
        /* Lazy loading placeholder */
        .lazy-image {
            background-color: #f0f0f0;
            background-image: linear-gradient(45deg, #f0f0f0 25%, transparent 25%),
                              linear-gradient(-45deg, #f0f0f0 25%, transparent 25%),
                              linear-gradient(45deg, transparent 75%, #f0f0f0 75%),
                              linear-gradient(-45deg, transparent 75%, #f0f0f0 75%);
            background-size: 20px 20px;
            background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
            animation: loading 1.5s infinite linear;
        }

        @keyframes loading {
            0% { background-position: 0 0, 0 10px, 10px -10px, -10px 0px; }
            100% { background-position: 20px 20px, 20px 30px, 30px 10px, 10px 20px; }
        }

        .lazy-image.loaded {
            animation: none;
            background: none;
        }

        /* Smooth fade-in for loaded images */
        .fade-in {
            opacity: 0;
            transition: opacity 0.3s ease-in-out;
        }

        .fade-in.loaded {
            opacity: 1;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<!-- Banner ad at the top of the page -->
<div class="mb-4">
    <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'homepage_hero','limit' => '1','class' => 'w-100']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'homepage_hero','limit' => '1','class' => 'w-100']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
</div>


<!-- Diamond Ads Section - 4 Column Cards -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header d-flex align-items-center">
                <i class="fas fa-gem me-2 text-primary"></i>
                <h6 class="m-0 fw-bold"><?php echo e(__('welcome.featured_places')); ?></h6>
            </div>
            <div class="card-body">
                <!-- Enhanced Responsive Grid: Mobile(1), Tablet(2), Desktop(3), Large(4) -->
                <div class="row g-3 g-md-4" id="featured-locations-grid">
                    <style>
                        /* Custom responsive grid for featured locations */
                        #featured-locations-grid .col {
                            flex: 0 0 100%; /* Mobile: 1 column */
                        }

                        @media (min-width: 576px) {
                            #featured-locations-grid .col {
                                flex: 0 0 50%; /* Small tablets: 2 columns */
                            }
                        }

                        @media (min-width: 768px) {
                            #featured-locations-grid .col {
                                flex: 0 0 33.333333%; /* Tablets: 3 columns */
                            }
                        }

                        @media (min-width: 992px) {
                            #featured-locations-grid .col {
                                flex: 0 0 25%; /* Desktop: 4 columns */
                            }
                        }

                        @media (min-width: 1400px) {
                            #featured-locations-grid .col {
                                flex: 0 0 20%; /* Large screens: 5 columns */
                            }
                        }
                    </style>
                    <?php $__empty_1 = true; $__currentLoopData = $diamondAds; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $zoneAd): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <?php
                            $location = $zoneAd->location;
                            $tier = 'diamond'; // Default tier
                            if ($zoneAd->ad && $zoneAd->ad->custom_fields) {
                                $customFields = json_decode($zoneAd->ad->custom_fields, true);
                                $tier = $customFields['tier'] ?? 'diamond';
                            }

                            // Set badge and background color based on tier
                            $badgeClass = 'bg-info';
                            $bgColor = '#EBF5FB';
                            $badgeText = __('welcome.diamond');

                            if ($tier == 'gold') {
                                $badgeClass = 'bg-warning text-dark';
                                $bgColor = '#FFF8E1';
                                $badgeText = __('welcome.gold');
                            } elseif ($tier == 'silver') {
                                $badgeClass = 'bg-secondary';
                                $bgColor = '#FAFAFA';
                                $badgeText = __('welcome.silver');
                            } elseif ($tier == 'bronze') {
                                $badgeClass = 'bg-secondary text-white';
                                $bgColor = '#EFEBE9';
                                $badgeText = __('welcome.bronze');
                            }

                            // Working hours
                            $workingHours = $location->working_hours ?? __('welcome.24_hours');

                            // Distance (if available)
                            $distance = $location->distance ?? 17;

                            // Travel time (if available)
                            $travelTime = $location->drive_time ?? 18;

                            // Status (open/closed)
                            $isOpen = true;
                            if ($location->status == 'closed') {
                                $isOpen = false;
                            }

                            // Amenities/features (if available)
                            $amenities = [];
                            if ($location->amenities) {
                                $amenitiesData = json_decode($location->amenities, true);
                                if (is_array($amenitiesData)) {
                                    $amenities = array_slice($amenitiesData, 0, 3);
                                }
                            } else {
                                // Default amenities if none are available
                                $amenities = [__('welcome.pool'), __('welcome.special_services'), __('welcome.restaurant')];
                            }

                            // Star rating
                            $stars = $location->star_rating ?? 5;
                        ?>

                        <div class="col">
                            <div class="card card-optimized h-100 fade-in-up" style="border-radius: 15px; overflow: hidden; position: relative;">
                                <!-- Gradient overlay for modern look -->
                                <div class="position-absolute w-100 h-100" style="background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.05) 100%); z-index: 1; pointer-events: none;"></div>

                                <div class="card-header text-center py-3 position-relative" style="background: linear-gradient(135deg, <?php echo e($bgColor); ?> 0%, <?php echo e($bgColor); ?>dd 100%); border: none; z-index: 2;">
                                    <div class="d-flex justify-content-center align-items-center mb-2">
                                        <span class="badge <?php echo e($badgeClass); ?> px-3 py-2" style="font-size: 0.85rem; border-radius: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.15);">
                                            <i class="fas fa-gem me-1"></i><?php echo e($badgeText); ?>

                                        </span>
                                    </div>
                                    <h5 class="card-title mb-0 fw-bold" style="color: #2c3e50; text-shadow: 0 1px 2px rgba(255,255,255,0.8);">
                                        <?php echo e($location->getTranslatedTitle(app()->getLocale())); ?>

                                    </h5>
                                </div>
                                <div class="card-body p-4 position-relative" style="z-index: 2;">
                                    <!-- Info items with modern styling -->
                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #ff6b6b, #ee5a52); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-map-marker-alt text-white" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.distance')); ?></small>
                                            <span class="fw-semibold"><?php echo e(formatNumber($distance)); ?> <?php echo e(__('welcome.kilometers')); ?></span>
                                        </div>
                                    </div>

                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #4ecdc4, #44a08d); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-car text-white" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.drive_time')); ?></small>
                                            <span class="fw-semibold"><?php echo e(formatNumber($travelTime)); ?> <?php echo e(__('welcome.minutes')); ?></span>
                                        </div>
                                    </div>

                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #a8edea, #fed6e3); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-clock text-dark" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.working_hours')); ?></small>
                                            <span class="fw-semibold"><?php echo e($workingHours); ?></span>
                                        </div>
                                    </div>

                                    <!-- Action button with modern styling -->
                                    <div class="text-center mt-4">
                                        <?php if($location->phone): ?>
                                            <a href="tel:<?php echo e($location->phone); ?>" class="btn btn-modern btn-primary-modern w-100">
                                                <i class="fas fa-phone me-2"></i>
                                                <?php echo e(__('welcome.direct_call')); ?>

                                            </a>
                                        <?php elseif($isOpen): ?>
                                            <div class="status-badge open p-3 rounded" style="background: linear-gradient(135deg, #d4edda, #c3e6cb); border: 1px solid #b8daff;">
                                                <i class="fas fa-door-open text-success me-2"></i>
                                                <span class="fw-semibold text-success"><?php echo e(__('welcome.open')); ?></span>
                                            </div>
                                        <?php else: ?>
                                            <div class="status-badge closed p-3 rounded" style="background: linear-gradient(135deg, #f8d7da, #f1b0b7); border: 1px solid #f5c6cb;">
                                                <i class="fas fa-door-closed text-danger me-2"></i>
                                                <span class="fw-semibold text-danger"><?php echo e(__('welcome.closed')); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-footer border-0 p-3" style="background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(248,249,250,0.9) 100%); backdrop-filter: blur(10px);">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <!-- Rating section -->
                                        <?php if($stars > 0): ?>
                                            <div class="rating-section">
                                                <div class="d-flex align-items-center">
                                                    <?php for($i = 1; $i <= 5; $i++): ?>
                                                        <i class="fas fa-star <?php echo e($i <= $stars ? 'text-warning' : 'text-muted'); ?>" style="font-size: 0.8rem;"></i>
                                                    <?php endfor; ?>
                                                    <span class="ms-2 small fw-semibold text-dark"><?php echo e(formatNumber($stars)); ?></span>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="rating-section">
                                                <span class="small text-muted"><?php echo e(__('welcome.no_rating')); ?></span>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Amenities section -->
                                        <div class="amenities-section d-flex gap-1">
                                            <?php $__currentLoopData = array_slice($amenities, 0, 2); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $amenity): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <span class="badge rounded-pill" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; font-size: 0.7rem; padding: 4px 8px;">
                                                    <?php echo e($amenity); ?>

                                                </span>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php if(count($amenities) > 2): ?>
                                                <span class="badge rounded-pill bg-secondary" style="font-size: 0.7rem; padding: 4px 8px;">
                                                    +<?php echo e(count($amenities) - 2); ?>

                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <!-- Display static demo cards if no diamond ads are available -->
                        <!-- Demo card 1: Qeshm International Hotel - Diamond -->
                        <div class="col">
                            <div class="card card-optimized h-100 fade-in-up" style="border-radius: 15px; overflow: hidden; position: relative;">
                                <!-- Gradient overlay for modern look -->
                                <div class="position-absolute w-100 h-100" style="background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.05) 100%); z-index: 1; pointer-events: none;"></div>

                                <div class="card-header text-center py-3 position-relative" style="background: linear-gradient(135deg, #EBF5FB 0%, #EBF5FBdd 100%); border: none; z-index: 2;">
                                    <div class="d-flex justify-content-center align-items-center mb-2">
                                        <span class="badge bg-info px-3 py-2" style="font-size: 0.85rem; border-radius: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.15);">
                                            <i class="fas fa-gem me-1"></i><?php echo e(__('welcome.diamond')); ?>

                                        </span>
                                    </div>
                                    <h5 class="card-title mb-0 fw-bold" style="color: #2c3e50; text-shadow: 0 1px 2px rgba(255,255,255,0.8);">
                                        <?php echo e(__('welcome.demo_hotel_1')); ?>

                                    </h5>
                                </div>
                                <div class="card-body p-4 position-relative" style="z-index: 2;">
                                    <!-- Info items with modern styling -->
                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #ff6b6b, #ee5a52); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-map-marker-alt text-white" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.distance')); ?></small>
                                            <span class="fw-semibold"><?php echo e(number_format(17, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?> <?php echo e(__('welcome.kilometers')); ?></span>
                                        </div>
                                    </div>

                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #4ecdc4, #44a08d); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-car text-white" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.drive_time')); ?></small>
                                            <span class="fw-semibold"><?php echo e(number_format(18, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?> <?php echo e(__('welcome.minutes')); ?></span>
                                        </div>
                                    </div>

                                    <div class="info-item d-flex align-items-center mb-3 p-2 rounded" style="background: rgba(255,255,255,0.7); backdrop-filter: blur(10px);">
                                        <div class="icon-wrapper me-3" style="width: 35px; height: 35px; background: linear-gradient(135deg, #a8edea, #fed6e3); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-clock text-dark" style="font-size: 0.9rem;"></i>
                                        </div>
                                        <div>
                                            <small class="text-muted d-block"><?php echo e(__('welcome.working_hours')); ?></small>
                                            <span class="fw-semibold"><?php echo e(__('welcome.24_hours')); ?></span>
                                        </div>
                                    </div>

                                    <!-- Action button with modern styling -->
                                    <div class="text-center mt-4">
                                        <a href="#" class="btn btn-modern btn-primary-modern w-100">
                                            <i class="fas fa-phone me-2"></i>
                                            <?php echo e(__('welcome.direct_call')); ?>

                                        </a>
                                    </div>
                                </div>
                                <div class="card-footer border-0 p-3" style="background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(248,249,250,0.9) 100%); backdrop-filter: blur(10px);">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <!-- Rating section -->
                                        <div class="rating-section">
                                            <div class="d-flex align-items-center">
                                                <?php for($i = 1; $i <= 5; $i++): ?>
                                                    <i class="fas fa-star text-warning" style="font-size: 0.8rem;"></i>
                                                <?php endfor; ?>
                                                <span class="ms-2 small fw-semibold text-dark">۵</span>
                                            </div>
                                        </div>

                                        <!-- Amenities section -->
                                        <div class="amenities-section d-flex gap-1">
                                            <span class="badge rounded-pill" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; font-size: 0.7rem; padding: 4px 8px;">
                                                <?php echo e(__('welcome.pool')); ?>

                                            </span>
                                            <span class="badge rounded-pill" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; font-size: 0.7rem; padding: 4px 8px;">
                                                <?php echo e(__('welcome.restaurant')); ?>

                                            </span>
                                            <span class="badge rounded-pill bg-secondary" style="font-size: 0.7rem; padding: 4px 8px;">
                                                +1
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Demo card 2: Persian Gulf Hotel Qeshm - Silver -->
                        <div class="col">
                            <div class="card h-100" style="border-radius: 10px; overflow: hidden; border: 1px solid #e0e0e0;">
                                <div class="card-header text-center py-2" style="background-color: #FAFAFA;">
                                    <span class="badge bg-secondary"><?php echo e(__('welcome.silver')); ?></span>
                                    <h5 class="card-title mt-2 mb-0"><?php echo e(__('welcome.demo_hotel_2')); ?></h5>
                                </div>
                                <div class="card-body p-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-map-marker-alt text-danger me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.distance')); ?>: <?php echo e(number_format(17, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?> <?php echo e(__('welcome.kilometers')); ?></span>
                                    </div>
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-car text-info me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.drive_time')); ?>: <?php echo e(number_format(18, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?> <?php echo e(__('welcome.minutes')); ?></span>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-clock text-secondary me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.working_hours')); ?>: <?php echo e(__('welcome.24_hours')); ?></span>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <span class="badge bg-light text-dark p-2">
                                            <i class="fas fa-door-open text-primary me-1"></i>
                                            <?php echo e(__('welcome.open')); ?>

                                        </span>
                                    </div>
                                </div>
                                <div class="card-footer bg-white border-top-0 text-center p-2">
                                    <a href="#" class="btn btn-sm btn-outline-primary rounded-pill">
                                        <i class="fas fa-info-circle me-1"></i>
                                        <?php echo e(__('welcome.view_details')); ?>

                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- Demo card 3: Darius Hotel Qeshm - Gold -->
                        <div class="col">
                            <div class="card h-100" style="border-radius: 10px; overflow: hidden; border: 1px solid #e0e0e0;">
                                <div class="card-header text-center py-2" style="background-color: #FFF8E1;">
                                    <span class="badge bg-warning text-dark"><?php echo e(__('welcome.gold')); ?></span>
                                    <h5 class="card-title mt-2 mb-0"><?php echo e(__('welcome.demo_hotel_3')); ?></h5>
                                </div>
                                <div class="card-body p-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-map-marker-alt text-danger me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.distance')); ?>: <?php echo e(number_format(34, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?> <?php echo e(__('welcome.kilometers')); ?></span>
                                    </div>
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-car text-info me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.drive_time')); ?>: ۳۵ <?php echo e(__('welcome.minutes')); ?></span>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-clock text-secondary me-2"></i>
                                        <span class="text-muted small"><?php echo e(__('welcome.working_hours')); ?>: ۷:۰۰ - ۲۳:۰۰</span>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <span class="badge bg-light text-dark p-2">
                                            <i class="fas fa-door-closed text-danger me-1"></i>
                                            <?php echo e(__('welcome.closed')); ?>

                                        </span>
                                    </div>
                                </div>
                                <div class="card-footer bg-white border-top-0 text-center p-2">
                                    <a href="#" class="btn btn-sm btn-outline-primary rounded-pill">
                                        <i class="fas fa-info-circle me-1"></i>
                                        <?php echo e(__('welcome.view_details')); ?>

                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-search me-1"></i>
                <?php echo e(__('messages.search_and_filter_locations')); ?>

            </div>
            <div class="card-body">
                <form id="search-form" class="row g-3">
                    <!-- Search element has been moved above the map -->
                    <div class="col-md-12">
                        <h6 class="fw-bold mb-3"><?php echo e(__('messages.filter_by_geography')); ?></h6>
                        <div class="row geo-filters">
                            <div class="col-6 col-lg-2 mb-3">
                            <?php
                                $countryCount = isset($countries) ? count($countries) : 0;
                                $locale = app()->getLocale();
                                $labels = [
                                    'fa' => [
                                        'country' => 'کشور',
                                        'province' => 'استان',
                                        'county' => 'شهرستان',
                                        'district' => 'بخش',
                                        'city' => 'شهر',
                                        'village' => 'روستا',
                                        'zone' => 'منطقه',
                                    ],
                                    'en' => [
                                        'country' => 'Country',
                                        'province' => 'Province',
                                        'county' => 'County',
                                        'district' => 'District',
                                        'city' => 'City',
                                        'village' => 'Village',
                                        'zone' => 'Zone',
                                    ]
                                ];
                                $label = $labels[$locale] ?? $labels['fa'];
                            ?>
                            <label for="country-select" class="form-label">
                                <?php echo e(__('messages.country')); ?> (<?php echo e($countryCount); ?>)
                            </label>
                            <select class="form-select geo-select country-flag-select" id="country-select" name="country">
                                <option value=""><?php echo e(__('messages.all_countries')); ?></option>
                                <?php
                                    \Log::info('Countries data:', ['countries' => $countries->toArray()]);
                                ?>
                                <?php $__currentLoopData = $countries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $country): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($country->id); ?>"
                                        data-flag-url="https://flagcdn.com/24x18/<?php echo e(strtolower($country->iso_code)); ?>.png"
                                        data-name="<?php echo e($country->name); ?>"
                                        data-count="<?php echo e($country->location_count); ?>">
                                        <?php echo e($country->name); ?> (<?php echo e(number_format($country->location_count, 0, '.', ',')); ?>)
                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="province-container" style="display: none;">
                                <label for="province-select" class="form-label"><?php echo e(__('messages.province')); ?></label>
                                <select class="form-select geo-select" id="province-select" name="province">
                                    <option value=""><?php echo e(__('messages.all_provinces')); ?></option>
                                </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="county-container" style="display: none;">
                                <label for="county-select" class="form-label"><?php echo e(__('messages.county')); ?></label>
                                <select class="form-select geo-select" id="county-select" name="county">
                                    <option value=""><?php echo e(__('messages.all_counties')); ?></option>
                                </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="district-container" style="display: none;">
                                <label for="district-select" class="form-label"><?php echo e(__('messages.district')); ?></label>
                                <select class="form-select geo-select" id="district-select" name="district">
                                    <option value=""><?php echo e(__('messages.all_districts')); ?></option>
                                </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="city-container" style="display: none;">
                                <label for="city-select" class="form-label"><?php echo e(__('messages.city')); ?></label>
                                <select class="form-select geo-select" id="city-select" name="city">
                                    <option value=""><?php echo e(__('messages.all_cities')); ?></option>
                                </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="village-container" style="display: none;">
                                <label for="village-select" class="form-label"><?php echo e(__('messages.village')); ?></label>
                                <select class="form-select geo-select" id="village-select" name="village">
                                    <option value=""><?php echo e(__('messages.all_villages')); ?></option>
                                </select>
                            </div>
                            <div class="col-6 col-lg-2 mb-3 geo-step" id="zone-container" style="display: none;">
                                <label for="zone-select" class="form-label"><?php echo e(__('messages.zone')); ?></label>
                                <select class="form-select geo-select" id="zone-select" name="zone">
                                    <option value=""><?php echo e(__('messages.all_zones')); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12 mt-3">
                        <button type="button" id="reset-search" class="btn btn-secondary">
                            <i class="fas fa-redo me-1"></i>
                            <?php echo e(__('messages.reset_filters')); ?>

                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid mt-4">
    <div class="row">
        <!-- Main content -->
        <div class="col-lg-9">
            <!-- Hero ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'homepage_hero','limit' => '1','class' => 'w-100 mb-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'homepage_hero','limit' => '1','class' => 'w-100 mb-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>

            <!-- Categories section -->
            <!-- Enhanced Professional Category Filter -->
            <div class="card shadow-lg mb-4 modern-category-filter-card">
                <div class="card-header modern-gradient-header border-0">
                    <div class="d-flex align-items-center justify-content-between">
                        <h6 class="m-0 fw-bold text-white d-flex align-items-center">
                            <i class="fas fa-layer-group me-2"></i>
                            <?php echo e(__('messages.filter_by_category')); ?>

                        </h6>
                        <div class="header-actions d-flex align-items-center gap-2">
                            <span class="badge bg-light text-dark" id="active-category-count">0</span>
                            <button class="btn btn-sm btn-outline-light" id="clear-filter" title="<?php echo e(__('messages.clear_filters')); ?>">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <!-- Category Search -->
                    <div class="category-search-container p-3 border-bottom bg-light">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text bg-white border-end-0">
                                <i class="fas fa-search text-muted"></i>
                            </span>
                            <input type="text" class="form-control border-start-0" id="category-search"
                                   placeholder="<?php echo e(__('messages.search_categories')); ?>" autocomplete="off">
                        </div>
                    </div>

                    <!-- Category filter container -->
                    <div class="category-filter-container">
                        <div class="category-filter-content">
                            <!-- Parent categories and children from database -->
                            <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="category-filter-item" data-category-name="<?php echo e(strtolower($category->getTranslatedName(app()->getLocale()))); ?>">
                                    <div class="parent-category modern-category-item" data-category-id="<?php echo e($category->id); ?>">
                                        <div class="category-content">
                                            <div class="category-icon-wrapper">
                                                <?php if($category->emoji): ?>
                                                    <span class="category-emoji"><?php echo e($category->emoji); ?></span>
                                                <?php elseif($category->font_icon): ?>
                                                    <i class="fas fa-<?php echo e($category->font_icon); ?> category-icon"></i>
                                                <?php else: ?>
                                                    <i class="fas fa-tag category-icon"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div class="category-info">
                                                <span class="category-name"><?php echo e($category->getTranslatedName(app()->getLocale())); ?></span>
                                                <?php if($category->children && $category->children->count() > 0): ?>
                                                    <small class="subcategory-hint text-muted"><?php echo e($category->children->count()); ?> <?php echo e(__('messages.subcategories')); ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="category-meta">
                                            <span class="category-count badge bg-primary"><?php echo e(number_format($category->location_count, 0, '.', app()->getLocale() === 'fa' ? ',' : '.')); ?></span>
                                            <?php if($category->children && $category->children->count() > 0): ?>
                                                <i class="fas fa-chevron-down expand-icon"></i>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php if($category->children && $category->children->count() > 0): ?>
                                        <div class="children-container hidden">
                                            <div class="children-wrapper">
                                                <?php $__currentLoopData = $category->children; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <div class="child-category modern-subcategory-item" data-category-id="<?php echo e($child->id); ?>" data-category-name="<?php echo e(strtolower($child->getTranslatedName(app()->getLocale()))); ?>">
                                                        <div class="subcategory-content">
                                                            <div class="subcategory-icon-wrapper">
                                                                <?php if($child->emoji): ?>
                                                                    <span class="category-emoji"><?php echo e($child->emoji); ?></span>
                                                                <?php elseif($child->font_icon): ?>
                                                                    <i class="fas fa-<?php echo e($child->font_icon); ?> category-icon"></i>
                                                                <?php else: ?>
                                                                    <i class="fas fa-circle category-icon"></i>
                                                                <?php endif; ?>
                                                            </div>
                                                            <span class="subcategory-name"><?php echo e($child->getTranslatedName(app()->getLocale())); ?></span>
                                                        </div>
                                                        <span class="category-count badge bg-secondary"><?php echo e($child->location_count); ?></span>
                                                    </div>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>

                        <!-- No results message -->
                        <div class="no-categories-found d-none p-4 text-center text-muted">
                            <i class="fas fa-search mb-2 d-block" style="font-size: 2rem; opacity: 0.5;"></i>
                            <p class="mb-0"><?php echo e(__('messages.no_categories_found')); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Middle ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'homepage_middle','limit' => '1','class' => 'w-100 my-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'homepage_middle','limit' => '1','class' => 'w-100 my-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>

            <!-- Featured section -->
            <div class="card shadow mb-4">
                <div class="card-header">
                    <i class="fas fa-map-marker-alt me-1"></i>
                    <?php echo e(__('messages.map_of_locations')); ?>

                    <div class="float-end">
                        <span id="locations-count" class="badge bg-primary"></span>
                    </div>
                </div>
                <div class="card-body">
                    <div class="col-md-12 mb-4">
                        <!-- Enhanced Search Section -->
                        <div class="search-container position-relative">
                            <div class="input-group shadow-sm" style="border-radius: 15px; overflow: hidden;">
                                <span class="input-group-text border-0" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">
                                    <i class="fas fa-search"></i>
                                </span>
                                <input type="text"
                                       class="form-control form-control-modern border-0"
                                       id="search-input"
                                       name="q"
                                       placeholder="<?php echo e(__('messages.search_placeholder')); ?>"
                                       style="font-size: 16px; padding: 15px 20px; background: rgba(255,255,255,0.95);"
                                       autocomplete="off">
                                <button class="btn btn-modern btn-primary-modern border-0" type="submit" style="padding: 0 25px;">
                                    <i class="fas fa-search me-2"></i>
                                    <?php echo e(__('messages.search')); ?>

                                </button>
                            </div>

                            <!-- Search suggestions dropdown -->
                            <div id="search-suggestions" class="position-absolute w-100 bg-white rounded-3 shadow-lg d-none" style="top: 100%; z-index: 1000; max-height: 300px; overflow-y: auto; border: 1px solid #e0e0e0;">
                                <!-- Suggestions will be populated by JavaScript -->
                            </div>

                            <!-- Search stats -->
                            <div class="search-stats mt-2 text-center">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    <span id="search-stats-text"><?php echo e(__('messages.search_help')); ?></span>
                                </small>
                            </div>
                        </div>
                    </div>
                    <div id="map-loading" class="map-loading d-none">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden"><?php echo e(__('messages.loading')); ?></span>
                        </div>
                    </div>
                    <div id="map" style="height: 500px; width: 100%;"></div>
                    <div class="location-list-container mt-4">
                        <div class="row">
                            <!-- ستون فیلتر دسته‌بندی‌ها (انتقال تب‌ها به این ستون) -->
                            <div class="col-lg-3 col-md-4 mb-3 order-2 order-md-1">
                                <div class="card h-100 location-child-categories-sidebar">
                                    <div class="card-header bg-light fw-bold">
                                        <i class="fas fa-layer-group me-1"></i> <?php echo e(__('messages.categories')); ?>

                                    </div>
                                    <div class="card-body p-2">
                                    <ul class="nav nav-pills flex-column location-tabs" id="location-tabs" role="tablist">
                                        <!-- تب‌های دسته‌بندی به صورت پویا اضافه می‌شوند -->
                                    </ul>
                                </div>
                                </div>
                            </div>
                            <!-- ستون لیست مکان‌ها -->
                            <div class="col-lg-9 col-md-8 order-1 order-md-2">
                                <!-- ردیف بالای لیست: موقعیت و مرتب‌سازی -->
                                <div class="d-flex flex-wrap align-items-center justify-content-between mb-3 gap-2">
                                    <div class="user-location-card flex-grow-1 mb-0">
                                        <div class="card h-100">
                                            <div class="card-body text-center p-2">
                                                <h6 class="mb-2"><i class="fas fa-map-marker-alt me-2 text-danger"></i><?php echo e(__('messages.your_location')); ?></h6>
                                                <button id="get-user-location" class="btn btn-sm btn-primary w-100 mb-1">
                                                    <i class="fas fa-location-arrow me-2"></i><?php echo e(__('messages.get_my_location')); ?>

                                                </button>
                                                <div id="user-location-status" class="small text-muted mt-1 d-none">
                                                    <?php echo e(__('messages.loading')); ?>

                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="sorting-options card mb-0" style="min-width:220px;">
                                        <div class="card-body p-2">
                                            <h6 class="mb-2"><i class="fas fa-sort me-2"></i><?php echo e(__('messages.sort_by')); ?></h6>
                                            <select id="sort-locations" class="form-select form-select-sm">
                                            <option value="distance" selected><?php echo e(__('messages.sort_by_distance')); ?></option>
                                            <option value="name"><?php echo e(__('messages.sort_by_name')); ?></option>
                                            <option value="category"><?php echo e(__('messages.sort_by_category')); ?></option>
                                        </select>
                                    </div>
                                </div>
                                </div>
                                <!-- ردیف دوم: فیلتر فاصله -->
                                <div class="distance-filter card mb-3 w-100">
                                    <div class="card-body p-2">
                                        <h6 class="mb-2"><i class="fas fa-road me-2"></i><?php echo e(__('messages.distance_range')); ?></h6>
                                        <div class="d-flex align-items-center flex-wrap gap-2">
                                            <span><?php echo e(__('messages.max')); ?></span>
                                            <input type="range" class="form-range mx-2 flex-grow-1" id="distance-range" min="1" max="100" value="<?php echo e(\App\Helpers\NumberHelper::formatNumber(50)); ?>">
                                            <span id="distance-value"><?php echo e(\App\Helpers\NumberHelper::formatNumber(50)); ?></span>
                                            <span class="ms-1"><?php echo e(__('messages.kilometer')); ?></span>
                                        </div>
                                        <!-- کنترل محدودیت مسیر -->
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="unlimited-distance" checked>
                                            <label class="form-check-label" for="unlimited-distance"><?php echo e(__('messages.show_unlimited_distances')); ?></label>
                                        </div>
                                        <div class="route-distance-limit d-none">
                                            <div class="d-flex align-items-center">
                                                <span><?php echo e(__('messages.route_distance_limit')); ?></span>
                                                <input type="range" class="form-range mx-2" id="route-distance-range" min="500" max="10000" step="500" value="<?php echo e(\App\Helpers\NumberHelper::formatNumber(2000)); ?>">
                                                <span id="route-distance-value"><?php echo e(\App\Helpers\NumberHelper::formatNumber(2000)); ?></span>
                                                <span class="ms-1"><?php echo e(__('messages.kilometer')); ?></span>
                                            </div>
                                            <div class="small text-muted mt-1">
                                                <i class="fas fa-info-circle me-1"></i>
                                                <?php echo e(__('messages.route_direct_for_longer')); ?>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- لیست مکان‌ها و تب دسته‌بندی‌ها زیر نقشه -->
                                <div class="tab-content" id="location-tabs-content">
                                    <div class="tab-pane fade show active" id="all-locations" role="tabpanel" aria-labelledby="all-locations-tab">

                                        <div class="location-list row row-cols-1 row-cols-md-2 g-3"></div>
                                        <div id="no-results" class="alert alert-warning text-center mt-3 d-none">هیچ مکانی یافت نشد.</div>
                                        <div id="location-template" class="d-none location-item col">
                                                <div class="location-item-inner">
                                                <div class="d-flex align-items-center mb-2">
                                                    <span class="location-name fw-bold"></span>
                                                    </div>
                                                    <div class="location-categories mb-2"></div>
                                                <div class="location-address text-muted mb-2"></div>
                                                <div class="location-distance d-none mb-2"><i class="fas fa-road me-1"></i> <span class="distance-value"></span></div>
                                                <div class="transport-options d-flex gap-2 mb-2">
                                                    <span class="transport-option transport-walking d-none"><i class="fas fa-walking me-1"></i> <span class="transport-time"></span></span>
                                                    <span class="transport-option transport-driving d-none"><i class="fas fa-car me-1"></i> <span class="transport-time"></span></span>
                                                    <span class="transport-option transport-bus d-none"><i class="fas fa-bus me-1"></i> <span class="transport-time"></span></span>
                                                    </div>
                                                <div class="location-actions d-none mt-2">
                                                    <button class="btn btn-sm btn-outline-primary get-directions"><i class="fas fa-directions me-1"></i> <?php echo e(__('messages.route')); ?></button>
                                                    <a class="btn btn-sm btn-outline-success open-google-maps d-none" target="_blank"><i class="fab fa-google me-1"></i> <?php echo e(__('messages.google_map')); ?></a>
                                                </div>
                                            </div>
                                            </div>
                                        <div class="text-center mt-3">
                                            <button id="load-more-locations" class="btn btn-outline-primary d-none">
                                                <span id="load-more-text"><?php echo e(__('messages.load_more')); ?></span>
                                                <span id="load-more-spinner" class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                                            </button>
                                        </div>
                                    </div>
                                    <!-- تب‌های دسته‌بندی به صورت پویا اضافه می‌شوند -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Featured ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'homepage_featured','limit' => '1','class' => 'w-100 my-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'homepage_featured','limit' => '1','class' => 'w-100 my-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>

            <!-- Bottom ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'homepage_bottom','limit' => '2','class' => 'w-100 mt-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'homepage_bottom','limit' => '2','class' => 'w-100 mt-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-3">
            <!-- Sidebar top ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'sidebar_top','limit' => '1','class' => 'w-100 mb-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'sidebar_top','limit' => '1','class' => 'w-100 mb-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>

            <!-- Other sidebar content -->
            <!-- Enhanced Dynamic Filters Card -->
            <div class="card card-optimized shadow mb-4 modern-filter-card">
                <div class="card-header py-3 modern-gradient-header">
                    <h6 class="m-0 fw-bold d-flex align-items-center text-white">
                        <i class="fas fa-sliders-h me-2"></i>
                        <?php echo e(__('messages.advanced_filters')); ?>

                        <span class="badge bg-light text-dark ms-auto" id="active-filters-count">0</span>
                    </h6>
                </div>
                <div class="card-body p-3">
                    <!-- Dynamic Category Filter -->
                    <div class="filter-section mb-4">
                        <label class="form-label fw-semibold mb-3 modern-label">
                            <i class="fas fa-tags me-2 text-primary"></i>
                            <?php echo e(__('messages.filter_by_category')); ?>

                        </label>
                        <div class="category-filters modern-filter-group">
                            <div class="form-check mb-2 modern-radio-item">
                                <input class="form-check-input modern-radio" type="radio" name="categoryFilter" id="cat-all" value="all" checked>
                                <label class="form-check-label modern-radio-label d-flex justify-content-between align-items-center" for="cat-all">
                                    <span class="filter-option-content">
                                        <i class="fas fa-globe me-2 filter-icon"></i>
                                        <span class="filter-text"><?php echo e(__('messages.all_categories')); ?></span>
                                    </span>
                                    <span class="badge modern-badge" id="count-all">
                                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                                        <span class="count-text">0</span>
                                    </span>
                                </label>
                            </div>
                            <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="form-check mb-2 modern-radio-item">
                                    <input class="form-check-input modern-radio" type="radio" name="categoryFilter" id="cat-<?php echo e($category->id); ?>" value="<?php echo e($category->id); ?>">
                                    <label class="form-check-label modern-radio-label d-flex justify-content-between align-items-center" for="cat-<?php echo e($category->id); ?>">
                                        <span class="filter-option-content">
                                            <?php if($category->emoji): ?>
                                                <span class="me-2 filter-emoji"><?php echo e($category->emoji); ?></span>
                                            <?php elseif($category->font_icon): ?>
                                                <i class="fas fa-<?php echo e($category->font_icon); ?> me-2 filter-icon"></i>
                                            <?php else: ?>
                                                <i class="fas fa-tag me-2 filter-icon"></i>
                                            <?php endif; ?>
                                            <span class="filter-text"><?php echo e($category->getTranslatedName(app()->getLocale())); ?></span>
                                        </span>
                                        <span class="badge modern-badge" id="count-<?php echo e($category->id); ?>">
                                            <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                                            <span class="count-text"><?php echo e($category->location_count ?? 0); ?></span>
                                        </span>
                                    </label>
                                </div>
                                <?php if($category->children && $category->children->count() > 0): ?>
                                    <div class="subcategory-container ms-3 d-none" id="subcats-<?php echo e($category->id); ?>">
                                        <?php $__currentLoopData = $category->children; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <div class="form-check mb-1 modern-radio-item subcategory-item">
                                                <input class="form-check-input modern-radio" type="radio" name="categoryFilter" id="cat-<?php echo e($child->id); ?>" value="<?php echo e($child->id); ?>">
                                                <label class="form-check-label modern-radio-label d-flex justify-content-between align-items-center" for="cat-<?php echo e($child->id); ?>">
                                                    <span class="filter-option-content">
                                                        <?php if($child->emoji): ?>
                                                            <span class="me-2 filter-emoji"><?php echo e($child->emoji); ?></span>
                                                        <?php elseif($child->font_icon): ?>
                                                            <i class="fas fa-<?php echo e($child->font_icon); ?> me-2 filter-icon"></i>
                                                        <?php else: ?>
                                                            <i class="fas fa-circle me-2 filter-icon small"></i>
                                                        <?php endif; ?>
                                                        <span class="filter-text"><?php echo e($child->getTranslatedName(app()->getLocale())); ?></span>
                                                    </span>
                                                    <span class="badge modern-badge small" id="count-<?php echo e($child->id); ?>">
                                                        <span class="count-text"><?php echo e($child->location_count ?? 0); ?></span>
                                                    </span>
                                                </label>
                                            </div>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>

                    <!-- Enhanced Rating Filter -->
                    <div class="filter-section mb-4">
                        <label class="form-label fw-semibold mb-3 modern-label">
                            <i class="fas fa-star me-2 text-warning"></i>
                            <?php echo e(__('messages.min_rating')); ?>

                        </label>
                        <div class="rating-filter-container">
                            <select class="form-select modern-select" id="rating-filter">
                                <option value=""><?php echo e(__('messages.any_rating')); ?></option>
                                <option value="5">⭐⭐⭐⭐⭐ <?php echo e(__('messages.5_stars')); ?></option>
                                <option value="4">⭐⭐⭐⭐ <?php echo e(__('messages.4_plus_stars')); ?></option>
                                <option value="3">⭐⭐⭐ <?php echo e(__('messages.3_plus_stars')); ?></option>
                                <option value="2">⭐⭐ <?php echo e(__('messages.2_plus_stars')); ?></option>
                                <option value="1">⭐ <?php echo e(__('messages.1_plus_stars')); ?></option>
                            </select>
                            <div class="rating-stats mt-2 small text-muted">
                                <span id="rating-stats"><?php echo e(__('messages.select_rating_to_see_stats')); ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Geographic Filter -->
                    <div class="filter-section mb-4">
                        <label class="form-label fw-semibold mb-3 modern-label">
                            <i class="fas fa-map-marker-alt me-2 text-success"></i>
                            <?php echo e(__('messages.location_filter')); ?>

                        </label>
                        <div class="geographic-filter-container">
                            <div class="mb-3">
                                <select class="form-select modern-select" id="dynamic-country-filter">
                                    <option value=""><?php echo e(__('messages.all_countries')); ?></option>
                                    <?php $__currentLoopData = $countries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $country): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($country->id); ?>" data-count="<?php echo e($country->location_count); ?>">
                                            <?php echo e($country->name); ?> (<?php echo e(number_format($country->location_count)); ?>)
                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="mb-3 d-none" id="province-filter-container">
                                <select class="form-select modern-select" id="dynamic-province-filter">
                                    <option value=""><?php echo e(__('messages.all_provinces')); ?></option>
                                </select>
                            </div>
                            <div class="mb-3 d-none" id="city-filter-container">
                                <select class="form-select modern-select" id="dynamic-city-filter">
                                    <option value=""><?php echo e(__('messages.all_cities')); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Status Filter -->
                    <div class="filter-section mb-4">
                        <label class="form-label fw-semibold mb-3 modern-label">
                            <i class="fas fa-clock me-2 text-info"></i>
                            <?php echo e(__('messages.status')); ?>

                        </label>
                        <div class="status-filter-container">
                            <div class="btn-group w-100 modern-btn-group" role="group">
                                <input type="radio" class="btn-check" name="statusFilter" id="status-all" value="" checked>
                                <label class="btn btn-outline-secondary modern-btn" for="status-all">
                                    <i class="fas fa-globe me-1"></i>
                                    <?php echo e(__('messages.any_status')); ?>

                                </label>

                                <input type="radio" class="btn-check" name="statusFilter" id="status-open" value="open">
                                <label class="btn btn-outline-success modern-btn" for="status-open">
                                    <i class="fas fa-check-circle me-1"></i>
                                    <?php echo e(__('messages.open_now')); ?>

                                </label>

                                <input type="radio" class="btn-check" name="statusFilter" id="status-closed" value="closed">
                                <label class="btn btn-outline-danger modern-btn" for="status-closed">
                                    <i class="fas fa-times-circle me-1"></i>
                                    <?php echo e(__('messages.closed_now')); ?>

                                </label>
                            </div>
                            <div class="status-stats mt-2 small text-muted">
                                <span id="status-stats"><?php echo e(__('messages.select_status_to_see_stats')); ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Distance Filter -->
                    <div class="filter-section mb-4">
                        <label class="form-label fw-semibold mb-3 modern-label">
                            <i class="fas fa-route me-2 text-primary"></i>
                            <?php echo e(__('messages.distance_range')); ?>

                        </label>
                        <div class="distance-filter-container">
                            <div class="range-slider-container">
                                <input type="range" class="form-range modern-range" id="distance-filter-range"
                                       min="1" max="200" value="50" step="5">
                                <div class="range-labels d-flex justify-content-between mt-1">
                                    <span class="small text-muted">1 <?php echo e(__('messages.km')); ?></span>
                                    <span class="fw-bold text-primary" id="distance-display">50 <?php echo e(__('messages.km')); ?></span>
                                    <span class="small text-muted">200+ <?php echo e(__('messages.km')); ?></span>
                                </div>
                            </div>
                            <div class="distance-presets mt-2">
                                <div class="btn-group w-100" role="group">
                                    <button type="button" class="btn btn-sm btn-outline-primary distance-preset" data-distance="5">5<?php echo e(__('messages.km')); ?></button>
                                    <button type="button" class="btn btn-sm btn-outline-primary distance-preset" data-distance="25">25<?php echo e(__('messages.km')); ?></button>
                                    <button type="button" class="btn btn-sm btn-outline-primary distance-preset" data-distance="50">50<?php echo e(__('messages.km')); ?></button>
                                    <button type="button" class="btn btn-sm btn-outline-primary distance-preset" data-distance="100">100<?php echo e(__('messages.km')); ?></button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Filter Actions -->
                    <div class="filter-actions">
                        <button type="button" class="btn modern-btn-primary w-100 mb-2" id="apply-filters">
                            <i class="fas fa-search me-2"></i>
                            <span class="btn-text"><?php echo e(__('messages.apply_filters')); ?></span>
                            <span class="spinner-border spinner-border-sm d-none ms-2" role="status"></span>
                        </button>
                        <button type="button" class="btn btn-outline-secondary w-100 mb-2" id="clear-filters">
                            <i class="fas fa-eraser me-2"></i>
                            <?php echo e(__('messages.clear_filters')); ?>

                        </button>
                        <div class="filter-summary mt-2 p-2 bg-light rounded small">
                            <div class="d-flex justify-content-between">
                                <span><?php echo e(__('messages.active_filters')); ?>:</span>
                                <span class="fw-bold" id="active-filters-summary"><?php echo e(__('messages.none')); ?></span>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span><?php echo e(__('messages.results_found')); ?>:</span>
                                <span class="fw-bold text-primary" id="results-count">0</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sidebar middle ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'sidebar_middle','limit' => '1','class' => 'w-100 mb-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'sidebar_middle','limit' => '1','class' => 'w-100 mb-4']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>

            <!-- More sidebar content if needed -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo e(__('messages.popular_locations')); ?></h6>
                </div>
                <div class="card-body">
                    <!-- Popular locations could go here -->
                </div>
            </div>

            <!-- More sidebar content if needed -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo e(__('messages.featured_locations')); ?></h6>
                </div>
                <div class="card-body">
                    <?php if($featuredLocations->count() > 0): ?>
                        <div class="list-group">
                            <?php $__currentLoopData = $featuredLocations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $location): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <a href="<?php echo e($location->getUrl()); ?>" class="list-group-item list-group-item-action">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1"><?php echo e($location->name); ?></h6>
                                        <small class="text-<?php echo e($location->package_type === 'diamond' ? 'danger' : ($location->package_type === 'gold' ? 'warning' : ($location->package_type === 'silver' ? 'secondary' : 'info'))); ?>">
                                            <?php echo e($location->package_type === 'diamond' ? __('messages.diamond') : ($location->package_type === 'gold' ? __('messages.gold') : ($location->package_type === 'silver' ? __('messages.silver') : __('messages.bronze')))); ?>

                                        </small>
                                    </div>
                                    <p class="mb-1"><?php echo e(Str::limit($location->description, 100)); ?></p>
                                    <small><?php echo e($location->city->name ?? ''); ?>, <?php echo e($location->province->name ?? ''); ?></small>
                                </a>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted mb-0"><?php echo e(__('messages.no_featured_locations')); ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo e(__('messages.diamond_locations')); ?></h6>
                </div>
                <div class="card-body">
                    <?php if($diamondLocations->count() > 0): ?>
                        <div class="list-group">
                            <?php $__currentLoopData = $diamondLocations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $location): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <a href="<?php echo e($location->getUrl()); ?>" class="list-group-item list-group-item-action">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1"><?php echo e($location->name); ?></h6>
                                        <small class="text-danger"><?php echo e(__('messages.diamond')); ?></small>
                                    </div>
                                    <p class="mb-1"><?php echo e(Str::limit($location->description, 100)); ?></p>
                                    <small><?php echo e($location->city->name ?? ''); ?>, <?php echo e($location->province->name ?? ''); ?></small>
                                </a>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted mb-0"><?php echo e(__('messages.no_diamond_locations')); ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Sidebar bottom ad -->
            <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'sidebar_bottom','limit' => '1','class' => 'w-100']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'sidebar_bottom','limit' => '1','class' => 'w-100']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
        </div>
    </div>
</div>

<!-- Footer ad -->
<div class="container-fluid mt-4">
    <?php if (isset($component)) { $__componentOriginalc9abd992bc9046643b03bbeb9676a25b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.advertisement','data' => ['position' => 'footer','limit' => '3','class' => 'w-100']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('advertisement'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['position' => 'footer','limit' => '3','class' => 'w-100']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $attributes = $__attributesOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__attributesOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b)): ?>
<?php $component = $__componentOriginalc9abd992bc9046643b03bbeb9676a25b; ?>
<?php unset($__componentOriginalc9abd992bc9046643b03bbeb9676a25b); ?>
<?php endif; ?>
</div>
    <!-- Mobile Bottom Navigation -->
    <div class="mobile-nav d-md-none">
        <div class="container-fluid">
            <div class="row text-center">
                <div class="col">
                    <a href="<?php echo e(url('/')); ?>" class="mobile-nav-item <?php echo e(request()->is('/') ? 'active' : ''); ?>">
                        <i class="fas fa-home"></i>
                        <span>خانه</span>
                    </a>
                </div>
                <div class="col">
                    <a href="#" class="mobile-nav-item" onclick="toggleMobileSearch()">
                        <i class="fas fa-search"></i>
                        <span>جستجو</span>
                    </a>
                </div>
                <div class="col">
                    <a href="#" class="mobile-nav-item" onclick="toggleMobileFilters()">
                        <i class="fas fa-filter"></i>
                        <span>فیلتر</span>
                    </a>
                </div>
                <div class="col">
                    <a href="#map" class="mobile-nav-item">
                        <i class="fas fa-map"></i>
                        <span>نقشه</span>
                    </a>
                </div>
                <div class="col">
                    <a href="#" class="mobile-nav-item" onclick="scrollToTop()">
                        <i class="fas fa-arrow-up"></i>
                        <span>بالا</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<!-- Lazy Loading Script -->
<script>
    // Intersection Observer for lazy loading
    document.addEventListener('DOMContentLoaded', function() {
        // Lazy loading for images
        const lazyImages = document.querySelectorAll('img[data-src]');

        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.classList.remove('lazy-image');
                        img.classList.add('fade-in');

                        img.onload = () => {
                            img.classList.add('loaded');
                        };

                        imageObserver.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px 0px',
                threshold: 0.01
            });

            lazyImages.forEach(img => {
                img.classList.add('lazy-image', 'fade-in');
                imageObserver.observe(img);
            });
        } else {
            // Fallback for browsers without IntersectionObserver
            lazyImages.forEach(img => {
                img.src = img.dataset.src;
                img.classList.add('loaded');
            });
        }

        // Performance monitoring
        if ('performance' in window) {
            window.addEventListener('load', () => {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('Page Load Performance:', {
                    'DOM Content Loaded': perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart,
                    'Load Complete': perfData.loadEventEnd - perfData.loadEventStart,
                    'Total Load Time': perfData.loadEventEnd - perfData.navigationStart
                });
            });
        }
    });
</script>

<!-- Enhanced Search Script -->
<script>
    // Smart Search Implementation
    class SmartSearch {
        constructor() {
            this.searchInput = document.getElementById('search-input');
            this.suggestionsContainer = document.getElementById('search-suggestions');
            this.searchStatsText = document.getElementById('search-stats-text');
            this.searchTimeout = null;
            this.currentSuggestions = [];
            this.selectedIndex = -1;

            this.init();
        }

        init() {
            if (!this.searchInput) return;

            // Event listeners
            this.searchInput.addEventListener('input', this.handleInput.bind(this));
            this.searchInput.addEventListener('keydown', this.handleKeydown.bind(this));
            this.searchInput.addEventListener('focus', this.handleFocus.bind(this));
            this.searchInput.addEventListener('blur', this.handleBlur.bind(this));

            // Click outside to close suggestions
            document.addEventListener('click', (e) => {
                if (!this.searchInput.contains(e.target) && !this.suggestionsContainer.contains(e.target)) {
                    this.hideSuggestions();
                }
            });
        }

        handleInput(e) {
            const query = e.target.value.trim();

            // Clear previous timeout
            if (this.searchTimeout) {
                clearTimeout(this.searchTimeout);
            }

            // Update search stats
            this.updateSearchStats(query);

            // Debounce search suggestions
            this.searchTimeout = setTimeout(() => {
                if (query.length >= 2) {
                    this.fetchSuggestions(query);
                } else {
                    this.hideSuggestions();
                }
            }, 300);
        }

        handleKeydown(e) {
            if (!this.suggestionsContainer.classList.contains('d-none')) {
                switch(e.key) {
                    case 'ArrowDown':
                        e.preventDefault();
                        this.navigateSuggestions(1);
                        break;
                    case 'ArrowUp':
                        e.preventDefault();
                        this.navigateSuggestions(-1);
                        break;
                    case 'Enter':
                        e.preventDefault();
                        this.selectCurrentSuggestion();
                        break;
                    case 'Escape':
                        this.hideSuggestions();
                        break;
                }
            }
        }

        handleFocus() {
            const query = this.searchInput.value.trim();
            if (query.length >= 2 && this.currentSuggestions.length > 0) {
                this.showSuggestions();
            }
        }

        handleBlur() {
            // Delay hiding to allow clicking on suggestions
            setTimeout(() => {
                this.hideSuggestions();
            }, 200);
        }

        async fetchSuggestions(query) {
            try {
                const response = await fetch(`/api/search-suggestions?q=${encodeURIComponent(query)}`);
                const data = await response.json();

                if (data.success) {
                    this.currentSuggestions = data.suggestions || [];
                    this.renderSuggestions();
                }
            } catch (error) {
                console.error('Error fetching suggestions:', error);
                this.hideSuggestions();
            }
        }

        renderSuggestions() {
            if (this.currentSuggestions.length === 0) {
                this.hideSuggestions();
                return;
            }

            let html = '';
            this.currentSuggestions.forEach((suggestion, index) => {
                const isSelected = index === this.selectedIndex;
                html += `
                    <div class="suggestion-item p-3 border-bottom ${isSelected ? 'bg-light' : ''}"
                         data-index="${index}"
                         style="cursor: pointer; transition: background-color 0.2s;">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-${this.getSuggestionIcon(suggestion.type)} me-3 text-muted"></i>
                            <div class="flex-grow-1">
                                <div class="fw-semibold">${this.highlightMatch(suggestion.title)}</div>
                                ${suggestion.subtitle ? `<small class="text-muted">${suggestion.subtitle}</small>` : ''}
                            </div>
                            <small class="text-muted">${suggestion.type_label}</small>
                        </div>
                    </div>
                `;
            });

            this.suggestionsContainer.innerHTML = html;
            this.showSuggestions();

            // Add click listeners
            this.suggestionsContainer.querySelectorAll('.suggestion-item').forEach(item => {
                item.addEventListener('click', () => {
                    const index = parseInt(item.dataset.index);
                    this.selectSuggestion(index);
                });
            });
        }

        getSuggestionIcon(type) {
            const icons = {
                'location': 'map-marker-alt',
                'category': 'tags',
                'city': 'city',
                'province': 'map'
            };
            return icons[type] || 'search';
        }

        highlightMatch(text) {
            const query = this.searchInput.value.trim();
            if (!query) return text;

            const regex = new RegExp(`(${query})`, 'gi');
            return text.replace(regex, '<mark class="bg-warning">$1</mark>');
        }

        navigateSuggestions(direction) {
            const maxIndex = this.currentSuggestions.length - 1;

            if (direction === 1) {
                this.selectedIndex = this.selectedIndex < maxIndex ? this.selectedIndex + 1 : 0;
            } else {
                this.selectedIndex = this.selectedIndex > 0 ? this.selectedIndex - 1 : maxIndex;
            }

            this.renderSuggestions();
        }

        selectCurrentSuggestion() {
            if (this.selectedIndex >= 0 && this.selectedIndex < this.currentSuggestions.length) {
                this.selectSuggestion(this.selectedIndex);
            }
        }

        selectSuggestion(index) {
            const suggestion = this.currentSuggestions[index];
            if (suggestion) {
                this.searchInput.value = suggestion.title;
                this.hideSuggestions();

                // Trigger search
                if (window.mapController && window.mapController.handleSearch) {
                    window.mapController.handleSearch({ target: this.searchInput });
                }
            }
        }

        showSuggestions() {
            this.suggestionsContainer.classList.remove('d-none');
        }

        hideSuggestions() {
            this.suggestionsContainer.classList.add('d-none');
            this.selectedIndex = -1;
        }

        updateSearchStats(query) {
            if (query.length === 0) {
                this.searchStatsText.textContent = '<?php echo e(__("messages.search_help")); ?>';
            } else if (query.length < 2) {
                this.searchStatsText.textContent = 'حداقل ۲ کاراکتر وارد کنید';
            } else {
                this.searchStatsText.textContent = `در حال جستجو برای "${query}"...`;
            }
        }
    }

    // Initialize smart search when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        window.smartSearch = new SmartSearch();
    });
</script>

<!-- Enhanced Filters Script -->
<script>
    // Enhanced Dynamic Filters Implementation
    class AdvancedFilters {
        constructor() {
            this.filters = {
                category: 'all',
                rating: '',
                status: '',
                distance: 50,
                country: '',
                province: '',
                city: ''
            };

            this.locationCounts = {};
            this.isLoading = false;
            this.debounceTimer = null;
            this.apiEndpoints = {
                provinces: '/api/provinces-by-country',
                cities: '/api/cities-by-province',
                filterCounts: '/api/filter-counts'
            };

            this.init();
        }

        init() {
            this.setupEventListeners();
            this.setupGeographicFilters();
            this.setupDistancePresets();
            this.setupSubcategoryToggle();
            this.loadInitialCounts();
            this.initializeAnimations();
        }

        setupEventListeners() {
            // Category filter listeners with enhanced functionality
            document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
                input.addEventListener('change', (e) => {
                    this.filters.category = e.target.value;
                    this.updateActiveCategory(e.target.value);
                    this.toggleSubcategories(e.target.value);
                    this.debounceApplyFilters();
                });
            });

            // Enhanced rating filter
            const ratingFilter = document.getElementById('rating-filter');
            if (ratingFilter) {
                ratingFilter.addEventListener('change', (e) => {
                    this.filters.rating = e.target.value;
                    this.updateRatingStats(e.target.value);
                    this.debounceApplyFilters();
                });
            }

            // Enhanced status filter
            document.querySelectorAll('input[name="statusFilter"]').forEach(input => {
                input.addEventListener('change', (e) => {
                    this.filters.status = e.target.value;
                    this.updateStatusStats(e.target.value);
                    this.debounceApplyFilters();
                });
            });

            // Enhanced distance filter
            const distanceFilter = document.getElementById('distance-filter-range');
            if (distanceFilter) {
                distanceFilter.addEventListener('input', (e) => {
                    this.filters.distance = parseInt(e.target.value);
                    this.updateDistanceDisplay(this.filters.distance);
                    this.debounceApplyFilters();
                });
            }

            // Apply filters button with loading state
            const applyBtn = document.getElementById('apply-filters');
            if (applyBtn) {
                applyBtn.addEventListener('click', () => {
                    this.applyFilters();
                });
            }

            // Clear filters button
            const clearBtn = document.getElementById('clear-filters');
            if (clearBtn) {
                clearBtn.addEventListener('click', () => {
                    this.clearAllFilters();
                });
            }
        }

        setupGeographicFilters() {
            // Country filter
            const countryFilter = document.getElementById('dynamic-country-filter');
            if (countryFilter) {
                countryFilter.addEventListener('change', (e) => {
                    this.filters.country = e.target.value;
                    this.loadProvinces(e.target.value);
                    this.resetSubsequentFilters(['province', 'city']);
                    this.debounceApplyFilters();
                });
            }

            // Province filter
            const provinceFilter = document.getElementById('dynamic-province-filter');
            if (provinceFilter) {
                provinceFilter.addEventListener('change', (e) => {
                    this.filters.province = e.target.value;
                    this.loadCities(e.target.value);
                    this.resetSubsequentFilters(['city']);
                    this.debounceApplyFilters();
                });
            }

            // City filter
            const cityFilter = document.getElementById('dynamic-city-filter');
            if (cityFilter) {
                cityFilter.addEventListener('change', (e) => {
                    this.filters.city = e.target.value;
                    this.debounceApplyFilters();
                });
            }
        }

        setupDistancePresets() {
            document.querySelectorAll('.distance-preset').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const distance = parseInt(e.target.dataset.distance);
                    this.setDistance(distance);
                    this.updateDistancePresetButtons(distance);
                });
            });
        }

        setupSubcategoryToggle() {
            // Add click handlers for parent categories to show/hide subcategories
            document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
                const categoryId = input.value;
                const subcategoryContainer = document.getElementById(`subcats-${categoryId}`);

                if (subcategoryContainer) {
                    input.addEventListener('change', (e) => {
                        if (e.target.checked) {
                            this.showSubcategories(categoryId);
                        }
                    });
                }
            });
        }

        // === Enhanced UI Update Methods ===
        updateActiveCategory(category) {
            // Hide all subcategories first
            document.querySelectorAll('.subcategory-container').forEach(container => {
                container.classList.add('d-none');
            });

            // Update visual state and show relevant subcategories
            document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
                const label = input.nextElementSibling;
                if (input.value === category) {
                    label.classList.add('active');
                    this.showSubcategories(category);
                } else {
                    label.classList.remove('active');
                }
            });

            this.updateActiveFiltersCount();
        }

        updateDistanceDisplay(distance) {
            const distanceDisplay = document.getElementById('distance-display');
            if (distanceDisplay) {
                distanceDisplay.textContent = `${distance} <?php echo e(__('messages.km')); ?>`;
            }
        }

        updateDistancePresetButtons(selectedDistance) {
            document.querySelectorAll('.distance-preset').forEach(btn => {
                const btnDistance = parseInt(btn.dataset.distance);
                if (btnDistance === selectedDistance) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            });
        }

        updateRatingStats(rating) {
            const statsElement = document.getElementById('rating-stats');
            if (statsElement) {
                if (rating) {
                    statsElement.textContent = `نمایش مکان‌های ${rating}+ ستاره`;
                } else {
                    statsElement.textContent = '<?php echo e(__("messages.select_rating_to_see_stats")); ?>';
                }
            }
        }

        updateStatusStats(status) {
            const statsElement = document.getElementById('status-stats');
            if (statsElement) {
                switch(status) {
                    case 'open':
                        statsElement.textContent = 'نمایش مکان‌های باز';
                        break;
                    case 'closed':
                        statsElement.textContent = 'نمایش مکان‌های بسته';
                        break;
                    default:
                        statsElement.textContent = '<?php echo e(__("messages.select_status_to_see_stats")); ?>';
                }
            }
        }

        updateActiveFiltersCount() {
            const activeCount = Object.values(this.filters).filter(value =>
                value !== '' && value !== 'all' && value !== 50
            ).length;

            const countElement = document.getElementById('active-filters-count');
            if (countElement) {
                countElement.textContent = activeCount;
                countElement.className = activeCount > 0 ? 'badge bg-warning text-dark ms-auto' : 'badge bg-light text-dark ms-auto';
            }

            // Update filter summary
            this.updateFilterSummary();
        }

        updateFilterSummary() {
            const summaryElement = document.getElementById('active-filters-summary');
            if (summaryElement) {
                const activeFilters = [];

                if (this.filters.category !== 'all') {
                    const categoryLabel = document.querySelector(`input[value="${this.filters.category}"]`)?.nextElementSibling?.textContent || this.filters.category;
                    activeFilters.push(categoryLabel);
                }

                if (this.filters.rating) {
                    activeFilters.push(`${this.filters.rating}+ ستاره`);
                }

                if (this.filters.status) {
                    activeFilters.push(this.filters.status === 'open' ? 'باز' : 'بسته');
                }

                if (this.filters.distance !== 50) {
                    activeFilters.push(`${this.filters.distance} کیلومتر`);
                }

                summaryElement.textContent = activeFilters.length > 0 ? activeFilters.join(', ') : '<?php echo e(__("messages.none")); ?>';
            }
        }

        // === API and Data Loading Methods ===
        async loadProvinces(countryId) {
            if (!countryId) {
                this.hideContainer('province-filter-container');
                this.hideContainer('city-filter-container');
                return;
            }

            try {
                this.showLoadingInSelect('dynamic-province-filter');
                const response = await fetch(`${this.apiEndpoints.provinces}/${countryId}`);
                const data = await response.json();

                if (data.success) {
                    this.populateSelect('dynamic-province-filter', data.data, 'name', 'id');
                    this.showContainer('province-filter-container');
                } else {
                    console.error('Failed to load provinces:', data.message);
                }
            } catch (error) {
                console.error('Error loading provinces:', error);
            } finally {
                this.hideLoadingInSelect('dynamic-province-filter');
            }
        }

        async loadCities(provinceId) {
            if (!provinceId) {
                this.hideContainer('city-filter-container');
                return;
            }

            try {
                this.showLoadingInSelect('dynamic-city-filter');
                const response = await fetch(`${this.apiEndpoints.cities}/${provinceId}`);
                const data = await response.json();

                if (data.success) {
                    this.populateSelect('dynamic-city-filter', data.data, 'name', 'id');
                    this.showContainer('city-filter-container');
                } else {
                    console.error('Failed to load cities:', data.message);
                }
            } catch (error) {
                console.error('Error loading cities:', error);
            } finally {
                this.hideLoadingInSelect('dynamic-city-filter');
            }
        }

        async loadInitialCounts() {
            try {
                const response = await fetch(this.apiEndpoints.filterCounts);
                const data = await response.json();

                if (data.success) {
                    this.locationCounts = data.counts;
                    this.updateAllCounts();
                }
            } catch (error) {
                console.error('Error loading initial counts:', error);
                // Use fallback counts
                this.loadFallbackCounts();
            }
        }

        loadFallbackCounts() {
            // Fallback counts when API fails
            this.locationCounts = {
                all: 156,
                hotel: 45,
                restaurant: 67,
                attraction: 23,
                shopping: 12,
                service: 9
            };
            this.updateAllCounts();
        }

        async updateLocationCounts() {
            if (this.isLoading) return;

            try {
                this.isLoading = true;
                this.showCountLoadingStates();

                const response = await fetch(this.apiEndpoints.filterCounts, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify(this.filters)
                });

                const data = await response.json();

                if (data.success) {
                    this.locationCounts = data.counts;
                    this.updateAllCounts();
                    this.updateResultsCount(data.total || 0);
                }
            } catch (error) {
                console.error('Error updating counts:', error);
            } finally {
                this.isLoading = false;
                this.hideCountLoadingStates();
            }
        }

        // === Utility Methods ===
        populateSelect(selectId, data, textField, valueField) {
            const select = document.getElementById(selectId);
            if (!select) return;

            // Clear existing options except the first one
            const firstOption = select.firstElementChild;
            select.innerHTML = '';
            select.appendChild(firstOption);

            // Add new options
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item[valueField];
                option.textContent = `${item[textField]} ${item.location_count ? `(${item.location_count})` : ''}`;
                select.appendChild(option);
            });
        }

        showContainer(containerId) {
            const container = document.getElementById(containerId);
            if (container) {
                container.classList.remove('d-none');
                container.classList.add('fade-in-up');
            }
        }

        hideContainer(containerId) {
            const container = document.getElementById(containerId);
            if (container) {
                container.classList.add('d-none');
                container.classList.remove('fade-in-up');
            }
        }

        showLoadingInSelect(selectId) {
            const select = document.getElementById(selectId);
            if (select) {
                select.disabled = true;
                select.innerHTML = '<option>در حال بارگذاری...</option>';
            }
        }

        hideLoadingInSelect(selectId) {
            const select = document.getElementById(selectId);
            if (select) {
                select.disabled = false;
            }
        }

        resetSubsequentFilters(filterTypes) {
            filterTypes.forEach(type => {
                this.filters[type] = '';
                if (type === 'province') {
                    this.hideContainer('province-filter-container');
                } else if (type === 'city') {
                    this.hideContainer('city-filter-container');
                }
            });
        }

        showSubcategories(categoryId) {
            const container = document.getElementById(`subcats-${categoryId}`);
            if (container) {
                container.classList.remove('d-none');
                container.classList.add('slide-in-right');
            }
        }

        setDistance(distance) {
            this.filters.distance = distance;
            const rangeInput = document.getElementById('distance-filter-range');
            if (rangeInput) {
                rangeInput.value = distance;
            }
            this.updateDistanceDisplay(distance);
            this.debounceApplyFilters();
        }

        debounceApplyFilters() {
            if (this.debounceTimer) {
                clearTimeout(this.debounceTimer);
            }

            this.debounceTimer = setTimeout(() => {
                this.applyFilters();
            }, 300);
        }

        applyFilters() {
            // Show loading state
            this.showLoadingState(true);
            this.updateActiveFiltersCount();

            // Apply filters to map and location list
            if (window.mapController && window.mapController.applyFilters) {
                window.mapController.applyFilters(this.filters);
            }

            // Update location counts
            this.updateLocationCounts();

            // Hide loading state after a delay
            setTimeout(() => {
                this.showLoadingState(false);
                this.showFilterFeedback('فیلترها اعمال شد', 'success');
            }, 500);

            // Analytics tracking
            this.trackFilterUsage();
        }

        updateAllCounts() {
            Object.keys(this.locationCounts).forEach(category => {
                this.updateCountDisplay(category, this.locationCounts[category]);
            });
        }

        updateCountDisplay(category, count) {
            const countElement = document.getElementById(`count-${category}`);
            if (countElement) {
                const countText = countElement.querySelector('.count-text');
                if (countText) {
                    countText.textContent = count;
                } else {
                    countElement.textContent = count;
                }

                // Animate count change
                countElement.style.transform = 'scale(1.2)';
                setTimeout(() => {
                    countElement.style.transform = 'scale(1)';
                }, 200);
            }
        }

        updateResultsCount(count) {
            const resultsElement = document.getElementById('results-count');
            if (resultsElement) {
                resultsElement.textContent = count;

                // Animate the count
                resultsElement.style.transform = 'scale(1.3)';
                resultsElement.style.color = '#667eea';
                setTimeout(() => {
                    resultsElement.style.transform = 'scale(1)';
                    resultsElement.style.color = '';
                }, 300);
            }
        }

        showCountLoadingStates() {
            document.querySelectorAll('.modern-badge .spinner-border').forEach(spinner => {
                spinner.classList.remove('d-none');
            });
        }

        hideCountLoadingStates() {
            document.querySelectorAll('.modern-badge .spinner-border').forEach(spinner => {
                spinner.classList.add('d-none');
            });
        }

        clearAllFilters() {
            // Reset all filters to default
            this.filters = {
                category: 'all',
                rating: '',
                status: '',
                distance: 50,
                country: '',
                province: '',
                city: ''
            };

            // Reset form elements
            document.getElementById('cat-all').checked = true;

            const ratingFilter = document.getElementById('rating-filter');
            if (ratingFilter) ratingFilter.value = '';

            document.getElementById('status-all').checked = true;

            const distanceRange = document.getElementById('distance-filter-range');
            if (distanceRange) {
                distanceRange.value = 50;
                this.updateDistanceDisplay(50);
            }

            const countryFilter = document.getElementById('dynamic-country-filter');
            if (countryFilter) countryFilter.value = '';

            // Hide geographic containers
            this.hideContainer('province-filter-container');
            this.hideContainer('city-filter-container');

            // Reset distance presets
            this.updateDistancePresetButtons(50);

            // Apply cleared filters
            this.applyFilters();
            this.showFilterFeedback('فیلترها پاک شد', 'info');
        }

        initializeAnimations() {
            // Add entrance animations to filter sections
            const filterSections = document.querySelectorAll('.filter-section');
            filterSections.forEach((section, index) => {
                section.style.animationDelay = `${index * 0.1}s`;
                section.classList.add('fade-in-up');
            });
        }

        showLoadingState(show) {
            const applyBtn = document.getElementById('apply-filters');
            if (applyBtn) {
                const btnText = applyBtn.querySelector('.btn-text');
                const spinner = applyBtn.querySelector('.spinner-border');

                if (show) {
                    if (btnText) btnText.textContent = 'در حال اعمال...';
                    if (spinner) spinner.classList.remove('d-none');
                    applyBtn.disabled = true;
                } else {
                    if (btnText) btnText.textContent = '<?php echo e(__("messages.apply_filters")); ?>';
                    if (spinner) spinner.classList.add('d-none');
                    applyBtn.disabled = false;
                }
            }
        }



        showFilterFeedback(message, type) {
            // Create toast notification
            const toast = document.createElement('div');
            toast.className = `alert alert-${type} position-fixed`;
            toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px;';
            toast.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check' : 'info'}-circle me-2"></i>
                ${message}
            `;

            document.body.appendChild(toast);

            // Animate in
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                toast.style.transition = 'all 0.3s ease';
                toast.style.opacity = '1';
                toast.style.transform = 'translateX(0)';
            }, 10);

            // Remove after 3 seconds
            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }

        trackFilterUsage() {
            // Analytics tracking for filter usage
            if (typeof gtag !== 'undefined') {
                gtag('event', 'filter_applied', {
                    'event_category': 'user_interaction',
                    'event_label': JSON.stringify(this.filters)
                });
            }
        }

        // Public method to get current filters
        getCurrentFilters() {
            return { ...this.filters };
        }

        // Public method to set filters programmatically
        setFilters(newFilters) {
            this.filters = { ...this.filters, ...newFilters };
            this.applyFilters();
        }
    }

    // Initialize advanced filters when scripts are loaded
    function initializeAdvancedFilters() {
        if (typeof $ !== 'undefined' && typeof AdvancedFilters !== 'undefined') {
            window.advancedFilters = new AdvancedFilters();
            console.log('Advanced filters initialized');
        } else {
            console.log('Waiting for dependencies...');
            setTimeout(initializeAdvancedFilters, 100);
        }
    }

    // Listen for scripts loaded event
    window.addEventListener('scriptsLoaded', initializeAdvancedFilters);

    // Fallback initialization
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initializeAdvancedFilters, 1000);
    });
</script>

<!-- Mobile Enhancement Scripts -->
<script>
    // Mobile-specific functionality
    class MobileEnhancements {
        constructor() {
            this.isMobile = window.innerWidth <= 768;
            this.isTablet = window.innerWidth > 768 && window.innerWidth <= 1024;
            this.init();
        }

        init() {
            this.setupMobileNavigation();
            this.setupTouchGestures();
            this.setupMobileSearch();
            this.setupMobileFilters();
            this.optimizeForMobile();
            this.handleOrientationChange();
        }

        setupMobileNavigation() {
            if (this.isMobile) {
                // Add mobile nav active class to body
                document.body.classList.add('mobile-nav-active');

                // Update active nav item based on current page
                this.updateActiveNavItem();

                // Add smooth scrolling for mobile nav links
                const mobileNavLinks = document.querySelectorAll('.mobile-nav-item[href^="#"]');
                mobileNavLinks.forEach(link => {
                    link.addEventListener('click', (e) => {
                        e.preventDefault();
                        const targetId = link.getAttribute('href').substring(1);
                        const targetElement = document.getElementById(targetId);

                        if (targetElement) {
                            targetElement.scrollIntoView({
                                behavior: 'smooth',
                                block: 'start'
                            });
                        }
                    });
                });
            }
        }

        updateActiveNavItem() {
            const currentPath = window.location.pathname;
            const navItems = document.querySelectorAll('.mobile-nav-item');

            navItems.forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('href') === currentPath) {
                    item.classList.add('active');
                }
            });
        }

        setupTouchGestures() {
            if (this.isMobile) {
                // Add touch-friendly classes
                const cards = document.querySelectorAll('.card-optimized');
                cards.forEach(card => {
                    card.classList.add('touch-friendly');

                    // Add touch feedback
                    card.addEventListener('touchstart', () => {
                        card.style.transform = 'scale(0.98)';
                    });

                    card.addEventListener('touchend', () => {
                        card.style.transform = 'scale(1)';
                    });
                });

                // Swipe gestures for cards
                this.setupSwipeGestures();
            }
        }

        setupSwipeGestures() {
            let startX, startY, distX, distY;
            const threshold = 100; // minimum distance for swipe

            document.addEventListener('touchstart', (e) => {
                startX = e.touches[0].clientX;
                startY = e.touches[0].clientY;
            });

            document.addEventListener('touchend', (e) => {
                if (!startX || !startY) return;

                distX = e.changedTouches[0].clientX - startX;
                distY = e.changedTouches[0].clientY - startY;

                // Horizontal swipe
                if (Math.abs(distX) > Math.abs(distY) && Math.abs(distX) > threshold) {
                    if (distX > 0) {
                        // Swipe right - show filters
                        this.toggleMobileFilters();
                    } else {
                        // Swipe left - show search
                        this.toggleMobileSearch();
                    }
                }

                startX = startY = null;
            });
        }

        setupMobileSearch() {
            // Create mobile search overlay
            if (!document.getElementById('mobile-search-overlay')) {
                const overlay = document.createElement('div');
                overlay.id = 'mobile-search-overlay';
                overlay.className = 'mobile-overlay d-none';
                overlay.innerHTML = `
                    <div class="mobile-overlay-content">
                        <div class="mobile-overlay-header">
                            <h5>جستجو</h5>
                            <button class="btn btn-sm btn-outline-secondary" onclick="closeMobileSearch()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mobile-overlay-body">
                            <div class="search-container position-relative mb-3">
                                <input type="text" class="form-control form-control-lg" placeholder="جستجو..." id="mobile-search-input">
                                <div id="mobile-search-suggestions" class="position-absolute w-100 bg-white rounded shadow d-none" style="top: 100%; z-index: 1000;"></div>
                            </div>
                            <div class="recent-searches">
                                <h6>جستجوهای اخیر</h6>
                                <div id="recent-searches-list"></div>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(overlay);
            }
        }

        setupMobileFilters() {
            // Create mobile filters overlay
            if (!document.getElementById('mobile-filters-overlay')) {
                const overlay = document.createElement('div');
                overlay.id = 'mobile-filters-overlay';
                overlay.className = 'mobile-overlay d-none';
                overlay.innerHTML = `
                    <div class="mobile-overlay-content">
                        <div class="mobile-overlay-header">
                            <h5>فیلترها</h5>
                            <button class="btn btn-sm btn-outline-secondary" onclick="closeMobileFilters()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mobile-overlay-body">
                            <div class="mobile-filters-content">
                                <!-- Filters will be populated here -->
                            </div>
                            <div class="mobile-filters-actions mt-3">
                                <button class="btn btn-primary w-100 mb-2" onclick="applyMobileFilters()">اعمال فیلترها</button>
                                <button class="btn btn-outline-secondary w-100" onclick="clearMobileFilters()">پاک کردن</button>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(overlay);
            }
        }

        optimizeForMobile() {
            if (this.isMobile) {
                // Optimize images for mobile
                const images = document.querySelectorAll('img');
                images.forEach(img => {
                    if (!img.hasAttribute('loading')) {
                        img.setAttribute('loading', 'lazy');
                    }
                });

                // Reduce animation complexity on mobile
                const animatedElements = document.querySelectorAll('.fade-in-up, .slide-in-right');
                animatedElements.forEach(el => {
                    el.style.animation = 'none';
                    el.style.opacity = '1';
                    el.style.transform = 'none';
                });

                // Optimize form inputs for mobile
                const inputs = document.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    input.classList.add('form-control-lg');
                    if (input.type === 'search') {
                        input.setAttribute('autocomplete', 'off');
                        input.setAttribute('autocorrect', 'off');
                        input.setAttribute('autocapitalize', 'off');
                    }
                });
            }
        }

        handleOrientationChange() {
            window.addEventListener('orientationchange', () => {
                setTimeout(() => {
                    this.isMobile = window.innerWidth <= 768;
                    this.isTablet = window.innerWidth > 768 && window.innerWidth <= 1024;

                    // Recalculate layouts
                    this.optimizeForMobile();

                    // Update grid layouts
                    this.updateGridLayouts();
                }, 100);
            });
        }

        updateGridLayouts() {
            const grids = document.querySelectorAll('[id$="-grid"]');
            grids.forEach(grid => {
                if (this.isMobile) {
                    grid.classList.add('mobile-grid');
                    grid.classList.remove('tablet-grid');
                } else if (this.isTablet) {
                    grid.classList.add('tablet-grid');
                    grid.classList.remove('mobile-grid');
                } else {
                    grid.classList.remove('mobile-grid', 'tablet-grid');
                }
            });
        }
    }

    // Global functions for mobile navigation
    function toggleMobileSearch() {
        const overlay = document.getElementById('mobile-search-overlay');
        if (overlay) {
            overlay.classList.toggle('d-none');
            if (!overlay.classList.contains('d-none')) {
                document.getElementById('mobile-search-input').focus();
            }
        }
    }

    function closeMobileSearch() {
        const overlay = document.getElementById('mobile-search-overlay');
        if (overlay) {
            overlay.classList.add('d-none');
        }
    }

    function toggleMobileFilters() {
        const overlay = document.getElementById('mobile-filters-overlay');
        if (overlay) {
            overlay.classList.toggle('d-none');
        }
    }

    function closeMobileFilters() {
        const overlay = document.getElementById('mobile-filters-overlay');
        if (overlay) {
            overlay.classList.add('d-none');
        }
    }

    function applyMobileFilters() {
        // Apply filters logic here
        closeMobileFilters();

        // Show feedback
        const toast = document.createElement('div');
        toast.className = 'alert alert-success position-fixed';
        toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999;';
        toast.textContent = 'فیلترها اعمال شد';
        document.body.appendChild(toast);

        setTimeout(() => {
            document.body.removeChild(toast);
        }, 3000);
    }

    function clearMobileFilters() {
        // Clear filters logic here
        closeMobileFilters();
    }

    // Initialize mobile enhancements
    function initializeMobileEnhancements() {
        if (typeof MobileEnhancements !== 'undefined') {
            window.mobileEnhancements = new MobileEnhancements();
            console.log('Mobile enhancements initialized');
        } else {
            setTimeout(initializeMobileEnhancements, 100);
        }
    }

    window.addEventListener('scriptsLoaded', initializeMobileEnhancements);
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initializeMobileEnhancements, 500);
    });
</script>
<style>
    /* Category filter loading state */
    .category-filter-container.loading {
        position: relative;
        min-height: 100px;
        pointer-events: none;
    }

    /* Location list container height */
    .tab-pane {
        max-height: 70vh;
        overflow-y: auto;
    }

    .location-list {
        padding-bottom: 20px;
    }

    .category-filter-container.loading::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255, 255, 255, 0.7);
        z-index: 10;
    }

    .category-filter-container.loading::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 30px;
        height: 30px;
        border: 3px solid rgba(78, 115, 223, 0.2);
        border-top-color: #4e73df;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
        z-index: 11;
    }

    @keyframes spin {
        to {
            transform: translate(-50%, -50%) rotate(360deg);
        }
    }

    /* Estilos para íconos de imagen */
    .category-icon-img {
        width: 20px;
        height: 20px;
        object-fit: contain;
        vertical-align: middle;
    }

    .category-icon-img-small {
        width: 16px;
        height: 16px;
        object-fit: contain;
        vertical-align: middle;
        margin-right: 4px;
    }

    /* Estilos para las pestañas verticales de ubicaciones */
    .location-tabs-wrapper {
        background: linear-gradient(to right, #f0f0f0, #ffffff);
        border-radius: 10px;
        padding: 10px 5px;
        box-shadow: 3px 3px 10px rgba(0,0,0,0.1),
                    inset 1px 1px 0px rgba(255,255,255,0.8);
    }

    .location-tabs .nav-link {
        text-align: right;
        border-radius: 8px;
        margin-bottom: 10px;
        padding: 12px 15px;
        color: #495057;
        background: linear-gradient(to right, #f8f9fa, #e9ecef);
        border: 1px solid #dee2e6;
        box-shadow: 2px 2px 5px rgba(0,0,0,0.05),
                    inset 1px 1px 0px rgba(255,255,255,0.5);
        transition: all 0.3s ease;
        font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
        position: relative;
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    .location-tabs .nav-link.active {
        color: #ffffff;
        background: linear-gradient(to right, #007bff, #0056b3);
        border-color: #0062cc;
        box-shadow: 2px 2px 8px rgba(0,123,255,0.3),
                    inset 1px 1px 0px rgba(255,255,255,0.2);
        transform: translateX(-3px);
    }

    .location-tabs .nav-link:hover:not(.active) {
        background: linear-gradient(to right, #e9ecef, #dee2e6);
        box-shadow: 2px 2px 8px rgba(0,0,0,0.1),
                    inset 1px 1px 0px rgba(255,255,255,0.8);
        transform: translateX(-2px);
    }

    .location-tabs .category-count {
        font-size: 12px;
        background-color: rgba(0,0,0,0.1);
        border-radius: 12px;
        padding: 2px 8px;
        margin-left: 8px;
        color: inherit;
        float: left;
    }

    .location-tabs .nav-link.active .category-count {
        background-color: rgba(255,255,255,0.2);
    }

    /* Estilos para los elementos de la lista de ubicaciones */
    .location-item {
        transition: transform 0.2s ease;
    }

    .location-item-inner {
        padding: 6px;
        border-radius: 10px;
        border: 1px solid #e9ecef;
        height: 100%;
        background-color: #ffffff;
        box-shadow: 0 3px 8px rgba(0,0,0,0.05);
        transition: box-shadow 0.3s ease;
        font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
    }

    .location-item:hover .location-item-inner {
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        cursor: pointer;
    }

    .location-item.selected .location-item-inner {
        background-color: #e8f0ff;
        border-color: #b8daff;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }

    .location-name {
        color: #343a40;
        font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
        font-size: 1.1rem;
        margin-bottom: 10px;
    }

    .location-address {
        font-size: 13px;
        font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
    }

    /* Estilos adicionales para las funcionalidades de distancia y navegación */
    .user-location-card .card {
        border-radius: 10px;
        box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        background: linear-gradient(to bottom, #f8f9fa, #ffffff);
        border: none;
        transition: all 0.3s ease;
    }

    .user-location-card .card:hover {
        box-shadow: 0 5px 15px rgba(0,123,255,0.2);
    }

    .sorting-options .card, .distance-filter .card {
        border-radius: 10px;
        box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        border: none;
        background: linear-gradient(to bottom, #f8f9fa, #ffffff);
    }

    .distance-info {
        background-color: rgba(13, 110, 253, 0.08);
        padding: 4px 8px;
        border-radius: 6px;
        font-size: 14px;
    }

    .transport-options {
        margin-top: 5px;
    }

    .transport-option {
        background-color: rgba(0,0,0,0.04);
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
    }

    .transport-walking {
        background-color: rgba(25, 135, 84, 0.08);
    }

    .transport-driving {
        background-color: rgba(13, 202, 240, 0.08);
    }

    .transport-bus {
        background-color: rgba(255, 193, 7, 0.08);
    }

    .location-actions {
        margin-top: 10px;
        display: flex;
        gap: 5px;
    }

    /* Nuevos estilos para mejorar la experiencia de usuario */
    .pulse-animation {
        animation: pulse-effect 1.5s infinite;
    }

    @keyframes pulse-effect {
        0% {
            box-shadow: 0 0 0 0 rgba(13, 110, 253, 0.4);
        }
        70% {
            box-shadow: 0 0 0 10px rgba(13, 110, 253, 0);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(13, 110, 253, 0);
        }
    }

    .destination-badge {
        position: absolute;
        right: 10px;
        top: 10px;
        background-color: rgba(25, 135, 84, 0.7);
        color: white;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 11px;
        z-index: 10;
    }
</style>
<script>
    // Helper function for number formatting
    function formatNumber(number) {
        const locale = '<?php echo e(app()->getLocale()); ?>';
        return new Intl.NumberFormat(locale === 'fa' ? 'fa-IR' : 'en-US').format(number);
    }

    // Global variables
    var map;
    var markersMap = {};
    var locationsArray = [];
    var categoryIcons = {};
    var categoryImagePaths = {};
    var activeFilters = {
        search: '',
        country: '',
        province: '',
        county: '',
        district: '',
        city: '',
        village: '',
        zone: '',
        categories: []
    };
    var searchTimeout = null;
    var userLocation = null;
    var directionsService = null;
    var directionsRenderer = null;
    var maxDistanceFilter = 50; // Default distance filter (km)
    var maxRouteDistance = 2000000; // 2000 km in meters (for route calculations)
    var showUnlimitedDistance = true; // Show locations at any distance

    // Enhanced initialization with dependency checking
    function initializeMapComponents() {
        console.log('Initializing map components...');

        // Check if Leaflet is loaded
        if (typeof L === 'undefined') {
            console.log('Waiting for Leaflet to load...');
            setTimeout(initializeMapComponents, 500);
            return;
        }

        // Initialize the map
        initLeafletMap();

        // Initialize category icons (emoji-to-marker mapping)
        initCategoryIcons();

        // Initialize directions service
        initDirectionsService();

        // Apply icons to category filters
        applyCategoryIcons();

        // Initialize event listeners
        initEventListeners();

        // Initialize MapController if available
        if (typeof MapController !== 'undefined' && typeof MapApiAdapter !== 'undefined' && typeof MapHandler !== 'undefined') {
            console.log('Initializing MapController...');
            window.mapController = new MapController({
                mapContainerId: 'map',
                debug: true
            });

            // Initialize the controller
            window.mapController.init().then(() => {
                console.log('MapController initialized successfully');
            }).catch(error => {
                console.error('Error initializing MapController:', error);
            });
        } else {
            console.log('MapController dependencies not available yet, will retry...');
            setTimeout(() => {
                if (typeof MapController !== 'undefined' && typeof MapApiAdapter !== 'undefined' && typeof MapHandler !== 'undefined') {
                    console.log('MapController dependencies now available, initializing...');
                    window.mapController = new MapController({
                        mapContainerId: 'map',
                        debug: true
                    });

                    window.mapController.init().then(() => {
                        console.log('MapController initialized successfully (delayed)');
                    }).catch(error => {
                        console.error('Error initializing MapController (delayed):', error);
                    });
                }
            }, 1000);
        }

        // Load initial data
        loadLocations();

        // Event for getting user location
        const getUserLocationBtn = document.getElementById('get-user-location');
        if (getUserLocationBtn) {
            getUserLocationBtn.addEventListener('click', function() {
                getUserLocation();
            });
        }

        // Event for changing distance filter
        document.getElementById('distance-range').addEventListener('input', function() {
            maxDistanceFilter = parseInt(this.value);
            document.getElementById('distance-value').textContent = formatNumber(maxDistanceFilter);

            if (userLocation) {
                refreshDistances();
            }
        });

        // Evento para el checkbox de distancia ilimitada
        document.getElementById('unlimited-distance').addEventListener('change', function() {
            showUnlimitedDistance = this.checked;

            // Mostrar/ocultar el control de límite de ruta
            document.querySelector('.route-distance-limit').classList.toggle('d-none', showUnlimitedDistance);

            if (userLocation) {
                refreshDistances();
            }
        });

        // Evento para cambiar el límite de distancia para cálculos de ruta
        document.getElementById('route-distance-range').addEventListener('input', function() {
            // Valor en kilómetros
            const distanceKm = parseInt(this.value);
            document.getElementById('route-distance-value').textContent = formatNumber(distanceKm);
            maxRouteDistance = distanceKm * 1000; // Convertir a metros

            if (userLocation) {
                refreshDistances();
            }
        });

        // Evento para cambiar el ordenamiento
        document.getElementById('sort-locations').addEventListener('change', function() {
            const sortMethod = this.value;

            if (sortMethod === 'distance' && userLocation) {
                sortLocationsByDistance();
            } else if (sortMethod === 'name') {
                sortLocationsByName();
            } else if (sortMethod === 'category') {
                sortLocationsByCategory();
            }
        });

        console.log('Map components initialized successfully');
    }

    // Master initialization function that coordinates all components
    function initializeAllComponents() {
        console.log('Starting comprehensive initialization...');

        // Check if all dependencies are loaded
        const jQueryLoaded = typeof $ !== 'undefined';
        const leafletLoaded = typeof L !== 'undefined';
        const select2Loaded = jQueryLoaded && typeof $.fn.select2 !== 'undefined';

        console.log('Dependencies status:', {
            jQuery: jQueryLoaded,
            Leaflet: leafletLoaded,
            Select2: select2Loaded
        });

        // Initialize components based on availability
        try {
            // 1. Initialize map components if Leaflet is available
            if (leafletLoaded) {
                console.log('Initializing map components...');
                initializeMapComponents();
            } else {
                console.log('Leaflet not available, will retry...');
                setTimeout(() => {
                    if (typeof L !== 'undefined') {
                        console.log('Leaflet now available, initializing map...');
                        initializeMapComponents();
                    }
                }, 1000);
            }

            // 2. Initialize jQuery-dependent components
            if (jQueryLoaded) {
                console.log('jQuery available, initializing jQuery components...');

                // Initialize Select2 if available
                if (select2Loaded) {
                    setTimeout(() => {
                        if (typeof initializeSelect2 === 'function') {
                            initializeSelect2();
                        }
                    }, 300);
                } else {
                    console.log('Select2 not available yet, will retry...');
                    setTimeout(() => {
                        if (typeof $ !== 'undefined' && typeof $.fn.select2 !== 'undefined' && typeof initializeSelect2 === 'function') {
                            initializeSelect2();
                        }
                    }, 1000);
                }

                // Initialize geo event handlers
                setTimeout(() => {
                    if (typeof initializeGeoEventHandlers === 'function') {
                        initializeGeoEventHandlers();
                    }
                }, 500);

                // Initialize select counts
                setTimeout(() => {
                    if (typeof initializeSelectCounts === 'function') {
                        initializeSelectCounts();
                    }
                }, 700);

            } else {
                console.log('jQuery not available, will retry...');
                setTimeout(initializeAllComponents, 500);
                return;
            }

            console.log('All components initialization started');
        } catch (error) {
            console.error('Error during initialization:', error);
        }
    }

    // Initialize Modern Category Filter
    function initializeModernCategoryFilter() {
        if (typeof ModernCategoryFilter !== 'undefined') {
            // Disable the old category filter first
            if (window.categoryFilter) {
                console.log('Disabling old category filter in favor of modern one');
                window.categoryFilter = null;
            }

            window.modernCategoryFilter = new ModernCategoryFilter({
                containerSelector: '.category-filter-container',
                searchInputSelector: '#category-search',
                clearButtonSelector: '#clear-filter',
                activeCategoryCountSelector: '#active-category-count',
                onCategoryChange: (categoryId, options) => {
                    console.log('Modern Category Filter changed:', categoryId, options);

                    // Check if mapController exists and log its status
                    console.log('MapController status:', {
                        exists: !!window.mapController,
                        hasMethod: !!(window.mapController && window.mapController.handleCategoryFilterChange),
                        mapController: window.mapController
                    });

                    // Directly trigger map controller if available
                    if (window.mapController && window.mapController.handleCategoryFilterChange) {
                        console.log('Calling mapController.handleCategoryFilterChange...');
                        window.mapController.handleCategoryFilterChange(categoryId, options);
                    } else {
                        console.warn('MapController not available or missing handleCategoryFilterChange method');

                        // Fallback to old method if available
                        if (typeof loadLocations === 'function') {
                            console.log('Using fallback loadLocations method');

                            // IMPORTANT: Clear ALL previous category filters first
                            activeFilters.categories = [];
                            activeFilters.categoryOptions = null;

                            // Update active filters for fallback
                            if (categoryId) {
                                console.log('Setting category filter to:', categoryId);
                                console.log('Category options:', options);

                                // Set ONLY the new category filter (replace, don't append)
                                activeFilters.categories = [categoryId];

                                // Store additional filter information for API call
                                activeFilters.categoryOptions = {
                                    isParent: options.isParent,
                                    includeChildren: options.include_children
                                };
                            }

                            console.log('Updated activeFilters (should contain only one category):', activeFilters);
                            loadLocations();
                        }
                    }
                }
            });
            console.log('Modern Category Filter initialized');
        } else {
            console.log('ModernCategoryFilter not available yet, retrying...');
            setTimeout(initializeModernCategoryFilter, 100);
        }
    }

    // Listen for scripts loaded event
    window.addEventListener('scriptsLoaded', initializeAllComponents);
    window.addEventListener('scriptsLoaded', initializeModernCategoryFilter);

    // Fallback initialization
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initializeAllComponents, 1000);
        setTimeout(initializeModernCategoryFilter, 1200);
    });

    function initCategoryIcons() {
        console.log('Initializing category icons...');

        // Check if Leaflet is loaded
        if (typeof L === 'undefined') {
            console.log('Leaflet not loaded yet for category icons, waiting...');
            setTimeout(initCategoryIcons, 500);
            return;
        }

        // Define default icons for each category
        let iconPath = '';

        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            // Try to find the icon file based on category_key or id
            iconPath = ''; // Reset for each category
            <?php if($category->category_key): ?>
                if (iconFileExists('/images/map-icons/<?php echo e($category->category_key); ?>-icon.png')) {
                    iconPath = '/images/map-icons/<?php echo e($category->category_key); ?>-icon.png';
                }
            <?php endif; ?>

            // If not found by category_key, try with ID
            if (!iconPath) {
                if (iconFileExists('/images/map-icons/category-<?php echo e($category->id); ?>.png')) {
                    iconPath = '/images/map-icons/category-<?php echo e($category->id); ?>.png';
                }
            }

            if (iconPath) {
                // Use image icon if found
                categoryIcons[<?php echo e($category->id); ?>] = L.icon({
                    iconUrl: iconPath,
                    iconSize: [32, 32],
                    iconAnchor: [16, 32],
                    popupAnchor: [0, -32]
                });
                console.log('Using image icon for category <?php echo e($category->id); ?>: ' + iconPath);

                // Save the path for use in other places
                categoryImagePaths[<?php echo e($category->id); ?>] = iconPath;
            }
            <?php if($category->emoji): ?>
            else {
                // Fallback to emoji if no image found
                categoryIcons[<?php echo e($category->id); ?>] = L.divIcon({
                    html: '<div class="map-marker-icon"><?php echo e($category->emoji); ?></div>',
                    className: 'map-marker',
                    iconSize: [36, 36],
                    iconAnchor: [18, 36],
                    popupAnchor: [0, -36]
                });
                console.log('Using emoji icon for category <?php echo e($category->id); ?>');
            }
            <?php endif; ?>

            <?php $__currentLoopData = $category->children; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                // Try to find the icon file for child category
                iconPath = ''; // Reset icon path for each child
                <?php if($child->category_key): ?>
                    if (iconFileExists('/images/map-icons/<?php echo e($child->category_key); ?>-icon.png')) {
                        iconPath = '/images/map-icons/<?php echo e($child->category_key); ?>-icon.png';
                    }
                <?php endif; ?>

                // If not found by category_key, try with ID
                if (!iconPath) {
                    if (iconFileExists('/images/map-icons/category-<?php echo e($child->id); ?>.png')) {
                        iconPath = '/images/map-icons/category-<?php echo e($child->id); ?>.png';
                    }
                }

                if (iconPath) {
                    // Use image icon if found
                    categoryIcons[<?php echo e($child->id); ?>] = L.icon({
                        iconUrl: iconPath,
                        iconSize: [32, 32],
                        iconAnchor: [16, 32],
                        popupAnchor: [0, -32]
                    });
                    console.log('Using image icon for child category <?php echo e($child->id); ?>: ' + iconPath);

                    // Save the path for use in other places
                    categoryImagePaths[<?php echo e($child->id); ?>] = iconPath;
                }
                <?php if($child->emoji): ?>
                else {
                    // Fallback to emoji if no image found
                    categoryIcons[<?php echo e($child->id); ?>] = L.divIcon({
                        html: '<div class="map-marker-icon"><?php echo e($child->emoji); ?></div>',
                        className: 'map-marker',
                        iconSize: [36, 36],
                        iconAnchor: [18, 36],
                        popupAnchor: [0, -36]
                    });
                    console.log('Using emoji icon for child category <?php echo e($child->id); ?>');
                }
                <?php endif; ?>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    }

    // Helper function to check if an icon file exists
    function iconFileExists(url) {
        // Using a simple cached approach to avoid making too many requests
        if (typeof window.iconCache === 'undefined') {
            window.iconCache = {};
        }

        if (url in window.iconCache) {
            return window.iconCache[url];
        }

        // Extract just the filename from the URL
        const filename = url.split('/').pop();

        // Lista de iconos disponibles en la carpeta (sin comprobar la existencia real del archivo)
        const availableIcons = [
            'market.png',
            'map.png',
            'fastfood-icon.png',
            'ecotourism-icon.png',
            'pier-icon.png',
            'beauty_salon-icon.png',
            'men_haircut-icon.png',
            'pharmacy-icon.png',
            'cemetery-icon.png',
            'schools-icon.png',
            'university-icon.png',
            'mosques-icon.png',
            'atm-icon.png',
            'bank-icon.png',
            'attraction-icon.png',
            'restaurants-icon.png',
            'landmarks-icon.png',
            'beaches-icon.png',
            'airports-icon.png',
            'hospitals-icon.png',
            'bazaar-icon.png',
            'hotels-icon.png',
            'city-center-icon.png',
            'city-icon.png',
            'default-icon.png',
            'mountain-icon.png'
        ];

        // Check if the filename is in our list of available icons
        // IMPORTANTE: verificamos que la imagen existe en nuestra lista antes de intentar cargarla
        const exists = availableIcons.includes(filename);

        // Verificación adicional - tratamos de evitar 404 para iconos específicos
        if (filename === 'beauty_salon-icon.png' || filename === 'beauty_salon-icon .png') {
            // Este icono da problemas, usamos un fallback
            window.iconCache[url] = false;
            console.log(`Skipping problematic icon: ${filename}`);
            return false;
        }

        // Cache the result
        window.iconCache[url] = exists;

        console.log(`Icon check: ${filename} - ${exists ? 'Found' : 'Not found'}`);

        return exists;
    }

    function initEventListeners() {
        // Skip category filter events here since they are handled by ModernCategoryFilter
        // Only initialize if ModernCategoryFilter is not available
        if (typeof window.modernCategoryFilter === 'undefined' && typeof window.categoryFilter === 'undefined') {
            console.log('Initializing fallback category event listeners');

            // Category filter events (fallback only)
            document.querySelectorAll('.parent-category').forEach(function(element) {
                element.addEventListener('click', function(event) {
                    const parentId = this.getAttribute('data-category-id');
                    const childrenContainer = this.nextElementSibling;

                    // Check if clicking on expand icon
                    const isExpandIconClick = event.target.closest('.expand-icon') || event.target.classList.contains('expand-icon');

                    if (isExpandIconClick || event.target.closest('.category-meta')) {
                        // Just toggle expansion for icon clicks
                        if (childrenContainer) {
                            childrenContainer.classList.toggle('hidden');
                            this.classList.toggle('expanded');
                        }
                        return;
                    }

                    // For other clicks, toggle active state and apply filter
                    if (!event.target.classList.contains('category-count')) {
                        this.classList.toggle('active');
                        updateCategoryFilters();
                        loadLocations();
                    }
                });
            });

            document.querySelectorAll('.child-category').forEach(function(element) {
                element.addEventListener('click', function(event) {
                    // Toggle active state
                    this.classList.toggle('active');

                    // Apply filter
                    if (!event.target.classList.contains('category-count')) {
                        updateCategoryFilters();
                        loadLocations();
                    }
                });
            });
        } else {
            console.log('Modern category filter is available, skipping fallback event listeners');
        }

        const clearFilterBtn = document.getElementById('clear-filter');
        if (clearFilterBtn) {
            clearFilterBtn.addEventListener('click', function() {
                // Clear all active filters
                document.querySelectorAll('.parent-category.active, .child-category.active').forEach(function(element) {
                    element.classList.remove('active');
                });

                // Reset category filters
                updateCategoryFilters();
                loadLocations();
            });
        }

        // Filter section collapse/expand toggle
        const toggleFilterBtn = document.getElementById('toggle-filter-section');
        if (toggleFilterBtn) {
            toggleFilterBtn.addEventListener('click', function() {
                const filterContent = document.querySelector('.category-filter-content');
                const icon = this.querySelector('.toggle-icon');

                if (filterContent) {
                    filterContent.classList.toggle('d-none');

                    // Toggle icon
                    if (icon) {
                        if (filterContent.classList.contains('d-none')) {
                            icon.classList.remove('fa-chevron-down');
                            icon.classList.add('fa-chevron-up');
                        } else {
                            icon.classList.remove('fa-chevron-up');
                            icon.classList.add('fa-chevron-down');
                        }
                    }
                }
            });
        }

        // Initialize collapsible categories
        document.addEventListener('DOMContentLoaded', function() {
            // Show filter content by default (remove d-none if present)
            const filterContent = document.querySelector('.category-filter-content');
            if (filterContent) {
                filterContent.classList.remove('d-none');
            }
        });

        // Live search input with debounce
        const searchInput = document.getElementById('search-input');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);

                searchTimeout = setTimeout(() => {
                    activeFilters.search = this.value;
                    loadLocations();
                }, 500); // 500ms delay for debounce
            });
        }

        // Search form submit
        const searchForm = document.getElementById('search-form');
        if (searchForm) {
            searchForm.addEventListener('submit', function(event) {
                event.preventDefault();
                const searchInputEl = document.getElementById('search-input');
                if (searchInputEl) {
                    activeFilters.search = searchInputEl.value;
                    loadLocations();
                }
            });
        }

        // Reset search button
        const resetSearchBtn = document.getElementById('reset-search');
        if (resetSearchBtn) {
            resetSearchBtn.addEventListener('click', function() {
                resetAllFilters();
                loadLocations();
            });
        }

        // Geographic hierarchy dropdowns
        setupGeographicHierarchy();
    }

    function setupGeographicHierarchy() {
        // Country select
        const countrySelect = document.getElementById('country-select');
        if (countrySelect) {
            countrySelect.addEventListener('change', function() {
            const countryId = this.value;
            activeFilters.country = countryId;

            // Reset dependent filters
            activeFilters.province = '';
            activeFilters.county = '';
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';
            activeFilters.zone = '';

            // Hide all dependent containers
            resetGeoContainers();

            if (countryId) {
                // Show and fetch data for province and zone
                document.getElementById('province-container').style.display = 'block';
                document.getElementById('zone-container').style.display = 'block';

                fetchProvincesByCountry(countryId);
                fetchZonesByCountry(countryId);

                // Update categories based on geographic selection
                updateCategoriesByRegion();
            } else {
                // Hide all dependent containers
                resetGeoContainers();
                // Reset categories to show all
                resetCategoryFilter();
            }

            loadLocations();
            });
        }

        // Province select
        const provinceSelect = document.getElementById('province-select');
        if (provinceSelect) {
            provinceSelect.addEventListener('change', function() {
            const provinceId = this.value;
            activeFilters.province = provinceId;

            // Reset dependent filters
            activeFilters.county = '';
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';

            // Hide dependent containers
            document.getElementById('county-container').style.display = 'none';
            document.getElementById('district-container').style.display = 'none';
            document.getElementById('city-container').style.display = 'none';
            document.getElementById('village-container').style.display = 'none';

            // Prepare dependent selects
            resetSelect('county-select');
            resetSelect('district-select');
            resetSelect('city-select');
            resetSelect('village-select');

            if (provinceId) {
                // Show and fetch data for county
                document.getElementById('county-container').style.display = 'block';
                fetchCountiesByProvince(provinceId);

                // Update categories based on geographic selection
                updateCategoriesByRegion();
            }

            loadLocations();
            });
        }

        // County select
        const countySelect = document.getElementById('county-select');
        if (countySelect) {
            countySelect.addEventListener('change', function() {
            const countyId = this.value;
            activeFilters.county = countyId;

            // Reset dependent filters
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';

            // Hide dependent containers
            document.getElementById('district-container').style.display = 'none';
            document.getElementById('city-container').style.display = 'none';
            document.getElementById('village-container').style.display = 'none';

            // Prepare dependent selects
            resetSelect('district-select');
            resetSelect('city-select');
            resetSelect('village-select');

            if (countyId) {
                // Show and fetch data for district
                document.getElementById('district-container').style.display = 'block';
                fetchDistrictsByCounty(countyId);

                // Update categories based on geographic selection
                updateCategoriesByRegion();
            }

            loadLocations();
            });
        }

        // District select
        const districtSelect = document.getElementById('district-select');
        if (districtSelect) {
            districtSelect.addEventListener('change', function() {
            const districtId = this.value;
            activeFilters.district = districtId;

            // Reset dependent filters
            activeFilters.city = '';
            activeFilters.village = '';

            // Hide dependent containers
            document.getElementById('city-container').style.display = 'none';
            document.getElementById('village-container').style.display = 'none';

            // Prepare dependent selects
            resetSelect('city-select');
            resetSelect('village-select');

            if (districtId) {
                // Show and fetch data for city and village
                document.getElementById('city-container').style.display = 'block';
                document.getElementById('village-container').style.display = 'block';

                fetchCitiesByDistrict(districtId);
                fetchVillagesByDistrict(districtId);

                // Update categories based on geographic selection
                updateCategoriesByRegion();
            }

            loadLocations();
            });
        }

        // City select
        const citySelect = document.getElementById('city-select');
        if (citySelect) {
            citySelect.addEventListener('change', function() {
                activeFilters.city = this.value;

                // Update categories based on geographic selection
                updateCategoriesByRegion();

                loadLocations();
            });
        }

        // Village select
        const villageSelect = document.getElementById('village-select');
        if (villageSelect) {
            villageSelect.addEventListener('change', function() {
                activeFilters.village = this.value;

                // Update categories based on geographic selection
                updateCategoriesByRegion();

                loadLocations();
            });
        }

        // Zone select
        const zoneSelect = document.getElementById('zone-select');
        if (zoneSelect) {
            zoneSelect.addEventListener('change', function() {
                activeFilters.zone = this.value;

                // Update categories based on geographic selection
                updateCategoriesByRegion();

                loadLocations();
            });
        }
    }

    function resetGeoContainers() {
        // Hide all dependent containers (with null checks)
        const containers = [
            'province-container', 'county-container', 'district-container',
            'city-container', 'village-container', 'zone-container'
        ];

        containers.forEach(containerId => {
            const container = document.getElementById(containerId);
            if (container) {
                container.style.display = 'none';
            }
        });

        // Reset all selects
        resetSelect('province-select');
        resetSelect('county-select');
        resetSelect('district-select');
        resetSelect('city-select');
        resetSelect('village-select');
        resetSelect('zone-select');
    }

    function resetSelect(selectId) {
        const select = document.getElementById(selectId);
        if (select) {
            const labelElement = select.closest('div')?.querySelector('.form-label');
            const label = labelElement ? labelElement.textContent : '';
            select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.all')); ?> ${label}</option>`;
        }
    }

    function resetAllFilters() {
        console.log('Resetting all filters...');

        try {
            // Reset search input
            const searchInput = document.getElementById('search-input');
            if (searchInput) {
                searchInput.value = '';
                if (searchInput.placeholder !== undefined) {
                    searchInput.placeholder = '<?php echo e(__("welcome.filters.search_placeholder")); ?>';
                }
            }
            activeFilters.search = '';

            // Reset country select
            const countrySelect = document.getElementById('country-select');
            if (countrySelect) {
                countrySelect.value = '';
            }

            // Reset and hide all other geographic selects
            resetGeoContainers();

            // Reset all geographic filters
            activeFilters.country = '';
            activeFilters.province = '';
            activeFilters.county = '';
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';
            activeFilters.zone = '';

            // Reset distance filter (if it exists)
            const distanceFilter = document.getElementById('distance-filter');
            if (distanceFilter) {
                distanceFilter.value = '';
                activeFilters.distance = '';
            }

            // Reset sort order (if it exists)
            const sortOrder = document.getElementById('sort-order');
            if (sortOrder) {
                sortOrder.value = 'distance';
                activeFilters.sortOrder = 'distance';
            }

            // Reset category filters
            resetCategoryFilter();

            console.log('All filters reset successfully');
        } catch (error) {
            console.error('Error resetting filters:', error);
        }

        // Update category filters array
        updateCategoryFilters();

        // Update locations display (if function exists)
        if (typeof updateLocationsDisplay === 'function') {
            updateLocationsDisplay();
        } else {
            // Fallback to loadLocations if updateLocationsDisplay doesn't exist
            if (typeof loadLocations === 'function') {
                loadLocations();
            }
        }
    }

    function fetchProvincesByCountry(countryId) {
        fetch(`/api/countries/${countryId}/provinces`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('province-select');
                if (!select) {
                    console.warn('Province select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(province => {
                        const option = document.createElement('option');
                        option.value = province.id;
                        option.textContent = `${province.name} (${province.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching provinces:', error));
    }

    function fetchCountiesByProvince(provinceId) {
        fetch(`/api/provinces/${provinceId}/counties`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('county-select');
                if (!select) {
                    console.warn('County select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(county => {
                        const option = document.createElement('option');
                        option.value = county.id;
                        option.textContent = `${county.name} (${county.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching counties:', error));
    }

    function fetchDistrictsByCounty(countyId) {
        fetch(`/api/counties/${countyId}/districts`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('district-select');
                if (!select) {
                    console.warn('District select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(district => {
                        const option = document.createElement('option');
                        option.value = district.id;
                        option.textContent = `${district.name} (${district.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching districts:', error));
    }

    function fetchCitiesByDistrict(districtId) {
        fetch(`/api/districts/${districtId}/cities`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('city-select');
                if (!select) {
                    console.warn('City select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(city => {
                        const option = document.createElement('option');
                        option.value = city.id;
                        option.textContent = `${city.name} (${city.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching cities:', error));
    }

    function fetchVillagesByDistrict(districtId) {
        fetch(`/api/districts/${districtId}/villages`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('village-select');
                if (!select) {
                    console.warn('Village select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(village => {
                        const option = document.createElement('option');
                        option.value = village.id;
                        option.textContent = `${village.name} (${village.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching villages:', error));
    }

    function fetchZonesByCountry(countryId) {
        fetch(`/api/countries/${countryId}/zones`)
            .then(response => response.json())
            .then(data => {
                const select = document.getElementById('zone-select');
                if (!select) {
                    console.warn('Zone select element not found');
                    return;
                }

                select.innerHTML = `<option value=""><?php echo e(__('welcome.filters.select')); ?></option>`;

                if (data.success && data.data) {
                    data.data.forEach(zone => {
                        const option = document.createElement('option');
                        option.value = zone.id;
                        option.textContent = `${zone.name} (${zone.location_count})`;
                        select.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error fetching zones:', error));
    }

    function updateCategoryFilters() {
        // This function is now handled by ModernCategoryFilter
        // Don't update activeFilters.categories here to avoid conflicts
        console.log('updateCategoryFilters called - handled by ModernCategoryFilter');
    }

    // Add a variable to track ongoing requests
    let currentRequest = null;

    function loadLocations() {
        // Cancel any ongoing request
        if (currentRequest) {
            console.log('Cancelling previous request');
            currentRequest.abort();
            currentRequest = null;
        }

        // Show loading indicator
        showLoading(true);

        // Clear existing markers
        clearMap();

        // Build query parameters
        const params = new URLSearchParams();

        if (activeFilters.search) {
            params.append('q', activeFilters.search);
        }

        if (activeFilters.country) {
            params.append('country', activeFilters.country);
        }

        if (activeFilters.province) {
            params.append('province', activeFilters.province);
        }

        if (activeFilters.county) {
            params.append('county', activeFilters.county);
        }

        if (activeFilters.district) {
            params.append('district', activeFilters.district);
        }

        if (activeFilters.city) {
            params.append('city', activeFilters.city);
        }

        if (activeFilters.village) {
            params.append('village', activeFilters.village);
        }

        if (activeFilters.zone) {
            params.append('zone', activeFilters.zone);
        }

        if (activeFilters.categories.length > 0) {
            params.append('category', activeFilters.categories.join(','));

            // Add include_children parameter based on category options
            if (activeFilters.categoryOptions) {
                if (activeFilters.categoryOptions.includeChildren) {
                    params.append('include_children', '1');
                    console.log('Adding include_children=1 to API request');
                } else {
                    console.log('Not including children for this category request');
                }
            }
        }

        console.log('API Request URL:', `/api/search?${params.toString()}`);
        console.log('Active Filters:', activeFilters);

        // Variable to track retry attempts
        let retryCount = 0;
        const maxRetries = 2;

        function fetchData() {
            // Create AbortController for this request
            const controller = new AbortController();
            currentRequest = controller;

            // Make API request with abort signal
            fetch(`/api/search?${params.toString()}`, {
                signal: controller.signal
            })
                .then(response => {
                    console.log('API Response Status:', response.status);
                    if (!response.ok) {
                        throw new Error(`API returned status ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('API Response Data:', data);

                    if (data.success) {
                        // Initialize locationsArray to empty array if data.data is undefined or null
                        locationsArray = Array.isArray(data.data) ? data.data : [];

                        console.log('Locations Array:', locationsArray);
                        console.log('Location Count:', data.count);

                        // Update count badge
                        const locationsCount = document.getElementById('locations-count');
                        if (locationsCount) {
                            locationsCount.textContent = `${data.count} <?php echo e(__("welcome.filters.locations_found")); ?>`;
                        }

                        // Add markers to map
                        addMarkersToMap();

                        // Update list
                        updateLocationsList();

                        // Show/hide no results message
                        const noResults = document.getElementById('no-results');
                        if (noResults) {
                            noResults.style.display = locationsArray.length > 0 ? 'none' : '';
                        }

                        // Fit map bounds if we have markers
                        if (data.count > 0) {
                            fitMapToBounds();
                        }
                    } else {
                        console.error('API returned success=false:', data.error);

                        // If we've received an error response but haven't reached max retries, try again
                        if (retryCount < maxRetries) {
                            retryCount++;
                            console.log(`Retrying API call (${retryCount}/${maxRetries})...`);
                            setTimeout(fetchData, 1000);
                            return;
                        }

                        // Show no results message
                        const noResults = document.getElementById('no-results');
                        if (noResults) {
                            noResults.style.display = '';
                        }
                        const locationsCountError = document.getElementById('locations-count');
                        if (locationsCountError) {
                            locationsCountError.textContent = '0 مکان یافت شد';
                        }
                    }

                    // Clear current request and hide loading indicator
                    currentRequest = null;
                    showLoading(false);
                })
                .catch(error => {
                    // Handle aborted requests
                    if (error.name === 'AbortError') {
                        console.log('Request was cancelled');
                        return;
                    }

                    console.error('Error loading locations:', error);

                    // If we haven't reached max retries, try again
                    if (retryCount < maxRetries) {
                        retryCount++;
                        console.log(`Retrying API call (${retryCount}/${maxRetries}) after error: ${error.message}`);
                        setTimeout(fetchData, 1000);
                        return;
                    }

                    // Show no results message after max retries
                    const noResults = document.getElementById('no-results');
                    if (noResults) {
                        noResults.style.display = '';
                    }
                    const locationsCountCatch = document.getElementById('locations-count');
                    if (locationsCountCatch) {
                        locationsCountCatch.textContent = '0 مکان یافت شد';
                    }
                    currentRequest = null;
                    showLoading(false);
                });
        }

        // Start the initial fetch
        fetchData();
    }

    function showLoading(show) {
        const loader = document.getElementById('map-loading');
        if (loader) {
        if (show) {
            loader.classList.remove('d-none');
        } else {
            loader.classList.add('d-none');
            }
        }
    }

    function clearMap() {
        console.log('Clearing map - current markers count:', Object.keys(markersMap).length);

        // Remove all existing markers from the map
        for (const id in markersMap) {
            if (markersMap.hasOwnProperty(id)) {
                try {
                    if (markersMap[id] && map.hasLayer(markersMap[id])) {
                        map.removeLayer(markersMap[id]);
                        console.log('Removed marker for location:', id);
                    }
                } catch (error) {
                    console.warn('Error removing marker for location', id, ':', error);
                }
                delete markersMap[id];
            }
        }

        // Clear the markersMap object completely
        markersMap = {};

        // Alternative method: Remove all layers from map and re-add the tile layer
        // This ensures all markers are completely removed
        try {
            map.eachLayer(function(layer) {
                if (layer instanceof L.Marker) {
                    map.removeLayer(layer);
                    console.log('Force removed marker layer');
                }
            });
        } catch (error) {
            console.warn('Error in force marker removal:', error);
        }

        console.log('Map cleared - remaining markers:', Object.keys(markersMap).length);

        // Clear location list
        const locationList = document.querySelector('.location-list');
        const template = document.getElementById('location-template');
        const noResults = document.getElementById('no-results');
        // فقط اگر locationList وجود داشت ادامه بده
        if (locationList) {
        // Remove all items except template and no-results
        Array.from(locationList.children).forEach(child => {
            if (child.id !== 'location-template' && child.id !== 'no-results') {
                locationList.removeChild(child);
            }
        });
        }
    }

    function addMarkersToMap() {
        console.log('Adding markers to map for', locationsArray.length, 'locations');

        locationsArray.forEach(function(loc) {
            if (!loc.lat || !loc.lng) {
                console.log(`Skipping location ${loc.id} - missing coordinates`);
                return;
            }

            // Skip if marker already exists for this location
            if (markersMap[loc.id]) {
                console.log(`Marker already exists for location ${loc.id}, skipping`);
                return;
            }

            // Create marker with custom icon if available
            let marker;
            if (loc.category_id && categoryIcons[loc.category_id]) {
                console.log(`Using custom icon for location ${loc.id} with category ${loc.category_id}`);
                marker = L.marker([loc.lat, loc.lng], {
                    icon: categoryIcons[loc.category_id]
                }).addTo(map);
            } else {
                console.log(`Using default icon for location ${loc.id} (no category icon found)`);
                // Use default icon if no custom icon is available
                marker = L.marker([loc.lat, loc.lng]).addTo(map);
            }

            markersMap[loc.id] = marker;
            console.log(`Added marker for location ${loc.id} at [${loc.lat}, ${loc.lng}]`);

            // Prepare popup content
            // نمایش نام دسته‌بندی در پاپ‌آپ نقشه بر اساس زبان فعال سایت (پویای کامل)
let catName = '';
if (loc.category) {
    const lang = document.documentElement.lang || (window.appLocale ? window.appLocale : 'fa');
    catName = loc.category['category_' + lang];
    if (!catName || catName.trim() === '') {
        catName = loc.category.category_en || loc.category.category_fa || '';
    }
            }
            const popupContent = `
                <div class="map-popup">
                    <h5>${loc.title}</h5>
                    ${loc.category ? `<div class="category-badge">${catName}</div>` : ''}
                    ${loc.address ? `<div class="address"><i class="fas fa-map-marker-alt"></i> ${loc.address}</div>` : ''}
                </div>
            `;
marker.bindPopup(popupContent);
            marker.bindPopup(popupContent);

            // Add click event
            marker.on('click', function() {
                highlightLocation(loc.id);
            });
        });
    }

    function updateLocationsList() {
        const template = document.getElementById('location-template');
        const tabsList = document.getElementById('location-tabs');
        const tabsContent = document.getElementById('location-tabs-content');
        if (!tabsList || !tabsContent) return; // اگر المنت‌ها نبودند، ادامه نده
        // Limpiar las pestañas y contenidos de categorías existentes، excepto la pestaña "Todos"
        const existingCategoryTabs = tabsList.querySelectorAll('.nav-item:not(:first-child)');
        existingCategoryTabs.forEach(tab => tab.remove());
        const existingCategoryPanes = tabsContent.querySelectorAll('.tab-pane:not(:first-child)');
        existingCategoryPanes.forEach(pane => pane.remove());
        // Limpiar la lista "Todos"
        const allLocationsPane = document.getElementById('all-locations');
        if (!allLocationsPane) return;
        const allLocationsList = allLocationsPane.querySelector('.location-list');
        if (!allLocationsList) return;

        // Mostrar/ocultar el mensaje de "no hay resultados"
        const noResults = document.getElementById('no-results');
        if (noResults) {
        noResults.style.display = locationsArray.length > 0 ? 'none' : '';
        }

        // Agrupar ubicaciones por categoría
        const locationsByCategory = {};
        let categoriesInfo = {};

        locationsArray.forEach(function(loc) {
            if (loc.category) {
                const categoryId = loc.category_id;

                // Inicializar el array de la categoría si no existe
                if (!locationsByCategory[categoryId]) {
                    locationsByCategory[categoryId] = [];
                    categoriesInfo[categoryId] = {
                        name: loc.category.category_fa,
                        emoji: loc.category.emoji,
                        icon: (categoryId && categoryImagePaths[categoryId]) ? categoryImagePaths[categoryId] : null
                    };
                }

                // Añadir la ubicación a su categoría correspondiente
                locationsByCategory[categoryId].push(loc);
            }
        });

        // Añadir todas las ubicaciones a la pestaña "Todos"
        locationsArray.forEach(function(loc) {
            addLocationToList(loc, allLocationsList, template);
        });

        // Crear pestañas para cada categoría
        Object.keys(locationsByCategory).forEach(function(categoryId) {
            const locations = locationsByCategory[categoryId];
            const categoryInfo = categoriesInfo[categoryId];

            if (locations.length > 0) {
                // Crear la pestaña
                const tabId = `category-${categoryId}-tab`;
                const paneId = `category-${categoryId}`;

                let tabIcon = '';
                if (categoryInfo.icon) {
                    tabIcon = `<img src="${categoryInfo.icon}" class="category-icon-img me-2" alt="" />`;
                } else if (categoryInfo.emoji) {
                    tabIcon = `<span class="me-2">${categoryInfo.emoji}</span>`;
                }

                // نمایش نام دسته‌بندی در تب فیلتر پایین نقشه بر اساس زبان فعال سایت (پویای کامل)
                let tabCatName = '';
                if (locations[0] && locations[0].category) {
                    const lang = document.documentElement.lang || (window.appLocale ? window.appLocale : 'fa');
                    tabCatName = locations[0].category['category_' + lang];
                    if (!tabCatName || tabCatName.trim() === '') {
                        tabCatName = locations[0].category.category_en || locations[0].category.category_fa || '';
                    }
                }
                const tabHtml = `
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="${tabId}" data-bs-toggle="tab" data-bs-target="#${paneId}"
                            type="button" role="tab" aria-controls="${paneId}" aria-selected="false">
                            <span class="category-count">${locations.length}</span>
                            ${tabIcon}${tabCatName}
                        </button>
                    </li>
                `;
                tabsList.insertAdjacentHTML('beforeend', tabHtml);

                // Crear el contenido de la pestaña
                const paneHtml = `
                    <div class="tab-pane fade" id="${paneId}" role="tabpanel" aria-labelledby="${tabId}">
                        <div class="location-list row row-cols-1 row-cols-md-2 g-3 category-${categoryId}-list"></div>
                    </div>
                `;
                tabsContent.insertAdjacentHTML('beforeend', paneHtml);

                // Añadir ubicaciones a esta pestaña
                const categoryList = document.querySelector(`.category-${categoryId}-list`);
                locations.forEach(function(loc) {
                    addLocationToList(loc, categoryList, template);
                });
            }
        });

        // نمایش فقط perPage آیتم اول و نمایش دکمه بارگذاری بیشتر در صورت وجود آیتم بیشتر
        const allItems = allLocationsList.querySelectorAll('.location-item:not(#location-template):not(#no-results)');
        allItems.forEach((item, idx) => {
            if (idx < perPage * currentPage) {
                item.classList.remove('d-none');
            } else {
                item.classList.add('d-none');
            }
        });
        const loadMoreButton = document.getElementById('load-more-locations');
        if (loadMoreButton) {
            if (allItems.length > perPage * currentPage) {
                loadMoreButton.classList.remove('d-none');
            } else {
                loadMoreButton.classList.add('d-none');
            }
        }
        showLoading(false);
    }

    // Función auxiliar para añadir una ubicación a una lista
    function addLocationToList(loc, listElement, template) {
        // Crear elemento de lista
        const item = template.cloneNode(true);
        item.id = `location-${loc.id}`;
        item.classList.remove('d-none');
        item.classList.add('col');
        item.querySelector('.location-name').textContent = loc.title;

        // آدرس: شهر، شهرستان، استان، کشور
        let addressParts = [];
        const lang = document.documentElement.lang || 'fa';
        if (loc.city && (lang === 'en' ? loc.city.name_en : loc.city.name)) {
            addressParts.push(lang === 'en' ? loc.city.name_en : loc.city.name);
        }
        if (loc.county && (lang === 'en' ? loc.county.name_en : loc.county.name)) {
            addressParts.push(lang === 'en' ? loc.county.name_en : loc.county.name);
        }
        if (loc.province && (lang === 'en' ? loc.province.name_en : loc.province.name)) {
            addressParts.push(lang === 'en' ? loc.province.name_en : loc.province.name);
        }
        if (loc.country && (lang === 'en' ? loc.country.name_en : loc.country.name)) {
            addressParts.push(lang === 'en' ? loc.country.name_en : loc.country.name);
        }
        let addressText = addressParts.join(lang === 'en' ? ', ' : '، ');
        if (!addressText && loc.address) {
            addressText = loc.address;
        }
        item.querySelector('.location-address').textContent = addressText;

        // Añadir etiqueta de categoría
        if (loc.category) {
            const categoryBadge = document.createElement('span');
            categoryBadge.className = 'badge bg-secondary me-1';

            // نمایش نام دسته‌بندی بر اساس زبان فعال سایت (پویای کامل)
            const lang = document.documentElement.lang || (window.appLocale ? window.appLocale : 'fa');
            let catName = loc.category['category_' + lang]; // تلاش برای مقدار زبان فعلی
            // اگر مقدار زبان فعلی نبود، fallback به انگلیسی و سپس فارسی
            if (!catName || catName.trim() === '') {
                catName = loc.category.category_en || loc.category.category_fa || '';
            }
            if (loc.category_id && categoryImagePaths[loc.category_id]) {
                categoryBadge.innerHTML = `<img src="${categoryImagePaths[loc.category_id]}" class="category-icon-img-small" alt="" onerror="this.style.display='none'" /> ${catName}`;
            } else if (loc.category.emoji) {
                categoryBadge.innerHTML = `${loc.category.emoji} ${catName}`;
            } else {
                categoryBadge.textContent = catName;
            }

            item.querySelector('.location-categories').appendChild(categoryBadge);
        }

        // Añadir a la lista
        listElement.appendChild(item);

        // Añadir evento click para mostrar el popup cuando se hace clic en el elemento de la lista
        item.addEventListener('click', function() {
            highlightLocation(loc.id);
        });

        // Si hay ubicación del usuario, mostrar información de distancia
        if (userLocation && loc.lat && loc.lng) {
            // Calcular la distancia si no está calculada
            if (loc.distance === undefined) {
                loc.distance = calculateHaversineDistance(
                    userLocation.lat, userLocation.lng,
                    loc.lat, loc.lng
                );
                calculateEstimatedTimes(loc, loc.distance);
            }

            // Actualizar los elementos de distancia
            const distanceElement = item.querySelector('.location-distance');
            const distanceValue = item.querySelector('.distance-value');

            if (distanceElement && distanceValue) {
                // Mostrar la sección de distancia
                distanceElement.classList.remove('d-none');

                // Formatear la distancia
                if (loc.distance < 1000) {
                    distanceValue.textContent = `<?php echo e(__("welcome.routing.distance_meters")); ?>`.replace(':distance', Math.round(loc.distance));
                } else {
                    distanceValue.textContent = `<?php echo e(__("welcome.routing.distance_kilometers")); ?>`.replace(':distance', (loc.distance / 1000).toFixed(1));
                }

                // Mostrar opciones de transporte
                updateTransportOptions(item, loc);

                // Mostrar acciones
                const actionsElement = item.querySelector('.location-actions');
                if (actionsElement) {
                    actionsElement.classList.remove('d-none');

                    // Configurar el botón de direcciones
                    const directionsButton = actionsElement.querySelector('.get-directions');
                    if (directionsButton) {
                        // Eliminar eventos previos para evitar duplicados
                        const newDirectionsButton = directionsButton.cloneNode(true);
                        directionsButton.parentNode.replaceChild(newDirectionsButton, directionsButton);

                        newDirectionsButton.addEventListener('click', function() {
                            showDirections(loc);
                        });
                    }

                    // Configurar el enlace de Google Maps
                    const googleMapsLink = actionsElement.querySelector('.open-google-maps');
                    if (googleMapsLink) {
                        // Determine appropriate travel mode based on distance
                        let travelMode = 'driving'; // Default
                        if (loc.distance <= 5000) {
                            travelMode = 'walking';
                        } else if (loc.distance <= 20000) {
                            travelMode = 'transit'; // Bus/public transit
                        }

                        googleMapsLink.href = `https://www.google.com/maps/dir/?api=1&origin=${userLocation.lat},${userLocation.lng}&destination=${loc.lat},${loc.lng}&travelmode=${travelMode}`;
                        googleMapsLink.classList.remove('d-none');
                    }
                }
            }
        }
    }

    function highlightLocation(locationId) {
        // Highlight in list
        document.querySelectorAll('.location-item').forEach(el => el.classList.remove('selected'));
        const listItem = document.getElementById(`location-${locationId}`);
        if (listItem) {
            listItem.classList.add('selected');
            listItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }

        // Show popup on map
        const marker = markersMap[locationId];
        if (marker) {
            marker.openPopup();

            // Find the location object
            const location = locationsArray.find(loc => loc.id == locationId);
            if (location && location.lat && location.lng) {
                map.setView([location.lat, location.lng], 13);
            }
        }
    }

    function fitMapToBounds() {
        // Create a bounds object
        const bounds = L.latLngBounds();

        // Add all marker positions to the bounds
        let hasValidMarkers = false;
        locationsArray.forEach(function(loc) {
            if (loc.lat && loc.lng) {
                bounds.extend([loc.lat, loc.lng]);
                hasValidMarkers = true;
            }
        });

        // If we have valid markers, fit the map to these bounds
        if (hasValidMarkers) {
            map.fitBounds(bounds, {
                padding: [50, 50],
                maxZoom: 15
            });
        }
    }

    // Function to initialize Leaflet map
    function initLeafletMap() {
        console.log("Initializing Leaflet map...");

        // Check if Leaflet is loaded
        if (typeof L === 'undefined') {
            console.log('Leaflet not loaded yet, waiting...');
            setTimeout(initLeafletMap, 500);
            return;
        }

        try {
            // Check if the map container exists
            const mapContainer = document.getElementById('map');
            if (!mapContainer) {
                console.error("Map container not found");
                return;
            }

            // Check if map is already initialized
            if (window.map && typeof window.map.getZoom === 'function') {
                console.log('Map already initialized, skipping...');
                return;
            }

            // Create a map centered on Iran
            map = L.map('map').setView([32.4279, 53.6880], 5);

            // Add OpenStreetMap tiles
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            console.log("Map initialized successfully");

            // Add custom styles for markers
            const style = document.createElement('style');
            style.textContent = `
                /* Aplicar fuente a todos los elementos de Leaflet */
                .leaflet-container {
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                }

                /* Aplicar fuente a tooltips y popups */
                .leaflet-tooltip, .leaflet-popup-content {
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                    direction: rtl;
                    text-align: right;
                }

                .map-marker {
                    background-color: transparent;
                }

                .map-marker-icon {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 36px;
                    height: 36px;
                    background-color: white;
                    border-radius: 50%;
                    box-shadow: 0 2px 5px rgba(0,0,0,0.3);
                    font-size: 18px;
                    border: 2px solid #4a89dc;
                }

                .map-popup {
                    padding: 5px;
                    min-width: 200px;
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                }

                .map-popup h5 {
                    margin: 0 0 5px;
                    font-size: 16px;
                    font-weight: bold;
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                }

                .map-popup .category-badge {
                    display: inline-block;
                    background-color: #f0f0f0;
                    padding: 2px 8px;
                    border-radius: 10px;
                    font-size: 12px;
                    margin-bottom: 5px;
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                }

                .map-popup .address {
                    font-size: 13px;
                    color: #666;
                    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
                }

                .map-loading {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background-color: rgba(255,255,255,0.8);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 1000;
                }

                /* Estilos para íconos de imagen */
                .category-icon-img {
                    width: 20px;
                    height: 20px;
                    object-fit: contain;
                    vertical-align: middle;
                }

                .category-icon-img-small {
                    width: 16px;
                    height: 16px;
                    object-fit: contain;
                    vertical-align: middle;
                    margin-right: 4px;
                }
            `;
            document.head.appendChild(style);

        } catch (error) {
            console.error('Error initializing map:', error);
            const mapContainer = document.getElementById('map');
            if (mapContainer) {
                mapContainer.innerHTML = '<div class="map-error-container"><div class="map-error-message">خطا در بارگذاری نقشه: ' + error.message + '</div></div>';
            }
        }
    }

    // Add this new function after resetAllFilters()
    function resetCategoryFilter() {
        // Clear active state from categories
        document.querySelectorAll('.parent-category.active, .child-category.active').forEach(function(element) {
            element.classList.remove('active');
        });

        // Show all categories
        document.querySelectorAll('.parent-category, .child-category').forEach(function(element) {
            element.style.display = 'flex';
        });

        // Reset category counts to original values
        document.querySelectorAll('.parent-category, .child-category').forEach(function(element) {
            const countSpan = element.querySelector('.category-count');
            if (countSpan && countSpan.dataset.originalCount) {
                countSpan.textContent = countSpan.dataset.originalCount;
            }
        });

        // Update filter
        updateCategoryFilters();
    }

    // Add this new function to fetch and update categories based on geographic filters
    function updateCategoriesByRegion() {
        // Build query parameters based on active geographic filters
        const params = new URLSearchParams();

        if (activeFilters.country) {
            params.append('country', activeFilters.country);
        }

        if (activeFilters.province) {
            params.append('province', activeFilters.province);
        }

        if (activeFilters.county) {
            params.append('county', activeFilters.county);
        }

        if (activeFilters.district) {
            params.append('district', activeFilters.district);
        }

        if (activeFilters.city) {
            params.append('city', activeFilters.city);
        }

        if (activeFilters.village) {
            params.append('village', activeFilters.village);
        }

        if (activeFilters.zone) {
            params.append('zone', activeFilters.zone);
        }

        // If no geographic filters are active, reset to show all categories
        if (params.toString() === '') {
            resetCategoryFilter();
            return;
        }

        // Add a loading state to the category filter
        const categoryContainer = document.querySelector('.category-filter-container');
        categoryContainer.classList.add('loading');

        // Use the existing search API to get available categories
        params.append('get_categories_only', '1'); // Add parameter to only get categories

        fetch(`/api/search?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                // Add detailed logging
                console.log('API Response:', data);

                if (data.success) {
                    // Check if categories are provided in the response
                    if (data.categories) {
                        console.log('Categories found:', data.categories.length);
                        console.log('First category sample:', data.categories[0]);

                        updateCategoryDisplay(data.categories);
                    } else {
                        console.warn('Categories not provided in the API response');
                        resetCategoryFilter();
                    }
                } else {
                    console.error('Error fetching categories by region:', data.message || 'Unknown error');
                    resetCategoryFilter();
                }
                categoryContainer.classList.remove('loading');
            })
            .catch(error => {
                console.error('Error fetching categories by region:', error);
                resetCategoryFilter();
                categoryContainer.classList.remove('loading');
            });
    }

    // Add this new function to update the category display
    function updateCategoryDisplay(categories) {
        console.log('Updating category display with', categories);

        // Store all available category IDs from the API response
        const availableCategoryIds = new Set();
        const categoryCounts = {};

        // Process the response to get all category IDs and their counts
        categories.forEach(category => {
            availableCategoryIds.add(category.id.toString());
            categoryCounts[category.id] = category.location_count;
            console.log(`Parent category ${category.id} (${category.category_fa}) has ${category.location_count} locations`);

            // Add child categories if present
            if (category.children && Array.isArray(category.children)) {
                category.children.forEach(child => {
                    availableCategoryIds.add(child.id.toString());
                    categoryCounts[child.id] = child.location_count;
                    console.log(`- Child category ${child.id} (${child.category_fa}) has ${child.location_count} locations`);
                });
            }
        });

        // Process all parent categories
        document.querySelectorAll('.parent-category').forEach(parentElement => {
            const parentId = parentElement.getAttribute('data-category-id');
            const parentCountElement = parentElement.querySelector('.category-count');

            // Store original count if not already stored
            if (parentCountElement && !parentCountElement.dataset.originalCount) {
                parentCountElement.dataset.originalCount = parentCountElement.textContent;
            }

            // Check if this parent or any of its children are in the available categories
            const childrenContainer = parentElement.nextElementSibling;
            let parentHasChildren = false;
            let parentTotalCount = 0;

            if (childrenContainer && childrenContainer.classList.contains('children-container')) {
                const childElements = childrenContainer.querySelectorAll('.child-category');

                childElements.forEach(childElement => {
                    const childId = childElement.getAttribute('data-category-id');
                    const childCountElement = childElement.querySelector('.category-count');

                    // Store original count if not already stored
                    if (childCountElement && !childCountElement.dataset.originalCount) {
                        childCountElement.dataset.originalCount = childCountElement.textContent;
                    }

                    if (availableCategoryIds.has(childId)) {
                        // Show child category
                        childElement.style.display = 'flex';

                        // Update child count
                        if (childCountElement && categoryCounts[childId] !== undefined) {
                            childCountElement.textContent = `(${categoryCounts[childId]})`;
                        }

                        parentHasChildren = true;
                        parentTotalCount += (categoryCounts[childId] || 0);
                    } else {
                        // Hide child category
                        childElement.style.display = 'none';

                        // If the hidden category was active, deactivate it
                        if (childElement.classList.contains('active')) {
                            childElement.classList.remove('active');
                            updateCategoryFilters();
                        }
                    }
                });
            }

            // Determine whether to show the parent category
            if (availableCategoryIds.has(parentId) || parentHasChildren) {
                parentElement.style.display = 'flex';

                // Update parent count
                if (parentCountElement) {
                    if (availableCategoryIds.has(parentId) && categoryCounts[parentId] !== undefined) {
                        // If the parent has locations directly
                        parentCountElement.textContent = `(${categoryCounts[parentId]})`;
                        console.log(`Setting parent ${parentId} count to ${categoryCounts[parentId]}`);
                    } else if (parentHasChildren) {
                        // If the parent only has locations through children
                        parentCountElement.textContent = `(${parentTotalCount})`;
                        console.log(`Setting parent ${parentId} count to ${parentTotalCount} from children`);
                    }
                }
            } else {
                // Hide parent category
                parentElement.style.display = 'none';

                // If the hidden category was active, deactivate it
                if (parentElement.classList.contains('active')) {
                    parentElement.classList.remove('active');
                    updateCategoryFilters();
                }
            }
        });
    }

    // Función para aplicar íconos a los filtros de categoría
    function applyCategoryIcons() {
        // Aplicar íconos a las categorías padre
        document.querySelectorAll('.parent-category').forEach(function(element) {
            const categoryId = element.getAttribute('data-category-id');
            const emojiSpan = element.querySelector('.category-emoji');

            // Si la categoría tiene un icono de imagen, reemplazar el emoji
            if (categoryId in categoryImagePaths) {
                if (emojiSpan) {
                    // Reemplazar el emoji con una imagen
                    const imgHtml = `<img src="${categoryImagePaths[categoryId]}" class="category-icon-img" alt="" />`;
                    emojiSpan.innerHTML = imgHtml;
                } else {
                    // Si no hay span de emoji, crear uno
                    const imgHtml = `<span class="category-emoji me-1"><img src="${categoryImagePaths[categoryId]}" class="category-icon-img" alt="" /></span>`;
                    element.insertAdjacentHTML('afterbegin', imgHtml);
                }
            }
        });

        // Aplicar íconos a las categorías hijo
        document.querySelectorAll('.child-category').forEach(function(element) {
            const categoryId = element.getAttribute('data-category-id');
            const emojiSpan = element.querySelector('.category-emoji');

            // Si la categoría tiene un icono de imagen, reemplazar el emoji
            if (categoryId in categoryImagePaths) {
                if (emojiSpan) {
                    // Reemplazar el emoji con una imagen
                    const imgHtml = `<img src="${categoryImagePaths[categoryId]}" class="category-icon-img" alt="" />`;
                    emojiSpan.innerHTML = imgHtml;
                } else {
                    // Si no hay span de emoji, crear uno
                    const imgHtml = `<span class="category-emoji me-1"><img src="${categoryImagePaths[categoryId]}" class="category-icon-img" alt="" /></span>`;
                    element.insertAdjacentHTML('afterbegin', imgHtml);
                }
            }
        });
    }

    // Función para inicializar el servicio de direcciones
    function initDirectionsService() {
        // Inicializar una alternativa usando la API de OSRM directamente
        directionsRenderer = {
            waypoints: [],
            currentRoute: null,

            route: function() {
                if (this.waypoints.length < 2) {
                    console.log('Se necesitan al menos dos puntos para calcular una ruta');
                    return;
                }

                // Limpiar rutas anteriores
                if (this.currentRoute) {
                    map.removeLayer(this.currentRoute);
                }

                this.getRouteFromOSRM(this.waypoints)
                    .then(routeData => {
                        if (routeData && routeData.routes && routeData.routes.length > 0) {
                            // Obtener las coordenadas de la ruta
                            const route = routeData.routes[0];
                            const geometry = this.decodePolyline(route.geometry);

                            // Crear línea de ruta
                            this.currentRoute = L.polyline(geometry, {
                                color: '#0d6efd',
                                weight: 5,
                                opacity: 0.7
                            }).addTo(map);

                            // Ajustar vista
                            map.fitBounds(this.currentRoute.getBounds(), {
                                padding: [100, 100]
                            });

                            // Mostrar información de la ruta
                            console.log(`Ruta calculada: ${(route.distance / 1000).toFixed(1)} km, ${Math.round(route.duration / 60)} minutos`);
                        } else {
                            console.error('No se pudo calcular la ruta');
                        }
                    })
                    .catch(error => {
                        console.error('Error al calcular la ruta:', error);

                        // Fallback a línea recta si falla
                        const coords = this.waypoints.map(wp => [wp.lat, wp.lng]);
                        this.currentRoute = L.polyline(coords, {
                            color: '#dc3545',
                            weight: 4,
                            opacity: 0.7,
                            dashArray: '10, 10'
                        }).addTo(map);

                        map.fitBounds(this.currentRoute.getBounds(), {
                            padding: [100, 100]
                        });
                    });
            },

            setWaypoints: function(waypoints) {
                this.waypoints = waypoints;
            },

            getRouteFromOSRM: function(waypoints) {
                // Formato de la API OSRM: {lng},{lat};{lng},{lat}
                const coordinates = waypoints.map(wp => `${wp.lng},${wp.lat}`).join(';');
                const url = `https://router.project-osrm.org/route/v1/driving/${coordinates}?overview=full&geometries=polyline`;

                return fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Error en la respuesta de la API');
                        }
                        return response.json();
                    });
            },

            // Decodificar polyline de Google (usado por OSRM)
            decodePolyline: function(str, precision) {
                var index = 0,
                    lat = 0,
                    lng = 0,
                    coordinates = [],
                    shift = 0,
                    result = 0,
                    byte = null,
                    latitude_change,
                    longitude_change,
                    factor = Math.pow(10, precision || 5);

                // Coordinates have variable length when encoded, so just keep
                // track of whether we've hit the end of the string. In each
                // loop iteration, a single coordinate is decoded.
                while (index < str.length) {
                    // Reset shift, result, and byte
                    byte = null;
                    shift = 0;
                    result = 0;

                    do {
                        byte = str.charCodeAt(index++) - 63;
                        result |= (byte & 0x1f) << shift;
                        shift += 5;
                    } while (byte >= 0x20);

                    latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

                    shift = result = 0;

                    do {
                        byte = str.charCodeAt(index++) - 63;
                        result |= (byte & 0x1f) << shift;
                        shift += 5;
                    } while (byte >= 0x20);

                    longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

                    lat += latitude_change;
                    lng += longitude_change;

                    coordinates.push([lat / factor, lng / factor]);
                }

                return coordinates;
            }
        };

        console.log('Servicio de direcciones OSRM inicializado correctamente');
    }

    // Función para calcular distancias reales por carretera usando OSRM
    function calculateRouteDistances() {
        if (!userLocation) {
            console.log("No hay ubicación de usuario disponible para calcular distancias");
            return;
        }

        console.log('Calculando distancias por carretera para', locationsArray.length, 'ubicaciones');

        // Contador para operaciones completadas
        let completedCount = 0;
        const validLocations = locationsArray.filter(loc => loc.lat && loc.lng);
        const totalLocations = validLocations.length;

        // Mostrar indicador de progreso
        const statusElement = document.getElementById('user-location-status');
        statusElement.classList.remove('d-none');
        statusElement.innerHTML = `<span class="text-info"><i class="fas fa-spinner fa-spin me-1"></i><?php echo e(__("welcome.routing.getting_location")); ?></span>`;

        // Verificar si hay demasiadas ubicaciones para calcular (más de 200)
        if (totalLocations > 200) {
            if (!confirm(`تعداد ${totalLocations} مکان برای محاسبه مسافت وجود دارد. این عملیات ممکن است زمان زیادی طول بکشد.\n\nآیا مایل به ادامه هستید؟`)) {
                statusElement.innerHTML = `<span class="text-warning"><i class="fas fa-exclamation-circle me-1"></i>محاسبه مسافت‌ها لغو شد</span>`;
                setTimeout(() => {
                    statusElement.classList.add('d-none');
                }, 3000);
                return;
            }
        }

        // Mostrar mensaje de progreso
        statusElement.innerHTML = `<span class="text-info"><i class="fas fa-spinner fa-spin me-1"></i><?php echo e(__("welcome.routing.calculating_distances")); ?> (0/${totalLocations})</span>`;

        // Procesar ubicaciones en lotes para no sobrecargar la API
        const batchSize = 5;
        const locationBatches = [];

        // Crear lotes de ubicaciones
        let currentBatch = [];
        validLocations.forEach(loc => {
            currentBatch.push(loc);

            if (currentBatch.length === batchSize) {
                locationBatches.push([...currentBatch]);
                currentBatch = [];
            }
        });

        // Añadir el último lote si contiene elementos
        if (currentBatch.length > 0) {
            locationBatches.push(currentBatch);
        }

        // Preparar ubicaciones sin coordenadas
        locationsArray.forEach(loc => {
            if (!loc.lat || !loc.lng) {
                loc.distance = Infinity;
            }
        });

        // Si no hay ubicaciones válidas
        if (totalLocations === 0) {
            statusElement.innerHTML = `<span class="text-warning"><i class="fas fa-exclamation-circle me-1"></i><?php echo e(__("welcome.routing.no_valid_locations")); ?></span>`;
            setTimeout(() => {
                statusElement.classList.add('d-none');
            }, 3000);
            return;
        }

        // Función para procesar un lote
        const processBatch = (batchIndex) => {
            // Comprobar si hemos terminado
            if (batchIndex >= locationBatches.length) {
                // Todos los lotes procesados
                statusElement.innerHTML = `<span class="text-success"><i class="fas fa-check-circle me-1"></i><?php echo e(__("welcome.routing.calculation_completed")); ?></span>`;

                // Ordenar por distancia
                sortLocationsByDistance();

                // Mostrar distancias
                refreshDistances();

                // Ocultar mensaje después de 3 segundos
                setTimeout(() => {
                    statusElement.classList.add('d-none');
                }, 3000);

                return;
            }

            const batch = locationBatches[batchIndex];
            const batchPromises = batch.map(loc => {
                return calculateSingleRouteDistance(userLocation, loc)
                    .then(routeData => {
                        try {
                            if (routeData && routeData.routes && routeData.routes.length > 0) {
                                const route = routeData.routes[0];

                                // Guardar distancia en el objeto de ubicación (en metros)
                                loc.distance = route.distance;

                                // Guardar duración en segundos
                                loc.duration = route.duration;

                                // Calcular tiempos para otros medios de transporte (aproximados)
                                calculateEstimatedTimesFromDuration(loc, route.duration, route.distance);

                                const routeType = routeData.code === 'Ok' ? '<?php echo e(__("welcome.routing.road")); ?>' : '<?php echo e(__("welcome.routing.straight_line")); ?>';
                                console.log(`<?php echo e(__("welcome.routing.location_distance_time", ["id" => "loc.id", "title" => "loc.title", "type" => "routeType", "distance" => "(route.distance / 1000).toFixed(2)", "time" => "Math.round(route.duration / 60)"])); ?>`);
                            } else {
                                // Si no hay rutas, usar distancia haversine como fallback
                                loc.distance = calculateHaversineDistance(
                                    userLocation.lat, userLocation.lng,
                                    loc.lat, loc.lng
                                );

                                // Estimar duración
                                loc.duration = loc.distance / 13.9; // Aproximadamente 50 km/h

                                calculateEstimatedTimes(loc, loc.distance);

                                console.warn(`<?php echo e(__("welcome.routing.route_calculation_failed", ["id" => "loc.id", "title" => "loc.title"])); ?>`);
                            }
                        } catch (error) {
                            console.error(`<?php echo e(__("welcome.routing.error_processing_response", ["id" => "loc.id"])); ?>`, error);

                            // Usar distancia haversine como fallback
                            loc.distance = calculateHaversineDistance(
                                userLocation.lat, userLocation.lng,
                                loc.lat, loc.lng
                            );

                            calculateEstimatedTimes(loc, loc.distance);
                        }

                        // Actualizar contador de progreso
                        completedCount++;
                        statusElement.innerHTML = `<span class="text-info"><i class="fas fa-spinner fa-spin me-1"></i><?php echo e(__("welcome.routing.calculating_distances")); ?> (${completedCount}/${totalLocations})</span>`;
                    })
                    .catch(error => {
                        console.error(`Error al calcular ruta para ubicación ${loc.id}:`, error);

                        // Usar distancia haversine como fallback
                        loc.distance = calculateHaversineDistance(
                            userLocation.lat, userLocation.lng,
                            loc.lat, loc.lng
                        );

                        calculateEstimatedTimes(loc, loc.distance);

                        // Actualizar contador
                        completedCount++;
                        statusElement.innerHTML = `<span class="text-info"><i class="fas fa-spinner fa-spin me-1"></i><?php echo e(__("welcome.routing.calculating_distances")); ?> (${completedCount}/${totalLocations})</span>`;
                    });
            });

            // Procesar promesas del lote actual con manejo de errores
            Promise.all(batchPromises.map(p => p.catch(e => e)))
                .then(() => {
                    // Procesar siguiente lote con un pequeño retraso para no sobrecargar la API
                    setTimeout(() => {
                        processBatch(batchIndex + 1);
                    }, 1000);
                })
                .catch(error => {
                    console.error('Error general procesando lote de rutas:', error);
                    // Continuar con el siguiente lote a pesar del error
                    setTimeout(() => {
                        processBatch(batchIndex + 1);
                    }, 1000);
                });
        };

        // Iniciar procesamiento del primer lote
        processBatch(0);
    }

    // Función para calcular una sola ruta usando OSRM
    function calculateSingleRouteDistance(origin, destination) {
        // Verificar si las coordenadas están en el mismo continente o área cercana
        const directDistance = calculateHaversineDistance(
            origin.lat, origin.lng,
            destination.lat, destination.lng
        );

        // Si la distancia directa es demasiado grande, no intentamos usar la API OSRM
        if (directDistance > maxRouteDistance) {
            console.log(`<?php echo e(__("welcome.routing.distance_too_large", ["distance" => "(directDistance/1000).toFixed(0)"])); ?>`);
            return Promise.resolve({
                code: 'TooFar',
                routes: [{
                    distance: directDistance,
                    duration: directDistance / 13.9 // Velocidad media: ~50 km/h = 13.9 m/s
                }]
            });
        }

        // Formato OSRM: lng,lat;lng,lat
        const coordinates = `${origin.lng},${origin.lat};${destination.lng},${destination.lat}`;
        const url = `https://router.project-osrm.org/route/v1/driving/${coordinates}?overview=false`;

        return fetch(url)
            .then(response => {
                // Si la respuesta no es exitosa
                if (!response.ok) {
                    console.warn(`<?php echo e(__("welcome.routing.osrm_error", ["status" => "response.status", "text" => "response.statusText"])); ?>`);

                    // Usar distancia haversine como fallback
                    return {
                        code: 'ApiError',
                        routes: [{
                            distance: directDistance,
                            duration: directDistance / 13.9
                        }]
                    };
                }
                return response.json();
            })
            .catch(error => {
                console.error(`<?php echo e(__("welcome.routing.osrm_connection_error", ["error" => "error.message"])); ?>`);

                // Usar distancia haversine como fallback
                return {
                    code: 'ApiError',
                    routes: [{
                        distance: directDistance,
                        duration: directDistance / 13.9
                    }]
                };
            });
    }

    // Función para calcular tiempos estimados a partir de la duración real
    function calculateEstimatedTimesFromDuration(location, durationSeconds, distance) {
        // Guardar tiempo de conducción (ya lo tenemos de la API)
        location.driving_time = formatTime(durationSeconds);

        // Velocidades relativas (factores de conversión)
        const walkingFactor = 5; // Conducir es ~5 veces más rápido que caminar

        // Calcular otros tiempos
        const walkingTimeSeconds = durationSeconds * walkingFactor;

        // Guardar tiempos estimados
        location.walking_time = formatTime(walkingTimeSeconds);
    }

    // Función para obtener la ubicación del usuario
    function getUserLocation() {
        const statusElement = document.getElementById('user-location-status');
        statusElement.classList.remove('d-none');
        statusElement.innerHTML = `<span class="text-info"><i class="fas fa-spinner fa-spin me-1"></i><?php echo e(__("welcome.routing.getting_location")); ?></span>`;

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    userLocation = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    console.log('Ubicación del usuario obtenida:', userLocation);

                    // Mostrar la ubicación del usuario en el mapa
                    showUserLocationOnMap();

                    // Calcular distancias reales por carretera
                    calculateRouteDistances();

                    // Actualizar el estado
                    statusElement.innerHTML = `<span class="text-success"><i class="fas fa-check-circle me-1"></i>موقعیت شما دریافت شد</span>`;

                    // Habilitar filtro de distancia
                    document.querySelector('.distance-filter').classList.remove('disabled');

                    // Cambiar el botón a "Actualizar mi ubicación"
                    document.getElementById('get-user-location').innerHTML = `<i class="fas fa-sync-alt me-2"></i><?php echo e(__("welcome.location.update_location")); ?>`;

                    // Mostrar notificación de éxito
                    const successNotice = document.createElement('div');
                    successNotice.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
                    successNotice.style.zIndex = '9999';
                    successNotice.innerHTML = '<?php echo e(__("welcome.location.location_updated")); ?>';
                    document.body.appendChild(successNotice);

                    // Eliminar notificación después de 3 segundos
                    setTimeout(() => {
                        document.body.removeChild(successNotice);
                    }, 3000);
                },
                function(error) {
                    console.error('Error al obtener la ubicación del usuario:', error);

                    let errorMessage = '<?php echo e(__("welcome.errors.location_error")); ?>';
                    switch (error.code) {
                        case error.PERMISSION_DENIED:
                            errorMessage = '<?php echo e(__("welcome.errors.permission_denied")); ?>';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMessage = '<?php echo e(__("welcome.errors.position_unavailable")); ?>';
                            break;
                        case error.TIMEOUT:
                            errorMessage = '<?php echo e(__("welcome.errors.timeout")); ?>';
                            break;
                        case error.UNKNOWN_ERROR:
                            errorMessage = '<?php echo e(__("welcome.errors.unknown_error")); ?>';
                            break;
                    }

                    statusElement.innerHTML = `<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i>${errorMessage}</span>`;
                }
            );
        } else {
            statusElement.innerHTML = `<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i><?php echo e(__("welcome.errors.geolocation_not_supported")); ?></span>`;
        }
    }

    // Función para mostrar direcciones entre la ubicación del usuario y un destino
    function showDirections(location) {
        if (!userLocation || !location) return;

        try {
            // Calcular la distancia directa
            const directDistance = calculateHaversineDistance(
                userLocation.lat, userLocation.lng,
                location.lat, location.lng
            );

            // Si la distancia es demasiado grande, mostrar un mensaje
            if (directDistance > maxRouteDistance) {
                const distanceInKm = (directDistance/1000).toFixed(0);
                // Preguntar si desea abrir Google Maps en su lugar
                if (confirm(`<?php echo e(__("welcome.routing.long_distance")); ?>`.replace(':distance', distanceInKm))) {
                    // Determine appropriate travel mode based on distance
                    let travelMode = 'driving'; // Default
                    if (directDistance <= 5000) {
                        travelMode = 'walking';
                    } else if (directDistance <= 20000) {
                        travelMode = 'transit'; // Bus/public transit
                    }

                    const googleMapsUrl = `https://www.google.com/maps/dir/?api=1&origin=${userLocation.lat},${userLocation.lng}&destination=${location.lat},${location.lng}&travelmode=${travelMode}`;
                    window.open(googleMapsUrl, '_blank');
                    return;
                }

                // Mostrar una línea recta simple como alternativa
                if (directionsRenderer.currentRoute) {
                    map.removeLayer(directionsRenderer.currentRoute);
                }

                directionsRenderer.currentRoute = L.polyline([
                    [userLocation.lat, userLocation.lng],
                    [location.lat, location.lng]
                ], {
                    color: '#dc3545',
                    weight: 4,
                    opacity: 0.7,
                    dashArray: '10, 10'
                }).addTo(map);

                const bounds = L.latLngBounds(
                    L.latLng(userLocation.lat, userLocation.lng),
                    L.latLng(location.lat, location.lng)
                );

                map.fitBounds(bounds, {
                    padding: [100, 100]
                });

                // Mostrar el popup del destino
                if (markersMap[location.id]) {
                    markersMap[location.id].openPopup();
                }

                return;
            }

            if (directionsRenderer) {
                // Establecer nuevos puntos
                directionsRenderer.setWaypoints([
                    L.latLng(userLocation.lat, userLocation.lng),
                    L.latLng(location.lat, location.lng)
                ]);

                // Mostrar ruta
                directionsRenderer.route();

                // Mostrar el popup del destino
                if (markersMap[location.id]) {
                    markersMap[location.id].openPopup();
                }
            }
        } catch (error) {
            console.error('Error al mostrar direcciones:', error);
            alert('<?php echo e(__("welcome.routing.error")); ?>');
        }
    }

    // Función para añadir un marcador de destino destacado
    function addDestinationMarker(location) {
        // Eliminar marcador de destino anterior si existe
        if (window.destinationMarker) {
            map.removeLayer(window.destinationMarker);
        }

        // Crear un icono personalizado para el destino
        const destIcon = L.divIcon({
            html: '<div class="destination-marker-icon"><i class="fas fa-flag-checkered"></i></div>',
            className: 'destination-marker',
            iconSize: [36, 36],
            iconAnchor: [18, 36]
        });

        // Añadir marcador de destino
        window.destinationMarker = L.marker([location.lat, location.lng], {
            icon: destIcon,
            zIndexOffset: 900 // Para asegurar que esté por encima de otros marcadores normales
        }).addTo(map);

        // Añadir popup con información resumida
        window.destinationMarker.bindPopup(`
            <div class="destination-popup">
                <div class="destination-badge"><?php echo e(__("welcome.routing.destination")); ?></div>
                <h5>${location.title}</h5>
                <p>${location.distance < 1000 ? Math.round(location.distance) + ' <?php echo e(__("welcome.filters.meters")); ?>' : (location.distance / 1000).toFixed(1) + ' <?php echo e(__("welcome.filters.km")); ?>'} <?php echo e(__("welcome.routing.from_your_location")); ?></p>
                <p>${location.driving_time} <?php echo e(__("welcome.routing.by_car")); ?></p>
                ${location.bus_time && location.distance <= 20000 ? `<p>${location.bus_time} <?php echo e(__("welcome.routing.by_bus")); ?></p>` : ''}
            </div>
        `).openPopup();

        // Agregar estilos para el marcador de destino
        if (!document.getElementById('destination-marker-style')) {
            const style = document.createElement('style');
            style.id = 'destination-marker-style';
            style.textContent = `
                .destination-marker {
                    background-color: transparent;
                }

                .destination-marker-icon {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 36px;
                    height: 36px;
                    background-color: #198754;
                    border-radius: 50%;
                    box-shadow: 0 0 0 4px rgba(25, 135, 84, 0.4);
                    color: white;
                    font-size: 16px;
                    border: 2px solid white;
                    animation: pulse-effect 1.5s infinite;
                }

                .destination-popup {
                    position: relative;
                    padding: 5px;
                    min-width: 200px;
                }

                .destination-popup h5 {
                    margin: 0 0 5px;
                    color: #198754;
                    font-weight: bold;
                }

                .destination-popup p {
                    margin: 0 0 5px;
                    font-size: 13px;
                }
            `;
            document.head.appendChild(style);
        }
    }

    // Función para mostrar la ubicación del usuario en el mapa
    function showUserLocationOnMap() {
        // Eliminar marcador anterior si existe
        if (window.userMarker) {
            map.removeLayer(window.userMarker);
        }

        // Crear un icono personalizado para el usuario
        const userIcon = L.divIcon({
            html: '<div class="user-marker-icon"><i class="fas fa-user"></i></div>',
            className: 'user-marker',
            iconSize: [40, 40],
            iconAnchor: [20, 40]
        });

        // Añadir marcador de usuario
        window.userMarker = L.marker([userLocation.lat, userLocation.lng], {
            icon: userIcon,
            zIndexOffset: 1000 // Para asegurar que esté por encima de otros marcadores
        }).addTo(map);

        // Añadir círculo de precisión
        if (window.userCircle) {
            map.removeLayer(window.userCircle);
        }

        window.userCircle = L.circle([userLocation.lat, userLocation.lng], {
            radius: 100, // Radio en metros
            color: '#0d6efd',
            fillColor: '#0d6efd',
            fillOpacity: 0.1,
            weight: 1
        }).addTo(map);

        // Centrar el mapa en la ubicación del usuario
        map.setView([userLocation.lat, userLocation.lng], 14);

        // Agregar estilos para el marcador de usuario
        if (!document.getElementById('user-marker-style')) {
            const style = document.createElement('style');
            style.id = 'user-marker-style';
            style.textContent = `
                .user-marker {
                    background-color: transparent;
                }

                .user-marker-icon {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 40px;
                    height: 40px;
                    background-color: #0d6efd;
                    border-radius: 50%;
                    box-shadow: 0 0 0 5px rgba(13, 110, 253, 0.3), 0 0 0 10px rgba(13, 110, 253, 0.1);
                    color: white;
                    font-size: 18px;
                    border: 2px solid white;
                    animation: pulse 2s infinite;
                }

                @keyframes pulse {
                    0% {
                        box-shadow: 0 0 0 0 rgba(13, 110, 253, 0.6);
                    }
                    70% {
                        box-shadow: 0 0 0 10px rgba(13, 110, 253, 0);
                    }
                    100% {
                        box-shadow: 0 0 0 0 rgba(13, 110, 253, 0);
                    }
                }
            `;
            document.head.appendChild(style);
        }
    }

    // Función para calcular distancias desde la ubicación del usuario a todos los lugares
    function calculateDistances() {
        if (!userLocation) {
            console.log("No hay ubicación de usuario disponible para calcular distancias");
            alert("موقعیت کاربر برای محاسبه فاصله در دسترس نیست");
            return;
        }

        console.log('Calculando distancias para', locationsArray.length, 'ubicaciones');

        // Mostrar mensaje de carga
        const loadingMessage = document.createElement('div');
        loadingMessage.className = 'alert alert-info position-fixed top-0 start-50 translate-middle-x mt-3 d-flex align-items-center';
        loadingMessage.style.zIndex = '9999';
        loadingMessage.innerHTML = `
            <div class="spinner-border spinner-border-sm me-2" role="status">
                <span class="visually-hidden">در حال محاسبه...</span>
            </div>
            <span>در حال محاسبه فاصله‌ها... <span id="progress-counter">0</span> از ${locationsArray.length}</span>
        `;
        document.body.appendChild(loadingMessage);

        const progressCounter = document.getElementById('progress-counter');
        const batchSize = 100; // تعداد مکان‌ها در هر دسته
        let processedCount = 0;

        // تقسیم محاسبات به دسته‌های کوچکتر
        function processBatch(startIndex) {
            return new Promise(resolve => {
                setTimeout(() => {
                    const endIndex = Math.min(startIndex + batchSize, locationsArray.length);

                    for (let i = startIndex; i < endIndex; i++) {
                        const loc = locationsArray[i];
                        if (loc.lat && loc.lng) {
                            // Calcular distancia en línea recta (haversine)
                            const distance = calculateHaversineDistance(
                                userLocation.lat, userLocation.lng,
                                loc.lat, loc.lng
                            );

                            // Guardar la distancia en el objeto de ubicación
                            loc.distance = distance;

                            // Calcular tiempos estimados para diferentes modos de transporte
                            calculateEstimatedTimes(loc, distance);
                        } else {
                            loc.distance = Infinity;
                        }

                        // Actualizar contador de progreso
                        processedCount++;
                        progressCounter.textContent = processedCount;
                    }

                    resolve();
                }, 0);
            });
        }

        // Procesar todas las ubicaciones en lotes y actualizar la interfaz cuando termine
        async function processAllLocations() {
            for (let i = 0; i < locationsArray.length; i += batchSize) {
                await processBatch(i);
            }

            // Eliminar mensaje de carga
            document.body.removeChild(loadingMessage);

            // Mostrar distancias en la interfaz
            refreshDistances();

            // Ordenar por distancia
            sortLocationsByDistance();

            // Mostrar mensaje de éxito
            const successMessage = document.createElement('div');
            successMessage.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
            successMessage.style.zIndex = '9999';
            successMessage.innerHTML = 'محاسبه فاصله‌ها با موفقیت انجام شد';
            document.body.appendChild(successMessage);

            // Eliminar mensaje después de 3 segundos
            setTimeout(() => {
                document.body.removeChild(successMessage);
            }, 3000);
        }

        // Iniciar procesamiento
        processAllLocations();
    }

    // Función para refrescar la visualización de distancias
    function refreshDistances() {
        console.log("Refrescando distancias. maxDistanceFilter:", maxDistanceFilter, "showUnlimitedDistance:", showUnlimitedDistance);

        if (!userLocation) {
            console.log("No hay ubicación de usuario disponible");
            return;
        }

        // Seleccionamos todos los elementos de ubicación excepto el template
        const items = document.querySelectorAll('.location-item:not(#location-template)');
        console.log(`Procesando ${items.length} ubicaciones`);

        // Configuración para procesamiento por lotes
        const batchSize = 100;
        let processedCount = 0;

        // Mensaje de carga
        const loadingMessage = document.createElement('div');
        loadingMessage.className = 'alert alert-info position-fixed top-0 start-50 translate-middle-x mt-3 d-flex align-items-center';
        loadingMessage.style.zIndex = '9999';
        loadingMessage.innerHTML = `
            <div class="spinner-border spinner-border-sm me-2" role="status">
                <span class="visually-hidden">در حال به‌روزرسانی...</span>
            </div>
            <span>در حال به‌روزرسانی نمایش فاصله‌ها... <span id="refresh-progress">0</span> از ${items.length}</span>
        `;
        document.body.appendChild(loadingMessage);

        const progressCounter = document.getElementById('refresh-progress');

        // Procesar por lotes
        function processBatch(startIndex) {
            return new Promise(resolve => {
                setTimeout(() => {
                    const endIndex = Math.min(startIndex + batchSize, items.length);

                    for (let i = startIndex; i < endIndex; i++) {
                        const item = items[i];

                        // Extraer el ID de la ubicación desde el ID del elemento
                        const id = item.id.replace('location-', '');

                        // Encontrar la ubicación correspondiente en el array
                        const location = locationsArray.find(loc => loc.id == id);

                        if (location && location.distance !== undefined) {
                            // Seleccionar elementos dentro del item
                            const distanceElement = item.querySelector('.location-distance');
                            const distanceValue = item.querySelector('.distance-value');
                            const actionsElement = item.querySelector('.location-actions');

                            if (!distanceElement || !distanceValue) {
                                console.log(`Elementos de distancia no encontrados para la ubicación ${id}`);
                                continue;
                            }

                            // Verificar si la ubicación está dentro del rango o si mostramos todas las distancias
                            const inRange = location.distance < maxDistanceFilter * 1000;
                            const shouldShow = inRange || showUnlimitedDistance;

                            if (shouldShow) {
                                // Mostrar la sección de distancia
                                distanceElement.classList.remove('d-none');

                                // Formatear la distancia
                                if (location.distance < 1000) {
                                    distanceValue.textContent = `<?php echo e(__("welcome.routing.distance_meters")); ?>`.replace(':distance', Math.round(location.distance));
                                } else {
                                    distanceValue.textContent = `<?php echo e(__("welcome.routing.distance_kilometers")); ?>`.replace(':distance', (location.distance / 1000).toFixed(1));
                                }

                                // Mostrar opciones de transporte
                                updateTransportOptions(item, location);

                                // Mostrar acciones si existen
                                if (actionsElement) {
                                    actionsElement.classList.remove('d-none');

                                    // Configurar el botón de direcciones
                                    const directionsButton = actionsElement.querySelector('.get-directions');
                                    if (directionsButton) {
                                        // Eliminar eventos previos para evitar duplicados
                                        const newDirectionsButton = directionsButton.cloneNode(true);
                                        directionsButton.parentNode.replaceChild(newDirectionsButton, directionsButton);

                                        newDirectionsButton.addEventListener('click', function() {
                                            showDirections(location);
                                        });
                                    }

                                    // Configurar el enlace de Google Maps
                                    const googleMapsLink = actionsElement.querySelector('.open-google-maps');
                                    if (googleMapsLink) {
                                        // Determine appropriate travel mode based on distance
                                        let travelMode = 'driving'; // Default
                                        if (location.distance <= 5000) {
                                            travelMode = 'walking';
                                        } else if (location.distance <= 20000) {
                                            travelMode = 'transit'; // Bus/public transit
                                        }

                                        googleMapsLink.href = `https://www.google.com/maps/dir/?api=1&origin=${userLocation.lat},${userLocation.lng}&destination=${location.lat},${location.lng}&travelmode=${travelMode}`;
                                        googleMapsLink.classList.remove('d-none');
                                    }
                                }

                                // Mostrar el elemento
                                item.classList.remove('d-none');
                            } else {
                                // Ocultar elementos que están fuera del rango de distancia
                                item.classList.add('d-none');
                            }
                        } else {
                            console.log(`No se encontró distancia para la ubicación ${id}`);
                        }

                        // Actualizar contador de progreso
                        processedCount++;
                        progressCounter.textContent = processedCount;
                    }

                    resolve();
                }, 0);
            });
        }

        // Procesar todas las ubicaciones en lotes y actualizar contadores cuando termine
        async function processAllItems() {
            for (let i = 0; i < items.length; i += batchSize) {
                await processBatch(i);
            }

            // Eliminar mensaje de carga
            document.body.removeChild(loadingMessage);

            // Actualizar contador de ubicaciones visibles
            updateLocationCounts();
        }

        // Iniciar procesamiento
        processAllItems();
    }

    // Función para actualizar los contadores de ubicaciones
    function updateLocationCounts() {
        // Contar ubicaciones visibles en total
        const visibleLocations = document.querySelectorAll('#all-locations .location-item:not(#location-template):not(.d-none)').length;
        const allLocationsCount = document.getElementById('all-locations-count');
        if (allLocationsCount) {
            allLocationsCount.textContent = visibleLocations;
        }
        // Contar ubicaciones visibles por categoría
        document.querySelectorAll('[id^="category-"][id$="-tab"]').forEach(function(tab) {
            const categoryId = tab.id.replace('category-', '').replace('-tab', '');
            const categoryPane = document.getElementById(`category-${categoryId}`);
            if (categoryPane) {
                const visibleInCategory = categoryPane.querySelectorAll('.location-item:not(.d-none)').length;
                const countElement = tab.querySelector('.category-count');
                if (countElement) {
                    countElement.textContent = visibleInCategory;
                }
            }
        });
    }

    // Función para actualizar las opciones de transporte
    function updateTransportOptions(itemElement, location) {
        // Opciones de transporte
        const walkingOption = itemElement.querySelector('.transport-walking');
        const drivingOption = itemElement.querySelector('.transport-driving');
        const busOption = itemElement.querySelector('.transport-bus');

        // Mostrar opción de caminar si la distancia es menor a 5km
        if (location.distance <= 5000 && location.walking_time) {
            walkingOption.classList.remove('d-none');
            walkingOption.querySelector('.transport-time').textContent = location.walking_time;
        } else {
            walkingOption.classList.add('d-none');
        }

        // Mostrar opción de conducir
        if (location.driving_time) {
            drivingOption.classList.remove('d-none');
            drivingOption.querySelector('.transport-time').textContent = location.driving_time;
        } else {
            drivingOption.classList.add('d-none');
        }

        // Mostrar opción de autobús si la distancia es menor a 20km
        if (location.bus_time && location.distance <= 20000) {
            busOption.classList.remove('d-none');
            busOption.querySelector('.transport-time').textContent = location.bus_time;
        } else {
            busOption.classList.add('d-none');
        }
    }

    // Función para calcular tiempos estimados para diferentes modos de transporte
    function calculateEstimatedTimes(location, distance) {
        // Velocidades promedio en metros por segundo
        const walkingSpeed = 1.4; // ~5 km/h
        const drivingSpeed = 13.9; // ~50 km/h
        const busSpeed = 10; // ~36 km/h

        // Calcular tiempos en segundos
        const walkingTimeSeconds = distance / walkingSpeed;
        const drivingTimeSeconds = distance / drivingSpeed;
        const busTimeSeconds = distance / busSpeed;

        // Convertir segundos a formato legible
        location.walking_time = formatTime(walkingTimeSeconds);
        location.driving_time = formatTime(drivingTimeSeconds);
        location.bus_time = formatTime(busTimeSeconds);
    }

    // Función para formatear tiempo en segundos a un formato legible
    function formatTime(timeInSeconds) {
        if (timeInSeconds < 60) {
            return '<?php echo e(__("welcome.routing.time_less_than_minute")); ?>';
        } else if (timeInSeconds < 3600) {
            const minutes = Math.round(timeInSeconds / 60);
            return `<?php echo e(__("welcome.routing.time_minutes")); ?>`.replace(':minutes', minutes);
        } else {
            const hours = Math.floor(timeInSeconds / 3600);
            const minutes = Math.round((timeInSeconds % 3600) / 60);

            if (minutes === 0) {
                return `<?php echo e(__("welcome.routing.time_hours")); ?>`.replace(':hours', hours);
            } else {
                return `<?php echo e(__("welcome.routing.time_hours_minutes")); ?>`.replace(':hours', hours).replace(':minutes', minutes);
            }
        }
    }

    // Función para calcular distancia usando la fórmula de Haversine
    function calculateHaversineDistance(lat1, lon1, lat2, lon2) {
        const R = 6371000; // Radio de la Tierra en metros
        const dLat = deg2rad(lat2 - lat1);
        const dLon = deg2rad(lon2 - lon1);

        const a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
            Math.sin(dLon/2) * Math.sin(dLon/2);

        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c; // Distancia en metros
    }

    function deg2rad(deg) {
        return deg * (Math.PI/180);
    }

    // Función para ordenar ubicaciones por distancia
    function sortLocationsByDistance() {
        if (!userLocation) return;

        // Ordenar array de ubicaciones
        locationsArray.sort((a, b) => {
            // Manejar casos donde no hay distancia calculada
            if (a.distance === undefined) return 1;
            if (b.distance === undefined) return -1;

            return a.distance - b.distance;
        });

        // Reconstruir listas
        updateLocationsList();

        // Volver a mostrar distancias
        refreshDistances();
    }

    // Función para ordenar ubicaciones por nombre
    function sortLocationsByName() {
        // Ordenar array de ubicaciones
        locationsArray.sort((a, b) => {
            return a.title.localeCompare(b.title);
        });

        // Reconstruir listas
        updateLocationsList();

        // Volver a mostrar distancias si hay ubicación de usuario
        if (userLocation) {
            refreshDistances();
        }
    }

    // Función para ordenar ubicaciones por categoría
    function sortLocationsByCategory() {
        // Ordenar array de ubicaciones
        locationsArray.sort((a, b) => {
            // Primero por categoría
            if (a.category && b.category) {
                const catCompare = a.category.category_fa.localeCompare(b.category.category_fa);
                if (catCompare !== 0) return catCompare;
            } else if (a.category) {
                return -1;
            } else if (b.category) {
                return 1;
            }

            // Luego por nombre
            return a.title.localeCompare(b.title);
        });

        // Reconstruir listas
        updateLocationsList();

        // Volver a mostrar distancias si hay ubicación de usuario
        if (userLocation) {
            refreshDistances();
        }
    }

    // Función para centrar el mapa en una ubicación
    function showOnMap(location) {
        if (!location || !location.lat || !location.lng) return;

        map.setView([location.lat, location.lng], 15);

        if (markersMap[location.id]) {
            markersMap[location.id].openPopup();
        }

        // Añadir efecto de rebote al marcador
        if (markersMap[location.id] && markersMap[location.id]._icon) {
            markersMap[location.id]._icon.classList.add('marker-bounce');

            // Quitar la animación después de 2 segundos
            setTimeout(() => {
                if (markersMap[location.id] && markersMap[location.id]._icon) {
                    markersMap[location.id]._icon.classList.remove('marker-bounce');
                }
            }, 2000);
        }
    }

    let currentPage = 1;
    let perPage = <?php echo e((app(\App\Services\DisplaySettingService::class)->getItemsPerPage('homepage','below_map', request()->isMobile()))); ?>;
    let loadMoreText = <?php echo json_encode(app(\App\Services\DisplaySettingService::class)->getLoadMoreText('homepage', 'below_map'), 512) ?>;
    // اطمینان از وجود المنت قبل از مقداردهی متن دکمه بارگذاری بیشتر
    if (document.getElementById('load-more-text')) {
    document.getElementById('load-more-text').textContent = loadMoreText;
    }
    const loadMoreBtn = document.getElementById('load-more-locations');
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', function() {
        currentPage++;
            const spinner = document.getElementById('load-more-spinner');
            if (spinner) spinner.classList.remove('d-none');
        setTimeout(() => {
            updateLocationsList();
                if (spinner) spinner.classList.add('d-none');
        }, 300);
    });
    }
</script>

<!-- Popup advertisement script -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Check if there are any popup ads
        <?php if(isset($adsByPosition['popup']) && $adsByPosition['popup']->count() > 0): ?>
            // Show popup after 3 seconds
            setTimeout(function() {
                const ad = <?php echo $adsByPosition['popup']->first()->toJson(); ?>;
                showPopupAd(ad);
            }, 3000);
        <?php endif; ?>
    });

    function showPopupAd(ad) {
        // Create popup container
        const popup = document.createElement('div');
        popup.className = 'popup-ad';
        popup.setAttribute('data-ad-id', ad.id);

        // Create popup content
        let content = '';

        if (ad.ad_type === 'banner' && ad.image_path) {
            content = `
                <div class="popup-ad-header">
                    <span>${ad.title}</span>
                    <button class="popup-close">&times;</button>
                </div>
                <div class="popup-ad-content">
                    <a href="${ad.target_url}" target="_blank" onclick="trackAdView(${ad.id})">
                        <img src="/storage/${ad.image_path}" alt="${ad.title}" class="img-fluid">
                    </a>
                </div>
            `;
        } else if (ad.ad_type === 'html' && ad.html_content) {
            content = `
                <div class="popup-ad-header">
                    <span>${ad.title}</span>
                    <button class="popup-close">&times;</button>
                </div>
                <div class="popup-ad-content">
                    ${ad.html_content}
                </div>
            `;
        }

        popup.innerHTML = content;
        document.body.appendChild(popup);

        // Track view
        fetch('/ad/view/' + ad.id, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        });

        // Close popup when clicking the close button
        popup.querySelector('.popup-close').addEventListener('click', function() {
            document.body.removeChild(popup);
        });
    }
</script>

<style>
    .popup-ad {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #fff;
        box-shadow: 0 0 20px rgba(0,0,0,0.3);
        border-radius: 5px;
        max-width: 80%;
        max-height: 80%;
        overflow: auto;
        z-index: 9999;
    }

    .popup-ad-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background: #4e73df;
        color: #fff;
        border-radius: 5px 5px 0 0;
    }

    .popup-close {
        background: none;
        border: none;
        color: #fff;
        font-size: 24px;
        cursor: pointer;
    }

    .popup-ad-content {
        padding: 15px;
    }

    .advertisement-container {
        background: #f8f9fc;
        border-radius: 5px;
        overflow: hidden;
    }

    .advertisement-item {
        text-align: center;
    }

    .ad-image {
        max-width: 100%;
        height: auto;
    }
</style>

<!-- Include Boundary Manager -->
<script src="<?php echo e(asset('js/boundary-manager.js')); ?>"></script>

<!-- Include Modern Category Filter -->
<script src="<?php echo e(asset('js/modern-category-filter.js')); ?>"></script>

<!-- Boundary display script -->
<script>
    let boundaryManager = null;

    document.addEventListener('DOMContentLoaded', function() {
        console.log('[BoundaryDisplay] DOM loaded, waiting for map initialization');

        // Initialize boundary display when the map is ready
        let mapCheckInterval = setInterval(function() {
            if (window.map && typeof window.map.getZoom === 'function') {
                console.log('[BoundaryDisplay] Map found, initializing boundary display');
                clearInterval(mapCheckInterval);
                initializeBoundaryDisplay();
            } else {
                console.log('[BoundaryDisplay] Waiting for map...');
            }
        }, 500);

        // Fallback timeout
        setTimeout(function() {
            if (mapCheckInterval) {
                console.warn('[BoundaryDisplay] Map initialization timeout, clearing interval');
                clearInterval(mapCheckInterval);
            }
        }, 10000);
    });

    function initializeBoundaryDisplay() {
        // Initialize the boundary manager
        boundaryManager = new BoundaryManager(window.map);

        console.log('[BoundaryDisplay] Initializing boundary display system');

        // Wait for select2 to be initialized and check multiple times
        let listenerSetupAttempts = 0;
        const maxAttempts = 10;

        function attemptSetupListeners() {
            listenerSetupAttempts++;
            console.log(`[BoundaryDisplay] Attempt ${listenerSetupAttempts} to setup listeners`);

            if ($('#country-select').length && typeof $('#country-select').select2 === 'function') {
                console.log('[BoundaryDisplay] Select2 found, setting up listeners');
                setupBoundaryEventListeners();
            } else if (listenerSetupAttempts < maxAttempts) {
                console.log('[BoundaryDisplay] Select2 not ready, retrying in 1 second');
                setTimeout(attemptSetupListeners, 1000);
            } else {
                console.warn('[BoundaryDisplay] Max attempts reached, setting up basic listeners');
                setupBoundaryEventListeners();
            }
        }

        setTimeout(attemptSetupListeners, 1000);
    }

    function setupBoundaryEventListeners() {
        console.log('[BoundaryDisplay] Setting up event listeners');

        // Use jQuery for select2 compatibility
        $('#country-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] Country select changed: ${regionId}`);
            handleBoundarySelectChange('country', regionId);
        });

        $('#province-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] Province select changed: ${regionId}`);
            handleBoundarySelectChange('province', regionId);
        });

        $('#county-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] County select changed: ${regionId}`);
            handleBoundarySelectChange('county', regionId);
        });

        $('#district-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] District select changed: ${regionId}`);
            handleBoundarySelectChange('district', regionId);
        });

        $('#city-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] City select changed: ${regionId}`);
            handleBoundarySelectChange('city', regionId);
        });

        $('#village-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] Village select changed: ${regionId}`);
            handleBoundarySelectChange('village', regionId);
        });

        $('#zone-select').on('change.boundary', function() {
            const regionId = $(this).val();
            console.log(`[BoundaryDisplay] Zone select changed: ${regionId}`);
            handleBoundarySelectChange('zone', regionId);
        });

        console.log('[BoundaryDisplay] Event listeners setup complete');
    }

    function handleBoundarySelectChange(regionType, regionId) {
        console.log(`[BoundaryDisplay] Region selection changed: ${regionType} = ${regionId}`);

        if (regionId) {
            // Display the boundary for the selected region
            boundaryManager.displayBoundary(regionType, regionId);
        } else {
            // Clear boundary and find the highest level region that is still selected
            boundaryManager.clearBoundary();

            const regionTypes = ['zone', 'village', 'city', 'district', 'county', 'province', 'country'];
            for (const type of regionTypes) {
                const selectValue = $(`#${type}-select`).val();
                if (selectValue) {
                    boundaryManager.displayBoundary(type, selectValue);
                    break;
                }
            }
        }
    }
</script>

<style>
@media (max-width: 991.98px) {
    .location-list-container .col-lg-3 { order:2; margin-bottom: 1rem; }
    .location-list-container .col-lg-9 { order:1; }
}
@media (max-width: 767.98px) {
    .location-list-container .d-flex { flex-direction: column !important; gap: 0.5rem; }
    .location-list-container .sorting-options, .location-list-container .user-location-card { width: 100% !important; }
    .distance-filter { width: 100% !important; }
}
.location-tabs-wrapper { position: static !important; }
</style>

<style>
/* استایل ستون دسته‌بندی‌های فرزند */
.location-child-categories-sidebar {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    background: linear-gradient(to bottom, #f8f9fa, #fff);
    min-height: 300px;
}
.child-categories-list .list-group-item {
    border: none;
    border-radius: 8px;
    margin-bottom: 6px;
    background: #f4f6fb;
    color: #333;
    font-family: 'IRANSans', Tahoma, Arial, sans-serif !important;
    cursor: pointer;
    transition: background 0.2s;
}
.child-categories-list .list-group-item.active, .child-categories-list .list-group-item:hover {
    background: linear-gradient(to right, #007bff, #0056b3);
    color: #fff;
}
@media (max-width: 991.98px) {
    .location-child-categories-sidebar { margin-bottom: 1rem; }
}
</style>
<script>
// افزودن دسته‌های فرزند فعال به ستون کناری به صورت پویا
function renderChildCategoriesSidebar(childCategories) {
    const list = document.querySelector('.child-categories-list');
    if (!list) return;
    list.innerHTML = '';
    if (!childCategories || childCategories.length === 0) {
        list.innerHTML = '<li class="list-group-item text-muted">دسته‌بندی فرعی وجود ندارد</li>';
        return;
    }
    childCategories.forEach(cat => {
        const li = document.createElement('li');
        li.className = 'list-group-item';
        li.textContent = cat.name;
        li.onclick = function() {
            // فیلتر بر اساس دسته فرزند انتخاب شده
            // اینجا می‌توانید منطق فیلتر را اضافه کنید
        };
        list.appendChild(li);
    });
}
// مثال استفاده: renderChildCategoriesSidebar([{name:'رستوران'},{name:'کافی‌شاپ'}]);
</script>

<style>
/* بهبود نمایش لیست مکان‌ها: قرار دادن align-content: flex-end و align-items: stretch برای ردیف اصلی */
.location-list-container .row {
    align-content: flex-end !important;
    align-items: stretch !important;
}
</style>

<style>
/* بهبود نمایش تب‌ها: افزودن align-content و align-items به .nav */
.nav {
    --bs-nav-link-padding-x: 1rem;
    --bs-nav-link-padding-y: 0.5rem;
    --bs-nav-link-font-weight: ;
    --bs-nav-link-color: var(--bs-link-color);
    --bs-nav-link-hover-color: var(--bs-link-hover-color);
    --bs-nav-link-disabled-color: var(--bs-secondary-color);
    display: flex;
    flex-wrap: wrap;
    padding-right: 0;
    margin-bottom: 0;
    list-style: none;
    align-content: flex-end !important; /* چسباندن آیتم‌ها به انتهای محور متقاطع */
    align-items: stretch !important;    /* کشش آیتم‌ها در محور متقاطع */
}
</style>

<style>
/* نمایش صحیح ایموجی پرچم در سلکت کشور */
.country-flag-select {
    font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', 'Arial', sans-serif !important;
    font-size: 1rem;
}
.country-flag-select option {
    font-family: inherit;
    font-size: 1rem;
}
</style>

<!-- مستندات: برای نمایش صحیح پرچم کشورها در فیلتر، از پلاگین select2 با قالب سفارشی استفاده شده است تا پرچم و نام کشور به صورت واکنش‌گرا و زیبا نمایش داده شود. این راهکار در تمامی مرورگرها و سیستم‌عامل‌ها سازگاری کامل دارد. -->
<!-- Select2 CSS and JS are loaded in the main layout file -->
<script>
// راه‌اندازی select2 با قالب سفارشی برای نمایش پرچم و نام کشور بدون تکرار
function initializeSelect2() {
    // Check if jQuery and select2 are available
    if (typeof $ === 'undefined' || typeof $.fn.select2 === 'undefined') {
        console.log('jQuery or Select2 not available yet, retrying...');
        setTimeout(initializeSelect2, 500);
        return;
    }

    try {
        const countrySelect = $('#country-select');
        if (countrySelect.length && !countrySelect.hasClass('select2-hidden-accessible')) {
            countrySelect.select2({
                width: '100%',
                templateResult: function (state) {
                    if (!state.id) return state.text;
                    var flagUrl = $(state.element).data('flag-url');
                    var name = $(state.element).data('name');
                    var count = $(state.element).data('count');
                    return $('<span>' + (flagUrl ? '<img src="' + flagUrl + '" style="width:20px;vertical-align:middle;margin-left:6px;">' : '') + name + (count !== undefined ? ' <span style="color:#888;font-size:0.95em;">(' + count + ')</span>' : '') + '</span>');
                },
                templateSelection: function (state) {
                    if (!state.id) return state.text;
                    var flagUrl = $(state.element).data('flag-url');
                    var name = $(state.element).data('name');
                    var count = $(state.element).data('count');
                    return (flagUrl ? '<img src="' + flagUrl + '" style="width:20px;vertical-align:middle;margin-left:6px;">' : '') + name + (count !== undefined ? ' <span style="color:#888;font-size:0.95em;">(' + count + ')</span>' : '');
                },
                escapeMarkup: function (m) { return m; },
                dropdownParent: countrySelect.parent()
            });
            console.log('Select2 initialized successfully');
        }
    } catch (error) {
        console.error('Error initializing Select2:', error);
    }
}

// Initialize when scripts are loaded
if (typeof $ !== 'undefined') {
    $(document).ready(initializeSelect2);
} else {
    // Wait for scripts to load
    window.addEventListener('scriptsLoaded', initializeSelect2);
    // Fallback timeout
    setTimeout(initializeSelect2, 2000);
}
</script>

<style>
/* نمایش صحیح ایموجی پرچم در گزینه‌های select2 */
.select2-container--default .select2-results__option,
.select2-container--default .select2-selection--single .select2-selection__rendered {
    font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', 'Arial', sans-serif !important;
    font-size: 1rem;
    direction: rtl;
    text-align: right;
}
</style>

<script>
// مستندات: برای سازگاری کامل فیلتر مناطق با select2، رویدادهای change به صورت jQuery تعریف شده‌اند تا در همه حالت‌ها (select معمولی و select2) بدرستی کار کنند.
function initializeGeoEventHandlers() {
    // Check if jQuery is available
    if (typeof $ === 'undefined') {
        console.log('jQuery not available yet for geo handlers, retrying...');
        setTimeout(initializeGeoEventHandlers, 500);
        return;
    }

    try {
        // رویداد کشور
        $('#country-select').off('change.geo').on('change.geo', function() {
            const countryId = this.value;
            activeFilters.country = countryId;
            activeFilters.province = '';
            activeFilters.county = '';
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';
            activeFilters.zone = '';
            resetGeoContainers();
            if (countryId) {
                $('#province-container').show();
                $('#zone-container').show();
                fetchProvincesByCountry(countryId);
                fetchZonesByCountry(countryId);
                updateCategoriesByRegion();
            } else {
                resetGeoContainers();
                resetCategoryFilter();
            }
            loadLocations();
        });
        // رویداد استان
        $('#province-select').off('change.geo').on('change.geo', function() {
            const provinceId = this.value;
            activeFilters.province = provinceId;
            activeFilters.county = '';
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';
            $('#county-container').hide();
            $('#district-container').hide();
            $('#city-container').hide();
            $('#village-container').hide();
            resetSelect('county-select');
            resetSelect('district-select');
            resetSelect('city-select');
            resetSelect('village-select');
            if (provinceId) {
                $('#county-container').show();
                fetchCountiesByProvince(provinceId);
                updateCategoriesByRegion();
            }
            loadLocations();
        });

        // رویداد شهرستان
        $('#county-select').off('change.geo').on('change.geo', function() {
            const countyId = this.value;
            activeFilters.county = countyId;
            activeFilters.district = '';
            activeFilters.city = '';
            activeFilters.village = '';
            $('#district-container').hide();
            $('#city-container').hide();
            $('#village-container').hide();
            resetSelect('district-select');
            resetSelect('city-select');
            resetSelect('village-select');
            if (countyId) {
                $('#district-container').show();
                fetchDistrictsByCounty(countyId);
                updateCategoriesByRegion();
            }
            loadLocations();
        });

        // رویداد بخش
        $('#district-select').off('change.geo').on('change.geo', function() {
            const districtId = this.value;
            activeFilters.district = districtId;
            activeFilters.city = '';
            activeFilters.village = '';
            $('#city-container').hide();
            $('#village-container').hide();
            resetSelect('city-select');
            resetSelect('village-select');
            if (districtId) {
                $('#city-container').show();
                $('#village-container').show();
                fetchCitiesByDistrict(districtId);
                fetchVillagesByDistrict(districtId);
                updateCategoriesByRegion();
            }
            loadLocations();
        });

        // رویداد شهر
        $('#city-select').off('change.geo').on('change.geo', function() {
            activeFilters.city = this.value;
            updateCategoriesByRegion();
            loadLocations();
        });

        // رویداد روستا
        $('#village-select').off('change.geo').on('change.geo', function() {
            activeFilters.village = this.value;
            updateCategoriesByRegion();
            loadLocations();
        });

        // رویداد منطقه
        $('#zone-select').off('change.geo').on('change.geo', function() {
            activeFilters.zone = this.value;
            updateCategoriesByRegion();
            loadLocations();
        });

        console.log('Geo event handlers initialized successfully');
    } catch (error) {
        console.error('Error initializing geo event handlers:', error);
    }
}

// Initialize when scripts are loaded
if (typeof $ !== 'undefined') {
    $(document).ready(initializeGeoEventHandlers);
} else {
    // Wait for scripts to load
    window.addEventListener('scriptsLoaded', initializeGeoEventHandlers);
    // Fallback timeout
    setTimeout(initializeGeoEventHandlers, 2000);
}
</script>

<script>
// نمایش تعداد آیتم‌های هر منو در کنار عنوان و چندزبانه با استفاده از فایل زبان
function initializeSelectCounts() {
    // Check if jQuery is available
    if (typeof $ === 'undefined') {
        console.log('jQuery not available yet for select counts, retrying...');
        setTimeout(initializeSelectCounts, 500);
        return;
    }

    try {
        function updateSelectCounts() {
            const selects = [
                {id: '#country-select', label: '<?php echo e(__('messages.country')); ?>'},
                {id: '#province-select', label: '<?php echo e(__('messages.province')); ?>'},
                {id: '#county-select', label: '<?php echo e(__('messages.county')); ?>'},
                {id: '#district-select', label: '<?php echo e(__('messages.district')); ?>'},
                {id: '#city-select', label: '<?php echo e(__('messages.city')); ?>'},
                {id: '#village-select', label: '<?php echo e(__('messages.village')); ?>'},
                {id: '#zone-select', label: '<?php echo e(__('messages.zone')); ?>'}
            ];
            selects.forEach(function(sel) {
                const select = $(sel.id);
                const labelEl = select.closest('.mb-3').find('label.form-label');
                if (select.length && labelEl.length) {
                    const count = select.find('option').length - 1;
                    if (count >= 0) {
                        labelEl.html(sel.label + ' (' + count + ')');
                    }
                }
            });
        }

        updateSelectCounts();
        $(document).on('change', '.geo-select', updateSelectCounts);
        $(document).ajaxComplete(updateSelectCounts);
        setInterval(updateSelectCounts, 1000);

        console.log('Select counts initialized successfully');
    } catch (error) {
        console.error('Error initializing select counts:', error);
    }
}

// Initialize when scripts are loaded
if (typeof $ !== 'undefined') {
    $(document).ready(initializeSelectCounts);
} else {
    // Wait for scripts to load
    window.addEventListener('scriptsLoaded', initializeSelectCounts);
    // Fallback timeout
    setTimeout(initializeSelectCounts, 2000);
}
</script>

<style>
/* فونت مناسب برای منوهای کشویی فارسی/عربی و انگلیسی */
.geo-select, .country-flag-select, .select2-container--default .select2-selection--single, .select2-container--default .select2-results__option {
    font-family: 'IRANSans', 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', 'Arial', sans-serif !important;
    font-size: 1rem;
    direction: rtl;
    text-align: right;
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<!-- Map Controller Dependencies -->
<script src="<?php echo e(asset('js/map-api-adapter.js')); ?>" defer></script>
<script src="<?php echo e(asset('js/map-handler.js')); ?>" defer></script>
<script src="<?php echo e(asset('js/map-controller.js')); ?>" defer></script>
<script src="<?php echo e(asset('js/modern-category-filter.js')); ?>" defer></script>

<script>
// Ensure scripts are loaded in order and trigger initialization
document.addEventListener('DOMContentLoaded', function() {
    // Wait for all scripts to load
    let scriptsLoaded = 0;
    const totalScripts = 4; // map-api-adapter, map-handler, map-controller, modern-category-filter

    function checkScriptsLoaded() {
        scriptsLoaded++;
        console.log(`Script ${scriptsLoaded}/${totalScripts} loaded`);

        if (scriptsLoaded >= totalScripts) {
            console.log('All MapController scripts loaded, triggering initialization...');

            // Trigger custom event to signal scripts are loaded
            window.dispatchEvent(new CustomEvent('scriptsLoaded'));

            // Force initialization after a short delay
            setTimeout(() => {
                if (typeof MapController !== 'undefined' && typeof MapApiAdapter !== 'undefined' && typeof MapHandler !== 'undefined') {
                    console.log('All MapController dependencies available, initializing...');

                    if (!window.mapController) {
                        window.mapController = new MapController({
                            mapContainerId: 'map',
                            debug: true
                        });

                        window.mapController.init().then(() => {
                            console.log('MapController initialized successfully from scripts section');
                        }).catch(error => {
                            console.error('Error initializing MapController from scripts section:', error);
                        });
                    }
                } else {
                    console.error('MapController dependencies still not available:', {
                        MapController: typeof MapController !== 'undefined',
                        MapApiAdapter: typeof MapApiAdapter !== 'undefined',
                        MapHandler: typeof MapHandler !== 'undefined'
                    });
                }
            }, 500);
        }
    }

    // Monitor script loading
    const scripts = document.querySelectorAll('script[src*="map-"], script[src*="modern-category-filter"]');
    scripts.forEach(script => {
        script.addEventListener('load', checkScriptsLoaded);
        script.addEventListener('error', (e) => {
            console.error('Error loading script:', e.target.src);
            checkScriptsLoaded(); // Still count as "loaded" to prevent hanging
        });
    });

    // Fallback timeout
    setTimeout(() => {
        if (scriptsLoaded < totalScripts) {
            console.log('Timeout reached, forcing script initialization...');
            window.dispatchEvent(new CustomEvent('scriptsLoaded'));
        }
    }, 3000);
});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/aluirani/public_html/aludubai.ir/resources/views/welcome.blade.php ENDPATH**/ ?>