// screens-home.jsx — dashboard (الرئيسية)
(function(){
  const { useState } = React;
  const Icon = window.Icon;
  const { HorseAvatar, ProductThumb, Badge } = window;

  // ── single horse hero card ──
  function HorseHero({ h, onOpen }){
    const stats = [ ['العمر', h.age], ['السلالة', h.breed], ['اللون', h.color] ];
    return (
      <div className="card tap" onClick={onOpen} style={{padding:0, overflow:'hidden'}}>
        <div style={{padding:'16px 16px 15px', display:'flex', alignItems:'center', gap:14, position:'relative', overflow:'hidden'}}>
          <div style={{position:'absolute', insetInlineStart:-46, top:-34, width:150, height:150, borderRadius:'50%', background:'var(--green-tint)', opacity:.55}}/>
          <HorseAvatar size={66}/>
          <div style={{flex:1, position:'relative', minWidth:0}}>
            <div style={{display:'flex', alignItems:'center', gap:8}}>
              <span className="ar lead" style={{fontSize:18, color:'var(--ink)'}}>{h.name}</span>
              <span className={'badge '+(h.statusCls||'ok')}><span className="dot"/>{h.status||'الحالة ممتازة'}</span>
            </div>
            <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:4}}>عرض الملف الصحي الكامل</div>
          </div>
          <span style={{color:'var(--faint)', position:'relative'}}><Icon name="chevron-l" size={20}/></span>
        </div>
        <div style={{display:'flex', textAlign:'center', borderTop:'1px solid var(--line)'}}>
          {stats.map((s,i)=>(
            <div key={i} style={{flex:1, padding:'12px 4px', borderInlineStart:i?'1px solid var(--line)':'none'}}>
              <div className="ar lead" style={{fontSize:14, color:'var(--ink)'}}>{s[1]}</div>
              <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:3}}>{s[0]}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── horse switcher: a scrollable list to pick the active horse (scales to many) ──
  function HorseSwitcher({ horses, active, setActive, onAdd }){
    const [expanded,setExpanded] = useState(false);
    const CAP = 3;
    const many = horses.length > CAP;
    const shown = expanded ? horses : horses.slice(0, CAP);
    return (
      <div style={{padding:'20px 16px 0'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:12}}>
          <h3 className="ar lead" style={{margin:0, fontSize:16}}>خيولي <span className="t-mut" style={{fontSize:13, fontWeight:700}}>({horses.length})</span></h3>
          <button onClick={onAdd} className="ar" style={{border:'none', background:'none', color:'var(--green)', fontWeight:700, fontSize:13, cursor:'pointer'}}>+ إضافة</button>
        </div>
        <div className="card" style={{overflow:'hidden'}}>
          {shown.map((h,i)=>{
            const on = i===active;
            return (
              <button key={i} onClick={()=>setActive(i)}
                style={{width:'100%', border:'none', cursor:'pointer', display:'flex', alignItems:'center', gap:12, padding:'12px 14px', textAlign:'right',
                  background:on?'var(--green-tint)':'transparent', borderTop:i?'1px solid var(--line)':'none'}}>
                <HorseAvatar size={44}/>
                <div style={{flex:1, minWidth:0}}>
                  <div className="ar lead" style={{fontSize:14.5, color:'var(--ink)'}}>{h.name}</div>
                  <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{h.breed} · {h.age}</div>
                </div>
                {on
                  ? <span style={{width:24, height:24, borderRadius:'50%', background:'var(--green)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto'}}><Icon name="check" size={15} sw={2.6}/></span>
                  : <span className={'badge '+(h.statusCls||'ok')} style={{fontSize:10.5, padding:'3px 8px'}}><span className="dot"/>{h.status||'نشط'}</span>}
              </button>
            );
          })}
        </div>
        {many && (
          <button onClick={()=>setExpanded(e=>!e)} className="btn btn-soft ar" style={{marginTop:10, padding:'12px', fontSize:13.5}}>
            {expanded ? 'عرض أقل' : `عرض كل الخيول (${horses.length})`}
            <Icon name="chevron-l" size={16} style={{transform: expanded?'rotate(90deg)':'rotate(-90deg)'}}/>
          </button>
        )}
      </div>
    );
  }

  function QuickAction({ icon, label, sub, onClick, accent }){
    return (
      <button className="card tap" onClick={onClick}
        style={{border:'none', textAlign:'right', padding:'15px 14px', cursor:'pointer', display:'flex', flexDirection:'column', gap:11, alignItems:'flex-start'}}>
        <span style={{width:44, height:44, borderRadius:14, background:accent?'var(--green)':'var(--green-tint)',
          color:accent?'#fff':'var(--green)', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <Icon name={icon} size={22}/>
        </span>
        <span style={{display:'flex', flexDirection:'column', gap:3}}>
          <span className="ar lead" style={{fontSize:15, color:'var(--ink)'}}>{label}</span>
          <span className="ar t-mut" style={{fontSize:11.5, fontWeight:600}}>{sub}</span>
        </span>
      </button>
    );
  }

  function HomeScreen({ go, setTab }){
    const D = window.DATA;
    const [active,setActive] = useState(0);
    const tStep = D.transport.steps.filter(s=>s.done).length;

    return (
      <div className="scroll pad-tab scr-anim">
        {/* greeting bar */}
        <div style={{padding:'56px 18px 10px', display:'flex', alignItems:'center', gap:12}}>
          <div style={{flex:1, lineHeight:1.35}}>
            <div className="ar t-mut" style={{fontSize:12.5, fontWeight:700}}>السبت، 10 مايو</div>
            <div className="ar lead" style={{fontSize:20, color:'var(--ink)', marginTop:1}}>أهلاً، عبدالله 👋</div>
          </div>
          <button className="hdr-btn" aria-label="إضافة خيل" onClick={()=>go('addHorse')}>
            <Icon name="plus" size={21} sw={2.2}/>
          </button>
          <button className="hdr-btn" aria-label="الإشعارات" style={{position:'relative'}}>
            <Icon name="bell" size={20}/>
            <span style={{position:'absolute', top:9, left:11, width:7, height:7, borderRadius:'50%', background:'var(--gold)', border:'1.5px solid var(--surface)'}}/>
          </button>
        </div>

        {/* featured (active) horse */}
        <div style={{padding:'4px 16px 0'}}>
          <HorseHero h={D.horses[active]} onOpen={()=>go('health')} />
        </div>

        {/* horse switcher list (scales to many) */}
        <HorseSwitcher horses={D.horses} active={active} setActive={setActive} onAdd={()=>go('addHorse')} />

        {/* quick actions grid */}
        <div style={{padding:'20px 16px 4px'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:12}}>
            <h3 className="ar lead" style={{margin:0, fontSize:16}}>الخدمات</h3>
            <span className="ar t-mut t-xs" style={{fontWeight:700}}>كل ما يحتاجه حصانك</span>
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
            <QuickAction icon="bag"    label="الأعلاف"     sub="أعلاف عالية الجودة" onClick={()=>setTab('feed')} accent/>
            <QuickAction icon="stetho" label="البيطري"     sub="حجز موعد وفحص"      onClick={()=>setTab('vet')} />
            <QuickAction icon="shield" label="الملف الصحي" sub="السجل والتطعيمات"   onClick={()=>go('health')} />
            <QuickAction icon="truck"  label="النقل"       sub="نقل آمن ومريح"      onClick={()=>setTab('transport')} />
          </div>
        </div>

        {/* active transport tracker */}
        <div style={{padding:'20px 16px 0'}}>
          <h3 className="ar lead" style={{margin:'0 0 12px', fontSize:16}}>رحلة جارية</h3>
          <div className="card tap" onClick={()=>go('tripTrack')} style={{padding:16}}>
            <div style={{display:'flex', alignItems:'center', gap:11, marginBottom:14}}>
              <span style={{width:40, height:40, borderRadius:12, background:'var(--green)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto'}}><Icon name="truck" size={21}/></span>
              <div style={{flex:1, minWidth:0}}>
                <div className="ar lead" style={{fontSize:14.5}}>رحلة إلى {D.transport.to}</div>
                <div className="num t-mut" style={{fontSize:12, fontWeight:600, marginTop:2}}>{D.transport.id}</div>
              </div>
              <span className="badge info"><span className="dot"/>في الطريق</span>
            </div>
            <div style={{display:'flex', alignItems:'center', gap:5}}>
              {D.transport.steps.map((s,i)=>(
                <React.Fragment key={i}>
                  <span style={{width:11, height:11, borderRadius:'50%', flex:'0 0 auto',
                    background: i<tStep ? 'var(--green)' : (s.active?'var(--gold)':'var(--line-2)'),
                    boxShadow: s.active?'0 0 0 4px rgba(176,138,69,.22)':'none'}}/>
                  {i<D.transport.steps.length-1 && <span style={{flex:1, height:3, borderRadius:2, background: i<tStep-1?'var(--green)':'var(--line-2)'}}/>}
                </React.Fragment>
              ))}
            </div>
            <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:11}}>المرحلة الأخيرة · توصيل الخيل إلى المرسل</div>
          </div>
        </div>

        {/* recent feed orders */}
        <div style={{padding:'20px 16px 0'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:12}}>
            <h3 className="ar lead" style={{margin:0, fontSize:16}}>آخر طلبات الأعلاف</h3>
            <button onClick={()=>go('orders')} className="ar" style={{border:'none', background:'none', color:'var(--green)', fontWeight:700, fontSize:13, cursor:'pointer'}}>عرض الكل</button>
          </div>
          {D.orders.slice(0,3).map(o=>(
            <div key={o.id} className="card tap" onClick={()=>go('feedDetail',{order:o})} style={{padding:16, display:'flex', alignItems:'center', gap:12, marginBottom:10}}>
              <div style={{display:'flex', gap:6}}>
                {o.items.slice(0,2).map((it,i)=>(<ProductThumb key={i} size={44} tone={D.products[it.p].tone} radius={11} label={D.products[it.p].unit}/>))}
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div className="num lead" style={{fontSize:14}}>{o.id}</div>
                <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:3}}>{o.count} · {o.place}</div>
              </div>
              <div style={{textAlign:'left'}}>
                <div className="price" style={{fontSize:16, color:'var(--green)'}}>{o.total} <span style={{fontSize:11}}>د.ك</span></div>
                <div style={{marginTop:5}}><Badge status={o.status}/></div>
              </div>
            </div>
          ))}
          {D.orders.length>3 && (
            <button onClick={()=>go('orders')} className="btn btn-soft ar" style={{marginTop:4, padding:'13px', fontSize:14}}>
              عرض المزيد ({D.orders.length-3}+) <Icon name="chevron-l" size={17}/>
            </button>
          )}
        </div>
      </div>
    );
  }
  /* ───────────────────────── ADD HORSE ───────────────────────── */
  const { Header, SecureNote } = window;

  const inputStyle = {
    width:'100%', border:'none', background:'var(--surface)', borderRadius:14, padding:'13px 14px',
    fontSize:14.5, fontWeight:700, color:'var(--ink)', boxShadow:'var(--sh-sm)',
    fontFamily:"'Tajawal',sans-serif"
  };

  function Field({ label, children }){
    return (
      <div style={{marginBottom:14}}>
        <div className="ar t-mut t-xs" style={{fontWeight:700, marginBottom:7}}>{label}</div>
        {children}
      </div>
    );
  }

  function ChipPick({ options, value, onChange }){
    return (
      <div className="chips" style={{flexWrap:'wrap'}}>
        {options.map(o=>(
          <button key={o} className={'chip ar '+(value===o?'on':'')} onClick={()=>onChange(o)}>{o}</button>
        ))}
      </div>
    );
  }

  function AddHorseScreen({ back }){
    const [name,setName]   = useState('');
    const [age,setAge]     = useState('');
    const [sex,setSex]     = useState('ذكر');
    const [breed,setBreed] = useState('عربي أصيل');
    const [color,setColor] = useState('أشقر');
    const [stable,setStable] = useState('');
    const [done,setDone]   = useState(false);

    const breeds = ['عربي أصيل','إنجليزي','مهجّن','شعبي','بربري'];
    const colors = ['أشقر','أدهم','أشهب','كميت','أحمر','أبلق'];
    const canSave = name.trim().length>0;

    if(done){
      return (
        <div className="scroll scr-anim" style={{display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:'0 30px'}}>
          <div style={{width:96, height:96, borderRadius:'50%', background:'var(--ok-bg)', color:'var(--ok-fg)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:22}}>
            <Icon name="check" size={48} sw={2.4}/>
          </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}}>
            {name} · {breed} · {age || '—'}
          </div>
          <button className="btn btn-primary ar" style={{marginTop:26, 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'}}>
            {/* photo */}
            <div style={{display:'flex', justifyContent:'center', marginBottom:20}}>
              <button aria-label="إضافة صورة" style={{border:'none', background:'none', cursor:'pointer', position:'relative'}}>
                <div className="ph avatar-ring" style={{width:96, height:96, borderRadius:'50%', padding:0}}>
                  <div className="ph" style={{width:96, height:96, borderRadius:'50%'}}><span className="ph-label">صورة<br/>الخيل</span></div>
                </div>
                <span style={{position:'absolute', bottom:2, left:2, width:32, height:32, borderRadius:'50%', background:'var(--green)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', border:'3px solid var(--bg)'}}>
                  <Icon name="plus" size={16} sw={2.4}/>
                </span>
              </button>
            </div>

            <Field label="اسم الخيل">
              <input value={name} onChange={e=>setName(e.target.value)} placeholder="مثال: شاهين" className="ar" style={inputStyle}/>
            </Field>

            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
              <Field label="العمر">
                <input value={age} onChange={e=>setAge(e.target.value)} placeholder="6 سنوات" className="ar" style={inputStyle}/>
              </Field>
              <Field label="الجنس">
                <div style={{display:'flex', gap:8}}>
                  {['ذكر','أنثى'].map(s=>(
                    <button key={s} onClick={()=>setSex(s)} className="ar"
                      style={{flex:1, border:'none', cursor:'pointer', borderRadius:14, padding:'13px 4px', fontWeight:700, fontSize:14,
                        background:sex===s?'var(--green)':'var(--surface)', color:sex===s?'#fff':'var(--ink-2)', boxShadow:'var(--sh-sm)'}}>{s}</button>
                  ))}
                </div>
              </Field>
            </div>

            <Field label="السلالة"><ChipPick options={breeds} value={breed} onChange={setBreed}/></Field>
            <Field label="اللون"><ChipPick options={colors} value={color} onChange={setColor}/></Field>

            <Field label="الإسطبل">
              <input value={stable} onChange={e=>setStable(e.target.value)} placeholder="مثال: إسطبل الوفرة" className="ar" style={inputStyle}/>
            </Field>

            <SecureNote text="بيانات خيلك محفوظة وآمنة." />
          </div>
        </div>

        <div className="cta-bar">
          <button className="btn btn-primary ar" disabled={!canSave} onClick={()=>setDone(true)}
            style={!canSave?{opacity:.5}:{}}>
            <Icon name="check" size={19} color="#fff"/> حفظ الخيل
          </button>
        </div>
      </React.Fragment>
    );
  }

  Object.assign(window, { HomeScreen, AddHorseScreen });
})();
