/* ============ DASHBOARD ============ */
function buildTrend(range, base){
  // deterministic believable shape (dip then climb, like the inspo)
  const shape = {
    'This Week':[.72,.66,.7,.84,.92,.88,1],
    'This Month':[.62,.55,.5,.52,.74,.95,.9,.78,.7,.8,.86,1],
    'This Quarter':[.5,.58,.54,.66,.62,.72,.8,.76,.88,.84,.92,1],
  }[range];
  const labels = {
    'This Week':['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
    'This Month':['May 1','','May 8','','May 15','','May 22','','May 26','','','May 28'],
    'This Quarter':['Mar','','Apr','','','May','','','','','','Now'],
  }[range];
  return {data:shape.map(s=>Math.round(base*s)), labels};
}

function Dashboard({products, movements, setRoute}){
  const [range, setRange] = React.useState('This Month');
  const active = products.filter(p=>H.stockOf(p)>0);
  const low = active.filter(p=>['Low','Critical'].includes(H.statusOf(p).key));
  const expiring = active
    .map(p=>({p, exp:H.nearestExpiry(p)}))
    .filter(x=>x.exp && H.daysUntil(x.exp) >= 0 && H.daysUntil(x.exp) <= 35)
    .sort((a,b)=>a.exp<b.exp?-1:1);
  const totalStock = Math.round(active.reduce((s,p)=>s+H.stockOf(p),0));
  const totalBatches = active.reduce((s,p)=>s+p.batches.length,0);

  // category aggregation for donut
  const catTotals = {};
  active.forEach(p=>{ catTotals[p.category]=(catTotals[p.category]||0)+H.stockOf(p); });
  let segs = Object.entries(catTotals).map(([k,v])=>({label:k, value:Math.round(v), color:H.CAT_COLOR[k]}))
    .sort((a,b)=>b.value-a.value);
  const top = segs.slice(0,4);
  const otherVal = segs.slice(4).reduce((s,x)=>s+x.value,0);
  if(otherVal>0) top.push({label:'Others', value:otherVal, color:'#C9BFD0'});
  const donutSum = top.reduce((s,x)=>s+x.value,0)||1;

  const trend = buildTrend(range, Math.round(totalStock*1.05));

  // recent activity from movements
  const actMap = {
    IN:{icon:'arrowDownCircle', color:'#16A34A', bg:'#E8F7EE', verb:'Stock In'},
    OUT:{icon:'arrowUpCircle', color:'#D97706', bg:'#FEF3C7', verb:'Stock Out'},
    NEW_BATCH:{icon:'layers', color:'#7C3AED', bg:'#F1E9FE', verb:'New Batch Added'},
  };
  const recentAct = movements.slice(0,5);

  // recent batches across products
  const allBatches = [];
  active.forEach(p=>p.batches.forEach(b=>allBatches.push({...b, p})));
  allBatches.sort((a,b)=>a.addedOn<b.addedOn?1:-1);
  const recentBatches = allBatches.slice(0,6);

  return (
    <div className="content fade-up">
      {/* KPIs */}
      <div className="kpi-row">
        <KPICard icon="box" label="Total Items" value={H.fmtNum(active.length)} sub="All inventory items in stock"
          color="#D70059" tint="#FDEAF2" accent="#D70059"/>
        <KPICard icon="layers" label="Total Stock" value={H.fmtNum(totalStock)} sub={`Across ${totalBatches} active batches`}
          color="#E84393" tint="#FDEAF2" accent="#E84393"/>
        <KPICard icon="alert" label="Low Stock Items" value={H.fmtNum(low.length)} sub="Need restocking attention"
          color="#D97706" tint="#FEF3C7" accent="#D97706"/>
        <KPICard icon="calendar" label="Expiring Soon" value={H.fmtNum(expiring.length)} sub="Within the next 35 days"
          color="#7C3AED" tint="#F1E9FE" accent="#7C3AED"/>
      </div>

      {/* Alerts row */}
      <div className="grid-2">
        <Card>
          <CardHead title="Low Stock Alerts" sub="Items at or below their minimum threshold"
            right={<button className="link" onClick={()=>setRoute('low-stock')}>View All <Icon name="arrowR" size={15}/></button>}/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr><th>Item</th><th className="right">Current</th><th className="right">Minimum</th><th>Status</th></tr></thead>
            <tbody>
              {low.slice(0,5).map(p=>(
                <tr key={p.id}>
                  <td><PName p={p}/></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>
                </tr>
              ))}
              {low.length===0 && <tr><td colSpan="4"><div className="empty"><Icon name="checkCircle"/><div>All items above threshold</div></div></td></tr>}
            </tbody>
          </table></div>
        </Card>

        <Card>
          <CardHead title="Expiring Soon" sub="Batches approaching their expiry date"
            right={<button className="link" onClick={()=>setRoute('batches')}>View All <Icon name="arrowR" size={15}/></button>}/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr><th>Item</th><th>Batch Code</th><th>Expiry Date</th><th className="right">Remaining</th></tr></thead>
            <tbody>
              {expiring.slice(0,5).map(({p,exp})=>{
                const b = p.batches.find(x=>x.expiry===exp);
                const es = H.expiryState(exp);
                return (<tr key={p.id}>
                  <td><PName p={p} hideAr/></td>
                  <td className="num" style={{fontWeight:600}}>{b.code}</td>
                  <td className="num">{H.fmtDate(exp)}</td>
                  <td className="right"><span className={'pill '+es.cls}>{es.label}</span></td>
                </tr>);
              })}
              {expiring.length===0 && <tr><td colSpan="4"><div className="empty"><Icon name="checkCircle"/><div>Nothing expiring soon</div></div></td></tr>}
            </tbody>
          </table></div>
        </Card>
      </div>

      {/* Charts row */}
      <div className="grid-charts">
        <Card className="card-pad">
          <div className="spread" style={{marginBottom:6}}>
            <div><h2 style={{fontSize:18,fontWeight:800,margin:0}}>Stock Overview</h2>
              <div className="sub" style={{color:'var(--muted)',fontSize:13,marginTop:2}}>Total stock movement trend</div></div>
            <Segmented value={range} onChange={setRange}
              options={[{value:'This Week',label:'Week'},{value:'This Month',label:'Month'},{value:'This Quarter',label:'Quarter'}]}/>
          </div>
          <AreaChart data={trend.data} labels={trend.labels} height={250}/>
        </Card>

        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 14px'}}>Stock by Category</h2>
          <div style={{display:'flex',alignItems:'center',justifyContent:'center',marginBottom:18}}>
            <Donut segments={top} centerLabel={H.fmtNum(donutSum)} centerSub="Total stock" size={186} thickness={28}/>
          </div>
          <div className="legend">
            {top.map((s,i)=>(
              <div className="leg" key={i}>
                <span className="sw" style={{background:s.color}}></span>
                <span className="ln">{s.label}</span>
                <span className="lv num">{H.fmtNum(s.value)} ({Math.round(s.value/donutSum*100)}%)</span>
              </div>
            ))}
          </div>
        </Card>

        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 8px'}}>Recent Activity</h2>
          <div>
            {recentAct.map(m=>{
              const a = actMap[m.type];
              return (<div className="act" key={m.id}>
                <div className="aic" style={{background:a.bg, color:a.color}}><Icon name={a.icon} size={19}/></div>
                <div style={{minWidth:0}}>
                  <div className="atitle">{a.verb}</div>
                  <div className="adesc">{m.product} · {H.fmtQty(m.qty, m.unit)}</div>
                </div>
                <div className="atime">{H.relTime(m.date, m.time)}</div>
              </div>);
            })}
          </div>
        </Card>
      </div>

      {/* Recent batches */}
      <Card>
        <CardHead title="Recent Batches" sub="Latest stock received into the warehouse"
          right={<button className="link" onClick={()=>setRoute('batches')}>View All <Icon name="arrowR" size={15}/></button>}/>
        <div style={{padding:'0 16px 16px'}}>
          <div className="tbl-wrap"><table className="tbl tbl-mag">
            <thead><tr><th>Batch Code</th><th>Item</th><th className="right">Quantity</th><th>Added On</th><th>Expiry Date</th><th>Status</th></tr></thead>
            <tbody>
              {recentBatches.map((b,i)=>{
                const es = H.expiryState(b.expiry);
                const stat = es.key==='expired'? {cls:'pill-crit',label:'Expired'} : es.key==='soon'? {cls:'pill-exp',label:'Expiring'} : {cls:'pill-ok',label:'Active'};
                return (<tr key={i}>
                  <td className="strong num">{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><span className={'pill '+stat.cls}>{stat.label}</span></td>
                </tr>);
              })}
            </tbody>
          </table></div>
        </div>
      </Card>
    </div>
  );
}
window.Dashboard = Dashboard;
