/* ============ PRODUCT PICKER ============ */
function ProductPicker({products, value, onChange, placeholder='Search product by name, code or barcode…'}){
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(()=>{
    const fn = e=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn); return ()=>document.removeEventListener('mousedown', fn);
  },[]);
  const sel = products.find(p=>p.id===value);
  const list = products.filter(p=>H.stockOf(p)>=0).filter(p=>matchSearch(p,q)).slice(0,8);
  return (
    <div ref={ref} style={{position:'relative'}}>
      {sel && !open ? (
        <button className="input" style={{display:'flex',alignItems:'center',gap:12,textAlign:'left',cursor:'pointer'}} onClick={()=>{setOpen(true);setQ('');}}>
          <ProductThumb p={sel} size={34}/>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontWeight:700,color:'var(--ink)'}}>{sel.nameEn}</div>
            <div className="ar" style={{fontSize:12,color:'var(--muted)'}}>{sel.nameAr}</div>
          </div>
          <span className="num" style={{color:'var(--muted)',fontSize:12.5}}>{H.fmtQty(H.stockOf(sel),sel.unit)} in stock</span>
          <Icon name="chevD" size={18} style={{color:'var(--muted-2)'}}/>
        </button>
      ) : (
        <div className="input-wrap">
          <input className="input" autoFocus={open} placeholder={placeholder} value={q}
            onFocus={()=>setOpen(true)} onChange={e=>{setQ(e.target.value);setOpen(true);}}/>
        </div>
      )}
      {open && (
        <div className="card" style={{position:'absolute',top:'calc(100% + 6px)',left:0,right:0,zIndex:30,maxHeight:330,overflow:'auto',boxShadow:'var(--shadow-lg)',padding:6}}>
          {list.map(p=>(
            <button key={p.id} className="pcell" style={{width:'100%',padding:'9px 10px',borderRadius:10,textAlign:'left'}}
              onMouseDown={()=>{onChange(p.id);setOpen(false);}}
              onMouseEnter={e=>e.currentTarget.style.background='#FBF9FC'} onMouseLeave={e=>e.currentTarget.style.background=''}>
              <ProductThumb p={p} size={36}/>
              <div style={{flex:1,minWidth:0}}>
                <div className="nm">{p.nameEn}</div><div className="nm-ar ar">{p.nameAr}</div>
              </div>
              <span className="num" style={{fontSize:12.5,color:'var(--muted)'}}>{H.fmtQty(H.stockOf(p),p.unit)}</span>
            </button>
          ))}
          {list.length===0 && <div className="empty" style={{padding:24}}>No products found</div>}
        </div>
      )}
    </div>
  );
}

function todayPlus(days){ const d=new Date(H.TODAY); d.setDate(d.getDate()+days); return d.toISOString().slice(0,10); }

/* ============ ADAPTIVE QUANTITY INPUT ============ */
function QtyInput({unit, value, onChange, disabled, invalid}){
  if(unit==='pcs'){
    const n = parseInt(value)||0;
    const set = v => onChange(String(Math.max(0, v)));
    return (
      <div className="stepper" style={invalid?{borderColor:'var(--crit)'}:undefined}>
        <button type="button" disabled={disabled||n<=0} onClick={()=>set(n-1)}><Icon name="minus" size={18}/></button>
        <input type="number" min="0" step="1" inputMode="numeric" placeholder="0" value={value} disabled={disabled}
          onChange={e=>onChange(e.target.value.replace(/[^0-9]/g,''))}/>
        <span className="su">pcs</span>
        <button type="button" disabled={disabled} onClick={()=>set(n+1)}><Icon name="plus" size={18}/></button>
      </div>
    );
  }
  // weight — always shows a typeable input prominently
  function weigh(){ onChange(String(Math.round((0.5+Math.random()*4.5)*10)/10)); }
  return (
    <div style={{display:'flex',flexDirection:'column',gap:8}}>
      <div className="input-wrap">
        <input className="input num" type="number" min="0" step="0.1" inputMode="decimal"
          placeholder="0.0" value={value} disabled={disabled}
          onChange={e=>onChange(e.target.value)}
          style={invalid?{borderColor:'var(--crit)',paddingRight:48}:{paddingRight:48}}/>
        <span className="unit">kg</span>
      </div>
      <button type="button" className="btn btn-ghost" disabled={disabled} onClick={weigh}
        style={{alignSelf:'flex-start',padding:'7px 14px',fontSize:13}}>
        <Icon name="scale" size={15}/> Read from scale
      </button>
    </div>
  );
}

