@extends('layouts.app')

@section('title', 'Lab Trends — ' . ($pet->petname ?? 'Pet'))

@section('content')
<section class="content-header">
    <h1>
        <i class="fas fa-chart-line"></i> Lab Trends
        <small style="color:#64748b;">{{ $pet->petname }}</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('vc.pets.index') }}">Pets</a></li>
        <li><a href="{{ route('vc.pets.show', $pet->id) }}">{{ $pet->petname }}</a></li>
        <li class="active">Lab Trends</li>
    </ol>
</section>

<section class="content">

@php
    $sessions   = $trends['sessions'] ?? [];
    $parameters = $trends['parameters'] ?? [];
@endphp

<style>
.lt-card { background:#fff; border:1px solid #e5e7eb; border-radius:10px; padding:16px 18px; margin-bottom:16px; }
.lt-card-hd { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#475569; margin-bottom:10px; }
.lt-pet-row { display:flex; gap:18px; align-items:center; }
.lt-pet-avatar { width:46px; height:46px; border-radius:50%; background:#dbeafe; color:#1e40af; display:flex; align-items:center; justify-content:center; font-size:22px; font-weight:800; }
.lt-pet-name { font-size:17px; font-weight:800; color:#0f172a; }
.lt-pet-sub { font-size:12px; color:#64748b; margin-top:2px; }
.lt-empty { text-align:center; padding:36px 18px; color:#94a3b8; }
.lt-empty .icon { display:block; font-size:34px; margin-bottom:8px; opacity:.55; }

/* Cumulative table */
.lt-cum-wrap { overflow-x:auto; }
.lt-cum { width:100%; border-collapse:separate; border-spacing:0; font-size:12px; }
.lt-cum thead th {
    background:#f8fafc; color:#475569; font-weight:700;
    font-size:10px; text-transform:uppercase; letter-spacing:.4px;
    padding:7px 10px; border-bottom:2px solid #e2e8f0; text-align:right; white-space:nowrap;
}
.lt-cum thead th.first { text-align:left; }
.lt-cum tbody td { padding:6px 10px; border-bottom:1px solid #f1f5f9; text-align:right; font-variant-numeric:tabular-nums; }
.lt-cum tbody td.first { text-align:left; font-weight:600; color:#0f172a; }
.lt-cum tbody td.first .unit { color:#94a3b8; font-weight:500; font-size:11px; margin-left:4px; }
.lt-cum .out { background:#fef2f2; color:#b91c1c; font-weight:700; }
.lt-cum .in  { color:#0f172a; }
.lt-cum .delta { font-size:11px; margin-left:4px; font-weight:700; }
.lt-cum .delta-up   { color:#dc2626; }
.lt-cum .delta-down { color:#16a34a; }
.lt-cum .delta-flat { color:#94a3b8; }

/* Chart grid */
.lt-chart-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:14px; }
.lt-chart-card { border:1px solid #e5e7eb; border-radius:10px; padding:12px 14px; background:#fff; }
.lt-chart-hd { display:flex; align-items:baseline; justify-content:space-between; gap:8px; margin-bottom:6px; }
.lt-chart-name { font-size:13px; font-weight:800; color:#0f172a; }
.lt-chart-unit { font-size:11px; color:#94a3b8; }
.lt-chart-latest { font-size:13px; font-weight:700; }
.lt-chart-latest.bad { color:#dc2626; }
.lt-chart-latest.ok  { color:#16a34a; }
.lt-chart-ref { font-size:10.5px; color:#64748b; margin-bottom:6px; }
.lt-chart-box { height:140px; position:relative; }
.lt-chart-empty { text-align:center; color:#94a3b8; font-size:11.5px; padding:38px 0; }
</style>

{{-- Pet header --}}
<div class="lt-card lt-pet-row">
    <div class="lt-pet-avatar">{{ strtoupper(substr($pet->petname ?? 'P', 0, 1)) }}</div>
    <div style="flex:1;">
        <div class="lt-pet-name">{{ $pet->petname }}</div>
        <div class="lt-pet-sub">
            {{ ucfirst($pet->species ?? '—') }}{{ $pet->breed ? ' · ' . $pet->breed : '' }}
            @if($pet->dob) · {{ \Carbon\Carbon::parse($pet->dob)->age }} yrs @endif
            @if(optional($pet->owner)->name) · Owner: <strong>{{ $pet->owner->name }}</strong> @endif
        </div>
    </div>
    <div style="font-size:12px;color:#64748b;">
        <strong>{{ count($sessions) }}</strong> {{ count($sessions) === 1 ? 'session' : 'sessions' }} ·
        <strong>{{ count($parameters) }}</strong> {{ count($parameters) === 1 ? 'parameter' : 'parameters' }}
    </div>
</div>

@if(empty($sessions))
    <div class="lt-card lt-empty">
        <span class="icon">📊</span>
        No lab results yet for this pet. Run a few test sessions on the NX600 first.
    </div>
@else

    {{-- ── Cumulative comparison ────────────────────────────── --}}
    <div class="lt-card">
        <div class="lt-card-hd"><i class="fa fa-table"></i> Cumulative Comparison</div>
        <div class="lt-cum-wrap">
            <table class="lt-cum">
                <thead>
                    <tr>
                        <th class="first">Parameter</th>
                        <th>Reference</th>
                        @foreach($sessions as $s)
                            <th title="Sample {{ $s['sample_no'] }}">{{ $s['date_label'] }}</th>
                        @endforeach
                        <th>Δ vs prev</th>
                        <th>Δ vs first</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($parameters as $key => $p)
                        @php
                            // Map values onto the session axis (null gaps)
                            $valBySession = [];
                            foreach ($p['points'] as $pt) { $valBySession[$pt['session_id']] = $pt; }
                        @endphp
                        <tr>
                            <td class="first">
                                {{ $p['name'] }}
                                @if($p['unit'])<span class="unit">{{ $p['unit'] }}</span>@endif
                            </td>
                            <td style="text-align:left;font-size:11px;color:#64748b;">
                                @if($p['ref_lower'] !== null || $p['ref_upper'] !== null)
                                    {{ $p['ref_lower'] ?? '—' }} – {{ $p['ref_upper'] ?? '—' }}
                                @else
                                    —
                                @endif
                            </td>
                            @foreach($sessions as $s)
                                @php $pt = $valBySession[$s['id']] ?? null; @endphp
                                <td class="{{ $pt && $pt['is_abnormal'] ? 'out' : 'in' }}">
                                    {{ $pt ? rtrim(rtrim(number_format($pt['value'], 3, '.', ''), '0'), '.') : '—' }}
                                </td>
                            @endforeach
                            <td>
                                @if($p['delta_prev'] !== null)
                                    <span class="delta delta-{{ $p['direction'] === 'up' ? 'up' : ($p['direction'] === 'down' ? 'down' : 'flat') }}">
                                        {{ $p['delta_prev'] > 0 ? '↑' : ($p['delta_prev'] < 0 ? '↓' : '·') }}
                                        {{ rtrim(rtrim(number_format(abs($p['delta_prev']), 3, '.', ''), '0'), '.') }}
                                    </span>
                                @else — @endif
                            </td>
                            <td>
                                @if($p['count'] >= 2)
                                    <span class="delta delta-{{ $p['delta_first'] > 0 ? 'up' : ($p['delta_first'] < 0 ? 'down' : 'flat') }}">
                                        {{ $p['delta_first'] > 0 ? '↑' : ($p['delta_first'] < 0 ? '↓' : '·') }}
                                        {{ rtrim(rtrim(number_format(abs($p['delta_first']), 3, '.', ''), '0'), '.') }}
                                    </span>
                                @else — @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>

    {{-- ── Per-parameter line charts ────────────────────────── --}}
    <div class="lt-card">
        <div class="lt-card-hd"><i class="fa fa-chart-line"></i> Per-Parameter Trends</div>
        <div class="lt-chart-grid">
            @foreach($parameters as $key => $p)
                @php
                    $latestClass = $p['in_range'] === false ? 'bad' : ($p['in_range'] === true ? 'ok' : '');
                    $canvasId    = 'lt_chart_' . preg_replace('/[^a-z0-9]/i', '_', $key);
                @endphp
                <div class="lt-chart-card">
                    <div class="lt-chart-hd">
                        <div>
                            <span class="lt-chart-name">{{ $p['name'] }}</span>
                            @if($p['unit'])<span class="lt-chart-unit">· {{ $p['unit'] }}</span>@endif
                        </div>
                        <span class="lt-chart-latest {{ $latestClass }}">
                            {{ rtrim(rtrim(number_format($p['latest'], 3, '.', ''), '0'), '.') }}
                        </span>
                    </div>
                    <div class="lt-chart-ref">
                        @if($p['ref_lower'] !== null || $p['ref_upper'] !== null)
                            Reference: {{ $p['ref_lower'] ?? '—' }} – {{ $p['ref_upper'] ?? '—' }}{{ $p['unit'] ? ' '.$p['unit'] : '' }}
                        @else
                            No reference range
                        @endif
                        · {{ $p['count'] }} {{ $p['count'] === 1 ? 'reading' : 'readings' }}
                    </div>
                    @if($p['count'] >= 2)
                        <div class="lt-chart-box"><canvas id="{{ $canvasId }}"></canvas></div>
                    @else
                        <div class="lt-chart-empty">
                            Only one reading — need a second to plot a trend.
                        </div>
                    @endif
                </div>
            @endforeach
        </div>
    </div>

    {{-- Inject the chart payload as JSON for the script to consume. --}}
    <script id="lt_payload" type="application/json">{!! json_encode($parameters, JSON_UNESCAPED_SLASHES) !!}</script>
    {{-- Chart.js is bundled into vendor.js but not exposed on window — load from CDN. --}}
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <script>
    window.addEventListener('load', function () {
        if (typeof Chart === 'undefined') {
            console.warn('Chart.js could not be loaded — trends charts skipped.');
            return;
        }
        var payload = JSON.parse(document.getElementById('lt_payload').textContent || '{}');
        Object.keys(payload).forEach(function (key) {
            var p = payload[key];
            if (!p || p.count < 2) return;
            var id = 'lt_chart_' + key.replace(/[^a-z0-9]/gi, '_');
            var el = document.getElementById(id);
            if (!el) return;
            var labels = p.points.map(function (pt) { return pt.date || ''; });
            var values = p.points.map(function (pt) { return pt.value; });
            var lo = p.ref_lower, hi = p.ref_upper;
            var datasets = [{
                label: p.name + (p.unit ? ' (' + p.unit + ')' : ''),
                data: values,
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37,99,235,.08)',
                borderWidth: 2,
                tension: 0.25,
                pointRadius: 4,
                pointBackgroundColor: p.points.map(function (pt) { return pt.is_abnormal ? '#dc2626' : '#2563eb'; }),
                pointBorderColor: '#fff',
                pointBorderWidth: 1.5,
                fill: false
            }];
            // Shade the reference band by drawing two flat invisible datasets that "fill" between.
            if (lo !== null && hi !== null) {
                datasets.push({
                    label: 'Upper ref', data: labels.map(function () { return hi; }),
                    borderColor: 'rgba(16,185,129,.25)', borderDash: [4, 4], borderWidth: 1,
                    pointRadius: 0, fill: '+1', backgroundColor: 'rgba(16,185,129,.10)'
                });
                datasets.push({
                    label: 'Lower ref', data: labels.map(function () { return lo; }),
                    borderColor: 'rgba(16,185,129,.25)', borderDash: [4, 4], borderWidth: 1,
                    pointRadius: 0, fill: false
                });
            }
            new Chart(el.getContext('2d'), {
                type: 'line',
                data: { labels: labels, datasets: datasets },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { display: false }, tooltip: { mode: 'index', intersect: false } },
                    scales: {
                        x: { ticks: { font: { size: 9 }, maxRotation: 0 }, grid: { display: false } },
                        y: { ticks: { font: { size: 9 } }, grid: { color: 'rgba(0,0,0,.04)' } }
                    }
                }
            });
        });
    });
    </script>

@endif

</section>
@endsection
