{{--
    NX600 Lab — pet panel body (worklist + results tables).
    Rendered inside pet_lab_panel.blade.php and re-fetched by the Refresh control.
    Receives only $pet.
--}}
@php
    $nxWorklist = \Modules\NX600Lab\Entities\NxWorklist::where('vc_pet_id', $pet->id)
                    ->latest('id')->limit(25)->get();
    $nxSessions = \Modules\NX600Lab\Entities\NxTestSession::with('testResults')
                    ->where('vc_pet_id', $pet->id)
                    ->latest('test_date')->latest('test_time')->limit(25)->get();
    $nxTrends   = \Modules\NX600Lab\Entities\Services\NxLabTrendsService::forPet(
                    (int) $pet->id, (int) session('user.business_id')
                  );
    // Build a tiny inline SVG sparkline server-side so no extra JS deps are needed.
    $nxSpark = function (array $points, ?float $refLo, ?float $refHi) {
        $values = array_map(fn($p) => $p['value'], $points);
        if (count($values) < 2) return '';
        $tail = array_slice($values, -6);
        $abnTail = array_slice(array_map(fn($p) => $p['is_abnormal'], $points), -6);
        $min = min($tail); $max = max($tail);
        if ($refLo !== null) $min = min($min, $refLo);
        if ($refHi !== null) $max = max($max, $refHi);
        if ($max == $min) { $max = $min + 1; }
        $w = 86; $h = 24; $pad = 2;
        $sx = ($w - 2 * $pad) / max(1, count($tail) - 1);
        $sy = function ($v) use ($min, $max, $h, $pad) {
            return $h - $pad - (($v - $min) / ($max - $min)) * ($h - 2 * $pad);
        };
        $svg  = "<svg width=\"{$w}\" height=\"{$h}\" viewBox=\"0 0 {$w} {$h}\" style=\"vertical-align:middle;\">";
        // Reference band
        if ($refLo !== null && $refHi !== null) {
            $y1 = $sy($refHi); $y2 = $sy($refLo);
            $bh = max(0, $y2 - $y1);
            $svg .= "<rect x=\"0\" y=\"{$y1}\" width=\"{$w}\" height=\"{$bh}\" fill=\"#16a34a\" fill-opacity=\".10\" />";
        }
        // Polyline
        $pts = [];
        foreach ($tail as $i => $v) {
            $x = $pad + $i * $sx; $y = $sy($v);
            $pts[] = round($x, 1) . ',' . round($y, 1);
        }
        $svg .= "<polyline points=\"" . implode(' ', $pts) . "\" fill=\"none\" stroke=\"#2563eb\" stroke-width=\"1.5\" />";
        // Dots — red when abnormal
        foreach ($tail as $i => $v) {
            $x = $pad + $i * $sx; $y = $sy($v);
            $colour = !empty($abnTail[$i]) ? '#dc2626' : '#2563eb';
            $svg .= "<circle cx=\"" . round($x, 1) . "\" cy=\"" . round($y, 1) . "\" r=\"1.8\" fill=\"{$colour}\" />";
        }
        $svg .= '</svg>';
        return $svg;
    };
@endphp

<div class="row">
    <div class="col-md-12">
        <h5><strong>Lab Orders / Worklist</strong></h5>
        <table class="table table-bordered table-condensed">
            <thead>
                <tr>
                    <th>Sample No</th>
                    <th>Tests</th>
                    <th>Status</th>
                    <th>Created</th>
                </tr>
            </thead>
            <tbody>
                @forelse($nxWorklist as $w)
                    <tr>
                        <td><strong>{{ $w->sample_no }}</strong></td>
                        <td>{{ empty($w->test_names) ? 'Device default' : implode(', ', $w->test_names) }}</td>
                        <td>
                            @if($w->is_sent)
                                <span class="label label-default">Processed by device</span>
                            @else
                                <span class="label label-warning">Pending</span>
                            @endif
                        </td>
                        <td>{{ $w->created_at?->format('Y-m-d H:i') }}</td>
                    </tr>
                @empty
                    <tr><td colspan="4" class="text-center text-muted">No lab orders raised for this pet.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

