@extends('patient.layouts.app')
@section('title','الرئيسية')
@section('tb-sub','مرحباً بك 👋')

@push('styles')
<style>
/* Slider */
.slider-wrap{position:relative;overflow:hidden;background:#000}
.slider-track{display:flex;transition:transform .45s cubic-bezier(.25,.46,.45,.94);will-change:transform}
.slide{min-width:100%;height:175px;flex-shrink:0;position:relative;overflow:hidden;background:#0f172a}
.slide img,.slide video{width:100%;height:100%;object-fit:cover;display:block}
.slide video{pointer-events:none}
.slide-gradient{position:absolute;inset:0;background:linear-gradient(to top,rgba(0,0,0,.65) 0%,transparent 55%)}
.slide-content{position:absolute;bottom:0;right:0;left:0;padding:.9rem 1rem;color:#fff}
.slide-content h3{font-size:1rem;font-weight:800;margin-bottom:.2rem}
.slide-content p{font-size:.73rem;opacity:.85}
.slide-default{width:100%;height:175px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.5rem;color:#fff;padding:1.2rem;text-align:center}
.slide-dots{position:absolute;bottom:8px;left:50%;transform:translateX(-50%);display:flex;gap:4px;z-index:2}
.dot{width:5px;height:5px;border-radius:50%;background:rgba(255,255,255,.5);cursor:pointer;transition:all .3s}
.dot.on{background:#fff;width:16px;border-radius:3px}

/* Search */
.search-box{
    margin:.9rem 1rem .5rem;
    background:#fff;border-radius:50px;
    display:flex;align-items:center;gap:.5rem;
    padding:.6rem 1rem;
    box-shadow:0 2px 12px rgba(109,40,217,.15);
    border:1.5px solid var(--cM);
}
.search-box input{flex:1;border:none;outline:none;font-size:.88rem;color:var(--t1);background:transparent;direction:rtl}
.search-box input::placeholder{color:var(--t3)}

/* Specs */
.specs-row{display:flex;gap:.55rem;overflow-x:auto;padding:.2rem 1rem .6rem;scrollbar-width:none}
.specs-row::-webkit-scrollbar{display:none}
.spec-btn{
    flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:3px;
    padding:.55rem .8rem;background:#fff;border-radius:var(--r);
    box-shadow:var(--sh);cursor:pointer;border:2px solid transparent;
    text-decoration:none;transition:all .18s;min-width:64px;
}
.spec-btn.on,.spec-btn:active{border-color:var(--c1);background:var(--cL)}
.spec-btn .si{font-size:1.35rem;line-height:1}
.spec-btn .sn{font-size:.62rem;font-weight:700;color:var(--t2);text-align:center}

/* City filter */
.city-row{display:flex;gap:.45rem;overflow-x:auto;padding:.2rem 1rem .5rem;scrollbar-width:none}
.city-row::-webkit-scrollbar{display:none}
.city-pill{
    flex-shrink:0;padding:.38rem .9rem;border-radius:20px;
    font-size:.72rem;font-weight:700;cursor:pointer;
    border:1.5px solid #e5e7eb;background:#fff;color:var(--t2);
    transition:all .18s;white-space:nowrap;text-decoration:none;
}
.city-pill.on,.city-pill:hover{background:var(--c1);border-color:var(--c1);color:#fff}

/* Queue hero */
.q-hero{
    margin:0 1rem .8rem;
    border-radius:var(--r);
    background:linear-gradient(135deg,#4c1d95,var(--c1) 60%,var(--c3));
    padding:1.1rem;color:#fff;
    box-shadow:0 8px 28px rgba(109,40,217,.4);
    position:relative;overflow:hidden;
}
.q-hero::before{content:'';position:absolute;width:140px;height:140px;border-radius:50%;background:rgba(255,255,255,.07);top:-50px;left:-50px}
.q-hero::after{content:'';position:absolute;width:90px;height:90px;border-radius:50%;background:rgba(255,255,255,.05);bottom:-30px;right:20px}
.q-num{font-size:3.4rem;font-weight:900;line-height:1;position:relative;z-index:1}
.q-pulse{display:inline-block;width:7px;height:7px;background:#4ade80;border-radius:50%;box-shadow:0 0 0 0 rgba(74,222,128,.6);animation:qp 1.5s infinite}
@keyframes qp{0%{box-shadow:0 0 0 0 rgba(74,222,128,.6)}70%{box-shadow:0 0 0 8px rgba(74,222,128,0)}100%{box-shadow:0 0 0 0 rgba(74,222,128,0)}}

/* Doc card */
.doc-card{
    margin:0 1rem .6rem;
    background:#fff;border-radius:var(--r);box-shadow:var(--sh);
    display:flex;align-items:center;gap:.85rem;padding:.9rem 1rem;
    text-decoration:none;color:inherit;
    position:relative;transition:transform .12s;
}
.doc-card:active{transform:scale(.98)}
.doc-av{
    width:56px;height:56px;border-radius:14px;
    background:var(--c1);display:flex;align-items:center;justify-content:center;
    font-size:1.35rem;color:#fff;flex-shrink:0;overflow:hidden;
}
.doc-av img{width:100%;height:100%;object-fit:cover}
.doc-name{font-size:.9rem;font-weight:700;margin-bottom:1px}
.doc-spec{font-size:.75rem;color:var(--t2);margin-bottom:3px}
.doc-row{display:flex;align-items:center;gap:.5rem;font-size:.7rem;color:var(--t3)}
.stars{color:#f59e0b}
.q-badge{
    position:absolute;top:.65rem;left:.7rem;
    background:var(--cM);color:var(--c1);
    font-size:.62rem;font-weight:700;padding:2px 7px;border-radius:20px;
}

/* Appt */
.appt-card{
    margin:0 1rem .55rem;background:#fff;border-radius:var(--r);box-shadow:var(--sh);
    display:flex;align-items:center;gap:.85rem;padding:.85rem 1rem;
}
.appt-date{width:46px;height:52px;background:var(--cL);border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;flex-shrink:0}
.appt-date .d{font-size:1.25rem;font-weight:800;color:var(--c1);line-height:1}
.appt-date .m{font-size:.58rem;color:var(--t3);font-weight:700}

/* News */
.news-row{display:flex;gap:.7rem;overflow-x:auto;padding:.2rem 1rem .7rem;scrollbar-width:none}
.news-row::-webkit-scrollbar{display:none}
.nc{width:190px;flex-shrink:0;background:#fff;border-radius:var(--rs);box-shadow:var(--sh);overflow:hidden;text-decoration:none;color:inherit}
.nc img,.nc .nc-img{width:100%;height:105px;object-fit:cover}
.nc-body{padding:.65rem .75rem}
.nc-title{font-size:.76rem;font-weight:700;line-height:1.4;margin-bottom:3px}
.nc-date{font-size:.62rem;color:var(--t3)}

/* Stats row */
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:.6rem;padding:.3rem 1rem .7rem}
.stat-box{background:#fff;border-radius:var(--rs);box-shadow:var(--sh);padding:.8rem .6rem;text-align:center}
.stat-box .sv{font-size:1.5rem;font-weight:800}
.stat-box .sn{font-size:.62rem;color:var(--t3);margin-top:1px}
</style>
@endpush

@section('content')

{{-- ══ Ad Slider ══ --}}
<div class="slider-wrap">
    <div class="slider-track" id="sTrack">
        @if($advertisements->isNotEmpty())
            @foreach($advertisements as $ad)
            <div class="slide">
                @if($ad->isVideo())
                    <video src="{{ asset('storage/'.$ad->video_path) }}" muted playsinline autoplay loop></video>
                    <div class="slide-gradient"></div>
                    <div class="slide-content">
                        <h3>{{ $ad->title_ar ?? $ad->title }}</h3>
                        @if($ad->description)<p>{{ Str::limit($ad->description,70) }}</p>@endif
                    </div>
                @elseif($ad->image)
                    <img src="{{ asset('storage/'.$ad->image) }}" alt="{{ $ad->title }}">
                    <div class="slide-gradient"></div>
                    <div class="slide-content">
                        <h3>{{ $ad->title_ar ?? $ad->title }}</h3>
                        @if($ad->description)<p>{{ Str::limit($ad->description,70) }}</p>@endif
                    </div>
                @else
                    <div class="slide-default" style="background:linear-gradient(135deg,var(--c1),var(--c3))">
                        <div style="font-size:2rem">🏥</div>
                        <div style="font-size:1rem;font-weight:800">{{ $ad->title_ar ?? $ad->title }}</div>
                        @if($ad->description)<div style="font-size:.75rem;opacity:.85">{{ Str::limit($ad->description,60) }}</div>@endif
                    </div>
                @endif
            </div>
            @endforeach
        @else
            <div class="slide"><div class="slide-default" style="background:linear-gradient(135deg,#4c1d95,var(--c1))"><div style="font-size:2rem">🏥</div><div style="font-size:1rem;font-weight:800">{{ $siteBrand->name() }}</div><div style="font-size:.75rem;opacity:.85">احجز موعدك وتابع طابورك بسهولة</div></div></div>
            <div class="slide"><div class="slide-default" style="background:linear-gradient(135deg,#0f766e,#0d9488)"><div style="font-size:2rem">📋</div><div style="font-size:1rem;font-weight:800">سجلاتك الطبية</div><div style="font-size:.75rem;opacity:.85">وصفاتك وتشخيصاتك في مكان واحد</div></div></div>
            <div class="slide"><div class="slide-default" style="background:linear-gradient(135deg,#1e3a8a,#2563eb)"><div style="font-size:2rem">🔔</div><div style="font-size:1rem;font-weight:800">إشعارات فورية</div><div style="font-size:.75rem;opacity:.85">نُعلمك عندما يحين دورك</div></div></div>
        @endif
    </div>
    <div class="slide-dots" id="sDots"></div>
</div>

{{-- ══ Search ══ --}}
<form action="{{ route('patient.doctors.index') }}" method="GET" style="display:flex">
    <div class="search-box" style="flex:1">
        <i class="bi bi-search" style="color:var(--c1);font-size:1rem"></i>
        <input type="text" name="search" placeholder="ابحث عن طبيب أو تخصص...">
        <button type="submit" style="background:var(--c1);border:none;border-radius:20px;color:#fff;padding:.3rem .8rem;font-size:.8rem;cursor:pointer;font-weight:600">بحث</button>
    </div>
</form>

{{-- ══ الطابور الحالي ══ --}}
@if($currentQueue)
<div class="q-hero">
    <div style="font-size:.7rem;opacity:.75;margin-bottom:.25rem;display:flex;align-items:center;gap:5px;position:relative;z-index:1">
        <span class="q-pulse"></span> أنت في الطابور — د. {{ $currentQueue->doctor->user->name }}
    </div>
    <div style="display:flex;align-items:flex-end;gap:1.5rem;position:relative;z-index:1">
        <div><div style="font-size:.62rem;opacity:.7">رقمك</div><div class="q-num">{{ $currentQueue->queue_number }}</div></div>
        <div><div style="font-size:.62rem;opacity:.7">أمامك</div><div style="font-size:2.2rem;font-weight:800">{{ $queueAhead }}</div></div>
        @if($currentQueue->estimated_wait_minutes)
        <div><div style="font-size:.62rem;opacity:.7">انتظار</div><div style="font-size:1.5rem;font-weight:800">~{{ $currentQueue->estimated_wait_minutes }}د</div></div>
        @endif
    </div>
    <div style="display:flex;gap:.6rem;margin-top:.85rem;position:relative;z-index:1">
        @if($currentQueue->status==='called')
        <span style="background:#4ade80;color:#14532d;border-radius:9px;padding:.45rem 1rem;font-size:.78rem;font-weight:700">📣 دورك الآن!</span>
        @endif
        <form method="POST" action="{{ route('patient.queue.leave') }}">
            @csrf @method('DELETE')
            <button type="submit" style="background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);border-radius:9px;color:#fff;padding:.42rem 1rem;font-size:.75rem;font-weight:600;cursor:pointer">مغادرة الطابور</button>
        </form>
    </div>
</div>
@else
{{-- الإحصائيات السريعة --}}
<div class="stats-row">
    <div class="stat-box"><div class="sv" style="color:var(--c1)">{{ $upcomingCount }}</div><div class="sn">موعد قادم</div></div>
    <div class="stat-box"><div class="sv" style="color:#0f766e">{{ $recordsCount }}</div><div class="sn">زيارة طبية</div></div>
    <div class="stat-box"><div class="sv" style="color:#dc2626">{{ $unreadCount }}</div><div class="sn">إشعار جديد</div></div>
</div>
@endif

{{-- ══ التخصصات ══ --}}
<div class="sh"><span class="st">التخصصات</span><a href="{{ route('patient.doctors.index') }}" class="sl">عرض الكل</a></div>
<div class="specs-row">
    @php $specs=[['🏥','الكل',''],['🩺','عام','طب عام'],['❤️','قلب','قلب'],['🧠','أعصاب','أعصاب'],['🦷','أسنان','أسنان'],['👁','عيون','عيون'],['🦴','عظام','عظام'],['👶','أطفال','أطفال'],['🤰','نساء','أمراض نسائية'],['🧬','باطنية','باطنية'],['🔬','مختبر','مختبر']]; @endphp
    @foreach($specs as [$icon,$label,$spec])
    <a href="{{ route('patient.doctors.index',['specialty'=>$spec]) }}" class="spec-btn {{ $spec===''?'on':'' }}">
        <span class="si">{{ $icon }}</span><span class="sn">{{ $label }}</span>
    </a>
    @endforeach
</div>

{{-- ══ أطباء المنطقة + فلتر المحافظات ══ --}}
<div class="sh">
    <span class="st">
        @if($patientCity) 📍 أطباء {{ $patientCity }} @else أطباء مقترحون @endif
    </span>
    <a href="{{ route('patient.doctors.index') }}" class="sl">الكل</a>
</div>

{{-- فلتر المحافظات --}}
@if($allCities->isNotEmpty())
<div class="city-row">
    <a href="{{ route('patient.doctors.index') }}"
       class="city-pill {{ !request('city') ? 'on':'' }}">الكل</a>
    @if($patientCity)
    <a href="{{ route('patient.doctors.index',['city'=>$patientCity]) }}"
       class="city-pill {{ request('city')===$patientCity?'on':'' }}"
       style="border-color:var(--c1);color:var(--c1)">📍 {{ $patientCity }}</a>
    @endif
    @foreach($allCities->reject(fn($c)=>$c===$patientCity)->take(5) as $city)
    <a href="{{ route('patient.doctors.index',['city'=>$city]) }}"
       class="city-pill {{ request('city')===$city?'on':'' }}">{{ $city }}</a>
    @endforeach
</div>
@endif

{{-- قائمة الأطباء --}}
@forelse($nearbyDoctors as $doc)
<a href="{{ route('patient.doctors.show',$doc->id) }}" class="doc-card">
    <div class="doc-av">
        @if($doc->logo)<img src="{{ asset('storage/'.$doc->logo) }}" alt="">
        @else {{ strtoupper(mb_substr($doc->user->name,3,1)) }} @endif
    </div>
    <div style="flex:1;min-width:0">
        <div class="doc-name">د. {{ $doc->user->name }}</div>
        <div class="doc-spec">{{ $doc->specialty }}
            @if($doc->experience_years) · {{ $doc->experience_years }} سنة @endif
        </div>
        <div class="doc-row">
            <span class="stars">{{ str_repeat('★',min(5,round($doc->rating))) }}{{ str_repeat('☆',max(0,5-round($doc->rating))) }}</span>
            <span>{{ number_format($doc->rating,1) }}</span>
            @if($doc->city)<span>· 📍{{ $doc->city }}</span>@endif
            @if($doc->consultation_fee)<span>· {{ \App\Support\Money::iqd($doc->consultation_fee, 0) }}</span>@endif
        </div>
    </div>
    <div style="display:flex;flex-direction:column;align-items:flex-end;justify-content:space-between;height:54px">
        @if($doc->is_verified)<i class="bi bi-patch-check-fill" style="color:#059669;font-size:.85rem"></i>@endif
        @php $qn=\App\Models\Queue::where('doctor_id',$doc->id)->today()->whereIn('status',['waiting','in_progress'])->count() @endphp
        @if($qn>0)<span class="q-badge">{{ $qn }} الآن</span>@endif
        <i class="bi bi-chevron-left" style="color:var(--t3);font-size:.8rem"></i>
    </div>
</a>
@empty
<div style="text-align:center;padding:2rem;color:var(--t3)">
    <i class="bi bi-person-x" style="font-size:2rem;display:block;margin-bottom:.5rem"></i>
    لا يوجد أطباء في هذه المنطقة حالياً
</div>
@endforelse

{{-- ══ المواعيد القادمة ══ --}}
@if($upcomingAppointments->isNotEmpty())
<div class="sh"><span class="st">مواعيدك القادمة</span><a href="{{ route('patient.appointments.index') }}" class="sl">الكل</a></div>
@foreach($upcomingAppointments as $appt)
<div class="appt-card">
    <div class="appt-date">
        <div class="d">{{ $appt->appointment_date->format('d') }}</div>
        <div class="m">{{ $appt->appointment_date->locale('ar')->isoFormat('MMM') }}</div>
    </div>
    <div style="flex:1">
        <div style="font-weight:700;font-size:.88rem">د. {{ $appt->doctor->user->name }}</div>
        <div style="font-size:.75rem;color:var(--t2)">{{ $appt->doctor->specialty }}</div>
        <div style="font-size:.7rem;color:var(--t3)">🕐 {{ $appt->appointment_time }}</div>
    </div>
    <span class="pill {{ $appt->status==='confirmed'?'pg':'py' }}">
        {{ $appt->status==='confirmed'?'مؤكد':'بانتظار' }}
    </span>
</div>
@endforeach
@endif

{{-- ══ آخر الأخبار ══ --}}
@if($news->isNotEmpty())
<div class="sh"><span class="st">أخبار طبية</span></div>
<div class="news-row">
    @foreach($news as $n)
    <div class="nc">
        @if($n->cover_image)<img src="{{ asset('storage/'.$n->cover_image) }}" alt="">
        @else<div class="nc-img" style="background:linear-gradient(135deg,var(--c1),var(--c3));display:flex;align-items:center;justify-content:center;font-size:2rem">🏥</div>@endif
        <div class="nc-body">
            <div class="nc-title">{{ Str::limit($n->title,50) }}</div>
            <div class="nc-date">{{ $n->published_at?->diffForHumans() }}</div>
        </div>
    </div>
    @endforeach
</div>
@endif

<div style="height:.5rem"></div>
@endsection

@push('scripts')
<script>
// ══ Slider ══
const track=document.getElementById('sTrack');
const dotsC=document.getElementById('sDots');
const slides=track?track.children.length:0;
let cur=0,timer;

if(slides>0){
    // Build dots
    for(let i=0;i<slides;i++){
        const d=document.createElement('div');
        d.className='dot'+(i===0?' on':'');
        d.onclick=()=>go(i);
        dotsC.appendChild(d);
    }

    function go(n){
        cur=(n+slides)%slides;
        track.style.transform=`translateX(${cur*100}%)`;
        dotsC.querySelectorAll('.dot').forEach((d,i)=>d.classList.toggle('on',i===cur));
    }

    timer=setInterval(()=>go(cur+1),4500);

    // Swipe support
    let sx=0;
    track.addEventListener('touchstart',e=>{sx=e.touches[0].clientX;clearInterval(timer)},{passive:true});
    track.addEventListener('touchend',e=>{
        const dx=e.changedTouches[0].clientX-sx;
        if(Math.abs(dx)>40) go(dx>0?cur-1:cur+1);
        timer=setInterval(()=>go(cur+1),4500);
    });
}
</script>
@endpush
