/* ============ FILTER TOOLBAR ============ */
function Toolbar({children, right}){
  return (<div className="card card-pad" style={{display:'flex',alignItems:'center',gap:14,flexWrap:'wrap',padding:'16px 20px'}}>
    {children}<div style={{marginLeft:'auto',display:'flex',gap:12,alignItems:'center'}}>{right}</div>
  </div>);
}
function CatFilter({value, onChange}){
  return (
    <select className="select" style={{width:180}} value={value} onChange={e=>onChange(e.target.value)}>
      <option value="">All categories</option>
      {DATA.categories.map(c=><option key={c.id} value={c.id}>{c.label}</option>)}
    </select>
  );
}
function StatusFilter({value, onChange}){
  return (
    <select className="select" style={{width:160}} value={value} onChange={e=>onChange(e.target.value)}>
      <option value="">All statuses</option>
      <option value="OK">In Stock</option>
      <option value="Low">Low Stock</option>
      <option value="Critical">Critical</option>
    </select>
  );
}
function matchSearch(p, q){
  if(!q) return true;
  q=q.toLowerCase();
  return p.nameEn.toLowerCase().includes(q) || (p.nameAr||'').includes(q) ||
    p.code.toLowerCase().includes(q) || (p.plu||'').includes(q) || (p.barcode||'').includes(q);
}

/* ============ PRODUCT DETAIL MODAL ============ */
function ProductDetail({p, onClose, stockIn, stockOut, setRoute}){
  const [tab, setTab] = React.useState(null); // null | 'in' | 'out'
  const cur = H.stockOf(p);
  const s = H.statusOf(p);
  const color = H.CAT_COLOR[p.category];
  return (
    <Modal title="Product Details" onClose={onClose} width={620}>
      <div style={{display:'flex',gap:16,alignItems:'center',marginBottom:20}}>
        <ProductThumb p={p} size={62}/>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:20,fontWeight:800,lineHeight:1.15}}>{p.nameEn}</div>
          <div className="ar" style={{color:'var(--muted)',fontWeight:600,fontSize:15}}>{p.nameAr}</div>
        </div>
        <StatusPill p={p}/>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginBottom:18}}>
        {[['Current Stock',H.fmtQty(cur,p.unit),s.cls==='pill-ok'?'#16A34A':s.cls==='pill-low'?'#D97706':'#DC2626'],
          ['Min. Threshold',H.fmtQty(p.threshold,p.unit),'#1C1320'],
          ['Active Batches',p.batches.length+'','#1C1320']].map((c,i)=>(
          <div key={i} style={{background:'#FAF8FB',borderRadius:14,padding:'14px 16px'}}>
            <div style={{fontSize:12,color:'var(--muted)',fontWeight:600}}>{c[0]}</div>
            <div className="num" style={{fontSize:21,fontWeight:800,color:c[2],marginTop:2}}>{c[1]}</div>
          </div>
        ))}
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'8px 18px',fontSize:13,marginBottom:18,
        padding:'14px 16px',background:'#FAF8FB',borderRadius:14}}>
        {[['Category',p.category],['Unit',p.unit==='kg'?'Weight (kg) · Scale item':'Pieces (pcs)'],
          ['Product Code',p.code],['Scale PLU',p.plu],['Barcode',p.barcode],['Selling Price',H.money(p.price)+' / '+(p.unit==='kg'?'kg':'pc')]].map((r,i)=>(
          <div key={i} className="spread" style={{borderBottom:'1px solid var(--line)',paddingBottom:6}}>
            <span style={{color:'var(--muted)',fontWeight:600}}>{r[0]}</span>
            <span className="num" style={{fontWeight:700,color:'var(--ink)'}}>{r[1]}</span>
          </div>
        ))}
      </div>

      <div style={{fontWeight:800,fontSize:14,marginBottom:8}}>Batches</div>
      <div className="tbl-wrap"><table className="tbl" style={{border:'1px solid var(--line)',borderRadius:12,overflow:'hidden'}}>
        <thead><tr><th style={{padding:'10px 16px'}}>Code</th><th>Added</th><th>Expiry</th><th className="right">Qty</th><th>State</th></tr></thead>
        <tbody>
          {p.batches.map((b,i)=>{const es=H.expiryState(b.expiry);return(
            <tr key={i}><td style={{padding:'11px 16px'}} className="strong num">{b.code}</td>
              <td className="num">{H.fmtDate(b.addedOn)}</td>
              <td className="num">{H.fmtDate(b.expiry)}</td>
              <td className="right strong num">{H.fmtQty(b.qty,p.unit)}</td>
              <td><span className={'pill '+es.cls}>{es.key==='expired'?'Expired':es.key==='soon'?'Expiring':'Active'}</span></td>
            </tr>);})}
          {p.batches.length===0 && <tr><td colSpan="5"><div className="empty" style={{padding:24}}>No active batches</div></td></tr>}
        </tbody>
      </table></div>

      <div style={{display:'flex',gap:12,marginTop:20}}>
        <button className="btn btn-soft" style={{flex:1}} onClick={()=>{onClose();setRoute('stock-in');}}><Icon name="stockIn" size={18}/> Stock In</button>
        <button className="btn btn-ghost" style={{flex:1}} onClick={()=>{onClose();setRoute('stock-out');}}><Icon name="stockOut" size={18}/> Stock Out</button>
      </div>
    </Modal>
  );
}

