@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: 1.5rem; font-weight: 800; 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-6">
                    <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-6">
                    <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('component1.weof.index') }}" class="btn btn-dhis2-primary">
                            <i class="fas fa-briefcase me-1"></i> WEOF Beneficiaries
                        </a> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    {{-- <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold"><i class="fas fa-th-large me-2"></i>Component 1 Dashboard</h4>
        <div>
            <a href="{{ route('component1.groups.index') }}" class="btn btn-sm btn-primary">Manage Groups</a>
            <a href="{{ route('component1.members.index') }}" class="btn btn-sm btn-primary">
                <i class="fas fa-user-friends me-1"></i> ManageMembers
            </a>
            <a href="{{ route('component1.vsla.report') }}" class="btn btn-sm btn-success">Monthly Report</a>
        </div>
    </div> --}}

    <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">Total VSLA Groups Supported</span>
                <span class="stat-value green-stat-value">{{ number_format($stats['total_groups']) }}</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">Total VSLA Members Supported</span>
                <span class="stat-value green-stat-value">{{ number_format($stats['total_members']) }}</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">Total Groups Who Received Productive Assets</span>
                <span class="stat-value green-stat-value">{{ number_format($kpiStats['supports']) }}</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">Target Completion</span>
                <span class="stat-value green-stat-value">{{ round(($stats['total_groups'] / 800) * 100, 1) }}%</span>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            
            <div class="card">
                <div class="card-header"><h6 class="card-title">Engagement Performance (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">VSLA Identified/Enrolled</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 County</h6></div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p class="small text-muted text-center fw-bold">VSLA Kits Distributed By County</p>
                            <canvas id="trainingChart" height="200"></canvas>
                        </div>
                        <div class="col-md-6">
                            <p class="small text-muted text-center fw-bold">VLSA Kits Provided to Members</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</p>
                            <canvas id="kitsMembersChart" height="200"></canvas>
                        </div>
                        {{-- <div class="col-md-6">
                            <p class="small text-muted text-center fw-bold">Capacity Building</p>
                            <div id="groupStateMap" style="height: 300px;"></div>
                        </div> --}}
                        <div class="col-md-5">
                            <p class="small text-muted text-center fw-bold">Capacity Building</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">Top 10 Counties by Groups</h6></div>
                <div class="card-body">
                    <canvas id="countyChart" height="300"></canvas>
                </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>
</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'];

    // 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 + '%)';
                        }
                    }
                }
            }
        }
    });

    // 3. County Chart (Right side)
    // new Chart(document.getElementById('countyChart'), {
    //     type: 'bar',
    //     data: {
    //         labels: {!! json_encode($groupsByCounty->pluck('county')) !!},
    //         datasets: [{
    //             label: 'Groups',
    //             data: {!! json_encode($groupsByCounty->pluck('total')) !!},
    //             backgroundColor: colors[0]
    //         }]
    //     },
    //     options: { indexAxis: 'y', plugins: { legend: { display: false } } }
    // });

    // 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) !!};
    groupLocations.forEach(loc => {
        L.circleMarker([loc.lat, loc.lon], { radius: 5, color: colors[0] }).addTo(groupMap).bindPopup(loc.name);
    });

    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
    memberLocations.forEach(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();
        });
    });
</script>
@endpush