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

@extends($layout)

@section('title', 'Environmental and Social Safeguards')

@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-8">
                    <h1 class="dashboard-title">
                        <i class="fas fa-tachometer-alt" style="color: var(--dhis2-blue-primary);"></i>
                        Environmental and Social Safeguards (ESS) Tracker
                    </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('component1.dashboard') }}">Component 1 Dashboard</a></li>
                            <li class="breadcrumb-item active">ESS Tracker </li>
                        </ol>
                    </nav>
                </div>
                <div class="col-lg-4">
                    <div class="d-flex justify-content-lg-end gap-2 dashboard-actions">
                        <a href="{{ route('ess.create') }}" class="btn btn-success">
                            <i class="fas fa-plus me-2"></i> Add New Entry
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-lg-12">
            <!-- Summary Statistics Cards -->
            <div class="row mb-5">
                @php
                    $statusColors = [
                        'completed'    => 'bg-success',
                        'ongoing'      => 'bg-primary',
                        'delayed'      => 'bg-warning',
                        'not_started'  => 'bg-secondary',
                        'cancelled'    => 'bg-danger',
                    ];
                    $statusLabels = [
                        'completed'    => 'Completed',
                        'ongoing'      => 'Ongoing',
                        'delayed'      => 'Delayed',
                        'not_started'  => 'Not Started',
                        'cancelled'    => 'Cancelled',
                    ];
                @endphp

                @foreach ($stats ?? [] as $essCode => $counts)
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-header bg-light">
                                @php
                                switch ($essCode) {
                                    case 'ESS1':
                                        $essDisplayText = 'ESS1: Assessment and Management of Environmental and Social Risks and Impacts';
                                        break;
                                    case 'ESS2':
                                        $essDisplayText = 'ESS2: Labor and Working Conditions';
                                        break;
                                    case 'ESS3':
                                        $essDisplayText = 'ESS3: Resource Efficiency and Pollution Prevention and Management';
                                        break;
                                    case 'ESS4':
                                        $essDisplayText = 'ESS4: Community Health and Safety';
                                        break;
                                    case 'ESS5':
                                        $essDisplayText = 'ESS5: Land Acquisition, restrictions on land use and Involuntary Resettlement';
                                        break;
                                    case 'ESS6':
                                        $essDisplayText = 'ESS6: Biodiversity Conservation and Sustainable Management of Living Natural Resources';
                                        break;
                                    case 'ESS7':
                                        $essDisplayText = 'ESS7: Indigenous Peoples/sub-Saharan African, Historically Underserved traditional local Communities';
                                        break;
                                    case 'ESS8':
                                        $essDisplayText = 'ESS8: Cultural Heritage';
                                        break;
                                    case 'ESS10':
                                        $essDisplayText = 'ESS10: Stakeholders Engagement and Information Disclosure';
                                        break;
                                    default:
                                        $essDisplayText = $essCode; // fallback
                                }
                                @endphp
                                {{-- <h5 class="mb-0">{{ $essDisplayText }} - Summary</h5> --}}
                                <p>{{ $essDisplayText }} - Summary</p>
                            </div>
                            <div class="card-body">
                                @foreach ($counts as $status => $count)
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="badge {{ $statusColors[$status] ?? 'bg-info' }} px-3 py-2">
                                            {{ $statusLabels[$status] ?? ucfirst(str_replace('_', ' ', $status)) }}
                                        </span>
                                        <strong class="fs-5">{{ $count }}</strong>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>

            <!-- Full Tracker Table -->
            @if ($entries->count())
                <div class="card shadow-sm border-0 mb-5">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0">All ESS Entries</h5>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover table-bordered mb-0">
                                <thead class="table-dark">
                                    <tr>
                                        <th>#</th>
                                        <th>ESS Standard</th>
                                        <th>Activity</th>
                                        <th>Organization</th>
                                        <th>Sub-location</th>
                                        <th>Status</th>
                                        <th>Updated</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php
                                        $entriesGrouped = $entries->groupBy('ess_code');
                                    @endphp
                                    @foreach ($entriesGrouped as $essCode => $essEntries)
                                        <tr class="table-secondary">
                                            <td colspan="7">
                                                <button type="button"
                                                        class="btn btn-sm btn-link text-decoration-none toggle-ess"
                                                        data-target="ess-{{ \Illuminate\Support\Str::slug($essCode) }}">
                                                    <i class="fas fa-plus-circle me-1"></i>
                                                    {{ $essCode }}
                                                </button>
                                            </td>
                                        </tr>
                                        @foreach ($essEntries as $entry)
                                            <tr class="ess-row ess-{{ \Illuminate\Support\Str::slug($essCode) }} d-none">
                                                <td>{{ $loop->parent->iteration }}.{{ $loop->iteration }}</td>
                                                <td>{{ $entry->ess_code }}</td>
                                                <td>{{ $entry->activity_key }}</td>
                                                <td>{{ ucfirst($entry->organization) }}</td>
                                                <td>{{ strtoupper($entry->sub_org) }}</td>
                                                <td>
                                                    <span class="badge {{ $statusColors[$entry->status] ?? 'bg-info' }}">
                                                        {{ $statusLabels[$entry->status] ?? ucfirst(str_replace('_', ' ', $entry->status)) }}
                                                    </span>
                                                </td>
                                                <td>{{ $entry->updated_at->format('d M Y') }}</td>
                                            </tr>
                                        @endforeach
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        {{ $entries->links() }}
                    </div>
                </div>
            @else
                <div class="alert alert-info text-center mb-5">
                    No ESS entries found yet. <a href="{{ route('ess.create') }}" class="alert-link">Create one now</a>.
                </div>
            @endif

            <!-- Visualizations Section -->
            <div class="card shadow-sm border-0">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">ESS Tracker Visualizations</h5>
                </div>
                <div class="card-body">

                    <!-- 1. Overall Progress Doughnut Chart -->
                    <div class="row mb-5">
                        <div class="col-lg-6">
                            <h6 class="text-center mb-3">Overall Status Distribution</h6>
                            <canvas id="overallDoughnut" height="200"></canvas>
                        </div>

                        <!-- 2. Stacked Bar - Status per Organization -->
                        <div class="col-lg-6">
                            <h6 class="text-center mb-3">Status Breakdown by Organization</h6>
                            <canvas id="orgStackedBar" height="200"></canvas>
                        </div>
                    </div>

                    <!-- 3. Horizontal Bar per ESS Code -->
                    <div class="row mb-5">
                        <div class="col-12">
                            <h6 class="text-center mb-3">Status Distribution per ESS Standard</h6>
                            <canvas id="essBarChart" height="300"></canvas>
                        </div>
                    </div>

                    <!-- 4. Line Chart - Placeholder for Trend Over Time -->
                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-center mb-3">Progress Trend Over Time (Placeholder)</h6>
                            <canvas id="trendLineChart" height="250"></canvas>
                            <small class="form-text text-muted text-center d-block mt-2">
                                (Add timestamp/version tracking to enable real historical trends)
                            </small>
                        </div>
                    </div>

                    <!-- 5. Heatmap: Activities × Organizations/Sub-locations -->
                    <div class="row mt-5">
                        <div class="col-12">
                            <h6 class="text-center mb-3">Activity Heatmap (Color Intensity = Status)</h6>
                            <div class="text-center mb-3">
                                <small class="text-muted">
                                    Green = Completed | Blue = Ongoing | Yellow = Delayed | Gray = Not Started | Red = Cancelled
                                </small>
                            </div>
                            <canvas id="activityHeatmap" height="400"></canvas>
                        </div>
                    </div>

                </div>
            </div>

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

