// screens-vet.jsx — vet doctors list + booking (البيطري)
(function(){
  const { useState } = React;
  const Icon = window.Icon;
  const { Header, Stars, SecureNote } = window;

  // ── small heart favorite toggle ──
  function FavBtn({ on, onClick, size=34 }){
    return (
      <button onClick={(e)=>{ e.stopPropagation(); onClick(); }} aria-label="مفضلة"
        style={{width:size, height:size, flex:'0 0 auto', border:'none', borderRadius:12, cursor:'pointer',
          background:on?'var(--bad-bg)':'var(--surface-2)', color:on?'var(--bad-fg)':'var(--faint)',
          display:'flex', alignItems:'center', justifyContent:'center', transition:'.15s'}}>
        <Icon name="heart" size={Math.round(size*0.55)} sw={2} fill={on?'var(--bad-fg)':undefined}/>
      </button>
    );
  }

  function DocAvatar({ size=64 }){
    return (
      <div className="ph avatar-ring" style={{width:size, height:size, borderRadius:'50%', padding:0, flex:'0 0 auto'}}>
        <div className="ph" style={{width:size, height:size, borderRadius:'50%'}}><span className="ph-label">صورة<br/>الطبيب</span></div>
      </div>
    );
  }

  /* ───────────────────────── DOCTORS LIST ───────────────────────── */
  function DoctorCard({ v, fav, onFav, onOpen }){
    return (
      <div className="card tap" onClick={onOpen} style={{padding:14, marginBottom:12, display:'flex', alignItems:'center', gap:13}}>
        <DocAvatar size={62}/>
        <div style={{flex:1, minWidth:0}}>
          <div style={{display:'flex', alignItems:'center', gap:8}}>
            <span className="ar lead" style={{fontSize:16}}>{v.name}</span>
            <span className="badge ok" style={{padding:'3px 9px', fontSize:11}}>{v.specLabel}</span>
          </div>
          <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:3}}>{v.title} · {v.exp}</div>
          <div style={{display:'flex', alignItems:'center', gap:10, marginTop:7}}>
            <Stars value={v.rating}/>
            <span className="ar t-mut t-xs" style={{fontWeight:600}}>({v.reviews})</span>
            <span style={{display:'inline-flex', alignItems:'center', gap:4, color:'var(--green)'}}>
              <Icon name="clock" size={13} sw={1.8}/>
              <span className="ar t-xs" style={{fontWeight:700}}>{v.avail}</span>
            </span>
          </div>
        </div>
        <FavBtn on={fav} onClick={onFav}/>
      </div>
    );
  }

  function VetScreen({ go, favVets, toggleFav }){
    const D = window.DATA;
    const [spec,setSpec] = useState('all');
    const list = D.vets.filter(v=>{
      if(spec==='all') return true;
      if(spec==='fav') return favVets.includes(v.id);
      return v.spec===spec;
    });
    return (
      <div className="scroll pad-tab scr-anim">
        <Header title="البيطري"
          right={<button className="hdr-btn" aria-label="اتصال"><Icon name="phone" size={18}/></button>} />

        <div style={{padding:'0 16px 8px'}}>
          <div className="ar t-mut t-sm" style={{fontWeight:600, marginBottom:12}}>اختر طبيباً بيطرياً حسب التخصص</div>
        </div>

        {/* emergency broadcast */}
        <div style={{padding:'0 16px 16px'}}>
          <button onClick={()=>go('vetEmergency')} className="tap"
            style={{width:'100%', border:'none', cursor:'pointer', borderRadius:18, padding:'14px 16px', display:'flex', alignItems:'center', gap:13,
              background:'var(--bad-fg)', color:'#fff', boxShadow:'0 8px 20px rgba(175,74,75,.26)'}}>
            <span style={{width:42, height:42, borderRadius:13, background:'rgba(255,255,255,.18)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto'}}>
              <Icon name="pulse" size={22} color="#fff"/>
            </span>
            <div style={{flex:1, textAlign:'right'}}>
              <div className="ar lead" style={{fontSize:15, color:'#fff'}}>طلب طوارئ فوري</div>
              <div className="ar" style={{fontSize:11.5, fontWeight:600, opacity:.85, marginTop:2}}>أرسل لأقرب طبيب متاح أو لأطبائك المفضلين</div>
            </div>
            <Icon name="chevron-l" size={20} color="#fff"/>
          </button>
        </div>

        {/* specialty filter chips */}
        <div style={{padding:'0 16px 16px'}}>
          <div className="chips">
            {D.vetSpecs.map(s=>(
              <button key={s.id} className={'chip ar '+(spec===s.id?'on':'')} onClick={()=>setSpec(s.id)}>
                {s.id==='fav'
                  ? <span style={{display:'inline-flex', alignItems:'center', gap:5}}><Icon name="heart" size={13} sw={2} fill={spec==='fav'?'#fff':undefined}/>{s.label}</span>
                  : s.label}
              </button>
            ))}
          </div>
        </div>

        {/* doctors */}
        <div style={{padding:'0 16px'}}>
          {list.length ? list.map(v=>(
            <DoctorCard key={v.id} v={v}
              fav={favVets.includes(v.id)}
              onFav={()=>toggleFav(v.id)}
              onOpen={()=>go('vetBook',{id:v.id})} />
          )) : (
            <div className="ar t-mut" style={{textAlign:'center', padding:'48px 0', fontWeight:600}}>
              {spec==='fav' ? 'لم تقم بإضافة أطباء للمفضلة بعد' : 'لا يوجد أطباء في هذا التخصص'}
            </div>
          )}
        </div>

        <SecureNote text="جميع الأطباء معتمدون ومرخّصون." />
      </div>
    );
  }

  /* ───────────────────────── BOOKING ───────────────────────── */
  function VetBookScreen({ back, params, go, favVets, toggleFav }){
    const D = window.DATA;
    const V = D.vets.find(v=>v.id===params.id) || D.vets[0];
    const [svc,setSvc] = useState('general');
    const [day,setDay] = useState('d0');
    const [slot,setSlot] = useState('10:30 ص');
    const [booked,setBooked] = useState(false);
    const fav = favVets.includes(V.id);
    const fmt = (n)=> Number(n).toFixed(3);
    const svcObj = D.vetServices.find(s=>s.id===svc) || D.vetServices[0];
    const isEmergency = svc==='emergency';

    return (
      <div className="scroll pad-tab scr-anim">
        <Header title="حجز موعد" onBack={back}
          right={<button className="hdr-btn" aria-label="اتصال"><Icon name="phone" size={18}/></button>} />

        <div style={{padding:'2px 16px 0'}}>
          {/* vet profile */}
          <div className="card card-pad" style={{display:'flex', alignItems:'center', gap:14, marginBottom:14}}>
            <DocAvatar size={64}/>
            <div style={{flex:1}}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <span className="ar lead" style={{fontSize:17}}>{V.name}</span>
                <span className="badge ok" style={{padding:'3px 9px', fontSize:11}}>{V.specLabel}</span>
              </div>
              <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:2}}>{V.title} · {V.exp}</div>
              <div style={{display:'flex', alignItems:'center', gap:10, marginTop:8}}>
                <Stars value={V.rating}/>
                <span className="ar t-mut t-xs" style={{fontWeight:600}}>({V.reviews} تقييم)</span>
              </div>
            </div>
            <FavBtn on={fav} onClick={()=>toggleFav(V.id)} size={38}/>
          </div>

          {/* services */}
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10, marginBottom:18}}>
            {D.vetServices.map(s=>{
              const on = svc===s.id;
              return (
                <button key={s.id} onClick={()=>setSvc(s.id)} className="card tap"
                  style={{border:on?'1.5px solid var(--green)':'1.5px solid transparent', cursor:'pointer', padding:'14px 6px', display:'flex', flexDirection:'column', alignItems:'center', gap:7, background:on?'var(--green-tint)':'var(--surface)'}}>
                  <span style={{width:40, height:40, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center',
                    background:on?'var(--green)':'var(--surface-2)', color:on?'#fff':'var(--green)'}}>
                    <Icon name={s.icon} size={20}/>
                  </span>
                  <span className="ar lead" style={{fontSize:13, color:on?'var(--green-700)':'var(--ink)'}}>{s.label}</span>
                  <span className="price" style={{fontSize:12, color:on?'var(--green)':'var(--muted)'}}>{fmt(s.price)} <span style={{fontSize:9}}>د.ك</span></span>
                </button>
              );
            })}
          </div>

          {isEmergency ? (
            /* emergency: no scheduling — immediate dispatch */
            <div className="card card-pad" style={{marginBottom:14, background:'var(--bad-bg)', boxShadow:'none', display:'flex', gap:13, alignItems:'flex-start'}}>
              <span style={{width:42, height:42, borderRadius:13, background:'var(--bad-fg)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto'}}>
                <Icon name="pulse" size={22}/>
              </span>
              <div style={{flex:1}}>
                <div className="ar lead" style={{fontSize:14.5, color:'var(--bad-fg)'}}>طلب فوري — بدون موعد</div>
                <div className="ar t-sm" style={{fontWeight:600, marginTop:3, color:'var(--ink-2)'}}>سيتواصل معك {V.name} في أقرب وقت ويتوجّه إلى موقعك مباشرة.</div>
                <button onClick={()=>go && go('vetEmergency')} className="ar" style={{border:'none', background:'none', color:'var(--green)', fontWeight:700, fontSize:13, cursor:'pointer', padding:0, marginTop:8, textDecoration:'underline'}}>
                  أو أرسل الطلب لكل الأطباء المتاحين
                </button>
              </div>
            </div>
          ) : (
            <React.Fragment>
              {/* booking */}
              <h3 className="ar lead" style={{margin:'0 0 12px', fontSize:16}}>احجز موعد زيارة</h3>

              {/* day selector */}
              <div style={{display:'flex', gap:10, marginBottom:14}}>
                {D.vetDays.map(d=>{
                  const on = day===d.id;
                  return (
                    <button key={d.id} onClick={()=>setDay(d.id)} className="tap"
                      style={{flex:1, border:'none', cursor:'pointer', borderRadius:16, padding:'12px 4px', textAlign:'center',
                        background:on?'var(--green)':'var(--surface)', color:on?'#fff':'var(--ink)', boxShadow:'var(--sh-sm)'}}>
                      <div className="ar" style={{fontSize:12, fontWeight:700, opacity:on?.85:.6}}>{d.label}</div>
                      <div className="ar lead" style={{fontSize:14.5, marginTop:3}}>{d.date}</div>
                    </button>
                  );
                })}
              </div>

              {/* slots */}
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10, marginBottom:18}}>
                {D.vetSlots.map(t=>{
                  const on = slot===t;
                  return (
                    <button key={t} onClick={()=>{setSlot(t); setBooked(false);}} className="tap num"
                      style={{border:on?'1.5px solid var(--green)':'1.5px solid var(--line-2)', cursor:'pointer', borderRadius:13, padding:'12px 4px',
                        fontWeight:600, fontSize:13.5, background:on?'var(--green)':'var(--surface)', color:on?'#fff':'var(--ink-2)'}}>
                      {t}
                    </button>
                  );
                })}
              </div>
            </React.Fragment>
          )}

          {/* price summary for the selected service */}
          <div className="card card-pad" style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:14}}>
            <div style={{flex:1, minWidth:0}}>
              <div className="ar lead" style={{fontSize:14.5}}>سعر {svcObj.label}</div>
              <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{svcObj.desc}</div>
            </div>
            <div className="price" style={{fontSize:19, color:'var(--green)', whiteSpace:'nowrap'}}>{fmt(svcObj.price)} <span style={{fontSize:11, color:'var(--muted)'}}>د.ك</span></div>
          </div>

          <button className={'btn ar '+(isEmergency?'':'btn-primary')} onClick={()=>setBooked(true)}
            style={isEmergency?{background:'var(--bad-fg)', color:'#fff', boxShadow:'0 8px 20px rgba(175,74,75,.26)'}:{}}>
            {booked
              ? <React.Fragment><Icon name="check" size={20} color="#fff"/> {isEmergency?'تم إرسال طلب الطوارئ':'تم تأكيد الحجز'}</React.Fragment>
              : (isEmergency ? <React.Fragment><Icon name="pulse" size={19} color="#fff"/> اطلب طوارئ الآن · {fmt(svcObj.price)} د.ك</React.Fragment> : `احجز زيارة · ${fmt(svcObj.price)} د.ك`)}
          </button>

          {booked && (
            <div className="ar t-sm" style={{textAlign:'center', marginTop:10, color:'var(--green)', fontWeight:700}}>
              {isEmergency
                ? `${V.name} في الطريق إليك الآن · ${fmt(svcObj.price)} د.ك`
                : `${svcObj.label} مع ${V.name} · ${D.vetDays.find(d=>d.id===day).date} الساعة ${slot} · ${fmt(svcObj.price)} د.ك`}
            </div>
          )}

          {/* home visit */}
          <div className="card card-pad" style={{marginTop:18, display:'flex', alignItems:'center', gap:14, background:'var(--surface-2)', boxShadow:'none'}}>
            <span style={{width:46, height:46, borderRadius:14, background:'var(--surface)', color:'var(--green)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'var(--sh-sm)'}}>
              <Icon name="home" size={22}/>
            </span>
            <div style={{flex:1}}>
              <div className="ar lead" style={{fontSize:14.5}}>طلب زيارة منزلية</div>
              <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>لا يمكنك الذهاب؟ اطلب زيارة منزلية <span style={{color:'var(--gold)', fontWeight:700}}>(+{fmt(D.vetHomeFee)} د.ك)</span></div>
            </div>
            <span style={{color:'var(--faint)'}}><Icon name="chevron-l" size={20}/></span>
          </div>

          <SecureNote text="جميع بيانات الحجز محفوظة وآمنة." />
        </div>
      </div>
    );
  }

  /* ───────────────────────── EMERGENCY BROADCAST ───────────────────────── */
  function VetEmergencyScreen({ back, favVets }){
    const D = window.DATA;
    const fmt = (n)=> Number(n).toFixed(3);
    const svcObj = D.vetServices.find(s=>s.id==='emergency') || D.vetServices[2];
    const [mode,setMode] = useState('available'); // available | fav
    const [sent,setSent] = useState(false);

    const available = D.vets.filter(v=> v.avail.includes('الآن') || v.avail.includes('اليوم'));
    const favs = D.vets.filter(v=> favVets.includes(v.id));
    const recipients = mode==='fav' ? favs : available;
    const responder = recipients.find(v=>v.avail.includes('الآن')) || recipients[0];

    if(sent){
      return (
        <div className="scroll scr-anim" style={{display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:'0 26px'}}>
          <div style={{width:96, height:96, borderRadius:'50%', background:'var(--bad-bg)', color:'var(--bad-fg)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:22}}>
            <Icon name="pulse" size={46}/>
          </div>
          <div className="ar lead" style={{fontSize:21, color:'var(--ink)'}}>تم إرسال طلب الطوارئ</div>
          <div className="ar t-mut" style={{fontSize:14, fontWeight:600, marginTop:8, lineHeight:1.7}}>
            أُرسل طلبك إلى {recipients.length} {recipients.length===1?'طبيب متاح':'أطباء متاحين'}
          </div>
          {responder && (
            <div className="card card-pad" style={{marginTop:22, width:'100%', display:'flex', alignItems:'center', gap:12, textAlign:'right'}}>
              <DocAvatar size={50}/>
              <div style={{flex:1}}>
                <div className="ar lead" style={{fontSize:15}}>{responder.name}</div>
                <span className="badge ok" style={{marginTop:5, fontSize:11}}><span className="dot"/>استجاب · في الطريق إليك</span>
              </div>
              <button className="hdr-btn" aria-label="اتصال"><Icon name="phone" size={18}/></button>
            </div>
          )}
          <button className="btn btn-primary ar" style={{marginTop:18, width:'auto', padding:'14px 30px'}} onClick={back}>تم</button>
        </div>
      );
    }

    return (
      <React.Fragment>
        <div className="scroll pad-cta scr-anim">
          <Header title="طلب طوارئ" onBack={back} />
          <div style={{padding:'2px 16px 0'}}>
            {/* banner */}
            <div className="card card-pad" style={{background:'var(--bad-bg)', boxShadow:'none', display:'flex', gap:13, alignItems:'flex-start', marginBottom:16}}>
              <span style={{width:46, height:46, borderRadius:14, background:'var(--bad-fg)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto'}}>
                <Icon name="pulse" size={23}/>
              </span>
              <div style={{flex:1}}>
                <div className="ar lead" style={{fontSize:15, color:'var(--bad-fg)'}}>حالة طارئة</div>
                <div className="ar t-sm" style={{fontWeight:600, marginTop:3, color:'var(--ink-2)'}}>يُرسل الطلب فوراً لعدة أطباء، وأول من يستجيب يتوجّه إلى موقعك.</div>
              </div>
            </div>

            {/* recipients choice */}
            <h3 className="ar lead" style={{margin:'0 0 12px', fontSize:16}}>إرسال إلى</h3>
            <div style={{display:'flex', gap:10, marginBottom:14}}>
              {[{id:'available',label:'الأطباء المتاحون',count:available.length},{id:'fav',label:'أطبائي المفضلون',count:favs.length}].map(o=>{
                const on = mode===o.id;
                return (
                  <button key={o.id} onClick={()=>setMode(o.id)} className="tap"
                    style={{flex:1, border:on?'1.5px solid var(--green)':'1.5px solid var(--line-2)', cursor:'pointer', borderRadius:16, padding:'13px 8px', textAlign:'center',
                      background:on?'var(--green-tint)':'var(--surface)'}}>
                    <div className="ar lead" style={{fontSize:13.5, color:on?'var(--green-700)':'var(--ink)'}}>{o.label}</div>
                    <div className="ar t-mut t-xs" style={{fontWeight:700, marginTop:3}}>{o.count} أطباء</div>
                  </button>
                );
              })}
            </div>

            {/* recipients list */}
            <div className="card" style={{overflow:'hidden', marginBottom:14}}>
              {recipients.length ? recipients.map((v,i)=>(
                <div key={v.id} style={{display:'flex', alignItems:'center', gap:12, padding:'12px 14px', borderTop:i?'1px solid var(--line)':'none'}}>
                  <DocAvatar size={42}/>
                  <div style={{flex:1, minWidth:0}}>
                    <div className="ar lead" style={{fontSize:14}}>{v.name}</div>
                    <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{v.specLabel} · {v.avail}</div>
                  </div>
                  <span className={'badge '+(v.avail.includes('الآن')?'ok':'info')} style={{fontSize:10.5, padding:'3px 8px'}}><span className="dot"/>{v.avail}</span>
                </div>
              )) : (
                <div className="ar t-mut" style={{textAlign:'center', padding:'28px 0', fontWeight:600}}>لا يوجد أطباء في هذه القائمة</div>
              )}
            </div>

            {/* horse + price */}
            <div className="card card-pad" style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
              <span className="ar lead" style={{fontSize:14.5}}>رسوم الطوارئ</span>
              <span className="price" style={{fontSize:19, color:'var(--bad-fg)'}}>{fmt(svcObj.price)} <span style={{fontSize:11, color:'var(--muted)'}}>د.ك</span></span>
            </div>

            <SecureNote text="سيتم تحديد موقعك تلقائياً لإرسال الطبيب." />
          </div>
        </div>

        <div className="cta-bar">
          <button className="btn ar" disabled={!recipients.length} onClick={()=>setSent(true)}
            style={{background:'var(--bad-fg)', color:'#fff', boxShadow:'0 8px 20px rgba(175,74,75,.26)', opacity:recipients.length?1:.5}}>
            <Icon name="pulse" size={19} color="#fff"/> إرسال طلب الطوارئ · {fmt(svcObj.price)} د.ك
          </button>
        </div>
      </React.Fragment>
    );
  }

  Object.assign(window, { VetScreen, VetBookScreen, VetEmergencyScreen });
})();
