

<?php $__env->startSection('title', 'نقشه مکان‌ها'); ?>

<?php $__env->startPush('head'); ?>
<!-- Load critical scripts directly -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Modern Map CSS with Safari compatibility -->
<link rel="stylesheet" href="<?php echo e(asset('css/modern-map.css')); ?>">

<style>
    :root {
        --map-primary: #2563eb;
        --map-secondary: #64748b;
        --map-success: #059669;
        --map-warning: #d97706;
        --map-danger: #dc2626;
        --map-info: #0891b2;
        --map-light: #f8fafc;
        --map-dark: #1e293b;
        --map-border: #e2e8f0;
        --map-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        --map-shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        --map-radius: 0.75rem;
        --map-transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .modern-map-container {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        padding: 2rem 0;
    }

    .map-header {
        background: rgba(255, 255, 255, 0.95);
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        border-radius: var(--map-radius);
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: var(--map-shadow-lg);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .map-header h1 {
        font-size: 2rem;
        font-weight: 700;
        color: var(--map-dark);
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .map-header .header-icon {
        background: linear-gradient(135deg, var(--map-primary), var(--map-info));
        color: white;
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    .map-stats {
        display: flex;
        gap: 1rem;
        margin-top: 1rem;
    }

    .stat-item {
        background: rgba(255, 255, 255, 0.8);
        padding: 0.75rem 1rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-weight: 600;
        color: var(--map-dark);
        border: 1px solid rgba(255, 255, 255, 0.3);
    }

    .stat-item i {
        color: var(--map-primary);
    }

    .map-main-content {
        display: grid;
        grid-template-columns: 350px 1fr;
        gap: 2rem;
        height: calc(100vh - 200px);
    }

    .map-sidebar {
        background: rgba(255, 255, 255, 0.95);
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        border-radius: var(--map-radius);
        padding: 0;
        box-shadow: var(--map-shadow-lg);
        border: 1px solid rgba(255, 255, 255, 0.2);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .sidebar-header {
        background: linear-gradient(135deg, var(--map-primary), var(--map-info));
        color: white;
        padding: 1.5rem;
        font-weight: 600;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .sidebar-content {
        padding: 1.5rem;
        flex: 1;
        overflow-y: auto;
    }

    .map-container {
        background: rgba(255, 255, 255, 0.95);
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        border-radius: var(--map-radius);
        overflow: hidden;
        box-shadow: var(--map-shadow-lg);
        border: 1px solid rgba(255, 255, 255, 0.2);
        position: relative;
        height: 80vh;
        min-height: 600px;
    }

    #map {
        height: 100%;
        width: 100%;
        border-radius: var(--map-radius);
        font-family: 'IRANSans', sans-serif;
    }

    .map-controls {
        position: absolute;
        top: 1rem;
        right: 1rem;
        z-index: 1000;
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .map-control-btn {
        background: rgba(255, 255, 255, 0.95);
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        border: none;
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--map-dark);
        box-shadow: var(--map-shadow);
        transition: var(--map-transition);
        cursor: pointer;
    }

    .map-control-btn:hover {
        background: white;
        transform: translateY(-2px);
        box-shadow: var(--map-shadow-lg);
    }

    @media (max-width: 1024px) {
        .map-main-content {
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        .map-sidebar {
            order: 2;
            height: auto;
        }

        .map-container {
            order: 1;
            height: 60vh;
        }
    }

    @media (max-width: 768px) {
        .modern-map-container {
            padding: 1rem 0;
        }

        .map-header {
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .map-header h1 {
            font-size: 1.5rem;
        }

        .map-stats {
            flex-wrap: wrap;
        }

        .stat-item {
            flex: 1;
            min-width: calc(50% - 0.5rem);
        }
    }

    /* Filter Section Styles */
    .filter-section {
        border-bottom: 1px solid var(--map-border);
        padding-bottom: 1rem;
    }

    .filter-section:last-child {
        border-bottom: none;
        padding-bottom: 0;
    }

    .filter-title {
        font-weight: 600;
        color: var(--map-dark);
        margin-bottom: 0.75rem;
        font-size: 0.9rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .modern-btn {
        border-radius: 0.5rem;
        font-weight: 600;
        padding: 0.75rem 1rem;
        transition: var(--map-transition);
        border: none;
        position: relative;
        overflow: hidden;
    }

    .modern-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }

    .modern-btn:hover::before {
        left: 100%;
    }

    .modern-btn:hover {
        transform: translateY(-2px);
        box-shadow: var(--map-shadow-lg);
    }

    .modern-input, .modern-select {
        border: 2px solid var(--map-border);
        border-radius: 0.5rem;
        padding: 0.75rem;
        transition: var(--map-transition);
        background: white;
    }

    .modern-input:focus, .modern-select:focus {
        border-color: var(--map-primary);
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        outline: none;
    }

    .search-container {
        position: relative;
    }

    .search-icon {
        position: absolute;
        right: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--map-secondary);
        pointer-events: none;
    }

    .modern-range {
        margin: 0.5rem 0;
    }

    .range-labels {
        display: flex;
        justify-content: space-between;
        font-size: 0.8rem;
        color: var(--map-secondary);
        margin-top: 0.5rem;
    }

    .range-labels span:nth-child(2) {
        font-weight: 600;
        color: var(--map-primary);
    }

    .rating-filter {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .rating-option {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.5rem;
        border-radius: 0.5rem;
        cursor: pointer;
        transition: var(--map-transition);
        border: 2px solid transparent;
    }

    .rating-option:hover {
        background: var(--map-light);
        border-color: var(--map-border);
    }

    .rating-option.active {
        background: rgba(37, 99, 235, 0.1);
        border-color: var(--map-primary);
    }

    .rating-option .stars {
        display: flex;
        gap: 0.2rem;
    }

    .rating-option .stars i {
        color: #fbbf24;
        font-size: 0.9rem;
    }

    /* Package Filter Styles */
    .package-filter {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .package-option {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem;
        border: 2px solid var(--map-border);
        border-radius: 0.5rem;
        cursor: pointer;
        transition: var(--map-transition);
        background: white;
    }

    .package-option:hover {
        border-color: var(--map-primary);
        background: var(--map-light);
        transform: translateY(-1px);
    }

    .package-option.active {
        background: var(--map-primary);
        color: white;
        border-color: var(--map-primary);
    }

    .package-option .package-icon {
        font-size: 1.2rem;
        min-width: 1.5rem;
        text-align: center;
    }

    .package-option span:last-child {
        font-weight: 500;
        flex: 1;
    }

    .map-loading {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.9);
        -webkit-backdrop-filter: blur(5px);
        backdrop-filter: blur(5px);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2000;
    }

    .loading-spinner {
        text-align: center;
        color: var(--map-primary);
    }

    /* Custom Leaflet Styles */
    .leaflet-popup-content-wrapper {
        border-radius: 0.75rem;
        box-shadow: var(--map-shadow-lg);
        border: 1px solid var(--map-border);
        background: white;
    }

    .leaflet-popup-content {
        margin: 0;
        font-family: inherit;
        max-width: 320px;
    }

    .leaflet-popup-tip {
        background: white;
        border: 1px solid var(--map-border);
    }

    .custom-marker {
        background: var(--map-primary);
        border: 3px solid white;
        border-radius: 50%;
        box-shadow: var(--map-shadow);
        transition: var(--map-transition);
    }

    .custom-marker:hover {
        transform: scale(1.1);
        box-shadow: var(--map-shadow-lg);
    }

    /* Enhanced marker styles based on categories */
    .marker-restaurant { background: #ef4444; }
    .marker-hotel { background: #3b82f6; }
    .marker-attraction { background: #10b981; }
    .marker-shopping { background: #f59e0b; }
    .marker-medical { background: #dc2626; }
    .marker-education { background: #3498db; }
    .marker-transport { background: #f39c12; }
    .marker-sport { background: #2ecc71; }
    .marker-religious { background: #9b59b6; }
    .marker-fuel { background: #e67e22; }

    /* Loading overlay improvements */
    .map-loading {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.95);
        -webkit-backdrop-filter: blur(8px);
        backdrop-filter: blur(8px);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2000;
        transition: opacity 0.3s ease;
    }

    .loading-spinner {
        text-align: center;
        color: var(--map-primary);
    }

    .loading-spinner .spinner-border {
        width: 3rem;
        height: 3rem;
        border-width: 0.3em;
    }

    /* Enhanced accessibility */
    .map-control-btn:focus,
    .modern-btn:focus,
    .modern-input:focus,
    .modern-select:focus {
        outline: 2px solid var(--map-primary);
        outline-offset: 2px;
    }

    /* Improved mobile responsiveness */
    @media (max-width: 576px) {
        .map-header h1 {
            font-size: 1.25rem;
        }

        .map-stats {
            flex-direction: column;
            gap: 0.5rem;
        }

        .stat-item {
            justify-content: center;
            text-align: center;
        }

        .map-controls {
            top: 0.5rem;
            right: 0.5rem;
        }

        .map-control-btn {
            width: 2rem;
            height: 2rem;
            font-size: 0.8rem;
        }
    }

    /* Enhanced Location Card in Popup */
    .location-popup {
        min-width: 300px;
        max-width: 350px;
        padding: 1.25rem;
        background: white;
        border-radius: 0.75rem;
        box-shadow: var(--map-shadow-lg);
    }

    .location-popup .popup-header {
        display: flex;
        align-items: flex-start;
        gap: 1rem;
        margin-bottom: 1rem;
        padding-bottom: 0.75rem;
        border-bottom: 1px solid var(--map-border);
    }

    .location-popup .popup-icon {
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        background: var(--map-primary);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        flex-shrink: 0;
        box-shadow: var(--map-shadow);
    }

    .location-popup .popup-title {
        font-weight: 700;
        color: var(--map-dark);
        margin: 0 0 0.25rem 0;
        font-size: 1.2rem;
        line-height: 1.3;
    }

    .location-popup .popup-category {
        color: var(--map-secondary);
        font-size: 0.9rem;
        margin: 0;
        font-weight: 500;
    }

    .location-popup .popup-rating {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-top: 0.5rem;
    }

    .location-popup .popup-rating .stars {
        display: flex;
        gap: 0.1rem;
    }

    .location-popup .popup-rating .rating-text {
        font-size: 0.85rem;
        color: var(--map-secondary);
        font-weight: 500;
    }

    .location-popup .popup-details {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        margin: 1rem 0;
    }

    .location-popup .popup-detail {
        display: flex;
        align-items: flex-start;
        gap: 0.75rem;
        font-size: 0.9rem;
        color: var(--map-secondary);
        line-height: 1.4;
    }

    .location-popup .popup-detail i {
        color: var(--map-primary);
        width: 1.2rem;
        text-align: center;
        margin-top: 0.1rem;
        flex-shrink: 0;
    }

    .location-popup .popup-detail-text {
        flex: 1;
    }

    .location-popup .popup-actions {
        display: flex;
        gap: 0.75rem;
        margin-top: 1.25rem;
        padding-top: 1rem;
        border-top: 1px solid var(--map-border);
    }

    .popup-btn {
        flex: 1;
        padding: 0.75rem 1rem;
        border: none;
        border-radius: 0.5rem;
        font-weight: 600;
        font-size: 0.9rem;
        transition: var(--map-transition);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        text-decoration: none;
    }

    .popup-btn.primary {
        background: linear-gradient(135deg, var(--map-primary), var(--map-info));
        color: white;
        box-shadow: var(--map-shadow);
    }

    .popup-btn.secondary {
        background: var(--map-light);
        color: var(--map-dark);
        border: 2px solid var(--map-border);
    }

    .popup-btn:hover {
        transform: translateY(-2px);
        box-shadow: var(--map-shadow-lg);
    }

    .popup-btn.primary:hover {
        background: linear-gradient(135deg, #1d4ed8, #0284c7);
    }

    .popup-btn.secondary:hover {
        background: white;
        border-color: var(--map-primary);
        color: var(--map-primary);
    }

    /* Distance badge */
    .distance-badge {
        background: linear-gradient(135deg, var(--map-success), #16a34a);
        color: white;
        padding: 0.25rem 0.5rem;
        border-radius: 1rem;
        font-size: 0.75rem;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
    }

    /* Status indicators */
    .status-open {
        color: var(--map-success);
        font-weight: 600;
    }

    .status-closed {
        color: var(--map-danger);
        font-weight: 600;
    }

    /* Phone number styling */
    .phone-link {
        color: var(--map-primary);
        text-decoration: none;
        font-weight: 500;
    }

    .phone-link:hover {
        text-decoration: underline;
    }

    /* Notification System */
    .map-notification {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 10000;
        min-width: 300px;
        max-width: 400px;
        padding: 1rem 1.25rem;
        border-radius: 0.75rem;
        box-shadow: var(--map-shadow-lg);
        transform: translateX(100%);
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .map-notification.show {
        transform: translateX(0);
    }

    .map-notification-success {
        background: linear-gradient(135deg, rgba(16, 185, 129, 0.95), rgba(5, 150, 105, 0.95));
        color: white;
    }

    .map-notification-error {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.95), rgba(220, 38, 38, 0.95));
        color: white;
    }

    .map-notification-info {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.95), rgba(37, 99, 235, 0.95));
        color: white;
    }

    .notification-content {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-weight: 500;
    }

    .notification-content i {
        font-size: 1.25rem;
        flex-shrink: 0;
    }

    /* Enhanced map controls */
    .map-controls {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .map-control-btn {
        position: relative;
        overflow: hidden;
    }

    .map-control-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }

    .map-control-btn:hover::before {
        left: 100%;
    }

    /* Improved loading animation */
    @keyframes mapPulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }

    .map-loading .loading-spinner {
        animation: mapPulse 2s ease-in-out infinite;
    }

    /* Responsive improvements for notifications */
    @media (max-width: 576px) {
        .map-notification {
            right: 10px;
            left: 10px;
            min-width: auto;
            max-width: none;
            transform: translateY(-100%);
        }

        .map-notification.show {
            transform: translateY(0);
        }
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="modern-map-container">
    <div class="container-fluid px-4">
        <!-- Map Header -->
        <div class="map-header">
            <h1>
                <div class="header-icon">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                نقشه هوشمند مکان‌ها
            </h1>
            <div class="map-stats">
                <div class="stat-item">
                    <i class="fas fa-map-marker-alt"></i>
                    <span id="total-locations"><?php echo e($locations->count()); ?></span>
                    <span>مکان</span>
                </div>
                <div class="stat-item">
                    <i class="fas fa-eye"></i>
                    <span id="visible-locations">0</span>
                    <span>نمایش</span>
                </div>
                <div class="stat-item">
                    <i class="fas fa-filter"></i>
                    <span id="active-filters">0</span>
                    <span>فیلتر فعال</span>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="map-main-content">
            <!-- Sidebar -->
            <div class="map-sidebar">
                <div class="sidebar-header">
                    <i class="fas fa-sliders-h"></i>
                    فیلترهای پیشرفته
                </div>
                <div class="sidebar-content">
                    <!-- User Location Section -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">موقعیت شما</h6>
                        <button id="get-user-location" class="btn btn-primary w-100 modern-btn">
                            <i class="fas fa-location-arrow me-2"></i>
                            تشخیص موقعیت من
                        </button>
                        <div id="user-location-status" class="mt-2 d-none"></div>
                    </div>

                    <!-- Search Section -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">جستجو</h6>
                        <div class="search-container">
                            <input type="text" id="location-search" class="form-control modern-input"
                                   placeholder="نام مکان، شهر یا دسته‌بندی...">
                            <i class="fas fa-search search-icon"></i>
                        </div>
                    </div>

                    <!-- Category Filter -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">دسته‌بندی</h6>
                        <select id="category-filter" class="form-select modern-select">
                            <option value="">همه دسته‌بندی‌ها</option>
                        </select>
                    </div>

                    <!-- Enhanced Geographic Filter -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">منطقه جغرافیایی</h6>
                        <select id="province-filter" class="form-select modern-select mb-2">
                            <option value="">انتخاب استان</option>
                        </select>
                        <select id="county-filter" class="form-select modern-select mb-2">
                            <option value="">انتخاب شهرستان</option>
                        </select>
                        <select id="city-filter" class="form-select modern-select mb-2">
                            <option value="">انتخاب شهر</option>
                        </select>
                        <select id="district-filter" class="form-select modern-select mb-2">
                            <option value="">انتخاب بخش</option>
                        </select>
                        <select id="zone-filter" class="form-select modern-select">
                            <option value="">انتخاب منطقه</option>
                        </select>
                    </div>

                    <!-- Package Type Filter -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">نوع پکیج</h6>
                        <div class="package-filter">
                            <div class="package-option active" data-package="">
                                <span>همه پکیج‌ها</span>
                            </div>
                            <div class="package-option" data-package="diamond">
                                <span class="package-icon">💎</span>
                                <span>الماسی</span>
                            </div>
                            <div class="package-option" data-package="gold">
                                <span class="package-icon">🥇</span>
                                <span>طلایی</span>
                            </div>
                            <div class="package-option" data-package="silver">
                                <span class="package-icon">🥈</span>
                                <span>نقره‌ای</span>
                            </div>
                            <div class="package-option" data-package="bronze">
                                <span class="package-icon">🥉</span>
                                <span>برنزی</span>
                            </div>
                            <div class="package-option" data-package="regular">
                                <span class="package-icon">📍</span>
                                <span>عادی</span>
                            </div>
                        </div>
                    </div>

                    <!-- Distance Filter -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">شعاع جستجو</h6>
                        <div class="range-container">
                            <input type="range" id="distance-range" class="form-range modern-range"
                                   min="1" max="200" value="50">
                            <div class="range-labels">
                                <span>1 کیلومتر</span>
                                <span id="distance-value">50 کیلومتر</span>
                                <span>200 کیلومتر</span>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Rating Filter -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">امتیاز و نظرات</h6>
                        <div class="rating-filter">
                            <div class="rating-option active" data-rating="0">
                                <span>همه امتیازها</span>
                            </div>
                            <div class="rating-option" data-rating="4.5">
                                <div class="stars">
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star-half-alt"></i>
                                </div>
                                <span>4.5+ ستاره</span>
                            </div>
                            <div class="rating-option" data-rating="4">
                                <div class="stars">
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="far fa-star"></i>
                                </div>
                                <span>4+ ستاره</span>
                            </div>
                            <div class="rating-option" data-rating="3.5">
                                <div class="stars">
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star-half-alt"></i>
                                    <i class="far fa-star"></i>
                                </div>
                                <span>3.5+ ستاره</span>
                            </div>
                            <div class="rating-option" data-rating="3">
                                <div class="stars">
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="far fa-star"></i>
                                    <i class="far fa-star"></i>
                                </div>
                                <span>3+ ستاره</span>
                            </div>
                        </div>

                        <!-- Reviews Filter -->
                        <div class="mt-3">
                            <label class="form-label small">حداقل تعداد نظرات</label>
                            <select id="reviews-filter" class="form-select modern-select">
                                <option value="">همه</option>
                                <option value="50">50+ نظر</option>
                                <option value="20">20+ نظر</option>
                                <option value="10">10+ نظر</option>
                                <option value="5">5+ نظر</option>
                            </select>
                        </div>
                    </div>

                    <!-- Sort Options -->
                    <div class="filter-section mb-4">
                        <h6 class="filter-title">مرتب‌سازی</h6>
                        <select id="sort-filter" class="form-select modern-select">
                            <option value="created_at">جدیدترین</option>
                            <option value="rating">بالاترین امتیاز</option>
                            <option value="reviews">بیشترین نظر</option>
                            <option value="distance">نزدیک‌ترین</option>
                            <option value="package">نوع پکیج</option>
                        </select>
                    </div>

                    <!-- Filter Stats -->
                    <div class="filter-section mb-3">
                        <div class="filter-stats">
                            <div class="stat-item">
                                <span class="stat-label">نمایش داده شده:</span>
                                <span id="visible-locations" class="stat-value">۰</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">از مجموع:</span>
                                <span id="total-locations" class="stat-value">۰</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">فیلترهای فعال:</span>
                                <span id="active-filters" class="stat-value">۰</span>
                            </div>
                        </div>
                    </div>

                    <!-- Clear Filters -->
                    <div class="filter-section">
                        <button id="clear-filters" class="btn btn-outline-secondary w-100 modern-btn">
                            <i class="fas fa-times me-2"></i>
                            پاک کردن فیلترها
                        </button>
                    </div>
                </div>
            </div>

            <!-- Map Container -->
            <div class="map-container">
                <div id="map"></div>

                <!-- Inline script to ensure map loads -->
                <script>
                    // Immediate map creation
                    setTimeout(() => {
                        if (typeof L !== 'undefined' && !window.immediateMapCreated) {
                            console.log('Creating immediate inline map...');
                            try {
                                window.immediateMapCreated = true;
                                const map = L.map('map').setView([32.4279, 53.6880], 6);
                                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

                                // Test markers removed - only real locations from database will be shown

                                console.log('Immediate inline map created successfully');

                                // Now load real locations from database
                                loadRealLocations(map);
                            } catch (error) {
                                console.error('Immediate inline map failed:', error);
                            }
                        }
                    }, 100);

                    // Function to convert numbers to Persian/English based on site language
                    function convertNumbers(num) {
                        const currentLang = document.documentElement.lang || 'fa';
                        const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
                        const englishDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

                        if (currentLang === 'fa') {
                            return num.toString().replace(/[0-9]/g, function(w) {
                                return persianDigits[+w];
                            });
                        } else {
                            return num.toString().replace(/[۰-۹]/g, function(w) {
                                return englishDigits['۰۱۲۳۴۵۶۷۸۹'.indexOf(w)];
                            });
                        }
                    }

                    // Function to load real locations from database
                    async function loadRealLocations(map) {
                        try {
                            console.log('Loading real locations from database...');
                            const response = await fetch('/api/locations-simple');
                            const data = await response.json();

                            if (data.success && data.data.length > 0) {
                                console.log('Loaded', convertNumbers(data.data.length), 'real locations');

                                // Create marker cluster group for better organization
                                let markers;

                                // Wait a bit to ensure MarkerCluster is fully loaded
                                await new Promise(resolve => setTimeout(resolve, 100));

                                try {
                                    if (typeof L.markerClusterGroup === 'function') {
                                        markers = L.markerClusterGroup({
                                            chunkedLoading: true,
                                            chunkInterval: 200,
                                            chunkDelay: 50,
                                            maxClusterRadius: 80,
                                            spiderfyOnMaxZoom: true,
                                            showCoverageOnHover: false,
                                            zoomToBoundsOnClick: true,
                                            disableClusteringAtZoom: 15,
                                            removeOutsideVisibleBounds: true,
                                            animate: true,
                                            animateAddingMarkers: false,
                                            iconCreateFunction: function(cluster) {
                                                const count = cluster.getChildCount();
                                                let className = 'marker-cluster-small';
                                                if (count > 10) className = 'marker-cluster-medium';
                                                if (count > 100) className = 'marker-cluster-large';

                                                // Convert numbers based on site language
                                                const displayCount = convertNumbers(count);

                                                return L.divIcon({
                                                    html: '<div><span>' + displayCount + '</span></div>',
                                                    className: 'marker-cluster ' + className,
                                                    iconSize: L.point(40, 40)
                                                });
                                            }
                                        });

                                        // Add click event for clusters
                                        markers.on('clusterclick', function(event) {
                                            const cluster = event.layer;
                                            const childMarkers = cluster.getAllChildMarkers();

                                            console.log('Cluster clicked with', childMarkers.length, 'markers');

                                            // Get bounds of all markers in cluster
                                            const group = new L.featureGroup(childMarkers);
                                            const bounds = group.getBounds();

                                            // Zoom to cluster bounds with padding
                                            map.fitBounds(bounds, {
                                                padding: [20, 20],
                                                maxZoom: 16
                                            });
                                        });

                                        console.log('MarkerClusterGroup created successfully for all locations');
                                    } else {
                                        throw new Error('MarkerClusterGroup not available');
                                    }
                                } catch (error) {
                                    console.warn('MarkerCluster not available, using LayerGroup:', error);
                                    markers = L.layerGroup();
                                    console.log('Using LayerGroup fallback');
                                }

                                data.data.forEach(location => {
                                    if (location.lat && location.lng) {
                                        // Create custom icon with emoji from categories table
                                        const emoji = location.category_emoji || '📍';
                                        const color = location.category_color || '#2563eb';
                                        const packageType = location.package_type || 'regular';

                                        // Add package type class for special styling
                                        let packageClass = '';
                                        if (packageType !== 'regular') {
                                            packageClass = ` marker-${packageType}`;
                                        }

                                        const icon = L.divIcon({
                                            className: 'custom-marker',
                                            html: `<div class="marker-icon-style${packageClass}" style="background: ${color};">
                                                <span>${emoji}</span>
                                            </div>`,
                                            iconSize: [30, 30],
                                            iconAnchor: [15, 15]
                                        });

                                        const marker = L.marker([location.lat, location.lng], { icon });

                                        // Create popup content
                                        const popupContent = `
                                            <div class="location-popup">
                                                <h6 class="popup-title">
                                                    ${location.title}
                                                </h6>
                                                <p class="popup-subtitle">
                                                    <span style="font-size: 14px; margin-left: 5px;">${emoji}</span> ${location.category_fa || 'دسته‌بندی نامشخص'}
                                                </p>
                                                ${location.address ? `
                                                    <p class="popup-subtitle">
                                                        <i class="fas fa-map-marker-alt"></i> ${location.address}
                                                    </p>
                                                ` : ''}
                                                ${location.phone ? `
                                                    <p class="popup-subtitle">
                                                        <i class="fas fa-phone"></i> ${convertNumbers(location.phone)}
                                                    </p>
                                                ` : ''}
                                                ${location.average_rating > 0 ? `
                                                    <div class="rating">
                                                        <span class="star">★</span>
                                                        <span class="popup-subtitle">
                                                            ${convertNumbers(location.average_rating.toFixed(1))}
                                                            (${convertNumbers(location.total_ratings || 0)} نظر)
                                                        </span>
                                                    </div>
                                                ` : ''}
                                                ${location.package_type && location.package_type !== 'regular' ? `
                                                    <div>
                                                        <span class="package-badge">
                                                            ${location.package_type === 'diamond' ? '💎 الماسی' :
                                                              location.package_type === 'gold' ? '🥇 طلایی' :
                                                              location.package_type === 'silver' ? '🥈 نقره‌ای' :
                                                              location.package_type === 'bronze' ? '🥉 برنزی' : ''}
                                                        </span>
                                                    </div>
                                                ` : ''}
                                            </div>
                                        `;

                                        marker.bindPopup(popupContent);
                                        markers.addLayer(marker);
                                    }
                                });

                                // Add markers to map with error handling
                                try {
                                    map.addLayer(markers);
                                    console.log('Markers layer added to map successfully');

                                    // Fit map to show all markers
                                    if (markers.getLayers && markers.getLayers().length > 0) {
                                        try {
                                            map.fitBounds(markers.getBounds(), { padding: [20, 20] });
                                            console.log('Map bounds fitted to markers');
                                        } catch (boundsError) {
                                            console.log('Could not fit bounds, using default view');
                                            map.setView([32.4279, 53.6880], 6);
                                        }
                                    } else {
                                        console.log('No markers to fit bounds, using default view');
                                        map.setView([32.4279, 53.6880], 6);
                                    }
                                } catch (error) {
                                    console.error('Error adding markers to map:', error);
                                }

                                console.log('Real locations added to map successfully');

                                // Initialize map controls after map is ready
                                initializeMapControls(map);

                                // Initialize filters after map is ready
                                initializeFilters(map, markers, data.data);
                            } else {
                                console.log('No real locations found, keeping test markers');
                            }
                        } catch (error) {
                            console.error('Error loading real locations:', error);
                        }
                    }

                    // Function to initialize map controls
                    function initializeMapControls(map) {
                        console.log('Initializing map controls...');

                        // User location variables
                        let userMarker = null;
                        let currentTileLayer = 'osm';
                        let isFullscreen = false;

                        // Zoom to user location
                        document.getElementById('zoom-to-user').addEventListener('click', function() {
                            console.log('Zoom to user clicked');
                            if (navigator.geolocation) {
                                navigator.geolocation.getCurrentPosition(function(position) {
                                    const lat = position.coords.latitude;
                                    const lng = position.coords.longitude;

                                    // Remove existing user marker
                                    if (userMarker) {
                                        map.removeLayer(userMarker);
                                    }

                                    // Add user marker
                                    userMarker = L.marker([lat, lng], {
                                        icon: L.divIcon({
                                            className: 'user-location-marker',
                                            html: '<div style="background: #ef4444; border: 3px solid white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 4px rgba(0,0,0,0.3);"><i class="fas fa-user" style="color: white; font-size: 10px;"></i></div>',
                                            iconSize: [20, 20],
                                            iconAnchor: [10, 10]
                                        })
                                    }).addTo(map);

                                    userMarker.bindPopup('موقعیت شما');
                                    map.setView([lat, lng], 15);

                                    console.log('User location found:', lat, lng);
                                }, function(error) {
                                    console.error('Geolocation error:', error);
                                    alert('امکان دریافت موقعیت شما وجود ندارد');
                                });
                            } else {
                                alert('مرورگر شما از تشخیص موقعیت پشتیبانی نمی‌کند');
                            }
                        });

                        // Toggle satellite view
                        document.getElementById('toggle-satellite').addEventListener('click', function() {
                            console.log('Toggle satellite clicked');
                            const button = this;
                            const icon = button.querySelector('i');

                            if (currentTileLayer === 'osm') {
                                // Switch to satellite
                                map.eachLayer(function(layer) {
                                    if (layer instanceof L.TileLayer) {
                                        map.removeLayer(layer);
                                    }
                                });

                                L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                                    attribution: '&copy; <a href="https://www.esri.com/">Esri</a>',
                                    maxZoom: 19
                                }).addTo(map);

                                currentTileLayer = 'satellite';
                                icon.className = 'fas fa-map';
                                button.title = 'نمایش نقشه عادی';
                            } else {
                                // Switch to OSM
                                map.eachLayer(function(layer) {
                                    if (layer instanceof L.TileLayer) {
                                        map.removeLayer(layer);
                                    }
                                });

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

                                currentTileLayer = 'osm';
                                icon.className = 'fas fa-satellite';
                                button.title = 'نمایش تصاویر ماهواره‌ای';
                            }
                        });

                        // Fullscreen toggle
                        document.getElementById('fullscreen-map').addEventListener('click', function() {
                            console.log('Fullscreen clicked');
                            const mapContainer = document.querySelector('.map-container');
                            const button = this;
                            const icon = button.querySelector('i');

                            if (!isFullscreen) {
                                // Enter fullscreen
                                mapContainer.style.position = 'fixed';
                                mapContainer.style.top = '0';
                                mapContainer.style.left = '0';
                                mapContainer.style.width = '100vw';
                                mapContainer.style.height = '100vh';
                                mapContainer.style.zIndex = '9999';
                                mapContainer.style.borderRadius = '0';

                                icon.className = 'fas fa-compress';
                                button.title = 'خروج از تمام صفحه';
                                isFullscreen = true;
                            } else {
                                // Exit fullscreen
                                mapContainer.style.position = 'relative';
                                mapContainer.style.top = 'auto';
                                mapContainer.style.left = 'auto';
                                mapContainer.style.width = 'auto';
                                mapContainer.style.height = '80vh';
                                mapContainer.style.zIndex = 'auto';
                                mapContainer.style.borderRadius = 'var(--map-radius)';

                                icon.className = 'fas fa-expand';
                                button.title = 'تمام صفحه';
                                isFullscreen = false;
                            }

                            // Invalidate map size after fullscreen change
                            setTimeout(() => {
                                map.invalidateSize();
                            }, 100);
                        });

                        // Refresh map
                        document.getElementById('refresh-map').addEventListener('click', function() {
                            console.log('Refresh map clicked');
                            const button = this;
                            const icon = button.querySelector('i');

                            // Add spinning animation
                            icon.style.animation = 'spin 1s linear infinite';

                            // Reload locations
                            loadRealLocations(map).then(() => {
                                // Remove animation
                                icon.style.animation = '';
                                console.log('Map refreshed successfully');
                            }).catch(() => {
                                icon.style.animation = '';
                            });
                        });

                        // Center map to Iran
                        document.getElementById('center-map').addEventListener('click', function() {
                            console.log('Center map clicked');
                            map.setView([32.4279, 53.6880], 6);
                        });

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

                    // Function to initialize filters
                    function initializeFilters(map, markersLayer, allLocations) {
                        console.log('Initializing filters...');

                        // Store original data
                        window.allLocations = allLocations;
                        window.filteredLocations = [...allLocations];
                        window.markersLayer = markersLayer;
                        window.mapInstance = map;

                        // Current filter state
                        const filters = {
                            search: '',
                            category: '',
                            province: '',
                            county: '',
                            city: '',
                            district: '',
                            zone: '',
                            package: '',
                            rating: 0,
                            reviews: 0,
                            distance: 50,
                            userLocation: null,
                            sort: 'created_at'
                        };

                        // Load categories and provinces
                        loadFilterData();

                        // Initialize stats
                        updateFilterStats(allLocations.length);

                        // Search filter
                        document.getElementById('location-search').addEventListener('input', function() {
                            filters.search = this.value.trim();
                            applyFilters();
                        });

                        // Category filter
                        document.getElementById('category-filter').addEventListener('change', function() {
                            filters.category = this.value;
                            applyFilters();
                        });

                        // Geographic filters
                        document.getElementById('province-filter').addEventListener('change', function() {
                            filters.province = this.value;
                            filters.county = '';
                            filters.city = '';
                            filters.district = '';
                            filters.zone = '';

                            // Reset dependent dropdowns
                            document.getElementById('county-filter').innerHTML = '<option value="">انتخاب شهرستان</option>';
                            document.getElementById('city-filter').innerHTML = '<option value="">انتخاب شهر</option>';
                            document.getElementById('district-filter').innerHTML = '<option value="">انتخاب بخش</option>';
                            document.getElementById('zone-filter').innerHTML = '<option value="">انتخاب منطقه</option>';

                            if (this.value) {
                                loadCounties(this.value);
                            }
                            applyFilters();
                        });

                        document.getElementById('county-filter').addEventListener('change', function() {
                            filters.county = this.value;
                            filters.city = '';
                            filters.district = '';
                            filters.zone = '';

                            document.getElementById('city-filter').innerHTML = '<option value="">انتخاب شهر</option>';
                            document.getElementById('district-filter').innerHTML = '<option value="">انتخاب بخش</option>';
                            document.getElementById('zone-filter').innerHTML = '<option value="">انتخاب منطقه</option>';

                            if (this.value) {
                                loadCities(this.value);
                            }
                            applyFilters();
                        });

                        // Package filter
                        document.querySelectorAll('.package-option').forEach(option => {
                            option.addEventListener('click', function() {
                                // Remove active class from all options
                                document.querySelectorAll('.package-option').forEach(opt => opt.classList.remove('active'));

                                // Add active class to clicked option
                                this.classList.add('active');

                                filters.package = this.dataset.package;
                                applyFilters();
                            });
                        });

                        // Rating filter
                        document.querySelectorAll('.rating-option').forEach(option => {
                            option.addEventListener('click', function() {
                                // Remove active class from all options
                                document.querySelectorAll('.rating-option').forEach(opt => opt.classList.remove('active'));

                                // Add active class to clicked option
                                this.classList.add('active');

                                filters.rating = parseFloat(this.dataset.rating);
                                applyFilters();
                            });
                        });

                        // Reviews filter
                        document.getElementById('reviews-filter').addEventListener('change', function() {
                            filters.reviews = parseInt(this.value) || 0;
                            applyFilters();
                        });

                        // Distance filter
                        document.getElementById('distance-range').addEventListener('input', function() {
                            filters.distance = parseInt(this.value);
                            document.getElementById('distance-value').textContent = convertNumbers(this.value) + ' کیلومتر';
                            applyFilters();
                        });

                        // Sort filter
                        document.getElementById('sort-filter').addEventListener('change', function() {
                            filters.sort = this.value;
                            applyFilters();
                        });

                        // User location button
                        document.getElementById('get-user-location').addEventListener('click', function() {
                            const button = this;
                            const icon = button.querySelector('i');
                            const status = document.getElementById('user-location-status');

                            button.disabled = true;
                            icon.className = 'fas fa-spinner fa-spin me-2';
                            button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>در حال تشخیص...';

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

                                    button.disabled = false;
                                    button.innerHTML = '<i class="fas fa-check me-2"></i>موقعیت تشخیص داده شد';
                                    button.classList.remove('btn-primary');
                                    button.classList.add('btn-success');

                                    status.className = 'mt-2 text-success';
                                    status.textContent = 'موقعیت شما تشخیص داده شد';
                                    status.classList.remove('d-none');

                                    applyFilters();
                                }, function(error) {
                                    button.disabled = false;
                                    button.innerHTML = '<i class="fas fa-location-arrow me-2"></i>تشخیص موقعیت من';

                                    status.className = 'mt-2 text-danger';
                                    status.textContent = 'خطا در تشخیص موقعیت';
                                    status.classList.remove('d-none');
                                });
                            }
                        });

                        // Clear filters
                        document.getElementById('clear-filters').addEventListener('click', function() {
                            // Reset all filters
                            Object.keys(filters).forEach(key => {
                                if (key === 'distance') {
                                    filters[key] = 50;
                                } else if (key === 'sort') {
                                    filters[key] = 'created_at';
                                } else {
                                    filters[key] = key === 'rating' || key === 'reviews' ? 0 : '';
                                }
                            });

                            // Reset UI elements
                            document.getElementById('location-search').value = '';
                            document.getElementById('category-filter').value = '';
                            document.getElementById('province-filter').value = '';
                            document.getElementById('county-filter').innerHTML = '<option value="">انتخاب شهرستان</option>';
                            document.getElementById('city-filter').innerHTML = '<option value="">انتخاب شهر</option>';
                            document.getElementById('district-filter').innerHTML = '<option value="">انتخاب بخش</option>';
                            document.getElementById('zone-filter').innerHTML = '<option value="">انتخاب منطقه</option>';
                            document.getElementById('reviews-filter').value = '';
                            document.getElementById('distance-range').value = 50;
                            document.getElementById('distance-value').textContent = convertNumbers(50) + ' کیلومتر';
                            document.getElementById('sort-filter').value = 'created_at';

                            // Reset active classes
                            document.querySelectorAll('.package-option').forEach(opt => opt.classList.remove('active'));
                            document.querySelectorAll('.rating-option').forEach(opt => opt.classList.remove('active'));
                            document.querySelectorAll('.package-option[data-package=""]').forEach(opt => opt.classList.add('active'));
                            document.querySelectorAll('.rating-option[data-rating="0"]').forEach(opt => opt.classList.add('active'));

                            // Reset user location
                            const userLocationBtn = document.getElementById('get-user-location');
                            userLocationBtn.disabled = false;
                            userLocationBtn.innerHTML = '<i class="fas fa-location-arrow me-2"></i>تشخیص موقعیت من';
                            userLocationBtn.classList.remove('btn-success');
                            userLocationBtn.classList.add('btn-primary');
                            document.getElementById('user-location-status').classList.add('d-none');

                            applyFilters();
                        });

                        // Function to apply all filters
                        function applyFilters() {
                            console.log('Applying filters:', filters);

                            let filtered = [...allLocations];



                            // Search filter
                            if (filters.search) {
                                const searchTerm = filters.search.toLowerCase();
                                filtered = filtered.filter(location =>
                                    (location.title && location.title.toLowerCase().includes(searchTerm)) ||
                                    (location.address && location.address.toLowerCase().includes(searchTerm)) ||
                                    (location.category_fa && location.category_fa.toLowerCase().includes(searchTerm))
                                );
                            }

                            // Category filter
                            if (filters.category) {
                                filtered = filtered.filter(location => {
                                    // Convert both to string for comparison
                                    return String(location.category_id) === String(filters.category);
                                });
                            }

                            // Package filter
                            if (filters.package) {
                                filtered = filtered.filter(location =>
                                    (location.package_type || 'regular') === filters.package
                                );
                            }

                            // Rating filter
                            if (filters.rating > 0) {
                                filtered = filtered.filter(location =>
                                    (location.average_rating || 0) >= filters.rating
                                );
                            }

                            // Reviews filter
                            if (filters.reviews > 0) {
                                filtered = filtered.filter(location =>
                                    (location.total_ratings || 0) >= filters.reviews
                                );
                            }

                            // Distance filter (if user location is available)
                            if (filters.userLocation && filters.distance) {
                                filtered = filtered.filter(location => {
                                    const distance = calculateDistance(
                                        filters.userLocation.lat,
                                        filters.userLocation.lng,
                                        location.lat,
                                        location.lng
                                    );
                                    return distance <= filters.distance;
                                });
                            }

                            // Sort filtered results
                            filtered = sortLocations(filtered, filters.sort, filters.userLocation);

                            // Update map markers
                            updateMapMarkers(filtered);

                            // Update stats
                            updateFilterStats(filtered.length);

                            window.filteredLocations = filtered;
                        }

                        // Function to calculate distance between two points
                        function calculateDistance(lat1, lng1, lat2, lng2) {
                            const R = 6371; // Earth's radius in kilometers
                            const dLat = (lat2 - lat1) * Math.PI / 180;
                            const dLng = (lng2 - lng1) * Math.PI / 180;
                            const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                                    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                                    Math.sin(dLng/2) * Math.sin(dLng/2);
                            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                            return R * c;
                        }

                        // Function to sort locations
                        function sortLocations(locations, sortBy, userLocation) {
                            return locations.sort((a, b) => {
                                switch (sortBy) {
                                    case 'rating':
                                        return (b.average_rating || 0) - (a.average_rating || 0);
                                    case 'reviews':
                                        return (b.total_ratings || 0) - (a.total_ratings || 0);
                                    case 'distance':
                                        if (userLocation) {
                                            const distA = calculateDistance(userLocation.lat, userLocation.lng, a.lat, a.lng);
                                            const distB = calculateDistance(userLocation.lat, userLocation.lng, b.lat, b.lng);
                                            return distA - distB;
                                        }
                                        return 0;
                                    case 'package':
                                        const packageOrder = { diamond: 5, gold: 4, silver: 3, bronze: 2, regular: 1 };
                                        return (packageOrder[b.package_type] || 1) - (packageOrder[a.package_type] || 1);
                                    default: // created_at
                                        return new Date(b.created_at || 0) - new Date(a.created_at || 0);
                                }
                            });
                        }

                        // Function to load filter data (categories, provinces)
                        async function loadFilterData() {
                            try {
                                // Load categories
                                const categoriesResponse = await fetch('/api/categories');
                                if (categoriesResponse.ok) {
                                    const categoriesData = await categoriesResponse.json();
                                    if (categoriesData.success) {
                                        populateCategorySelect(categoriesData.data);
                                    }
                                }

                                // Load provinces
                                const provincesResponse = await fetch('/api/provinces');
                                if (provincesResponse.ok) {
                                    const provincesData = await provincesResponse.json();
                                    if (provincesData.success) {
                                        populateProvinceSelect(provincesData.data);
                                    }
                                }
                            } catch (error) {
                                console.error('Error loading filter data:', error);
                            }
                        }

                        // Function to populate category select
                        function populateCategorySelect(categories) {
                            const select = document.getElementById('category-filter');
                            select.innerHTML = '<option value="">همه دسته‌بندی‌ها</option>';



                            categories.forEach(category => {
                                const option = document.createElement('option');
                                option.value = category.id;
                                option.textContent = `${category.emoji || '📍'} ${category.category_fa} (${category.locations_count || 0})`;
                                select.appendChild(option);

                                // Add children if they exist
                                if (category.children && category.children.length > 0) {
                                    category.children.forEach(child => {
                                        const childOption = document.createElement('option');
                                        childOption.value = child.id;
                                        childOption.textContent = `  └─ ${child.emoji || '📍'} ${child.category_fa} (${child.locations_count || 0})`;
                                        select.appendChild(childOption);
                                    });
                                }
                            });
                        }

                        // Function to populate province select
                        function populateProvinceSelect(provinces) {
                            const select = document.getElementById('province-filter');
                            select.innerHTML = '<option value="">انتخاب استان</option>';

                            provinces.forEach(province => {
                                const option = document.createElement('option');
                                option.value = province.id;
                                option.textContent = province.name;
                                select.appendChild(option);
                            });
                        }

                        // Function to load counties
                        async function loadCounties(provinceId) {
                            try {
                                const response = await fetch(`/api/provinces/${provinceId}/counties`);
                                if (response.ok) {
                                    const data = await response.json();
                                    if (data.success) {
                                        populateCountySelect(data.data);
                                    }
                                } else {
                                    console.error('Failed to load counties:', response.status);
                                }
                            } catch (error) {
                                console.error('Error loading counties:', error);
                            }
                        }

                        // Function to populate county select
                        function populateCountySelect(counties) {
                            const select = document.getElementById('county-filter');
                            select.innerHTML = '<option value="">انتخاب شهرستان</option>';

                            counties.forEach(county => {
                                const option = document.createElement('option');
                                option.value = county.id;
                                option.textContent = county.name;
                                select.appendChild(option);
                            });
                        }

                        // Function to load cities
                        async function loadCities(countyId) {
                            try {
                                const response = await fetch(`/api/counties/${countyId}/cities`);
                                if (response.ok) {
                                    const data = await response.json();
                                    if (data.success) {
                                        populateCitySelect(data.data);
                                    }
                                }
                            } catch (error) {
                                console.error('Error loading cities:', error);
                            }
                        }

                        // Function to populate city select
                        function populateCitySelect(cities) {
                            const select = document.getElementById('city-filter');
                            select.innerHTML = '<option value="">انتخاب شهر</option>';

                            cities.forEach(city => {
                                const option = document.createElement('option');
                                option.value = city.id;
                                option.textContent = city.name;
                                select.appendChild(option);
                            });
                        }

                        // Function to update map markers
                        function updateMapMarkers(filteredLocations) {
                            // Check if markersLayer exists and is properly initialized
                            if (!markersLayer || !window.mapInstance) {
                                console.error('Map or markers layer not properly initialized');
                                return;
                            }

                            try {
                                // Clear existing markers safely
                                if (markersLayer.clearLayers) {
                                    markersLayer.clearLayers();
                                } else {
                                    // Fallback for LayerGroup
                                    markersLayer.eachLayer(function(layer) {
                                        markersLayer.removeLayer(layer);
                                    });
                                }

                                // Add filtered markers
                                filteredLocations.forEach(location => {
                                if (location.lat && location.lng) {
                                    // Create custom icon with emoji from categories table
                                    const emoji = location.category_emoji || '📍';
                                    const color = location.category_color || '#2563eb';
                                    const packageType = location.package_type || 'regular';

                                    // Add package type class for special styling
                                    let packageClass = '';
                                    if (packageType !== 'regular') {
                                        packageClass = ` marker-${packageType}`;
                                    }

                                    const icon = L.divIcon({
                                        className: 'custom-marker',
                                        html: `<div class="marker-icon-style${packageClass}" style="background: ${color};">
                                            <span>${emoji}</span>
                                        </div>`,
                                        iconSize: [30, 30],
                                        iconAnchor: [15, 15]
                                    });

                                    const marker = L.marker([location.lat, location.lng], { icon });

                                    // Create popup content
                                    const popupContent = `
                                        <div class="location-popup">
                                            <h6 class="popup-title">
                                                ${location.title}
                                            </h6>
                                            <p class="popup-subtitle">
                                                <span style="font-size: 14px; margin-left: 5px;">${emoji}</span> ${location.category_fa || 'دسته‌بندی نامشخص'}
                                            </p>
                                            ${location.address ? `
                                                <p class="popup-subtitle">
                                                    <i class="fas fa-map-marker-alt"></i> ${location.address}
                                                </p>
                                            ` : ''}
                                            ${location.phone ? `
                                                <p class="popup-subtitle">
                                                    <i class="fas fa-phone"></i> ${convertNumbers(location.phone)}
                                                </p>
                                            ` : ''}
                                            ${location.average_rating > 0 ? `
                                                <div class="rating">
                                                    <span class="star">★</span>
                                                    <span class="popup-subtitle">
                                                        ${convertNumbers(location.average_rating.toFixed(1))}
                                                        (${convertNumbers(location.total_ratings || 0)} نظر)
                                                    </span>
                                                </div>
                                            ` : ''}
                                            ${location.package_type && location.package_type !== 'regular' ? `
                                                <div>
                                                    <span class="package-badge">
                                                        ${location.package_type === 'diamond' ? '💎 الماسی' :
                                                          location.package_type === 'gold' ? '🥇 طلایی' :
                                                          location.package_type === 'silver' ? '🥈 نقره‌ای' :
                                                          location.package_type === 'bronze' ? '🥉 برنزی' : ''}
                                                    </span>
                                                </div>
                                            ` : ''}
                                        </div>
                                    `;

                                    marker.bindPopup(popupContent);

                                    // Add marker safely
                                    if (markersLayer.addLayer && typeof markersLayer.addLayer === 'function') {
                                        markersLayer.addLayer(marker);
                                    } else {
                                        console.warn('Cannot add marker to layer');
                                    }
                                }
                            });

                            console.log('Map updated with', filteredLocations.length, 'filtered locations');

                            } catch (error) {
                                console.error('Error updating map markers:', error);
                                // Fallback: try to recreate markers layer
                                try {
                                    window.mapInstance.removeLayer(markersLayer);
                                    markersLayer = L.markerClusterGroup({
                                        chunkedLoading: true,
                                        maxClusterRadius: 80,
                                        iconCreateFunction: function(cluster) {
                                            const count = cluster.getChildCount();
                                            let className = 'marker-cluster-small';
                                            if (count > 10) className = 'marker-cluster-medium';
                                            if (count > 100) className = 'marker-cluster-large';

                                            const displayCount = convertNumbers(count);

                                            return L.divIcon({
                                                html: '<div><span>' + displayCount + '</span></div>',
                                                className: 'marker-cluster ' + className,
                                                iconSize: L.point(40, 40)
                                            });
                                        }
                                    });
                                    window.mapInstance.addLayer(markersLayer);
                                    window.markersLayer = markersLayer;
                                    console.log('Markers layer recreated');
                                } catch (recreateError) {
                                    console.error('Failed to recreate markers layer:', recreateError);
                                }
                            }
                        }

                        // Function to update filter stats
                        function updateFilterStats(visibleCount) {
                            document.getElementById('visible-locations').textContent = convertNumbers(visibleCount);
                            document.getElementById('total-locations').textContent = convertNumbers(allLocations.length);

                            // Count active filters
                            let activeFilters = 0;
                            if (filters.search) activeFilters++;
                            if (filters.category) activeFilters++;
                            if (filters.province) activeFilters++;
                            if (filters.county) activeFilters++;
                            if (filters.city) activeFilters++;
                            if (filters.package) activeFilters++;
                            if (filters.rating > 0) activeFilters++;
                            if (filters.reviews > 0) activeFilters++;
                            if (filters.userLocation) activeFilters++;

                            document.getElementById('active-filters').textContent = convertNumbers(activeFilters);
                        }

                        console.log('Filters initialized successfully');
                    }
                </script>

                <!-- Map Controls -->
                <div class="map-controls">
                    <button class="map-control-btn" id="zoom-to-user" title="بازگشت به موقعیت من" aria-label="بازگشت به موقعیت من">
                        <i class="fas fa-crosshairs"></i>
                    </button>
                    <button class="map-control-btn" id="toggle-satellite" title="تغییر نوع نقشه" aria-label="تغییر نوع نقشه">
                        <i class="fas fa-satellite"></i>
                    </button>
                    <button class="map-control-btn" id="fullscreen-map" title="تمام صفحه" aria-label="تمام صفحه">
                        <i class="fas fa-expand"></i>
                    </button>
                    <button class="map-control-btn" id="refresh-map" title="بروزرسانی نقشه" aria-label="بروزرسانی نقشه">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="map-control-btn" id="center-map" title="مرکز نقشه" aria-label="مرکز نقشه">
                        <i class="fas fa-compress-arrows-alt"></i>
                    </button>
                </div>

                <!-- Loading Overlay -->
                <div id="map-loading" class="map-loading d-none">
                    <div class="loading-spinner">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">در حال بارگذاری...</span>
                        </div>
                        <p class="mt-2">در حال بارگذاری مکان‌ها...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?php $__env->startPush('scripts'); ?>
<script>
class ModernMapController {
    constructor() {
        this.map = null;
        this.markers = [];
        this.markerClusterGroup = null;
        this.userLocation = null;
        this.userMarker = null;
        this.currentTileLayer = null;
        this.isLoading = false;
        this.filters = {
            search: '',
            category: '',
            province: '',
            city: '',
            distance: 50,
            rating: 0,
            userLocation: null
        };
        this.locations = <?php echo json_encode($locations, 15, 512) ?>;
        this.filteredLocations = [...this.locations];
        this.categories = [];
        this.provinces = [];
        this.cities = [];

        this.init();
    }

    async init() {
        try {
            this.showLoading();

            // Initialize map first
            await this.initializeMap();

            // Load data in parallel for better performance
            const [locationsResult, categoriesResult, provincesResult] = await Promise.allSettled([
                this.loadLocations(),
                this.loadCategories(),
                this.loadProvinces()
            ]);

            // Check for any failures
            if (locationsResult.status === 'rejected') {
                console.warn('Failed to load locations:', locationsResult.reason);
                this.showNotification('خطا در بارگذاری مکان‌ها', 'error');
            }

            if (categoriesResult.status === 'rejected') {
                console.warn('Failed to load categories:', categoriesResult.reason);
            }

            if (provincesResult.status === 'rejected') {
                console.warn('Failed to load provinces:', provincesResult.reason);
            }

            this.setupEventListeners();

            // Only render markers if locations were loaded successfully
            if (locationsResult.status === 'fulfilled' && this.locations.length > 0) {
                console.log('Locations loaded successfully, rendering markers...'); // Debug log
                this.renderMarkers();
                this.updateStats();
                this.showNotification(`${this.locations.length} مکان بارگذاری شد`, 'success');
            } else {
                console.log('No locations loaded or loading failed'); // Debug log
                this.updateStats();

                // Add a test marker to verify map is working
                this.addTestMarker();
            }

            this.hideLoading();

        } catch (error) {
            console.error('Critical error initializing map:', error);
            this.handleError(error, 'initialization');
        }
    }

    async loadLocations() {
        try {
            console.log('Starting to load locations...'); // Debug log
            const response = await fetch('/api/locations');
            console.log('Response status:', response.status); // Debug log

            if (response.ok) {
                const result = await response.json();
                console.log('API Response:', result); // Debug log

                if (result.success) {
                    this.locations = result.data;
                    this.filteredLocations = [...this.locations];
                    console.log('Loaded locations:', this.locations.length); // Debug log
                    console.log('Sample location:', this.locations[0]); // Debug log
                    console.log('All locations:', this.locations); // Debug log
                    return Promise.resolve(); // Indicate success
                } else {
                    console.error('API returned error:', result.message);
                    return Promise.reject(new Error(result.message));
                }
            } else {
                console.error('Failed to load locations:', response.status);
                const errorText = await response.text();
                console.error('Error response:', errorText);
                return Promise.reject(new Error(`HTTP ${response.status}: ${errorText}`));
            }
        } catch (error) {
            console.error('Error loading locations:', error);
            return Promise.reject(error);
        }
    }

    async initializeMap() {
        // Initialize map with Iran center
        this.map = L.map('map', {
            center: [32.4279, 53.6880],
            zoom: 6,
            zoomControl: false,
            attributionControl: false
        });

        // Add custom zoom control
        L.control.zoom({
            position: 'bottomright'
        }).addTo(this.map);

        // Add attribution control
        L.control.attribution({
            position: 'bottomleft',
            prefix: false
        }).addTo(this.map);

        // Initialize tile layers
        this.initializeTileLayers();

        // Initialize marker cluster group
        this.markerClusterGroup = L.markerClusterGroup({
            chunkedLoading: true,
            maxClusterRadius: 50,
            iconCreateFunction: (cluster) => {
                const count = cluster.getChildCount();
                let className = 'marker-cluster-small';
                if (count > 10) className = 'marker-cluster-medium';
                if (count > 100) className = 'marker-cluster-large';

                return L.divIcon({
                    html: `<div><span>${count}</span></div>`,
                    className: `marker-cluster ${className}`,
                    iconSize: L.point(40, 40)
                });
            }
        });

        this.map.addLayer(this.markerClusterGroup);
        console.log('Marker cluster group added to map'); // Debug log

        // Test marker will be added after locations are loaded
    }

    initializeTileLayers() {
        // OpenStreetMap layer
        const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            maxZoom: 19
        });

        // Satellite layer
        const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: '&copy; <a href="https://www.esri.com/">Esri</a>',
            maxZoom: 19
        });

        // Set default layer
        this.currentTileLayer = osmLayer;
        this.currentTileLayer.addTo(this.map);

        // Store layers for switching
        this.tileLayers = {
            osm: osmLayer,
            satellite: satelliteLayer
        };
    }

    async loadCategories() {
        try {
            const response = await fetch('/api/categories');
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    this.categories = result.data;
                    this.populateCategorySelect();
                }
            }
        } catch (error) {
            console.error('Error loading categories:', error);
        }
    }

    async loadProvinces() {
        try {
            const response = await fetch('/api/provinces');
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    this.provinces = result.data;
                    this.populateProvinceSelect();
                }
            }
        } catch (error) {
            console.error('Error loading provinces:', error);
        }
    }

    populateCategorySelect() {
        const select = document.getElementById('category-filter');
        select.innerHTML = '<option value="">همه دسته‌بندی‌ها</option>';

        this.categories.forEach(category => {
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.category_fa;
            select.appendChild(option);

            // Add children if they exist
            if (category.children && category.children.length > 0) {
                category.children.forEach(child => {
                    const childOption = document.createElement('option');
                    childOption.value = child.id;
                    childOption.textContent = `-- ${child.category_fa}`;
                    select.appendChild(childOption);
                });
            }
        });
    }

    populateProvinceSelect() {
        const select = document.getElementById('province-filter');
        select.innerHTML = '<option value="">انتخاب استان</option>';

        this.provinces.forEach(province => {
            const option = document.createElement('option');
            option.value = province.id;
            option.textContent = province.name;
            select.appendChild(option);
        });
    }

    async loadCitiesByProvince(provinceId) {
        try {
            const response = await fetch(`/api/provinces/${provinceId}/cities`);
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    this.cities = result.data;
                    this.populateCitySelect();
                }
            }
        } catch (error) {
            console.error('Error loading cities:', error);
        }
    }

    populateCitySelect() {
        const select = document.getElementById('city-filter');
        select.innerHTML = '<option value="">انتخاب شهر</option>';

        this.cities.forEach(city => {
            const option = document.createElement('option');
            option.value = city.id;
            option.textContent = city.name;
            select.appendChild(option);
        });
    }

    setupEventListeners() {
        // Search input with improved debouncing
        const searchInput = document.getElementById('location-search');
        const debouncedSearch = this.debounce((value) => {
            this.filters.search = value;
            this.applyFilters();
        }, 500);

        searchInput.addEventListener('input', (e) => {
            debouncedSearch(e.target.value);
        });

        // Add keyboard navigation for search
        searchInput.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                searchInput.value = '';
                this.filters.search = '';
                this.applyFilters();
            }
        });

        // Category filter
        document.getElementById('category-filter').addEventListener('change', (e) => {
            this.filters.category = e.target.value;
            this.applyFilters();
        });

        // Province filter
        document.getElementById('province-filter').addEventListener('change', (e) => {
            this.filters.province = e.target.value;
            this.filters.city = ''; // Reset city filter
            document.getElementById('city-filter').value = '';

            if (e.target.value) {
                this.loadCitiesByProvince(e.target.value);
            } else {
                document.getElementById('city-filter').innerHTML = '<option value="">انتخاب شهر</option>';
            }

            this.applyFilters();
        });

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

        // Distance range
        const distanceRange = document.getElementById('distance-range');
        const distanceValue = document.getElementById('distance-value');
        distanceRange.addEventListener('input', (e) => {
            const value = e.target.value;
            distanceValue.textContent = `${value} کیلومتر`;
            this.filters.distance = parseInt(value);
            this.applyFilters();
        });

        // Rating filter
        document.querySelectorAll('.rating-option').forEach(option => {
            option.addEventListener('click', () => {
                document.querySelectorAll('.rating-option').forEach(opt => opt.classList.remove('active'));
                option.classList.add('active');
                this.filters.rating = parseInt(option.dataset.rating);
                this.applyFilters();
            });
        });

        // Clear filters
        document.getElementById('clear-filters').addEventListener('click', () => {
            this.clearFilters();
        });

        // User location
        document.getElementById('get-user-location').addEventListener('click', () => {
            this.getUserLocation();
        });

        // Map controls
        document.getElementById('zoom-to-user').addEventListener('click', () => {
            this.zoomToUserLocation();
        });

        document.getElementById('toggle-satellite').addEventListener('click', () => {
            this.toggleSatelliteView();
        });

        document.getElementById('fullscreen-map').addEventListener('click', () => {
            this.toggleFullscreen();
        });

        document.getElementById('refresh-map').addEventListener('click', () => {
            this.refreshMap();
        });

        document.getElementById('center-map').addEventListener('click', () => {
            this.centerMap();
        });
    }

    async applyFilters() {
        this.showLoading();

        try {
            // Build API parameters
            const params = new URLSearchParams();

            if (this.filters.search) {
                params.append('search', this.filters.search);
            }

            if (this.filters.category) {
                params.append('category_id', this.filters.category);
                params.append('include_children', 'true');
            }

            if (this.filters.province) {
                params.append('province_id', this.filters.province);
            }

            if (this.filters.city) {
                params.append('city_id', this.filters.city);
            }

            if (this.filters.rating > 0) {
                params.append('min_rating', this.filters.rating);
            }

            // Fetch filtered locations from API
            const response = await fetch(`/api/locations?${params.toString()}`);
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    let filtered = result.data;

                    // Apply distance filter on client side if user location is available
                    if (this.userLocation && this.filters.distance < 200) {
                        filtered = filtered.filter(location => {
                            if (!location.lat || !location.lng) return false;
                            const distance = this.calculateDistance(
                                this.userLocation.lat, this.userLocation.lng,
                                location.lat, location.lng
                            );
                            return distance <= this.filters.distance;
                        });
                    }

                    this.filteredLocations = filtered;
                    this.renderMarkers();
                    this.updateStats();
                }
            }
        } catch (error) {
            console.error('Error applying filters:', error);
            // Fallback to client-side filtering if API fails
            this.applyClientSideFilters();
        }

        this.hideLoading();
    }

    applyClientSideFilters() {
        let filtered = [...this.locations];

        // Search filter
        if (this.filters.search) {
            const searchTerm = this.filters.search.toLowerCase();
            filtered = filtered.filter(location =>
                location.title?.toLowerCase().includes(searchTerm) ||
                location.category_fa?.toLowerCase().includes(searchTerm) ||
                location.address?.toLowerCase().includes(searchTerm) ||
                (location.city_name && location.city_name.toLowerCase().includes(searchTerm)) ||
                (location.province_name && location.province_name.toLowerCase().includes(searchTerm))
            );
        }

        // Category filter
        if (this.filters.category) {
            filtered = filtered.filter(location => location.category_id == this.filters.category);
        }

        // Province filter
        if (this.filters.province) {
            filtered = filtered.filter(location => location.province_id == this.filters.province);
        }

        // City filter
        if (this.filters.city) {
            filtered = filtered.filter(location => location.city_id == this.filters.city);
        }

        // Rating filter
        if (this.filters.rating > 0) {
            filtered = filtered.filter(location => {
                const rating = location.star_rating || 0;
                return rating >= this.filters.rating;
            });
        }

        // Distance filter (if user location is available)
        if (this.userLocation && this.filters.distance < 200) {
            filtered = filtered.filter(location => {
                if (!location.lat || !location.lng) return false;
                const distance = this.calculateDistance(
                    this.userLocation.lat, this.userLocation.lng,
                    location.lat, location.lng
                );
                return distance <= this.filters.distance;
            });
        }

        this.filteredLocations = filtered;
        this.renderMarkers();
        this.updateStats();
    }

    renderMarkers() {
        console.log('renderMarkers called with', this.filteredLocations.length, 'locations'); // Debug log
        console.log('markerClusterGroup exists:', !!this.markerClusterGroup); // Debug log
        console.log('map exists:', !!this.map); // Debug log

        // Clear existing markers
        this.markerClusterGroup.clearLayers();
        this.markers = [];

        // Add markers for filtered locations
        this.filteredLocations.forEach((location, index) => {
            console.log(`Processing location ${index}:`, location.title, 'lat:', location.lat, 'lng:', location.lng, 'type:', typeof location.lat, typeof location.lng); // Debug log

            // Ensure coordinates are numbers
            const lat = parseFloat(location.lat);
            const lng = parseFloat(location.lng);

            console.log(`Parsed coordinates - lat: ${lat}, lng: ${lng}, valid: ${!isNaN(lat) && !isNaN(lng)}`); // Debug log

            if (!isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0) {
                // Update location object with parsed coordinates
                location.lat = lat;
                location.lng = lng;

                try {
                    const marker = this.createLocationMarker(location);
                    this.markers.push(marker);
                    this.markerClusterGroup.addLayer(marker);
                    console.log(`Added marker for: ${location.title} at [${lat}, ${lng}]`); // Debug log

                    // Add directly to map for testing (bypass cluster group)
                    marker.addTo(this.map);
                    console.log(`Marker added directly to map for: ${location.title}`); // Debug log

                } catch (error) {
                    console.error(`Error creating marker for ${location.title}:`, error); // Debug log
                }
            } else {
                console.log(`Skipped location ${location.title} - invalid coordinates: lat=${lat}, lng=${lng}`); // Debug log
            }
        });

        console.log('Total markers added:', this.markers.length); // Debug log
        console.log('Cluster group layer count:', this.markerClusterGroup.getLayers().length); // Debug log

        // Fit map to markers if there are any
        if (this.markers.length > 0) {
            try {
                const group = new L.featureGroup(this.markers);
                const bounds = group.getBounds();
                console.log('Fitting map to bounds:', bounds); // Debug log
                this.map.fitBounds(bounds, {
                    padding: [20, 20],
                    maxZoom: 15
                });
                console.log('Map bounds fitted to markers successfully'); // Debug log
            } catch (error) {
                console.error('Error fitting bounds:', error); // Debug log
                // Fallback: center on first marker
                if (this.markers[0]) {
                    const firstMarker = this.markers[0];
                    const latLng = firstMarker.getLatLng();
                    this.map.setView([latLng.lat, latLng.lng], 10);
                    console.log('Fallback: centered on first marker'); // Debug log
                }
            }
        } else {
            console.log('No markers to display - keeping default view'); // Debug log
        }
    }

    createLocationMarker(location) {
        console.log('Creating marker for location:', location.title, 'at coordinates:', location.lat, location.lng); // Debug log

        // Use category data from API
        const categoryIcon = location.category_icon || 'fas fa-map-marker-alt';
        const categoryColor = location.category_color || '#2563eb';
        const categoryKey = location.category_key || 'default';

        // Determine marker size based on rating or importance
        const rating = location.star_rating || 0;
        const markerSize = rating >= 4 ? 36 : rating >= 3 ? 32 : 28;
        const iconSize = rating >= 4 ? 16 : rating >= 3 ? 14 : 12;

        console.log('Marker details:', { categoryIcon, categoryColor, categoryKey, rating, markerSize }); // Debug log

        // Create custom icon with enhanced styling
        const icon = L.divIcon({
            className: `custom-marker marker-${categoryKey}`,
            html: `
                <div style="
                    background: ${categoryColor};
                    border: 3px solid white;
                    border-radius: 50%;
                    width: ${markerSize}px;
                    height: ${markerSize}px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: white;
                    font-size: ${iconSize}px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.25);
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    position: relative;
                    ${rating >= 4 ? 'border-color: #fbbf24; border-width: 4px;' : ''}
                ">
                    <i class="${categoryIcon}"></i>
                    ${rating >= 4 ? '<div style="position: absolute; top: -2px; right: -2px; background: #fbbf24; color: #1f2937; border-radius: 50%; width: 12px; height: 12px; display: flex; align-items: center; justify-content: center; font-size: 8px; font-weight: bold;">★</div>' : ''}
                </div>
            `,
            iconSize: [markerSize, markerSize],
            iconAnchor: [markerSize/2, markerSize/2],
            popupAnchor: [0, -markerSize/2 - 5]
        });

        // Create marker with enhanced options
        console.log('Creating L.marker with coordinates:', [location.lat, location.lng]); // Debug log
        const marker = L.marker([location.lat, location.lng], {
            icon,
            title: location.title,
            alt: `${location.title} - ${location.category_fa}`
        });

        console.log('Marker created successfully:', marker); // Debug log

        // Create popup content
        const popupContent = this.createPopupContent(location);
        marker.bindPopup(popupContent, {
            maxWidth: 380,
            minWidth: 300,
            className: 'custom-popup',
            closeButton: true,
            autoPan: true,
            keepInView: true,
            offset: [0, -10]
        });

        // Add hover effects
        marker.on('mouseover', function(e) {
            this.getElement().style.transform = 'scale(1.1)';
            this.getElement().style.zIndex = '1000';
        });

        marker.on('mouseout', function(e) {
            this.getElement().style.transform = 'scale(1)';
            this.getElement().style.zIndex = 'auto';
        });

        console.log('Returning marker for:', location.title); // Debug log
        return marker;
    }

    createPopupContent(location) {
        const rating = location.star_rating || 0;
        const ratingStars = this.generateStarRating(rating);
        const categoryIcon = location.category_icon || 'fas fa-map-marker-alt';
        const distance = this.userLocation ?
            this.calculateDistance(this.userLocation.lat, this.userLocation.lng, location.lat, location.lng) : null;

        // Determine if location is currently open
        const currentTime = new Date();
        const currentHour = currentTime.getHours();
        const isOpen = this.isLocationOpen(location, currentHour);

        return `
            <div class="location-popup">
                <div class="popup-header">
                    <div class="popup-icon" style="background: ${location.category_color || '#2563eb'}">
                        <i class="${categoryIcon}"></i>
                    </div>
                    <div style="flex: 1;">
                        <h5 class="popup-title">${location.title}</h5>
                        <p class="popup-category">${location.category_fa || 'دسته‌بندی نامشخص'}</p>
                        ${rating > 0 ? `
                            <div class="popup-rating">
                                <div class="stars">${ratingStars}</div>
                                <span class="rating-text">(${rating}/5)</span>
                            </div>
                        ` : ''}
                    </div>
                    ${distance ? `
                        <div class="distance-badge">
                            <i class="fas fa-route"></i>
                            ${distance.toFixed(1)} کم
                        </div>
                    ` : ''}
                </div>

                <div class="popup-details">
                    ${location.address ? `
                        <div class="popup-detail">
                            <i class="fas fa-map-marker-alt"></i>
                            <div class="popup-detail-text">${location.address}</div>
                        </div>
                    ` : ''}

                    ${location.province_name || location.city_name ? `
                        <div class="popup-detail">
                            <i class="fas fa-location-dot"></i>
                            <div class="popup-detail-text">${[location.city_name, location.province_name].filter(Boolean).join(', ')}</div>
                        </div>
                    ` : ''}

                    ${location.phone ? `
                        <div class="popup-detail">
                            <i class="fas fa-phone"></i>
                            <div class="popup-detail-text">
                                <a href="tel:${location.phone}" class="phone-link">${location.phone}</a>
                            </div>
                        </div>
                    ` : ''}

                    ${location.open_hours && location.closing_hours ? `
                        <div class="popup-detail">
                            <i class="fas fa-clock"></i>
                            <div class="popup-detail-text">
                                ${location.open_hours} - ${location.closing_hours}
                                <span class="${isOpen ? 'status-open' : 'status-closed'}">
                                    ${isOpen ? '• باز' : '• بسته'}
                                </span>
                            </div>
                        </div>
                    ` : ''}

                    ${location.description ? `
                        <div class="popup-detail">
                            <i class="fas fa-info-circle"></i>
                            <div class="popup-detail-text">${location.description.substring(0, 100)}${location.description.length > 100 ? '...' : ''}</div>
                        </div>
                    ` : ''}
                </div>

                <div class="popup-actions">
                    <a href="/location/${location.title_id}" target="_blank" class="popup-btn primary">
                        <i class="fas fa-eye"></i>
                        جزئیات
                    </a>
                    <a href="https://maps.google.com/maps?q=${location.lat},${location.lng}" target="_blank" class="popup-btn secondary">
                        <i class="fas fa-directions"></i>
                        مسیریابی
                    </a>
                </div>
            </div>
        `;
    }

    isLocationOpen(location, currentHour) {
        if (!location.open_hours || !location.closing_hours) return null;

        try {
            const openHour = parseInt(location.open_hours.split(':')[0]);
            const closeHour = parseInt(location.closing_hours.split(':')[0]);

            if (closeHour > openHour) {
                return currentHour >= openHour && currentHour < closeHour;
            } else {
                // Handle overnight hours (e.g., 22:00 - 06:00)
                return currentHour >= openHour || currentHour < closeHour;
            }
        } catch (e) {
            return null;
        }
    }

    getCategoryIcon(category) {
        const categoryMap = {
            'رستوران': 'fas fa-utensils',
            'هتل': 'fas fa-bed',
            'جاذبه گردشگری': 'fas fa-camera',
            'مرکز خرید': 'fas fa-shopping-bag',
            'بیمارستان': 'fas fa-hospital',
            'مسجد': 'fas fa-mosque',
            'پارک': 'fas fa-tree',
            'موزه': 'fas fa-university',
            'کافه': 'fas fa-coffee',
            'بانک': 'fas fa-university'
        };
        return categoryMap[category] || 'fas fa-map-marker-alt';
    }

    getCategoryColor(category) {
        const colorMap = {
            'رستوران': '#ef4444',
            'هتل': '#3b82f6',
            'جاذبه گردشگری': '#10b981',
            'مرکز خرید': '#f59e0b',
            'بیمارستان': '#dc2626',
            'مسجد': '#059669',
            'پارک': '#16a34a',
            'موزه': '#7c3aed',
            'کافه': '#92400e',
            'بانک': '#1e40af'
        };
        return colorMap[category] || '#2563eb';
    }

    generateStarRating(rating) {
        let stars = '';
        for (let i = 1; i <= 5; i++) {
            if (i <= rating) {
                stars += '<i class="fas fa-star" style="color: #fbbf24;"></i>';
            } else {
                stars += '<i class="far fa-star" style="color: #d1d5db;"></i>';
            }
        }
        return stars;
    }

    calculateDistance(lat1, lng1, lat2, lng2) {
        const R = 6371; // Earth's radius in kilometers
        const dLat = this.toRadians(lat2 - lat1);
        const dLng = this.toRadians(lng2 - lng1);
        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                  Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
                  Math.sin(dLng / 2) * Math.sin(dLng / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c;
    }

    toRadians(degrees) {
        return degrees * (Math.PI / 180);
    }

    getUserLocation() {
        const statusElement = document.getElementById('user-location-status');
        const button = document.getElementById('get-user-location');

        statusElement.classList.remove('d-none');
        statusElement.innerHTML = '<div class="text-info"><i class="fas fa-spinner fa-spin me-2"></i>در حال تشخیص موقعیت شما...</div>';
        button.disabled = true;

        if (!navigator.geolocation) {
            statusElement.innerHTML = '<div class="text-danger"><i class="fas fa-exclamation-triangle me-2"></i>مرورگر شما از تشخیص موقعیت پشتیبانی نمی‌کند.</div>';
            button.disabled = false;
            return;
        }

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

                // Remove existing user marker
                if (this.userMarker) {
                    this.map.removeLayer(this.userMarker);
                }

                // Add user marker
                this.userMarker = L.marker([this.userLocation.lat, this.userLocation.lng], {
                    icon: L.divIcon({
                        className: 'user-location-marker',
                        html: `
                            <div style="
                                background: #dc2626;
                                border: 4px solid white;
                                border-radius: 50%;
                                width: 20px;
                                height: 20px;
                                box-shadow: 0 2px 8px rgba(0,0,0,0.3);
                                animation: pulse 2s infinite;
                            "></div>
                        `,
                        iconSize: [20, 20],
                        iconAnchor: [10, 10]
                    })
                }).addTo(this.map);

                this.userMarker.bindPopup(`
                    <div class="text-center">
                        <i class="fas fa-user-circle fa-2x text-primary mb-2"></i>
                        <h6>موقعیت شما</h6>
                        <p class="small text-muted">دقت: ${position.coords.accuracy.toFixed(0)} متر</p>
                    </div>
                `);

                // Center map on user location
                this.map.setView([this.userLocation.lat, this.userLocation.lng], 12);

                statusElement.innerHTML = '<div class="text-success"><i class="fas fa-check-circle me-2"></i>موقعیت شما تشخیص داده شد!</div>';
                button.disabled = false;

                // Apply filters to show nearby locations
                this.applyFilters();

                // Hide status after 3 seconds
                setTimeout(() => {
                    statusElement.classList.add('d-none');
                }, 3000);
            },
            (error) => {
                let errorMessage = 'خطا در تشخیص موقعیت';
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = 'دسترسی به موقعیت مکانی رد شد';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = 'اطلاعات موقعیت در دسترس نیست';
                        break;
                    case error.TIMEOUT:
                        errorMessage = 'زمان تشخیص موقعیت به پایان رسید';
                        break;
                }
                statusElement.innerHTML = `<div class="text-danger"><i class="fas fa-exclamation-triangle me-2"></i>${errorMessage}</div>`;
                button.disabled = false;
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 300000
            }
        );
    }

    zoomToUserLocation() {
        if (this.userLocation) {
            this.map.setView([this.userLocation.lat, this.userLocation.lng], 15);
            if (this.userMarker) {
                this.userMarker.openPopup();
            }
        } else {
            this.getUserLocation();
        }
    }

    toggleSatelliteView() {
        const button = document.getElementById('toggle-satellite');
        const icon = button.querySelector('i');

        if (this.currentTileLayer === this.tileLayers.osm) {
            // Switch to satellite
            this.map.removeLayer(this.tileLayers.osm);
            this.map.addLayer(this.tileLayers.satellite);
            this.currentTileLayer = this.tileLayers.satellite;
            icon.className = 'fas fa-map';
            button.title = 'نمایش نقشه معمولی';
        } else {
            // Switch to normal map
            this.map.removeLayer(this.tileLayers.satellite);
            this.map.addLayer(this.tileLayers.osm);
            this.currentTileLayer = this.tileLayers.osm;
            icon.className = 'fas fa-satellite';
            button.title = 'نمایش تصاویر ماهواره‌ای';
        }
    }

    toggleFullscreen() {
        const mapContainer = document.querySelector('.map-container');
        const button = document.getElementById('fullscreen-map');
        const icon = button.querySelector('i');

        if (!document.fullscreenElement) {
            mapContainer.requestFullscreen().then(() => {
                icon.className = 'fas fa-compress';
                button.title = 'خروج از تمام صفحه';
                // Invalidate map size after fullscreen
                setTimeout(() => this.map.invalidateSize(), 100);
            });
        } else {
            document.exitFullscreen().then(() => {
                icon.className = 'fas fa-expand';
                button.title = 'تمام صفحه';
                // Invalidate map size after exit fullscreen
                setTimeout(() => this.map.invalidateSize(), 100);
            });
        }
    }

    clearFilters() {
        // Reset all filters
        this.filters = {
            search: '',
            category: '',
            province: '',
            city: '',
            distance: 50,
            rating: 0,
            userLocation: this.userLocation
        };

        // Reset UI elements
        document.getElementById('location-search').value = '';
        document.getElementById('category-filter').value = '';
        document.getElementById('province-filter').value = '';
        document.getElementById('city-filter').innerHTML = '<option value="">انتخاب شهر</option>';
        document.getElementById('distance-range').value = 50;
        document.getElementById('distance-value').textContent = '50 کیلومتر';
        document.querySelectorAll('.rating-option').forEach(opt => opt.classList.remove('active'));
        document.querySelector('.rating-option[data-rating="0"]').classList.add('active');

        // Apply filters
        this.applyFilters();
    }

    updateStats() {
        document.getElementById('visible-locations').textContent = this.filteredLocations.length;

        // Count active filters
        let activeFilters = 0;
        if (this.filters.search) activeFilters++;
        if (this.filters.category) activeFilters++;
        if (this.filters.province) activeFilters++;
        if (this.filters.city) activeFilters++;
        if (this.filters.rating > 0) activeFilters++;
        if (this.userLocation && this.filters.distance < 200) activeFilters++;

        document.getElementById('active-filters').textContent = activeFilters;
    }

    showLoading() {
        document.getElementById('map-loading').classList.remove('d-none');
        this.isLoading = true;
    }

    hideLoading() {
        document.getElementById('map-loading').classList.add('d-none');
        this.isLoading = false;
    }

    refreshMap() {
        if (this.isLoading) return;

        this.showLoading();

        // Refresh data from API
        this.loadLocations().then(() => {
            this.applyFilters();
            this.hideLoading();

            // Show success message
            this.showNotification('نقشه با موفقیت بروزرسانی شد', 'success');
        }).catch(error => {
            console.error('Error refreshing map:', error);
            this.hideLoading();
            this.showNotification('خطا در بروزرسانی نقشه', 'error');
        });
    }

    centerMap() {
        if (this.markers.length > 0) {
            const group = new L.featureGroup(this.markers);
            this.map.fitBounds(group.getBounds(), {
                padding: [20, 20],
                maxZoom: 15
            });
        } else {
            // Center on Iran
            this.map.setView([32.4279, 53.6880], 6);
        }
    }

    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `map-notification map-notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            </div>
        `;

        // Add to page
        document.body.appendChild(notification);

        // Show with animation
        setTimeout(() => notification.classList.add('show'), 100);

        // Remove after 3 seconds
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => document.body.removeChild(notification), 300);
        }, 3000);
    }

    // Enhanced error handling
    handleError(error, context = '') {
        console.error(`Map Error ${context}:`, error);

        let message = 'خطای غیرمنتظره‌ای رخ داد';

        if (error.message) {
            if (error.message.includes('network') || error.message.includes('fetch')) {
                message = 'خطا در اتصال به شبکه';
            } else if (error.message.includes('location') || error.message.includes('geolocation')) {
                message = 'خطا در تشخیص موقعیت';
            }
        }

        this.showNotification(message, 'error');
        this.hideLoading();
    }

    // Performance optimization: debounce function
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Add test marker to verify map functionality
    addTestMarker() {
        console.log('Adding test marker to verify map functionality'); // Debug log
        try {
            // Simple marker first
            const simpleMarker = L.marker([32.4279, 53.6880]).addTo(this.map);
            simpleMarker.bindPopup('Simple Test Marker - Iran Center');
            console.log('Simple test marker added successfully'); // Debug log

            // Custom icon marker
            const testMarker = L.marker([32.5, 54], {
                icon: L.divIcon({
                    className: 'test-marker',
                    html: '<div style="background: red; border: 2px solid white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: bold;">T</div>',
                    iconSize: [20, 20],
                    iconAnchor: [10, 10]
                })
            }).addTo(this.map);

            testMarker.bindPopup('<div style="text-align: center;"><strong>Test Marker</strong><br>Custom Icon<br>Map is working!</div>');
            console.log('Custom test marker added successfully'); // Debug log

            // Force map to show markers
            this.map.setView([32.4279, 53.6880], 6);

        } catch (error) {
            console.error('Error adding test marker:', error); // Debug log
        }
    }
}

