@extends('layouts.app')
@section('title', 'Clinic — Dashboard')

@section('css')
<style>
/* ── Override layout scroll container on desktop ─── */
@media (min-width: 768px) {
    #scrollable-container {
        overflow-y: visible !important;
        height: auto !important;
    }
}

/* ── Reset / Globals ─────────────────────────────── */
.vc-dash { font-family:inherit; }

/* ── Page Header ─────────────────────────────────── */
.dash-header {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:20px; flex-wrap:wrap; gap:10px;
}
.dash-title { font-size:23px; font-weight:800; color:#1e293b; display:flex; align-items:center; gap:10px; }
.dash-title .dash-icon {
    width:44px; height:44px; border-radius:12px;
    background:linear-gradient(135deg,#3b82f6,#6366f1);
    display:flex; align-items:center; justify-content:center;
    font-size:18px; color:#fff; flex-shrink:0;
    box-shadow:0 4px 12px rgba(99,102,241,.35);
}
.dash-date { font-size:12px; color:#94a3b8; font-weight:500; }
.dash-header-actions { display:flex; gap:8px; }

/* ── KPI Grid ────────────────────────────────────── */
.kpi-grid {
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:14px;
    margin-bottom:18px;
}
@media(max-width:1024px){ .kpi-grid { grid-template-columns:repeat(2,1fr); } }
@media(max-width:640px) { .kpi-grid { grid-template-columns:1fr; } }

.kpi-card {
    border-radius:14px; padding:18px 20px; position:relative; overflow:hidden;
    color:#fff; cursor:default;
    box-shadow:0 4px 16px rgba(0,0,0,.12);
    transition:transform .18s, box-shadow .18s;
}
.kpi-card:hover { transform:translateY(-3px); box-shadow:0 8px 24px rgba(0,0,0,.18); }
.kpi-card::after {
    content:''; position:absolute; right:-18px; bottom:-18px;
    width:100px; height:100px; border-radius:50%;
    background:rgba(255,255,255,.1); pointer-events:none;
}
.kpi-label { font-size:10.5px; font-weight:700; text-transform:uppercase; letter-spacing:.6px; opacity:.82; margin-bottom:8px; }
.kpi-num   { font-size:36px; font-weight:900; line-height:1; margin-bottom:6px; letter-spacing:-1px; }
.kpi-sub   { font-size:11.5px; opacity:.78; display:flex; align-items:center; gap:5px; }
.kpi-icon  { position:absolute; right:18px; top:16px; font-size:32px; opacity:.18; }
.kpi-trend { font-size:11px; font-weight:700; padding:2px 7px; border-radius:10px; background:rgba(255,255,255,.22); }

/* KPI card themes */
.kpi-blue   { background:linear-gradient(135deg,#2563eb,#3b82f6); }
.kpi-green  { background:linear-gradient(135deg,#16a34a,#22c55e); }
.kpi-purple { background:linear-gradient(135deg,#7c3aed,#a78bfa); }
.kpi-orange { background:linear-gradient(135deg,#d97706,#f59e0b); }
.kpi-red    { background:linear-gradient(135deg,#dc2626,#f87171); }
.kpi-teal   { background:linear-gradient(135deg,#0d9488,#2dd4bf); }
.kpi-indigo { background:linear-gradient(135deg,#4338ca,#818cf8); }
.kpi-slate  { background:linear-gradient(135deg,#334155,#64748b); }

/* Second KPI row */
.kpi-grid-2 { grid-template-columns:repeat(4,1fr); }

/* ── Smart Insights ──────────────────────────────── */
.insights-panel {
    background:#fff; border-radius:12px; padding:16px 20px; margin-bottom:18px;
    box-shadow:0 1px 6px rgba(0,0,0,.07); border:1px solid #e8ecf1;
}
.insights-title {
    font-size:11px; font-weight:800; text-transform:uppercase; letter-spacing:.6px;
    color:#64748b; margin-bottom:12px; display:flex; align-items:center; gap:7px;
}
.insights-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); gap:8px; }
.insight-item {
    display:flex; align-items:flex-start; gap:10px;
    padding:10px 13px; border-radius:9px; font-size:12px; line-height:1.45;
}
.insight-icon { font-size:15px; flex-shrink:0; margin-top:1px; }
.insight-item.danger  { background:#fef2f2; color:#991b1b; border:1px solid #fecaca; }
.insight-item.warning { background:#fffbeb; color:#92400e; border:1px solid #fde68a; }
.insight-item.info    { background:#eff6ff; color:#1e40af; border:1px solid #bfdbfe; }
.insight-item.success { background:#f0fdf4; color:#166534; border:1px solid #bbf7d0; }

/* ── Main Content Grid ───────────────────────────── */
.dash-main { display:grid; grid-template-columns:1fr 340px; gap:16px; margin-bottom:18px; }
@media(max-width:1100px){ .dash-main { grid-template-columns:1fr; } }

/* ── Today Schedule ──────────────────────────────── */
.sched-card {
    background:#fff; border-radius:12px; overflow:hidden;
    box-shadow:0 1px 6px rgba(0,0,0,.07); border:1px solid #e8ecf1;
}
.sched-header {
    padding:14px 18px; border-bottom:1px solid #f1f5f9;
    display:flex; align-items:center; justify-content:space-between;
}
.sched-header-title { font-size:13px; font-weight:800; color:#1e293b; display:flex; align-items:center; gap:7px; }
.sched-count { font-size:11px; font-weight:700; padding:2px 8px; border-radius:10px; background:#eff6ff; color:#2563eb; }
.sched-body { padding:10px 14px; max-height:420px; overflow-y:auto; }

.sched-item {
    display:flex; align-items:center; gap:12px;
    padding:10px 8px; border-bottom:1px solid #f8fafc;
    transition:background .12s; border-radius:8px; margin-bottom:2px;
}
.sched-item:hover { background:#f8fafc; }
.sched-item:last-child { border-bottom:none; }
.sched-time {
    flex-shrink:0; width:52px; font-size:13px; font-weight:800;
    color:#1e293b; text-align:center; line-height:1.1;
}
.sched-time small { font-size:9px; font-weight:600; color:#94a3b8; display:block; text-transform:uppercase; }
.sched-bar { flex-shrink:0; width:3px; height:38px; border-radius:3px; }
.sched-info { flex:1; min-width:0; }
.sched-pet  { font-size:13px; font-weight:700; color:#1e293b; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.sched-meta { font-size:11px; color:#64748b; margin-top:2px; }
.sched-badge { font-size:10px; font-weight:700; padding:2px 8px; border-radius:10px; flex-shrink:0; }

.sched-status-pending     { background:#fef3c7; color:#92400e; }
.sched-status-confirmed   { background:#dbeafe; color:#1e40af; }
.sched-status-in_progress { background:#ede9fe; color:#4c1d95; }
.sched-status-completed   { background:#dcfce7; color:#14532d; }
.sched-status-cancelled   { background:#fee2e2; color:#991b1b; }
.sched-status-no_show     { background:#f1f5f9; color:#475569; }

.sched-bar-pending     { background:#f59e0b; }
.sched-bar-confirmed   { background:#3b82f6; }
.sched-bar-in_progress { background:#8b5cf6; }
.sched-bar-completed   { background:#22c55e; }
.sched-bar-cancelled   { background:#ef4444; }
.sched-bar-no_show     { background:#94a3b8; }

.sched-empty { padding:40px 20px; text-align:center; color:#94a3b8; }
.sched-empty i { font-size:36px; margin-bottom:8px; display:block; }

/* ── Side Panel ──────────────────────────────────── */
.side-panel { display:flex; flex-direction:column; gap:14px; }

.side-card {
    background:#fff; border-radius:12px; overflow:hidden;
    box-shadow:0 1px 6px rgba(0,0,0,.07); border:1px solid #e8ecf1;
}
.side-card-header {
    padding:11px 15px; border-bottom:1px solid #f1f5f9;
    font-size:11px; font-weight:800; text-transform:uppercase;
    letter-spacing:.4px; color:#64748b; display:flex; align-items:center;
    justify-content:space-between;
}
.side-card-body { padding:12px 15px; }

/* Doctors on duty */
.doctor-row {
    display:flex; align-items:center; gap:10px; padding:7px 0;
    border-bottom:1px solid #f8fafc;
}
.doctor-row:last-child { border-bottom:none; }
.doc-avatar {
    width:32px; height:32px; border-radius:50%; flex-shrink:0;
    background:linear-gradient(135deg,#6366f1,#a5b4fc);
    display:flex; align-items:center; justify-content:center;
    font-size:13px; color:#fff; font-weight:700;
}
.doc-name  { font-size:12px; font-weight:700; color:#1e293b; }
.doc-count { font-size:11px; color:#64748b; }
.doc-bar-wrap { flex:1; background:#f1f5f9; height:5px; border-radius:3px; overflow:hidden; }
.doc-bar-fill { height:100%; border-radius:3px; background:linear-gradient(90deg,#6366f1,#3b82f6); }

/* ── Chart Row ───────────────────────────────────── */
.chart-row { display:grid; grid-template-columns:1fr 300px; gap:16px; margin-bottom:18px; }
@media(max-width:900px){ .chart-row { grid-template-columns:1fr; } }

.chart-card {
    background:#fff; border-radius:12px; padding:18px 20px;
    box-shadow:0 1px 6px rgba(0,0,0,.07); border:1px solid #e8ecf1;
}
.chart-card-title { font-size:13px; font-weight:800; color:#1e293b; margin-bottom:14px; display:flex; align-items:center; gap:7px; }

/* ── Treatment Alert Strip ─────────────────────── */
.vax-strip {
    display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:18px;
}
@media(max-width:768px){ .vax-strip { grid-template-columns:1fr; } }

.vax-strip-card {
    background:#fff; border-radius:12px; overflow:hidden;
    box-shadow:0 1px 6px rgba(0,0,0,.07); border:1px solid #e8ecf1;
}
.vax-strip-hd {
    padding:12px 16px; display:flex; align-items:center; gap:8px;
    font-size:12px; font-weight:800;
}
.vax-strip-hd.overdue  { background:#fef2f2; color:#991b1b; border-bottom:2px solid #ef4444; }
.vax-strip-hd.due-soon { background:#fffbeb; color:#92400e; border-bottom:2px solid #f59e0b; }
.vax-strip-hd .cnt { font-size:18px; font-weight:900; margin-right:2px; }

.vax-row {
    display:flex; align-items:center; gap:10px; padding:8px 16px;
    border-bottom:1px solid #f8fafc; font-size:12px;
}
.vax-row:last-child { border-bottom:none; }
.vax-pet  { font-weight:700; color:#1e293b; flex:1; }
.vax-vax  { color:#64748b; font-size:11px; flex:1; }
.vax-due  { font-size:11px; font-weight:700; flex-shrink:0; }
.vax-due.overdue  { color:#dc2626; }
.vax-due.due-soon { color:#d97706; }
.vax-empty { padding:16px; text-align:center; color:#94a3b8; font-size:12px; }
.vax-row-link { text-decoration:none; color:inherit; display:flex; }
.vax-row-link:hover { background:#fafafa; text-decoration:none; color:inherit; }
.vax-row-link:hover .vax-pet strong { text-decoration:underline; }
</style>
@endsection

@section('content')
<section class="content-header" style="padding-bottom:0;"><h1 style="display:none;"></h1></section>

<section class="content vc-dash">

{{-- ── Page Header ──────────────────────────────────────── --}}
<div class="dash-header">
    <div class="dash-title">
        <div class="dash-icon"><i class="fas fa-notes-medical"></i></div>
        <div>
            Clinic
            <div class="dash-date">{{ \Carbon\Carbon::today()->format('l, d F Y') }}</div>
        </div>
    </div>
    <div class="dash-header-actions">
        <a href="{{ route('clinic.appointments.index') }}?preset=today" class="btn btn-default btn-sm">
            <i class="fas fa-calendar-alt"></i> Today's List
        </a>
        @can('clinic.manage_appointments')
        <a href="{{ route('clinic.appointments.create') }}" class="btn btn-primary btn-sm">
            <i class="fa fa-plus"></i> New Appointment
        </a>
        @endcan
    </div>
</div>

{{-- ── KPI Row 1 ────────────────────────────────────────── --}}
<div class="kpi-grid">
    <div class="kpi-card kpi-blue">
        <div class="kpi-label"><i class="fa fa-calendar fa-fw"></i> Today's Appointments</div>
        <div class="kpi-num">{{ $stats['todayTotal'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">{{ $stats['todayCompleted'] }} done</span>
            <span>· {{ $stats['todayPending'] }} pending</span>
        </div>
        <i class="fa fa-calendar-check kpi-icon"></i>
    </div>
    <div class="kpi-card kpi-green">
        <div class="kpi-label"><i class="fa fa-chart-line fa-fw"></i> This Week</div>
        <div class="kpi-num">{{ $stats['weekTotal'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">{{ $stats['completionRate'] }}% completed</span>
        </div>
        <i class="fa fa-chart-bar kpi-icon"></i>
    </div>
    <div class="kpi-card kpi-purple">
        <div class="kpi-label"><i class="fa fa-notes-medical fa-fw"></i> Active Patients</div>
        <div class="kpi-num">{{ $stats['totalPets'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">+{{ $stats['newPetsMonth'] }} this month</span>
        </div>
        <i class="fa fa-notes-medical kpi-icon"></i>
    </div>
    @if($stats['overdueVax'] > 0)
    <div class="kpi-card kpi-red">
        <div class="kpi-label"><i class="fa fa-syringe fa-fw"></i> Overdue Vaccinations</div>
        <div class="kpi-num">{{ $stats['overdueVax'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">{{ $stats['dueSoonVax'] }} due in 30d</span>
        </div>
        <i class="fa fa-exclamation-circle kpi-icon"></i>
    </div>
    @else
    <div class="kpi-card kpi-teal">
        <div class="kpi-label"><i class="fa fa-syringe fa-fw"></i> Vaccinations</div>
        <div class="kpi-num">{{ $stats['dueSoonVax'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">due in 30 days</span>
            <span>· 0 overdue ✓</span>
        </div>
        <i class="fa fa-check-circle kpi-icon"></i>
    </div>
    @endif
</div>

{{-- ── KPI Row 2 ────────────────────────────────────────── --}}
<div class="kpi-grid" style="margin-bottom:18px;">
    <div class="kpi-card kpi-orange">
        <div class="kpi-label"><i class="fa fa-clock fa-fw"></i> Awaiting Confirmation</div>
        <div class="kpi-num">{{ $stats['pendingTotal'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">{{ $stats['confirmedTotal'] }} confirmed</span>
        </div>
        <i class="fa fa-hourglass-half kpi-icon"></i>
    </div>
    <div class="kpi-card kpi-slate">
        <div class="kpi-label"><i class="fa fa-user-times fa-fw"></i> Today's No-Shows</div>
        <div class="kpi-num">{{ $stats['todayNoShow'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">{{ $stats['noShowRate'] }}% rate (7d)</span>
        </div>
        <i class="fa fa-user-times kpi-icon"></i>
    </div>
    <div class="kpi-card kpi-indigo">
        <div class="kpi-label"><i class="fa fa-calendar fa-fw"></i> This Month Total</div>
        <div class="kpi-num">{{ $stats['monthTotal'] }}</div>
        <div class="kpi-sub">
            <span class="kpi-trend">appointments</span>
        </div>
        <i class="fa fa-calendar kpi-icon"></i>
    </div>
    <div class="kpi-card kpi-teal" style="background:linear-gradient(135deg,#0f766e,#0d9488);">
        <div class="kpi-label"><i class="fa fa-check-circle fa-fw"></i> Completed Today</div>
        <div class="kpi-num">{{ $stats['todayCompleted'] }}</div>
        <div class="kpi-sub">
            @if($stats['todayTotal'] > 0)
            <span class="kpi-trend">{{ $stats['todayTotal'] > 0 ? round(($stats['todayCompleted']/$stats['todayTotal'])*100) : 0 }}% of today</span>
            @else
            <span class="kpi-trend">No appointments today</span>
            @endif
        </div>
        <i class="fa fa-check-double kpi-icon"></i>
    </div>
</div>

{{-- ── Smart Insights ───────────────────────────────────── --}}
<div class="insights-panel">
    <div class="insights-title">
        <i class="fa fa-lightbulb" style="color:#f59e0b;font-size:14px;"></i>
        Smart Insights
    </div>
    <div class="insights-grid">
        @foreach($insights as $insight)
        <div class="insight-item {{ $insight['type'] }}">
            <i class="fa {{ $insight['icon'] }} insight-icon"></i>
            <span>{{ $insight['msg'] }}</span>
        </div>
        @endforeach
    </div>
</div>

{{-- ── Main: Schedule + Side Panel ─────────────────────── --}}
<div class="dash-main">

    {{-- Today's Schedule --}}
    <div class="sched-card">
        <div class="sched-header">
            <div class="sched-header-title">
                <i class="fas fa-calendar-day" style="color:#3b82f6;"></i>
                Today's Schedule
                <span class="sched-count">{{ $today_appointments->count() }} appointments</span>
            </div>
            <a href="{{ route('clinic.appointments.index') }}?preset=today" class="btn btn-xs btn-default">View All →</a>
        </div>
        <div class="sched-body">
            @if($today_appointments->isEmpty())
            <div class="sched-empty">
                <i class="fa fa-calendar"></i>
                No appointments scheduled for today.
                @can('clinic.manage_appointments')
                <br><a href="{{ route('clinic.appointments.create') }}" class="btn btn-sm btn-primary" style="margin-top:10px;">
                    <i class="fa fa-plus"></i> Schedule One
                </a>
                @endcan
            </div>
            @else
            @foreach($today_appointments as $apt)
            @php
            $barClass    = 'sched-bar-'    . $apt->status;
            $badgeClass  = 'sched-status-' . $apt->status;
            $statusLabel = ucfirst(str_replace('_', ' ', $apt->status));
            $tfmt        = session('business.time_format', 24) == 12 ? 'h:i' : 'H:i';
            $time        = $apt->appointment_time ? \Carbon\Carbon::parse($apt->appointment_time)->format($tfmt) : '—';
            $ampm        = $apt->appointment_time ? \Carbon\Carbon::parse($apt->appointment_time)->format('A') : '';
            @endphp
            <div class="sched-item">
                <div class="sched-time">
                    {{ $time }}
                    <small>{{ $ampm }}</small>
                </div>
                <div class="sched-bar {{ $barClass }}"></div>
                <div class="sched-info">
                    <div class="sched-pet">
                        {{ optional($apt->pet)->patient_name ?? '—' }}
                        <small style="font-weight:500;color:#94a3b8;font-size:11px;">
                            · {{ optional($apt->owner)->name ?? '' }}
                        </small>
                    </div>
                    <div class="sched-meta">
                        @if($apt->doctor)
                        <i class="fa fa-user-md fa-fw" style="color:#aaa;"></i> Dr. {{ $apt->doctor->name }}
                        @endif
                        @if($apt->department)
                        &nbsp;<i class="fa fa-hospital fa-fw" style="color:#aaa;"></i> {{ $apt->department->name }}
                        @endif
                    </div>
                </div>
                <span class="sched-badge {{ $badgeClass }}">{{ $statusLabel }}</span>
                <a href="{{ route('clinic.appointments.show', $apt->id) }}" class="btn btn-xs btn-default" title="View">
                    <i class="fa fa-eye"></i>
                </a>
            </div>
            @endforeach
            @endif
        </div>
    </div>

    {{-- Side Panel --}}
    <div class="side-panel">

        {{-- Doctors on duty --}}
        <div class="side-card">
            <div class="side-card-header">
                <span><i class="fa fa-user-md fa-fw"></i> Doctors — Today</span>
            </div>
            <div class="side-card-body" style="padding:8px 15px;">
                @php $maxCount = $doctorsToday->max('appointments_count') ?: 1; @endphp
                @forelse($doctorsToday as $doc)
                <div class="doctor-row">
                    <div class="doc-avatar">{{ strtoupper(substr($doc->name, 0, 1)) }}</div>
                    <div style="flex:1;min-width:0;">
                        <div class="doc-name">{{ $doc->name }}</div>
                        <div class="doc-bar-wrap" style="margin-top:4px;">
                            <div class="doc-bar-fill"
                                 style="width:{{ $maxCount > 0 ? round(($doc->appointments_count/$maxCount)*100) : 0 }}%;"></div>
                        </div>
                    </div>
                    <div class="doc-count" style="flex-shrink:0;margin-left:8px;">
                        <strong>{{ $doc->appointments_count }}</strong>
                        <small style="display:block;font-size:9px;text-align:center;">appts</small>
                    </div>
                </div>
                @empty
                <div style="text-align:center;color:#94a3b8;font-size:12px;padding:14px 0;">No doctors configured.</div>
                @endforelse
            </div>
        </div>

        {{-- Status Distribution mini-donut --}}
        <div class="side-card">
            <div class="side-card-header">
                <span><i class="fa fa-chart-pie fa-fw"></i> Status Mix (30 days)</span>
            </div>
            <div class="side-card-body" style="padding:10px 15px;">
                <div style="position:relative;height:160px;margin-bottom:10px;">
                    <canvas id="statusDonut"></canvas>
                </div>
                <div style="display:flex;flex-wrap:wrap;gap:5px;">
                    @php
                    $statusColors = [
                        'pending'     => '#f59e0b',
                        'confirmed'   => '#3b82f6',
                        'in_progress' => '#8b5cf6',
                        'completed'   => '#22c55e',
                        'cancelled'   => '#ef4444',
                        'no_show'     => '#94a3b8',
                    ];
                    @endphp
                    @foreach($statusDist as $s => $cnt)
                    <div style="display:flex;align-items:center;gap:4px;font-size:10.5px;color:#64748b;">
                        <span style="width:8px;height:8px;border-radius:50%;background:{{ $statusColors[$s] ?? '#ccc' }};flex-shrink:0;"></span>
                        {{ ucfirst(str_replace('_',' ',$s)) }} ({{ $cnt }})
                    </div>
                    @endforeach
                    @if(empty($statusDist))
                    <div style="color:#94a3b8;font-size:12px;text-align:center;width:100%;padding:8px 0;">No data for last 30 days.</div>
                    @endif
                </div>
            </div>
        </div>

    </div>{{-- /side-panel --}}
</div>{{-- /dash-main --}}

{{-- ── Charts Row ───────────────────────────────────────── --}}
<div class="chart-row">
    <div class="chart-card">
        <div class="chart-card-title">
            <i class="fa fa-chart-line" style="color:#3b82f6;"></i>
            Appointment Trend — Last 14 Days
        </div>
        <canvas id="trendChart" height="90"></canvas>
    </div>
    @if(config('cliniccore.show_animal_fields', false))
    <div class="chart-card">
        <div class="chart-card-title">
            <i class="fa fa-chart-pie" style="color:#8b5cf6;"></i>
            Patients by Skin Type
        </div>
        <div style="position:relative;height:160px;">
            <canvas id="speciesDonut"></canvas>
        </div>
        <div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:10px;">
            @php
            $speciesColors = ['dog'=>'#3b82f6','cat'=>'#f59e0b','rabbit'=>'#22c55e','bird'=>'#8b5cf6','other'=>'#94a3b8'];
            $speciesEmoji  = ['dog'=>'🐕','cat'=>'🐈','rabbit'=>'🐇','bird'=>'🦜'];
            @endphp
            @foreach($speciesDist as $sp => $cnt)
            <div style="display:flex;align-items:center;gap:4px;font-size:10.5px;color:#64748b;">
                <span style="width:8px;height:8px;border-radius:50%;background:{{ $speciesColors[$sp] ?? '#94a3b8' }};flex-shrink:0;"></span>
                {{ $speciesEmoji[$sp] ?? '🐾' }} {{ ucfirst($sp) }} ({{ $cnt }})
            </div>
            @endforeach
            @if(empty($speciesDist))<div style="color:#94a3b8;font-size:12px;">No patient data yet.</div>@endif
        </div>
    </div>
    @endif
</div>

{{-- ── Treatment Alert Strip ──────────────────────────── --}}
@if($overdue_vaccinations->isNotEmpty() || $due_soon_vaccinations->isNotEmpty())
<div class="vax-strip">

    {{-- Overdue --}}
    <div class="vax-strip-card">
        <div class="vax-strip-hd overdue">
            <i class="fa fa-exclamation-circle"></i>
            <span class="cnt">{{ $overdue_vaccinations->count() }}</span>
            Overdue Treatments
            <a href="{{ route('clinic.vaccinations.index') }}" class="btn btn-xs" style="margin-left:auto;background:rgba(220,38,38,.15);border-color:#fca5a5;color:#991b1b;">View All →</a>
        </div>
        @if($overdue_vaccinations->isEmpty())
        <div class="vax-empty"><i class="fa fa-check-circle" style="color:#22c55e;"></i> None overdue — great!</div>
        @else
        @foreach($overdue_vaccinations as $vax)
        @php $days = (int) now()->diffInDays($vax->next_due_date, false); @endphp
        <a href="{{ route('clinic.patients.show', $vax->patient_id) }}" class="vax-row vax-row-link">
            <span class="vax-pet">
                <strong>{{ optional($vax->pet)->patient_name ?? '—' }}</strong>
                @if(optional(optional($vax->pet)->owner)->mobile)
                <small style="color:#94a3b8;display:block;font-size:10px;">{{ $vax->pet->owner->mobile }}</small>
                @endif
            </span>
            <span class="vax-vax">{{ optional($vax->vaccineType)->name ?? '—' }}</span>
            <span class="vax-due overdue"><i class="fa fa-exclamation-circle"></i> {{ abs($days) }}d ago</span>
            <i class="fa fa-chevron-right" style="color:#fca5a5;font-size:10px;flex-shrink:0;"></i>
        </a>
        @endforeach
        @endif
    </div>

    {{-- Due Soon --}}
    <div class="vax-strip-card">
        <div class="vax-strip-hd due-soon">
            <i class="fa fa-clock"></i>
            <span class="cnt">{{ $due_soon_vaccinations->count() }}</span>
            Due Within 30 Days
            <a href="{{ route('clinic.vaccinations.index') }}" class="btn btn-xs" style="margin-left:auto;background:rgba(217,119,6,.15);border-color:#fcd34d;color:#92400e;">View All →</a>
        </div>
        @if($due_soon_vaccinations->isEmpty())
        <div class="vax-empty"><i class="fa fa-calendar-check" style="color:#22c55e;"></i> No vaccinations due soon.</div>
        @else
        @foreach($due_soon_vaccinations as $vax)
        @php $days = (int) now()->diffInDays($vax->next_due_date, false); @endphp
        <a href="{{ route('clinic.patients.show', $vax->patient_id) }}" class="vax-row vax-row-link">
            <span class="vax-pet">
                <strong>{{ optional($vax->pet)->patient_name ?? '—' }}</strong>
                @if(optional(optional($vax->pet)->owner)->mobile)
                <small style="color:#94a3b8;display:block;font-size:10px;">{{ $vax->pet->owner->mobile }}</small>
                @endif
            </span>
            <span class="vax-vax">{{ optional($vax->vaccineType)->name ?? '—' }}</span>
            <span class="vax-due due-soon">{{ $days === 0 ? 'Today' : 'In '.$days.'d' }}</span>
            <i class="fa fa-chevron-right" style="color:#fcd34d;font-size:10px;flex-shrink:0;"></i>
        </a>
        @endforeach
        @endif
    </div>

</div>
@endif

</section>
@endsection

@section('javascript')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script>
(function initDashCharts() {
    // ── 14-day Trend Chart ────────────────────────────
    var trendEl = document.getElementById('trendChart');
    if (trendEl) {
        var ctx    = trendEl.getContext('2d');
        var labels = @json($chart_labels);
        var data   = @json($chart_data);

        var gradient = ctx.createLinearGradient(0, 0, 0, 180);
        gradient.addColorStop(0,   'rgba(59,130,246,.30)');
        gradient.addColorStop(1,   'rgba(59,130,246,.02)');

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Appointments',
                    data: data,
                    fill: true,
                    backgroundColor: gradient,
                    borderColor: '#3b82f6',
                    borderWidth: 2.5,
                    pointBackgroundColor: '#fff',
                    pointBorderColor: '#3b82f6',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    tension: 0.4,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        titleColor: '#94a3b8',
                        bodyColor: '#fff',
                        padding: 10,
                        callbacks: {
                            label: function(c) {
                                return ' ' + c.parsed.y + ' appointment' + (c.parsed.y !== 1 ? 's' : '');
                            }
                        }
                    }
                },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 10 }, color: '#94a3b8' } },
                    y: { beginAtZero: true, ticks: { stepSize: 1, font: { size: 10 }, color: '#94a3b8' }, grid: { color: '#f1f5f9' } }
                }
            }
        });
    }

    // ── Status Donut ──────────────────────────────────
    var statusEl = document.getElementById('statusDonut');
    if (statusEl) {
        var dist = @json($statusDist);
        var colorMap = {
            pending:'#f59e0b', confirmed:'#3b82f6', in_progress:'#8b5cf6',
            completed:'#22c55e', cancelled:'#ef4444', no_show:'#94a3b8'
        };
        var sLabels = Object.keys(dist).map(function(s) {
            return s.charAt(0).toUpperCase() + s.slice(1).replace('_', ' ');
        });
        var sValues = Object.values(dist);
        var sColors = Object.keys(dist).map(function(s) { return colorMap[s] || '#ccc'; });

        if (sValues.length) {
            new Chart(statusEl.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: sLabels,
                    datasets: [{ data: sValues, backgroundColor: sColors, borderWidth: 2, borderColor: '#fff', hoverOffset: 6 }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '68%',
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            callbacks: { label: function(c) { return ' ' + c.label + ': ' + c.parsed; } }
                        }
                    }
                }
            });
        } else {
            statusEl.closest('.side-card-body').innerHTML += '<p style="text-align:center;color:#94a3b8;font-size:12px;margin-top:8px;">No appointment data yet.</p>';
        }
    }

    // ── Skin Type Donut ─────────────────────────────────
    var speciesEl = document.getElementById('speciesDonut');
    if (speciesEl) {
        var spDist   = @json($speciesDist);
        var spColors = { dog:'#3b82f6', cat:'#f59e0b', rabbit:'#22c55e', bird:'#8b5cf6' };
        var spLabels = Object.keys(spDist).map(function(s) { return s.charAt(0).toUpperCase() + s.slice(1); });
        var spValues = Object.values(spDist);
        var spBg     = Object.keys(spDist).map(function(s) { return spColors[s] || '#94a3b8'; });

        if (spValues.length) {
            new Chart(speciesEl.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: spLabels,
                    datasets: [{ data: spValues, backgroundColor: spBg, borderWidth: 2, borderColor: '#fff', hoverOffset: 6 }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '65%',
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            callbacks: { label: function(c) { return ' ' + c.label + ': ' + c.parsed + ' pets'; } }
                        }
                    }
                }
            });
        } else {
            speciesEl.closest('div').innerHTML = '<p style="text-align:center;color:#94a3b8;font-size:12px;padding:20px 0;">No patient data yet.</p>';
        }
    }
})();
</script>
@endsection
