@php
    $layout = auth()->user()->role === 'super_admin' ? 'layouts.admin' : 'layouts.app';
@endphp

@extends($layout)

@section('title', ' Community Empowerment Support to Women and Girls :: Component 1')

@push('styles')
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        /* Professional DHIS2/PowerBI Palette */
        :root {
            --dhis2-blue: #2c6693;
            --dhis2-teal: #00796b;
            --dhis2-grey: #f8fafc;
            --border-color: #e2e8f0;
        }

        body {
            background-color: #f1f5f9;
            color: #334155;
        }

        /* Fix for White Space: Remove all negative margins and use standard padding */
        .dashboard-wrapper {
            padding: 1.5rem;
        }

        .card {
            border: 1px solid var(--border-color);
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            margin-bottom: 1.5rem;
            /* Consistent spacing between cards */
        }

        .card-header {
            background-color: #fff;
            border-bottom: 1px solid var(--border-color);
            padding: 1rem;
        }

        .card-title {
            color: var(--dhis2-blue);
            font-weight: 700;
            text-transform: uppercase;
            font-size: 0.85rem;
            margin: 0;
        }

        /* KPI Cards */
        .stat-card {
            padding: 1.25rem;
            border-left: 4px solid var(--dhis2-blue);
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: 400;
            display: block;
        }

        .stat-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }

        /* Table Styling */
        .table thead th {
            background-color: var(--dhis2-grey);
            text-transform: uppercase;
            font-size: 0.7rem;
            letter-spacing: 0.025em;
        }

        /* Map and Chart Sizing - Logic to prevent "White Space" */
        .chart-body {
            position: relative;
            width: 100%;
            height: 280px;
        }

        /* Modern map card & tabs */
        .map-card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06), 0 1px 3px rgba(0, 0, 0, 0.04);
            overflow: hidden;
        }

        .map-card .card-header {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
            border-bottom: 1px solid var(--border-color);
            padding: 0;
        }

        .map-card .nav-tabs-modern {
            display: flex;
            gap: 0;
            padding: 0.5rem 0.5rem 0;
            border: none;
        }

        .map-card .nav-tabs-modern .nav-link {
            flex: 1;
            text-align: center;
            padding: 0.65rem 0.75rem;
            font-size: 0.8rem;
            font-weight: 600;
            color: #64748b;
            border: none;
            border-radius: 8px 8px 0 0;
            background: transparent;
            transition: color 0.2s, background 0.2s;
        }

        .map-card .nav-tabs-modern .nav-link:hover {
            color: var(--dhis2-blue);
            background: rgba(44, 102, 147, 0.06);
        }

        .map-card .nav-tabs-modern .nav-link.active {
            color: #fff;
            background: linear-gradient(135deg, var(--dhis2-blue) 0%, #00796b 100%);
            box-shadow: 0 2px 8px rgba(44, 102, 147, 0.35);
        }

        .map-card .tab-content {
            padding: 0;
        }

        .map-card .tab-pane {
            padding: 0;
        }

        .map-wrapper {
            position: relative;
            width: 100%;
            height: 360px;
            border-radius: 0 0 12px 12px;
            overflow: hidden;
            background: #e2e8f0;
        }

        #groupMap,
        #memberMap {
            width: 100%;
            height: 100%;
            min-height: 360px;
        }

        .map-card .map-hint {
            position: absolute;
            bottom: 12px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 0.7rem;
            color: #64748b;
            background: rgba(255, 255, 255, 0.9);
            padding: 4px 10px;
            border-radius: 20px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
            z-index: 1000;
            pointer-events: none;
        }

        .nav-pills .nav-link.active {
            background-color: var(--dhis2-blue);
        }
    </style>
@endpush