/* ============ EMPLOYEE INPUT ============ */
function EmployeeInput({value, onChange, invalid}){
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const employees = DATA.employees || [];
  const filtered = employees.filter(e=>!value||e.toLowerCase().includes(value.toLowerCase()));
  React.useEffect(()=>{
    const fn = e=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn); return ()=>document.removeEventListener('mousedown', fn);
  },[]);
  return (
    <div ref={ref} style={{position:'relative'}}>
      <input className="input" placeholder="Type employee name…" value={value}
        style={invalid?{borderColor:'var(--low)'}:undefined}
        onChange={e=>{onChange(e.target.value);setOpen(true);}}
        onFocus={()=>setOpen(true)}/>
      {open && filtered.length>0 && (
        <div className="card" style={{position:'absolute',top:'calc(100% + 4px)',left:0,right:0,zIndex:30,
          boxShadow:'var(--shadow-lg)',borderRadius:12,overflow:'hidden',maxHeight:180,overflowY:'auto'}}>
          {filtered.map(e=>(
            <button key={e} style={{width:'100%',padding:'11px 14px',textAlign:'left',fontWeight:600,
              fontSize:14,display:'block',background:'none',borderBottom:'1px solid var(--line-2)'}}
              onMouseDown={()=>{onChange(e);setOpen(false);}}
              onMouseEnter={ev=>ev.currentTarget.style.background='#FAF8FB'}
              onMouseLeave={ev=>ev.currentTarget.style.background=''}>
              {e}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ============ RECENT OPS LIST ============ */
function RecentOps({movements, type, title}){
  const list = movements.filter(m=> type==='IN'? (m.type==='IN'||m.type==='NEW_BATCH') : m.type==='OUT').slice(0,7);
  return (
    <Card className="card-pad" style={{alignSelf:'start'}}>
      <h2 style={{fontSize:16,fontWeight:800,margin:'0 0 6px'}}>{title}</h2>
      {list.map(m=>(
        <div className="act" key={m.id}>
          <div className="aic" style={{background:type==='IN'?'#E8F7EE':'#FEF3C7',color:type==='IN'?'#16A34A':'#D97706'}}>
            <Icon name={type==='IN'?'arrowDownCircle':'arrowUpCircle'} size={18}/></div>
          <div style={{minWidth:0}}>
            <div className="atitle">{m.product}</div>
            <div className="adesc">{H.fmtQty(m.qty,m.unit)} · {m.batchCode}{m.employee?' · '+m.employee:''}</div>
          </div>
          <div className="atime">{H.relTime(m.date,m.time)}</div>
        </div>
      ))}
      {list.length===0 && <div className="empty" style={{padding:30}}><Icon name="clock"/><div>No recent activity</div></div>}
    </Card>
  );
}

/* ============ STOCK IN SCREEN ============ */
function StockInScreen({products, movements, stockIn}){
  const [pid, setPid] = React.useState(null);
  const [qty, setQty] = React.useState('');
  const [expiry, setExpiry] = React.useState(todayPlus(180));
  const p = products.find(x=>x.id===pid);
  const sameBatch = p && p.batches.find(b=>b.expiry===expiry);
  const valid = p && +qty>0 && expiry;
  function submit(){
    if(!valid) return;
    stockIn({productId:pid, qty:+qty, expiry});
    toast({title:'Stock added', desc:`${H.fmtQty(+qty,p.unit)} of ${p.nameEn} ${sameBatch?'added to '+sameBatch.code:'as a new batch'}`});
    setQty('');
  }
  return (
    <div className="content fade-up">
      <div className="action-layout">
        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 4px'}}>Receive Stock</h2>
          <div className="muted" style={{marginBottom:20,fontSize:13}}>Select a product, enter the quantity and expiry date.</div>
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            <Field label="Product"><ProductPicker products={products} value={pid} onChange={setPid}/></Field>
            {p && (
              <div className="spread" style={{background:'#FAF8FB',borderRadius:12,padding:'11px 14px'}}>
                <span className="muted" style={{fontWeight:600,fontSize:13}}>Current stock</span>
                <span className="num" style={{fontWeight:800}}>{H.fmtQty(H.stockOf(p),p.unit)}</span>
              </div>
            )}
            <Field label={p&&p.unit==='pcs'?'Quantity received':'Weight received (kg)'}>
              <QtyInput unit={p?p.unit:'kg'} value={qty} onChange={setQty} disabled={!p}/>
            </Field>
            <Field label="Expiry date" hint="Same expiry merges batches · Different expiry creates a new batch">
              <input className="input num" type="date" value={expiry} onChange={e=>setExpiry(e.target.value)}/>
            </Field>
            {p && valid && (
              <div className="pill np" style={{alignSelf:'flex-start',background:sameBatch?'#F1E9FE':'#E8F7EE',
                color:sameBatch?'#7C3AED':'#16A34A',padding:'9px 14px',fontSize:13}}>
                <Icon name={sameBatch?'layers':'plus'} size={15} style={{marginRight:6}}/>
                {sameBatch?`Will merge into batch ${sameBatch.code}`:'Will create a new batch'}
              </div>
            )}
            <button className="btn btn-primary btn-lg" disabled={!valid} onClick={submit}>
              <Icon name="stockIn" size={19}/> Add to Inventory
            </button>
          </div>
        </Card>
        <RecentOps movements={movements} type="IN" title="Recent Stock In"/>
      </div>
    </div>
  );
}

/* ============ STOCK OUT SCREEN ============ */
function StockOutScreen({products, movements, stockOut}){
  const [pid, setPid] = React.useState(null);
  const [qty, setQty] = React.useState('');
  const [emp, setEmp] = React.useState('');
  const p = products.find(x=>x.id===pid);
  const avail = p? H.stockOf(p):0;
  const over = p && +qty>avail;
  const valid = p && +qty>0 && !over && emp;
  let drawdown=[];
  if(p && +qty>0){
    let rem=+qty;
    for(const b of [...p.batches].sort((a,b)=>a.expiry<b.expiry?-1:1)){
      if(rem<=0)break; const take=Math.min(b.qty,rem); drawdown.push({code:b.code,take,exp:b.expiry}); rem-=take;
    }
  }
  function submit(){
    if(!valid)return;
    const ok = stockOut({productId:pid, qty:+qty, employee:emp});
    if(ok){ toast({title:'Stock removed', desc:`${H.fmtQty(+qty,p.unit)} of ${p.nameEn} · ${emp}`}); setQty(''); setEmp(''); }
    else toast({kind:'err', title:'Not enough stock', desc:'Reduce the quantity.'});
  }
  return (
    <div className="content fade-up">
      <div className="action-layout">
        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 4px'}}>Remove Stock</h2>
          <div className="muted" style={{marginBottom:20,fontSize:13}}>Select a product and enter the quantity being removed.</div>
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            <Field label="Product"><ProductPicker products={products.filter(p=>H.stockOf(p)>0)} value={pid} onChange={setPid}/></Field>
            {p && (
              <div className="spread" style={{background:'#FAF8FB',borderRadius:12,padding:'11px 14px'}}>
                <span className="muted" style={{fontWeight:600,fontSize:13}}>Available</span>
                <span className="num" style={{fontWeight:800,color:over?'var(--crit)':undefined}}>{H.fmtQty(avail,p.unit)}</span>
              </div>
            )}
            <Field label={p&&p.unit==='pcs'?'Quantity out':'Weight out (kg)'} hint={over?'Exceeds available stock!':undefined}>
              <QtyInput unit={p?p.unit:'kg'} value={qty} onChange={setQty} disabled={!p} invalid={over}/>
            </Field>
            <Field label="Employee name" hint="Required for stock-out records">
              <EmployeeInput value={emp} onChange={setEmp} invalid={!emp&&!!qty}/>
            </Field>
            {!over && drawdown.length>0 && (
              <div style={{background:'#FAF8FB',borderRadius:12,padding:'12px 14px'}}>
                <div style={{fontSize:11,fontWeight:700,color:'var(--muted)',marginBottom:8,letterSpacing:'.06em'}}>BATCH DRAW-DOWN (FEFO)</div>
                {drawdown.map((d,i)=>(<div key={i} className="spread" style={{fontSize:13,padding:'3px 0'}}>
                  <span className="num" style={{fontWeight:600}}>{d.code}<span className="muted"> · exp {H.fmtDate(d.exp)}</span></span>
                  <span className="num" style={{fontWeight:700,color:'var(--crit)'}}>-{H.fmtQty(d.take,p.unit)}</span>
                </div>))}
              </div>
            )}
            <button className="btn btn-primary btn-lg" disabled={!valid} onClick={submit}>
              <Icon name="stockOut" size={19}/> Record Stock Out
            </button>
          </div>
        </Card>
        <RecentOps movements={movements} type="OUT" title="Recent Stock Out"/>
      </div>
    </div>
  );
}

/* ============ SCAN SCREEN ============ */
function ScanScreen({products, stockIn, stockOut, setRoute}){
  const [code, setCode] = React.useState('');
  const [pid, setPid] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [weight, setWeight] = React.useState('');
  const inputRef = React.useRef(null);
  const p = products.find(x=>x.id===pid);
  function resolve(c){
    const found = products.find(x=>x.barcode===c.trim() || x.plu===c.trim() || x.code.toLowerCase()===c.trim().toLowerCase());
    if(found){ setPid(found.id); setErr(''); setWeight(found.unit==='kg'? (Math.round((1+Math.random()*3)*10)/10)+'' : '1'); }
    else { setErr('No product matches "'+c+'"'); setPid(null); }
  }
  function simulate(){
    const r = products[Math.floor(Math.random()*products.length)];
    setCode(r.barcode); resolve(r.barcode);
  }
  function doIn(){ if(!p||!(+weight>0))return; stockIn({productId:p.id, qty:+weight, expiry:todayPlus(180)}); toast({title:'Scanned in', desc:`${H.fmtQty(+weight,p.unit)} of ${p.nameEn}`}); }
  function doOut(){ if(!p||!(+weight>0))return; const ok=stockOut({productId:p.id, qty:+weight, employee:DATA.employees[0]}); if(ok)toast({title:'Scanned out',desc:`${H.fmtQty(+weight,p.unit)} of ${p.nameEn} · ${DATA.employees[0]}`}); else toast({kind:'err',title:'Not enough stock'}); }
  return (
    <div className="content fade-up">
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:22,alignItems:'start'}}>
        <Card className="card-pad" style={{textAlign:'center'}}>
          <div style={{width:96,height:96,borderRadius:26,background:'var(--pink-tint)',color:'var(--magenta)',display:'flex',alignItems:'center',justifyContent:'center',margin:'8px auto 18px'}}>
            <Icon name="scan" size={48}/>
          </div>
          <h2 style={{fontSize:20,fontWeight:800,margin:'0 0 4px'}}>Scan or weigh an item</h2>
          <div className="muted" style={{marginBottom:22}}>Point the scanner at a barcode, or read a scale PLU. Enter the code below to simulate.</div>
          <div className="input-wrap" style={{marginBottom:14}}>
            <input ref={inputRef} className="input num" style={{textAlign:'center',fontSize:18,padding:'16px',letterSpacing:'.04em'}}
              placeholder="Barcode / PLU / code" value={code}
              onChange={e=>setCode(e.target.value)} onKeyDown={e=>{if(e.key==='Enter')resolve(code);}}/>
          </div>
          <div style={{display:'flex',gap:12}}>
            <button className="btn btn-primary" style={{flex:1}} onClick={()=>resolve(code)}><Icon name="scan" size={18}/> Resolve</button>
            <button className="btn btn-ghost" style={{flex:1}} onClick={simulate}><Icon name="refresh" size={18}/> Simulate scan</button>
          </div>
          {err && <div className="pill pill-crit" style={{marginTop:16}}>{err}</div>}
        </Card>

        <Card className="card-pad">
          {!p ? (
            <div className="empty" style={{padding:'70px 20px'}}><Icon name="package"/><div style={{fontWeight:700,color:'var(--ink)'}}>No item scanned yet</div><div>Resolved products appear here</div></div>
          ) : (
            <div className="fade-up">
              <div style={{display:'flex',gap:14,alignItems:'center',marginBottom:18}}>
                <ProductThumb p={p} size={58}/>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:18,fontWeight:800}}>{p.nameEn}</div>
                  <div className="ar muted" style={{fontWeight:600}}>{p.nameAr}</div>
                </div>
                <StatusPill p={p}/>
              </div>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:18}}>
                <div style={{background:'#FAF8FB',borderRadius:12,padding:'12px 14px'}}><div className="muted" style={{fontSize:12,fontWeight:600}}>Barcode</div><div className="num" style={{fontWeight:700}}>{p.barcode}</div></div>
                <div style={{background:'#FAF8FB',borderRadius:12,padding:'12px 14px'}}><div className="muted" style={{fontSize:12,fontWeight:600}}>In stock</div><div className="num" style={{fontWeight:700}}>{H.fmtQty(H.stockOf(p),p.unit)}</div></div>
              </div>
              <Field label={p.unit==='kg'?'Weight (from scale)':'Quantity'} style={{marginBottom:16}}>
                <QtyInput unit={p.unit} value={weight} onChange={setWeight}/>
              </Field>
              <div style={{display:'flex',gap:12}}>
                <button className="btn btn-primary" style={{flex:1}} onClick={doIn}><Icon name="stockIn" size={18}/> Stock In</button>
                <button className="btn btn-ghost" style={{flex:1}} onClick={doOut}><Icon name="stockOut" size={18}/> Stock Out</button>
              </div>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}

/* ============ ADD PRODUCT MODAL ============ */
function AddProductModal({onClose, addProduct}){
  const [f, setF] = React.useState({nameEn:'',nameAr:'',category:'Nuts',unit:'kg',price:'',threshold:'',qty:'',expiry:todayPlus(180),barcode:''});
  const set = (k,v)=>setF(p=>({...p,[k]:v}));
  const valid = f.nameEn && +f.qty>0 && f.expiry;
  function submit(){ if(!valid)return; addProduct(f); toast({title:'Product added', desc:f.nameEn+' is now in your catalogue'}); onClose(); }
  return (
    <Modal title="Add New Product" onClose={onClose} width={600}
      footer={<><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" disabled={!valid} onClick={submit}><Icon name="check" size={18}/> Add Product</button></>}>
      <div style={{display:'flex',flexDirection:'column',gap:16}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <Field label="Product name (English)"><input className="input" placeholder="e.g. Roasted Cashews" value={f.nameEn} onChange={e=>set('nameEn',e.target.value)}/></Field>
          <Field label="Arabic name"><input className="input ar" style={{textAlign:'right'}} placeholder="مثال: كاجو محمص" value={f.nameAr} onChange={e=>set('nameAr',e.target.value)}/></Field>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <Field label="Category"><select className="select" value={f.category} onChange={e=>set('category',e.target.value)}>{DATA.categories.map(c=><option key={c.id}>{c.label}</option>)}</select></Field>
          <Field label="Unit type"><Segmented value={f.unit} onChange={v=>set('unit',v)} options={[{value:'kg',label:'Weight (kg)'},{value:'pcs',label:'Pieces'}]}/></Field>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <Field label="Min. threshold" hint={f.unit==='kg'?'Low-stock alert at or below':'Low when < 5 pcs'}>
            <div className="input-wrap"><input className="input" type="number" min="0" placeholder={f.unit==='kg'?'8':'5'} value={f.threshold} onChange={e=>set('threshold',e.target.value)}/><span className="unit">{f.unit}</span></div>
          </Field>
          <Field label="Selling price" hint="Per kg / piece">
            <div className="input-wrap"><input className="input num" type="number" min="0" placeholder="0" value={f.price} onChange={e=>set('price',e.target.value)}/><span className="unit">LBP</span></div>
          </Field>
        </div>
        <div style={{height:1,background:'var(--line)',margin:'2px 0'}}></div>
        <div style={{fontWeight:800,fontSize:13.5}}>First Batch</div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <Field label="Initial quantity"><QtyInput unit={f.unit} value={f.qty} onChange={v=>set('qty',v)}/></Field>
          <Field label="Expiry date"><input className="input num" type="date" value={f.expiry} onChange={e=>set('expiry',e.target.value)}/></Field>
        </div>
        <Field label="Barcode (optional)" hint="Leave blank to auto-generate"><input className="input num" placeholder="Auto-generated" value={f.barcode} onChange={e=>set('barcode',e.target.value)}/></Field>
      </div>
    </Modal>
  );
}

Object.assign(window,{ProductPicker,StockInScreen,StockOutScreen,ScanScreen,AddProductModal,RecentOps,todayPlus,QtyInput,EmployeeInput});
