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

@extends($layout)

@section('title', 'Component 2 – WEOF Dashboard')

@section('content')
<div class="container-fluid py-4">
    <!-- 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>
                        Women Entrepreneur Opportunity and Facility (WEOF)
                    </h1> --}}
                    <p class="text-muted">Real-time analytics for SeedLab and GrowthLab beneficiaries</p>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                            <li class="breadcrumb-item active">Component 2 Dashboard</li>
                        </ol>
                    </nav>
                </div>
                <div class="col-lg-6">
                    <div class="d-flex justify-content-lg-end gap-2 dashboard-actions flex-wrap">
                        <a href="{{ route('component2.seedlab.create') }}" class="btn btn-success btn-sm">
                            <i class="bi bi-person-plus"></i> Add SeedLab Beneficiary
                        </a>
                        <a href="{{ route('component2.seedlab.index') }}" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-list-ul"></i> View SeedLab Data
                        </a>
                        <a href="{{ route('component2.growthlab.create') ?? '#' }}" class="btn btn-success btn-sm">
                            <i class="bi bi-person-plus"></i> Add GrowthLab Beneficiary
                        </a>
                        <a href="{{ route('component2.growthlab.index') ?? '#' }}" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-list-ul"></i> View GrowthLab Data
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Stats Cards -->
    <div class="row g-4 mb-5">
        <!-- SeedLab Total Beneficiaries -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm" style="background-color: #fff;
; border-bottom:3px solid #29ab52!important; border-right:1px solid #29ab52!important; color: #29ab52!important;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['total_seedlab_beneficiaries'] ?? 0 }}">0</h3>
                    <p class="mb-0">SeedLab Businesses Benefiting</p>
                </div>
            </div>
        </div>
    
        <!-- Female / Adolescent Girls (mostly SeedLab-focused) -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #29ab52
;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['female_and_adolgirl_count'] ?? $stats['female_count'] ?? 0 }}">0</h3>
                    <p class="mb-0 small-text">Female & Adolescent Girls (SeedLab)</p>
                </div>
            </div>
        </div>
    
        <!-- SeedLab Grants Disbursed -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #fff;
; border-bottom:3px solid #29ab52!important; border-right:1px solid #29ab52!important; color: #29ab52!important;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['seedlab_total_disbursed'] ?? $stats['total_disbursed'] ?? 0 }}" data-prefix="USD $" data-format="number">0</h3>
                    <p class="mb-0 small-text">SeedLab Grants Disbursed</p>
                </div>
            </div>
        </div>
    
        <!-- SeedLab Businesses that Received Grants -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #29ab52
;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['seedlab_with_grant'] ?? $stats['with_grant'] ?? 0 }}">0</h3>
                    <p class="mb-0 small-text">SeedLab Businesses Receiving Grants</p>
                </div>
            </div>
        </div>
    
        <!-- Pitch Passed (SeedLab-specific) -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #fff;
; border-bottom:3px solid #29ab52!important; border-right:1px solid #29ab52!important; color: #29ab52!important;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $pitchPassedCount ?? 0 }}">0</h3>
                    <p class="mb-0 small-text">SeedLab Pitch Passed</p>
                </div>
            </div>
        </div>
    
        <!-- Accelerator Average Passed (SeedLab-specific) -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #29ab52
;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $acceleratorAvgPassed ?? 0 }}" data-decimals="1">0</h3>
                    <p class="mb-0 small-text">Avg Accelerator Modules Passed (SeedLab)</p>
                </div>
            </div>
        </div>
    
        <!-- Placeholder / Future for GrowthLab (add real numbers when ready) -->
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #fff;
; border-bottom:3px solid #29ab52!important; border-right:1px solid #29ab52!important; color: #29ab52!important;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['total_growthlab_beneficiaries'] ?? 0 }}">0</h3>
                    <p class="mb-0 small-text">GrowthLab Businesses Benefiting</p>
                </div>
            </div>
        </div>
    
        <div class="col-md-3 col-sm-6">
            <div class="card border-0 shadow-sm text-white" style="background-color: #29ab52
