<div>
    <x-title>Pipeline KPIs</x-title>

    @php
        $fmt = function ($value, string $type) {
            if ($value === null) {
                return '—';
            }
            return match ($type) {
                'percent' => number_format($value, 1) . '%',
                'days'    => number_format($value, 1) . 'd',
                default   => number_format($value),
            };
        };

        // Inline SVG sparkline over the daily series (uses currentColor, so the
        // parent's text-{accent} class tints it). Includes a soft area fill.
        $spark = function (array $s): string {
            $n = count($s);
            if ($n < 2) {
                return '';
            }
            $min = min($s);
            $max = max($s);
            $range = max(1, $max - $min);
            $w = 100.0; $h = 28.0; $pad = 3.0;
            $pts = [];
            foreach ($s as $i => $v) {
                $x = round(($i / ($n - 1)) * $w, 2);
                $y = round($h - $pad - (($v - $min) / $range) * ($h - 2 * $pad), 2);
                $pts[] = "$x,$y";
            }
            $line = implode(' ', $pts);
            $area = '0,' . $h . ' ' . $line . ' ' . $w . ',' . $h; // close the fill to the baseline
            return '<svg viewBox="0 0 ' . $w . ' ' . $h . '" preserveAspectRatio="none" width="100%" height="30" style="display:block;">'
                . '<polygon points="' . $area . '" fill="currentColor" fill-opacity="0.12" stroke="none"/>'
                . '<polyline points="' . $line . '" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>'
                . '</svg>';
        };

        // Net change across the visible series. $dir decides good/bad colouring:
        // 'down' = fewer is better, 'up' = more is better, 'neutral' = no judgement.
        $netTrend = function (array $s, string $dir = 'down'): string {
            $net = end($s) - reset($s);
            $arr = $net < 0 ? '▼' : ($net > 0 ? '▲' : '●');
            if ($net === 0) {
                return '<span class="badge rounded-pill bg-light text-muted fw-normal">● 0 · 14d</span>';
            }
            $good = match ($dir) {
                'up'    => $net > 0,
                'down'  => $net < 0,
                default => null,
            };
            $cls = $good === null
                ? 'bg-light text-muted'
                : ($good ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger');
            return '<span class="badge rounded-pill ' . $cls . ' fw-semibold">' . $arr . ' ' . number_format(abs($net)) . ' · 14d</span>';
        };
    @endphp

    <style>
        .kpi-card { transition: transform .12s ease, box-shadow .12s ease; }
        .kpi-card:hover { transform: translateY(-2px); box-shadow: 0 .5rem 1rem rgba(0,0,0,.09) !important; }
        .kpi-panel { transition: box-shadow .12s ease; }
        .kpi-panel:hover { box-shadow: 0 .5rem 1.25rem rgba(0,0,0,.08) !important; }
        .kpi-panel table td, .kpi-panel table th { vertical-align: middle; }
        .kpi-hist { background: rgba(0,0,0,.02); }
        .kpi-num { font-variant-numeric: tabular-nums; }
        .kpi-val { font-size: 2rem; font-weight: 700; line-height: 1.1; }
    </style>

    {{-- Subtitle + filter --}}
    <div class="d-flex flex-wrap align-items-center justify-content-between mb-3 gap-2 mt-2">
        <small class="text-muted">Current backlog up top · pipeline flow (Day / Week / Month) below</small>
        <div class="d-flex align-items-center gap-2">
            <i class="mdi mdi-filter-variant text-muted"></i>
            <select wire:model.live="leadSourceId" class="form-select form-select-sm shadow-sm" style="min-width:220px;">
                <option value="">All Lead Sources</option>
                @foreach ($leadSources as $source)
                    <option value="{{ $source->id }}">{{ $source->display_name }}</option>
                @endforeach
            </select>
        </div>
    </div>

    {{-- Current backlog / snapshot metrics — stat cards --}}
    <div class="d-flex align-items-center gap-2 mb-2">
        <span class="badge bg-dark-subtle text-dark fw-bold text-uppercase small px-3 py-2">Right now</span>
        <div class="flex-grow-1" style="height:1px;background:rgba(0,0,0,.08);"></div>
    </div>

    <div class="row g-3 mb-2">
        @foreach ($currentCards as $card)
            <div class="col-6 col-md-4 col-xl-3">
                <div class="card kpi-card border-0 shadow-sm h-100">
                    <div class="card-body py-3">
                        <div class="d-flex justify-content-between align-items-start mb-1">
                            <span class="text-muted small fw-semibold">{{ $card['label'] }}</span>
                            @if ($card['fivePm'])
                                <span class="badge bg-light text-muted fw-normal flex-shrink-0">5pm</span>
                            @endif
                        </div>
                        <div class="d-flex align-items-end justify-content-between gap-2 mb-1">
                            <span class="kpi-val kpi-num text-{{ $card['accent'] }}">{{ number_format($card['value']) }}</span>
                            @if ($card['series'])
                                <span class="text-nowrap">{!! $netTrend($card['series'], $card['dir']) !!}</span>
                            @endif
                        </div>
                        @if ($card['series'])
                            <div class="text-{{ $card['accent'] }}" title="Last 14 days">{!! $spark($card['series']) !!}</div>
                        @else
                            <div class="text-muted small fst-italic">current value</div>
                        @endif
                        @if ($card['note'])
                            <div class="text-muted mt-1" style="font-size:.72rem;">{{ $card['note'] }}</div>
                        @endif
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    {{-- Pipeline flow — one panel (card) per stage, each with its own table --}}
    <div class="d-flex align-items-center gap-2 mt-4 mb-2">
        <span class="badge bg-secondary-subtle text-secondary fw-bold text-uppercase small px-3 py-2">Pipeline flow</span>
        <div class="flex-grow-1" style="height:1px;background:rgba(0,0,0,.08);"></div>
    </div>

    <div class="row g-4">
        @foreach ($sections as $section)
            <div class="col-12 col-xl-6">
                <div class="card kpi-panel border-0 shadow-sm h-100">
                    <div class="card-header bg-{{ $section['accent'] }}-subtle border-0 py-2 d-flex align-items-center">
                        <span class="fw-bold text-{{ $section['accent'] }} text-uppercase small">{{ $section['title'] }}</span>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-sm table-hover align-middle mb-0 kpi-num">
                            <thead>
                                <tr class="text-muted small">
                                    <th class="fw-normal ps-3" style="width:38%;">Metric</th>
                                    <th class="text-center fw-normal">Day</th>
                                    <th class="text-center fw-normal">Week</th>
                                    <th class="text-center fw-semibold">Month</th>
                                    <th class="text-center fw-normal border-start kpi-hist">Lst Wk</th>
                                    <th class="text-center fw-normal kpi-hist pe-3">Lst Mo</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($section['rows'] as $row)
                                    <tr>
                                        <td class="ps-3 text-dark small fw-medium" @if($row['note']) title="{{ $row['note'] }}" @endif>
                                            {{ $row['label'] }}
                                            @if ($row['sub'])
                                                <span class="text-muted fw-normal">{{ $row['sub'] }}</span>
                                            @endif
                                        </td>
                                        <td class="text-center text-muted small">{{ $fmt($row['values']['today'], $row['type']) }}</td>
                                        <td class="text-center text-muted small">{{ $fmt($row['values']['week'], $row['type']) }}</td>
                                        <td class="text-center fw-bold text-dark">{{ $fmt($row['values']['month'], $row['type']) }}</td>
                                        <td class="text-center text-muted small border-start kpi-hist">{{ $fmt($row['values']['histWeek'], $row['type']) }}</td>
                                        <td class="text-center text-muted small kpi-hist pe-3">{{ $fmt($row['values']['histMonth'], $row['type']) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    @unless ($showDeltas)
        <p class="text-muted small mb-0 mt-3">
            <i class="mdi mdi-information-outline me-1"></i>
            Backlog trend arrows are hidden while a lead source is selected — daily snapshots are recorded across all lead sources.
        </p>
    @endunless
</div>