@section('content')
    <div class="dashboard-wrapper">
        <!-- Dashboard Header -->
        <div class="dashboard-header">
            <div class="container-fluid">
                <div class="row align-items-center dashboard-header-content">
                    <div class="col-lg-2">
                        {{-- <h1 class="dashboard-title">
                        <i class="fas fa-tachometer-alt" style="color: var(--dhis2-blue-primary);"></i>
                        Community Empowerment Support to Women and Girls
                    </h1> --}}
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="javascript:history.back()">Back</a></li>
                                <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                                <li class="breadcrumb-item active">Component 1</li>
                            </ol>
                        </nav>
                    </div>
                    <div class="col-lg-10">
                        <div class="d-flex justify-content-lg-end gap-2 dashboard-actions">
                            <a href="{{ route('component1.groups.index') }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-users me-1"></i> Manage Groups
                            </a>
                            <a href="{{ route('component1.members.index') }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-user-friends me-1"></i> Members
                            </a>
                            <a href="{{ route('component1.vsla.report') }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-file-excel"></i> VSLA Monthly Report
                            </a>
                            <a href="{{ route('grievances.index', ['component' => 1]) }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-briefcase me-1"></i> GRM
                            </a>
                            <a href="{{ route('grievances.create', ['component' => 1]) }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-file-alt me-1"></i> Register New Grievance
                            </a>
                            <a href="{{ route('ess.index') }}" class="btn btn-dhis2-secondary">
                                <i class="fas fa-shield-alt"></i> ESS Tracker
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {{-- Quick Stats --}}
        <div class="row g-3 mb-4">
            <div class="col-md-3">
                <div class="card stat-card" style="border-left-color: var(--official-sswseep-green);">
                    <span class="stat-label">VSLA <br />Groups Supported</span>
                    <hr style="margin: 0.5rem 0; width:50%;">
                    <span class="stat-value green-stat-value stat-count" data-target="{{ $stats['total_groups'] ?? 0 }}"
                        data-format="number">0</span>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card" style="border-left-color: var(--official-sswseep-green);">
                    <span class="stat-label">VSLA <br />Members Supported</span>
                    <hr style="margin: 0.5rem 0; width:50%;">
                    <span class="stat-value green-stat-value stat-count" data-target="{{ $stats['total_members'] ?? 0 }}"
                        data-format="number">0</span>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card" style="border-left-color: var(--official-sswseep-green);">
                    <span class="stat-label">Groups Who <br />Received Productive Assets</span>
                    <hr style="margin: 0.5rem 0; width:50%;">
                    <span class="stat-value green-stat-value stat-count" data-target="{{ $kpiStats['supports'] ?? 0 }}"
                        data-format="number">0</span>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card" style="border-left-color: var(--official-sswseep-green);">
                    <span class="stat-label">Groups <br />Receiving Capacity Building</span>
                    <hr style="margin: 0.5rem 0; width:50%;">
                    <span class="stat-value green-stat-value stat-count"
                        data-target="{{ $groupsReceivingCapacityBuilding['matured']['total'] ?? 0 }}"
                        data-format="number">0</span>
                </div>
            </div>
        </div>

        {{-- PROFESSIONAL FILTER BAR --}}
        <div class="row mb-4">
            <div class="col-12">
                <form method="GET" class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h6 class="card-title mb-0">Filter Dashboard Data</h6>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label small fw-bold">State</label>
                                <select name="state" class="form-select">
                                    <option value="">All States</option>
                                    <option value="WBGS"
                                        {{ request('state') === 'WBGS' ? 'selected' : '' }}>WBGS –
                                        Western Bahr el Ghazal</option>
                                    <option value="EES"
                                        {{ request('state') === 'EES' ? 'selected' : '' }}>EES – Eastern
                                        Equatoria</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small fw-bold">County</label>
                                <input type="text" name="county" class="form-control" value="{{ request('county') }}"
                                    placeholder="e.g. Wau">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small fw-bold">Payam</label>
                                <input type="text" name="payam" class="form-control" value="{{ request('payam') }}"
                                    placeholder="e.g. Payam name">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small fw-bold">Period (Month Range)</label>
                                <div class="input-group">
                                    <input type="month" name="from_month" class="form-control"
                                        value="{{ request('from_month') }}">
                                    <span class="input-group-text">to</span>
                                    <input type="month" name="to_month" class="form-control"
                                        value="{{ request('to_month') }}">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer d-flex justify-content-between bg-white">
                        <button type="submit" class="btn btn-dhis2-primary">
                            <i class="fas fa-filter me-1"></i> Apply Filter
                        </button>

                        @if (request()->hasAny(['state', 'county', 'payam', 'from_month', 'to_month']))
                            <div>
                                <a href="{{ route('component1.dashboard') }}"
                                    class="btn btn-outline-secondary me-2">Clear All Filters</a>
                                <button type="button" onclick="downloadFilteredReport()" class="btn btn-success">
                                    <i class="fas fa-file-excel me-1"></i> Download Filtered Report
                                </button>
                            </div>
                        @endif
                    </div>
                </form>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title">VSLA Support Performance <br />(Target vs Achieved)</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>VSLA Type</th>
                                    <th class="text-center">Project Target</th>
                                    <th class="text-center">Benefit From Support</th>
                                    <th class="text-end">Result %</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (['mature' => 240, 'progressive' => 160, 'new' => 400] as $nature => $target)
                                    @php
                                        // Controller uses 'progressive', mapping ensures data shows
                                        $achieved = $groupsByNature->where('nature', $nature)->first()->achieved ?? 0;
                                    @endphp
                                    <tr>
                                        <td class="text-capitalize fw-bold">{{ $nature }}</td>
                                        <td class="text-center">{{ $target }}</td>
                                        <td class="text-center fw-bold">{{ $achieved }}</td>
                                        <td class="text-end">
                                            <div class="progress" style="height: 8px;">
                                                <div class="progress-bar bg-primary"
                                                    style="width: {{ ($achieved / $target) * 100 }}%"></div>
                                            </div>
                                            <small>{{ round(($achieved / $target) * 100) }}%</small>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title">VSLA Membership Breakdown</h6>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-bordered mb-0">
                            <thead>
                                <tr>
                                    <th>VSLA Categories</th>
                                    <th class="text-center">Female</th>
                                    <th class="text-center">Male</th>
                                    <th class="text-center">Adol. Girls</th>
                                    <th class="text-center">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (['mature', 'progressive', 'new'] as $nature)
                                    <tr>
                                        <td class="text-capitalize bg-light fw-bold">{{ $nature }}</td>
                                        <td class="text-center">
                                            {{ number_format($membershipByNature2[$nature]['female'] ?? 0) }}</td>
                                        <td class="text-center">
                                            {{ number_format($membershipByNature2[$nature]['male'] ?? 0) }}</td>
                                        <td class="text-center">
                                            {{ number_format($membershipByNature2[$nature]['adol_girls'] ?? 0) }}</td>
                                        <td class="text-center fw-bold text-primary">
                                            {{ number_format($membershipByNature2[$nature]['total'] ?? 0) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title">Support Provided By State</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p class="small text-muted text-center fw-bold">Supported in WBGS</p>
                                <canvas id="trainingChart" height="200"></canvas>
                            </div>
                            <div class="col-md-6">
                                <p class="small text-muted text-center fw-bold">Supported in EES</p>
                                <canvas id="kitsChart" height="200"></canvas>
                            </div>
                            <p>&nbsp;</p>
                            <hr>
                            <div class="col-md-6">
                                <p class="small text-muted text-center fw-bold">Productive Assets Distribution by types of
                                    Groups</p>
                                <canvas id="kitsMembersChart" height="200"></canvas>
                            </div>
                            <div class="col-md-5">
                                <p class="small text-muted text-center fw-bold">Capacity Building by types of Groups</p>
                                <canvas id="capacityBuildingChart" height="200"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card map-card">
                    <div class="card-header">
                        <ul class="nav nav-pills nav-tabs-modern" id="mapTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="group-map-tab" data-bs-toggle="tab"
                                    data-bs-target="#group-map" type="button" role="tab"><i
                                        class="fas fa-layer-group me-1"></i> VSLA Groups Distribution</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="member-map-tab" data-bs-toggle="tab"
                                    data-bs-target="#member-map" type="button" role="tab"><i
                                        class="fas fa-users me-1"></i> VSLA Members Distribution</button>
                            </li>
                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="group-map" role="tabpanel">
                            <div class="map-wrapper">
                                <div id="groupMap"></div>
                                <span class="map-hint">Click markers for location details</span>
                            </div>
                        </div>
                        <div class="tab-pane fade" id="member-map" role="tabpanel">
                            <div class="map-wrapper">
                                <div id="memberMap"></div>
                                <span class="map-hint">Click markers for location details</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title">Capacity Building Provided to VLSA Members</h6>
                    </div>
                    <div class="card-body">
                        <canvas id="genderChart" height="200"></canvas>
                    </div>
                </div>
            </div>
        </div>
        {{-- Additional Charts Row --}}
        <div class="row">
            <div class="col-md-6">
                <p class="small text-muted text-center fw-bold">Supported in WBGS</p>
                <canvas id="wbgsChart" height="200"></canvas>
            </div>
            <div class="col-md-6">
                <p class="small text-muted text-center fw-bold">Supported in EES</p>
                <canvas id="eesChart" height="200"></canvas>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // --- Global Config ---
        Chart.defaults.font.size = 12;
        Chart.defaults.color = '#111827'; // dark grey text
        Chart.defaults.plugins.legend.labels.color = '#111827';
        Chart.defaults.plugins.title.color = '#111827';
        Chart.defaults.plugins.tooltip.titleColor = '#111827';
        Chart.defaults.plugins.tooltip.bodyColor = '#111827';
        Chart.defaults.plugins.tooltip.footerColor = '#111827';
        Chart.defaults.plugins.tooltip.titleFont = {
            weight: 'bold'
        };
        Chart.defaults.plugins.tooltip.bodyFont = {
            size: 12,
            weight: 'bold'
        };
        Chart.defaults.plugins.tooltip.footerFont = {
            size: 12,
            weight: 'bold'
        };
        Chart.defaults.plugins.tooltip.titleFont = {
            size: 14,
            weight: 'bold'
        };

        const colors = ['#29ab52', '#2c6693', '#00796b', '#f59e0b', '#ef4444', '#8b5cf6'];

        // Count-up animation for stat cards
        (function runStatCountUp() {
            var duration = 4000;
            var els = document.querySelectorAll('.stat-count');

            function formatValue(val, el) {
                var prefix = el.getAttribute('data-prefix') || '';
                var decimals = el.getAttribute('data-decimals');
                var fmt = el.getAttribute('data-format');
                var text = val;
                if (decimals !== null && decimals !== '') {
                    text = Number(val).toFixed(parseInt(decimals, 10));
                } else if (fmt === 'number') {
                    text = Math.round(val).toLocaleString();
                } else {
                    text = Math.round(val);
                }
                return prefix + text;
            }

            function animate(el) {
                var target = parseFloat(el.getAttribute('data-target')) || 0;
                var start = 0;
                var startTime = null;

                function step(timestamp) {
                    if (!startTime) startTime = timestamp;
                    var elapsed = timestamp - startTime;
                    var progress = Math.min(elapsed / duration, 1);
                    progress = 1 - Math.pow(1 - progress, 2);
                    var current = start + (target - start) * progress;
                    el.textContent = formatValue(current, el);
                    if (progress < 1) requestAnimationFrame(step);
                    else el.textContent = formatValue(target, el);
                }
                requestAnimationFrame(step);
            }
            for (var i = 0; i < els.length; i++) animate(els[i]);
        })();

        // 1. Training Chart (Left side)
        new Chart(document.getElementById('trainingChart'), {
            type: 'bar',
            data: {
                labels: ['Mature', 'Progressive', 'New'],
                datasets: [{
                    label: 'Completed',
                    data: [
                        {{ $trainingsCumulative['matured']['total'] ?? 0 }},
                        {{ $trainingsCumulative['progressive']['total'] ?? 0 }},
                        {{ $trainingsCumulative['new']['total'] ?? 0 }}
                    ],
                    backgroundColor: colors[0]
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false,
                        labels: {
                            color: '#111827',
                            font: {
                                size: 12,
                                weight: 'bold'
                            }
                        }
                    }
                }
            }
        });

        // 2. Kits Chart (Left side)
        new Chart(document.getElementById('kitsChart'), {
            type: 'bar',
            data: {
                labels: ['Matured', 'Progressive', 'New'],
                datasets: [{
                    data: [
                        {{ $kitsGroupsCumulative['matured']['groups'] ?? 0 }},
                        {{ $kitsGroupsCumulative['progressive']['groups'] ?? 0 }},
                        {{ $kitsGroupsCumulative['new']['groups'] ?? 0 }}
                    ],
                    backgroundColor: colors[1]
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
        // 6. Kits Members
        new Chart(document.getElementById('kitsMembersChart'), {
            type: 'bar',
            data: {
                labels: ['Mature', 'Progressive', 'New'],
                datasets: [{
                    label: 'Members',
                    data: [{{ $kitsMembersCumulative['matured']['total'] ?? 0 }},
                        {{ $kitsMembersCumulative['progressive']['total'] ?? 0 }},
                        {{ $kitsMembersCumulative['new']['total'] ?? 0 }}
                    ],
                    borderColor: colors[0],
                    backgroundColor: colors[0],
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
        // 7. Capacity Building Chart (Right side) – doughnut for a friendly, clear view
        new Chart(document.getElementById('capacityBuildingChart'), {
            type: 'doughnut',
            data: {
                labels: ['Mature', 'Progressive', 'New'],
                datasets: [{
                    data: [{{ $capacityBuildingCumulative['matured']['total'] ?? 0 }},
                        {{ $capacityBuildingCumulative['progressive']['total'] ?? 0 }},
                        {{ $capacityBuildingCumulative['new']['total'] ?? 0 }}
                    ],
                    backgroundColor: [colors[0], colors[1], colors[3]],
                    borderColor: '#fff',
                    borderWidth: 2,
                    hoverOffset: 8
                }]
            },
            options: {
                cutout: '55%',
                plugins: {
                    legend: {
                        position: 'bottom'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(ctx) {
                                var total = ctx.dataset.data.reduce(function(a, b) {
                                    return a + b;
                                }, 0);
                                var pct = total ? ((ctx.raw / total) * 100).toFixed(1) : 0;
                                return ctx.label + ': ' + ctx.raw + ' (' + pct + '%)';
                            }
                        }
                    }
                }
            }
        });

        // 4. Gender Chart (Right side)
        new Chart(document.getElementById('genderChart'), {
            type: 'doughnut',
            data: {
                labels: ['Female', 'Male'],
                datasets: [{
                    data: [{{ $genderData['female'] }}, {{ $genderData['male'] }}],
                    backgroundColor: ['#29ab52', '#3b82f6']
                }]
            },
            options: {
                cutout: '70%'
            }
        });

        // --- MAPS ---
        const mapCenter = [7.0, 30.0];
        const groupMap = L.map('groupMap', {
            scrollWheelZoom: false
        }).setView(mapCenter, 6);
        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png').addTo(groupMap);

        const groupLocations = {!! json_encode($groupLocations) !!};
        console.log('Group Locations:', groupLocations);
        console.log('Group Locations count:', groupLocations.length);
        
        // Group by coordinates to see how many groups share the same location
        const coordGroups = {};
        groupLocations.forEach((loc, index) => {
            const key = `${loc.lat},${loc.lon}`;
            if (!coordGroups[key]) {
                coordGroups[key] = [];
            }
            coordGroups[key].push({index, ...loc});
        });
        
        console.log('Groups by coordinates:', coordGroups);
        
        // Create clustered markers for groups at same location
        const clusteredLocations = {};
        groupLocations.forEach((loc, index) => {
            const key = `${loc.lat},${loc.lon}`;
            if (!clusteredLocations[key]) {
                clusteredLocations[key] = {
                    lat: loc.lat,
                    lon: loc.lon,
                    groups: []
                };
            }
            clusteredLocations[key].groups.push(loc);
        });
        
        // Add clustered markers
        Object.values(clusteredLocations).forEach(cluster => {
            const radius = Math.min(5 + cluster.groups.length * 2, 20); // Larger radius for more groups
            const color = cluster.groups.some(g => g.using_fallback) ? '#ff0000' : colors[0];
            
            const marker = L.circleMarker([cluster.lat, cluster.lon], {
                radius: radius,
                color: color,
                fillColor: color,
                fillOpacity: 0.7
            }).addTo(groupMap);
            
            // Create popup with all groups at this location
            let popupContent = `<strong>${cluster.groups.length} Groups at this location</strong><br><hr>`;
            cluster.groups.forEach(group => {
                popupContent += `
                    <div style="margin: 5px 0; padding: 5px; border-left: 3px solid ${group.using_fallback ? '#ff0000' : '#29ab52'};">
                        <strong>${group.name}</strong><br>
                        <small>County: ${group.county}</small><br>
                        ${group.using_fallback ? '<small style="color: red;">⚠ Using fallback coordinates</small>' : '<small style="color: green;">✓ Exact coordinates</small>'}
                    </div>
                `;
            });
            
            marker.bindPopup(popupContent, {
                maxWidth: 300,
                maxHeight: 400
            });
        });

        const memberMap = L.map('memberMap', {
            scrollWheelZoom: false
        }).setView(mapCenter, 6);
        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png').addTo(memberMap);
        const memberLocations = {!! json_encode($memberLocations) !!}; // Similar aggregation
        console.log('Member Locations:', memberLocations);
        console.log('Member Locations count:', memberLocations.length);
        
        memberLocations.forEach((loc, index) => {
            console.log(`Adding member marker ${index}:`, loc);
            L.circleMarker([loc.lat, loc.lon], {
                radius: 5,
                color: colors[1]
            }).addTo(memberMap).bindPopup(loc.name);
        });

        var groupStateMapEl = document.getElementById('groupStateMap');
        if (groupStateMapEl) {
            const groupStateMap = L.map('groupStateMap', {
                scrollWheelZoom: false
            }).setView(mapCenter, 6);
            L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png').addTo(groupStateMap);
            const groupStateLocations = {!! json_encode($groupLocationsByState ?? []) !!};
            groupStateLocations.forEach(loc => L.circleMarker([loc.lat, loc.lon], {
                radius: 5,
                color: colors[0]
            }).addTo(groupStateMap).bindPopup(loc.name));
        }

        // Bootstrap Tab resize fix for Leaflet
        document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(btn => {
            btn.addEventListener('shown.bs.tab', () => {
                groupMap.invalidateSize();
                memberMap.invalidateSize();
            });
        });

        function downloadFilteredReport() {
            const url = new URL(window.location);
            url.searchParams.set('export', '1');
            window.location.href = url.toString();
        }
        // WBGS Support Chart
        new Chart(document.getElementById('wbgsChart'), {
            type: 'bar',
            data: {
                labels: ['Mature', 'Progressive', 'New'],
                datasets: [{
                    label: 'Groups Supported',
                    data: [
                        {{ $wbgsSupported['matured'] ?? 0 }},
                        {{ $wbgsSupported['progressive'] ?? 0 }},
                        {{ $wbgsSupported['new'] ?? 0 }}
                    ],
                    backgroundColor: '#29ab52'
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // EES Support Chart
        new Chart(document.getElementById('eesChart'), {
            type: 'bar',
            data: {
                labels: ['Mature', 'Progressive', 'New'],
                datasets: [{
                    label: 'Groups Supported',
                    data: [
                        {{ $eesSupported['matured'] ?? 0 }},
                        {{ $eesSupported['progressive'] ?? 0 }},
                        {{ $eesSupported['new'] ?? 0 }}
                    ],
                    backgroundColor: '#2c6693'
                }]
            },
            options: {
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    </script>
@endpush