;">
                <div class="card-body text-center">
                    <h3 class="stat-count" data-target="{{ $stats['growthlab_with_grant'] ?? 0 }}">0</h3>
                    <p class="mb-0 small-text">GrowthLab Businesses Receiving Grants</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row g-4">
        <!-- Sector Distribution -->
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Business Sector Distribution</h5>
                </div>
                <div class="card-body">
                    <canvas id="sectorChart" height="150"></canvas>
                </div>
            </div>
        </div>

        <!-- Grant Status -->
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Grant Status</h5>
                </div>
                <div class="card-body">
                    <canvas id="grantStatusChart" height="150"></canvas>
                </div>
            </div>
        </div>

        <!-- Cohort Progress (updated label) -->
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Cohort Progress – Bootcamp Completion</h5>
                </div>
                <div class="card-body">
                    <canvas id="cohortChart" height="180"></canvas>
                </div>
            </div>
        </div>

        <!-- Capacity Building Progress -->
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Capacity Building Progress</h5>
                </div>
                <div class="card-body">
                    <div class="row g-4">
                        <div class="col-md-4">
                            <h6 class="text-center">Bootcamp Modules (% Completed)</h6>
                            <canvas id="bootcampHeatmap" height="140"></canvas>
                        </div>
                        <div class="col-md-4">
                            <h6 class="text-center">Pitch Outcomes</h6>
                            <canvas id="pitchHeatmap" height="140"></canvas>
                        </div>
                        <div class="col-md-4">
                            <h6 class="text-center">Accelerator Modules (% Passed)</h6>
                            <canvas id="acceleratorHeatmap" height="140"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.3.1"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Count-up animation for stat cards
    (function runStatCountUp() {
        var duration = 1800;
        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]);
    })();

    const chartData = @json($chartData ?? []);

    // Sector Chart
    new Chart(document.getElementById('sectorChart'), {
        type: 'doughnut',
        data: {
            labels: chartData.sectors?.labels || [],
            datasets: [{
                data: chartData.sectors?.data || [],
                backgroundColor: ['#FF6384','#36A2EB','#FFCE56','#4BC0C0','#9966FF','#FF9F40','#C9CBCF','#66BB6A']
            }]
        },
        options: { plugins: { legend: { position: 'right' } } }
    });

    // Grant Status Pie
    new Chart(document.getElementById('grantStatusChart'), {
        type: 'pie',
        data: {
            labels: ['Disbursed', 'Approved (Not Paid)', 'No Grant Yet'],
            datasets: [{
                data: [
                    chartData.grants?.disbursed ?? 0,
                    chartData.grants?.approved_not_paid ?? 0,
                    chartData.grants?.no_grant ?? 0
                ],
                backgroundColor: ['#4CAF50', '#FFC107', '#9E9E9E']
            }]
        },
        options: { plugins: { legend: { position: 'bottom' } } }
    });

    // Cohort Progress (Bootcamp focused)
    new Chart(document.getElementById('cohortChart'), {
        type: 'bar',
        data: {
            labels: chartData.cohorts?.labels || [],
            datasets: [
                { label: 'Total Beneficiaries', data: chartData.cohorts?.total || [], backgroundColor: '#E0E0E0' },
                { label: 'Bootcamp Fully Completed', data: chartData.cohorts?.completed || [], backgroundColor: '#4CAF50' }
            ]
        },
        options: { scales: { y: { beginAtZero: true } } }
    });

    // Bootcamp Heatmap
    new Chart(document.getElementById('bootcampHeatmap'), {
        type: 'bar',
        data: {
            labels: ['M1','M2','M3','M4','M5'],
            datasets: [{
                label: '% Completed',
                data: Object.values(chartData.bootcamp_completion_rates || {}),
                backgroundColor: '#66BB6A'
            }]
        },
        options: {
            scales: { y: { max: 100, ticks: { callback: v => v + '%' } } },
            plugins: { legend: { display: false } }
        }
    });

    // Pitch Outcomes Doughnut
    new Chart(document.getElementById('pitchHeatmap'), {
        type: 'doughnut',
        data: {
            labels: ['Passed', 'Failed / Not Completed'],
            datasets: [{
                data: [chartData.pitch_success_rate ?? 0, 100 - (chartData.pitch_success_rate ?? 0)],
                backgroundColor: ['#4CAF50', '#F44336']
            }]
        },
        options: { plugins: { legend: { position: 'bottom' } } }
    });

    // Accelerator Heatmap
    new Chart(document.getElementById('acceleratorHeatmap'), {
        type: 'bar',
        data: {
            labels: Array.from({length: 10}, (_, i) => `M${i+1}`),
            datasets: [{
                label: '% Passed',
                data: Object.values(chartData.accelerator_pass_rates || {}),
                backgroundColor: '#2196F3'
            }]
        },
        options: {
            scales: { y: { max: 100, ticks: { callback: v => v + '%' } } },
            plugins: { legend: { display: false } }
        }
    });
});
</script>
@endsection