/* ============ MOVEMENT HISTORY ============ */
const MV_META = {
  IN:{label:'Stock In', cls:'pill-ok', icon:'arrowDownCircle'},
  OUT:{label:'Stock Out', cls:'pill-low', icon:'arrowUpCircle'},
  NEW_BATCH:{label:'New Batch', cls:'pill-info', icon:'layers'},
};
function MovementsScreen({movements, products, search}){
  const [type, setType] = React.useState('all');
  const [emp, setEmp] = React.useState('');
  const rows = movements
    .filter(m=> type==='all'||m.type===type)
    .filter(m=> !emp || m.employee===emp)
    .filter(m=> !search || m.product.toLowerCase().includes(search.toLowerCase()) || (m.batchCode||'').toLowerCase().includes(search.toLowerCase()) || (m.productAr||'').includes(search));
  const totIn = movements.filter(m=>m.type==='IN'||m.type==='NEW_BATCH').length;
  const totOut = movements.filter(m=>m.type==='OUT').length;
  return (
    <div className="content fade-up">
      <div className="kpi-row" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
        <KPICard icon="arrowDownCircle" label="Stock-In Events" value={totIn} sub="Receipts & new batches" color="#16A34A" tint="#E8F7EE" accent="#16A34A"/>
        <KPICard icon="arrowUpCircle" label="Stock-Out Events" value={totOut} sub="Items dispatched" color="#D97706" tint="#FEF3C7" accent="#D97706"/>
        <KPICard icon="clock" label="Total Movements" value={movements.length} sub="All logged transactions" color="#D70059" tint="#FDEAF2" accent="#D70059"/>
      </div>
      <Toolbar right={<span className="muted" style={{fontWeight:600}}>{rows.length} records</span>}>
        <Segmented value={type} onChange={setType} options={[{value:'all',label:'All'},{value:'IN',label:'In'},{value:'OUT',label:'Out'},{value:'NEW_BATCH',label:'Batches'}]}/>
        <select className="select" style={{width:180}} value={emp} onChange={e=>setEmp(e.target.value)}>
          <option value="">All employees</option>
          {DATA.employees.map(e=><option key={e}>{e}</option>)}
        </select>
      </Toolbar>
      <Card>
        <div className="tbl-wrap"><table className="tbl">
          <thead><tr><th>Product</th><th>Type</th><th className="right">Quantity</th><th>Batch Code</th><th>Expiry</th><th>Employee</th><th>Date</th></tr></thead>
          <tbody>
            {rows.map(m=>{
              const meta=MV_META[m.type];
              const prod = products.find(p=>p.id===m.productId);
              return (<tr key={m.id}>
                <td><div className="pcell">{prod?<ProductThumb p={prod} size={34}/>:<div className="thumb" style={{width:34,height:34,background:'#F1EFF3',color:'#8B8392'}}><Icon name="box" size={17}/></div>}
                  <div className="col"><span className="nm" style={{fontSize:13.5}}>{m.product}</span><span className="nm-ar ar">{m.productAr}</span></div></div></td>
                <td><span className={'pill '+meta.cls}>{meta.label}</span></td>
                <td className="right strong num" style={{color:m.type==='OUT'?'var(--low)':'var(--ok)'}}>{m.type==='OUT'?'−':'+'}{H.fmtQty(m.qty,m.unit)}</td>
                <td className="num" style={{fontWeight:600}}>{m.batchCode||'—'}</td>
                <td className="num">{m.expiry?H.fmtDate(m.expiry):'—'}</td>
                <td>{m.employee? <span className="row" style={{gap:7}}><span className="thumb" style={{width:26,height:26,fontSize:11,background:'var(--pink-tint)',color:'var(--magenta)'}}>{m.employee.split(' ').map(x=>x[0]).join('')}</span>{m.employee}</span> : <span className="muted">—</span>}</td>
                <td className="num">{H.fmtDate(m.date)} <span className="muted">{m.time}</span></td>
              </tr>);
            })}
            {rows.length===0 && <tr><td colSpan="7"><div className="empty"><Icon name="clock"/><div>No movements match</div></div></td></tr>}
          </tbody>
        </table></div>
      </Card>
    </div>
  );
}