// Initialize the map when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded - Starting map initialization'); // Debug log

    // Add CSS for animations
    const style = document.createElement('style');
    style.textContent = `
        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }

        .marker-cluster-small {
            background-color: rgba(37, 99, 235, 0.6);
        }
        .marker-cluster-small div {
            background-color: rgba(37, 99, 235, 0.8);
        }

        .marker-cluster-medium {
            background-color: rgba(245, 158, 11, 0.6);
        }
        .marker-cluster-medium div {
            background-color: rgba(245, 158, 11, 0.8);
        }

        .marker-cluster-large {
            background-color: rgba(239, 68, 68, 0.6);
        }
        .marker-cluster-large div {
            background-color: rgba(239, 68, 68, 0.8);
        }

        .marker-cluster {
            border-radius: 50%;
        }
        .marker-cluster div {
            width: 30px;
            height: 30px;
            margin-left: 5px;
            margin-top: 5px;
            text-align: center;
            border-radius: 50%;
            font: 12px "Helvetica Neue", Arial, Helvetica, sans-serif;
            color: white;
            font-weight: bold;
            line-height: 30px;
        }
    `;
    document.head.appendChild(style);

    // Scripts are loaded in head, initialize directly
    console.log('Scripts loaded in head, checking availability...');
    console.log('Dependencies check:', {
        jQuery: typeof $ !== 'undefined',
        Leaflet: typeof L !== 'undefined',
        MarkerCluster: typeof L !== 'undefined' && typeof L.markerClusterGroup !== 'undefined',
        MapManager: typeof MapManager !== 'undefined'
    });

    function initializeMapWhenReady() {
        if (typeof L !== 'undefined' && typeof L.markerClusterGroup !== 'undefined') {
            console.log('All dependencies ready, initializing MapManager...');
            try {
                window.mapController = new MapManager();
                console.log('MapManager initialized successfully');
            } catch (error) {
                console.error('Error initializing MapManager:', error);
                console.error('Error stack:', error.stack);

                // Fallback: Create simple map without test markers
                console.log('Creating fallback map...');
                try {
                    const map = L.map('map').setView([32.4279, 53.6880], 6);
                    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
                    console.log('Fallback map created successfully - waiting for real data');
                } catch (fallbackError) {
                    console.error('Fallback map creation failed:', fallbackError);
                }
            }
        } else {
            console.log('Dependencies not ready, retrying...');
            setTimeout(initializeMapWhenReady, 200);
        }
    }

    // Start initialization immediately
    initializeMapWhenReady();

    // Also try emergency fallback immediately to ensure map shows
    setTimeout(() => {
        console.log('Immediate fallback: Creating simple map...');
        try {
            if (!window.fallbackMapCreated) {
                window.fallbackMapCreated = true;
                const map = L.map('map').setView([32.4279, 53.6880], 6);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors'
                }).addTo(map);

                // No test markers - waiting for real data from database
                console.log('Emergency fallback map created - waiting for real data');
            }
        } catch (error) {
            console.error('Immediate fallback failed:', error);
        }
    }, 1000);
});


</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/templates/map.blade.php ENDPATH**/ ?>