<div>
    <x-title>Pipeline Throughput Trends</x-title>

    {{-- Tab nav --}}
    <ul class="nav nav-tabs mb-0" id="trendTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="tab-weekly-btn"
                    data-bs-toggle="tab" data-bs-target="#tab-weekly"
                    type="button" role="tab">
                Week on Week
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="tab-monthly-btn"
                    data-bs-toggle="tab" data-bs-target="#tab-monthly"
                    type="button" role="tab">
                Month on Month
            </button>
        </li>
    </ul>

    <div class="tab-content">

        {{-- ── Weekly ── --}}
        <div class="tab-pane fade show active" id="tab-weekly" role="tabpanel">
            <div class="card shadow-sm border-0" style="border-radius:0 0.375rem 0.375rem 0.375rem">
                <div class="card-body pb-2">
                    <div style="position:relative;height:260px">
                        <canvas id="weeklyChart"></canvas>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size:.78rem;width:auto">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-3 py-2 border-0 text-nowrap">Metric</th>
                                    @foreach($weeklyData['labels'] as $label)
                                        <th class="text-center border-0 text-nowrap py-2" style="width:44px;padding-left:4px;padding-right:4px">{{ $label }}</th>
                                    @endforeach
                                    <th class="text-center border-0 pe-3 py-2" style="width:52px">vs prev</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($weeklyData['metrics'] as $metric => $values)
                                    @php
                                        $count    = count($values);
                                        $current  = $values[$count - 1] ?? 0;
                                        $previous = $values[$count - 2] ?? 0;
                                        if ($previous == 0) {
                                            $changeText  = $current > 0 ? 'New' : '—';
                                            $changeClass = $current > 0 ? 'text-success' : 'text-muted';
                                        } else {
                                            $pct         = round((($current - $previous) / $previous) * 100, 1);
                                            $changeText  = ($pct >= 0 ? '+' : '') . $pct . '%';
                                            $changeClass = $pct >= 0 ? 'text-success' : 'text-danger';
                                        }
                                    @endphp
                                    <tr>
                                        <td class="ps-3 fw-semibold">{{ $metric }}</td>
                                        @foreach($values as $value)
                                            <td class="text-center" style="padding:6px 4px">{{ $value > 0 ? number_format($value) : '—' }}</td>
                                        @endforeach
                                        <td class="text-center pe-3 fw-bold {{ $changeClass }}">{{ $changeText }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        {{-- ── Monthly ── --}}
        <div class="tab-pane fade" id="tab-monthly" role="tabpanel">
            <div class="card shadow-sm border-0" style="border-radius:0 0.375rem 0.375rem 0.375rem">
                <div class="card-body pb-2">
                    <div style="position:relative;height:260px">
                        <canvas id="monthlyChart"></canvas>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size:.78rem;width:auto">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-3 py-2 border-0 text-nowrap">Metric</th>
                                    @foreach($monthlyData['labels'] as $label)
                                        <th class="text-center border-0 text-nowrap py-2" style="width:50px;padding-left:4px;padding-right:4px">{{ $label }}</th>
                                    @endforeach
                                    <th class="text-center border-0 pe-3 py-2" style="width:52px">vs prev</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($monthlyData['metrics'] as $metric => $values)
                                    @php
                                        $count    = count($values);
                                        $current  = $values[$count - 1] ?? 0;
                                        $previous = $values[$count - 2] ?? 0;
                                        if ($previous == 0) {
                                            $changeText  = $current > 0 ? 'New' : '—';
                                            $changeClass = $current > 0 ? 'text-success' : 'text-muted';
                                        } else {
                                            $pct         = round((($current - $previous) / $previous) * 100, 1);
                                            $changeText  = ($pct >= 0 ? '+' : '') . $pct . '%';
                                            $changeClass = $pct >= 0 ? 'text-success' : 'text-danger';
                                        }
                                    @endphp
                                    <tr>
                                        <td class="ps-3 fw-semibold">{{ $metric }}</td>
                                        @foreach($values as $value)
                                            <td class="text-center" style="padding:6px 4px">{{ $value > 0 ? number_format($value) : '—' }}</td>
                                        @endforeach
                                        <td class="text-center pe-3 fw-bold {{ $changeClass }}">{{ $changeText }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

@assets
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
@endassets

@script
<script>
    const weeklyData  = @json($weeklyData);
    const monthlyData = @json($monthlyData);

    const palette = [
        '#0d6efd',
        '#fd7e14',
        '#198754',
        '#dc3545',
        '#6f42c1',
        '#20c997',
        '#6c757d',
    ];

    function buildDatasets(metricsObj) {
        return Object.entries(metricsObj).map(([label, data], i) => ({
            label,
            data,
            borderColor: palette[i % palette.length],
            backgroundColor: palette[i % palette.length] + '18',
            borderWidth: 2,
            pointRadius: 3,
            pointHoverRadius: 5,
            tension: 0.35,
            fill: false,
        }));
    }

    const chartDefaults = {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: { position: 'bottom', labels: { boxWidth: 12, padding: 16 } },
            tooltip: { padding: 10 },
        },
        scales: {
            x: { grid: { display: false } },
            y: { beginAtZero: true, ticks: { precision: 0 } },
        },
    };

    setTimeout(() => {
        // Weekly chart — visible immediately
        new Chart(document.getElementById('weeklyChart'), {
            type: 'line',
            data: { labels: weeklyData.labels, datasets: buildDatasets(weeklyData.metrics) },
            options: chartDefaults,
        });

        // Monthly chart — defer until tab is first shown so Chart.js can size correctly
        let monthlyChartInstance = null;
        document.getElementById('tab-monthly-btn').addEventListener('shown.bs.tab', () => {
            if (!monthlyChartInstance) {
                monthlyChartInstance = new Chart(document.getElementById('monthlyChart'), {
                    type: 'line',
                    data: { labels: monthlyData.labels, datasets: buildDatasets(monthlyData.metrics) },
                    options: chartDefaults,
                });
            }
        });
    }, 0);
</script>
@endscript
