// screens-feed.jsx — feed store (المتجر): products list, product detail, cart, + orders (طلباتي)
(function(){
  const { useState } = React;
  const Icon = window.Icon;
  const { Header, Badge, Segmented, ProductThumb, KV, SectionTitle, SecureNote } = window;

  const fmt = (n)=> Number(n).toFixed(3);

  // ── cart button for headers (with live count) ──
  function CartButton({ count, onClick }){
    return (
      <button className="hdr-btn" onClick={onClick} aria-label="السلة" style={{position:'relative'}}>
        <Icon name="bag" size={19}/>
        {count>0 && (
          <span className="num" style={{position:'absolute', top:-5, left:-6, minWidth:17, height:17, padding:'0 4px',
            background:'var(--gold)', color:'#fff', borderRadius:9, fontSize:10, fontWeight:700,
            display:'flex', alignItems:'center', justifyContent:'center', border:'2px solid var(--bg)'}}>{count}</span>
        )}
      </button>
    );
  }

  // ── quantity stepper ──
  function Stepper({ value, onChange, min=1 }){
    return (
      <div style={{display:'flex', alignItems:'center', gap:0, background:'var(--surface-2)', borderRadius:'var(--r-pill)', padding:4}}>
        <button onClick={()=>onChange(value+1)} aria-label="زيادة"
          style={{width:30, height:30, border:'none', borderRadius:'50%', background:'var(--surface)', color:'var(--green)', cursor:'pointer', boxShadow:'var(--sh-sm)', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <Icon name="plus" size={16} sw={2.2}/>
        </button>
        <span className="num lead" style={{minWidth:30, textAlign:'center', fontSize:15}}>{value}</span>
        <button onClick={()=>onChange(Math.max(min,value-1))} aria-label="إنقاص" disabled={value<=min}
          style={{width:30, height:30, border:'none', borderRadius:'50%', background:'var(--surface)', color:value<=min?'var(--faint)':'var(--green)', cursor:value<=min?'default':'pointer', boxShadow:'var(--sh-sm)', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <span style={{width:13, height:2.2, borderRadius:2, background:'currentColor'}}/>
        </button>
      </div>
    );
  }

  /* ───────────────────────── STORE (products list) ───────────────────────── */
  function ProductCard({ id, p, onOpen, onAdd }){
    return (
      <div className="card tap" onClick={onOpen} style={{padding:10, display:'flex', flexDirection:'column', gap:9, position:'relative', overflow:'hidden'}}>
        <ProductThumb size={'100%'} tone={p.tone} radius={15} label={p.unit}/>
        <div style={{padding:'0 2px'}}>
          <div className="ar lead" style={{fontSize:14.5, color:'var(--ink)'}}>{p.name}</div>
          <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{p.note} · {p.weight}</div>
          <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:9}}>
            <div className="price" style={{fontSize:16, color:'var(--green)'}}>{fmt(p.price)} <span style={{fontSize:10, color:'var(--muted)'}}>د.ك</span></div>
            <button onClick={(e)=>{ e.stopPropagation(); onAdd(); }} aria-label="أضف للسلة"
              style={{width:34, height:34, border:'none', borderRadius:12, background:'var(--green)', color:'#fff', cursor:'pointer', boxShadow:'0 4px 12px rgba(30,74,53,.28)', display:'flex', alignItems:'center', justifyContent:'center'}}>
              <Icon name="plus" size={18} sw={2.3}/>
            </button>
          </div>
        </div>
      </div>
    );
  }

  function FeedListScreen({ go, cart, addToCart }){
    const D = window.DATA;
    const [cat,setCat] = useState('الكل');
    const count = cart.reduce((s,c)=>s+c.qty,0);
    const keys = Object.keys(D.products).filter(k=> cat==='الكل' ? true : D.products[k].cat===cat);
    const cats = D.shopCats.map(c=>({ id:c, label:c }));
    return (
      <div className="scroll pad-tab scr-anim">
        <Header title="متجر الأعلاف"
          right={<CartButton count={count} onClick={()=>go('cart')} />} />

        {/* search (decorative) */}
        <div style={{padding:'2px 16px 12px'}}>
          <div style={{display:'flex', alignItems:'center', gap:9, background:'var(--surface)', borderRadius:'var(--r-pill)', padding:'12px 16px', boxShadow:'var(--sh-sm)', color:'var(--muted)'}}>
            <Icon name="search" size={18} sw={1.9}/>
            <span className="ar t-sm" style={{fontWeight:600}}>ابحث عن علف أو مكمل…</span>
          </div>
        </div>

        {/* category chips */}
        <div style={{padding:'0 16px 14px'}}>
          <Segmented items={cats} value={cat} onChange={setCat}/>
        </div>

        {/* products grid */}
        <div style={{padding:'0 16px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
          {keys.map(k=>(
            <ProductCard key={k} id={k} p={D.products[k]}
              onOpen={()=>go('product',{id:k})}
              onAdd={()=>addToCart(k,1)} />
          ))}
        </div>
      </div>
    );
  }

  /* ───────────────────────── PRODUCT DETAIL ───────────────────────── */
  function ProductDetailScreen({ back, params, go, cart, addToCart }){
    const D = window.DATA;
    const id = params.id;
    const p = D.products[id];
    const [qty,setQty] = useState(1);
    const count = cart.reduce((s,c)=>s+c.qty,0);
    return (
      <React.Fragment>
        <div className="scroll pad-cta scr-anim">
          <Header title="تفاصيل المنتج" onBack={back}
            right={<CartButton count={count} onClick={()=>go('cart')} />} />

          <div style={{padding:'2px 16px 0'}}>
            {/* hero image */}
            <ProductThumb size={'100%'} tone={p.tone} radius={22} label={p.name}/>

            {/* title row */}
            <div style={{display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10, marginTop:16}}>
              <div style={{flex:1}}>
                <div className="ar lead" style={{fontSize:21, color:'var(--ink)'}}>{p.name}</div>
                <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:4}}>{p.note}</div>
              </div>
              <span style={{display:'inline-flex', alignItems:'center', gap:4, color:'var(--gold)', background:'var(--warn-bg)', padding:'5px 10px', borderRadius:'var(--r-pill)'}}>
                <Icon name="star" size={14} fill="var(--gold)"/>
                <span className="num" style={{fontWeight:700, fontSize:12.5, color:'var(--warn-fg)'}}>{p.rating}</span>
              </span>
            </div>

            {/* price + spec chips */}
            <div style={{display:'flex', alignItems:'center', gap:8, margin:'14px 0'}}>
              <div className="price" style={{fontSize:24, color:'var(--green)'}}>{fmt(p.price)} <span style={{fontSize:13, color:'var(--muted)'}}>د.ك</span></div>
              <span className="ar t-mut t-sm" style={{fontWeight:600}}>/ {p.unit}</span>
              <span style={{flex:1}}/>
              <span className="badge info"><span className="dot"/>{p.weight}</span>
              <span className="badge ok"><span className="dot"/>{p.cat}</span>
            </div>

            {/* description */}
            <div className="card card-pad" style={{marginBottom:12}}>
              <SectionTitle icon="doc">الوصف</SectionTitle>
              <p className="ar" style={{margin:0, fontSize:14, lineHeight:1.85, color:'var(--ink-2)', fontWeight:500}}>{p.desc}</p>
            </div>

            {/* quantity */}
            <div className="card card-pad" style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
              <span className="ar lead" style={{fontSize:15}}>الكمية</span>
              <Stepper value={qty} onChange={setQty}/>
            </div>

            <SecureNote text="منتجات أصلية ومضمونة الجودة." />
          </div>
        </div>

        <div className="cta-bar">
          <button className="btn btn-primary ar" onClick={()=>{ addToCart(id,qty); go('cart'); }}>
            <Icon name="bag" size={19} color="#fff"/> أضف للسلة · {fmt(p.price*qty)} د.ك
          </button>
        </div>
      </React.Fragment>
    );
  }

  /* ───────────────────────── CART ───────────────────────── */
  function CartScreen({ back, go, cart, setQty, removeItem, clearCart }){
    const D = window.DATA;
    const [placed,setPlaced] = useState(false);

    const sub = cart.reduce((s,c)=> s + D.products[c.id].price*c.qty, 0);
    const ship = cart.length ? (sub>=20 ? 0 : 2) : 0;
    const total = sub + ship;

    if(placed){
      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}}>سيتم تجهيز طلبك وتوصيله في أقرب وقت. يمكنك متابعة حالته من طلباتي.</div>
          <button className="btn btn-primary ar" style={{marginTop:26, width:'auto', padding:'14px 28px'}} onClick={()=>go('orders')}>عرض طلباتي</button>
          <button className="btn btn-line ar" style={{marginTop:10, width:'auto', padding:'12px 28px'}} onClick={back}>متابعة التسوق</button>
        </div>
      );
    }

    if(!cart.length){
      return (
        <React.Fragment>
          <Header title="سلة المشتريات" onBack={back} />
          <div className="scroll scr-anim" style={{display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:'0 30px', marginTop:-60}}>
            <div style={{width:88, height:88, borderRadius:'50%', background:'var(--surface-2)', color:'var(--faint)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:18}}>
              <Icon name="bag" size={40}/>
            </div>
            <div className="ar lead" style={{fontSize:18, color:'var(--ink)'}}>سلتك فارغة</div>
            <div className="ar t-mut" style={{fontSize:13.5, fontWeight:600, marginTop:6}}>أضف بعض الأعلاف لتبدأ طلبك</div>
            <button className="btn btn-primary ar" style={{marginTop:22, width:'auto', padding:'13px 28px'}} onClick={back}>تصفح المتجر</button>
          </div>
        </React.Fragment>
      );
    }

    return (
      <React.Fragment>
        <div className="scroll pad-cta scr-anim">
          <Header title="سلة المشتريات" onBack={back}
            right={<button className="hdr-btn" onClick={clearCart} aria-label="تفريغ"><Icon name="tag" size={18}/></button>} />

          <div style={{padding:'2px 16px 0'}}>
            {/* items */}
            <div className="card card-pad" style={{marginBottom:12}}>
              {cart.map((c,i)=>{
                const p = D.products[c.id];
                return (
                  <div key={c.id} style={{display:'flex', alignItems:'center', gap:12, padding:'12px 0', borderTop:i?'1px solid var(--line)':'none'}}>
                    <ProductThumb size={56} tone={p.tone} label={p.unit}/>
                    <div style={{flex:1, minWidth:0}}>
                      <div className="ar lead" style={{fontSize:14.5}}>{p.name}</div>
                      <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{p.weight}</div>
                      <div className="price" style={{fontSize:14.5, color:'var(--green)', marginTop:5}}>{fmt(p.price*c.qty)} <span style={{fontSize:10, color:'var(--muted)'}}>د.ك</span></div>
                    </div>
                    <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:8}}>
                      <button onClick={()=>removeItem(c.id)} aria-label="حذف" style={{border:'none', background:'none', color:'var(--faint)', cursor:'pointer', padding:2}}>
                        <Icon name="plus" size={17} sw={2} style={{transform:'rotate(45deg)'}}/>
                      </button>
                      <Stepper value={c.qty} onChange={(q)=>setQty(c.id,q)}/>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* summary */}
            <div className="card card-pad">
              <SectionTitle icon="wallet">ملخص الطلب</SectionTitle>
              <KV k="إجمالي المنتجات" v={fmt(sub)+' د.ك'} />
              <KV k="تكلفة التوصيل" v={ship===0 ? 'مجاني' : fmt(ship)+' د.ك'} accent={ship===0?'var(--ok-fg)':null}/>
              <div className="rowline" style={{margin:'8px 0'}}/>
              <KV k="الإجمالي الكلي" v={fmt(total)+' د.ك'} strong/>
              {sub<20 && <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:8, color:'var(--gold)'}}>أضف {fmt(20-sub)} د.ك للحصول على توصيل مجاني</div>}
            </div>

            <SecureNote text="الدفع آمن ومشفّر بالكامل." />
          </div>
        </div>

        <div className="cta-bar">
          <button className="btn btn-primary ar" onClick={()=>{ setPlaced(true); clearCart(); }}>
            <Icon name="check" size={19} color="#fff"/> تأكيد الطلب · {fmt(total)} د.ك
          </button>
        </div>
      </React.Fragment>
    );
  }

  /* ───────────────────────── ORDERS (now under المزيد) ───────────────────────── */
  const FILTERS = [
    { id:'all',        label:'الكل' },
    { id:'preparing',  label:'قيد التجهيز' },
    { id:'delivering', label:'قيد التوصيل' },
    { id:'delivered',  label:'تم التوصيل' },
    { id:'cancelled',  label:'ملغي' },
  ];

  function OrderCard({ o, onOpen }){
    const D = window.DATA;
    return (
      <div className="card" style={{padding:16, marginBottom:12}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <Badge status={o.status}/>
          <div style={{display:'flex', alignItems:'center', gap:7}}>
            <span className="num lead" style={{fontSize:14.5}}>{o.id}</span>
            <Icon name="tag" size={16} color="var(--faint)"/>
          </div>
        </div>
        <div style={{display:'flex', alignItems:'center', gap:12, margin:'13px 0'}}>
          <div style={{flex:1}}>
            <div className="price" style={{fontSize:19, color:'var(--ink)'}}>{o.total} <span style={{fontSize:12, color:'var(--muted)'}}>د.ك</span></div>
            <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:3}}>{o.count}</div>
          </div>
          <div style={{display:'flex', gap:6}}>
            {o.items.slice(0,3).map((it,i)=>(<ProductThumb key={i} size={46} tone={D.products[it.p].tone} label={D.products[it.p].unit}/>))}
          </div>
        </div>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <div style={{display:'flex', alignItems:'center', gap:6, color:'var(--muted)'}}>
            <Icon name="pin" size={15} sw={1.7}/>
            <span className="ar t-sm" style={{fontWeight:600}}>{o.place}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap:6, color:'var(--muted)'}}>
            <span className="ar t-xs" style={{fontWeight:600}}>{o.date} · {o.time}</span>
            <Icon name="clock" size={14} sw={1.7}/>
          </div>
        </div>
        <button className="btn btn-soft ar" onClick={()=>onOpen(o)} style={{marginTop:14, padding:'12px', fontSize:14, background:'var(--surface-2)', boxShadow:'none'}}>
          عرض التفاصيل
        </button>
      </div>
    );
  }

  function OrdersScreen({ go, back }){
    const D = window.DATA;
    const [filter,setFilter] = useState('all');
    const list = D.orders.filter(o=> filter==='all' ? true : o.status===filter);
    const totalAll = D.orders.reduce((s,o)=> s + parseFloat(o.total), 0).toFixed(3);
    return (
      <div className="scroll pad-tab scr-anim">
        <Header title="طلباتي" onBack={back}
          right={<button className="hdr-btn" aria-label="طباعة"><Icon name="printer" size={19}/></button>} />

        <div style={{padding:'2px 16px 14px'}}>
          <Segmented items={FILTERS} value={filter} onChange={setFilter}/>
        </div>

        {/* summary strip */}
        <div style={{padding:'0 16px 14px'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', background:'var(--green)', borderRadius:18, padding:'13px 16px', color:'#fff'}}>
            <div style={{display:'flex', alignItems:'center', gap:9}}>
              <Icon name="box" size={20} color="rgba(255,255,255,.85)"/>
              <span className="ar" style={{fontWeight:700, fontSize:13.5, opacity:.9}}>{D.orders.length} طلبات</span>
            </div>
            <div style={{textAlign:'left'}}>
              <div className="ar t-xs" style={{opacity:.7, fontWeight:600}}>إجمالي الطلبات</div>
              <div className="price" style={{fontSize:17}}>{totalAll} <span style={{fontSize:11, opacity:.8}}>د.ك</span></div>
            </div>
          </div>
        </div>

        <div style={{padding:'0 16px'}}>
          {list.length ? list.map(o=>(<OrderCard key={o.id} o={o} onOpen={(ord)=>go('feedDetail',{order:ord})}/>))
            : <div className="ar t-mut" style={{textAlign:'center', padding:'48px 0', fontWeight:600}}>لا توجد طلبات في هذه الحالة</div>}
        </div>
      </div>
    );
  }

  function FeedDetailScreen({ back, params }){
    const D = window.DATA;
    const o = params.order;
    return (
      <React.Fragment>
        <div className="scroll pad-cta scr-anim">
          <Header title="تفاصيل الطلب" onBack={back}
            right={<button className="hdr-btn" aria-label="الدعم"><Icon name="headset" size={19}/></button>} />

          <div style={{padding:'2px 16px 0'}}>
            {/* order head */}
            <div className="card card-pad" style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:12}}>
              <Badge status={o.status}/>
              <div style={{textAlign:'left'}}>
                <div className="num lead" style={{fontSize:16}}>{o.id}</div>
                <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:3}}>{o.date} · {o.time}</div>
              </div>
            </div>

            {/* status timeline */}
            <div className="card card-pad" style={{marginBottom:12}}>
              <SectionTitle icon="list">حالة الطلب</SectionTitle>
              <div className="tl">
                {o.track.map((s,i)=>(
                  <div className="tl-row" key={i}>
                    <div className="tl-node">
                      <div className={'tl-dot '+(s.done?'':(s.cancel?'':'soft'))} style={s.cancel?{background:'var(--bad-fg)'}:{}}>
                        <Icon name={s.cancel?'plus':'check'} size={20} sw={2.4} style={s.cancel?{transform:'rotate(45deg)'}:{}}/>
                      </div>
                      {i<o.track.length-1 && <div className={'tl-line'+(s.done?'':' dashed')}/>}
                    </div>
                    <div className="tl-body">
                      <div style={{display:'flex', justifyContent:'space-between', gap:8}}>
                        <span className="ar lead" style={{fontSize:14.5, color: s.done||s.cancel?'var(--ink)':'var(--muted)'}}>{s.t}</span>
                        <span className="num t-mut t-xs" style={{fontWeight:600, whiteSpace:'nowrap'}}>{s.time}</span>
                      </div>
                      <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:3}}>{s.d}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* products */}
            <div className="card card-pad" style={{marginBottom:12}}>
              <SectionTitle icon="bag">المنتجات</SectionTitle>
              {o.items.map((it,i)=>{
                const p = D.products[it.p];
                return (
                  <div key={i} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderTop: i?'1px solid var(--line)':'none'}}>
                    <ProductThumb size={52} tone={p.tone} label={p.unit}/>
                    <div style={{flex:1}}>
                      <div className="ar lead" style={{fontSize:14.5}}>{p.name}</div>
                      <div className="ar t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{p.note} · {it.unit}</div>
                      <div className="num t-mut t-xs" style={{fontWeight:600, marginTop:2}}>{it.price} د.ك × {it.qty}</div>
                    </div>
                    <div className="price" style={{fontSize:15.5, color:'var(--ink)'}}>{it.total}<span style={{fontSize:10, color:'var(--muted)'}}> د.ك</span></div>
                  </div>
                );
              })}
            </div>

            {/* summary */}
            <div className="card card-pad" style={{marginBottom:12}}>
              <SectionTitle icon="wallet">ملخص الطلب</SectionTitle>
              <KV k="إجمالي المنتجات" v={o.sub+' د.ك'} />
              <KV k="تكلفة التوصيل" v={o.ship+' د.ك'} />
              <KV k="الخصم" v={o.disc+' د.ك'} accent="var(--bad-fg)"/>
              <div className="rowline" style={{margin:'8px 0'}}/>
              <KV k="الإجمالي الكلي" v={o.total+' د.ك'} strong/>
              <div style={{display:'flex', alignItems:'center', gap:7, marginTop:10, color:'var(--muted)'}}>
                <Icon name="card" size={16} sw={1.7}/>
                <span className="ar t-sm" style={{fontWeight:600}}>طريقة الدفع: {o.pay}</span>
              </div>
            </div>

            {/* delivery */}
            <div className="card card-pad">
              <SectionTitle icon="truck">معلومات التوصيل</SectionTitle>
              <div style={{display:'flex', gap:10, alignItems:'flex-start'}}>
                <span style={{color:'var(--green)', marginTop:2}}><Icon name="pin" size={18} sw={1.7}/></span>
                <div>
                  <div className="ar lead" style={{fontSize:14}}>{o.place}</div>
                  <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:2}}>شارع 52 - منزل 10</div>
                  <div className="ar t-mut t-sm" style={{fontWeight:600, marginTop:6}}>موعد التوصيل: {o.date} - 02:00 م</div>
                </div>
              </div>
            </div>

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

        <div className="cta-bar">
          <button className="btn btn-soft ar" style={{flex:'0 0 52px', padding:0}} aria-label="مشاركة"><Icon name="share" size={20}/></button>
          <button className="btn btn-primary ar"><Icon name="reorder" size={19} color="#fff"/> إعادة طلب نفس المنتجات</button>
        </div>
      </React.Fragment>
    );
  }

  Object.assign(window, { FeedListScreen, ProductDetailScreen, CartScreen, OrdersScreen, FeedDetailScreen });
})();
