@extends('layouts.app')
@section('title', $patient->patient_name . ' — ' . __('clinicCore::lang.pet_profile'))

@section('css')
<style>
/* ── Hero ─────────────────────────────────────────────────── */
.pet-hero {
    border-radius:14px; padding:26px 28px 0; margin-bottom:20px;
    color:#fff; position:relative; overflow:hidden;
    box-shadow:0 8px 32px rgba(0,0,0,.22);
}
.hero-overlay {
    position:absolute; inset:0; border-radius:14px; pointer-events:none;
    background:
        radial-gradient(ellipse at 22% 38%, rgba(255,255,255,.22) 0%, transparent 52%),
        linear-gradient(170deg, rgba(255,255,255,.07) 0%, rgba(0,0,0,.3) 100%);
}
.hero-shimmer {
    position:absolute; top:0; left:0; right:0; height:1px; border-radius:14px 14px 0 0;
    background:linear-gradient(90deg, transparent 5%, rgba(255,255,255,.5) 50%, transparent 95%);
    pointer-events:none; z-index:1;
}
.hero-bg-icon {
    position:absolute; right:-18px; bottom:-24px;
    font-size:190px; opacity:.10; line-height:1;
    color:#fff; pointer-events:none; user-select:none;
}
.pet-hero-top { position:relative; display:flex; align-items:flex-start; gap:18px; }
.pet-avatar {
    width:100px; height:100px; border-radius:18px;
    border:3px solid rgba(255,255,255,.55);
    background:rgba(255,255,255,.18);
    display:flex; align-items:center; justify-content:center;
    font-size:40px; flex-shrink:0; overflow:hidden;
    box-shadow:0 4px 20px rgba(0,0,0,.3), 0 0 0 3px rgba(255,255,255,.15);
}
.pet-avatar img { width:100px; height:100px; object-fit:cover; }
.pet-hero-info { flex:1; min-width:0; }
.pet-hero-info h2 { margin:0 0 4px; font-size:22px; font-weight:800; display:flex; align-items:center; gap:8px; flex-wrap:wrap; text-shadow:0 1px 4px rgba(0,0,0,.2); }
.pet-hero-info .meta-line { font-size:13px; opacity:.9; margin:3px 0; }
.hero-stat-pills { display:flex; gap:7px; flex-wrap:wrap; margin-top:9px; }
.hero-pill {
    background:rgba(255,255,255,.17); border:1px solid rgba(255,255,255,.22);
    border-radius:20px; font-size:11px; font-weight:700; padding:4px 12px; letter-spacing:.3px;
    backdrop-filter:blur(4px);
}
.hero-pill.urgent { background:rgba(231,76,60,.55); border-color:rgba(255,100,80,.4); }
.hero-pill.warn   { background:rgba(243,156,18,.5);  border-color:rgba(255,180,0,.4); }
.pet-hero-actions { margin-left:auto; display:flex; flex-direction:column; gap:7px; align-items:flex-end; flex-shrink:0; position:relative; }
.hero-btn { display:inline-flex; align-items:center; gap:6px; padding:8px 16px; border-radius:8px; font-size:12px; font-weight:700; border:none; cursor:pointer; text-decoration:none; white-space:nowrap; transition:all .15s; line-height:1.2; }
.hero-btn:focus { outline:none; text-decoration:none; }
.hero-btn-appt  { background:#27ae60; color:#fff !important; box-shadow:0 3px 10px rgba(39,174,96,.5); }
.hero-btn-appt:hover  { background:#219a52; color:#fff !important; box-shadow:0 4px 14px rgba(39,174,96,.6); transform:translateY(-1px); }
.hero-btn-vax   { background:#2980b9; color:#fff !important; box-shadow:0 3px 10px rgba(41,128,185,.5); }
.hero-btn-vax:hover   { background:#2471a3; color:#fff !important; box-shadow:0 4px 14px rgba(41,128,185,.6); transform:translateY(-1px); }
.hero-btn-edit  { background:rgba(255,255,255,.15); color:#fff !important; border:1px solid rgba(255,255,255,.35); backdrop-filter:blur(4px); padding:6px 12px; font-size:11px; }
.hero-btn-edit:hover  { background:rgba(255,255,255,.28); color:#fff !important; }
.hero-btn-deceased { background:rgba(192,57,43,.2); color:#ffcdd2 !important; border:1px solid rgba(231,76,60,.35); padding:6px 12px; font-size:11px; }
.hero-btn-deceased:hover { background:rgba(192,57,43,.45); color:#fff !important; }
.hero-deceased-badge { display:inline-flex; align-items:center; gap:6px; padding:7px 14px; background:rgba(231,76,60,.3); border:1px solid rgba(231,76,60,.4); border-radius:8px; font-size:12px; font-weight:700; color:#ffcdd2; }
.hero-status-bar {
    position:relative; margin:18px -28px 0; padding:10px 28px;
    background:rgba(0,0,0,.2); border-radius:0 0 14px 14px;
    display:flex; gap:16px; flex-wrap:wrap; align-items:center;
    border-top:1px solid rgba(255,255,255,.1);
}
.hero-chip { font-size:11px; font-weight:600; opacity:.85; display:flex; align-items:center; gap:5px; }
.hero-chip i { opacity:.7; }

/* ── Sidebar cards ────────────────────────────────────────── */
.vc-card { background:#fff; border-radius:8px; box-shadow:0 1px 4px rgba(0,0,0,.08); margin-bottom:14px; overflow:hidden; }
.vc-card-header { padding:9px 14px; border-bottom:1px solid #f3f3f3; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#888; display:flex; align-items:center; gap:6px; }
.vc-card-body { padding:10px 14px; }
.detail-row { display:flex; justify-content:space-between; align-items:center; padding:5px 0; border-bottom:1px solid #f8f8f8; font-size:12px; }
.detail-row:last-child { border-bottom:none; }
.detail-row .dk { font-weight:600; color:#555; display:flex; align-items:center; gap:5px; }
.detail-row .dv { color:#333; text-align:right; max-width:58%; }

/* ── Tabs ─────────────────────────────────────────────────── */
.nav-tabs > li > a { font-size:13px; padding:8px 14px; }

/* ── Overview ─────────────────────────────────────────────── */
.ov-stat-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:16px; }
.ov-stat { background:#f8fafc; border-radius:8px; padding:12px 10px; text-align:center; border:1px solid #e8ecf0; }
.ov-stat .num { font-size:26px; font-weight:800; line-height:1; }
.ov-stat .lbl { font-size:10px; text-transform:uppercase; letter-spacing:.4px; color:#94a3b8; margin-top:4px; }

/* ── Weight history ───────────────────────────────────────── */
.wh-entry { display:flex; align-items:center; gap:0; border-bottom:1px solid #f0f0f0; transition:background .12s; }
.wh-entry:last-child { border-bottom:none; }
.wh-entry:hover { background:#f8fafc; }
.wh-weight-col { width:88px; flex-shrink:0; display:flex; flex-direction:column; align-items:flex-start; gap:3px; padding:9px 0 9px 14px; }
.wh-num-row { display:flex; align-items:baseline; gap:3px; }
.wh-num { font-size:17px; font-weight:800; color:#1e293b; line-height:1; }
.wh-unit { font-size:11px; color:#94a3b8; font-weight:600; }
.wh-trend { display:inline-flex; align-items:center; gap:3px; font-size:10px; font-weight:700; padding:2px 6px; border-radius:8px; white-space:nowrap; line-height:1.4; }
.wh-trend.up   { color:#e74c3c; background:#fdf2f2; border:1px solid #fecaca; }
.wh-trend.down { color:#27ae60; background:#f0faf4; border:1px solid #bbf7d0; }
.wh-trend.same { color:#94a3b8; background:#f8fafc; border:1px solid #e2e8f0; }
.wh-source-col { flex:1; padding:10px 8px; min-width:0; }
.wh-type-pill { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:700; padding:2px 7px; border-radius:10px; margin-bottom:3px; }
.wh-type-pill.appt { background:#e8f4fd; color:#2980b9; }
.wh-type-pill.vax  { background:#eafaf1; color:#27ae60; }
.wh-label { font-size:12px; color:#2980b9; text-decoration:none; display:flex; align-items:center; gap:4px; }
.wh-label:hover { text-decoration:underline; color:#1a5f8a; }
.wh-label.no-link { color:#555; }
.wh-date-col { text-align:right; padding:10px 14px 10px 0; flex-shrink:0; }
.wh-date-abs { font-size:11px; font-weight:600; color:#555; }
.wh-date-rel { font-size:10px; color:#aaa; margin-top:1px; }

/* ── Treatment passport cards ───────────────────────────── */
.vax-filter-bar { display:flex; gap:7px; flex-wrap:wrap; margin-bottom:12px; }
.vax-chip { font-size:11px; font-weight:700; padding:4px 12px; border-radius:20px; cursor:pointer; border:2px solid transparent; transition:all .15s; background:transparent; }

.vax-pcard { display:flex; background:#fff; border-radius:8px; border:1px solid #eee; margin-bottom:8px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,.05); transition:box-shadow .15s; }
.vax-pcard:hover { box-shadow:0 2px 8px rgba(0,0,0,.1); }
.vpc-stripe { width:5px; flex-shrink:0; }
.vpc-icon { width:38px; display:flex; align-items:flex-start; justify-content:center; padding:13px 0; color:#ccc; font-size:13px; }
.vpc-body { flex:1; padding:10px 10px 10px 0; min-width:0; }
.vpc-top { display:flex; align-items:center; gap:8px; margin-bottom:4px; flex-wrap:wrap; min-width:0; }
.vpc-name { font-size:13px; font-weight:700; color:#1e293b; }
.vpc-cat-chip { font-size:10px; padding:2px 7px; border-radius:10px; font-weight:600; background:#e8f4fd; color:#2980b9; white-space:nowrap; }
.vpc-due-badge { margin-left:auto; font-size:11px; font-weight:700; padding:3px 10px; border-radius:12px; color:#fff; white-space:nowrap; flex-shrink:0; }
.vpc-sub { font-size:11px; color:#64748b; display:flex; gap:12px; flex-wrap:wrap; }
.vpc-sub i { color:#bbb; }
.vpc-meta { font-size:11px; color:#aaa; margin-top:3px; display:flex; gap:10px; flex-wrap:wrap; }
.vpc-actions { display:flex; flex-direction:column; align-items:center; justify-content:center; padding:8px 10px; gap:5px; flex-shrink:0; }
.vpc-edit-btn { width:26px; height:26px; border-radius:5px; background:#3498db; color:#fff; border:none; font-size:11px; display:flex; align-items:center; justify-content:center; cursor:pointer; transition:all .15s; padding:0; }
.vpc-edit-btn:hover { background:#1d6fa4; }
.vpc-del-btn  { width:26px; height:26px; border-radius:5px; background:transparent; border:1.5px solid #e74c3c; color:#e74c3c; font-size:11px; display:flex; align-items:center; justify-content:center; cursor:pointer; transition:all .15s; padding:0; }
.vpc-del-btn:hover  { background:#e74c3c; color:#fff; }

/* ── Condition cards ──────────────────────────────────────── */
.cond-card { display:flex; align-items:center; gap:10px; background:#fff; border-radius:8px; border:1px solid #eee; border-left:4px solid #cbd5e1; padding:9px 12px; margin-bottom:8px; }
.cond-card.active  { border-left-color:#e74c3c; }
.cond-card.chronic { border-left-color:#f39c12; }
.cond-card.resolved { border-left-color:#27ae60; }
.cond-name { font-weight:700; font-size:13px; color:#1e293b; }
.cond-meta { font-size:11px; color:#94a3b8; margin-top:2px; display:flex; gap:8px; flex-wrap:wrap; }

/* ── Appointment type colors ──────────────────────────────── */

/* ── Tab filter bars ──────────────────────────────────────── */
.tab-toolbar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-bottom:14px; }
.tc-chip { font-size:11px; font-weight:700; padding:3px 11px; border-radius:20px; cursor:pointer; border:1.5px solid currentColor; background:transparent; transition:all .14s; white-space:nowrap; line-height:1.5; }
.tc-chip.tc-active { color:#fff !important; }
.tab-vtbtn { width:28px; height:28px; border:1.5px solid #e2e8f0; border-radius:6px; background:#fff; display:flex; align-items:center; justify-content:center; cursor:pointer; color:#94a3b8; font-size:11px; transition:all .13s; padding:0; }
.tab-vtbtn.active { background:#2980b9; border-color:#2980b9; color:#fff; }
.tab-vtbtn-wrap { display:flex; gap:3px; margin-left:auto; }

/* ── Appointment cards ────────────────────────────────────── */
.apt-card { display:flex; background:#fff; border-radius:8px; border:1px solid #eee; margin-bottom:8px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,.05); transition:box-shadow .15s; }
.apt-card:hover { box-shadow:0 2px 8px rgba(0,0,0,.1); }
.apt-stripe { width:5px; flex-shrink:0; }
.apt-body { flex:1; padding:10px 12px; min-width:0; }
.apt-top { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:4px; }
.apt-ref { font-size:12px; font-weight:700; color:#2980b9; text-decoration:none; }
.apt-ref:hover { text-decoration:underline; }
.apt-sub { font-size:11px; color:#64748b; display:flex; gap:12px; flex-wrap:wrap; }
.apt-sub i { color:#bbb; }
.apt-actions { display:flex; align-items:center; justify-content:center; padding:8px 10px; flex-shrink:0; }

/* ── Prescription cards ───────────────────────────────────── */
.rx-card { display:flex; background:#fff; border-radius:8px; border:1px solid #eee; margin-bottom:8px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,.05); transition:box-shadow .15s; }
.rx-card:hover { box-shadow:0 2px 8px rgba(0,0,0,.1); }
.rx-stripe { width:5px; flex-shrink:0; }
.rx-body { flex:1; padding:10px 12px; min-width:0; }
.rx-top { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:4px; }
.rx-ref { font-size:12px; font-weight:700; color:#8e44ad; text-decoration:none; }
.rx-ref:hover { text-decoration:underline; }
.rx-sub { font-size:11px; color:#64748b; display:flex; gap:12px; flex-wrap:wrap; }
.rx-sub i { color:#bbb; }
.rx-actions { display:flex; align-items:center; justify-content:center; padding:8px 10px; flex-shrink:0; gap:4px; }

/* ── Print-only elements (hidden on screen) ──────────────── */
.print-only { display: none; }

/* ──────────── PRINT STYLESHEET (item 5.1) ────────────────
   When the doctor hits Print from the Clinical History tab,
   strip the app chrome and any non-finalised appointments
   ("pending actions"), force every collapsed panel open, and
   present a clean, ink-friendly clinical history with a
   printed header identifying the patient and clinic.
*/
@media print {
    /* Reveal the print-only header and hide every other major
       UI region. The .printable-clinical container itself stays
       visible; everything above/beside/below it goes away. */
    .print-only { display: block !important; }

    body, html { background: #fff !important; }

    /* Hide app-wide chrome - layout-defined elements that
       shouldn't appear on paper. */
    .main-header, .main-sidebar, .control-sidebar,
    .left-side, .navbar, .breadcrumb, .content-header > .breadcrumb,
    footer, .main-footer, #header-mobile,
    .pet-hero, .hero-overlay, .hero-shimmer, .hero-bg-icon,
    .nav-tabs,
    /* Hide other tabs - we ONLY print clinical history. */
    .tab-pane:not(#tab-clinical),
    /* Hide the in-page toolbar (Expand/Collapse/Print buttons)
       and any per-appointment action buttons (eye/full link). */
    #tab-clinical .tab-toolbar,
    .clinical-apt-panel .panel-heading a.btn,
    /* Hide the toggle chevron - everything is forced open. */
    .clinical-apt-toggle .toggle-icon,
    /* And per task 5.1 explicitly: hide non-finalised
       appointments (pending / confirmed / waiting / in_progress). */
    .clinical-apt-panel.print-hidden {
        display: none !important;
    }

    /* Force the clinical tab visible regardless of which tab
       the user was on when they hit Print. Bootstrap 3's
       .tab-pane defaults to display:none until activated. */
    #tab-clinical {
        display: block !important;
        opacity: 1 !important;
        visibility: visible !important;
    }
    #tab-clinical.fade { opacity: 1 !important; }

    /* Force every appointment body open so the print captures
       the full record, not just the first 3 the user saw. */
    .clinical-apt-body { display: block !important; }
    .clinical-apt-toggle { cursor: default !important; }

    /* Page margin, base typography, no page-breaks inside a visit. */
    @page { margin: 12mm 14mm; }
    body { font-size: 11pt; color: #000; }
    .clinical-apt-panel {
        page-break-inside: avoid;
        border: 1px solid #888 !important;
        border-left: 4px solid #444 !important;
        background: #fff !important;
        margin-bottom: 8mm !important;
    }
    .panel-heading {
        background: #f5f5f5 !important;
        border-bottom: 1px solid #ccc !important;
    }
    /* Don't waste ink on coloured boxes around vitals/SOAP. */
    .clinical-apt-body [style*="background:#f0fdf4"],
    .clinical-apt-body [style*="background:#f8fafc"],
    .clinical-apt-body [style*="background:#fef2f2"] {
        background: #fff !important;
        border: 1px solid #ccc !important;
    }

    /* Print header layout */
    .print-header {
        border-bottom: 2px solid #000;
        padding-bottom: 6mm;
        margin-bottom: 6mm;
    }
    .print-header .ph-title {
        font-size: 18pt; font-weight: 800; margin-bottom: 4mm;
        text-transform: uppercase; letter-spacing: .5pt;
    }
    .print-header .ph-grid {
        display: grid; grid-template-columns: 1fr 1fr;
        gap: 2mm 8mm; font-size: 10.5pt;
    }

    /* Anchor links shouldn't show their URL in print. */
    a[href]:after { content: ""; }
}
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
@php
/* Skin Type theming */
$sp = strtolower($patient->species ?? '');
$heroGradient = match(true) {
    str_contains($sp,'dog')  || str_contains($sp,'canine')  => 'linear-gradient(135deg,#1a237e 0%,#1565c0 50%,#1e88e5 100%)',
    str_contains($sp,'cat')  || str_contains($sp,'feline')  => 'linear-gradient(135deg,#4a0072 0%,#7b1fa2 50%,#ab47bc 100%)',
    str_contains($sp,'bird') || str_contains($sp,'avian')   => 'linear-gradient(135deg,#004d40 0%,#00796b 50%,#26a69a 100%)',
    str_contains($sp,'rabbit')                              => 'linear-gradient(135deg,#880e4f 0%,#c2185b 50%,#ec407a 100%)',
    str_contains($sp,'fish')                                => 'linear-gradient(135deg,#006064 0%,#0288d1 50%,#29b6f6 100%)',
    str_contains($sp,'reptile')||str_contains($sp,'snake')  => 'linear-gradient(135deg,#1b5e20 0%,#388e3c 50%,#66bb6a 100%)',
    str_contains($sp,'horse')                               => 'linear-gradient(135deg,#3e2723 0%,#6d4c41 50%,#a1887f 100%)',
    default                                                 => 'linear-gradient(135deg,#1a237e 0%,#3949ab 50%,#7986cb 100%)',
};
$speciesIcon = match(true) {
    str_contains($sp,'dog')  || str_contains($sp,'canine') => 'fa-dog',
    str_contains($sp,'cat')  || str_contains($sp,'feline') => 'fa-cat',
    str_contains($sp,'bird') || str_contains($sp,'parrot') => 'fa-dove',
    str_contains($sp,'fish')                               => 'fa-fish',
    default => 'fa-notes-medical',
};
$ownerName   = trim(optional($patient->owner)->name ?? '') ?: (optional($patient->owner)->supplier_business_name ?? '—');
$ownerMobile = optional($patient->owner)->mobile ?? '';

/* Treatment stats */
$reminderDays = (int) config('cliniccore.reminder_days', 30);
$vaxOverdue  = $patient->vaccinations->filter(fn($v) => $v->due_status === 'overdue')->count();
$vaxDueSoon  = $patient->vaccinations->filter(fn($v) => $v->due_status === 'due_soon')->count();
$vaxUpcoming = $patient->vaccinations->filter(fn($v) => $v->due_status === 'upcoming')->count();
$activeConditions = $patient->conditions->where('status','active')->count();

/* Type/status display maps */
$aptTypeColors   = ['checkup'=>'#2980b9','vaccination'=>'#27ae60','surgery'=>'#c0392b','grooming'=>'#8e44ad','emergency'=>'#e67e22','other'=>'#7f8c8d'];
$aptStatusColors = ['pending'=>'warning','waiting'=>'warning','confirmed'=>'info','in_progress'=>'primary','completed'=>'success','cancelled'=>'danger','no_show'=>'default'];
$catLabels       = ['core_vaccine'=>'Core','non_core_vaccine'=>'Non-Core','deworming'=>'Dewormer','spot_on'=>'Spot-on','preventive'=>'Preventive','other'=>'Other'];
$patientShowTimeFormat = session('business.time_format', 24) == 12 ? 'h:i A' : 'H:i';
@endphp

<section class="content-header">
    <h1><i class="fas fa-notes-medical"></i> {{ $patient->patient_name }}
        @if(config('cliniccore.show_animal_fields', false))
        <small>{{ $patient->species }}{{ $patient->breed ? ' · '.$patient->breed : '' }}</small>
        @endif
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('clinic.patients.index') }}">@lang('clinicCore::lang.pets')</a></li>
        <li class="active">{{ $patient->patient_name }}</li>
    </ol>
</section>

<section class="content">

{{-- SIFA P3-T8 — shared patient medical-alert banner (reusable partial). --}}
@include('clinicCore::partials.patient_alert_banner', ['patientId' => $patient->id, 'activeAlerts' => $activeAlerts ?? null])

@if($patient->deceased)
<div class="alert alert-danger" style="border-radius:8px;border-left:5px solid #c0392b;padding:10px 16px;display:flex;align-items:center;gap:10px;margin-bottom:16px;">
    <i class="fas fa-heart-broken" style="font-size:18px;"></i>
    <div>
        <strong>{{ $patient->patient_name }} has passed away.</strong>
        @if($patient->deceased_date) &nbsp;Date of death: {{ \Carbon\Carbon::parse($patient->deceased_date)->format('d-m-Y') }}. @endif
        &nbsp;All records are preserved in read-only mode.
    </div>
</div>
@endif

{{-- ─────────── HERO ─────────── --}}
<div class="pet-hero" style="background:{{ $heroGradient }};">
    <div class="hero-overlay"></div>
    <div class="hero-shimmer"></div>
    <div class="hero-bg-icon"><i class="fas {{ $speciesIcon }}"></i></div>
    <div class="pet-hero-top">

        <div class="pet-avatar">
            @if($patient->photo_url)
                <img src="{{ $patient->photo_url }}" alt="{{ $patient->patient_name }}">
            @else
                <i class="fas {{ $speciesIcon }}"></i>
            @endif
        </div>

        <div class="pet-hero-info">
            <h2>
                {{ $patient->patient_name }}
                @if($patient->deceased)
                    <span class="label label-danger" style="font-size:11px;">Deceased</span>
                @endif
                <span class="label label-{{ $patient->status === 'active' ? 'success' : 'warning' }}" style="font-size:11px;">
                    {{ ucfirst($patient->status) }}
                </span>
            </h2>
            <div class="meta-line">
                <i class="fas {{ $speciesIcon }}" style="opacity:.7;"></i>
                @if(config('cliniccore.show_animal_fields', false))
                {{ $patient->species }}{{ $patient->breed ? ' · '.$patient->breed : '' }}
                @if($patient->gender) &nbsp;·&nbsp; {{ ucfirst($patient->gender) }} @endif
                @else
                @if($patient->gender) {{ ucfirst($patient->gender) }} @endif
                @endif
                @if($patient->dob) &nbsp;·&nbsp; {{ $patient->age }} yr{{ $patient->age != 1 ? 's' : '' }}
                    <small style="opacity:.75;">({{ $patient->dob->format('d-m-Y') }})</small>
                @endif
            </div>
            <div class="meta-line">
                <i class="fas fa-user" style="opacity:.7;"></i>
                <strong>{{ $ownerName }}</strong>
                @if($ownerMobile) &nbsp;·&nbsp; {{ $ownerMobile }} @endif
            </div>
            <div class="hero-stat-pills">
                <span class="hero-pill"><i class="fas fa-calendar"></i> {{ $patient->appointments->count() }} Visits</span>
                <span class="hero-pill"><i class="fas fa-syringe"></i> {{ $patient->vaccinations->count() }} Vaccinations</span>
                <span class="hero-pill"><i class="fas fa-disease"></i> {{ $patient->conditions->count() }} Conditions</span>
                <span class="hero-pill"><i class="fas fa-prescription-bottle-alt"></i> {{ $patient->prescriptions->count() }}</span>
                @if($vaxOverdue > 0)
                    <span class="hero-pill urgent"><i class="fas fa-exclamation-triangle"></i> {{ $vaxOverdue }} Overdue Treatment{{ $vaxOverdue > 1 ? 's' : '' }}</span>
                @elseif($vaxDueSoon > 0)
                    <span class="hero-pill warn"><i class="fas fa-clock"></i> {{ $vaxDueSoon }} Due Soon</span>
                @endif
            </div>
        </div>

        <div class="pet-hero-actions">
            @if(!$patient->deceased)
                @can('clinic.manage_appointments')
                <a href="{{ route('clinic.appointments.create') }}?patient_id={{ $patient->id }}&contact_id={{ $patient->contact_id }}"
                   class="hero-btn hero-btn-appt">
                    <i class="fas fa-calendar-plus"></i> New Appointment
                </a>
                @endcan
                @can('clinic.manage_vaccinations')
                <button class="hero-btn hero-btn-vax" data-toggle="modal" data-target="#addTreatmentModal">
                    <i class="fas fa-syringe"></i> Record Treatment
                </button>
                @endcan
                <div style="display:flex;gap:6px;">
                    @if(\Modules\ClinicCore\Http\Controllers\ClcAiController::available() && \Modules\ClinicCore\Entities\Services\ClinicCapabilities::businessHas((int)session('user.business_id'), 'ai_assist'))
                    @can('clinic.use_ai_assist')
                    <button type="button" class="hero-btn hero-btn-edit clc-ai-btn" data-mode="summarize_history" data-patient="{{ $patient->id }}" style="background:#0ea5e9;">
                        <i class="fa fa-robot"></i> AI Summary
                    </button>
                    @endcan
                    @endif
                    @can('clinic.manage_pets')
                    <a href="{{ route('clinic.patients.edit', $patient->id) }}" class="hero-btn hero-btn-edit">
                        <i class="fa fa-pencil-alt"></i> Edit
                    </a>
                    <button class="hero-btn hero-btn-deceased" data-toggle="modal" data-target="#deceasedModal" title="Record that this patient has died">
                        <i class="fas fa-heart-broken"></i> Record Death
                    </button>
                    @endcan
                </div>
            @else
                <span class="hero-deceased-badge">
                    <i class="fas fa-heart-broken"></i> Deceased
                </span>
                @can('clinic.manage_pets')
                <a href="{{ route('clinic.patients.edit', $patient->id) }}" class="hero-btn hero-btn-edit">
                    <i class="fa fa-pencil-alt"></i> Edit
                </a>
                @endcan
            @endif
        </div>

    </div>
    <div class="hero-status-bar">
        @if($patient->default_specialty_id && $patient->defaultSpecialty)
        <span class="hero-chip"><i class="fas {{ $patient->defaultSpecialty->icon ?: 'fa-stethoscope' }}"></i> {{ $patient->defaultSpecialty->name }}</span>
        <span style="opacity:.25;font-size:14px;">|</span>
        @endif
        @if($patient->allergies)
        <span class="hero-chip" style="background:rgba(245,158,11,.18);"><i class="fas fa-exclamation-triangle"></i> Allergies</span>
        @endif
        <span class="hero-chip" style="margin-left:auto;opacity:.6;font-size:11px;">ID #{{ $patient->id }}</span>
    </div>
</div>

{{-- ─────────── BODY ─────────── --}}
<div class="row">

    {{-- LEFT SIDEBAR --}}
    <div class="col-md-3">

        <div class="vc-card">
            <div class="vc-card-header"><i class="fa fa-info-circle"></i> Details</div>
            <div class="vc-card-body" style="padding:6px 14px;">
                @if($patient->dob)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-birthday-cake fa-fw"></i> DOB</span>
                    <span class="dv">{{ $patient->dob->format('d-m-Y') }}</span>
                </div>
                @endif
                @if($patient->color)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-palette fa-fw"></i> Color</span>
                    <span class="dv">{{ $patient->color }}</span>
                </div>
                @endif
                @if($patient->bloodgroup)
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-tint fa-fw"></i> Blood Group</span>
                    <span class="dv">{{ $patient->bloodgroup }}</span>
                </div>
                @endif
                {{-- ── P3-T1 Identity master fields ─────────────────────── --}}
                @if($patient->preferred_name)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-user-tag fa-fw"></i> @lang('clinicCore::lang.preferred_name')</span>
                    <span class="dv">{{ $patient->preferred_name }}</span>
                </div>
                @endif
                @if($patient->national_id)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-id-card fa-fw"></i> @lang('clinicCore::lang.national_id')</span>
                    <span class="dv" style="font-size:11px;">{{ $patient->national_id }}</span>
                </div>
                @endif
                @if($patient->passport_number)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-passport fa-fw"></i> @lang('clinicCore::lang.passport_number')</span>
                    <span class="dv" style="font-size:11px;">{{ $patient->passport_number }}</span>
                </div>
                @endif
                @if($patient->marital_status)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-ring fa-fw"></i> @lang('clinicCore::lang.marital_status')</span>
                    <span class="dv">@lang('clinicCore::lang.marital_' . $patient->marital_status)</span>
                </div>
                @endif
                @if($patient->nationality)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-flag fa-fw"></i> @lang('clinicCore::lang.nationality')</span>
                    <span class="dv">{{ $patient->nationality }}</span>
                </div>
                @endif
                @if($patient->primary_language)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-language fa-fw"></i> @lang('clinicCore::lang.primary_language')</span>
                    <span class="dv">{{ $patient->primary_language }}</span>
                </div>
                @endif
                @if($patient->gender_identity)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-venus-mars fa-fw"></i> @lang('clinicCore::lang.gender_identity')</span>
                    <span class="dv">{{ $patient->gender_identity }}</span>
                </div>
                @endif
                @if($patient->registered_location_id && $patient->registeredLocation)
                <div class="detail-row">
                    <span class="dk"><i class="fa fa-map-marker-alt fa-fw"></i> @lang('clinicCore::lang.registered_location')</span>
                    <span class="dv">{{ $patient->registeredLocation->name }}</span>
                </div>
                @endif
                @if(config('cliniccore.show_animal_fields', false) && $patient->microchip_no)
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-microchip fa-fw"></i> File No.</span>
                    <span class="dv" style="font-size:11px;word-break:break-all;">{{ $patient->microchip_no }}</span>
                </div>
                @endif
                @if($patient->serial_no)
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-barcode fa-fw"></i> Serial No.</span>
                    <span class="dv" style="font-size:11px;">{{ $patient->serial_no }}</span>
                </div>
                @endif
                @php $clcShowDriver = optional($patient->defaultSpecialty)->driver(); @endphp
                @if($clcShowDriver && $clcShowDriver->patientShowFragment())
                    @includeIf($clcShowDriver->patientShowFragment(), ['patient' => $patient])
                @endif
                @if($patient->allergies)
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-exclamation-triangle fa-fw text-warning"></i> Allergies</span>
                    <span class="dv" style="font-size:11px;">{{ $patient->allergies }}</span>
                </div>
                @endif
                @if(isset($lastWeightRecord))
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-weight fa-fw"></i> Last Weight</span>
                    <span class="dv">
                        <strong>{{ $lastWeightRecord['weight'] }} kg</strong><br>
                        <small class="text-muted" style="font-size:10px;">
                            @if($lastWeightRecord['url'])
                                <a href="{{ $lastWeightRecord['url'] }}">{{ $lastWeightRecord['label'] }}</a>
                            @else
                                {{ $lastWeightRecord['label'] }}
                            @endif
                        </small>
                    </span>
                </div>
                @endif
                {{-- SIFA P5-T1 — cumulative radiation dose (sum of recorded DAP/DLP/CTDIvol). --}}
                @php
                    $imgDose = $imagingDose ?? ['dap'=>null,'dlp'=>null,'ctdivol'=>null];
                    $imgDoseParts = [];
                    if (!is_null($imgDose['dap']))     $imgDoseParts[] = 'DAP '.number_format($imgDose['dap'], 2).' Gy·cm²';
                    if (!is_null($imgDose['dlp']))     $imgDoseParts[] = 'DLP '.number_format($imgDose['dlp'], 2).' mGy·cm';
                    if (!is_null($imgDose['ctdivol'])) $imgDoseParts[] = 'CTDIvol '.number_format($imgDose['ctdivol'], 2).' mGy';
                @endphp
                @if(count($imgDoseParts))
                <div class="detail-row">
                    <span class="dk"><i class="fas fa-radiation fa-fw"></i> {{ __('clinicCore::lang.imgrep_cumulative_dose') }}</span>
                    <span class="dv" style="font-size:11px;">{{ implode(' · ', $imgDoseParts) }}</span>
                </div>
                @endif
            </div>
        </div>

        {{-- Item #2 - Preferred Doctor for this patient, with inline change UI.
             Falls back to the owner-level preferred doctor when the patient
             itself doesn't have one set (shows it as inherited so the
             doctor knows where the value is coming from). --}}
        @php
            $patientPrefDoctor       = $patient->preferredDoctor;
            $inheritedPrefDoctor = !$patientPrefDoctor ? optional($patient->ownerDetail)->preferredDoctor : null;
        @endphp
        <div class="vc-card" id="clc_pref_doctor_card">
            <div class="vc-card-header">
                <i class="fa fa-user-md" style="color:#6366f1;"></i> Preferred Doctor
            </div>
            <div class="vc-card-body" style="padding:10px 14px;">
                <div id="clc_pref_doctor_current" style="font-size:13px;color:#334155;margin-bottom:8px;">
                    @if($patientPrefDoctor)
                        <strong>{{ $patientPrefDoctor->name }}</strong>
                        @if($patientPrefDoctor->specialization)
                            <small class="text-muted">· {{ $patientPrefDoctor->specialization }}</small>
                        @endif
                    @elseif($inheritedPrefDoctor)
                        <strong>{{ $inheritedPrefDoctor->name }}</strong>
                        <small class="text-muted" style="display:block;font-style:italic;margin-top:2px;">
                            <i class="fa fa-link"></i> Inherited from contact
                        </small>
                    @else
                        <span class="text-muted" style="font-style:italic;">No preferred doctor set</span>
                    @endif
                </div>
                @can('clinic.manage_pets')
                <div style="display:flex;gap:6px;align-items:center;">
                    <select id="clc_pref_doctor_select" class="form-control input-sm" style="flex:1;">
                        <option value="">— None (use contact default) —</option>
                        @foreach($doctorsList as $doc)
                            <option value="{{ $doc->id }}" {{ $patient->preferred_doctor_id == $doc->id ? 'selected' : '' }}>
                                {{ $doc->name }}{{ $doc->specialization ? ' — ' . $doc->specialization : '' }}
                            </option>
                        @endforeach
                    </select>
                    <button id="clc_pref_doctor_save" type="button" class="btn btn-sm btn-primary">
                        <i class="fa fa-save"></i>
                    </button>
                </div>
                <script>
                // This block lives in the content section (before jQuery loads at
                // page bottom), so defer until jQuery is available.
                (function initPrefDoctor(){
                    if (typeof window.jQuery === 'undefined') { return setTimeout(initPrefDoctor, 50); }
                    jQuery(function ($) {
                    $('#clc_pref_doctor_save').on('click', function () {
                        var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
                        $.post('{{ route('clinic.patients.set-preferred-doctor', $patient->id) }}', {
                            _token: '{{ csrf_token() }}',
                            preferred_doctor_id: $('#clc_pref_doctor_select').val() || ''
                        }).done(function (res) {
                            if (res.success) {
                                toastr.success('Preferred doctor updated.');
                                if (res.preferred_doctor) {
                                    $('#clc_pref_doctor_current').html('<strong>' + $('<i>').text(res.preferred_doctor).html() + '</strong>');
                                } else {
                                    $('#clc_pref_doctor_current').html('<span class="text-muted" style="font-style:italic;">No patient-specific preferred doctor (will inherit from contact)</span>');
                                }
                            }
                        }).fail(function () {
                            toastr.error('Could not save preferred doctor.');
                        }).always(function () {
                            $btn.prop('disabled', false).html('<i class="fa fa-save"></i>');
                        });
                    });
                    });
                })();
                </script>
                @endcan
            </div>
        </div>

        <div class="vc-card">
            <div class="vc-card-header"><i class="fa fa-user"></i> @lang('clinicCore::lang.pet_owner')</div>
            <div class="vc-card-body">
                <div style="font-weight:700;font-size:13px;color:#1e293b;margin-bottom:5px;">{{ $ownerName }}</div>
                @if($ownerMobile)
                <div style="font-size:12px;color:#555;margin-bottom:3px;"><i class="fa fa-phone fa-fw text-muted"></i> {{ $ownerMobile }}</div>
                @endif
                @if(optional($patient->owner)->email)
                <div style="font-size:12px;color:#555;margin-bottom:3px;"><i class="fa fa-envelope fa-fw text-muted"></i> {{ $patient->owner->email }}</div>
                @endif
                @php
                    $ownerDetailId = \Modules\ClinicCore\Entities\ClcPatientContactDetail::where('contact_id', $patient->contact_id)->value('id');
                @endphp
                @if($ownerDetailId)
                <a href="{{ route('clinic.patient-contacts.show', $ownerDetailId) }}"
                   class="btn btn-xs btn-default btn-block" style="margin-top:8px;">
                    <i class="fa fa-external-link-alt"></i> View Contact Profile
                </a>
                @endif
            </div>
        </div>

        @if(!$patient->deceased)
        <div class="vc-card">
            <div class="vc-card-header"><i class="fa fa-bolt"></i> Quick Actions</div>
            <div class="vc-card-body" style="padding:8px 14px;">
                @can('clinic.manage_appointments')
                <a href="{{ route('clinic.appointments.create') }}?patient_id={{ $patient->id }}&contact_id={{ $patient->contact_id }}"
                   class="btn btn-success btn-sm btn-block" style="margin-bottom:5px;">
                    <i class="fas fa-calendar-plus"></i> New Appointment
                </a>
                @endcan
                @can('clinic.manage_vaccinations')
                <button class="btn btn-primary btn-sm btn-block" style="margin-bottom:5px;"
                        data-toggle="modal" data-target="#addTreatmentModal">
                    <i class="fas fa-syringe"></i> Record Treatment
                </button>
                @endcan
                @can('clinic.manage_pets')
                <button class="btn btn-default btn-sm btn-block"
                        data-toggle="modal" data-target="#addConditionModal">
                    <i class="fas fa-disease"></i> Add Condition
                </button>
                @endcan
            </div>
        </div>
        @endif

    </div>{{-- /sidebar --}}

    {{-- MAIN CONTENT --}}
    <div class="col-md-9">

        <ul class="nav nav-tabs" id="petTabs">
            <li class="active">
                <a data-toggle="tab" href="#tab-overview">
                    <i class="fas fa-chart-pie"></i> Overview
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-conditions">
                    <i class="fas fa-disease"></i> @lang('clinicCore::lang.medical_history_tab')
                    @if($patient->conditions->count() > 0)
                        <span class="badge" style="background:#e74c3c;">{{ $patient->conditions->count() }}</span>
                    @endif
                </a>
            </li>
            {{-- SIFA P3-T1 structured clinical baseline (allergies / meds / insurance) --}}
            <li>
                <a data-toggle="tab" href="#tab-baseline">
                    <i class="fas fa-notes-medical"></i> @lang('clinicCore::lang.baseline_tab')
                    @php $blCount = $patient->structuredAllergies->count() + $patient->medications->count() + $patient->insurances->count(); @endphp
                    @if($blCount > 0)
                        <span class="badge" style="background:#0ea5e9;">{{ $blCount }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-vaccinations">
                    <i class="fas fa-syringe"></i> @lang('clinicCore::lang.vaccinations_tab')
                    @if($vaxOverdue > 0)
                        <span class="badge" style="background:#e74c3c;">{{ $vaxOverdue }} overdue</span>
                    @elseif($vaxDueSoon > 0)
                        <span class="badge" style="background:#f39c12;">{{ $vaxDueSoon }} due soon</span>
                    @elseif($patient->vaccinations->count() > 0)
                        <span class="badge">{{ $patient->vaccinations->count() }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-appointments">
                    <i class="fas fa-calendar"></i> @lang('clinicCore::lang.appointments_tab')
                    @if($patient->appointments->count() > 0)
                        <span class="badge">{{ $patient->appointments->count() }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-prescriptions">
                    <i class="fas fa-prescription-bottle-alt"></i> @lang('clinicCore::lang.prescriptions_tab')
                    @if($patient->prescriptions->count() > 0)
                        <span class="badge">{{ $patient->prescriptions->count() }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-clinical">
                    <i class="fas fa-notes-medical"></i> Clinical History
                    @php $clinicalCount = $patient->appointments->filter(fn($a) =>
                        $a->soap_subjective || $a->soap_objective || $a->soap_assessment ||
                        $a->soap_plan || $a->soap_investigations || $a->soap_lab_investigations ||
                        $a->soap_exam_investigations || $a->weight_kg || $a->temperature
                    )->count(); @endphp
                    @if($clinicalCount > 0)
                        <span class="badge" style="background:#16a085;">{{ $clinicalCount }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-documents">
                    <i class="fas fa-folder-open"></i> Documents
                    @php $docsCount = $patient->appointments->sum(fn($a) => $a->documents->count()) + $patient->medicalReports->count(); @endphp
                    @if($docsCount > 0)
                        <span class="badge" style="background:#8e44ad;">{{ $docsCount }}</span>
                    @endif
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-photos">
                    <i class="fas fa-camera"></i> Photos
                    <span class="badge" id="photos_count_badge" style="background:#0ea5e9;display:none;"></span>
                </a>
            </li>
            <li>
                <a data-toggle="tab" href="#tab-plans">
                    <i class="fas fa-clipboard-list"></i> Treatment Plans
                    <span class="badge" id="plans_count_badge" style="background:#0ea5e9;display:none;"></span>
                </a>
            </li>
            {{-- NX600 Lab module integration (only shown when the module is installed) --}}
            @if(false /* NX600Lab analyzer is vet-only; disabled in ClinicCore */)
            <li>
                <a data-toggle="tab" href="#tab-lab">
                    <i class="fas fa-vials"></i> Lab Tests
                    @php
                        $nxLabCount = \Modules\NX600Lab\Entities\NxTestSession::where('clc_patient_id', $patient->id)->count();
                    @endphp
                    @if($nxLabCount > 0)
                        <span class="badge" style="background:#2980b9;">{{ $nxLabCount }}</span>
                    @endif
                </a>
            </li>
            @endif
        </ul>

        <div class="tab-content" style="background:#fff;border:1px solid #ddd;border-top:none;border-radius:0 0 8px 8px;padding:18px;">

            {{-- ══ OVERVIEW ══ --}}
            <div id="tab-overview" class="tab-pane fade in active">

                {{-- Treatment Alerts --}}
                @if($vaxOverdue > 0)
                <div class="alert alert-danger" style="border-radius:7px;border-left:4px solid #c0392b;padding:10px 14px;display:flex;align-items:center;gap:10px;margin-bottom:14px;">
                    <i class="fas fa-exclamation-circle" style="font-size:18px;flex-shrink:0;"></i>
                    <div style="flex:1;"><strong>{{ $vaxOverdue }} vaccination{{ $vaxOverdue > 1 ? 's are' : ' is' }} overdue.</strong> Immediate attention required.</div>
                    <a href="#tab-vaccinations" onclick="$('#petTabs a[href=\'#tab-vaccinations\']').tab('show')"
                       class="btn btn-xs btn-danger" style="white-space:nowrap;">View →</a>
                </div>
                @elseif($vaxDueSoon > 0)
                <div class="alert alert-warning" style="border-radius:7px;border-left:4px solid #f39c12;padding:10px 14px;display:flex;align-items:center;gap:10px;margin-bottom:14px;">
                    <i class="fas fa-clock" style="font-size:18px;flex-shrink:0;"></i>
                    <div style="flex:1;"><strong>{{ $vaxDueSoon }} vaccination{{ $vaxDueSoon > 1 ? 's are' : ' is' }} due within {{ $reminderDays }} day{{ $reminderDays > 1 ? 's' : '' }}.</strong></div>
                    <a href="#tab-vaccinations" onclick="$('#petTabs a[href=\'#tab-vaccinations\']').tab('show')"
                       class="btn btn-xs btn-warning" style="white-space:nowrap;">View →</a>
                </div>
                @endif

                {{-- Stats --}}
                <div class="ov-stat-grid">
                    <div class="ov-stat">
                        <div class="num" style="color:#2c3e50;">{{ $patient->appointments->count() }}</div>
                        <div class="lbl">Appointments</div>
                    </div>
                    <div class="ov-stat">
                        <div class="num" style="color:#27ae60;">{{ $patient->vaccinations->count() }}</div>
                        <div class="lbl">Vaccinations</div>
                    </div>
                    <div class="ov-stat">
                        <div class="num" style="color:#e74c3c;">{{ $activeConditions }}</div>
                        <div class="lbl">Active Conditions</div>
                    </div>
                    <div class="ov-stat">
                        <div class="num" style="color:#8e44ad;">{{ $patient->prescriptions->count() }}</div>
                        <div class="lbl">Prescriptions</div>
                    </div>
                </div>

                {{-- Vitals trend (constants over recent visits) --}}
                @php
                    $vitalRows = $patient->appointments
                        ->filter(function ($a) {
                            return $a->weight_kg || $a->temperature || $a->heart_rate
                                || ($a->systolic_bp ?? null) || ($a->spo2 ?? null) || ($a->blood_glucose ?? null) || ($a->bmi ?? null);
                        })
                        ->sortByDesc('appointment_date')->take(8)->values();
                @endphp
                @if($vitalRows->isNotEmpty())
                <div style="margin-bottom:16px;">
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#aaa;margin-bottom:8px;">
                        <i class="fa fa-heartbeat"></i> @lang('clinicCore::lang.vitals_trend')
                    </div>
                    <div style="overflow-x:auto;">
                    <table class="table table-condensed" style="font-size:11.5px;border:1px solid #eee;margin:0;min-width:520px;">
                        <thead style="background:#f8fafc;">
                            <tr>
                                <th style="border-top:none;">Date</th>
                                <th style="border-top:none;">BP</th>
                                <th style="border-top:none;">Pulse</th>
                                <th style="border-top:none;">Temp</th>
                                <th style="border-top:none;">SpO₂</th>
                                <th style="border-top:none;">Glu</th>
                                <th style="border-top:none;">Wt</th>
                                <th style="border-top:none;">BMI</th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach($vitalRows as $vr)
                            <tr>
                                <td>{{ \Carbon\Carbon::parse($vr->appointment_date)->format('d M y') }}</td>
                                <td>{{ ($vr->systolic_bp ?? null) ? ($vr->systolic_bp.'/'.$vr->diastolic_bp) : '—' }}</td>
                                <td>{{ $vr->heart_rate ?: '—' }}</td>
                                <td>{{ $vr->temperature ?: '—' }}</td>
                                <td>{{ ($vr->spo2 ?? null) ?: '—' }}</td>
                                <td>{{ ($vr->blood_glucose ?? null) ?: '—' }}</td>
                                <td>{{ $vr->weight_kg ?: '—' }}</td>
                                <td>{{ ($vr->bmi ?? null) ?: '—' }}</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                    </div>
                </div>
                @endif

                {{-- Recent Appointments (SIFA P3-T2 encounter timeline: read-only
                     encounter_type / priority + a diagnoses summary per row). --}}
                @php
                    $recentApts = $patient->appointments->sortByDesc('appointment_date')->take(5);
                    // One grouped query for the diagnoses of the shown encounters.
                    $encDiagSummary = collect();
                    if (\Illuminate\Support\Facades\Schema::hasTable('clc_appointment_diagnoses') && $recentApts->isNotEmpty()) {
                        $encDiagSummary = \Modules\ClinicCore\Entities\ClcAppointmentDiagnosis::whereIn('appointment_id', $recentApts->pluck('id'))
                            ->get()->groupBy('appointment_id');
                    }
                    $encHasCol = \Illuminate\Support\Facades\Schema::hasColumn('clc_appointments', 'encounter_type');
                @endphp
                @if($recentApts->isNotEmpty())
                <div style="margin-bottom:16px;">
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#aaa;margin-bottom:8px;">
                        <i class="fa fa-calendar"></i> Recent Encounters
                    </div>
                    <table class="table table-condensed table-hover" style="font-size:12px;border:1px solid #eee;margin:0;border-radius:6px;overflow:hidden;">
                        <thead style="background:#f8fafc;">
                            <tr>
                                <th style="border-top:none;">Date</th>
                                <th style="border-top:none;">Doctor</th>
                                <th style="border-top:none;">Type</th>
                                @if($encHasCol)<th style="border-top:none;">Encounter</th>@endif
                                <th style="border-top:none;">Status</th>
                                <th style="border-top:none;width:40px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach($recentApts as $appt)
                        <tr>
                            <td>{{ \Carbon\Carbon::parse($appt->appointment_date)->format(session('business.date_format', 'd M Y')) }}
                                <small class="text-muted">{{ \Carbon\Carbon::parse($appt->appointment_time)->format($patientShowTimeFormat) }}</small>
                                @php $encDx = $encDiagSummary->get($appt->id); @endphp
                                @if($encDx && $encDx->isNotEmpty())
                                    <div class="text-muted" style="font-size:10.5px;margin-top:2px;">
                                        <i class="fa fa-notes-medical"></i>
                                        {{ $encDx->take(3)->pluck('description')->implode(', ') }}{{ $encDx->count() > 3 ? '…' : '' }}
                                    </div>
                                @endif
                            </td>
                            <td>{{ optional($appt->doctor)->name ?? '—' }}</td>
                            <td>
                                <span class="label" style="background:{{ $aptTypeColors[$appt->type] ?? '#7f8c8d' }};color:#fff;font-size:10px;">
                                    {{ ucfirst($appt->type) }}
                                </span>
                            </td>
                            @if($encHasCol)
                            <td>
                                @if($appt->encounter_type)
                                    <span class="label label-info" style="font-size:10px;">{{ ucfirst(str_replace('_',' ',$appt->encounter_type)) }}</span>
                                @endif
                                @if($appt->priority && $appt->priority !== 'routine')
                                    <span class="label label-{{ $appt->priority === 'emergency' ? 'danger' : 'warning' }}" style="font-size:10px;">{{ ucfirst($appt->priority) }}</span>
                                @endif
                            </td>
                            @endif
                            <td>
                                <span class="label label-{{ $aptStatusColors[$appt->status] ?? 'default' }}" style="font-size:10px;">
                                    {{ ucfirst(str_replace('_',' ',$appt->status)) }}
                                </span>
                            </td>
                            <td>
                                <a href="{{ route('clinic.appointments.show', $appt->id) }}" class="btn btn-xs btn-default">
                                    <i class="fa fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                        @endforeach
                        </tbody>
                    </table>
                    @if($patient->appointments->count() > 5)
                    <div style="text-align:right;margin-top:4px;">
                        <a href="#tab-appointments" onclick="$('#petTabs a[href=\'#tab-appointments\']').tab('show')" style="font-size:12px;">
                            View all {{ $patient->appointments->count() }} appointments →
                        </a>
                    </div>
                    @endif
                </div>
                @endif

                {{-- Weight History --}}
                @if(isset($weightHistory) && $weightHistory->isNotEmpty())
                @php $whArr = $weightHistory->values()->all(); @endphp
                <div>
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#aaa;margin-bottom:8px;">
                        <i class="fa fa-weight"></i> Weight History
                        <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#bbb;">
                            — last {{ count($whArr) }} reading{{ count($whArr) > 1 ? 's' : '' }}
                        </span>
                        @if(auth()->user() && (auth()->user()->can('clinic.vitals.view_trends') || auth()->user()->can('clinic.view_appointments')))
                        <a href="{{ route('clinic.patients.vitals-trends', $patient->id) }}" style="float:right;font-weight:600;font-size:11px;text-transform:none;letter-spacing:0;">
                            <i class="fa fa-line-chart"></i> {{ __('clinicCore::lang.vitals_trend') }}
                        </a>
                        @endif
                    </div>
                    <div style="background:#fff;border-radius:8px;border:1px solid #e8ecf0;overflow:hidden;">
                        @foreach($whArr as $idx => $wr)
                        @php
                            $trend    = null;
                            $trendPct = null;
                            $trendClass = 'same';
                            if (isset($whArr[$idx + 1])) {
                                $older = (float) $whArr[$idx + 1]['weight'];
                                $curr  = (float) $wr['weight'];
                                if ($older > 0) {
                                    $trend     = round($curr - $older, 2);
                                    $trendPct  = round(abs($trend / $older) * 100, 1);
                                    $trendClass = $trend > 0 ? 'up' : ($trend < 0 ? 'down' : 'same');
                                }
                            }
                            $isAppt   = $wr['icon'] === 'fa-calendar';
                            $pillClass = $isAppt ? 'appt' : 'vax';
                            $pillLabel = $isAppt ? 'Appointment' : 'Treatment';
                            $relDate   = \Carbon\Carbon::parse($wr['date'])->diffForHumans();
                        @endphp
                        <div class="wh-entry">
                            <div class="wh-weight-col">
                                <div class="wh-num-row">
                                    <span class="wh-num">{{ $wr['weight'] }}</span>
                                    <span class="wh-unit">kg</span>
                                </div>
                                @if($trend !== null)
                                <span class="wh-trend {{ $trendClass }}">
                                    @if($trendClass === 'up')
                                        <i class="fas fa-arrow-up" style="font-size:9px;"></i> +{{ $trendPct }}%
                                    @elseif($trendClass === 'down')
                                        <i class="fas fa-arrow-down" style="font-size:9px;"></i> -{{ $trendPct }}%
                                    @else
                                        <i class="fas fa-minus" style="font-size:9px;"></i> ±0
                                    @endif
                                </span>
                                @endif
                            </div>
                            <div class="wh-source-col">
                                <div>
                                    <span class="wh-type-pill {{ $pillClass }}">
                                        <i class="fas {{ $wr['icon'] }}"></i> {{ $pillLabel }}
                                    </span>
                                </div>
                                @if($wr['url'])
                                <a href="{{ $wr['url'] }}" class="wh-label">
                                    {{ $wr['label'] }} <i class="fas fa-external-link-alt" style="font-size:9px;opacity:.6;"></i>
                                </a>
                                @else
                                <span class="wh-label no-link">{{ $wr['label'] }}</span>
                                @endif
                            </div>
                            <div class="wh-date-col">
                                <div class="wh-date-abs">{{ \Carbon\Carbon::parse($wr['date'])->format('d-m-Y') }}</div>
                                <div class="wh-date-rel">{{ $relDate }}</div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
                @endif

            </div>

            {{-- ══ MEDICAL CONDITIONS ══ --}}
            <div id="tab-conditions" class="tab-pane fade">
                @php
                    $condActive   = $patient->conditions->where('status','active')->count();
                    $condChronic  = $patient->conditions->where('status','chronic')->count();
                    $condResolved = $patient->conditions->where('status','resolved')->count();
                @endphp
                {{-- Toolbar --}}
                <div class="tab-toolbar">
                    @can('clinic.manage_pets')
                    <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addConditionModal">
                        <i class="fa fa-plus"></i> Add Condition
                    </button>
                    @endcan
                    {{-- Status filter chips --}}
                    <button class="tc-chip tc-active cond-sfilt" data-sf="all"
                        style="color:#475569;border-color:#475569;background:#475569;">
                        All ({{ $patient->conditions->count() }})
                    </button>
                    @if($condActive)
                    <button class="tc-chip cond-sfilt" data-sf="active"
                        style="color:#e74c3c;border-color:#e74c3c;">
                        <i class="fa fa-circle" style="font-size:7px;"></i> Active ({{ $condActive }})
                    </button>
                    @endif
                    @if($condChronic)
                    <button class="tc-chip cond-sfilt" data-sf="chronic"
                        style="color:#f39c12;border-color:#f39c12;">
                        <i class="fa fa-circle" style="font-size:7px;"></i> Chronic ({{ $condChronic }})
                    </button>
                    @endif
                    @if($condResolved)
                    <button class="tc-chip cond-sfilt" data-sf="resolved"
                        style="color:#27ae60;border-color:#27ae60;">
                        <i class="fa fa-circle" style="font-size:7px;"></i> Resolved ({{ $condResolved }})
                    </button>
                    @endif
                    {{-- Severity filter --}}
                    <div style="margin-left:auto;display:flex;align-items:center;gap:6px;">
                        <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;">Severity:</span>
                        <select id="cond_sev_filter" style="height:28px;font-size:11px;padding:2px 8px;border:1.5px solid #e2e8f0;border-radius:7px;background:#fff;">
                            <option value="">All</option>
                            <option value="mild">Mild</option>
                            <option value="moderate">Moderate</option>
                            <option value="severe">Severe</option>
                        </select>
                    </div>
                </div>

                @if($patient->conditions->isEmpty())
                <div style="text-align:center;padding:48px 20px;background:#f8fafc;border-radius:8px;border:2px dashed #e2e8f0;">
                    <i class="fa fa-stethoscope" style="font-size:36px;color:#cbd5e1;display:block;margin-bottom:10px;"></i>
                    <p style="color:#94a3b8;margin:0;font-size:13px;">No medical conditions recorded yet.</p>
                </div>
                @else
                <div id="cond-list">
                    @foreach($patient->conditions->sortByDesc('created_at') as $pc)
                    <div class="cond-card {{ $pc->status }}"
                         data-cond-status="{{ $pc->status }}"
                         data-cond-severity="{{ $pc->severity ?? '' }}">
                        <div style="flex:1;min-width:0;">
                            <div class="cond-name">{{ optional($pc->condition)->name ?? '—' }}</div>
                            <div class="cond-meta">
                                @if($pc->severity)
                                <span><i class="fa fa-exclamation-triangle"></i> {{ ucfirst($pc->severity) }}</span>
                                @endif
                                {{-- P3-T8 problem-list: certainty + structured type --}}
                                @if($pc->certainty)
                                <span><i class="fa fa-question-circle"></i> {{ __('clinicCore::lang.certainty_' . $pc->certainty) }}</span>
                                @endif
                                @if($pc->condition_type)
                                <span><i class="fa fa-tag"></i> {{ __('clinicCore::lang.problem_type_' . $pc->condition_type) }}</span>
                                @endif
                                @if($pc->diagnosed_date)
                                <span><i class="fa fa-calendar"></i> Diagnosed {{ \Carbon\Carbon::parse($pc->diagnosed_date)->format('d-m-Y') }}</span>
                                @endif
                                @if($pc->resolved_date)
                                <span class="text-success"><i class="fa fa-check"></i> Resolved {{ \Carbon\Carbon::parse($pc->resolved_date)->format('d-m-Y') }}</span>
                                @endif
                                @php $condDoctor = optional(optional($pc)->doctor ?? null); @endphp
                                @if(isset($pc->doctor) && optional($pc->doctor)->name)
                                <span><i class="fa fa-user-md"></i> {{ $pc->doctor->name }}</span>
                                @endif
                                @if($pc->notes)
                                <span><i class="fa fa-comment"></i> {{ \Illuminate\Support\Str::limit($pc->notes, 80) }}</span>
                                @endif
                            </div>
                        </div>
                        <span class="label label-{{ $pc->status === 'active' ? 'danger' : ($pc->status === 'chronic' ? 'warning' : 'success') }}"
                              style="align-self:center;font-size:11px;">
                            {{ ucfirst($pc->status) }}
                        </span>
                        @can('clinic.manage_pets')
                        <div style="display:flex;flex-direction:column;gap:4px;flex-shrink:0;margin-left:8px;">
                            <button class="vpc-edit-btn btn-edit-condition"
                                data-id="{{ $pc->id }}"
                                data-name="{{ optional($pc->condition)->name ?? '' }}"
                                data-severity="{{ $pc->severity }}"
                                data-status="{{ $pc->status }}"
                                data-date-iso="{{ $pc->diagnosed_date }}"
                                data-notes="{{ $pc->notes }}"
                                data-certainty="{{ $pc->certainty }}"
                                data-condition-type="{{ $pc->condition_type }}"
                                title="Edit condition"><i class="fa fa-edit"></i></button>
                            <button class="vpc-del-btn btn-remove-condition"
                                data-id="{{ $pc->id }}"
                                title="Delete condition"><i class="fa fa-trash"></i></button>
                        </div>
                        @endcan
                    </div>
                    @endforeach
                </div>
                <div id="cond-empty-msg" style="display:none;text-align:center;padding:30px;color:#94a3b8;font-size:13px;">
                    <i class="fa fa-filter"></i> No conditions match this filter.
                </div>
                @endif
            </div>

            {{-- ══ CLINICAL BASELINE (P3-T1: allergies / meds / insurance) ══ --}}
            <div id="tab-baseline" class="tab-pane fade">
                @include('clinicCore::patients._baseline_tab', ['patient' => $patient])
            </div>

            {{-- ══ TREATMENTS ══ --}}
            <div id="tab-vaccinations" class="tab-pane fade">
                @can('clinic.manage_vaccinations')
                <div style="margin-bottom:12px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                    <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addTreatmentModal">
                        <i class="fas fa-syringe"></i> @lang('clinicCore::lang.add_vaccination')
                    </button>
                    @if($vaxOverdue > 0 || $vaxDueSoon > 0)
                    <a href="{{ route('clinic.vaccinations.index') }}" class="btn btn-sm btn-warning">
                        <i class="fa fa-bell"></i> All Reminders
                    </a>
                    @endif
                    @if($patient->vaccinations->isNotEmpty())
                    {{-- #5 - upgraded from btn-default (washed out) to btn-info
                         with explicit text-decoration removed so the link
                         doesn't underline on hover. Matches the visual
                         weight of its neighbours (primary / warning / etc). --}}
                    <a href="{{ route('clinic.patients.print-vaccinations', $patient->id) }}" target="_blank"
                       class="btn btn-sm btn-info"
                       style="text-decoration:none;font-weight:600;"
                       title="Print vaccination history & next due dates">
                        <i class="fa fa-print"></i> Print Vaccination History
                    </a>
                    @endif
                </div>
                @endcan

                @if($patient->vaccinations->isEmpty())
                    <p class="text-muted text-center" style="padding:24px 0;"><i class="fa fa-info-circle"></i> No vaccinations recorded yet.</p>
                @else

                {{-- Summary filter bar --}}
                <div class="vax-filter-bar">
                    <button class="vax-chip active" data-vax-filter="all"
                            style="color:#2c3e50;border-color:#2c3e50;" data-color="#2c3e50">
                        All ({{ $patient->vaccinations->count() }})
                    </button>
                    @if($vaxOverdue > 0)
                    <button class="vax-chip" data-vax-filter="overdue"
                            style="color:#e74c3c;border-color:#e74c3c;" data-color="#e74c3c">
                        <i class="fas fa-exclamation-circle"></i> Overdue ({{ $vaxOverdue }})
                    </button>
                    @endif
                    @if($vaxDueSoon > 0)
                    <button class="vax-chip" data-vax-filter="due_soon"
                            style="color:#f39c12;border-color:#f39c12;" data-color="#f39c12">
                        <i class="fas fa-clock"></i> Due Soon ({{ $vaxDueSoon }})
                    </button>
                    @endif
                    @if($vaxUpcoming > 0)
                    <button class="vax-chip" data-vax-filter="upcoming"
                            style="color:#27ae60;border-color:#27ae60;" data-color="#27ae60">
                        <i class="fas fa-check-circle"></i> Upcoming ({{ $vaxUpcoming }})
                    </button>
                    @endif
                </div>

                {{-- Secondary filter bar: category + taken status --}}
                <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px;padding:8px 10px;background:#f8fafc;border-radius:7px;border:1px solid #e8ecf0;align-items:center;">
                    <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;margin-right:2px;white-space:nowrap;">Where:</span>
                    <button class="vax-taken-chip active" data-taken="" data-color="#64748b" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #64748b;color:#fff;background:#64748b;cursor:pointer;">All</button>
                    <button class="vax-taken-chip" data-taken="taken_in" data-color="#27ae60" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #27ae60;color:#27ae60;background:transparent;cursor:pointer;"><i class="fa fa-hospital"></i> At Clinic</button>
                    <button class="vax-taken-chip" data-taken="taken_out" data-color="#2980b9" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #2980b9;color:#2980b9;background:transparent;cursor:pointer;"><i class="fa fa-home"></i> External</button>
                    <button class="vax-taken-chip" data-taken="not_taken" data-color="#e67e22" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #e67e22;color:#e67e22;background:transparent;cursor:pointer;"><i class="fa fa-clock"></i> Not Taken</button>
                    <span style="width:1px;height:18px;background:#ddd;margin:0 4px;"></span>
                    <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;margin-right:2px;white-space:nowrap;">Type:</span>
                    <button class="vax-cat-chip active" data-cat="" data-color="#64748b" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #64748b;color:#fff;background:#64748b;cursor:pointer;">All</button>
                    <button class="vax-cat-chip" data-cat="core_vaccine" data-color="#2980b9" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #2980b9;color:#2980b9;background:transparent;cursor:pointer;">Core</button>
                    <button class="vax-cat-chip" data-cat="non_core_vaccine" data-color="#8e44ad" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #8e44ad;color:#8e44ad;background:transparent;cursor:pointer;">Non-Core</button>
                    <button class="vax-cat-chip" data-cat="deworming" data-color="#16a085" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #16a085;color:#16a085;background:transparent;cursor:pointer;">Dewormer</button>
                    <button class="vax-cat-chip" data-cat="spot_on" data-color="#d35400" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #d35400;color:#d35400;background:transparent;cursor:pointer;">Spot-on</button>
                    {{-- View toggle (right-aligned) --}}
                    <div class="tab-vtbtn-wrap" style="margin-left:auto;">
                        <button class="tab-vtbtn active" id="vax_view_card" title="Card view"><i class="fa fa-th-large"></i></button>
                        <button class="tab-vtbtn" id="vax_view_list" title="List view"><i class="fa fa-list"></i></button>
                    </div>
                </div>

                {{-- Compact list view (hidden by default) --}}
                <div id="vax-list-view" style="display:none;">
                    <table class="table table-condensed table-hover" style="font-size:12px;border:1px solid #eee;border-radius:6px;overflow:hidden;">
                        <thead style="background:#f8fafc;">
                            <tr>
                                <th style="border-top:none;">Treatment</th>
                                <th style="border-top:none;">Type</th>
                                <th style="border-top:none;">Date</th>
                                <th style="border-top:none;">Next Due</th>
                                <th style="border-top:none;">Status</th>
                                <th style="border-top:none;width:44px;"></th>
                            </tr>
                        </thead>
                        <tbody id="vax-list-body">
                        @foreach($patient->vaccinations->sortByDesc('administered_date') as $vaxL)
                        @php
                            $vLDs      = $vaxL->due_status;
                            $vLWaived  = $vaxL->waived_at !== null;
                            $vLTaken   = $vaxL->taken_status ?? '';
                            $vLIsNT    = $vLTaken === 'not_taken';
                            $vLCat     = optional($vaxL->vaccineType)->category ?? '';
                            $vLBadgeBg = $vLWaived ? '#78909c' : match($vLDs) { 'overdue'=>'#e74c3c','due_soon'=>'#f39c12','upcoming'=>'#27ae60',default=>'#94a3b8' };
                            $vLTakenLbl = match($vLTaken) { 'taken_in'=>'At Clinic','taken_out'=>'External','not_taken'=>'Not Taken',default=>'—' };
                        @endphp
                        <tr class="vax-list-row" data-vax-ds="{{ $vLDs }}" data-vax-taken="{{ $vLTaken }}" data-vax-category="{{ $vLCat }}" style="{{ $vLWaived ? 'opacity:.55;' : '' }}">
                            <td style="font-weight:600;">{{ optional($vaxL->vaccineType)->name ?? '—' }}</td>
                            <td>
                                @if($vLCat && isset($catLabels[$vLCat]))
                                <span class="vpc-cat-chip">{{ $catLabels[$vLCat] }}</span>
                                @else <span class="text-muted">—</span>
                                @endif
                            </td>
                            <td>
                                {{ $vLIsNT ? 'Scheduled:' : '' }}
                                {{ optional($vaxL->administered_date)->format('d-m-Y') ?? '—' }}
                            </td>
                            <td>
                                @if(!$vLIsNT && $vaxL->next_due_date)
                                    <span style="color:{{ $vLDs === 'overdue' ? '#e74c3c' : ($vLDs === 'due_soon' ? '#f39c12' : '#27ae60') }};">
                                        {{ $vaxL->next_due_date->format('d-m-Y') }}
                                    </span>
                                @else
                                    <span class="text-muted">—</span>
                                @endif
                            </td>
                            <td>
                                <span style="font-size:10px;font-weight:700;padding:2px 7px;border-radius:10px;color:#fff;background:{{ $vLBadgeBg }};white-space:nowrap;">
                                    {{ $vLTakenLbl }}
                                </span>
                            </td>
                            <td>
                                @can('clinic.manage_vaccinations')
                                <button class="btn btn-xs btn-primary vpc-edit-btn btn-edit-vax-inline"
                                    data-id="{{ $vaxL->id }}"
                                    data-name="{{ optional($vaxL->vaccineType)->name ?? '' }}"
                                    data-vaccine-type-id="{{ $vaxL->vaccine_type_id }}"
                                    title="Edit"><i class="fa fa-edit"></i></button>
                                @endcan
                            </td>
                        </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>

                {{-- Passport Cards --}}
                <div id="vax-cards">
                @foreach($patient->vaccinations->sortByDesc('administered_date') as $vax)
                @php
                    $isWaived    = $vax->waived_at !== null;
                    $ds          = $vax->due_status; // returns 'waived' if waived_at set
                    $takenStatus = $vax->taken_status ?? '';
                    $isNotTaken  = $takenStatus === 'not_taken';
                    $stripeColor = $isWaived
                        ? '#b0bec5'
                        : ($isNotTaken
                            ? '#e67e22'
                            : match($ds) { 'overdue'=>'#e74c3c','due_soon'=>'#f39c12','upcoming'=>'#27ae60',default=>'#cbd5e1' });
                    $badgeBg     = $isWaived ? '#78909c' : match($ds) { 'overdue'=>'#e74c3c','due_soon'=>'#f39c12','upcoming'=>'#27ae60',default=>'#94a3b8' };

                    // Due label: not_taken shows scheduled date, taken shows next_due_date
                    $dueLabel = null;
                    if ($isWaived) {
                        $waivedReasonLabels = ['deceased'=>'Patient Deceased','refused'=>'Patient Refused','contraindicated'=>'Contraindicated','other'=>'Other'];
                        $dueLabel = 'Waived' . ($vax->waived_reason ? ': ' . ($waivedReasonLabels[$vax->waived_reason] ?? $vax->waived_reason) : '');
                    } elseif ($isNotTaken && $vax->administered_date) {
                        $dDays = (int) now()->diffInDays($vax->administered_date, false);
                        $dueLabel = match(true) { $dDays < 0 => abs($dDays).' days overdue', $dDays === 0 => 'Due today', default => 'In '.$dDays.' days' };
                    } elseif (!$isNotTaken && $vax->next_due_date) {
                        $dDays = (int) now()->diffInDays($vax->next_due_date, false);
                        $dueLabel = match(true) { $dDays < 0 => abs($dDays).' days overdue', $dDays === 0 => 'Due today', default => 'In '.$dDays.' days' };
                    }

                    $cat = optional($vax->vaccineType)->category ?? null;
                    $takenBadge = match($takenStatus) {
                        'taken_in'  => ['bg'=>'#27ae60','icon'=>'fa-hospital','label'=>'At Clinic'],
                        'taken_out' => ['bg'=>'#2980b9','icon'=>'fa-home',      'label'=>'External'],
                        'not_taken' => ['bg'=>'#e67e22','icon'=>'fa-clock',   'label'=>'Not Taken'],
                        default     => null,
                    };
                @endphp
                <div class="vax-pcard" data-vax-ds="{{ $ds ?? 'none' }}" data-vax-taken="{{ $takenStatus }}" data-vax-category="{{ $cat ?? '' }}" style="{{ $isWaived ? 'opacity:.6;' : '' }}">
                    <div class="vpc-stripe" style="background:{{ $stripeColor }};"></div>
                    <div class="vpc-icon"><i class="fas fa-syringe" style="{{ $isNotTaken && !$isWaived ? 'color:#e67e22;' : ($isWaived ? 'color:#90a4ae;' : '') }}"></i></div>
                    <div class="vpc-body">
                        <div class="vpc-top">
                            <span class="vpc-name vpc-name-clickable"
                                data-id="{{ $vax->id }}"
                                data-name="{{ optional($vax->vaccineType)->name ?? '' }}"
                                data-vaccine-type-id="{{ $vax->vaccine_type_id }}"
                                style="cursor:pointer;border-bottom:1px dotted #94a3b8;"
                                title="Click to edit">{{ optional($vax->vaccineType)->name ?? '—' }}</span>
                            @if($cat && isset($catLabels[$cat]))
                            <span class="vpc-cat-chip">{{ $catLabels[$cat] }}</span>
                            @endif
                            @if($takenBadge)
                            <span style="font-size:10px;font-weight:700;padding:2px 8px;border-radius:10px;color:#fff;background:{{ $takenBadge['bg'] }};white-space:nowrap;">
                                <i class="fa {{ $takenBadge['icon'] }}"></i> {{ $takenBadge['label'] }}
                            </span>
                            @endif
                            @if($dueLabel)
                            <span class="vpc-due-badge" style="background:{{ $badgeBg }};">{{ $dueLabel }}</span>
                            @endif
                        </div>
                        <div class="vpc-sub">
                            <span><i class="fas fa-calendar-check"></i>
                                {{ $isNotTaken ? 'Scheduled:' : 'Given:' }} {{ optional($vax->administered_date)->format('d-m-Y') ?? '—' }}
                            </span>
                            @if(!$isNotTaken && $vax->next_due_date)
                            <span><i class="fas fa-calendar-plus"></i> Next due: {{ $vax->next_due_date->format('d-m-Y') }}</span>
                            @endif
                            @if(optional($vax->doctor)->name)
                            <span><i class="fas fa-user-md"></i> {{ $vax->doctor->name }}</span>
                            @endif
                        </div>
                        @if($vax->dose || $vax->batch_no || $vax->weight_at_time || $vax->temperature_at_time)
                        <div class="vpc-meta">
                            @if($vax->dose)<span><i class="fa fa-flask"></i> {{ $vax->dose }}</span>@endif
                            @if($vax->batch_no)<span><i class="fa fa-barcode"></i> Batch: {{ $vax->batch_no }}</span>@endif
                            @if($vax->weight_at_time)<span><i class="fa fa-weight"></i> {{ $vax->weight_at_time }} kg</span>@endif
                            @if($vax->temperature_at_time)<span><i class="fa fa-thermometer-half"></i> {{ $vax->temperature_at_time }}°C</span>@endif
                        </div>
                        @endif
                        @if($vax->notes)
                        <div class="vpc-meta" style="margin-top:2px;"><i class="fa fa-comment"></i> {{ \Illuminate\Support\Str::limit($vax->notes, 80) }}</div>
                        @endif
                    </div>
                    @can('clinic.manage_vaccinations')
                    <div class="vpc-actions">
                        <button class="vpc-edit-btn btn-edit-vax-inline"
                            data-id="{{ $vax->id }}"
                            data-name="{{ optional($vax->vaccineType)->name ?? '' }}"
                            data-vaccine-type-id="{{ $vax->vaccine_type_id }}"
                            title="Edit vaccination"><i class="fa fa-edit"></i></button>
                        <button class="vpc-del-btn btn-delete-vax-inline"
                            data-id="{{ $vax->id }}"
                            title="Delete vaccination"><i class="fa fa-trash"></i></button>
                    </div>
                    @endcan
                </div>
                @endforeach
                </div>

                @endif
            </div>

            {{-- ══ APPOINTMENTS ══ --}}
            <div id="tab-appointments" class="tab-pane fade">

                {{-- Toolbar --}}
                <div class="tab-toolbar">
                    @if(!$patient->deceased)
                    @can('clinic.manage_appointments')
                    <a href="{{ route('clinic.appointments.create') }}?patient_id={{ $patient->id }}&contact_id={{ $patient->contact_id }}"
                       class="btn btn-sm btn-success">
                        <i class="fas fa-calendar-plus"></i> New Appointment
                    </a>
                    @endcan
                    @endif

                    {{-- Status filter --}}
                    <button class="tc-chip tc-active apt-sfilt" data-asf="all"
                        style="color:#475569;border-color:#475569;background:#475569;">
                        All ({{ $patient->appointments->count() }})
                    </button>
                    @foreach(['completed'=>['#27ae60','Completed'],'pending'=>['#f39c12','Pending'],'confirmed'=>['#2980b9','Confirmed'],'in_progress'=>['#3498db','In Progress'],'cancelled'=>['#e74c3c','Cancelled'],'no_show'=>['#95a5a6','No Show']] as $aSt => [$aStClr, $aStLbl])
                    @php $aStCnt = $patient->appointments->where('status', $aSt)->count(); @endphp
                    @if($aStCnt)
                    <button class="tc-chip apt-sfilt" data-asf="{{ $aSt }}"
                        style="color:{{ $aStClr }};border-color:{{ $aStClr }};">
                        {{ $aStLbl }} ({{ $aStCnt }})
                    </button>
                    @endif
                    @endforeach

                    {{-- Type filter --}}
                    <select id="apt_type_filter"
                        style="height:28px;font-size:11px;padding:2px 8px;border:1.5px solid #e2e8f0;border-radius:7px;background:#fff;">
                        <option value="">All types</option>
                        @foreach(['checkup','vaccination','surgery','grooming','emergency','other'] as $aTyp)
                        @if($patient->appointments->where('type', $aTyp)->count())
                        <option value="{{ $aTyp }}">{{ ucfirst($aTyp) }}</option>
                        @endif
                        @endforeach
                    </select>

                    {{-- View toggle --}}
                    <div class="tab-vtbtn-wrap">
                        <button class="tab-vtbtn active" id="apt_view_list" title="List view"><i class="fa fa-list"></i></button>
                        <button class="tab-vtbtn" id="apt_view_card" title="Card view"><i class="fa fa-th-large"></i></button>
                    </div>
                </div>

                @if($patient->appointments->isEmpty())
                <div style="text-align:center;padding:48px 20px;background:#f8fafc;border-radius:8px;border:2px dashed #e2e8f0;">
                    <i class="fas fa-calendar" style="font-size:36px;color:#cbd5e1;display:block;margin-bottom:10px;"></i>
                    <p style="color:#94a3b8;margin:0;font-size:13px;">No appointments recorded yet.</p>
                </div>
                @else

                {{-- LIST VIEW --}}
                <div id="apt-list-view">
                    <table class="table table-condensed table-hover" style="font-size:12px;border:1px solid #eee;border-radius:6px;overflow:hidden;">
                        <thead style="background:#f8fafc;">
                            <tr>
                                <th style="border-top:none;">Ref</th>
                                <th style="border-top:none;">Date &amp; Time</th>
                                <th style="border-top:none;">Doctor</th>
                                <th style="border-top:none;">Type</th>
                                <th style="border-top:none;">Status</th>
                                <th style="border-top:none;width:44px;"></th>
                            </tr>
                        </thead>
                        <tbody id="apt-table-body">
                        @foreach($patient->appointments->sortByDesc('appointment_date') as $appt)
                        <tr class="apt-row" data-ast="{{ $appt->status }}" data-atype="{{ $appt->type }}">
                            <td><a href="{{ route('clinic.appointments.show', $appt->id) }}" style="font-weight:700;color:#2980b9;">{{ $appt->ref_no }}</a></td>
                            <td>
                                {{ \Carbon\Carbon::parse($appt->appointment_date)->format(session('business.date_format','d M Y')) }}
                                <small class="text-muted"> {{ \Carbon\Carbon::parse($appt->appointment_time)->format($patientShowTimeFormat) }}</small>
                            </td>
                            <td>{{ optional($appt->doctor)->name ?? '—' }}</td>
                            <td>
                                <span class="label" style="background:{{ $aptTypeColors[$appt->type] ?? '#7f8c8d' }};color:#fff;font-size:10px;">
                                    {{ ucfirst($appt->type) }}
                                </span>
                            </td>
                            <td>
                                <span class="label label-{{ $aptStatusColors[$appt->status] ?? 'default' }}" style="font-size:10px;">
                                    {{ ucfirst(str_replace('_',' ',$appt->status)) }}
                                </span>
                            </td>
                            <td>
                                <a href="{{ route('clinic.appointments.show', $appt->id) }}" class="btn btn-xs btn-info">
                                    <i class="fa fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                        @endforeach
                        </tbody>
                    </table>
                    <div id="apt-list-empty" style="display:none;text-align:center;padding:24px;color:#94a3b8;font-size:13px;">
                        <i class="fa fa-filter"></i> No appointments match this filter.
                    </div>
                </div>

                {{-- CARD VIEW --}}
                <div id="apt-card-view" style="display:none;">
                    <div id="apt-cards-grid">
                    @foreach($patient->appointments->sortByDesc('appointment_date') as $appt)
                    @php
                        $aptStripe = $aptTypeColors[$appt->type] ?? '#7f8c8d';
                        $aptStLbl  = ucfirst(str_replace('_', ' ', $appt->status));
                        $aptStCls  = $aptStatusColors[$appt->status] ?? 'default';
                    @endphp
                    <div class="apt-card apt-card-item" data-ast="{{ $appt->status }}" data-atype="{{ $appt->type }}">
                        <div class="apt-stripe" style="background:{{ $aptStripe }};"></div>
                        <div class="apt-body">
                            <div class="apt-top">
                                <a href="{{ route('clinic.appointments.show', $appt->id) }}" class="apt-ref">{{ $appt->ref_no }}</a>
                                <span class="label" style="background:{{ $aptStripe }};color:#fff;font-size:10px;">{{ ucfirst($appt->type) }}</span>
                                <span class="label label-{{ $aptStCls }}" style="font-size:10px;">{{ $aptStLbl }}</span>
                            </div>
                            <div class="apt-sub">
                                <span><i class="fa fa-calendar"></i> {{ \Carbon\Carbon::parse($appt->appointment_date)->format(session('business.date_format','d M Y')) }}
                                    <small>{{ \Carbon\Carbon::parse($appt->appointment_time)->format($patientShowTimeFormat) }}</small>
                                </span>
                                @if(optional($appt->doctor)->name)
                                <span><i class="fa fa-user-md"></i> {{ $appt->doctor->name }}</span>
                                @endif
                                @if($appt->reason)
                                <span><i class="fa fa-comment"></i> {{ \Illuminate\Support\Str::limit($appt->reason, 60) }}</span>
                                @endif
                            </div>
                        </div>
                        <div class="apt-actions">
                            <a href="{{ route('clinic.appointments.show', $appt->id) }}" class="btn btn-xs btn-info">
                                <i class="fa fa-eye"></i>
                            </a>
                        </div>
                    </div>
                    @endforeach
                    </div>
                    <div id="apt-card-empty" style="display:none;text-align:center;padding:24px;color:#94a3b8;font-size:13px;">
                        <i class="fa fa-filter"></i> No appointments match this filter.
                    </div>
                </div>

                @endif
            </div>

            {{-- ══ PRESCRIPTIONS ══ --}}
            <div id="tab-prescriptions" class="tab-pane fade">

                @php
                    $rxActive    = $patient->prescriptions->where('status','active')->count();
                    $rxCompleted = $patient->prescriptions->where('status','completed')->count();
                    $rxCancelled = $patient->prescriptions->where('status','cancelled')->count();
                @endphp

                {{-- Toolbar --}}
                <div class="tab-toolbar">
                    {{-- Status filter chips --}}
                    <button class="tc-chip tc-active rx-sfilt" data-rxf="all"
                        style="color:#475569;border-color:#475569;background:#475569;">
                        All ({{ $patient->prescriptions->count() }})
                    </button>
                    @if($rxActive)
                    <button class="tc-chip rx-sfilt" data-rxf="active"
                        style="color:#27ae60;border-color:#27ae60;">
                        <i class="fa fa-circle" style="font-size:7px;"></i> Active ({{ $rxActive }})
                    </button>
                    @endif
                    @if($rxCompleted)
                    <button class="tc-chip rx-sfilt" data-rxf="completed"
                        style="color:#2980b9;border-color:#2980b9;">
                        <i class="fa fa-check-circle" style="font-size:9px;"></i> Completed ({{ $rxCompleted }})
                    </button>
                    @endif
                    @if($rxCancelled)
                    <button class="tc-chip rx-sfilt" data-rxf="cancelled"
                        style="color:#e74c3c;border-color:#e74c3c;">
                        <i class="fa fa-times-circle" style="font-size:9px;"></i> Cancelled ({{ $rxCancelled }})
                    </button>
                    @endif

                    {{-- View toggle --}}
                    <div class="tab-vtbtn-wrap">
                        <button class="tab-vtbtn active" id="rx_view_list" title="List view"><i class="fa fa-list"></i></button>
                        <button class="tab-vtbtn" id="rx_view_card" title="Card view"><i class="fa fa-th-large"></i></button>
                    </div>
                </div>

                @if($patient->prescriptions->isEmpty())
                <div style="text-align:center;padding:48px 20px;background:#f8fafc;border-radius:8px;border:2px dashed #e2e8f0;">
                    <i class="fas fa-prescription-bottle-alt" style="font-size:36px;color:#cbd5e1;display:block;margin-bottom:10px;"></i>
                    <p style="color:#94a3b8;margin:0;font-size:13px;">No prescriptions recorded yet.</p>
                </div>
                @else

                {{-- LIST VIEW --}}
                <div id="rx-list-view">
                    <table class="table table-condensed table-hover" style="font-size:12px;border:1px solid #eee;border-radius:6px;overflow:hidden;">
                        <thead style="background:#f8fafc;">
                            <tr>
                                <th style="border-top:none;">Ref</th>
                                <th style="border-top:none;">Date</th>
                                <th style="border-top:none;">Doctor</th>
                                <th style="border-top:none;">Valid Until</th>
                                <th style="border-top:none;">Status</th>
                                <th style="border-top:none;width:60px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach($patient->prescriptions->sortByDesc('prescribed_date') as $rx)
                        <tr class="rx-row" data-rxst="{{ $rx->status }}">
                            <td>
                                <a href="{{ route('clinic.prescriptions.show', $rx->id) }}" style="font-weight:700;color:#8e44ad;">{{ $rx->ref_no }}</a>
                            </td>
                            <td>{{ optional($rx->prescribed_date)->format('d-m-Y') ?? '—' }}</td>
                            <td>{{ optional($rx->doctor)->name ?? '—' }}</td>
                            <td>
                                @if($rx->valid_until)
                                    @php $rxExpired = $rx->valid_until->isPast(); @endphp
                                    <span style="color:{{ $rxExpired ? '#e74c3c' : '#555' }};">
                                        {{ $rx->valid_until->format('d-m-Y') }}
                                        @if($rxExpired) <small class="text-muted">(expired)</small> @endif
                                    </span>
                                @else
                                    <span class="text-muted">—</span>
                                @endif
                            </td>
                            <td>
                                <span class="label label-{{ $rx->status === 'active' ? 'success' : ($rx->status === 'completed' ? 'info' : 'danger') }}" style="font-size:10px;">
                                    {{ ucfirst($rx->status) }}
                                </span>
                            </td>
                            <td>
                                <a href="{{ route('clinic.prescriptions.show', $rx->id) }}" class="btn btn-xs btn-info"><i class="fa fa-eye"></i></a>
                                <a href="{{ route('clinic.prescriptions.print', $rx->id) }}" target="_blank" class="btn btn-xs btn-default" title="Print"><i class="fa fa-print"></i></a>
                            </td>
                        </tr>
                        @endforeach
                        </tbody>
                    </table>
                    <div id="rx-list-empty" style="display:none;text-align:center;padding:24px;color:#94a3b8;font-size:13px;">
                        <i class="fa fa-filter"></i> No prescriptions match this filter.
                    </div>
                </div>

                {{-- CARD VIEW --}}
                <div id="rx-card-view" style="display:none;">
                    <div id="rx-cards-grid">
                    @foreach($patient->prescriptions->sortByDesc('prescribed_date') as $rx)
                    @php
                        $rxStripe  = $rx->status === 'active' ? '#27ae60' : ($rx->status === 'completed' ? '#2980b9' : '#e74c3c');
                        $rxStLabel = ucfirst($rx->status);
                        $rxStCls   = $rx->status === 'active' ? 'success' : ($rx->status === 'completed' ? 'info' : 'danger');
                        $rxExpired = $rx->valid_until ? $rx->valid_until->isPast() : false;
                    @endphp
                    <div class="rx-card rx-card-item" data-rxst="{{ $rx->status }}">
                        <div class="rx-stripe" style="background:{{ $rxStripe }};"></div>
                        <div class="rx-body">
                            <div class="rx-top">
                                <a href="{{ route('clinic.prescriptions.show', $rx->id) }}" class="rx-ref">{{ $rx->ref_no }}</a>
                                <span class="label label-{{ $rxStCls }}" style="font-size:10px;">{{ $rxStLabel }}</span>
                                @if($rx->diagnosis)
                                <span style="font-size:11px;color:#64748b;font-style:italic;">{{ \Illuminate\Support\Str::limit($rx->diagnosis, 50) }}</span>
                                @endif
                            </div>
                            <div class="rx-sub">
                                @if($rx->prescribed_date)
                                <span><i class="fa fa-calendar"></i> {{ $rx->prescribed_date->format('d-m-Y') }}</span>
                                @endif
                                @if(optional($rx->doctor)->name)
                                <span><i class="fa fa-user-md"></i> {{ $rx->doctor->name }}</span>
                                @endif
                                @if($rx->valid_until)
                                <span style="{{ $rxExpired ? 'color:#e74c3c;' : '' }}">
                                    <i class="fa fa-hourglass-{{ $rxExpired ? 'end' : 'half' }}"></i>
                                    Valid until {{ $rx->valid_until->format('d-m-Y') }}
                                    @if($rxExpired) <em>(expired)</em> @endif
                                </span>
                                @endif
                            </div>
                        </div>
                        <div class="rx-actions">
                            <a href="{{ route('clinic.prescriptions.show', $rx->id) }}" class="btn btn-xs btn-info"><i class="fa fa-eye"></i></a>
                            <a href="{{ route('clinic.prescriptions.print', $rx->id) }}" target="_blank" class="btn btn-xs btn-default"><i class="fa fa-print"></i></a>
                        </div>
                    </div>
                    @endforeach
                    </div>
                    <div id="rx-card-empty" style="display:none;text-align:center;padding:24px;color:#94a3b8;font-size:13px;">
                        <i class="fa fa-filter"></i> No prescriptions match this filter.
                    </div>
                </div>

                @endif
            </div>

            {{-- ══ CLINICAL HISTORY ══ --}}
            <div id="tab-clinical" class="tab-pane fade printable-clinical">

                {{-- Print-only header. Hidden on screen; appears at the top
                     of the print output so the printed page identifies the
                     patient, contact, clinic and generation date. --}}
                <div class="print-only print-header">
                    <div class="ph-title">Clinical History</div>
                    <div class="ph-grid">
                        <div><strong>Patient:</strong> {{ $patient->patient_name }}</div>
                        @if(config('cliniccore.show_animal_fields', false))
                        <div><strong>Skin Type:</strong> {{ ucfirst($patient->species ?? '') }}{{ $patient->breed ? ' - '.$patient->breed : '' }}</div>
                        @endif
                        @if(optional($patient)->dob)
                        <div><strong>Age:</strong> {{ $patient->age }} yrs</div>
                        @endif
                        @if(optional($patient)->gender)
                        <div><strong>Gender:</strong> {{ ucfirst($patient->gender) }}{{ (config('cliniccore.show_animal_fields', false) && $patient->neutered) ? ' (Neutered)' : '' }}</div>
                        @endif
                        @if(config('cliniccore.show_animal_fields', false) && optional($patient)->microchip_no)
                        <div><strong>File No.:</strong> {{ $patient->microchip_no }}</div>
                        @endif
                        <div><strong>Contact:</strong> {{ $ownerName }}{{ $ownerMobile ? ' (' . $ownerMobile . ')' : '' }}</div>
                        <div><strong>Generated:</strong> {{ \Carbon\Carbon::now()->format(session('business.date_format', 'd M Y') . ' H:i') }}</div>
                        <div><strong>Clinic:</strong> {{ session('business.name', config('app.name')) }}</div>
                    </div>
                </div>

                @php
                    $clinicalApts = $patient->appointments->sortByDesc('appointment_date');
                    $typeColors = ['checkup'=>'#2980b9','vaccination'=>'#27ae60','surgery'=>'#c0392b','grooming'=>'#8e44ad','emergency'=>'#e67e22','other'=>'#7f8c8d'];
                    $statusColors = ['pending'=>'#f39c12','confirmed'=>'#3498db','in_progress'=>'#9b59b6','completed'=>'#27ae60','cancelled'=>'#e74c3c','no_show'=>'#95a5a6'];
                    // Statuses that represent a finished clinical encounter -
                    // anything else is a pending action and is excluded from
                    // the printed history per task 5.1.
                    $finalisedStatuses = ['completed', 'cancelled', 'no_show'];
                    $soapLabels = [
                        'soap_subjective'        => ['S','Subjective — Chief Complaint / History',  '#2c3e50'],
                        'soap_objective'         => ['O','Objective — Physical Examination',         '#2980b9'],
                        'soap_investigations'    => ['I','Investigations — General',                 '#16a085'],
                        'soap_lab_investigations'=> ['I','Investigations — Lab',                     '#16a085'],
                        'soap_exam_investigations'=> ['I','Investigations — Examination',            '#16a085'],
                        'soap_assessment'        => ['A','Assessment — Diagnosis / Differential',    '#8e44ad'],
                        'soap_plan'              => ['P','Plan — Treatment',                         '#c0392b'],
                    ];
                    $dfmt = session('business.date_format', 'd M Y');
                @endphp

                {{-- Toolbar --}}
                <div class="tab-toolbar" style="margin-bottom:16px;">
                    <span style="font-size:12px;font-weight:700;color:#64748b;">
                        <i class="fas fa-notes-medical" style="color:#16a085;"></i>
                        {{ $clinicalApts->count() }} visit{{ $clinicalApts->count() != 1 ? 's' : '' }}
                        — {{ $clinicalCount }} with clinical notes
                    </span>
                    <div style="margin-left:auto;display:flex;gap:6px;">
                        <button id="btn_expand_all" class="btn btn-xs btn-default">
                            <i class="fa fa-expand"></i> Expand All
                        </button>
                        <button id="btn_collapse_all" class="btn btn-xs btn-default">
                            <i class="fa fa-compress"></i> Collapse All
                        </button>
                        {{-- Item #8 - professional PDF (dompdf) with QR. Opens inline; add
                             ?download=1 to force a download. Falls back to browser print
                             via the secondary button below if the PDF endpoint errors out. --}}
                        <a href="{{ route('clinic.patients.clinical-history.pdf', $patient->id) }}"
                           target="_blank"
                           class="btn btn-xs btn-primary"
                           title="Open a professional PDF clinical history with QR verification.">
                            <i class="fa fa-file-pdf"></i> PDF Clinical History
                        </a>
                        <a href="{{ route('clinic.patients.clinical-history.pdf', $patient->id) }}?download=1"
                           class="btn btn-xs btn-default"
                           title="Download the PDF instead of opening it.">
                            <i class="fa fa-download"></i>
                        </a>
                        <button onclick="window.print()" class="btn btn-xs btn-default"
                                title="Browser-print fallback (excludes pending visits).">
                            <i class="fa fa-print"></i>
                        </button>
                    </div>
                </div>

                @if($clinicalApts->isEmpty())
                    <div style="text-align:center;padding:40px;color:#94a3b8;">
                        <i class="fas fa-notes-medical" style="font-size:36px;opacity:.3;display:block;margin-bottom:10px;"></i>
                        No appointment history found.
                    </div>
                @else
                @foreach($clinicalApts as $ci => $capt)
                @php
                    $captColor     = $typeColors[$capt->type ?? 'other'] ?? '#7f8c8d';
                    $captStatusClr = $statusColors[$capt->status ?? 'pending'] ?? '#95a5a6';
                    $captId        = 'capt_' . $capt->id;
                    $hasSoap       = $capt->soap_subjective || $capt->soap_objective || $capt->soap_assessment ||
                                     $capt->soap_plan || $capt->soap_investigations ||
                                     $capt->soap_lab_investigations || $capt->soap_exam_investigations;
                    $hasVitals     = $capt->weight_kg || $capt->temperature || $capt->heart_rate || $capt->respiratory_rate;
                    $hasClinical   = $hasSoap || $hasVitals;
                    $captVax       = $capt->vaccinations->where('taken_status','!=','not_taken');
                    $captRx        = $capt->prescriptions;
                    $captDocsCount = $capt->documents->count();
                    $captNotes     = $capt->appointmentNotes;
                    $isExpanded    = $ci < 3; // first 3 open by default
                    $isFinalised   = in_array($capt->status, $finalisedStatuses, true);
                @endphp
                <div class="panel clinical-apt-panel{{ $isFinalised ? '' : ' print-hidden' }}"
                     data-finalised="{{ $isFinalised ? '1' : '0' }}"
                     style="border:1px solid #e2e8f0;border-radius:8px;margin-bottom:10px;overflow:hidden;border-left:4px solid {{ $captColor }};">
                    {{-- Header --}}
                    <div class="panel-heading clinical-apt-toggle"
                         data-target="#{{ $captId }}"
                         style="background:{{ $hasClinical ? '#f8fafc' : '#fafafa' }};padding:11px 14px;cursor:pointer;display:flex;align-items:center;gap:10px;user-select:none;">
                        <i class="fa fa-chevron-{{ $isExpanded ? 'up' : 'down' }} toggle-icon"
                           style="font-size:11px;color:#94a3b8;flex-shrink:0;transition:transform .2s;"></i>
                        <div style="flex:1;min-width:0;">
                            <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                                <strong style="font-size:13px;color:#1e293b;">
                                    {{ \Carbon\Carbon::parse($capt->appointment_date)->format($dfmt) }}
                                </strong>
                                @if($capt->appointment_time)
                                <span style="font-size:12px;color:#64748b;">
                                    {{ \Carbon\Carbon::parse($capt->appointment_time)->format('H:i') }}
                                </span>
                                @endif
                                @if($capt->ref_no)
                                <span style="font-size:11px;color:#94a3b8;">#{{ $capt->ref_no }}</span>
                                @endif
                                <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:10px;color:#fff;background:{{ $captColor }};">
                                    {{ ucfirst($capt->type ?? 'Visit') }}
                                </span>
                                <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:10px;color:#fff;background:{{ $captStatusClr }};">
                                    {{ ucfirst(str_replace('_',' ',$capt->status ?? '')) }}
                                </span>
                            </div>
                            <div style="font-size:11px;color:#64748b;margin-top:3px;display:flex;gap:12px;flex-wrap:wrap;">
                                @if(optional($capt->doctor)->name)
                                <span><i class="fas fa-user-md"></i> {{ $capt->doctor->name }}</span>
                                @endif
                                @if($hasVitals)
                                <span style="color:#16a085;"><i class="fas fa-heartbeat"></i> Vitals recorded</span>
                                @endif
                                @if($hasSoap)
                                <span style="color:#2980b9;"><i class="fas fa-file-medical-alt"></i> SOIAP notes</span>
                                @endif
                                @if($captVax->count())
                                <span style="color:#27ae60;"><i class="fas fa-syringe"></i> {{ $captVax->count() }} vaccine{{ $captVax->count()>1?'s':'' }}</span>
                                @endif
                                @if($captRx->count())
                                <span style="color:#8e44ad;"><i class="fas fa-prescription-bottle-alt"></i> {{ $captRx->count() }} prescription{{ $captRx->count()>1?'s':'' }}</span>
                                @endif
                                @if($captDocsCount)
                                <span style="color:#546e7a;"><i class="fas fa-paperclip"></i> {{ $captDocsCount }} doc{{ $captDocsCount>1?'s':'' }}</span>
                                @endif
                            </div>
                        </div>
                        <a href="{{ route('clinic.appointments.show', $capt->id) }}"
                           class="btn btn-xs btn-default" onclick="event.stopPropagation();"
                           style="flex-shrink:0;white-space:nowrap;">
                            <i class="fa fa-eye"></i> Full
                        </a>
                    </div>

                    {{-- Body --}}
                    <div id="{{ $captId }}" class="clinical-apt-body" style="{{ $isExpanded ? '' : 'display:none;' }}padding:0;">
                        <div style="padding:14px 16px;">

                            {{-- Vitals --}}
                            @if($hasVitals)
                            <div style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:14px;padding:10px 14px;background:#f0fdf4;border-radius:7px;border:1px solid #bbf7d0;">
                                <span style="font-size:10px;font-weight:800;text-transform:uppercase;color:#16a085;letter-spacing:.5px;align-self:center;">Vitals</span>
                                @if($capt->weight_kg)
                                <span style="font-size:12px;"><i class="fas fa-weight" style="color:#16a085;"></i> <strong>{{ $capt->weight_kg }}</strong> kg</span>
                                @endif
                                @if($capt->temperature)
                                <span style="font-size:12px;"><i class="fas fa-thermometer-half" style="color:#e67e22;"></i> <strong>{{ $capt->temperature }}</strong>°C</span>
                                @endif
                                @if($capt->heart_rate)
                                <span style="font-size:12px;"><i class="fas fa-heartbeat" style="color:#e74c3c;"></i> <strong>{{ $capt->heart_rate }}</strong> bpm</span>
                                @endif
                                @if($capt->respiratory_rate)
                                <span style="font-size:12px;"><i class="fas fa-lungs" style="color:#3498db;"></i> <strong>{{ $capt->respiratory_rate }}</strong>/min</span>
                                @endif
                            </div>
                            @endif

                            {{-- SOIAP Sections --}}
                            @if($hasSoap)
                            <div style="display:flex;flex-direction:column;gap:10px;">
                                @foreach($soapLabels as $field => [$letter, $label, $color])
                                    @if(!empty($capt->$field))
                                    <div style="display:flex;gap:10px;align-items:flex-start;">
                                        <div style="flex-shrink:0;width:26px;height:26px;border-radius:50%;background:{{ $color }};color:#fff;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;">{{ $letter }}</div>
                                        <div style="flex:1;min-width:0;">
                                            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:{{ $color }};margin-bottom:3px;">{{ $label }}</div>
                                            <div style="font-size:13px;color:#334155;white-space:pre-wrap;background:#f8fafc;border-radius:5px;padding:8px 10px;border:1px solid #e2e8f0;line-height:1.6;">{{ $capt->$field }}</div>
                                        </div>
                                    </div>
                                    @endif
                                @endforeach

                                {{-- Plan Medications JSON --}}
                                @if(!empty($capt->soap_plan_meds_json))
                                @php
                                    $planMeds = is_array($capt->soap_plan_meds_json)
                                        ? $capt->soap_plan_meds_json
                                        : json_decode($capt->soap_plan_meds_json, true);
                                @endphp
                                @if(!empty($planMeds))
                                <div style="display:flex;gap:10px;align-items:flex-start;">
                                    <div style="flex-shrink:0;width:26px;height:26px;border-radius:50%;background:#c0392b;color:#fff;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;">P</div>
                                    <div style="flex:1;">
                                        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#c0392b;margin-bottom:5px;">Plan — Medications</div>
                                        <table style="width:100%;font-size:12px;border-collapse:collapse;">
                                            <thead><tr style="background:#fef2f2;">
                                                <th style="padding:4px 8px;text-align:left;border:1px solid #fecaca;font-weight:700;">Medicine</th>
                                                <th style="padding:4px 8px;text-align:left;border:1px solid #fecaca;font-weight:700;">Dose</th>
                                                <th style="padding:4px 8px;text-align:left;border:1px solid #fecaca;font-weight:700;">Frequency</th>
                                                <th style="padding:4px 8px;text-align:left;border:1px solid #fecaca;font-weight:700;">Duration</th>
                                            </tr></thead>
                                            <tbody>
                                            @foreach($planMeds as $med)
                                            <tr style="border-bottom:1px solid #fee2e2;">
                                                <td style="padding:4px 8px;border:1px solid #fecaca;">{{ $med['name'] ?? $med['medicine_name'] ?? '—' }}</td>
                                                <td style="padding:4px 8px;border:1px solid #fecaca;">{{ $med['dose'] ?? $med['dosage'] ?? '—' }}</td>
                                                <td style="padding:4px 8px;border:1px solid #fecaca;">{{ $med['frequency'] ?? '—' }}</td>
                                                <td style="padding:4px 8px;border:1px solid #fecaca;">{{ isset($med['duration_days']) ? $med['duration_days'].' days' : '—' }}</td>
                                            </tr>
                                            @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                @endif
                                @endif
                            </div>
                            @endif

                            @if(!$hasClinical)
                            <p class="text-muted" style="font-size:12px;margin:0;padding:4px 0;">
                                <i class="fa fa-info-circle"></i> No clinical notes recorded for this visit.
                            </p>
                            @endif

                            {{-- Linked: Treatments --}}
                            @if($captVax->count())
                            <div style="margin-top:12px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#27ae60;letter-spacing:.5px;">
                                    <i class="fas fa-syringe"></i> Treatments Given
                                </span>
                                <div style="margin-top:5px;display:flex;flex-wrap:wrap;gap:5px;">
                                    @foreach($captVax as $cv)
                                    <span style="font-size:11px;font-weight:600;padding:2px 9px;border-radius:10px;background:#d1fae5;color:#065f46;border:1px solid #6ee7b7;">
                                        {{ optional($cv->vaccineType)->name ?? '—' }}
                                        @if($cv->dose) <span style="opacity:.7;">· {{ $cv->dose }}</span>@endif
                                    </span>
                                    @endforeach
                                </div>
                            </div>
                            @endif

                            {{-- Linked: Prescriptions --}}
                            @if($captRx->count())
                            <div style="margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#8e44ad;letter-spacing:.5px;">
                                    <i class="fas fa-prescription-bottle-alt"></i> Prescriptions
                                </span>
                                {{-- Item 5.2 — show prescription items inline, not just a ref-no chip.
                                     Each Rx expands to its line items (med + dose + frequency + dispensed). --}}
                                <div style="margin-top:5px;display:flex;flex-direction:column;gap:6px;">
                                    @foreach($captRx as $crx)
                                    <div style="border:1px solid #c4b5fd;border-left:3px solid #8e44ad;border-radius:5px;padding:6px 9px;background:#faf5ff;">
                                        <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:11.5px;">
                                            <a href="{{ route('clinic.prescriptions.show', $crx->id) }}"
                                               style="font-weight:700;color:#5b21b6;text-decoration:none;">
                                                {{ $crx->ref_no ?? 'Rx #' . $crx->id }}
                                            </a>
                                            <span style="font-size:10px;padding:1px 7px;border-radius:9px;background:#ede9fe;color:#5b21b6;">{{ ucfirst($crx->status) }}</span>
                                            @if(optional($crx->items)->count())
                                            <span class="text-muted" style="font-size:10.5px;">{{ $crx->items->count() }} item{{ $crx->items->count() > 1 ? 's' : '' }}</span>
                                            @endif
                                        </div>
                                        @if(optional($crx->items)->count())
                                        <ul style="margin:5px 0 0 0;padding-left:18px;font-size:11.5px;color:#334155;">
                                            @foreach($crx->items as $rxItem)
                                            <li style="line-height:1.5;">
                                                <strong>{{ $rxItem->medicine_name ?? $rxItem->name ?? '—' }}</strong>
                                                @if($rxItem->dose ?? null) — {{ $rxItem->dose }}@endif
                                                @if($rxItem->frequency ?? null) · {{ $rxItem->frequency }}@endif
                                                @if($rxItem->duration_days ?? null) · {{ $rxItem->duration_days }} day{{ $rxItem->duration_days > 1 ? 's' : '' }}@endif
                                                @if(($rxItem->qty_dispensed ?? 0) > 0)
                                                <span class="text-muted" style="font-size:10.5px;">(dispensed {{ $rxItem->qty_dispensed }}/{{ $rxItem->qty ?? $rxItem->quantity ?? '?' }})</span>
                                                @endif
                                            </li>
                                            @endforeach
                                        </ul>
                                        @endif
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                            @endif

                            {{-- Item 5.2 — Lab / Imaging results recorded against this appointment.
                                 Reads exam_results JSON (per-test status + values) plus any
                                 linked clc_medical_reports for this date. --}}
                            @php
                                $captExamResults = $capt->exam_results ?? null;
                                if (is_string($captExamResults)) {
                                    $captExamResults = json_decode($captExamResults, true);
                                }
                                $captReports = $patient->medicalReports
                                    ->where('appointment_id', $capt->id)
                                    ->values();
                            @endphp
                            @if(is_array($captExamResults) && count($captExamResults))
                            <div style="margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#0ea5e9;letter-spacing:.5px;">
                                    <i class="fas fa-flask"></i> Lab / Investigation Results
                                </span>
                                <ul style="margin:5px 0 0 0;padding-left:18px;font-size:11.5px;color:#334155;">
                                    @foreach($captExamResults as $er)
                                    <li>
                                        <strong>{{ $er['label'] ?? $er['name'] ?? '—' }}</strong>
                                        @if(!empty($er['result'])) — {{ $er['result'] }}@endif
                                        @if(!empty($er['status']))
                                        <span style="font-size:10px;padding:1px 6px;border-radius:8px;background:#dbeafe;color:#1e40af;">{{ ucfirst($er['status']) }}</span>
                                        @endif
                                        @if(!empty($er['note'])) <small class="text-muted">— {{ \Illuminate\Support\Str::limit($er['note'], 120) }}</small>@endif
                                    </li>
                                    @endforeach
                                </ul>
                            </div>
                            @endif
                            @if($captReports && $captReports->count())
                            <div style="margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#0ea5e9;letter-spacing:.5px;">
                                    <i class="fas fa-file-medical-alt"></i> Medical Reports
                                </span>
                                <div style="margin-top:5px;display:flex;flex-direction:column;gap:4px;">
                                    @foreach($captReports as $rep)
                                    <a href="{{ route('clinic.medical-reports.show', $rep->id) }}"
                                       style="font-size:11.5px;color:#0e7490;text-decoration:none;display:flex;align-items:center;gap:6px;">
                                        <i class="fas fa-file-medical"></i>
                                        <strong>{{ $rep->title ?? ucfirst($rep->report_type ?? 'Report') }}</strong>
                                        @if($rep->report_date)
                                        <small class="text-muted">· {{ \Carbon\Carbon::parse($rep->report_date)->format('d M Y') }}</small>
                                        @endif
                                    </a>
                                    @endforeach
                                </div>
                            </div>
                            @endif

                            {{-- Item 5.2 — Documents attached to this visit (inline list with type icons). --}}
                            @if($capt->documents->count())
                            <div style="margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#546e7a;letter-spacing:.5px;">
                                    <i class="fas fa-paperclip"></i> Documents ({{ $capt->documents->count() }})
                                </span>
                                <div style="margin-top:5px;display:flex;flex-wrap:wrap;gap:5px;">
                                    @foreach($capt->documents as $doc)
                                    @php
                                        $dtype = $doc->document_type ?? 'other';
                                        $iconMap = [
                                            'lab_report'=>'fa-flask','xray'=>'fa-x-ray','prescription'=>'fa-prescription-bottle-alt',
                                            'consent_form'=>'fa-file-signature','discharge_summary'=>'fa-file-medical','other'=>'fa-file',
                                        ];
                                        $icon = $iconMap[$dtype] ?? 'fa-file';
                                    @endphp
                                    <a href="{{ method_exists($doc,'getUrlAttribute') ? $doc->url : '#' }}" target="_blank"
                                       style="font-size:11px;padding:3px 9px;border-radius:9px;background:#f1f5f9;color:#475569;border:1px solid #cbd5e1;text-decoration:none;">
                                        <i class="fas {{ $icon }}"></i>
                                        {{ $doc->original_name ?? $doc->file_name ?? basename($doc->file_path ?? '—') }}
                                        @if($doc->file_size_kb) <small style="opacity:.7;">· {{ $doc->file_size_kb }} KB</small>@endif
                                    </a>
                                    @endforeach
                                </div>
                            </div>
                            @endif

                            {{-- Item 5.2 — Consents signed for this visit (or linked to it). --}}
                            @php
                                $captConsents = collect();
                                if (method_exists($capt, 'consents') && $capt->relationLoaded('consents')) {
                                    $captConsents = $capt->consents;
                                } else {
                                    // Fall back to a direct query; safe if the table exists.
                                    if (\Schema::hasTable('clc_informed_consents')) {
                                        $captConsents = \DB::table('clc_informed_consents')
                                            ->where('appointment_id', $capt->id)
                                            ->select('id', 'consent_name', 'signed_at', 'signatory_name', 'status')
                                            ->get();
                                    }
                                }
                            @endphp
                            @if($captConsents && $captConsents->count())
                            <div style="margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;">
                                <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#f39c12;letter-spacing:.5px;">
                                    <i class="fas fa-file-signature"></i> Consents Signed
                                </span>
                                <div style="margin-top:5px;display:flex;flex-direction:column;gap:3px;">
                                    @foreach($captConsents as $cs)
                                    <div style="font-size:11.5px;color:#92400e;">
                                        <i class="fas fa-check-circle" style="color:#16a34a;"></i>
                                        <strong>{{ $cs->consent_name ?? 'Consent' }}</strong>
                                        @if($cs->signatory_name) — signed by {{ $cs->signatory_name }}@endif
                                        @if($cs->signed_at) <small class="text-muted">· {{ \Carbon\Carbon::parse($cs->signed_at)->format('d M Y') }}</small>@endif
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                            @endif

                            {{-- Linked: Appointment Notes count --}}
                            @if($captNotes->count())
                            <div style="margin-top:8px;">
                                <a href="{{ route('clinic.appointments.show', $capt->id) }}#tab-notes"
                                   style="font-size:11px;color:#64748b;">
                                    <i class="fa fa-sticky-note"></i>
                                    {{ $captNotes->count() }} clinical note{{ $captNotes->count()>1?'s':'' }} — view in appointment
                                </a>
                            </div>
                            @endif

                        </div>
                    </div>
                </div>
                @endforeach
                @endif

            </div>{{-- /tab-clinical --}}

            {{-- ══ PHOTOS (before/after clinical photography) ══ --}}
            <div id="tab-photos" class="tab-pane fade">
                @include('clinicCore::patients._photos_tab', ['patient' => $patient])
            </div>

            {{-- ══ TREATMENT PLANS (multi-session courses) ══ --}}
            <div id="tab-plans" class="tab-pane fade">
                @include('clinicCore::patients._plans_tab', ['patient' => $patient])
            </div>

            {{-- ══ DOCUMENTS & REPORTS ══ --}}
            <div id="tab-documents" class="tab-pane fade">

                @php
                    // Collect all appointment documents
                    $allAptDocs = collect();
                    foreach ($patient->appointments->sortByDesc('appointment_date') as $dApt) {
                        foreach ($dApt->documents as $doc) {
                            $allAptDocs->push([
                                'id'          => $doc->id,
                                'doc_name'    => $doc->document_name ?? null,
                                'description' => $doc->description ?? null,
                                'name'        => $doc->original_name ?? $doc->file_name ?? basename($doc->file_path ?? ''),
                                'type'        => $doc->document_type ?? 'other',
                                'type_label'  => $doc->type_label,
                                'date'        => $dApt->appointment_date,
                                'date_fmt'    => \Carbon\Carbon::parse($dApt->appointment_date)->format($dfmt),
                                'apt_ref'     => $dApt->ref_no,
                                'apt_id'      => $dApt->id,
                                'size_kb'     => $doc->file_size_kb,
                                'url'         => method_exists($doc,'getUrlAttribute') ? $doc->url : null,
                                'source'      => 'appointment',
                            ]);
                        }
                    }

                    // Medical reports
                    $docTypeColors = [
                        'lab_report'        => ['#2980b9','fa-flask'],
                        'xray'              => ['#2c3e50','fa-x-ray'],
                        'prescription'      => ['#8e44ad','fa-prescription-bottle-alt'],
                        'consent_form'      => ['#f39c12','fa-file-signature'],
                        'discharge_summary' => ['#27ae60','fa-file-medical'],
                        'other'             => ['#7f8c8d','fa-file'],
                    ];
                    $rptTypeColors = [
                        'lab'        => ['#2980b9','fa-flask'],
                        'xray'       => ['#2c3e50','fa-x-ray'],
                        'ultrasound' => ['#9b59b6','fa-wave-square'],
                        'ecg'        => ['#e74c3c','fa-heartbeat'],
                        'other'      => ['#7f8c8d','fa-file-medical-alt'],
                    ];
                @endphp

                {{-- Filter chips --}}
                <div class="tab-toolbar" id="doc_filter_toolbar" style="margin-bottom:14px;">
                    <button class="tc-chip tc-active doc-type-chip" data-doctype="all"
                        style="color:#475569;border-color:#475569;background:#475569;">
                        All ({{ $allAptDocs->count() + $patient->medicalReports->count() }})
                    </button>
                    @foreach($allAptDocs->groupBy('type') as $dtype => $dgroup)
                    @php [$dc,$di] = $docTypeColors[$dtype] ?? ['#7f8c8d','fa-file']; @endphp
                    <button class="tc-chip doc-type-chip" data-doctype="aptdoc_{{ $dtype }}"
                        style="color:{{ $dc }};border-color:{{ $dc }};">
                        <i class="fas {{ $di }}" style="font-size:9px;"></i>
                        {{ ($allAptDocs->firstWhere('type',$dtype)['type_label'] ?? ucfirst($dtype)) }}
                        ({{ $dgroup->count() }})
                    </button>
                    @endforeach
                    @if($patient->medicalReports->count())
                    <button class="tc-chip doc-type-chip" data-doctype="medreport"
                        style="color:#16a085;border-color:#16a085;">
                        <i class="fas fa-file-medical-alt" style="font-size:9px;"></i>
                        Medical Reports ({{ $patient->medicalReports->count() }})
                    </button>
                    @endif
                </div>

                {{-- ── Appointment Documents ── --}}
                @if($allAptDocs->isNotEmpty())
                <div class="doc-section" data-section="aptdocs" style="margin-bottom:18px;">
                    <div style="font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.6px;color:#546e7a;margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid #eceff1;">
                        <i class="fas fa-paperclip"></i> Appointment Documents
                    </div>
                    @foreach($allAptDocs as $adoc)
                    @php [$adc,$adi] = $docTypeColors[$adoc['type']] ?? ['#7f8c8d','fa-file']; @endphp
                    <div class="doc-row" data-doctype="aptdoc_{{ $adoc['type'] }}"
                         style="display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:6px;border:1px solid #e8ecf0;margin-bottom:5px;background:#fff;transition:box-shadow .12s;">
                        <div style="width:34px;height:34px;border-radius:8px;background:{{ $adc }}22;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                            <i class="fas {{ $adi }}" style="color:{{ $adc }};font-size:14px;"></i>
                        </div>
                        <div style="flex:1;min-width:0;">
                            <div style="font-size:13px;font-weight:600;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                {{ $adoc['doc_name'] ?? $adoc['name'] }}
                            </div>
                            @if($adoc['doc_name'])
                            <div style="font-size:11px;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:1px;">
                                <i class="fa fa-file" style="opacity:.5;"></i> {{ $adoc['name'] }}
                            </div>
                            @endif
                            @if($adoc['description'])
                            <div style="font-size:11px;color:#475569;margin-top:3px;line-height:1.4;">
                                {{ $adoc['description'] }}
                            </div>
                            @endif
                            <div style="font-size:11px;color:#94a3b8;margin-top:3px;">
                                <span style="font-size:10px;font-weight:700;padding:1px 7px;border-radius:8px;background:{{ $adc }}22;color:{{ $adc }};">{{ $adoc['type_label'] }}</span>
                                &nbsp; {{ $adoc['date_fmt'] }}
                                &nbsp;·&nbsp; Apt: <a href="{{ route('clinic.appointments.show', $adoc['apt_id']) }}" style="color:#64748b;">#{{ $adoc['apt_ref'] }}</a>
                                @if($adoc['size_kb']) &nbsp;·&nbsp; {{ $adoc['size_kb'] }} KB @endif
                            </div>
                        </div>
                        @if($adoc['url'])
                        <div class="btn-group" style="flex-shrink:0;">
                            <button class="btn btn-xs btn-info btn-doc-preview"
                                data-url="{{ $adoc['url'] }}"
                                data-name="{{ $adoc['doc_name'] ?? $adoc['name'] }}"
                                title="Preview">
                                <i class="fa fa-eye"></i>
                            </button>
                            <a href="{{ $adoc['url'] }}" target="_blank" class="btn btn-xs btn-default" title="Download">
                                <i class="fa fa-download"></i>
                            </a>
                        </div>
                        @endif
                    </div>
                    @endforeach
                </div>
                @endif

                {{-- ── Medical Reports ── --}}
                @if($patient->medicalReports->isNotEmpty())
                <div class="doc-section" data-section="medreports">
                    <div style="font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.6px;color:#16a085;margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid #ccfbf1;">
                        <i class="fas fa-file-medical-alt"></i> Medical Reports
                    </div>
                    @foreach($patient->medicalReports as $mrpt)
                    @php [$mrc,$mri] = $rptTypeColors[$mrpt->report_type ?? 'other'] ?? ['#7f8c8d','fa-file-medical-alt']; @endphp
                    <div class="doc-row" data-doctype="medreport"
                         style="border:1px solid #e8ecf0;border-radius:8px;margin-bottom:8px;background:#fff;overflow:hidden;">
                        <div style="padding:10px 14px;display:flex;align-items:center;gap:10px;">
                            <div style="width:36px;height:36px;border-radius:8px;background:{{ $mrc }}22;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                <i class="fas {{ $mri }}" style="color:{{ $mrc }};font-size:15px;"></i>
                            </div>
                            <div style="flex:1;min-width:0;">
                                <div style="font-size:13px;font-weight:700;color:#1e293b;">{{ $mrpt->report_title }}</div>
                                <div style="font-size:11px;color:#94a3b8;margin-top:2px;display:flex;gap:10px;flex-wrap:wrap;">
                                    <span style="font-size:10px;font-weight:700;padding:1px 7px;border-radius:8px;background:{{ $mrc }}22;color:{{ $mrc }};">
                                        {{ ucfirst($mrpt->report_type ?? 'Other') }}
                                    </span>
                                    @if(optional($mrpt->doctor)->name)
                                    <span><i class="fas fa-user-md"></i> {{ $mrpt->doctor->name }}</span>
                                    @endif
                                    <span><i class="fa fa-calendar"></i> {{ $mrpt->created_at->format($dfmt) }}</span>
                                    @if($mrpt->appointment_id)
                                    <a href="{{ route('clinic.appointments.show', $mrpt->appointment_id) }}" style="color:#64748b;">
                                        <i class="fa fa-calendar-check"></i> View Appointment
                                    </a>
                                    @endif
                                </div>
                            </div>
                        </div>
                        @if($mrpt->findings)
                        <div style="padding:0 14px 10px 60px;">
                            <div style="font-size:11px;font-weight:700;color:#64748b;margin-bottom:3px;">Findings</div>
                            <div style="font-size:12px;color:#334155;background:#f8fafc;border-radius:5px;padding:8px 10px;border:1px solid #e2e8f0;white-space:pre-wrap;max-height:120px;overflow-y:auto;">{{ $mrpt->findings }}</div>
                        </div>
                        @endif
                        @if(!empty($mrpt->attachments))
                        <div style="padding:0 14px 10px 60px;display:flex;flex-wrap:wrap;gap:5px;">
                            @foreach($mrpt->attachments as $att)
                            @php
                                $attUrl  = is_array($att) ? ($att['url'] ?? null) : (is_string($att) ? $att : null);
                                $attName = is_array($att) ? ($att['name'] ?? 'Attachment') : 'Attachment';
                            @endphp
                            @if($attUrl)
                            <span style="display:inline-flex;align-items:center;gap:2px;border-radius:8px;background:#f1f5f9;border:1px solid #e2e8f0;overflow:hidden;">
                                <button class="btn-doc-preview"
                                    data-url="{{ $attUrl }}"
                                    data-name="{{ $attName }}"
                                    title="Preview"
                                    style="background:none;border:none;padding:2px 7px;cursor:pointer;color:#2980b9;font-size:11px;">
                                    <i class="fa fa-eye"></i>
                                </button>
                                <a href="{{ $attUrl }}" target="_blank"
                                   style="font-size:11px;font-weight:600;padding:2px 9px;color:#475569;text-decoration:none;">
                                    <i class="fa fa-paperclip"></i> {{ $attName }}
                                </a>
                            </span>
                            @endif
                            @endforeach
                        </div>
                        @endif
                    </div>
                    @endforeach
                </div>
                @endif

                @if($allAptDocs->isEmpty() && $patient->medicalReports->isEmpty())
                <div style="text-align:center;padding:40px;color:#94a3b8;">
                    <i class="fas fa-folder-open" style="font-size:36px;opacity:.3;display:block;margin-bottom:10px;"></i>
                    No documents or medical reports found.
                </div>
                @endif

            </div>{{-- /tab-documents --}}

            {{-- ── Document Preview Modal ─────────────────────────────── --}}
            <div class="modal fade" id="docPreviewModal" tabindex="-1" role="dialog">
                <div class="modal-dialog" style="width:90%;max-width:960px;" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="padding:10px 16px;background:#1e293b;">
                            <button type="button" class="close" data-dismiss="modal"
                                style="color:#fff;opacity:.8;font-size:15px;margin-top:-2px;">&times;</button>
                            <h4 class="modal-title" id="docPreviewModalTitle"
                                style="color:#fff;font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:10px;">
                                Preview
                            </h4>
                        </div>
                        <div class="modal-body" id="docPreviewBody"
                             style="padding:0;min-height:200px;background:#0f172a;display:flex;align-items:center;justify-content:center;">
                            <div id="docPreviewSpinner" style="color:#94a3b8;padding:40px;text-align:center;">
                                <i class="fa fa-spinner fa-spin fa-2x"></i>
                            </div>
                        </div>
                        <div class="modal-footer" style="padding:8px 14px;background:#f8fafc;text-align:left;">
                            <a id="docPreviewDownload" href="#" target="_blank"
                               class="btn btn-sm btn-default">
                                <i class="fa fa-download"></i> Download
                            </a>
                            <button type="button" class="btn btn-sm btn-default pull-right" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>

            {{-- ══ NX600 LAB ══ --}}
            @if(false /* NX600Lab analyzer is vet-only; disabled in ClinicCore */)
            <div id="tab-lab" class="tab-pane fade">
                @include('nx600Lab::bridge.pet_lab_panel', ['pet' => $patient])
            </div>
            @endif

        </div>{{-- /tab-content --}}
    </div>{{-- /col-md-9 --}}

</div>{{-- /row --}}

@include('clinicCore::partials.notes_panel', [
    'subjectType' => 'pet',
    'subjectId'   => $patient->id,
])

@include('clinicCore::partials._ai_panel')

</section>

{{-- ══ MODALS ══ --}}

{{-- Mark Deceased --}}
<div class="modal fade" id="deceasedModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header" style="background:#c0392b;color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fas fa-heart-broken"></i> Mark as Deceased</h4>
            </div>
            <div class="modal-body">
                <p class="text-danger" style="font-size:13px;">
                    This will mark <strong>{{ $patient->patient_name }}</strong> as deceased and stop new appointments.
                </p>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">Date of Death <span class="text-danger">*</span></label>
                    <input type="text" id="deceased_date_display" class="form-control input-sm" autocomplete="off">
                    <input type="hidden" id="deceased_date_iso" value="{{ date('Y-m-d') }}">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                <button class="btn btn-danger btn-sm" id="btn_mark_deceased">Confirm</button>
            </div>
        </div>
    </div>
</div>

{{-- Add Condition --}}
<div class="modal fade" id="addConditionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                <h4 class="modal-title">@lang('clinicCore::lang.add_condition')</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.condition') <span class="text-danger">*</span></label>
                    <select id="condition_id" class="form-control select2-condition" style="width:100%"></select>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.severity')</label>
                            <select id="condition_severity" class="form-control input-sm">
                                <option value="">— Select —</option>
                                <option value="mild">Mild</option>
                                <option value="moderate">Moderate</option>
                                <option value="severe">Severe</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">Status</label>
                            <select id="condition_status" class="form-control input-sm">
                                <option value="active">Active</option>
                                <option value="chronic">Chronic</option>
                                <option value="resolved">Resolved</option>
                            </select>
                        </div>
                    </div>
                </div>
                {{-- P3-T8 problem-list: certainty + structured type --}}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.certainty')</label>
                            <select id="condition_certainty" class="form-control input-sm">
                                <option value="">—</option>
                                @foreach(\Modules\ClinicCore\Entities\ClcPatientCondition::CERTAINTIES as $c)
                                    <option value="{{ $c }}">@lang('clinicCore::lang.certainty_' . $c)</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.problem_type')</label>
                            <select id="condition_type" class="form-control input-sm">
                                <option value="">—</option>
                                @foreach(\Modules\ClinicCore\Entities\ClcPatientCondition::CONDITION_TYPES as $ct)
                                    <option value="{{ $ct }}">@lang('clinicCore::lang.problem_type_' . $ct)</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.diagnosed_date')</label>
                    <input type="text" id="condition_date_display" class="form-control input-sm" autocomplete="off">
                    <input type="hidden" id="condition_date_iso" value="{{ date('Y-m-d') }}">
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.notes')</label>
                    <textarea id="condition_notes" class="form-control input-sm" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                <button class="btn btn-primary btn-sm" id="btn_add_condition">@lang('clinicCore::lang.save')</button>
            </div>
        </div>
    </div>
</div>

{{-- Edit Condition --}}
<div class="modal fade" id="editConditionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fas fa-disease"></i> Edit Medical Condition</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_pc_id">
                <div style="font-weight:700;font-size:14px;color:#1e293b;margin-bottom:14px;padding:8px 10px;background:#f8fafc;border-radius:6px;border-left:3px solid #e74c3c;" id="edit_pc_condition_name"></div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.severity')</label>
                            <select id="edit_condition_severity" class="form-control input-sm">
                                <option value="">— Select —</option>
                                <option value="mild">Mild</option>
                                <option value="moderate">Moderate</option>
                                <option value="severe">Severe</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">Status</label>
                            <select id="edit_condition_status" class="form-control input-sm">
                                <option value="active">Active</option>
                                <option value="chronic">Chronic</option>
                                <option value="resolved">Resolved</option>
                            </select>
                        </div>
                    </div>
                </div>
                {{-- P3-T8 problem-list: certainty + structured type --}}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.certainty')</label>
                            <select id="edit_condition_certainty" class="form-control input-sm">
                                <option value="">—</option>
                                @foreach(\Modules\ClinicCore\Entities\ClcPatientCondition::CERTAINTIES as $c)
                                    <option value="{{ $c }}">@lang('clinicCore::lang.certainty_' . $c)</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.problem_type')</label>
                            <select id="edit_condition_type" class="form-control input-sm">
                                <option value="">—</option>
                                @foreach(\Modules\ClinicCore\Entities\ClcPatientCondition::CONDITION_TYPES as $ct)
                                    <option value="{{ $ct }}">@lang('clinicCore::lang.problem_type_' . $ct)</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.diagnosed_date')</label>
                    <input type="text" id="edit_condition_date_display" class="form-control input-sm" autocomplete="off">
                    <input type="hidden" id="edit_condition_date_iso">
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.notes')</label>
                    <textarea id="edit_condition_notes" class="form-control input-sm" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                <button class="btn btn-primary btn-sm" id="btn_update_condition"><i class="fa fa-save"></i> @lang('clinicCore::lang.update')</button>
            </div>
        </div>
    </div>
</div>

{{-- Edit Treatment --}}
<div class="modal fade" id="editTreatmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background:#2471a3;color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;opacity:1;font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fas fa-syringe"></i> Edit Vaccination Record</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_vax_id">
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.vaccine_type') <span class="text-danger">*</span></label>
                            <select id="edit_vax_vaccine_type_id" class="form-control select2-edit-vaccine" style="width:100%"></select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">Treatment Status</label>
                            <select id="edit_vax_taken_status" class="form-control input-sm">
                                <option value="taken_in">🏥 At Clinic (Taken In)</option>
                                <option value="taken_out">🏠 External (Taken Out)</option>
                                <option value="not_taken">⏳ Not Taken / Scheduled</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.dose')</label>
                    <input type="text" id="edit_vax_dose" class="form-control input-sm" placeholder="e.g. 1 ml, Booster, 1st dose">
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.administered_date')</label>
                            <input type="text" id="edit_vax_date_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="edit_vax_date_iso">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.next_due_date')
                                <small class="text-muted" id="edit_vax_auto_calc_hint" style="font-weight:400;">@lang('clinicCore::lang.auto_calculated')</small>
                            </label>
                            <input type="text" id="edit_vax_next_due_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="edit_vax_next_due_iso">
                        </div>
                    </div>
                </div>
                <div class="form-group" style="margin-top:-6px;margin-bottom:10px;padding:8px 12px;background:#fff8f8;border-radius:6px;border:1px solid #fecaca;">
                    <label style="font-size:12px;font-weight:600;color:#c0392b;margin:0;cursor:pointer;">
                        <input type="checkbox" id="edit_vax_last_dose" style="margin-right:6px;">
                        <i class="fas fa-stop-circle"></i> Last dose — no next due date needed
                    </label>
                    <div style="font-size:11px;color:#888;margin-top:2px;margin-left:20px;">Check this if this vaccine will not be repeated again.</div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.batch_no')</label>
                            <input type="text" id="edit_vax_batch" class="form-control input-sm">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.weight_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.01" id="edit_vax_weight" class="form-control">
                                <span class="input-group-addon">kg</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.temperature_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.1" id="edit_vax_temperature" class="form-control" placeholder="38.5">
                                <span class="input-group-addon">°C</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.notes')</label>
                    <textarea id="edit_vax_notes" class="form-control input-sm" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer" style="display:flex;justify-content:space-between;align-items:center;">
                <button class="btn btn-danger btn-sm" id="btn_delete_vaccination">
                    <i class="fa fa-trash"></i> Delete Record
                </button>
                <div>
                    <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                    <button class="btn btn-primary btn-sm" id="btn_update_vaccination"><i class="fa fa-save"></i> @lang('clinicCore::lang.update')</button>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Add Treatment --}}
<div class="modal fade" id="addTreatmentModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background:#2980b9;color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fas fa-syringe"></i> @lang('clinicCore::lang.add_vaccination')</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.vaccine_type') <span class="text-danger">*</span></label>
                    <select id="vax_vaccine_type_id" class="form-control select2-vaccine" style="width:100%"></select>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">Treatment Status</label>
                    <select id="vax_taken_status" class="form-control input-sm">
                        <option value="taken_in">🏥 At Clinic (Taken In)</option>
                        <option value="taken_out">🏠 External (Taken Out)</option>
                        <option value="not_taken">⏳ Not Taken / Scheduled</option>
                    </select>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.dose')</label>
                    <input type="text" id="vax_dose" class="form-control input-sm" placeholder="e.g. 1 ml, Booster, 1st dose">
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.administered_date') <span class="text-danger">*</span></label>
                            <input type="text" id="vax_date_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="vax_date_iso">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.next_due_date') <small class="text-muted">@lang('clinicCore::lang.auto_calculated')</small></label>
                            <input type="text" id="vax_next_due_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="vax_next_due_iso">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.batch_no')</label>
                            <input type="text" id="vax_batch" class="form-control input-sm">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.weight_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.01" id="vax_weight" class="form-control"
                                       value="{{ isset($lastWeightRecord) ? $lastWeightRecord['weight'] : '' }}">
                                <span class="input-group-addon">kg</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.temperature_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.1" id="vax_temperature" class="form-control" placeholder="38.5">
                                <span class="input-group-addon">°C</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('clinicCore::lang.notes')</label>
                    <textarea id="vax_notes" class="form-control input-sm" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                <button class="btn btn-primary btn-sm" id="btn_add_vaccination"><i class="fa fa-save"></i> @lang('clinicCore::lang.save')</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
$(document).ready(function () {

    /* ── Hash-based tab activation (weight history links) ─── */
    (function () {
        function showHashTab() {
            var h = window.location.hash;
            if (h) { var $t = $('#petTabs a[href="' + h + '"]'); if ($t.length) { $t.tab('show'); } }
        }
        showHashTab();
        $(window).on('hashchange', showHashTab);
    })();

    /* ── Condition Select2 ─────────────────────── */
    $('.select2-condition').select2({
        width: '100%', minimumInputLength: 1,
        ajax: {
            url: '{{ route('clinic.medical-conditions.search') }}',
            dataType: 'json', delay: 250,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return { results: d }; }
        },
        placeholder: 'Search condition…'
    });

    /* ── Condition date picker ─────────────────── */
    $('#addConditionModal').on('shown.bs.modal', function () {
        $('#condition_date_display').datepicker('destroy').datepicker({
            todayHighlight: true, autoclose: true,
            format: datepicker_date_format, endDate: new Date()
        }).on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#condition_date_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth()+1).padStart(2,'0') + '-' +
                    String(d.getDate()).padStart(2,'0')
                );
            }
        });
        $('#condition_date_display').datepicker('setDate', new Date());
    });

    $('#btn_add_condition').on('click', function () {
        $.ajax({
            url: '{{ route('clinic.patients.conditions.add', $patient->id) }}',
            method: 'POST',
            data: {
                _token:         '{{ csrf_token() }}',
                condition_id:   $('#condition_id').val(),
                severity:       $('#condition_severity').val(),
                status:         $('#condition_status').val(),
                diagnosed_date: $('#condition_date_iso').val(),
                notes:          $('#condition_notes').val(),
                certainty:      $('#condition_certainty').val(),
                condition_type: $('#condition_type').val()
            },
            success: function (res) { if (res.success) { $('#addConditionModal').modal('hide'); location.reload(); } },
            error:   function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
        });
    });

    /* ── Treatment Modal ─────────────────────── */
    var validForMonths = 12;

    $('#addTreatmentModal').on('shown.bs.modal', function () {
        // Date pickers
        $('#vax_date_display, #vax_next_due_display').datepicker('destroy').datepicker({
            todayHighlight: true, autoclose: true,
            format: datepicker_date_format
        });
        $('#vax_date_display').on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                var iso = d.getFullYear() + '-' +
                          String(d.getMonth()+1).padStart(2,'0') + '-' +
                          String(d.getDate()).padStart(2,'0');
                $('#vax_date_iso').val(iso);
                updateNextDue();
            }
        });
        $('#vax_next_due_display').on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#vax_next_due_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth()+1).padStart(2,'0') + '-' +
                    String(d.getDate()).padStart(2,'0')
                );
            }
        });
        // Set today as default for administered date
        var today = new Date();
        $('#vax_date_display').datepicker('setDate', today);
        $('#vax_date_iso').val(
            today.getFullYear() + '-' +
            String(today.getMonth()+1).padStart(2,'0') + '-' +
            String(today.getDate()).padStart(2,'0')
        );
    });

    /* ── Treatment Type Select2 ──────────────────── */
    $('.select2-vaccine').select2({
        width: '100%', minimumInputLength: 1,
        dropdownParent: $('#addTreatmentModal'),
        ajax: {
            url: '{{ route('clinic.vaccine-types.search') }}',
            dataType: 'json', delay: 250,
            data: function (p) { return { q: p.term, species: '{{ strtolower($patient->species ?? '') }}' }; },
            processResults: function (d) { return { results: d }; }
        },
        templateResult: function (d) {
            if (!d.id) return d.text;
            var catColors = { 'core_vaccine':'primary','non_core_vaccine':'info','deworming':'success','spot_on':'warning','other':'default' };
            var color = catColors[d.category] || 'default';
            var badge = d.category_label ? ' <span class="label label-' + color + '" style="font-size:10px;">' + d.category_label + '</span>' : '';
            var mfr   = d.manufacturer ? '<br><small style="color:#aaa;">' + d.manufacturer + '</small>' : '';
            return $('<span>' + d.text + badge + mfr + '</span>');
        },
        templateSelection: function (d) { return d.text || d.id; },
        placeholder: 'Search vaccine…'
    }).on('select2:select', function (e) {
        validForMonths = e.params.data.valid_for_months || 12;
        updateNextDue();
    });

    function updateNextDue() {
        var isoVal = $('#vax_date_iso').val();
        if (!isoVal) return;
        var parts = isoVal.split('-');
        // Use local midnight to avoid timezone offset shifting the date via getUTC*
        var nd = new Date(+parts[0], +parts[1]-1, +parts[2]);
        nd.setMonth(nd.getMonth() + parseInt(validForMonths));
        var ndIso = nd.getFullYear() + '-' +
                    String(nd.getMonth()+1).padStart(2,'0') + '-' +
                    String(nd.getDate()).padStart(2,'0');
        $('#vax_next_due_iso').val(ndIso);
        $('#vax_next_due_display').datepicker('setDate', nd);
    }

    $('#btn_add_vaccination').on('click', function () {
        $.ajax({
            url: '{{ route('clinic.vaccinations.store') }}',
            method: 'POST',
            data: {
                _token:              '{{ csrf_token() }}',
                patient_id:              {{ $patient->id }},
                vaccine_type_id:     $('#vax_vaccine_type_id').val(),
                taken_status:        $('#vax_taken_status').val(),
                dose:                $('#vax_dose').val(),
                administered_date:   $('#vax_date_iso').val(),
                next_due_date:       $('#vax_next_due_iso').val(),
                batch_no:            $('#vax_batch').val(),
                weight_at_time:      $('#vax_weight').val(),
                temperature_at_time: $('#vax_temperature').val(),
                notes:               $('#vax_notes').val()
            },
            success: function (res) { if (res.success) { $('#addTreatmentModal').modal('hide'); location.reload(); } },
            error:   function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
        });
    });

    /* ── Initialize active vax-chip background on load ─── */
    $('.vax-chip.active').each(function () {
        var c = $(this).data('color');
        if (c) $(this).css({ background: c, color: '#fff', borderColor: c });
    });

    /* ── Treatment card/list view toggle ─── */
    var _vaxView = 'card';
    $('#vax_view_card').on('click', function () {
        _vaxView = 'card';
        $(this).addClass('active'); $('#vax_view_list').removeClass('active');
        $('#vax-cards').show(); $('#vax-list-view').hide();
    });
    $('#vax_view_list').on('click', function () {
        _vaxView = 'list';
        $(this).addClass('active'); $('#vax_view_card').removeClass('active');
        $('#vax-list-view').show(); $('#vax-cards').hide();
        // Apply current filters to list rows too
        _syncVaxListFilters();
    });

    function _syncVaxListFilters() {
        $('#vax-list-body .vax-list-row').each(function () {
            var show = (!_vaxDsFilter    || $(this).data('vax-ds')       === _vaxDsFilter)
                    && (!_vaxTakenFilter || $(this).data('vax-taken')    === _vaxTakenFilter)
                    && (!_vaxCatFilter   || $(this).data('vax-category') === _vaxCatFilter);
            $(this).toggle(show);
        });
    }

    /* ── Treatment filter chips (due-status) ─── */
    var _vaxDsFilter    = '';
    var _vaxTakenFilter = '';
    var _vaxCatFilter   = '';

    function applyVaxFilters() {
        $('#vax-cards .vax-pcard').each(function () {
            var show = (!_vaxDsFilter    || $(this).data('vax-ds')       === _vaxDsFilter)
                    && (!_vaxTakenFilter || $(this).data('vax-taken')    === _vaxTakenFilter)
                    && (!_vaxCatFilter   || $(this).data('vax-category') === _vaxCatFilter);
            $(this).toggle(show);
        });
        if (_vaxView === 'list') { _syncVaxListFilters(); }
    }

    $('.vax-chip').on('click', function () {
        var filter = $(this).data('vax-filter');
        var color  = $(this).data('color');
        $('.vax-chip').each(function () {
            $(this).removeClass('active').css({ background:'', color: $(this).data('color') });
        });
        $(this).addClass('active').css({ background: color, color:'#fff' });
        _vaxDsFilter = (filter === 'all') ? '' : filter;
        applyVaxFilters();
    });

    $(document).on('click', '.vax-taken-chip', function () {
        var $this = $(this);
        var val   = $this.data('taken');
        $('.vax-taken-chip').each(function () {
            var c = $(this).data('color') || '#64748b';
            $(this).css({ background: 'transparent', color: c, borderColor: c });
        });
        var ac = $this.data('color') || '#64748b';
        $this.css({ background: ac, color: '#fff', borderColor: ac });
        _vaxTakenFilter = val;
        applyVaxFilters();
    });

    $(document).on('click', '.vax-cat-chip', function () {
        var $this = $(this);
        var val   = $this.data('cat');
        $('.vax-cat-chip').each(function () {
            var c = $(this).data('color') || '#64748b';
            $(this).css({ background: 'transparent', color: c, borderColor: c });
        });
        var ac = $this.data('color') || '#64748b';
        $this.css({ background: ac, color: '#fff', borderColor: ac });
        _vaxCatFilter = val;
        applyVaxFilters();
    });

    /* ── Mark Deceased ─────────────────────────── */
    $('#deceasedModal').on('shown.bs.modal', function () {
        $('#deceased_date_display').datepicker('destroy').datepicker({
            todayHighlight: true, autoclose: true,
            format: datepicker_date_format, endDate: new Date()
        }).on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#deceased_date_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth()+1).padStart(2,'0') + '-' +
                    String(d.getDate()).padStart(2,'0')
                );
            }
        });
        $('#deceased_date_display').datepicker('setDate', new Date());
    });

    $('#btn_mark_deceased').on('click', function () {
        $.ajax({
            url:    '{{ route('clinic.patients.mark-deceased', $patient->id) }}',
            method: 'POST',
            data:   { _token: '{{ csrf_token() }}', deceased_date: $('#deceased_date_iso').val() },
            success: function (res) { if (res.success) { location.reload(); } },
            error:   function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
        });
    });

    /* ── Remove Condition ──────────────────────── */
    $(document).on('click', '.btn-remove-condition', function (e) {
        e.preventDefault();
        if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
        var id = $(this).data('id');
        $.ajax({
            url:    '{{ url('clinic/patients/conditions') }}/' + id,
            method: 'DELETE',
            data:   { _token: '{{ csrf_token() }}' },
            success: function (res) { if (res.success) location.reload(); }
        });
    });

    /* ── Edit Condition ────────────────────────── */
    $(document).on('click', '.btn-edit-condition', function () {
        var btn = $(this);
        $('#edit_pc_id').val(btn.data('id'));
        $('#edit_pc_condition_name').text(btn.data('name') || 'Condition');
        $('#edit_condition_severity').val(btn.data('severity') || '');
        $('#edit_condition_status').val(btn.data('status') || 'active');
        $('#edit_condition_date_iso').val(btn.data('date-iso') || '');
        $('#edit_condition_notes').val(btn.data('notes') || '');
        $('#edit_condition_certainty').val(btn.data('certainty') || '');
        $('#edit_condition_type').val(btn.data('condition-type') || '');
        $('#editConditionModal').modal('show');
    });

    $('#editConditionModal').on('shown.bs.modal', function () {
        $('#edit_condition_date_display').datepicker('destroy').datepicker({
            todayHighlight: true, autoclose: true,
            format: datepicker_date_format, endDate: new Date()
        }).on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#edit_condition_date_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth()+1).padStart(2,'0') + '-' +
                    String(d.getDate()).padStart(2,'0')
                );
            }
        });
        var iso = $('#edit_condition_date_iso').val();
        if (iso) {
            var p = iso.split('-');
            $('#edit_condition_date_display').datepicker('setDate', new Date(+p[0], +p[1]-1, +p[2]));
        }
    });

    $('#btn_update_condition').on('click', function () {
        $.ajax({
            url:    '{{ url('clinic/patients/conditions') }}/' + $('#edit_pc_id').val() + '/update',
            method: 'POST',
            data:   {
                _token:         '{{ csrf_token() }}',
                severity:       $('#edit_condition_severity').val(),
                status:         $('#edit_condition_status').val(),
                diagnosed_date: $('#edit_condition_date_iso').val(),
                notes:          $('#edit_condition_notes').val(),
                certainty:      $('#edit_condition_certainty').val(),
                condition_type: $('#edit_condition_type').val()
            },
            success: function (res) { if (res.success) { $('#editConditionModal').modal('hide'); location.reload(); } },
            error:   function () { toastr.error('Error updating condition.'); }
        });
    });

    /* ── Edit Treatment (deferred-data pattern) ─ */
    var _editVaxPending = {};
    var _editVaxDpReady = false;
    var _editVaxValidForMonths = 12;

    function _isoToLocal(iso) { var p = iso.split('-'); return new Date(+p[0], +p[1]-1, +p[2]); }

    function _editVaxCalcNextDue() {
        if ($('#edit_vax_last_dose').is(':checked')) return;
        var ai = $('#edit_vax_date_iso').val();
        if (!ai || !_editVaxValidForMonths) return;
        // Use local midnight to avoid UTC offset shifting the date
        var nd = _isoToLocal(ai);
        nd.setMonth(nd.getMonth() + parseInt(_editVaxValidForMonths));
        var ndIso = nd.getFullYear() + '-' + String(nd.getMonth()+1).padStart(2,'0') + '-' + String(nd.getDate()).padStart(2,'0');
        $('#edit_vax_next_due_iso').val(ndIso);
        if (_editVaxDpReady) { try { $('#edit_vax_next_due_display').datepicker('setDate', nd); } catch(e){} }
    }

    function _applyEditVaxData(data) {
        $('#edit_vax_dose').val(data.dose || '');
        $('#edit_vax_batch').val(data.batch_no || '');
        $('#edit_vax_weight').val(data.weight_at_time || '');
        $('#edit_vax_temperature').val(data.temperature_at_time || '');
        $('#edit_vax_notes').val(data.notes || '');
        $('#edit_vax_taken_status').val(data.taken_status || 'taken_in');
        var ai = data.administered_date_iso || (typeof data.administered_date === 'string' ? data.administered_date.substring(0,10) : '');
        var ni = data.next_due_date_iso     || (typeof data.next_due_date     === 'string' ? data.next_due_date.substring(0,10) : '');
        // "Last dose" checkbox: check if no next_due_date exists
        var isLastDose = !ni;
        $('#edit_vax_last_dose').prop('checked', isLastDose);
        $('#edit_vax_next_due_display, #edit_vax_next_due_iso').prop('disabled', isLastDose);
        $('#edit_vax_auto_calc_hint').toggle(!isLastDose);
        if (ai) {
            $('#edit_vax_date_iso').val(ai);
            if (_editVaxDpReady) { try { $('#edit_vax_date_display').datepicker('setDate', _isoToLocal(ai)); } catch(e) {} }
        }
        if (ni && !isLastDose) {
            $('#edit_vax_next_due_iso').val(ni);
            if (_editVaxDpReady) { try { $('#edit_vax_next_due_display').datepicker('setDate', _isoToLocal(ni)); } catch(e) {} }
        } else if (isLastDose) {
            $('#edit_vax_next_due_display').val('');
            $('#edit_vax_next_due_iso').val('');
        }
        if (data.vaccine_type_id && data.vaccine_type_name) {
            var opt = new Option(data.vaccine_type_name, data.vaccine_type_id, true, true);
            $('#edit_vax_vaccine_type_id').empty().append(opt).trigger('change');
        }
    }

    $('#editTreatmentModal').on('shown.bs.modal', function () {
        $('#edit_vax_date_display').datepicker('destroy').datepicker({ todayHighlight:true, autoclose:true, format:datepicker_date_format })
            .on('changeDate', function(e) {
                if (e.dates.length) {
                    var d = e.dates[0];
                    $('#edit_vax_date_iso').val(d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0'));
                    _editVaxCalcNextDue();
                }
            });
        $('#edit_vax_next_due_display').datepicker('destroy').datepicker({ todayHighlight:true, autoclose:true, format:datepicker_date_format })
            .on('changeDate', function(e) { if(e.dates.length){var d=e.dates[0];$('#edit_vax_next_due_iso').val(d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0'));} });
        _editVaxDpReady = true;
        if (_editVaxPending && _editVaxPending.id) { _applyEditVaxData(_editVaxPending); }

        if (!$('.select2-edit-vaccine').data('select2')) {
            $('.select2-edit-vaccine').select2({
                width: '100%', minimumInputLength: 1, dropdownParent: $('#editTreatmentModal'),
                ajax: { url: '{{ route('clinic.vaccine-types.search') }}', dataType:'json', delay:250,
                    data: function(p){return{q:p.term,species:'{{ strtolower($patient->species ?? '') }}'};},
                    processResults: function(d){return{results:d};} },
                templateResult: function(d){if(!d.id)return d.text;return $('<span>'+d.text+(d.category_label?' <span class="label label-default" style="font-size:9px;">'+d.category_label+'</span>':'')+'</span>');},
                templateSelection: function(d){return d.text||d.id;},
                placeholder:'Search vaccine…'
            }).on('select2:select', function(e) {
                var vtData = e.params.data;
                _editVaxValidForMonths = vtData.valid_for_months || 12;
                _editVaxCalcNextDue();
            });
        }
    });

    /* ── Last dose checkbox ────────────────────── */
    $('#edit_vax_last_dose').on('change', function() {
        var isLast = $(this).is(':checked');
        $('#edit_vax_next_due_display').prop('disabled', isLast).val(isLast ? '' : '');
        $('#edit_vax_next_due_iso').val('').prop('disabled', isLast);
        $('#edit_vax_auto_calc_hint').toggle(!isLast);
        if (!isLast) { _editVaxCalcNextDue(); }
    });

    $('#editTreatmentModal').on('hidden.bs.modal', function () {
        _editVaxDpReady = false; _editVaxPending = {};
        $('#edit_vax_last_dose').prop('checked', false);
        $('#edit_vax_next_due_display, #edit_vax_next_due_iso').prop('disabled', false);
    });

    function openVaxEdit(id, name, vaccineTypeId) {
        _editVaxPending = {}; _editVaxDpReady = false;
        $('#edit_vax_id').val(id);
        $('#edit_vax_dose,#edit_vax_batch,#edit_vax_notes').val('');
        $('#edit_vax_weight,#edit_vax_temperature').val('');
        $('#edit_vax_date_iso,#edit_vax_next_due_iso').val('');
        $('#edit_vax_date_display,#edit_vax_next_due_display').val('');
        if (name && vaccineTypeId) {
            $('#edit_vax_vaccine_type_id').empty().append(new Option(name, vaccineTypeId, true, true)).trigger('change');
        }
        $('#editTreatmentModal').modal('show');
        $.getJSON('{{ url('clinic/vaccinations') }}/' + id + '/edit', function(data) {
            _editVaxPending = data;
            if (_editVaxDpReady) { _applyEditVaxData(data); }
        });
    }

    $(document).on('click', '.btn-edit-vax-inline, .vpc-name-clickable', function(e) {
        e.stopPropagation();
        openVaxEdit($(this).data('id'), $(this).data('name'), $(this).data('vaccine-type-id'));
    });

    $('#btn_update_vaccination').on('click', function () {
        var vaxId = $('#edit_vax_id').val(); if (!vaxId) return;
        var nextDue = $('#edit_vax_last_dose').is(':checked') ? '' : $('#edit_vax_next_due_iso').val();
        $.ajax({
            url: '{{ url('clinic/vaccinations') }}/' + vaxId + '/update', method: 'POST',
            data: { _token:'{{ csrf_token() }}', vaccine_type_id:$('#edit_vax_vaccine_type_id').val(),
                    taken_status:$('#edit_vax_taken_status').val(), dose:$('#edit_vax_dose').val(),
                    administered_date:$('#edit_vax_date_iso').val(), next_due_date: nextDue,
                    batch_no:$('#edit_vax_batch').val(), weight_at_time:$('#edit_vax_weight').val(),
                    temperature_at_time:$('#edit_vax_temperature').val(), notes:$('#edit_vax_notes').val() },
            success: function(res) { if(res.success){toastr.success(res.msg||'Updated.');$('#editTreatmentModal').modal('hide');location.reload();} },
            error: function() { toastr.error('Error updating.'); }
        });
    });

    $('#btn_delete_vaccination').on('click', function () {
        if (!confirm('@lang('clinicCore::lang.confirm_delete')')) return;
        $.ajax({
            url: '{{ url('clinic/vaccinations') }}/' + $('#edit_vax_id').val(), method: 'DELETE',
            data: { _token: '{{ csrf_token() }}' },
            success: function(res) { if(res.success){toastr.success(res.msg||'Deleted.');$('#editTreatmentModal').modal('hide');location.reload();} },
            error: function() { toastr.error('Error deleting.'); }
        });
    });

    $(document).on('click', '.btn-delete-vax-inline', function (e) {
        e.preventDefault(); e.stopPropagation();
        if (!confirm('@lang('clinicCore::lang.confirm_delete')')) return;
        var id = $(this).data('id');
        var $card = $(this).closest('.vax-pcard');
        $.ajax({
            url:    '{{ url('clinic/vaccinations') }}/' + id,
            method: 'DELETE',
            data:   { _token: '{{ csrf_token() }}' },
            success: function (res) {
                if (res.success) { toastr.success(res.msg || 'Deleted.'); $card.fadeOut(200, function(){ $(this).remove(); }); }
            },
            error: function () { toastr.error('Error deleting vaccination.'); }
        });
    });

    /* ══════════════════════════════════════════════════════════
       11.4 — Tab filter / view-toggle logic
    ══════════════════════════════════════════════════════════ */

    /* ── Conditions: status + severity filter ──── */
    var _condStatus = 'all';
    var _condSev    = '';

    function applyCondFilters() {
        var visible = 0;
        $('#cond-list .cond-card').each(function () {
            var show = (_condStatus === 'all' || $(this).data('cond-status') === _condStatus)
                    && (!_condSev || $(this).data('cond-severity') === _condSev);
            $(this).toggle(show);
            if (show) visible++;
        });
        $('#cond-empty-msg').toggle(visible === 0 && $('#cond-list').length > 0);
    }

    $(document).on('click', '.cond-sfilt', function () {
        _condStatus = $(this).data('sf');
        var clr = _condStatus === 'all' ? '#475569'
                : (_condStatus === 'active' ? '#e74c3c'
                : (_condStatus === 'chronic' ? '#f39c12' : '#27ae60'));
        $('.cond-sfilt').each(function () {
            var c = $(this).data('sf') === 'all' ? '#475569'
                    : ($(this).data('sf') === 'active' ? '#e74c3c'
                    : ($(this).data('sf') === 'chronic' ? '#f39c12' : '#27ae60'));
            $(this).css({ background: 'transparent', color: c, borderColor: c });
        });
        $(this).css({ background: clr, color: '#fff', borderColor: clr });
        applyCondFilters();
    });

    $('#cond_sev_filter').on('change', function () {
        _condSev = $(this).val();
        applyCondFilters();
    });

    /* ── Appointments: status + type filter + view toggle ── */
    var _aptStatus  = 'all';
    var _aptType    = '';
    var _aptView    = 'list';

    function applyAptFilters() {
        var visible = 0;
        var selector = _aptView === 'list' ? '#apt-table-body .apt-row' : '#apt-cards-grid .apt-card-item';
        $(selector).each(function () {
            var show = (_aptStatus === 'all' || $(this).data('ast') === _aptStatus)
                    && (!_aptType || $(this).data('atype') === _aptType);
            $(this).toggle(show);
            if (show) visible++;
        });
        if (_aptView === 'list') {
            $('#apt-list-empty').toggle(visible === 0);
        } else {
            $('#apt-card-empty').toggle(visible === 0);
        }
    }

    $(document).on('click', '.apt-sfilt', function () {
        _aptStatus = $(this).data('asf');
        var clrs = { all:'#475569', completed:'#27ae60', pending:'#f39c12', confirmed:'#2980b9',
                     in_progress:'#3498db', cancelled:'#e74c3c', no_show:'#95a5a6' };
        $('.apt-sfilt').each(function () {
            var c = clrs[$(this).data('asf')] || '#475569';
            $(this).css({ background: 'transparent', color: c, borderColor: c });
        });
        var ac = clrs[_aptStatus] || '#475569';
        $(this).css({ background: ac, color: '#fff', borderColor: ac });
        applyAptFilters();
    });

    $('#apt_type_filter').on('change', function () {
        _aptType = $(this).val();
        applyAptFilters();
    });

    $('#apt_view_list').on('click', function () {
        _aptView = 'list';
        $(this).addClass('active'); $('#apt_view_card').removeClass('active');
        $('#apt-list-view').show(); $('#apt-card-view').hide();
        applyAptFilters();
    });
    $('#apt_view_card').on('click', function () {
        _aptView = 'card';
        $(this).addClass('active'); $('#apt_view_list').removeClass('active');
        $('#apt-card-view').show(); $('#apt-list-view').hide();
        applyAptFilters();
    });

    /* ── Prescriptions: status filter + view toggle ── */
    var _rxStatus = 'all';
    var _rxView   = 'list';

    function applyRxFilters() {
        var visible = 0;
        var selector = _rxView === 'list' ? '#rx-list-view .rx-row' : '#rx-cards-grid .rx-card-item';
        $(selector).each(function () {
            var show = (_rxStatus === 'all' || $(this).data('rxst') === _rxStatus);
            $(this).toggle(show);
            if (show) visible++;
        });
        if (_rxView === 'list') {
            $('#rx-list-empty').toggle(visible === 0);
        } else {
            $('#rx-card-empty').toggle(visible === 0);
        }
    }

    $(document).on('click', '.rx-sfilt', function () {
        _rxStatus = $(this).data('rxf');
        var clrs = { all:'#475569', active:'#27ae60', completed:'#2980b9', cancelled:'#e74c3c' };
        $('.rx-sfilt').each(function () {
            var c = clrs[$(this).data('rxf')] || '#475569';
            $(this).css({ background: 'transparent', color: c, borderColor: c });
        });
        var ac = clrs[_rxStatus] || '#475569';
        $(this).css({ background: ac, color: '#fff', borderColor: ac });
        applyRxFilters();
    });

    $('#rx_view_list').on('click', function () {
        _rxView = 'list';
        $(this).addClass('active'); $('#rx_view_card').removeClass('active');
        $('#rx-list-view').show(); $('#rx-card-view').hide();
        applyRxFilters();
    });
    $('#rx_view_card').on('click', function () {
        _rxView = 'card';
        $(this).addClass('active'); $('#rx_view_list').removeClass('active');
        $('#rx-card-view').show(); $('#rx-list-view').hide();
        applyRxFilters();
    });

    /* ── Clinical History tab ─────────────────────────────────────── */
    $(document).on('click', '.clinical-apt-toggle', function () {
        var target = $($(this).data('target'));
        var chevron = $(this).find('.fa-chevron-down, .fa-chevron-up');
        if (target.is(':visible')) {
            target.slideUp(180);
            chevron.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        } else {
            target.slideDown(180);
            chevron.removeClass('fa-chevron-down').addClass('fa-chevron-up');
        }
    });

    $('#btn_expand_all').on('click', function () {
        $('.clinical-apt-body').slideDown(180);
        $('.clinical-apt-toggle .fa-chevron-down').removeClass('fa-chevron-down').addClass('fa-chevron-up');
    });

    $('#btn_collapse_all').on('click', function () {
        $('.clinical-apt-body').slideUp(180);
        $('.clinical-apt-toggle .fa-chevron-up').removeClass('fa-chevron-up').addClass('fa-chevron-down');
    });

    /* ── Document Preview Modal ───────────────────────────────────── */
    var _imgExts   = ['jpg','jpeg','png','gif','webp','bmp','svg'];
    var _pdfExts   = ['pdf'];
    var _videoExts = ['mp4','webm','ogg'];

    function _extOf(url) {
        var clean = url.split('?')[0].split('#')[0];
        var parts = clean.split('.');
        return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
    }

    $(document).on('click', '.btn-doc-preview', function () {
        var url  = $(this).data('url');
        var name = $(this).data('name') || 'Document';
        var ext  = _extOf(url);

        $('#docPreviewModalTitle').text(name);
        $('#docPreviewDownload').attr('href', url);
        $('#docPreviewBody').html(
            '<div id="docPreviewSpinner" style="color:#94a3b8;padding:60px;text-align:center;">' +
            '<i class="fa fa-spinner fa-spin fa-2x"></i></div>'
        );
        $('#docPreviewModal').modal('show');

        var content;
        if (_imgExts.indexOf(ext) !== -1) {
            content = '<img src="' + url + '" alt="' + name +
                '" style="max-width:100%;max-height:80vh;display:block;margin:auto;" ' +
                'onerror="this.parentNode.innerHTML=\'<div style=&quot;padding:40px;color:#ef4444;text-align:center;&quot;><i class=&quot;fa fa-exclamation-triangle fa-2x&quot;></i><br>Image failed to load.</div>\'">';
        } else if (_pdfExts.indexOf(ext) !== -1) {
            content = '<iframe src="' + url + '" style="width:100%;height:80vh;border:none;display:block;"></iframe>';
        } else if (_videoExts.indexOf(ext) !== -1) {
            content = '<video controls style="max-width:100%;max-height:80vh;display:block;margin:auto;">' +
                '<source src="' + url + '"> Your browser does not support video playback.</video>';
        } else {
            content = '<div style="padding:50px;text-align:center;color:#94a3b8;">' +
                '<i class="fa fa-file fa-3x" style="margin-bottom:14px;opacity:.5;display:block;"></i>' +
                '<div style="font-size:14px;font-weight:600;color:#cbd5e1;margin-bottom:8px;">' + name + '</div>' +
                '<div style="font-size:12px;">Preview not available for .' + (ext || 'this file type') + ' files.</div>' +
                '<a href="' + url + '" target="_blank" class="btn btn-sm btn-primary" style="margin-top:16px;">' +
                '<i class="fa fa-download"></i> Download to view</a></div>';
        }
        $('#docPreviewBody').html(content);
    });

    $('#docPreviewModal').on('hidden.bs.modal', function () {
        $('#docPreviewBody').html(
            '<div style="color:#94a3b8;padding:40px;text-align:center;"><i class="fa fa-spinner fa-spin fa-2x"></i></div>'
        );
    });

    /* ── Documents tab ────────────────────────────────────────────── */
    $(document).on('click', '.doc-type-chip', function () {
        var type = $(this).data('doctype');
        $('.doc-type-chip').removeClass('tc-active')
            .css({ background: '#f0f0f0', color: '#555', borderColor: '#ddd' });
        $(this).addClass('tc-active')
            .css({ background: '#8e44ad', color: '#fff', borderColor: '#8e44ad' });

        if (type === 'all') {
            $('.doc-row').show();
            $('.doc-section').show();
        } else if (type === 'medreport') {
            $('.doc-row').hide();
            $('.doc-section').hide();
            $('.doc-row[data-doctype="medreport"]').show().closest('.doc-section').show();
        } else {
            $('.doc-row').hide();
            $('.doc-section').hide();
            $('.doc-row[data-doctype="' + type + '"]').show().closest('.doc-section').show();
        }
    });

});
</script>
@endsection
