/* ============ ORDER STOCK — morning walk-through order list ============ */
function OrderScreen({products, movements, user}){
  const [items, setItems] = React.useState([]);        // {pid, qty}
  const [comments, setComments] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [sentInfo, setSentInfo] = React.useState(null);
  const [history, setHistory] = React.useState(null);  // null = not loaded
  const [showHistory, setShowHistory] = React.useState(false);
  const [target, setTarget] = React.useState({whatsapp:'', hasEmail:false});

  React.useEffect(()=>{
    apiFetch('/api/order-target').then(setTarget).catch(()=>{});
  },[]);

  // formatted WhatsApp message for the factory
  function waMessage(id, list){
    const lines = list.map((i,n)=>{
      const p = products.find(x=>x.id===i.pid);
      return `${n+1}. ${p.nameEn}${p.nameAr?' / '+p.nameAr:''} — ${i.qty} ${p.unit}`;
    });
    return [
      `🧾 *Helbawi Stock Order ${id}*`,
      `📅 ${H.fmtDate(window.HELBAWI.today)} · ${user?user.displayName:''}`,
      '',
      ...lines,
      comments ? `\n📝 ${comments}` : '',
    ].filter(Boolean).join('\n');
  }

  // smart suggestions from the analytics engine
  const suggestions = React.useMemo(()=>{
    try {
      return window.Analytics.performance(products, movements)
        .filter(r=>r.needReorder)
        .sort((a,b)=>(a.daysLeft??999)-(b.daysLeft??999))
        .slice(0,12);
    } catch(e){ return []; }
  }, [products, movements]);

  const inList = pid => items.some(i=>i.pid===pid);
  function addItem(pid, qty){
    if(inList(pid)) return;
    setItems(list=>[...list, {pid, qty: qty!=null?String(qty):''}]);
  }
  function setQty(pid, qty){ setItems(list=>list.map(i=>i.pid===pid?{...i,qty}:i)); }
  function removeItem(pid){ setItems(list=>list.filter(i=>i.pid!==pid)); }

  const validItems = items.filter(i=>+i.qty>0);
  const canSubmit = validItems.length>0 && !submitting;

  function submit(){
    if(!canSubmit) return;
    setSubmitting(true);
    const payload = {
      createdBy: user ? user.displayName : '',
      comments,
      items: validItems.map(i=>{
        const p = products.find(x=>x.id===i.pid);
        return {name:p.nameEn, nameAr:p.nameAr||'', code:p.code, qty:+i.qty, unit:p.unit};
      }),
    };
    const itemsSnapshot = [...validItems];
    apiFetch('/api/orders', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload)})
      .then(r=>{
        setSentInfo(r);
        // WhatsApp is the primary channel — open chat with the order pre-filled
        if(target.whatsapp){
          const msg = waMessage(r.id, itemsSnapshot);
          window.open('https://wa.me/'+target.whatsapp+'?text='+encodeURIComponent(msg), '_blank');
          toast({title:t('ord.waOpened'), desc:`${itemsSnapshot.length} ${t('ord.items')} · ${r.id}`});
        } else if(r.emailedTo){
          toast({title:t('ord.sent'), desc:`${itemsSnapshot.length} ${t('ord.items')} → ${r.emailedTo}`});
        } else {
          toast({kind:'info', title:t('ord.savedOnly'), desc:t('ord.noTarget')});
        }
        setItems([]); setComments(''); setSubmitting(false); setHistory(null);
      })
      .catch(e=>{ toast({kind:'err', title:t('ord.failed'), desc:e.message}); setSubmitting(false); });
  }

  function loadHistory(){
    setShowHistory(s=>!s);
    if(history===null) apiFetch('/api/orders').then(setHistory).catch(()=>setHistory([]));
  }

  return (
    <div className="content fade-up">
      <div className="action-layout">
        <Card className="card-pad">
          <div className="spread">
            <div>
              <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 4px'}}>{t('ord.heading')}</h2>
              <div className="muted" style={{marginBottom:18,fontSize:13}}>{t('ord.sub')}</div>
            </div>
          </div>

          {/* suggestions */}
          {suggestions.length>0 && (
            <div style={{marginBottom:18}}>
              <div style={{fontSize:11.5,fontWeight:800,color:'var(--magenta)',letterSpacing:'.05em',marginBottom:8,display:'flex',alignItems:'center',gap:6}}>
                <Icon name="sparkle" size={14}/> {t('ord.suggested')}
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {suggestions.map(s=>(
                  <div key={s.p.id} style={{display:'flex',alignItems:'center',gap:10,border:'1px solid var(--line)',
                    borderRadius:12,padding:'10px 12px',background:inList(s.p.id)?'#F0FAF3':'#fff'}}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontWeight:700,fontSize:13.5,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{s.p.nameEn}</div>
                      <div className="muted num" style={{fontSize:11.5}}>
                        {s.daysLeft!=null?`${s.daysLeft} ${t('ord.daysLeft')}`:t('ord.lowCover')} · {H.fmtQty(s.stock,s.p.unit)} {t('inStock')}
                      </div>
                    </div>
                    {inList(s.p.id) ? (
                      <span style={{color:'#16A34A',fontWeight:700,fontSize:12,display:'flex',alignItems:'center',gap:4}}><Icon name="check" size={14}/>{t('ord.added')}</span>
                    ) : (
                      <button className="btn btn-ghost" style={{padding:'6px 12px',fontSize:12.5,flexShrink:0}}
                        onClick={()=>addItem(s.p.id, s.suggested)}>
                        <Icon name="plus" size={14}/> {s.suggested} {s.p.unit}
                      </button>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* manual add */}
          <Field label={t('ord.addProduct')} style={{marginBottom:14}}>
            <ProductPicker products={products.filter(p=>!inList(p.id))} value={null} onChange={pid=>addItem(pid)}/>
          </Field>

          {/* the order list */}
          {items.length>0 && (
            <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:16}}>
              <div style={{fontSize:11.5,fontWeight:800,color:'var(--muted)',letterSpacing:'.05em'}}>{t('ord.yourList')} ({items.length})</div>
              {items.map((i,n)=>{
                const p=products.find(x=>x.id===i.pid);
                if(!p) return null;
                return (
                  <div key={i.pid} style={{display:'flex',alignItems:'center',gap:10,background:'#FAF8FB',borderRadius:12,padding:'10px 12px'}}>
                    <div style={{width:22,height:22,borderRadius:'50%',background:+i.qty>0?'#16A34A':'var(--line)',
                      color:+i.qty>0?'#fff':'var(--muted)',display:'flex',alignItems:'center',justifyContent:'center',
                      fontSize:11,fontWeight:800,flexShrink:0}}>{n+1}</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontWeight:700,fontSize:13.5,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{p.nameEn}</div>
                      <div className="ar muted" style={{fontSize:11.5}}>{p.nameAr}</div>
                    </div>
                    <div className="input-wrap" style={{width:110,flexShrink:0}}>
                      <input className="input num" type="number" min="0" step={p.unit==='pcs'?'1':'0.5'} placeholder="0"
                        value={i.qty} onChange={e=>setQty(i.pid, e.target.value)}
                        style={{padding:'8px 36px 8px 10px',fontSize:14}}/>
                      <span className="unit" style={{fontSize:11}}>{p.unit}</span>
                    </div>
                    <button type="button" onClick={()=>removeItem(i.pid)}
                      style={{background:'none',border:'none',color:'var(--muted)',cursor:'pointer',padding:4,flexShrink:0}}>
                      <Icon name="x" size={16}/>
                    </button>
                  </div>
                );
              })}
            </div>
          )}

          <Field label={t('commentsOpt')} style={{marginBottom:14}}>
            <textarea className="input" rows={2} placeholder={t('ord.notesEg')} value={comments}
              onChange={e=>setComments(e.target.value)} style={{resize:'vertical',minHeight:54}}/>
          </Field>

          <button className="btn btn-primary btn-lg" style={{width:'100%',...(target.whatsapp?{background:'#25D366'}:{})}} disabled={!canSubmit} onClick={submit}>
            {submitting ? t('ord.sending') : <><Icon name="stockIn" size={19}/> {target.whatsapp?t('ord.sendWa'):t('ord.send')} {validItems.length>0?`(${validItems.length})`:''}</>}
          </button>
          <div className="muted" style={{fontSize:11.5,textAlign:'center',marginTop:10}}>{target.whatsapp?t('ord.waHint'):t('ord.sendHint')}</div>
        </Card>

        {/* history */}
        <Card className="card-pad" style={{alignSelf:'start'}}>
          <div className="spread" style={{marginBottom:6}}>
            <h2 style={{fontSize:16,fontWeight:800,margin:0}}>{t('ord.history')}</h2>
            <button className="link" onClick={loadHistory}>{showHistory?t('close'):t('viewAll')}</button>
          </div>
          {!showHistory && <div className="muted" style={{fontSize:12.5}}>{t('ord.historyHint')}</div>}
          {showHistory && history===null && <div className="muted" style={{padding:16,fontSize:13}}>…</div>}
          {showHistory && Array.isArray(history) && history.length===0 && (
            <div className="empty" style={{padding:24}}><Icon name="clipboard"/><div>{t('ord.noOrders')}</div></div>
          )}
          {showHistory && Array.isArray(history) && history.map(o=>(
            <div key={o.id} style={{border:'1px solid var(--line)',borderRadius:12,padding:'12px 14px',marginBottom:8}}>
              <div className="spread">
                <span className="num" style={{fontWeight:800,fontSize:13}}>{o.id}</span>
                <span style={{fontSize:11,fontWeight:700,padding:'3px 8px',borderRadius:20,
                  background:o.status==='sent'?'#E8F7EE':'#FEF3C7', color:o.status==='sent'?'#16A34A':'#D97706'}}>
                  {o.status==='sent'?t('ord.statusSent'):t('ord.statusSaved')}
                </span>
              </div>
              <div className="muted" style={{fontSize:12,margin:'4px 0'}}>
                {o.items.length} {t('ord.items')} · {o.createdBy||'—'} · {H.fmtDate(o.date)} {o.time}
              </div>
              <div style={{fontSize:12.5}}>{o.items.slice(0,4).map(i=>`${i.name} (${i.qty}${i.unit})`).join(', ')}{o.items.length>4?` +${o.items.length-4}`:''}</div>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

window.OrderScreen = OrderScreen;