<!-- Chart.js CDN (add to layouts.app or admin if not already present) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-chart-matrix@2"></script>

<script>
    // Expand/collapse groups by ESS standard
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.toggle-ess').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.preventDefault(); // Prevent page jump
                const target = this.getAttribute('data-target');
                const rows = document.querySelectorAll('.' + target);
                const icon = this.querySelector('i');

                rows.forEach(row => {
                    row.classList.toggle('d-none');
                });

                if (icon) {
                    icon.classList.toggle('fa-plus-circle');
                    icon.classList.toggle('fa-minus-circle');
                }
            });
        });
    });

    const statusLabels = @json($statusLabels);

    // Prepare data from Laravel (passed via controller)
    const statusOrder = ['completed', 'ongoing', 'delayed', 'not_started', 'cancelled'];
    const statusColors = {
        completed:    '#198754',
        ongoing:      '#0d6efd',
        delayed:      '#ffc107',
        not_started:  '#6c757d',
        cancelled:    '#dc3545'
    };

    // 1. Overall Doughnut
    const overallData = @json($overallStats ?? []); // e.g. {completed: 12, ongoing: 8, ...}
    new Chart(document.getElementById('overallDoughnut'), {
        type: 'doughnut',
        data: {
            labels: statusOrder.map(s => statusLabels[s] || s.replace('_', ' ').toUpperCase()),
            datasets: [{
                data: statusOrder.map(s => overallData[s] || 0),
                backgroundColor: statusOrder.map(s => statusColors[s]),
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'bottom' } }
        }
    });

    // 2. Stacked Bar by Organization
    const orgData = @json($orgStats ?? []); // e.g. {unwomen: {completed:5,...}, unops: {...}, adra: {...}}
    new Chart(document.getElementById('orgStackedBar'), {
        type: 'bar',
        data: {
            labels: ['UN Women', 'UNOPS', 'ADRA'],
            datasets: statusOrder.map(status => ({
                label: statusLabels[status] || status.replace('_', ' ').toUpperCase(),
                data: [
                    orgData.unwomen?.[status] || 0,
                    orgData.unops?.[status]   || 0,
                    orgData.adra?.[status]    || 0
                ],
                backgroundColor: statusColors[status]
            }))
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            plugins: { legend: { position: 'bottom' } },
            scales: { x: { stacked: true }, y: { stacked: true } }
        }
    });

    // 3. Horizontal Bar per ESS
    const essLabels = @json(array_keys($stats ?? []));
    const essDatasets = statusOrder.map(status => ({
        label: statusLabels[status] || status.replace('_', ' ').toUpperCase(),
        data: essLabels.map(code => ($stats[code] ?? [])[status] ?? 0),
        backgroundColor: statusColors[status]
    }));

    new Chart(document.getElementById('essBarChart'), {
        type: 'bar',
        data: { labels: essLabels, datasets: essDatasets },
        options: {
            indexAxis: 'y',
            responsive: true,
            plugins: { legend: { position: 'bottom' } },
            scales: { x: { stacked: true }, y: { stacked: true } }
        }
    });

    // 4. Line Chart - Placeholder (customize later with real time-series data)
    new Chart(document.getElementById('trendLineChart'), {
        type: 'line',
        data: {
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], // example months
            datasets: statusOrder.map(status => ({
                label: statusLabels[status] || status,
                data: [0, 2, 5, 8, 12, 15], // dummy increasing for completed, etc.
                borderColor: statusColors[status],
                tension: 0.3,
                fill: false
            }))
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'bottom' } }
        }
    });

    // 5. Activity Heatmap using chartjs-chart-matrix
    const heatmapActivities = @json($activities ?? []);
    const heatmapOrgSubs   = @json($orgSubs ?? []);
    const heatmapValues    = @json($heatmapData ?? []);
    const heatmapColors    = @json($heatmapBackgrounds ?? []);

    new Chart(document.getElementById('activityHeatmap'), {
        type: 'matrix',
        data: {
            datasets: [{
                label: 'ESS Status Heatmap',
                data: heatmapValues.flatMap((row, rowIndex) => 
                    row.map((value, colIndex) => ({
                        x: heatmapOrgSubs[colIndex],
                        y: heatmapActivities[rowIndex],
                        v: value,
                        backgroundColor: heatmapColors[rowIndex][colIndex]
                    }))
                ),
                width: ({chart}) => (chart.chartArea || {}).width / heatmapOrgSubs.length - 1,
                height: ({chart}) => (chart.chartArea || {}).height / heatmapActivities.length - 1,
                borderWidth: 1,
                borderColor: 'rgba(255,255,255,0.3)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        title: (ctx) => `${ctx[0].raw.y} • ${ctx[0].raw.x}`,
                        label: (ctx) => {
                            const status = Object.keys({completed:5,ongoing:3,delayed:1,not_started:0,cancelled:-1})
                                .find(k => {completed:5,ongoing:3,delayed:1,not_started:0,cancelled:-1}[k] === ctx.raw.v) || 'unknown';
                            return `Status: ${status.replace('_', ' ').toUpperCase()}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'category',
                    labels: heatmapOrgSubs,
                    ticks: { maxRotation: 45, minRotation: 45 }
                },
                y: {
                    type: 'category',
                    labels: heatmapActivities.map(act => act.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())),
                    reverse: true  // so most important activities at top if ordered
                }
            }
        }
    });
</script>
@endsection