/* ============ ITEMS SCREEN ============ */
function ItemsScreen({products, search, stockIn, stockOut, setRoute}){
  const [cat, setCat] = React.useState('');
  const [stat, setStat] = React.useState('');
  const [sel, setSel] = React.useState(null);
  const [inStockOnly, setInStockOnly] = React.useState(false);
  const rows = products
    .filter(p=>!inStockOnly||H.stockOf(p)>0)
    .filter(p=>!cat||p.category===cat)
    .filter(p=>!stat||H.statusOf(p).key===stat)
    .filter(p=>matchSearch(p,search))
    .sort((a,b)=>(a.nameEn||a.nameAr||'').localeCompare(b.nameEn||b.nameAr||''));
  const selProd = sel!=null ? products.find(p=>p.id===sel) : null;
  return (
    <div className="content fade-up">
      <Toolbar right={<span className="muted" style={{fontWeight:600}}>{rows.length} items</span>}>
        <CatFilter value={cat} onChange={setCat}/>
        <StatusFilter value={stat} onChange={setStat}/>
        <button onClick={()=>setInStockOnly(v=>!v)}
          className={'pill np'+(inStockOnly?' pill-ok':' pill-grey')}
          style={{padding:'7px 12px',cursor:'pointer',border:'none',fontFamily:'inherit',fontSize:13,fontWeight:600,display:'flex',alignItems:'center',gap:6}}>
          <Icon name="info" size={14}/>{inStockOnly?'In stock only':'All products'}
        </button>
      </Toolbar>
      <Card>
        <div className="tbl-wrap"><table className="tbl">
          <thead><tr>
            <th>Product</th><th>Category</th><th>Unit</th><th className="right">Current Stock</th>
            <th className="right">Threshold</th><th>Status</th><th>Batches</th><th></th>
          </tr></thead>
          <tbody>
            {rows.map(p=>{
              const exp = H.nearestExpiry(p);
              return (<tr key={p.id} style={{cursor:'pointer'}} onClick={()=>setSel(p.id)}>
                <td><PName p={p}/></td>
                <td><span className="pill np" style={{background:H.CAT_COLOR[p.category]+'18',color:H.CAT_COLOR[p.category]}}>{p.category}</span></td>
                <td className="num">{p.unit==='kg'?'kg':'pcs'}</td>
                <td className="right strong num">{H.fmtQty(H.stockOf(p),p.unit)}</td>
                <td className="right num">{H.fmtQty(p.threshold,p.unit)}</td>
                <td><StatusPill p={p}/></td>
                <td className="num"><span style={{fontWeight:700,color:'var(--ink)'}}>{p.batches.length}</span>
                  <span className="muted" style={{fontSize:12}}> · exp {exp?H.fmtDate(exp):'—'}</span></td>
                <td className="right"><Icon name="chevR" size={17} style={{color:'var(--muted-2)'}}/></td>
              </tr>);
            })}
            {rows.length===0 && <tr><td colSpan="8"><div className="empty"><Icon name="search"/><div>No items match your filters</div></div></td></tr>}
          </tbody>
        </table></div>
      </Card>
      {selProd && <ProductDetail p={selProd} onClose={()=>setSel(null)} stockIn={stockIn} stockOut={stockOut} setRoute={setRoute}/>}
    </div>
  );
}

