@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 <span style="font-size: 0.8rem;">(Click on + icon to view details)</span></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 pagination-footer">
                        {{ $entries->links('pagination::bootstrap-4') }}
                    </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-4 green-bordered">
                            <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-4 green-bordered">
                            <h6 class="text-center mb-3">Status Breakdown by Organization</h6>
                            <canvas id="orgStackedBar" height="200"></canvas>
                        </div>
                         <!-- 3. Horizontal Bar per ESS Code -->       
                        <div class="col-lg-4 green-bordered">
                            <h6 class="text-center mb-3">Status Distribution per ESS Standard</h6>
                            <canvas id="essBarChart" height="300"></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-lg-4 green-bordered">
                            <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>

                        <!-- 5. Heatmap: Activities × Organizations/Sub-locations  -->
                        <div class="col-lg-8 green-bordered">
                            <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>
                            <div class="heatmap-container" style="height: 400px; overflow-y: auto;">
                                <canvas id="activityHeatmap" style="max-height: 350px;"></canvas>
                            </div>
                        </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>
                            <div class="heatmap-container" style="height: 400px; overflow-y: auto;">
                                <canvas id="activityHeatmap" style="max-height: 350px;"></canvas>
                            </div>
                        </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>
    /**
     * 1. Data Initialization (The Bridge)
     * Convert all PHP variables to JS Objects immediately.
     */
    const statusLabels = @json($statusLabels ?? []);
    const statsData    = @json($stats ?? []);
    const overallData  = @json($overallStats ?? []);
    const orgData      = @json($orgStats ?? []);
    
    // Heatmap specific data
    const heatmapActivities = @json($activities ?? []);
    const heatmapOrgSubs   = @json($orgSubs ?? []);
    const heatmapValues    = @json($heatmapData ?? []);
    const heatmapColors    = @json($heatmapBackgrounds ?? []);

    const statusOrder = ['completed', 'ongoing', 'delayed', 'not_started', 'cancelled'];
    const statusColors = {
        completed:    '#198754',
        ongoing:      '#0d6efd',
        delayed:      '#ffc107',
        not_started:  '#6c757d',
        cancelled:    '#dc3545'
    };
    
    const statusValueMap = {
        completed: 5, ongoing: 3, delayed: 1, not_started: 0, cancelled: -1
    };

    /**
     * 2. Table Toggle Logic
     */
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.toggle-ess').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                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');
                }
            });
        });
    });

    /**
     * 3. Chart Implementations
     */

    // --- 1. Overall Doughnut ---
    new Chart(document.getElementById('overallDoughnut'), {
        type: 'doughnut',
        data: {
            labels: statusOrder.map(s => statusLabels[s] || s.toUpperCase()),
            datasets: [{
                data: statusOrder.map(s => overallData[s] || 0),
                backgroundColor: statusOrder.map(s => statusColors[s])
            }]
        },
        options: { responsive: true, plugins: { legend: { position: 'bottom' } } }
    });

    // --- 2. Stacked Bar by Organization ---
    new Chart(document.getElementById('orgStackedBar'), {
        type: 'bar',
        data: {
            labels: ['UN Women', 'UNOPS', 'ADRA'],
            datasets: statusOrder.map(status => ({
                label: statusLabels[status] || status.toUpperCase(),
                data: [
                    orgData.unwomen?.[status] || 0,
                    orgData.unops?.[status]   || 0,
                    orgData.adra?.[status]    || 0
                ],
                backgroundColor: statusColors[status]
            }))
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            scales: { x: { stacked: true }, y: { stacked: true } }
        }
    });

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

    // --- 3. Horizontal Bar per ESS ---
    const essLabels = Object.keys(statsData);
    new Chart(document.getElementById('essBarChart'), {
        type: 'bar',
        data: {
            labels: essLabels,
            datasets: statusOrder.map(status => ({
                label: statusLabels[status] || status.toUpperCase(),
                data: essLabels.map(code => (statsData[code] || {})[status] || 0),
                backgroundColor: statusColors[status]
            }))
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            scales: { x: { stacked: true }, y: { stacked: true } }
        }
    });

    // --- 4. Activity Heatmap (The "Max Size" Fix) ---
    const ctxHeatmap = document.getElementById('activityHeatmap');
    
    // Fix: Set maximum canvas dimensions to prevent "Canvas exceeds max size"
    ctxHeatmap.style.maxHeight = '350px';
    ctxHeatmap.style.maxWidth = '100%';

    new Chart(ctxHeatmap, {
        type: 'matrix',
        data: {
            datasets: [{
                label: 'ESS Status',
                data: heatmapValues.flatMap((row, rowIndex) => 
                    row.map((value, colIndex) => ({
                        x: heatmapOrgSubs[colIndex],
                        y: heatmapActivities[rowIndex],
                        v: value,
                        backgroundColor: heatmapColors[rowIndex][colIndex]
                    }))
                ),
                // Using fixed numbers or relative percentages to prevent infinite growth
                width: ({chart}) => chart.chartArea ? (chart.chartArea.width / heatmapOrgSubs.length) - 1 : 0,
                height: ({chart}) => chart.chartArea ? (chart.chartArea.height / heatmapActivities.length) - 1 : 0,
                borderWidth: 1,
                borderColor: 'rgba(255,255,255,0.3)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false, // Required for custom height
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        title: (ctx) => `${ctx[0].raw.y}`,
                        label: (ctx) => {
                            const val = ctx.raw.v;
                            const statusKey = Object.keys(statusValueMap).find(k => statusValueMap[k] === val);
                            return `Org: ${ctx.raw.x} | Status: ${statusLabels[statusKey] || 'Unknown'}`;
                        }
                    }
                }
            },
            scales: {
                x: { type: 'category', labels: heatmapOrgSubs },
                y: { 
                    type: 'category', 
                    labels: heatmapActivities.map(act => act.replace(/_/g, ' ')),
                    reverse: true 
                }
            }
        }
    });
</script>
@endsection