/* ============ REPORTS ============ */
function ReportsScreen({products, movements}){
  const [tab, setTab] = React.useState('overview');
  const active = products.filter(p=>H.stockOf(p)>0);

  // ── CORE DATA ────────────────────────────────────────────────────────────

  // Items with urgency scores
  const itemRows = active.map(p => {
    const stock   = Math.round(H.stockOf(p)*100)/100;
    const st      = H.statusOf(p);
    const batches = [...p.batches].sort((a,b)=>a.expiry<b.expiry?-1:1);
    const nearest = batches[0]||null;
    const daysLeft= nearest ? H.daysUntil(nearest.expiry) : null;
    const expSt   = nearest ? H.expiryState(nearest.expiry) : null;
    let urgency = 9;
    if (st.key==='critical')              urgency=0;
    else if (expSt?.key==='expired')      urgency=1;
    else if (daysLeft!==null&&daysLeft<=30)urgency=2;
    else if (st.key==='low')              urgency=3;
    else if (daysLeft!==null&&daysLeft<=90)urgency=4;
    return {p, stock, st, nearest, daysLeft, expSt, urgency};
  }).sort((a,b)=>a.urgency-b.urgency||a.p.nameEn.localeCompare(b.p.nameEn));

  const needsAttention = itemRows.filter(r=>r.urgency<=4);

  // Category stats
  const byCat = DATA.categories.map(c=>{
    const items = active.filter(p=>p.category===c.id);
    const stock = Math.round(items.reduce((s,p)=>s+H.stockOf(p),0));
    const low   = items.filter(p=>['Low','Critical'].includes(H.statusOf(p).key)).length;
    const value = items.reduce((s,p)=>s+H.stockOf(p)*p.price,0);
    const outMvs= movements.filter(m=>m.type==='OUT'&&items.find(p=>p.id===m.productId));
    const qtyOut= Math.round(outMvs.reduce((s,m)=>s+m.qty,0)*10)/10;
    return {cat:c, items:items.length, stock, low, value, qtyOut, txns:outMvs.length};
  }).filter(x=>x.items>0).sort((a,b)=>b.value-a.value);
  const totalValue = byCat.reduce((s,x)=>s+x.value,0);

  // Top selling products (by qty out)
  const sellMap = {};
  movements.filter(m=>m.type==='OUT').forEach(m=>{
    if (!sellMap[m.productId]) sellMap[m.productId]={name:m.product,nameAr:m.productAr,qtyOut:0,txns:0,productId:m.productId};
    sellMap[m.productId].qtyOut = Math.round((sellMap[m.productId].qtyOut+m.qty)*100)/100;
    sellMap[m.productId].txns++;
  });
  const topSelling = Object.values(sellMap)
    .sort((a,b)=>b.qtyOut-a.qtyOut)
    .slice(0,10)
    .map(s=>({...s, p:products.find(p=>p.id===s.productId)}));

  // Slow movers: in stock but 0 OUT movements ever
  const slowMovers = active
    .filter(p=>!sellMap[p.id])
    .sort((a,b)=>H.stockOf(b)-H.stockOf(a))
    .slice(0,10);

  // Out-of-stock: products with 0 stock (need restocking)
  const outOfStock = products
    .filter(p=>H.stockOf(p)===0)
    .sort((a,b)=>a.nameEn.localeCompare(b.nameEn));

  // Expiry windows
  let allB=[]; active.forEach(p=>p.batches.forEach(b=>allB.push({...b,p})));
  const win={expired:[],d30:[],d90:[],ok:[]};
  allB.forEach(b=>{const d=H.daysUntil(b.expiry);if(d<0)win.expired.push(b);else if(d<=30)win.d30.push(b);else if(d<=90)win.d90.push(b);else win.ok.push(b);});

  // Last 7 days movement
  const days=[]; for(let i=6;i>=0;i--){const d=new Date(H.TODAY);d.setDate(d.getDate()-i);days.push(d.toISOString().slice(0,10));}
  const moveByDay=days.map(d=>{
    const dayM=movements.filter(m=>m.date===d);
    return{label:new Date(d+'T00:00:00').toLocaleDateString('en-GB',{weekday:'short'}),
      inN:dayM.filter(m=>m.type!=='OUT').length,outN:dayM.filter(m=>m.type==='OUT').length,total:dayM.length};
  });

  // ── PDF NAME HELPER ───────────────────────────────────────────────────────
  function pdfName(p){
    if(!p) return '—';
    const hasArabic=/[؀-ۿ]/.test(p.nameEn||'');
    return hasArabic ? p.code : (p.nameEn||p.code);
  }

  // ── PDF EXPORT ────────────────────────────────────────────────────────────
  function exportPDF(){
    if(!window.jspdf){toast({kind:'err',title:'PDF library not loaded yet'});return;}
    const {jsPDF}=window.jspdf;
    const doc=new jsPDF({orientation:'landscape',unit:'mm',format:'a4'});
    const date=new Date().toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'});
    const LABELS={overview:'Management Overview',items:'Items Report',stock:'Stock Report',movement:'Movement Report',expiry:'Expiry Report'};

    doc.setFillColor(215,0,89);
    doc.rect(0,0,297,22,'F');
    doc.setTextColor(255,255,255);
    doc.setFontSize(16);doc.setFont(undefined,'bold');
    doc.text('Helbawi Warehouse — '+LABELS[tab],14,14);
    doc.setFontSize(10);doc.setFont(undefined,'normal');
    doc.text('Generated: '+date,245,14);
    doc.setTextColor(30,19,32);

    const HEAD={fillColor:[215,0,89],textColor:255,fontStyle:'bold',fontSize:9};
    const BODY={fontSize:8.5};
    const ALT={fillColor:[250,248,252]};
    const FOOT={fillColor:[235,230,242],fontStyle:'bold',fontSize:9};

    if(tab==='overview'){
      doc.setFontSize(10);doc.setFont(undefined,'bold');
      doc.text(`In Stock: ${active.length}   Out of Stock: ${outOfStock.length}   Needs Attention: ${needsAttention.length}   Total Value: ${(totalValue/1e9).toFixed(2)}B LBP`,14,31);

      doc.setFontSize(12);doc.setFont(undefined,'bold');doc.text('Top Selling Products',14,40);
      doc.autoTable({startY:44,
        head:[['#','Product','Category','Unit','Total Qty Sold','Transactions']],
        body:topSelling.map((s,i)=>[i+1,pdfName(s.p),s.p?.category||'—',s.p?.unit||'—',H.fmtQty(s.qtyOut,s.p?.unit||'kg'),s.txns]),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,
        columnStyles:{0:{cellWidth:8,halign:'center'},4:{halign:'right'},5:{halign:'right'}},
        margin:{left:14,right:14},
      });

      const y2=doc.lastAutoTable.finalY+10;
      doc.setFontSize(12);doc.setFont(undefined,'bold');doc.text('Needs Attention (Low Stock & Expiring)',14,y2);
      doc.autoTable({startY:y2+4,
        head:[['Product','Category','Stock','Stock Status','Nearest Expiry','Days Left']],
        body:needsAttention.slice(0,20).map(r=>[pdfName(r.p),r.p.category,H.fmtQty(r.stock,r.p.unit),r.st.label,r.nearest?H.fmtDate(r.nearest.expiry):'—',r.daysLeft===null?'—':r.daysLeft<0?'EXPIRED':r.daysLeft+'d']),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,
        columnStyles:{2:{halign:'right'},5:{halign:'right'}},
        margin:{left:14,right:14},
      });

    } else if(tab==='items'){
      doc.setFontSize(10);doc.setFont(undefined,'bold');
      doc.text(`Total items in stock: ${active.length}   Needs attention: ${needsAttention.length}`,14,31);
      doc.autoTable({startY:36,
        head:[['#','Product','Category','Unit','Stock','Stock Status','Nearest Expiry','Days Left','Expiry Status']],
        body:itemRows.map((r,i)=>[i+1,pdfName(r.p),r.p.category,r.p.unit,H.fmtQty(r.stock,r.p.unit),r.st.label,r.nearest?H.fmtDate(r.nearest.expiry):'—',r.daysLeft===null?'—':r.daysLeft<0?'EXPIRED':r.daysLeft+'d',r.expSt?r.expSt.label:'—']),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,
        columnStyles:{0:{cellWidth:8,halign:'center'},4:{halign:'right'},7:{halign:'right'}},
        didParseCell(data){
          if(data.section!=='body')return;
          const r=itemRows[data.row.index];if(!r)return;
          if(r.urgency<=1)data.cell.styles.fillColor=[253,231,231];
          else if(r.urgency===2)data.cell.styles.fillColor=[255,238,221];
          else if(r.urgency===3)data.cell.styles.fillColor=[254,243,199];
          if(data.column.index===5){if(r.st.key==='critical'){data.cell.styles.textColor=[220,38,38];data.cell.styles.fontStyle='bold';}else if(r.st.key==='low'){data.cell.styles.textColor=[217,119,6];data.cell.styles.fontStyle='bold';}else data.cell.styles.textColor=[22,163,74];}
        },
        margin:{left:14,right:14},
      });

    } else if(tab==='stock'){
      doc.setFontSize(10);doc.setFont(undefined,'bold');
      doc.text(`Items: ${active.length}   Categories: ${byCat.length}   Total value: ${(totalValue/1e9).toFixed(2)}B LBP`,14,31);
      doc.autoTable({startY:36,head:[['Category','Items','Total Stock','Qty Sold','Low/Critical','Value (LBP)']],
        body:byCat.map(x=>[x.cat.label,x.items,H.fmtNum(x.stock),H.fmtNum(x.qtyOut),x.low,H.fmtNum(Math.round(x.value))]),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,
        columnStyles:{1:{halign:'right'},2:{halign:'right'},3:{halign:'right'},4:{halign:'right'},5:{halign:'right'}},
        foot:[['TOTAL',byCat.reduce((s,x)=>s+x.items,0),H.fmtNum(byCat.reduce((s,x)=>s+x.stock,0)),H.fmtNum(Math.round(byCat.reduce((s,x)=>s+x.qtyOut,0))),byCat.reduce((s,x)=>s+x.low,0),H.fmtNum(Math.round(totalValue))]],
        footStyles:FOOT,margin:{left:14,right:14},
      });

    } else if(tab==='movement'){
      doc.setFontSize(10);doc.setFont(undefined,'bold');
      doc.text(`Stock-In: ${movements.filter(m=>m.type!=='OUT').length}   Stock-Out: ${movements.filter(m=>m.type==='OUT').length}   Total: ${movements.length}`,14,31);
      doc.autoTable({startY:36,head:[['Date','Time','Product','Type','Quantity','Batch','Employee']],
        body:movements.slice(0,500).map(m=>{const mp=products.find(p=>p.id===m.productId);return[H.fmtDate(m.date),m.time||'',mp?pdfName(mp):m.product,m.type==='OUT'?'Stock Out':m.type==='IN'?'Stock In':'New Batch',(m.type==='OUT'?'− ':'+ ')+H.fmtQty(m.qty,m.unit),m.batchCode||'—',m.employee||'—'];}),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,columnStyles:{4:{halign:'right'}},margin:{left:14,right:14},
      });

    } else {
      const attention=[...win.expired,...win.d30].sort((a,b)=>a.expiry<b.expiry?-1:1);
      doc.setFontSize(10);doc.setFont(undefined,'bold');
      doc.text(`Expired: ${win.expired.length}   ≤30 days: ${win.d30.length}   ≤90 days: ${win.d90.length}   Healthy: ${win.ok.length}`,14,31);
      doc.autoTable({startY:36,head:[['Batch','Product','Category','Quantity','Expiry Date','Days Left','Status']],
        body:attention.map(b=>{const d=H.daysUntil(b.expiry);return[b.code,pdfName(b.p),b.p.category,H.fmtQty(b.qty,b.p.unit),H.fmtDate(b.expiry),d<0?'EXPIRED':d+'d',d<0?'Expired':'Expiring'];}),
        headStyles:HEAD,bodyStyles:BODY,alternateRowStyles:ALT,
        columnStyles:{3:{halign:'right'},5:{halign:'right'}},
        didParseCell(data){if(data.section==='body'&&data.column.index===6){data.cell.styles.textColor=data.cell.raw==='Expired'?[220,38,38]:[234,88,12];data.cell.styles.fontStyle='bold';}},
        margin:{left:14,right:14},
      });
    }

    const pages=doc.internal.getNumberOfPages();
    for(let i=1;i<=pages;i++){doc.setPage(i);doc.setFontSize(8);doc.setTextColor(150);doc.text(`Helbawi Warehouse · ${LABELS[tab]} · ${date} · Page ${i} of ${pages}`,14,doc.internal.pageSize.height-6);}
    doc.save(`helbawi-${tab}-report-${new Date().toISOString().slice(0,10)}.pdf`);
    toast({kind:'ok',title:'PDF exported',desc:`helbawi-${tab}-report downloaded`});
  }

  // ── URGENCY ROW STYLE ────────────────────────────────────────────────────
  function urgRow(r){
    if(r.urgency<=1)return{background:'#FDE7E7'};
    if(r.urgency===2)return{background:'#FFF0E6'};
    if(r.urgency===3)return{background:'#FFFBEB'};
    return{};
  }

  const Tabs=(
    <div className="seg" style={{marginBottom:0,flexWrap:'wrap',gap:4}}>
      {[['overview','Overview'],['items','Items'],['stock','Stock'],['movement','Movement'],['expiry','Expiry']].map(([v,l])=>(
        <button key={v} className={tab===v?'on':''} onClick={()=>setTab(v)}>{l}</button>
      ))}
    </div>
  );

  return (
    <div className="content fade-up">
      <Toolbar right={<button className="btn btn-soft" onClick={exportPDF}><Icon name="download" size={18}/> Export PDF</button>}>
        {Tabs}
      </Toolbar>

      {/* ══ OVERVIEW TAB ══ */}
      {tab==='overview' && (<>

        {/* KPI row */}
        <div className="kpi-row" style={{gridTemplateColumns:'repeat(5,1fr)'}}>
          <KPICard icon="box"          label="In Stock"       value={active.length}           sub="Products with stock"       color="#D70059" tint="#FDEAF2" accent="#D70059"/>
          <KPICard icon="trendUp"      label="Inventory Value" value={(totalValue/1e9).toFixed(2)+'B'} sub="LBP at selling price" color="#16A34A" tint="#E8F7EE" accent="#16A34A"/>
          <KPICard icon="alert"        label="Needs Attention" value={needsAttention.length}   sub="Low stock or expiring"     color="#DC2626" tint="#FDE7E7" accent="#DC2626"/>
          <KPICard icon="expire"       label="Expiring ≤30d"   value={win.expired.length+win.d30.length} sub="Batches needing action" color="#EA580C" tint="#FFEEDD" accent="#EA580C"/>
          <KPICard icon="box"          label="Out of Stock"    value={outOfStock.length}        sub="Need restocking"           color="#7C3AED" tint="#F1E9FE" accent="#7C3AED"/>
        </div>

        {/* Top row: Top Selling + Category Performance */}
        <div className="grid-2" style={{gridTemplateColumns:'1.2fr 1fr'}}>

          {/* Top Selling */}
          <Card>
            <CardHead title="🏆 Top Selling Products" sub="Ranked by total quantity sold (stock out)"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>#</th><th>Product</th><th>Category</th><th className="right">Qty Sold</th><th className="right">Transactions</th></tr></thead>
              <tbody>
                {topSelling.length===0 && <tr><td colSpan="5"><div className="empty"><Icon name="arrowUpCircle"/><div>No stock-out movements yet</div></div></td></tr>}
                {topSelling.map((s,i)=>(
                  <tr key={s.productId}>
                    <td className="muted num" style={{fontSize:12,width:28}}>
                      {i===0?'🥇':i===1?'🥈':i===2?'🥉':<span style={{fontWeight:700}}>{i+1}</span>}
                    </td>
                    <td>
                      <div className="pcell">
                        {s.p?<ProductThumb p={s.p} size={32}/>:<div className="thumb" style={{width:32,height:32,background:'#F1EFF3'}}><Icon name="box" size={15}/></div>}
                        <div className="col">
                          <span className="nm" style={{fontSize:13}}>{s.p?.nameEn||s.name}</span>
                          {s.p?.nameAr&&s.p.nameAr!==s.p.nameEn&&<span className="nm-ar ar">{s.p.nameAr}</span>}
                        </div>
                      </div>
                    </td>
                    <td><span className="pill np" style={{background:H.CAT_COLOR[s.p?.category]+'22',color:H.CAT_COLOR[s.p?.category],fontSize:11}}>{s.p?.category||'—'}</span></td>
                    <td className="right strong num">{H.fmtQty(s.qtyOut, s.p?.unit||'kg')}</td>
                    <td className="right"><span className="pill np pill-mag">{s.txns}</span></td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          </Card>

          {/* Category Performance */}
          <Card>
            <CardHead title="📦 Category Performance" sub="Stock value and qty sold per category"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>Category</th><th className="right">Items</th><th className="right">Qty Sold</th><th className="right">Value (LBP)</th></tr></thead>
              <tbody>
                {byCat.sort((a,b)=>b.qtyOut-a.qtyOut).map((x,i)=>(
                  <tr key={i}>
                    <td><span className="row" style={{gap:8}}><span style={{width:10,height:10,borderRadius:3,background:x.cat.color,flexShrink:0}}/><span className="strong" style={{fontSize:13}}>{x.cat.label}</span></span></td>
                    <td className="right num">{x.items}</td>
                    <td className="right strong num">{H.fmtNum(Math.round(x.qtyOut))}</td>
                    <td className="right num" style={{fontSize:12}}>{(x.value/1e9).toFixed(2)}B</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          </Card>
        </div>

        {/* Needs Attention */}
        {needsAttention.length>0 && (
          <Card>
            <CardHead title="⚠️ Needs Attention" sub="Critical stock, low stock, and expiring items — act on these first"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>Product</th><th>Category</th><th className="right">Stock</th><th>Stock Status</th><th>Nearest Expiry</th><th>Days Left</th></tr></thead>
              <tbody>
                {needsAttention.slice(0,15).map(r=>(
                  <tr key={r.p.id} style={urgRow(r)}>
                    <td><PName p={r.p}/></td>
                    <td><span className="pill np" style={{background:H.CAT_COLOR[r.p.category]+'22',color:H.CAT_COLOR[r.p.category]}}>{r.p.category}</span></td>
                    <td className="right strong num">{H.fmtQty(r.stock,r.p.unit)}</td>
                    <td><span className={'pill '+r.st.cls}>{r.st.label}</span></td>
                    <td className="num">{r.nearest?H.fmtDate(r.nearest.expiry):<span className="muted">—</span>}</td>
                    <td className="right num">
                      {r.daysLeft===null?<span className="muted">—</span>
                        :r.daysLeft<0?<span className="pill pill-crit">Expired</span>
                        :r.daysLeft<=30?<span style={{color:'var(--exp)',fontWeight:700}}>{r.daysLeft}d</span>
                        :<span style={{color:'var(--low)',fontWeight:700}}>{r.daysLeft}d</span>}
                    </td>
                  </tr>
                ))}
                {needsAttention.length>15&&<tr><td colSpan="6" style={{textAlign:'center',padding:'10px',color:'var(--muted)',fontWeight:600}}>+{needsAttention.length-15} more — switch to Items tab for full list</td></tr>}
              </tbody>
            </table></div>
          </Card>
        )}

        {/* Bottom row: Slow Movers + Out of Stock */}
        <div className="grid-2">
          {/* Slow Movers */}
          <Card>
            <CardHead title="🐢 Slow Movers" sub="In stock but never sold — consider promoting or repositioning"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>Product</th><th>Category</th><th className="right">Stock</th></tr></thead>
              <tbody>
                {slowMovers.length===0&&<tr><td colSpan="3"><div className="empty"><Icon name="checkCircle"/><div>All stocked items have been sold</div></div></td></tr>}
                {slowMovers.map(p=>(
                  <tr key={p.id}>
                    <td><PName p={p}/></td>
                    <td><span className="pill np" style={{background:H.CAT_COLOR[p.category]+'22',color:H.CAT_COLOR[p.category],fontSize:11}}>{p.category}</span></td>
                    <td className="right strong num">{H.fmtQty(H.stockOf(p),p.unit)}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          </Card>

          {/* Out of Stock */}
          <Card>
            <CardHead title="🔴 Out of Stock" sub="No stock remaining — reorder these products"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>Product</th><th>Category</th><th>Unit</th></tr></thead>
              <tbody>
                {outOfStock.length===0&&<tr><td colSpan="3"><div className="empty"><Icon name="checkCircle"/><div>All products have stock</div></div></td></tr>}
                {outOfStock.slice(0,10).map(p=>(
                  <tr key={p.id}>
                    <td><PName p={p}/></td>
                    <td><span className="pill np" style={{background:H.CAT_COLOR[p.category]+'22',color:H.CAT_COLOR[p.category],fontSize:11}}>{p.category}</span></td>
                    <td className="muted">{p.unit}</td>
                  </tr>
                ))}
                {outOfStock.length>10&&<tr><td colSpan="3" style={{textAlign:'center',padding:'10px',color:'var(--muted)',fontWeight:600}}>+{outOfStock.length-10} more out of stock</td></tr>}
              </tbody>
            </table></div>
          </Card>
        </div>

        {/* 7-day movement chart */}
        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 4px'}}>Stock Movement — Last 7 Days</h2>
          <p style={{color:'var(--muted)',fontSize:13,margin:'0 0 16px'}}>Total transactions per day</p>
          <BarChart data={moveByDay.map(d=>({label:d.label,value:d.total,color:'#D70059'}))} height={200}/>
        </Card>

      </>)}

      {/* ══ ITEMS TAB ══ */}
      {tab==='items' && (<>
        <div className="kpi-row" style={{gridTemplateColumns:'repeat(4,1fr)'}}>
          <KPICard icon="box" label="Items in Stock" value={active.length} sub="All stocked products" color="#D70059" tint="#FDEAF2" accent="#D70059"/>
          <KPICard icon="alert" label="Needs Attention" value={needsAttention.length} sub="Low stock or expiring" color="#DC2626" tint="#FDE7E7" accent="#DC2626"/>
          <KPICard icon="expire" label="Expiring ≤ 30 days" value={win.d30.length+win.expired.length} sub="Batches needing action" color="#EA580C" tint="#FFEEDD" accent="#EA580C"/>
          <KPICard icon="trendDown" label="Low / Critical" value={active.filter(p=>['low','critical'].includes(H.statusOf(p).key)).length} sub="Stock running out" color="#D97706" tint="#FEF3C7" accent="#D97706"/>
        </div>
        {needsAttention.length>0&&(
          <Card>
            <CardHead title={<span style={{display:'flex',alignItems:'center',gap:8}}><span style={{width:10,height:10,borderRadius:3,background:'#DC2626',display:'inline-block'}}/> Needs Attention ({needsAttention.length})</span>} sub="Critical stock, low stock, or expiring items — sorted by urgency"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>Product</th><th>Category</th><th className="right">Stock</th><th>Stock Status</th><th>Nearest Expiry</th><th>Days Left</th><th>Expiry Status</th></tr></thead>
              <tbody>{needsAttention.map(r=>(<tr key={r.p.id} style={urgRow(r)}>
                <td><PName p={r.p}/></td>
                <td><span className="pill np" style={{background:H.CAT_COLOR[r.p.category]+'22',color:H.CAT_COLOR[r.p.category]}}>{r.p.category}</span></td>
                <td className="right strong num">{H.fmtQty(r.stock,r.p.unit)}</td>
                <td><span className={'pill '+r.st.cls}>{r.st.label}</span></td>
                <td className="num">{r.nearest?H.fmtDate(r.nearest.expiry):<span className="muted">—</span>}</td>
                <td className="right num">{r.daysLeft===null?<span className="muted">—</span>:r.daysLeft<0?<span className="pill pill-crit">Expired</span>:r.daysLeft<=30?<span style={{color:'var(--exp)',fontWeight:700}}>{r.daysLeft}d</span>:<span style={{color:'var(--low)',fontWeight:700}}>{r.daysLeft}d</span>}</td>
                <td>{r.expSt?<span className={'pill '+r.expSt.cls}>{r.expSt.label}</span>:<span className="muted">—</span>}</td>
              </tr>))}</tbody>
            </table></div>
          </Card>
        )}
        <Card>
          <CardHead title={<span style={{display:'flex',alignItems:'center',gap:8}}><span style={{width:10,height:10,borderRadius:3,background:'#16A34A',display:'inline-block'}}/> All Items ({active.length})</span>} sub="Every stocked product with current weight and nearest expiry date"/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr><th>#</th><th>Product</th><th>Category</th><th className="right">Stock</th><th>Stock Status</th><th>Nearest Expiry</th><th>Days Left</th><th>Expiry Status</th></tr></thead>
            <tbody>{itemRows.map((r,i)=>(<tr key={r.p.id} style={urgRow(r)}>
              <td className="muted num" style={{fontSize:12}}>{i+1}</td>
              <td><PName p={r.p}/></td>
              <td><span className="pill np" style={{background:H.CAT_COLOR[r.p.category]+'22',color:H.CAT_COLOR[r.p.category]}}>{r.p.category}</span></td>
              <td className="right strong num">{H.fmtQty(r.stock,r.p.unit)}</td>
              <td><span className={'pill '+r.st.cls}>{r.st.label}</span></td>
              <td className="num">{r.nearest?H.fmtDate(r.nearest.expiry):<span className="muted">—</span>}</td>
              <td className="right num">{r.daysLeft===null?<span className="muted">—</span>:r.daysLeft<0?<span className="pill pill-crit">Expired</span>:r.daysLeft<=30?<span style={{color:'var(--exp)',fontWeight:700}}>{r.daysLeft}d</span>:r.daysLeft<=90?<span style={{color:'var(--low)',fontWeight:700}}>{r.daysLeft}d</span>:<span className="muted num">{r.daysLeft}d</span>}</td>
              <td>{r.expSt?<span className={'pill '+r.expSt.cls}>{r.expSt.label}</span>:<span className="muted">—</span>}</td>
            </tr>))}</tbody>
          </table></div>
        </Card>
      </>)}

      {/* ══ STOCK TAB ══ */}
      {tab==='stock' && (<>
        <div className="kpi-row" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
          <KPICard icon="box" label="Items in Stock" value={active.length} sub="Across all categories" color="#D70059" tint="#FDEAF2" accent="#D70059"/>
          <KPICard icon="layers" label="Categories" value={byCat.length} sub="Active product groups" color="#7C3AED" tint="#F1E9FE" accent="#7C3AED"/>
          <KPICard icon="trendUp" label="Inventory Value" value={(totalValue/1e9).toFixed(2)+'B'} sub="Total LBP at selling price" color="#16A34A" tint="#E8F7EE" accent="#16A34A"/>
        </div>
        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 14px'}}>Stock by Category</h2>
          <BarChart data={byCat.map(x=>({label:x.cat.label.split(' ')[0],value:x.stock,color:x.cat.color}))} height={250}/>
        </Card>
        <Card>
          <CardHead title="Category Breakdown" sub="Stock levels, sales, and value per category"/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr><th>Category</th><th className="right">Items</th><th className="right">Stock</th><th className="right">Qty Sold</th><th className="right">Low/Critical</th><th className="right">Value (LBP)</th></tr></thead>
            <tbody>{byCat.map((x,i)=>(<tr key={i}>
              <td><span className="row" style={{gap:10}}><span style={{width:11,height:11,borderRadius:4,background:x.cat.color}}/><span className="strong">{x.cat.label}</span></span></td>
              <td className="right num">{x.items}</td>
              <td className="right strong num">{H.fmtNum(x.stock)}</td>
              <td className="right num" style={{color:'var(--low)',fontWeight:700}}>{H.fmtNum(Math.round(x.qtyOut))}</td>
              <td className="right">{x.low>0?<span className="pill pill-low">{x.low}</span>:<span className="muted num">0</span>}</td>
              <td className="right num strong">{H.fmtNum(x.value)}</td>
            </tr>))}</tbody>
          </table></div>
        </Card>
      </>)}

      {/* ══ MOVEMENT TAB ══ */}
      {tab==='movement' && (<>
        <div className="kpi-row" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
          <KPICard icon="arrowDownCircle" label="Stock In (events)" value={movements.filter(m=>m.type!=='OUT').length} sub="Receipts & batches" color="#16A34A" tint="#E8F7EE" accent="#16A34A"/>
          <KPICard icon="arrowUpCircle" label="Stock Out (events)" value={movements.filter(m=>m.type==='OUT').length} sub="Items dispatched" color="#D97706" tint="#FEF3C7" accent="#D97706"/>
          <KPICard icon="refresh" label="Total Movements" value={movements.length} sub="All transactions" color="#D70059" tint="#FDEAF2" accent="#D70059"/>
        </div>
        <div className="grid-2" style={{gridTemplateColumns:'1.5fr 1fr'}}>
          <Card className="card-pad">
            <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 14px'}}>Movements — Last 7 Days</h2>
            <BarChart data={moveByDay.map(d=>({label:d.label,value:d.total,color:'#D70059'}))} height={250}/>
          </Card>
          <Card>
            <CardHead title="Top Selling Products" sub="By total qty sold"/>
            <div className="tbl-wrap"><table className="tbl">
              <thead><tr><th>#</th><th>Product</th><th className="right">Qty</th><th className="right">Txns</th></tr></thead>
              <tbody>{topSelling.slice(0,8).map((s,i)=>(<tr key={s.productId}>
                <td className="muted num" style={{fontSize:12,width:24}}>{i+1}</td>
                <td className="strong" style={{fontSize:13}}>{s.p?.nameEn||s.name}</td>
                <td className="right strong num">{H.fmtQty(s.qtyOut,s.p?.unit||'kg')}</td>
                <td className="right"><span className="pill np pill-mag">{s.txns}</span></td>
              </tr>))}</tbody>
            </table></div>
          </Card>
        </div>
      </>)}

      {/* ══ EXPIRY TAB ══ */}
      {tab==='expiry' && (<>
        <div className="kpi-row" style={{gridTemplateColumns:'repeat(4,1fr)'}}>
          <KPICard icon="alert" label="Expired" value={win.expired.length} sub="Remove from shelves" color="#DC2626" tint="#FDE7E7" accent="#DC2626"/>
          <KPICard icon="expire" label="≤ 30 days" value={win.d30.length} sub="Sell or discount soon" color="#EA580C" tint="#FFEEDD" accent="#EA580C"/>
          <KPICard icon="calendar" label="≤ 90 days" value={win.d90.length} sub="Monitor closely" color="#D97706" tint="#FEF3C7" accent="#D97706"/>
          <KPICard icon="checkCircle" label="Healthy" value={win.ok.length} sub="More than 90 days" color="#16A34A" tint="#E8F7EE" accent="#16A34A"/>
        </div>
        <Card>
          <CardHead title="Batches Needing Attention" sub="Expired and expiring within 30 days"/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr><th>Batch</th><th>Item</th><th className="right">Quantity</th><th>Expiry</th><th className="right">Remaining</th><th>Status</th></tr></thead>
            <tbody>
              {[...win.expired,...win.d30].sort((a,b)=>a.expiry<b.expiry?-1:1).map((b,i)=>{const es=H.expiryState(b.expiry);return(
                <tr key={i}><td className="strong num">{b.code}</td>
                  <td><div className="pcell"><ProductThumb p={b.p} size={32}/><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.expiry)}</td>
                  <td className="right"><span className={'pill '+es.cls}>{es.label}</span></td>
                  <td><span className={'pill '+(es.key==='expired'?'pill-crit':'pill-exp')}>{es.key==='expired'?'Expired':'Expiring'}</span></td>
                </tr>);})}
              {win.expired.length+win.d30.length===0&&<tr><td colSpan="6"><div className="empty"><Icon name="checkCircle"/><div>Nothing expiring within 30 days</div></div></td></tr>}
            </tbody>
          </table></div>
        </Card>
      </>)}
    </div>
  );
}

Object.assign(window,{MovementsScreen,ReportsScreen});