/* ============ BATCHES SCREEN ============ */
function BatchesScreen({products, search}){
  const [cat, setCat] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  let batches=[];
  products.filter(p=>H.stockOf(p)>0).forEach(p=>p.batches.forEach(b=>batches.push({...b,p})));
  batches = batches.filter(x=>!cat||x.p.category===cat).filter(x=>matchSearch(x.p,search));
  if(filter==='expiring') batches=batches.filter(x=>{const d=H.daysUntil(x.expiry);return d>=0&&d<=30;});
  if(filter==='expired') batches=batches.filter(x=>H.daysUntil(x.expiry)<0);
  batches.sort((a,b)=>a.expiry<b.expiry?-1:1);
  return (
    <div className="content fade-up">
      <Toolbar right={<span className="muted" style={{fontWeight:600}}>{batches.length} batches</span>}>
        <CatFilter value={cat} onChange={setCat}/>
        <Segmented value={filter} onChange={setFilter} options={[{value:'all',label:'All'},{value:'expiring',label:'Expiring ≤30d'},{value:'expired',label:'Expired'}]}/>
      </Toolbar>
      <Card>
        <div className="tbl-wrap"><table className="tbl tbl-mag" style={{margin:'0 0'}}>
          <thead style={{}}><tr>
            <th style={{paddingLeft:26}}>Batch Code</th><th>Item</th><th className="right">Quantity</th>
            <th>Added On</th><th>Expiry Date</th><th className="right">Remaining</th><th>Status</th>
          </tr></thead>
          <tbody>
            {batches.map((b,i)=>{const es=H.expiryState(b.expiry);return(
              <tr key={i}>
                <td className="strong num" style={{paddingLeft:26}}>{b.code}</td>
                <td><div className="pcell"><ProductThumb p={b.p} size={34}/><span className="nm" style={{fontSize:13.5}}>{b.p.nameEn}</span></div></td>
                <td className="right strong num">{H.fmtQty(b.qty,b.p.unit)}</td>
                <td className="num">{H.fmtDate(b.addedOn)}</td>
                <td className="num">{H.fmtDate(b.expiry)}</td>
                <td className="right"><span className={'pill '+es.cls}>{es.label}</span></td>
                <td><span className={'pill '+(es.key==='expired'?'pill-crit':es.key==='soon'?'pill-exp':'pill-ok')}>{es.key==='expired'?'Expired':es.key==='soon'?'Expiring':'Active'}</span></td>
              </tr>);})}
            {batches.length===0 && <tr><td colSpan="7"><div className="empty"><Icon name="layers"/><div>No batches match</div></div></td></tr>}
          </tbody>
        </table></div>
      </Card>
    </div>
  );
}

/* ============ LOW STOCK SCREEN ============ */
function LowStockScreen({products, search, setRoute}){
  const crit = products.filter(p=>H.stockOf(p)>0 && H.statusOf(p).key==='Critical' && matchSearch(p,search));
  const low = products.filter(p=>H.stockOf(p)>0 && H.statusOf(p).key==='Low' && matchSearch(p,search));
  const Section = ({title, list, tone})=> (
    <Card>
      <CardHead title={title} sub={list.length+' item'+(list.length===1?'':'s')}/>
      <div className="tbl-wrap"><table className="tbl">
        <thead><tr><th>Product</th><th className="right">Current</th><th className="right">Minimum</th><th className="right">Shortfall</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {list.map(p=>{const cur=H.stockOf(p);const short=Math.round((p.threshold-cur)*10)/10;return(
            <tr key={p.id}>
              <td><PName p={p}/></td>
              <td className="right strong num">{H.fmtQty(cur,p.unit)}</td>
              <td className="right num">{H.fmtQty(p.threshold,p.unit)}</td>
              <td className="right num" style={{color:'var(--crit)',fontWeight:700}}>{short>0?'-'+H.fmtQty(short,p.unit):'—'}</td>
              <td><StatusPill p={p}/></td>
              <td className="right"><button className="btn btn-soft" style={{padding:'8px 14px'}} onClick={()=>setRoute('stock-in')}><Icon name="stockIn" size={16}/> Restock</button></td>
            </tr>);})}
          {list.length===0 && <tr><td colSpan="6"><div className="empty"><Icon name="checkCircle"/><div>Nothing here — all good</div></div></td></tr>}
        </tbody>
      </table></div>
    </Card>
  );
  return (
    <div className="content fade-up">
      <div className="kpi-row" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
        <KPICard icon="alert" label="Critical Items" value={crit.length} sub="Severely below threshold" color="#DC2626" tint="#FDE7E7" accent="#DC2626"/>
        <KPICard icon="trendDown" label="Low Stock Items" value={low.length} sub="At or below minimum" color="#D97706" tint="#FEF3C7" accent="#D97706"/>
        <KPICard icon="refresh" label="Total to Restock" value={crit.length+low.length} sub="Needs purchasing action" color="#D70059" tint="#FDEAF2" accent="#D70059"/>
      </div>
      {crit.length>0 && <Section title="Critical — Restock Immediately" list={crit}/>}
      <Section title="Low Stock" list={low}/>
    </div>
  );
}

Object.assign(window,{ItemsScreen,BatchesScreen,LowStockScreen,ProductDetail,Toolbar,CatFilter,StatusFilter,matchSearch});