@if(!empty($nxTrends['parameters']))
<div class="row">
    <div class="col-md-12">
        <h5 style="display:flex;align-items:baseline;justify-content:space-between;">
            <strong><i class="fa fa-chart-line"></i> Parameter Trends</strong>
            <a href="{{ route('nx.bridge.pet-trends', $pet->id) }}" target="_blank" style="font-size:12px;font-weight:600;">
                View full Lab Trends <i class="fa fa-arrow-right" style="font-size:10px;"></i>
            </a>
        </h5>
        <table class="table table-bordered table-condensed" style="margin-bottom:0;">
            <thead>
                <tr>
                    <th>Parameter</th>
                    <th>Reference</th>
                    <th style="width:100px;">Trend (last 6)</th>
                    <th style="text-align:right;">Latest</th>
                    <th>vs prev</th>
                </tr>
            </thead>
            <tbody>
                @foreach($nxTrends['parameters'] as $key => $p)
                    @php
                        $latestFmt = rtrim(rtrim(number_format($p['latest'], 3, '.', ''), '0'), '.');
                        $latestCls = $p['in_range'] === false ? 'text-danger' : ($p['in_range'] === true ? 'text-success' : '');
                        $dir = $p['direction'];
                        $arrow = $dir === 'up' ? '↑' : ($dir === 'down' ? '↓' : '·');
                        $arrowCls = $dir === 'up' ? 'text-danger' : ($dir === 'down' ? 'text-success' : 'text-muted');
                    @endphp
                    <tr>
                        <td><strong>{{ $p['name'] }}</strong>@if($p['unit'])&nbsp;<span class="text-muted" style="font-size:11px;">{{ $p['unit'] }}</span>@endif</td>
                        <td style="font-size:11px;color:#64748b;">
                            @if($p['ref_lower'] !== null || $p['ref_upper'] !== null)
                                {{ $p['ref_lower'] ?? '—' }} – {{ $p['ref_upper'] ?? '—' }}
                            @else — @endif
                        </td>
                        <td>{!! $nxSpark($p['points'], $p['ref_lower'], $p['ref_upper']) !!}</td>
                        <td style="text-align:right;font-variant-numeric:tabular-nums;" class="{{ $latestCls }}"><strong>{{ $latestFmt }}</strong></td>
                        <td>
                            @if($p['delta_prev'] !== null)
                                <span class="{{ $arrowCls }}" style="font-weight:700;">
                                    {{ $arrow }}
                                    {{ rtrim(rtrim(number_format(abs($p['delta_prev']), 3, '.', ''), '0'), '.') }}
                                </span>
                            @else — @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        <p class="text-muted" style="font-size:10.5px;margin:6px 0 14px;">
            Green band on the spark = reference range · red dots = abnormal readings.
        </p>
    </div>
</div>
@endif

<div class="row">
    <div class="col-md-12">
        <h5><strong>Lab Results</strong></h5>
        <table class="table table-bordered table-condensed">
            <thead>
                <tr>
                    <th>Sample No</th>
                    <th>Date / Time</th>
                    <th>Parameters</th>
                    <th>Outcome</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @forelse($nxSessions as $s)
                    @php $abn = $s->testResults->where('is_abnormal', true)->count(); @endphp
                    <tr>
                        <td><strong>{{ $s->sample_no }}</strong></td>
                        <td>{{ $s->test_date?->format('Y-m-d') }} {{ $s->test_time }}</td>
                        <td>{{ $s->testResults->count() }}</td>
                        <td>
                            @if($abn > 0)
                                <span class="label label-warning">{{ $abn }} abnormal</span>
                            @else
                                <span class="label label-success">All normal</span>
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('nx.results.show', $s->id) }}" target="_blank" class="btn btn-xs btn-primary">
                                <i class="fa fa-eye"></i> View
                            </a>
                            <a href="{{ route('nx.results.print', $s->id) }}" target="_blank" class="btn btn-xs btn-default">
                                <i class="fa fa-print"></i>
                            </a>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="5" class="text-center text-muted">No lab results yet for this pet.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>
