// Enhanced Company Dashboard — Fully Interactive ERP-Style with Drill-Down
const { useState: dSt, useEffect: dEf, useContext: dCtx, useMemo: dMemo } = React;

// ── Date helpers ──────────────────────────────────────────
function getRange(preset, cFrom, cTo) {
  const now = new Date(), tod = now.toISOString().slice(0,10);
  const yst = new Date(now - 86400000).toISOString().slice(0,10);
  if (preset === 'today')     return { from: tod, to: tod };
  if (preset === 'yesterday') return { from: yst, to: yst };
  if (preset === 'week')      { const s = new Date(now); s.setDate(now.getDate() - now.getDay()); return { from: s.toISOString().slice(0,10), to: tod }; }
  if (preset === 'month')     return { from: `${tod.slice(0,7)}-01`, to: tod };
  if (preset === 'custom')    return { from: cFrom || tod, to: cTo || tod };
  return { from: null, to: null };
}
function inRange(d, from, to) {
  if (!d) return false;
  if (from && d < from) return false;
  if (to   && d > to)   return false;
  return true;
}

// ── Premium Material Quantity Comparison Chart ────────────
function GroupedBar({ data, h = 150, onBarClick }) {
  const [hovered, setHovered] = dSt(null);
  const [selected, setSelected] = dSt(null);
  const [tooltip, setTooltip] = dSt(null);
  const [mounted, setMounted] = dSt(false);
  const containerRef = React.useRef(null);
  const dataKey = data ? data.map(d => (d.purchased||0)+'_'+(d.sold||0)).join(',') : '';

  dEf(() => {
    setMounted(false);
    setSelected(null);
    const t = setTimeout(() => setMounted(true), 80);
    return () => clearTimeout(t);
  }, [dataKey]);

  if (!data || !data.length) return (
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',
      padding:'28px 0',gap:8,animation:'omFadeIn .4s ease'}}>
      <svg width="36" height="36" viewBox="0 0 36 36" fill="none">
        <rect x="4" y="20" width="7" height="12" rx="2.5" fill="#E5E3DF"/>
        <rect x="14.5" y="11" width="7" height="21" rx="2.5" fill="#E5E3DF"/>
        <rect x="25" y="16" width="7" height="16" rx="2.5" fill="#E5E3DF"/>
      </svg>
      <div style={{fontSize:11.5,color:'var(--txt3)',fontWeight:500,letterSpacing:'-.01em'}}>No Material Data Available</div>
    </div>
  );

  const maxV = Math.max(...data.flatMap(d => [d.purchased||0, d.sold||0]), 1);
  const totalQty = data.reduce((s,d) => s+(d.purchased||0)+(d.sold||0), 0);
  const chartH = h - 28;

  const handleEnter = (i, d, e) => {
    setHovered(i);
    if (containerRef.current) {
      const r = containerRef.current.getBoundingClientRect();
      setTooltip({ x: e.clientX - r.left, y: e.clientY - r.top, d, i });
    }
  };
  const handleMove = (i, d, e) => {
    if (containerRef.current) {
      const r = containerRef.current.getBoundingClientRect();
      setTooltip(prev => prev ? { ...prev, x: e.clientX - r.left, y: e.clientY - r.top } : null);
    }
  };
  const handleLeave = () => { setHovered(null); setTooltip(null); };
  const handleClick = (i, d) => {
    const next = selected === i ? null : i;
    setSelected(next);
    if (next !== null) onBarClick && onBarClick(d);
  };

  return (
    <div ref={containerRef} style={{position:'relative',userSelect:'none',paddingTop:6}}>
      {/* Chart area */}
      <div style={{position:'relative',height:chartH}}>
        {/* Hairline grid */}
        {[0,.25,.5,.75,1].map((t,gi) => (
          <div key={gi} style={{
            position:'absolute',left:0,right:0,
            bottom:`${t*100}%`,
            height:1,
            background:t===0?'rgba(0,0,0,0.055)':'rgba(0,0,0,0.022)',
            pointerEvents:'none',
          }}/>
        ))}
        {/* Bar groups */}
        <div style={{display:'flex',alignItems:'flex-end',height:'100%',gap:5,padding:'0 2px'}}>
          {data.map((d, i) => {
            const pPct = (d.purchased||0) / maxV;
            const sPct = (d.sold||0) / maxV;
            const isHov = hovered === i;
            const isSel = selected === i;
            const isDim = (hovered !== null && !isHov) || (selected !== null && !isSel);
            const delay = `${i * 65}ms`;
            const lift = isHov || isSel ? 'translateY(-3px)' : 'translateY(0)';
            return (
              <div key={d.id||i}
                style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',
                  gap:0,cursor:'pointer',height:'100%',
                  opacity: isDim ? 0.28 : 1,
                  transition:'opacity 0.22s ease',
                }}
                onMouseEnter={e=>handleEnter(i,d,e)}
                onMouseMove={e=>handleMove(i,d,e)}
                onMouseLeave={handleLeave}
                onClick={()=>handleClick(i,d)}
              >
                <div style={{display:'flex',alignItems:'flex-end',gap:2,width:'100%',maxWidth:52,height:'100%'}}>
                  {/* Purchase bar */}
                  <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'flex-end',height:'100%'}}>
                    {pPct > 0 && <div style={{
                      width:'100%',
                      height: mounted ? `${Math.max(pPct*100,1.5)}%` : '0%',
                      background:'linear-gradient(180deg,#FB923C 0%,#C2440C 100%)',
                      borderRadius:'6px 6px 3px 3px',
                      transition:`height 0.6s cubic-bezier(0.22,1,0.36,1) ${delay}, transform 0.2s ease, box-shadow 0.2s ease`,
                      transform: lift,
                      boxShadow: isSel
                        ? '0 0 0 2px rgba(249,115,22,0.3),0 6px 18px rgba(249,115,22,0.38)'
                        : isHov ? '0 4px 14px rgba(249,115,22,0.28)' : '0 1px 3px rgba(249,115,22,0.12)',
                      position:'relative',overflow:'hidden',
                    }}>
                      <div style={{position:'absolute',inset:0,background:'linear-gradient(180deg,rgba(255,255,255,0.28) 0%,rgba(255,255,255,0) 55%)',borderRadius:'inherit',pointerEvents:'none'}}/>
                    </div>}
                  </div>
                  {/* Sale bar */}
                  <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'flex-end',height:'100%'}}>
                    {sPct > 0 && <div style={{
                      width:'100%',
                      height: mounted ? `${Math.max(sPct*100,1.5)}%` : '0%',
                      background:'linear-gradient(180deg,#60A5FA 0%,#1D4ED8 100%)',
                      borderRadius:'6px 6px 3px 3px',
                      transition:`height 0.6s cubic-bezier(0.22,1,0.36,1) ${delay}, transform 0.2s ease, box-shadow 0.2s ease`,
                      transform: lift,
                      boxShadow: isSel
                        ? '0 0 0 2px rgba(37,99,235,0.3),0 6px 18px rgba(37,99,235,0.3)'
                        : isHov ? '0 4px 14px rgba(37,99,235,0.22)' : '0 1px 3px rgba(37,99,235,0.1)',
                      position:'relative',overflow:'hidden',
                    }}>
                      <div style={{position:'absolute',inset:0,background:'linear-gradient(180deg,rgba(255,255,255,0.24) 0%,rgba(255,255,255,0) 55%)',borderRadius:'inherit',pointerEvents:'none'}}/>
                    </div>}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
      {/* X-axis labels */}
      <div style={{display:'flex',gap:5,padding:'5px 2px 0',marginTop:1}}>
        {data.map((d,i) => (
          <div key={d.id||i} style={{
            flex:1,textAlign:'center',
            fontSize:8.5,lineHeight:1.2,
            color:(hovered===i||selected===i)?'var(--txt)':'var(--txt3)',
            fontWeight:(hovered===i||selected===i)?600:400,
            overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',
            transition:'color .18s,font-weight .18s',
            cursor:'pointer',
          }}
          onClick={()=>handleClick(i,d)}
          onMouseEnter={e=>handleEnter(i,d,e)}
          onMouseLeave={handleLeave}
          >{d.name}</div>
        ))}
      </div>
      {/* Premium tooltip */}
      {tooltip && hovered !== null && (() => {
        const cW = containerRef.current ? containerRef.current.offsetWidth : 300;
        const tipW = 172;
        const tx = Math.min(Math.max(tooltip.x - tipW/2, 4), cW - tipW - 4);
        const ty = Math.max(tooltip.y - 110, 2);
        const td = tooltip.d;
        const contrib = totalQty > 0 ? (((td.purchased||0)+(td.sold||0))/totalQty*100).toFixed(1) : '0.0';
        return (
          <div style={{
            position:'absolute',left:tx,top:ty,
            background:'rgba(255,255,255,0.96)',
            backdropFilter:'blur(14px)',WebkitBackdropFilter:'blur(14px)',
            border:'1px solid rgba(0,0,0,0.075)',
            borderRadius:13,
            boxShadow:'0 2px 4px rgba(0,0,0,0.04),0 10px 28px rgba(0,0,0,0.11)',
            padding:'10px 13px',width:tipW,
            pointerEvents:'none',zIndex:60,
            animation:'omTipIn .14s ease',
          }}>
            <div style={{fontWeight:700,fontSize:12,color:'var(--txt)',marginBottom:8,
              paddingBottom:6,borderBottom:'1px solid rgba(0,0,0,0.055)',
              overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{td.name}</div>
            <div style={{display:'flex',flexDirection:'column',gap:5}}>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <span style={{display:'flex',alignItems:'center',gap:5,fontSize:10.5,color:'var(--txt2)'}}>
                  <span style={{width:7,height:7,borderRadius:2,background:'linear-gradient(135deg,#FB923C,#EA580C)',display:'inline-block',flexShrink:0}}/>
                  Purchase
                </span>
                <span style={{fontSize:11.5,fontWeight:600,color:'var(--txt)',fontVariantNumeric:'tabular-nums'}}>{window.formatQuantity((td.purchased||0))} T</span>
              </div>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <span style={{display:'flex',alignItems:'center',gap:5,fontSize:10.5,color:'var(--txt2)'}}>
                  <span style={{width:7,height:7,borderRadius:2,background:'linear-gradient(135deg,#60A5FA,#2563EB)',display:'inline-block',flexShrink:0}}/>
                  Sale
                </span>
                <span style={{fontSize:11.5,fontWeight:600,color:'var(--txt)',fontVariantNumeric:'tabular-nums'}}>{window.formatQuantity((td.sold||0))} T</span>
              </div>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',
                borderTop:'1px solid rgba(0,0,0,0.05)',paddingTop:5,marginTop:1}}>
                <span style={{fontSize:10,color:'var(--txt3)'}}>Contribution</span>
                <span style={{fontSize:11,fontWeight:700,color:'var(--or)'}}>{contrib}%</span>
              </div>
            </div>
          </div>
        );
      })()}
    </div>
  );
}

// ── Clickable KPI Card ────────────────────────────────────
function DKPICard({ label, value, sub, color, onClick }) {
  const accentColor = color || 'var(--or)';
  const iconName = window.KPI_ICON_MAP && window.KPI_ICON_MAP[label];
  const bgTint = window.getIconBg ? window.getIconBg(accentColor) : 'rgba(249,115,22,0.07)';
  return (
    <div className="kpi"
      onClick={onClick}
      style={{ cursor: onClick ? 'pointer' : 'default' }}
    >
      {window.LucideIcon && iconName && (
        <div className="kpi-ic-wrap" style={{ background: bgTint }}>
          <window.LucideIcon name={iconName} size={22} strokeWidth={2} color={accentColor} />
        </div>
      )}
      <div className="kpi-lbl">{label}</div>
      <div className="kpi-val" style={{ color: accentColor }}>{value}</div>
      {sub && <div className="kpi-sub">{sub}</div>}
    </div>
  );
}

// ── Mini Progress Bar ─────────────────────────────────────
function DashMiniBar({ value, max, color }) {
  const pct = max > 0 ? Math.min(100, Math.max(0, (value / max) * 100)) : 0;
  return (
    <window.PremiumProgress pct={pct} color={color||'var(--or)'} height={5} style={{marginTop:3}}/>
  );
}

// ── Material Analytics Modal ──────────────────────────────
function MaterialAnalyticsModal({ mat, purchases, sales, onClose }) {
  const C = window.fmtCur, fmt = n => Number(n||0).toFixed(3);
  const [tab, setTab] = dSt('overview');
  const matP = dMemo(() => purchases.filter(p => (p.items||[]).some(i => i.materialId === mat.id)), [purchases, mat.id]);
  const matS = dMemo(() => sales.filter(s => s.materialId === mat.id), [sales, mat.id]);
  const pQty  = matP.reduce((s,p) => s + (p.items||[]).filter(i=>i.materialId===mat.id).reduce((a,i)=>a+(parseFloat(i.quantity)||0),0), 0);
  const sQty  = matS.reduce((s,o) => s + (parseFloat(o.quantity)||0), 0);
  const rev   = matS.reduce((s,o) => s + (window.gAmt(o)), 0);
  const cost  = matP.reduce((s,p) => s + (p.items||[]).filter(i=>i.materialId===mat.id).reduce((a,i)=>a+(parseFloat(i.quantity)||0)*(parseFloat(i.ratePerTon)||0),0), 0);
  const profit = rev - cost;
  const ppt = sQty > 0 ? Math.round(profit / sQty) : 0;
  const byCust = dMemo(() => { const m={}; matS.forEach(s=>{ const k=Store.name('customers',s.customerId)||'Unknown'; if(!m[k])m[k]={name:k,qty:0,rev:0,orders:0}; m[k].qty+=parseFloat(s.quantity)||0; m[k].rev+=window.gAmt(s); m[k].orders++; }); return Object.values(m).sort((a,b)=>b.qty-a.qty); }, [matS]);
  const byVend = dMemo(() => { const m={}; matP.forEach(p=>{ const k=Store.name('vendors',p.vendorId)||'Unknown'; if(!m[k])m[k]={name:k,qty:0,orders:0}; (p.items||[]).filter(i=>i.materialId===mat.id).forEach(i=>{m[k].qty+=parseFloat(i.quantity)||0;m[k].orders++;}); }); return Object.values(m).sort((a,b)=>b.qty-a.qty); }, [matP]);
  const byVeh  = dMemo(() => { const m={}; [...matP,...matS].forEach(r=>{ const k=r.vehicleFull||''; if(!k) return; if(!m[k])m[k]={name:k,trips:0,qty:0}; m[k].trips++; m[k].qty += r.items ? (r.items||[]).filter(i=>i.materialId===mat.id).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0) : (parseFloat(r.quantity)||0); }); return Object.values(m).sort((a,b)=>b.trips-a.trips); }, [matP, matS]);
  const trend  = dMemo(() => { const m={}; matP.forEach(p=>{ const mo=(p.date||'').slice(0,7); if(!mo) return; if(!m[mo])m[mo]={month:mo,purchased:0,sold:0}; m[mo].purchased+=(p.items||[]).filter(i=>i.materialId===mat.id).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0); }); matS.forEach(s=>{ const mo=(s.date||'').slice(0,7); if(!mo) return; if(!m[mo])m[mo]={month:mo,purchased:0,sold:0}; m[mo].sold+=parseFloat(s.quantity)||0; }); return Object.values(m).sort((a,b)=>a.month.localeCompare(b.month)); }, [matP, matS]);
  const challans = dMemo(() => { const rows=[]; matP.forEach(p=>rows.push({date:p.date,type:'Purchase',challan:p.challanNumber||'—',vehicle:p.vehicleFull||'—',party:Store.name('vendors',p.vendorId)||'—',qty:(p.items||[]).filter(i=>i.materialId===mat.id).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0)})); matS.forEach(s=>rows.push({date:s.date,type:'Sale',challan:s.challanNumber||'—',vehicle:s.vehicleFull||'—',party:Store.name('customers',s.customerId)||'—',qty:parseFloat(s.quantity)||0})); return rows.sort((a,b)=>(b.date||'').localeCompare(a.date||'')); }, [matP, matS]);
  const TABS = ['overview','customers','vendors','vehicles','challans','trend'];
  return (
    <window.DashDrillModal title={`${mat.name}`} subtitle="Material Analytics — Purchase · Sale · Profit · Movement" color="var(--or)" onClose={onClose} width={920}>
      <window.DashKPIs items={[['Purchased',fmt(pQty)+' T','var(--or)'],['Sold',fmt(sQty)+' T','var(--info)'],['Balance',fmt(pQty-sQty)+' T',(pQty-sQty)>=0?'var(--ok)':'var(--err)'],['Revenue',C(rev),'var(--ok)'],['Gross Profit',C(profit),profit>=0?'var(--ok)':'var(--err)'],['₹/Ton',C(ppt),ppt>=0?'var(--ok)':'var(--err)']]}/>
      <div style={{display:'flex',gap:4,marginBottom:14,flexWrap:'wrap'}}>
        {TABS.map(t => <button key={t} className={`btn btn-sm ${tab===t?'btn-or':'btn-wh'}`} onClick={()=>setTab(t)} style={{textTransform:'capitalize'}}>{t}</button>)}
      </div>
      {tab === 'overview' && <div className="dd-2col"><window.DashBTable title="Top Customers" rows={byCust.slice(0,10)} cols={[{k:'name',h:'Customer'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'rev',h:'Revenue',r:true,cl:'var(--ok)',f:v=>C(v)},{k:'orders',h:'Orders',r:true}]}/><window.DashBTable title="Top Vendors" rows={byVend.slice(0,10)} cols={[{k:'name',h:'Vendor'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'orders',h:'Orders',r:true}]}/></div>}
      {tab === 'customers' && <window.DashBTable title={`All Customers — ${byCust.length}`} rows={byCust} cols={[{k:'name',h:'Customer'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'rev',h:'Revenue',r:true,cl:'var(--ok)',f:v=>C(v)},{k:'orders',h:'Orders',r:true}]} maxH={420}/>}
      {tab === 'vendors'   && <window.DashBTable title={`All Vendors — ${byVend.length}`} rows={byVend} cols={[{k:'name',h:'Vendor'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'orders',h:'Orders',r:true}]} maxH={420}/>}
      {tab === 'vehicles'  && <window.DashBTable title={`Vehicle Activity — ${byVeh.length}`} rows={byVeh} cols={[{k:'name',h:'Vehicle',mono:true},{k:'trips',h:'Trips',r:true,b:true,cl:'var(--info)'},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)}]} maxH={420}/>}
      {tab === 'challans'  && <window.DashBTable title={`Challan History — ${challans.length}`} rows={challans} cols={[{k:'date',h:'Date',f:v=>window.fmtDate(v)},{k:'type',h:'Type'},{k:'challan',h:'Challan No.',mono:true},{k:'vehicle',h:'Vehicle',mono:true},{k:'party',h:'Party'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)}]} maxH={420}/>}
      {tab === 'trend'     && <window.DashBTable title="Monthly Qty Movement" rows={trend} cols={[{k:'month',h:'Month'},{k:'purchased',h:'Purchased (T)',r:true,cl:'var(--or)',f:v=>v.toFixed(3)},{k:'sold',h:'Sold (T)',r:true,cl:'var(--info)',f:v=>v.toFixed(3)}]}/>}
    </window.DashDrillModal>
  );
}

// ── Balance Drill Modal ───────────────────────────────────
function BalanceDrillModal({ materials, purchases, sales, onClose }) {
  const fmt = n => Number(n||0).toFixed(3);
  const rows = dMemo(() => materials.map(m => {
    const pQty = purchases.reduce((s,p) => s+(p.items||[]).filter(i=>i.materialId===m.id).reduce((a,i)=>a+(parseFloat(i.quantity)||0),0), 0);
    const sQty = sales.filter(s=>s.materialId===m.id).reduce((s,o)=>s+(parseFloat(o.quantity)||0), 0);
    return { name: m.name, purchased: pQty, sold: sQty, balance: pQty-sQty };
  }).filter(r => r.purchased > 0 || r.sold > 0).sort((a,b) => b.balance - a.balance), [materials, purchases, sales]);
  return (
    <window.DashDrillModal title="Material Qty Balance" subtitle="Purchased vs sold — per material breakdown" color="var(--or)" onClose={onClose}>
      <window.DashKPIs items={[['Materials',rows.length,'var(--or)'],['Total Purchased',fmt(rows.reduce((s,r)=>s+r.purchased,0))+' T','var(--info)'],['Total Sold',fmt(rows.reduce((s,r)=>s+r.sold,0))+' T','var(--ok)'],['Net Balance',fmt(rows.reduce((s,r)=>s+r.balance,0))+' T','var(--txt)']]}/>
      <window.DashBTable title="Balance by Material" rows={rows} cols={[{k:'name',h:'Material'},{k:'purchased',h:'Purchased (T)',r:true,cl:'var(--or)',f:v=>v.toFixed(3)},{k:'sold',h:'Sold (T)',r:true,cl:'var(--info)',f:v=>v.toFixed(3)},{k:'balance',h:'Balance (T)',r:true,b:true,f:v=>v.toFixed(3)}]} maxH={360}/>
    </window.DashDrillModal>
  );
}

// ── Customer Intel Card ───────────────────────────────────
function CustomerIntelCard({ sales, onCustomerClick }) {
  const C = window.fmtCur;
  const rows = dMemo(() => { const m={}; sales.forEach(s=>{ const k=s.customerId; if(!k) return; if(!m[k])m[k]={id:k,name:Store.name('customers',k)||k,rev:0,qty:0,orders:0,lastDate:''}; m[k].rev+=window.gAmt(s); m[k].qty+=parseFloat(s.quantity)||0; m[k].orders++; if(!m[k].lastDate||(s.date||'')>m[k].lastDate)m[k].lastDate=s.date||''; }); return Object.values(m).sort((a,b)=>b.rev-a.rev); }, [sales]);
  const totalRev = rows.reduce((s,r)=>s+r.rev, 0);
  return (
    <div className="card" style={{padding:'10px 12px'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
        <div style={{fontWeight:700,fontSize:12,color:'#7C3AED'}}>Customer Intelligence</div>
        <span style={{fontSize:10.5,color:'var(--txt2)',cursor:'pointer',color:'#7C3AED'}} onClick={()=>onCustomerClick('all')}>All {rows.length} →</span>
      </div>
      {rows.length === 0
        ? <div style={{fontSize:11,color:'var(--txt3)',textAlign:'center',padding:'16px 0'}}>No sales data in period</div>
        : rows.slice(0,6).map(cu => {
          const pct = totalRev > 0 ? cu.rev/totalRev*100 : 0;
          return (
            <div key={cu.id} style={{marginBottom:7,cursor:'pointer',padding:'4px 6px',borderRadius:4}}
              onClick={() => onCustomerClick(cu)}
              onMouseEnter={e=>e.currentTarget.style.background='#F5F3FF'}
              onMouseLeave={e=>e.currentTarget.style.background=''}>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:11.5}}>
                <span style={{fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',maxWidth:160}}>{cu.name}</span>
                <span style={{color:'#7C3AED',fontWeight:600,fontSize:10.5}}>{pct.toFixed(1)}%</span>
              </div>
              <DashMiniBar value={cu.rev} max={totalRev} color="#7C3AED"/>
              <div style={{fontSize:10,color:'var(--txt2)',marginTop:2}}>{C(cu.rev)} · {window.formatQuantity(cu.qty)} T · {cu.orders} orders</div>
            </div>
          );
        })
      }
    </div>
  );
}

// ── Customer Full Drill Modal ─────────────────────────────
function CustomerFullModal({ customer, sales, onClose }) {
  const C = window.fmtCur;
  const cuSales = customer === 'all' ? sales : sales.filter(s => s.customerId === customer.id);
  const byMat = dMemo(() => { const m={}; cuSales.forEach(s=>{ const k=Store.name('materials',s.materialId)||'Unknown'; if(!m[k])m[k]={name:k,qty:0,rev:0,orders:0}; m[k].qty+=parseFloat(s.quantity)||0; m[k].rev+=window.gAmt(s); m[k].orders++; }); return Object.values(m).sort((a,b)=>b.rev-a.rev); }, [cuSales]);
  const rows = dMemo(() => [...cuSales].sort((a,b)=>(b.date||'').localeCompare(a.date||'')).map(s=>({date:s.date,customer:Store.name('customers',s.customerId)||'—',material:Store.name('materials',s.materialId)||'—',vehicle:s.vehicleFull||'—',transporter:s.transporter||'—',challan:s.challanNumber||'—',qty:parseFloat(s.quantity)||0,rate:s.ratePerTon||s.rate||0,total:window.gAmt(s)})), [cuSales]);
  const totalRev = cuSales.reduce((s,o)=>s+(window.gAmt(o)),0), totalQty = cuSales.reduce((s,o)=>s+(parseFloat(o.quantity)||0),0);
  return (
    <window.DashDrillModal title={customer==='all'?'All Customers':customer.name} subtitle="Transaction history · Materials · Vehicles · Revenue" color="#7C3AED" onClose={onClose} width={960}>
      <window.DashKPIs items={[['Revenue',C(totalRev),'#7C3AED'],['Total Qty',totalQty.toFixed(3)+' T','var(--ok)'],['Orders',cuSales.length,'var(--info)'],['Avg Order',cuSales.length>0?C(Math.round(totalRev/cuSales.length)):'—','var(--txt)']]}/>
      <window.DashBTable title="Materials Consumed" rows={byMat} cols={[{k:'name',h:'Material'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'rev',h:'Revenue',r:true,cl:'#7C3AED',f:v=>C(v)},{k:'orders',h:'Orders',r:true}]}/>
      <window.DashBTable title={`Transaction History — ${rows.length} records`} rows={rows.slice(0,200)} cols={[{k:'date',h:'Date',f:v=>window.fmtDate(v)},{k:'customer',h:'Customer'},{k:'material',h:'Material'},{k:'vehicle',h:'Vehicle',mono:true},{k:'transporter',h:'Transporter'},{k:'challan',h:'Challan',mono:true},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)},{k:'rate',h:'Rate/T',r:true,f:v=>C(v)},{k:'total',h:'Amount',r:true,b:true,cl:'#7C3AED',f:v=>C(v)}]} maxH={360}/>
    </window.DashDrillModal>
  );
}

// ── Vendor Intel Card ─────────────────────────────────────
function VendorIntelCard({ purchases, onVendorClick }) {
  const C = window.fmtCur;
  const rows = dMemo(() => { const m={}; purchases.forEach(p=>{ const k=p.vendorId; if(!k) return; if(!m[k])m[k]={id:k,name:Store.name('vendors',k)||k,cost:0,qty:0,orders:0}; m[k].cost+=window.gAmt(p); m[k].qty+=(p.items||[]).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0); m[k].orders++; }); return Object.values(m).sort((a,b)=>b.qty-a.qty); }, [purchases]);
  const totalQty = rows.reduce((s,r)=>s+r.qty, 0);
  return (
    <div className="card" style={{padding:'10px 12px'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
        <div style={{fontWeight:700,fontSize:12,color:'#B45309'}}>Vendor Intelligence</div>
        <span style={{fontSize:10.5,color:'#B45309',cursor:'pointer'}} onClick={()=>onVendorClick('all')}>All {rows.length} →</span>
      </div>
      {rows.length === 0
        ? <div style={{fontSize:11,color:'var(--txt3)',textAlign:'center',padding:'16px 0'}}>No purchase data in period</div>
        : rows.slice(0,6).map(v => {
          const pct = totalQty > 0 ? v.qty/totalQty*100 : 0;
          return (
            <div key={v.id} style={{marginBottom:7,cursor:'pointer',padding:'4px 6px',borderRadius:4}}
              onClick={() => onVendorClick(v)}
              onMouseEnter={e=>e.currentTarget.style.background='#FFFBEB'}
              onMouseLeave={e=>e.currentTarget.style.background=''}>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:11.5}}>
                <span style={{fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',maxWidth:160}}>{v.name}</span>
                <span style={{color:'#B45309',fontWeight:600,fontSize:10.5}}>{pct.toFixed(1)}%</span>
              </div>
              <DashMiniBar value={v.qty} max={totalQty} color="#B45309"/>
              <div style={{fontSize:10,color:'var(--txt2)',marginTop:2}}>{window.formatQuantity(v.qty)} T · {C(v.cost)} · {v.orders} orders</div>
            </div>
          );
        })
      }
    </div>
  );
}

// ── Vendor Full Drill Modal ───────────────────────────────
function VendorFullModal({ vendor, purchases, onClose }) {
  const C = window.fmtCur;
  const vP = vendor === 'all' ? purchases : purchases.filter(p => p.vendorId === vendor.id);
  const byMat = dMemo(() => { const m={}; vP.forEach(p=>(p.items||[]).forEach(i=>{ const k=Store.name('materials',i.materialId)||'Unknown'; if(!m[k])m[k]={name:k,qty:0,cost:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].cost+=(parseFloat(i.quantity)||0)*(parseFloat(i.ratePerTon)||0); })); return Object.values(m).sort((a,b)=>b.qty-a.qty); }, [vP]);
  const rows = dMemo(() => [...vP].sort((a,b)=>(b.date||'').localeCompare(a.date||'')).map(p=>({date:p.date,vendor:Store.name('vendors',p.vendorId)||'—',vehicle:p.vehicleFull||'—',challan:p.challanNumber||'—',qty:(p.items||[]).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0),total:window.gAmt(p)})), [vP]);
  const totalQty = rows.reduce((s,r)=>s+r.qty,0), totalCost = rows.reduce((s,r)=>s+r.total,0);
  return (
    <window.DashDrillModal title={vendor==='all'?'All Vendors':`${vendor.name}`} subtitle="Supply history · Materials · Quantities · Challans" color="#B45309" onClose={onClose} width={920}>
      <window.DashKPIs items={[['Total Cost',C(totalCost),'#B45309'],['Total Qty',totalQty.toFixed(3)+' T','var(--ok)'],['Purchases',vP.length,'var(--info)'],['Materials',byMat.length,'var(--or)']]}/>
      <window.DashBTable title="Materials Supplied" rows={byMat} cols={[{k:'name',h:'Material'},{k:'qty',h:'Qty (T)',r:true,b:true,f:v=>v.toFixed(3)},{k:'cost',h:'Est. Cost',r:true,cl:'#B45309',f:v=>C(v)}]}/>
      <window.DashBTable title={`Purchase History — ${rows.length} records`} rows={rows.slice(0,200)} cols={[{k:'date',h:'Date',f:v=>window.fmtDate(v)},{k:'vendor',h:'Vendor'},{k:'vehicle',h:'Vehicle',mono:true},{k:'challan',h:'Challan',mono:true},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)},{k:'total',h:'Amount',r:true,b:true,cl:'#B45309',f:v=>C(v)}]} maxH={360}/>
    </window.DashDrillModal>
  );
}

// ── Transport Intel Card ──────────────────────────────────
function TransportIntelCard({ purchases, sales, onVehicleClick, onTransporterClick }) {
  const { vehRows, transRows, totalTrips } = dMemo(() => {
    const vehs = {}, trans = {};
    const _rt = r => {
      const tId   = r.transporterId || r.transporterMasterId || null;
      const tDisp = (r.transporter    && r.transporter    !== '—') ? r.transporter
                  : (r.transporterName && r.transporterName !== '—') ? r.transporterName : null;
      const tKey  = tId || tDisp;
      if (!tKey) return null;
      return tDisp || (tId ? (Store.name('transportersList', tId)||tId) : tKey);
    };
    [...purchases, ...sales].forEach(r => {
      if (r.vehicleFull) { if(!vehs[r.vehicleFull])vehs[r.vehicleFull]={name:r.vehicleFull,trips:0,qty:0}; vehs[r.vehicleFull].trips++; vehs[r.vehicleFull].qty += r.items?(r.items||[]).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0):(parseFloat(r.quantity)||0); }
      const _tName2 = _rt(r);
      if (_tName2) { if(!trans[_tName2])trans[_tName2]={name:_tName2,trips:0,qty:0,vehs:new Set()}; trans[_tName2].trips++; trans[_tName2].qty += r.items?(r.items||[]).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0):(parseFloat(r.quantity)||0); if(r.vehicleFull)trans[_tName2].vehs.add(r.vehicleFull); }
    });
    return { vehRows: Object.values(vehs).sort((a,b)=>b.trips-a.trips), transRows: Object.values(trans).map(r=>({...r,vehs:r.vehs.size})).sort((a,b)=>b.trips-a.trips), totalTrips: purchases.length+sales.length };
  }, [purchases, sales]);
  return (
    <div className="card" style={{padding:'10px 12px'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
        <div style={{fontWeight:700,fontSize:12,color:'var(--info)'}}>Transport Intelligence</div>
        <span style={{fontSize:10.5,color:'var(--txt2)'}}>{totalTrips} total trips</span>
      </div>
      <div className="g-transport-mini" style={{gap:8,marginBottom:8}}>
        <div style={{background:'#EFF6FF',borderRadius:4,padding:'7px 10px',cursor:'pointer'}} onClick={()=>onVehicleClick('all')}>
          <div style={{fontSize:9.5,color:'var(--txt2)',fontWeight:600,textTransform:'uppercase',letterSpacing:'0.04em'}}>Active Vehicles</div>
          <div style={{fontWeight:700,fontSize:16,color:'var(--info)',lineHeight:1.2}}>{vehRows.length}</div>
          {vehRows[0]&&<div style={{fontSize:10,color:'var(--txt2)',marginTop:2,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>Top: {vehRows[0].name}</div>}
        </div>
        <div style={{background:'#F0F9FF',borderRadius:4,padding:'7px 10px',cursor:'pointer'}} onClick={()=>onTransporterClick('all')}>
          <div style={{fontSize:9.5,color:'var(--txt2)',fontWeight:600,textTransform:'uppercase',letterSpacing:'0.04em'}}>Transporters</div>
          <div style={{fontWeight:700,fontSize:16,color:'#0284C7',lineHeight:1.2}}>{transRows.length}</div>
          {transRows[0]&&<div style={{fontSize:10,color:'var(--txt2)',marginTop:2,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>Top: {transRows[0].name}</div>}
        </div>
      </div>
      <div style={{fontWeight:600,fontSize:11,color:'var(--txt2)',marginBottom:5}}>TOP VEHICLES</div>
      {vehRows.slice(0,5).map(v => (
        <div key={v.name} style={{display:'flex',alignItems:'center',justifyContent:'space-between',fontSize:11,marginBottom:4,cursor:'pointer',padding:'3px 5px',borderRadius:3}}
          onClick={() => onVehicleClick(v)}
          onMouseEnter={e=>e.currentTarget.style.background='#EFF6FF'}
          onMouseLeave={e=>e.currentTarget.style.background=''}>
          <span style={{fontFamily:'var(--font)',fontWeight:600,color:'var(--txt)'}}>{v.name}</span>
          <span style={{color:'var(--info)',fontWeight:600}}>{v.trips} trips · {window.formatQuantity(v.qty)} T</span>
        </div>
      ))}
      {vehRows.length === 0 && <div style={{fontSize:11,color:'var(--txt3)',textAlign:'center',padding:'8px 0'}}>No transport data in period</div>}
    </div>
  );
}

// ── Transport Full Drill Modal ────────────────────────────
function TransportFullModal({ mode, filter, purchases, sales, onClose }) {
  const C = window.fmtCur;
  const allRecs = dMemo(() => {
    const rows = [];
    const _resolveT = r => {
      if (r.transporter    && r.transporter    !== '—') return r.transporter;
      if (r.transporterName && r.transporterName !== '—') return r.transporterName;
      if (r.transporterId)      return Store.name('transportersList', r.transporterId)     || r.transporterId;
      if (r.transporterMasterId) return Store.name('transportersList', r.transporterMasterId) || r.transporterMasterId;
      return '—';
    };
    purchases.forEach(p => (p.items||[]).forEach(i => rows.push({date:p.date,type:'Purchase',vehicle:p.vehicleFull||'—',transporter:_resolveT(p),material:Store.name('materials',i.materialId)||'—',challan:p.challanNumber||'—',party:Store.name('vendors',p.vendorId)||'—',qty:parseFloat(i.quantity)||0})));
    sales.forEach(s => rows.push({date:s.date,type:'Sale',vehicle:s.vehicleFull||'—',transporter:_resolveT(s),material:Store.name('materials',s.materialId)||'—',challan:s.challanNumber||'—',party:Store.name('customers',s.customerId)||'—',qty:parseFloat(s.quantity)||0}));
    if (mode === 'vehicle' && filter !== 'all') return rows.filter(r => r.vehicle === filter.name);
    if (mode === 'transporter' && filter !== 'all') return rows.filter(r => r.transporter === filter.name);
    return rows;
  }, [purchases, sales, mode, filter]);
  const sorted = dMemo(() => [...allRecs].sort((a,b)=>(b.date||'').localeCompare(a.date||'')), [allRecs]);
  const vehSum = dMemo(() => { const m={}; allRecs.forEach(r=>{ if(r.vehicle==='—') return; if(!m[r.vehicle])m[r.vehicle]={name:r.vehicle,trips:0,qty:0}; m[r.vehicle].trips++; m[r.vehicle].qty+=r.qty; }); return Object.values(m).sort((a,b)=>b.trips-a.trips); }, [allRecs]);
  const totalQty = allRecs.reduce((s,r)=>s+r.qty,0);
  const title = mode==='vehicle'?(filter==='all'?'All Vehicles':`${filter.name}`):mode==='transporter'?(filter==='all'?'All Transporters':`${filter.name}`):'Transport Overview';
  return (
    <window.DashDrillModal title={title} subtitle="Trip history · Materials · Challans · Quantities" color="var(--info)" onClose={onClose} width={980}>
      <window.DashKPIs items={[['Total Trips',allRecs.length,'var(--info)'],['Total Qty',totalQty.toFixed(3)+' T','var(--ok)'],['Unique Vehicles',vehSum.length,'var(--or)'],['Avg Qty/Trip',allRecs.length>0?(totalQty/allRecs.length).toFixed(3)+' T':'—','var(--txt)']]}/>
      {(mode==='all'||(mode==='vehicle'&&filter==='all')) && <window.DashBTable title="Vehicle Summary" rows={vehSum.slice(0,15)} cols={[{k:'name',h:'Vehicle',mono:true},{k:'trips',h:'Trips',r:true,b:true,cl:'var(--info)'},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)}]} maxH={180}/>}
      <window.DashBTable title={`Trip Log — ${sorted.length} records`} rows={sorted.slice(0,200)} cols={[{k:'date',h:'Date',f:v=>window.fmtDate(v)},{k:'type',h:'Type'},{k:'vehicle',h:'Vehicle',mono:true},{k:'transporter',h:'Transporter'},{k:'material',h:'Material'},{k:'party',h:'Party'},{k:'challan',h:'Challan',mono:true},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)}]} maxH={380}/>
    </window.DashDrillModal>
  );
}

// ── Expandable Activity Row ───────────────────────────────
function ExpandableRow({ item, type, cols }) {
  const [open, setOpen] = dSt(false);
  return (
    <>
      <tr style={{cursor:'pointer',borderBottom:'1px solid var(--bdr)'}}
        onClick={() => setOpen(o => !o)}
        onMouseEnter={e=>e.currentTarget.style.background='#FAFAFA'}
        onMouseLeave={e=>e.currentTarget.style.background=''}>
        {cols.map((col, ci) => (
          <td key={ci} style={{padding:'5px 10px',verticalAlign:'middle',whiteSpace:'nowrap',borderRight:'1px solid #F3F4F6'}}>
            {col.render ? col.render(item) : (item[col.key]||'—')}
          </td>
        ))}
        <td style={{padding:'5px 10px',textAlign:'center',color:'var(--or)',fontWeight:700,fontSize:12,width:28}}>
          {open ? '▲' : '▼'}
        </td>
      </tr>
      {open && (
        <tr>
          <td colSpan={cols.length + 1} style={{padding:0}}>
            <window.DashActRowDrill item={item} type={type}/>
          </td>
        </tr>
      )}
    </>
  );
}

// ── Main Dashboard Page ───────────────────────────────────
function DashboardPage() {
  const { companyId, navigate } = dCtx(window.AppCtx);
  const [preset, setPreset] = dSt('month');
  const [cFrom,  setCFrom]  = dSt('');
  const [cTo,    setCTo]    = dSt('');
  const [tab,    setTab]    = dSt('purchase');
  const [drill,  setDrill]  = dSt(null);
  const [, setTick] = dSt(0);

  dEf(() => { const unsub = Store.on(() => setTick(t => t+1)); return unsub; }, []);

  const range        = dMemo(() => getRange(preset, cFrom, cTo), [preset, cFrom, cTo]);
  const allPurchases = Store.all('purchases', companyId);
  const allSales     = Store.all('salesOrders', companyId);
  const allMaterials = Store.all('materials', companyId);
  const purchases    = dMemo(() => allPurchases.filter(p => inRange(p.date, range.from, range.to)), [allPurchases, range]);
  const sales        = dMemo(() => allSales.filter(s => inRange(s.date, range.from, range.to)), [allSales, range]);
  const allTransport = Store.all('transportEntries', companyId);
  const allDiesel    = Store.all('dieselRecords', companyId);
  const allDebris    = Store.all('debrisMovements', companyId);
  const transport    = dMemo(() => allTransport.filter(t => inRange(t.date, range.from, range.to)), [allTransport, range]);
  const diesel       = dMemo(() => allDiesel.filter(d => inRange(d.date || d.periodStart, range.from, range.to)), [allDiesel, range]);
  // Debris Movement is a genuine commercial sale — Smart Revenue Engine (profit-engine.js)
  // folds it into every Revenue figure below via PE.revenue()/PE.method1()/PE.method2().
  const debris       = dMemo(() => allDebris.filter(d => inRange(d.date, range.from, range.to)), [allDebris, range]);

  // ── Data-health gate: a load failure on `purchases` must never be presented
  // as "0 purchases" — Store already quarantines/locks the collection instead
  // of deleting it (see erp/store.js), but every KPI below still read the
  // resulting empty array with no check. That silent conversion — read error
  // → [] → ₹0 — is the defect: this flag and the uv()/uvSub() helpers stop it
  // from reaching the screen.
  const purchLoadState      = (Store.loadState && Store.loadState('purchases')) || { state: 'OK' };
  const purchasesUnavailable = purchLoadState.state === 'ERROR' || purchLoadState.state === 'BLOCKED';
  // Phase 6 (REPORTS/27): purchases now hydrates in the background in
  // staging — distinct from ERROR/BLOCKED, this resolves itself within
  // moments via the existing Store.on() re-render, so it must not say
  // "UNAVAILABLE" (which implies Data Health recovery is needed).
  const purchasesLoading    = purchLoadState.state === 'LOADING';
  const uv    = (v) => purchasesUnavailable ? 'UNAVAILABLE' : purchasesLoading ? 'Loading…' : v;
  const uvSub = (s) => purchasesUnavailable ? 'Recovery required — see Data Health' : purchasesLoading ? 'Purchase data is still loading' : s;

  // ── Qty KPIs ─────────────────────────────────────────────
  const totalPQty = dMemo(() => purchases.reduce((s,p) => s+(p.items||[]).reduce((a,i)=>a+(parseFloat(i.quantity)||0),0), 0), [purchases]);
  const totalSQty = dMemo(() => sales.reduce((s,o) => s+(parseFloat(o.quantity)||0), 0), [sales]);
  const balance   = totalPQty - totalSQty;
  const variance  = totalPQty > 0 ? ((balance/totalPQty)*100).toFixed(2) : '0.00';

  // ── Financial KPIs ────────────────────────────────────────
  // Single Source of Truth: routed through window.ProfitEngine — the same
  // engine every other dashboard/report in the ERP reads. "Gross Profit"
  // (Revenue − Purchase Cost) is a simple sub-metric; "Net Profit" is the
  // one authoritative bottom-line figure (Method 1, GST-incl.) and matches
  // the Group Dashboard / Executive Dashboard exactly for this company.
  const PE          = window.ProfitEngine;
  const totalRev    = dMemo(() => PE.revenue({ sales, debris }, 'incl'), [sales, debris]);
  const totalCost   = dMemo(() => PE.purchAmt(purchases, 'incl'), [purchases]);
  const grossProfit = totalRev - totalCost;
  const margin      = totalRev > 0 ? (grossProfit/totalRev*100).toFixed(1) : '0.0';
  const peM1        = dMemo(() => PE.method1({ sales, purchases, transport, diesel, debris, gstMode: 'incl' }), [sales, purchases, transport, diesel, debris]);
  const netProfit   = peM1.netProfit;
  const ppt         = totalSQty > 0 ? Math.round(netProfit/totalSQty) : 0;

  // ── NEW: Material Turnover Rate ──────────────────────────────────────────
  const matTurnoverRate = totalPQty > 0 ? (totalSQty/totalPQty*100).toFixed(1) : '0.0';

  // ── Transporter resolver — handles both field-name conventions:
  //   purchases use: transporterMasterId (ID) + transporterName (display)
  //   sales / transport entries use: transporterId (ID) + transporter (display)
  // Returns { tKey, tName } — tKey is null if no transporter info found.
  function _resolveTransporter(r) {
    const tId   = r.transporterId || r.transporterMasterId || null;
    const tDisp = (r.transporter    && r.transporter    !== '—') ? r.transporter
                : (r.transporterName && r.transporterName !== '—') ? r.transporterName
                : null;
    const tKey  = tId || tDisp;
    if (!tKey) return { tKey: null, tName: null };
    const tName = tDisp || (tId ? (Store.name('transportersList', tId) || tId) : tKey);
    return { tKey, tName };
  }

  // ── Operational KPIs ──────────────────────────────────────
  const { totalTrips, activeVehicles, activeTransporters, topVehicle, topTransporter, avgTripSize, _dbgTrips } = dMemo(() => {
    const vehs = {}, trans = {};
    const dbg = [];
    [...purchases, ...sales].forEach(r => {
      const src  = r.items ? 'Purchase' : 'Sale';
      if (r.vehicleFull) vehs[r.vehicleFull] = (vehs[r.vehicleFull]||0)+1;
      const { tKey, tName } = _resolveTransporter(r);
      if (tKey && tName) trans[tName] = (trans[tName]||0)+1;
      dbg.push({
        id:   r.id||'?',
        co:   r.companyId||'?',
        src,
        veh:  r.vehicleFull||'—',
        tId:  r.transporterId||r.transporterMasterId||'—',
        tRaw: r.transporter||r.transporterName||'—',
        tResolved: tName||'—',
        countsTrip: true,
        countsVeh:  !!r.vehicleFull,
        countsTrans: !!(tKey && tName),
      });
    });
    const vA = Object.entries(vehs).sort((a,b)=>b[1]-a[1]);
    const tA = Object.entries(trans).sort((a,b)=>b[1]-a[1]);
    return {
      totalTrips: purchases.length + sales.length,
      activeVehicles: vA.length, activeTransporters: tA.length,
      topVehicle: vA[0]?.[0]||'—', topTransporter: tA[0]?.[0]||'—',
      avgTripSize: sales.length > 0 ? totalSQty/sales.length : 0,
      _dbgTrips: dbg,
    };
  }, [purchases, sales, totalSQty]);

  // ── Revenue per Trip (computed AFTER totalTrips is defined) ───────────
  const revPerTrip = totalTrips > 0 ? totalRev/totalTrips : 0;

  // ── Top Material ──────────────────────────────────────────
  const topMat = dMemo(() => {
    const m={}; sales.forEach(s=>{ if(s.materialId) m[s.materialId]=(m[s.materialId]||0)+(parseFloat(s.quantity)||0); });
    const top = Object.entries(m).sort((a,b)=>b[1]-a[1])[0];
    if (!top) return null;
    const mat = Store.byId('materials', top[0]);
    return { id:top[0], name:mat?.name||top[0], qty:top[1] };
  }, [sales]);

  // ── Top 5 Materials by Revenue ────────────────────────────
  const top5Mats = dMemo(() => {
    const m={}; sales.forEach(s=>{ if(!s.materialId) return; if(!m[s.materialId])m[s.materialId]={id:s.materialId,name:Store.name('materials',s.materialId)||s.materialId,qty:0,rev:0}; m[s.materialId].qty+=parseFloat(s.quantity)||0; m[s.materialId].rev+=window.gAmt(s); });
    return Object.values(m).sort((a,b)=>b.rev-a.rev).slice(0,5);
  }, [sales]);

  // ── Chart Data ────────────────────────────────────────────
  const matChartData = dMemo(() => allMaterials.map(m => {
    const pQ = purchases.reduce((s,p) => s+(p.items||[]).filter(i=>i.materialId===m.id).reduce((a,i)=>a+(parseFloat(i.quantity)||0),0), 0);
    const sQ = sales.filter(s=>s.materialId===m.id).reduce((s,o)=>s+(parseFloat(o.quantity)||0), 0);
    return { id:m.id, name:m.name, purchased:pQ, sold:sQ };
  }).filter(d => d.purchased>0 || d.sold>0), [allMaterials, purchases, sales]);

  // ── Recent Activity ───────────────────────────────────────
  const recentP = purchases.slice().sort((a,b)=>b.date.localeCompare(a.date)).slice(0,15);
  const recentS = sales.slice().sort((a,b)=>b.date.localeCompare(a.date)).slice(0,15);

  const C = window.fmtCur;
  const fmt = n => Number(n||0).toFixed(3);

  const openDrill = (type, data) => setDrill({ type, data });
  const closeDrill = () => setDrill(null);

  const PRESETS = [
    {id:'today',label:'Today'},{id:'yesterday',label:'Yesterday'},
    {id:'week',label:'This Week'},{id:'month',label:'This Month'},{id:'custom',label:'Custom'},
  ];

  const pCols = [
    {key:'sr',    render:(p,i)=><span style={{color:'var(--txt2)'}}>{i+1}</span>},
    {key:'ch',    render:p=><span style={{fontFamily:'var(--font)',fontSize:11.5}}>{p.challanNumber||'—'}</span>},
    {key:'veh',   render:p=><span style={{fontFamily:'var(--font)',fontSize:11.5,fontWeight:600}}>{p.vehicleFull||'—'}</span>},
    {key:'mat',   render:p=><span>{(p.items?.[0]?.materialId)?Store.name('materials',p.items[0].materialId):Store.name('materials',p.materialId)}</span>},
    {key:'vnd',   render:p=><span>{Store.name('vendors',p.vendorId)||'—'}</span>},
    {key:'dt',    render:p=><span style={{color:'var(--txt2)',whiteSpace:'nowrap'}}>{window.fmtDate(p.date)}</span>},
    {key:'qty',   render:p=><span style={{fontWeight:600}}>{fmt((p.items||[]).reduce((s,i)=>s+(parseFloat(i.quantity)||0),0))} MT</span>},
    {key:'amt',   render:p=><span style={{fontWeight:600,color:'var(--or)'}}>{C(window.gAmt(p))}</span>},
  ];
  const sCols = [
    {key:'sr',    render:(s,i)=><span style={{color:'var(--txt2)'}}>{i+1}</span>},
    {key:'ch',    render:s=><span style={{fontFamily:'var(--font)',fontSize:11.5}}>{s.challanNumber||'—'}</span>},
    {key:'veh',   render:s=><span style={{fontFamily:'var(--font)',fontSize:11.5,fontWeight:600}}>{s.vehicleFull||'—'}</span>},
    {key:'mat',   render:s=><span>{Store.name('materials',s.materialId)||'—'}</span>},
    {key:'cust',  render:s=><span>{Store.name('customers',s.customerId)||'—'}</span>},
    {key:'dt',    render:s=><span style={{color:'var(--txt2)',whiteSpace:'nowrap'}}>{window.fmtDate(s.date)}</span>},
    {key:'qty',   render:s=><span style={{fontWeight:600}}>{fmt(s.quantity)} {s.uom||'MT'}</span>},
    {key:'amt',   render:s=><span style={{fontWeight:600,color:'var(--ok)'}}>{C(window.gAmt(s))}</span>},
  ];

  return (
    <div>
      {/* Header */}
      <div className="ph">
        <div><h1>{Store.currentCompany?.name} Dashboard</h1><p>Operational Intelligence — {Store.currentCompany?.name}</p></div>
      </div>

      {/* Date Filter */}
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:12,flexWrap:'wrap',rowGap:6}}>
        <div className="dtf-row" style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap'}}>
          {PRESETS.map(p => (
            <button key={p.id} className={`btn ${preset===p.id?'btn-or':'btn-wh'} btn-sm`} onClick={()=>setPreset(p.id)}>{p.label}</button>
          ))}
          {preset==='custom' && <>
            <input className="inp" type="date" value={cFrom} onChange={e=>setCFrom(e.target.value)} style={{height:28,fontSize:11.5,width:130,padding:'3px 7px'}}/>
            <span style={{fontSize:11.5,color:'var(--txt2)'}}>to</span>
            <input className="inp" type="date" value={cTo} onChange={e=>setCTo(e.target.value)} style={{height:28,fontSize:11.5,width:130,padding:'3px 7px'}}/>
          </>}
        </div>
        {range.from && <span style={{fontSize:11,color:'var(--txt2)'}}>{window.fmtDate(range.from)}{range.from!==range.to?` — ${window.fmtDate(range.to)}`:''}</span>}
      </div>

      {purchasesUnavailable && (
        <div style={{background:'#FEF3C7',border:'1px solid #FDE68A',borderRadius:8,padding:'10px 14px',marginBottom:12,display:'flex',alignItems:'center',gap:10,fontSize:12.5,color:'#92400E'}}>
          <strong style={{whiteSpace:'nowrap'}}>Purchase data unavailable — recovery required.</strong>
          <span style={{flex:1}}>Storage could not load the purchases collection ({(purchLoadState.detail && purchLoadState.detail.reason) || 'write blocked by fail-safe'}). Nothing has been deleted — the records are locked against overwriting. Purchase Cost, Gross Profit, Net Profit and Purchased tonnage below exclude purchases and are not shown as ₹0/zero.</span>
          <button className="btn btn-sm" style={{background:'#92400E',color:'#fff',border:'none',whiteSpace:'nowrap'}} onClick={()=>navigate && navigate('datahealth')}>Open Data Health</button>
        </div>
      )}

      {/* ── Material Intelligence KPI Cards ── */}
      <div style={{fontSize:10.5,fontWeight:700,color:'var(--txt2)',textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:6}}>Material Intelligence</div>
      <div className="g-kpi-row-6" style={{display:'grid',gridTemplateColumns:'repeat(6,1fr)',gap:8,marginBottom:12}}>
        <DKPICard label="Material Qty Balance"   value={purchasesUnavailable?uv():fmt(balance)+' T'}        sub={uvSub('Purchased − Sold')}                         color={purchasesUnavailable?'#B45309':(balance>=0?'var(--ok)':'var(--err)')}   onClick={()=>openDrill('balance',null)}/>
        <DKPICard label="Material Purchased"     value={purchasesUnavailable?uv():fmt(totalPQty)}            sub={uvSub(`Tons · ${purchases.length} orders`)}     color={purchasesUnavailable?'#B45309':'var(--or)'}                             onClick={()=>openDrill('purchased',null)}/>
        <DKPICard label="Material Sold"          value={fmt(totalSQty)}            sub={`Tons · ${sales.length} orders`}         color="var(--info)"                           onClick={()=>openDrill('sold',null)}/>
        <DKPICard label="Qty Variance"           value={purchasesUnavailable?uv():variance+'%'}              sub={uvSub(`P: ${fmt(totalPQty)} · S: ${fmt(totalSQty)}`)} color={purchasesUnavailable?'#B45309':(balance>=0?'var(--ok)':'var(--err)')} onClick={()=>openDrill('balance',null)}/>
        <DKPICard label="Top Material"           value={topMat?.name||'—'}         sub={topMat?`${fmt(topMat.qty)} Tons sold`:'No data'} color="var(--or)"               onClick={()=>topMat&&openDrill('material',{matId:topMat.id})}/>
        <DKPICard label="Material Turnover Rate" value={matTurnoverRate+'%'}       sub={`Sold ${fmt(totalSQty)} / Purch ${fmt(totalPQty)} T`} color="var(--info)"       onClick={()=>openDrill('matTurnover',null)}/>
      </div>

      {/* ── Business Intelligence ── */}
      <div style={{marginBottom:10}}>
        <div style={{fontWeight:700,fontSize:12,color:'var(--txt2)',textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:7}}>Business Intelligence</div>
        {/* Financial KPIs */}
        <div className="g-kpi-row-6" style={{display:'grid',gridTemplateColumns:'repeat(6,1fr)',gap:8,marginBottom:8}}>
          <DKPICard label="Revenue"          value={C(totalRev)}              sub={sales.length+" sales orders"}   color="var(--ok)"                              onClick={()=>openDrill('sold',null)}/>
          <DKPICard label="Purchase Cost"    value={purchasesUnavailable?uv():C(totalCost)}             sub={uvSub(purchases.length+" purchases")}  color={purchasesUnavailable?'#B45309':'var(--or)'}                              onClick={()=>openDrill('purchased',null)}/>
          <DKPICard label="Gross Profit"     value={purchasesUnavailable?uv():C(grossProfit)}           sub={uvSub("Revenue − Cost")}                 color={purchasesUnavailable?'#B45309':(grossProfit>=0?'var(--ok)':'var(--err)')} onClick={()=>openDrill('profit',null)}/>
          <DKPICard label="Net Profit"       value={purchasesUnavailable?uv():C(netProfit)}             sub={uvSub("Profit Engine · Method 1 · GST Incl.")} color={purchasesUnavailable?'#B45309':(netProfit>=0?'var(--ok)':'var(--err)')} onClick={()=>openDrill('netProfit',null)}/>
          <DKPICard label="Profit Margin"    value={margin+'%'}               sub="Gross margin"                   color={parseFloat(margin)>=10?'var(--ok)':'var(--err)'} onClick={()=>openDrill('profit',null)}/>
          <DKPICard label="Profit / Ton"     value={C(ppt)}                   sub="Net profit per MT sold"         color={ppt>=0?'var(--ok)':'var(--err)'}        onClick={()=>openDrill('profitPerTon',null)}/>
          <DKPICard label="Revenue per Trip" value={C(Math.round(revPerTrip))} sub={`${totalTrips} trips considered`} color="var(--ok)"                           onClick={()=>openDrill('revPerTrip',null)}/>
        </div>
        {/* Operational KPIs */}
        <div className="g-kpi-row-6" style={{display:'grid',gridTemplateColumns:'repeat(6,1fr)',gap:8}}>
          <DKPICard label="Total Trips"     value={totalTrips}       sub="Purchases + sales"    color="var(--info)" onClick={()=>openDrill('transport',{mode:'all',filter:'all'})}/>
          <DKPICard label="Active Vehicles" value={activeVehicles}   sub="Unique vehicles"      color="var(--info)" onClick={()=>openDrill('transport',{mode:'vehicle',filter:'all'})}/>
          <DKPICard label="Transporters"    value={activeTransporters} sub="Active in period"   color="var(--info)" onClick={()=>openDrill('transport',{mode:'transporter',filter:'all'})}/>
          <DKPICard label="Avg Trip Size"   value={fmt(avgTripSize)+' T'} sub="Per sale trip"  color="var(--txt)"/>
          <DKPICard label="Top Vehicle"     value={topVehicle}       sub="Most active"          color="var(--info)" onClick={topVehicle!=='—'?()=>openDrill('transport',{mode:'vehicle',filter:{name:topVehicle}}):undefined}/>
          <DKPICard label="Top Transporter" value={topTransporter}   sub="Most trips"           color="var(--info)" onClick={topTransporter!=='—'?()=>openDrill('transport',{mode:'transporter',filter:{name:topTransporter}}):undefined}/>
        </div>

      </div>

      {/* ── Material Chart + Customer + Vendor Intel ── */}
      <div className="g-chart-intel" style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:8,marginBottom:10,alignItems:'start'}}>
        {/* Chart + Top Materials */}
        <div className="card" style={{padding:'10px 12px'}}>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
            <div style={{fontWeight:700,fontSize:12}}>Material Qty Comparison</div>
            <div style={{display:'flex',alignItems:'center',gap:6}}>
              <div style={{display:'flex',alignItems:'center',gap:5,padding:'3px 9px',borderRadius:20,
                background:'rgba(249,115,22,0.08)',border:'1px solid rgba(249,115,22,0.15)',
                fontSize:10,fontWeight:600,color:'#C2440C',letterSpacing:'-.01em'}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:'#F97316',display:'inline-block',flexShrink:0}}/>
                Purchase
              </div>
              <div style={{display:'flex',alignItems:'center',gap:5,padding:'3px 9px',borderRadius:20,
                background:'rgba(37,99,235,0.07)',border:'1px solid rgba(37,99,235,0.14)',
                fontSize:10,fontWeight:600,color:'#1D4ED8',letterSpacing:'-.01em'}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:'#3B82F6',display:'inline-block',flexShrink:0}}/>
                Sale
              </div>
            </div>
          </div>
          <GroupedBar data={matChartData} h={130} onBarClick={d=>openDrill('material',{matId:d.id})}/>
          <div style={{fontSize:10,color:'var(--txt3)',textAlign:'center',marginTop:3,marginBottom:10}}>Click any bar to drill into material analytics</div>
          <div style={{fontWeight:600,fontSize:10.5,color:'var(--txt2)',textTransform:'uppercase',letterSpacing:'0.05em',marginBottom:6}}>Top Materials by Revenue</div>
          {top5Mats.length === 0
            ? <div style={{fontSize:11,color:'var(--txt3)',textAlign:'center',padding:'8px 0'}}>No sales data</div>
            : top5Mats.map((m,i)=>(
            <div key={m.id} style={{display:'flex',alignItems:'center',gap:7,marginBottom:5,cursor:'pointer',padding:'3px 5px',borderRadius:3}}
              onClick={()=>openDrill('material',{matId:m.id})}
              onMouseEnter={e=>e.currentTarget.style.background='var(--or-lt)'}
              onMouseLeave={e=>e.currentTarget.style.background=''}>
              <span style={{width:16,height:16,background:'var(--or)',borderRadius:3,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontSize:9,fontWeight:700,flexShrink:0}}>{i+1}</span>
              <span style={{flex:1,fontSize:11.5,fontWeight:500,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{m.name}</span>
              <span style={{fontSize:11,color:'var(--ok)',fontWeight:600}}>{C(m.rev)}</span>
              <span style={{fontSize:10,color:'var(--txt2)'}}>{window.formatQuantity(m.qty)}T</span>
            </div>
          ))}
        </div>
        <CustomerIntelCard sales={sales} onCustomerClick={cu=>openDrill('customer',cu)}/>
        <VendorIntelCard purchases={purchases} onVendorClick={v=>openDrill('vendor',v)}/>
      </div>

      {/* ── Transport Intelligence ── */}
      <div style={{marginBottom:10}}>
        <TransportIntelCard purchases={purchases} sales={sales}
          onVehicleClick={v=>openDrill('transport',{mode:'vehicle',filter:v})}
          onTransporterClick={t=>openDrill('transport',{mode:'transporter',filter:t})}/>
      </div>

      {/* ── Executive Analytics ── */}
      {window.ExecutiveAnalyticsSection && (
        <window.ExecutiveAnalyticsSection
          purchases={purchases}
          sales={sales}
          allMaterials={allMaterials}
          companyId={companyId}
          range={range}
        />
      )}

      {/* ── Recent Activity ── */}
      <div className="card" style={{marginBottom:10}}>
        <div className="card-hd" style={{padding:'8px 12px'}}>
          <div style={{display:'flex',gap:0,border:'1px solid var(--bdr)',borderRadius:4,overflow:'hidden'}}>
            <button className={`btn btn-sm${tab==='purchase'?' btn-or':' btn-gh'}`} style={{borderRadius:0,border:'none',height:28}} onClick={()=>setTab('purchase')}>Purchase Activity</button>
            <button className={`btn btn-sm${tab==='sales'?' btn-or':' btn-gh'}`}    style={{borderRadius:0,border:'none',height:28}} onClick={()=>setTab('sales')}>Sales Activity</button>
          </div>
          <span className="act-entries-lbl" style={{fontSize:11,color:'var(--txt2)'}}>{tab==='purchase'?recentP.length:recentS.length} entries &nbsp;·&nbsp; <span style={{color:'var(--or)'}}>click row to expand</span></span>
        </div>
        <div className="tbl-w">
          {tab === 'purchase' ? (
            <table className="tbl" style={{tableLayout:'auto'}}>
              <thead><tr><th>SR</th><th>CHALLAN</th><th>VEHICLE</th><th>MATERIAL</th><th>VENDOR</th><th>DATE</th><th>QTY</th><th>AMOUNT</th><th style={{width:28}}></th></tr></thead>
              <tbody>
                {recentP.length === 0
                  ? <tr className="empty"><td colSpan="9">No purchase activity in selected period</td></tr>
                  : recentP.map((p,i) => <ExpandableRow key={p.id} item={p} type="Purchases" cols={pCols.map(c=>({...c,render:()=>c.render(p,i)}))}/>)}
              </tbody>
            </table>
          ) : (
            <table className="tbl" style={{tableLayout:'auto'}}>
              <thead><tr><th>SR</th><th>CHALLAN</th><th>VEHICLE</th><th>MATERIAL</th><th>CUSTOMER</th><th>DATE</th><th>QTY</th><th>AMOUNT</th><th style={{width:28}}></th></tr></thead>
              <tbody>
                {recentS.length === 0
                  ? <tr className="empty"><td colSpan="9">No sales activity in selected period</td></tr>
                  : recentS.map((s,i) => <ExpandableRow key={s.id} item={s} type="Sales" cols={sCols.map(c=>({...c,render:()=>c.render(s,i)}))}/>)}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* ── Drill-Down Modals ── */}
      {drill && <window.ErrorBoundary resetKey={JSON.stringify(drill)}>
      {drill?.type === 'balance' && <BalanceDrillModal materials={allMaterials} purchases={purchases} sales={sales} onClose={closeDrill}/>}
      {drill?.type === 'purchased' && (
        <window.DashDrillModal title="Material Purchased" subtitle="Purchase cost analysis — vendors · materials · quantities" color="var(--or)" onClose={closeDrill} width={880}>
          <window.DashCostDrill purchases={purchases}/>
        </window.DashDrillModal>
      )}
      {drill?.type === 'sold' && (
        <window.DashDrillModal title="Material Sold" subtitle="Sales revenue analysis — customers · materials · trends" color="var(--info)" onClose={closeDrill} width={880}>
          <window.DashRevenueDrill sales={sales} debris={debris}/>
        </window.DashDrillModal>
      )}
      {drill?.type === 'profit' && (
        <window.DashDrillModal title="Profitability Analysis" subtitle="Revenue vs Cost — material-wise profit breakdown" color="var(--ok)" onClose={closeDrill} width={880}>
          <window.DashProfitDrill leaderboard={[{name:Store.currentCompany?.name||'This Company',rev:totalRev,cost:totalCost,profit:grossProfit,margin:parseFloat(margin)}]} sales={sales} purchases={purchases}/>
        </window.DashDrillModal>
      )}
      {drill?.type === 'profitPerTon' && (
        <window.DashDrillModal title="Profit Per Ton" subtitle="₹ profitability ranking per metric tonne by material" color="var(--ok)" onClose={closeDrill} width={820}>
          <window.DashProfitPerTonDrill sales={sales} purchases={purchases}/>
        </window.DashDrillModal>
      )}
      {drill?.type === 'netProfit' && (
        <window.DashDrillModal title="Net Profit Waterfall — Profit Engine" subtitle="Method 1 (Commercial) · Method 2 (Operational) · GST toggle · Auto Compare" color={netProfit>=0?'var(--ok)':'var(--err)'} onClose={closeDrill} width={1080}>
          <window.DashNetProfitDrill sales={sales} purchases={purchases} transport={transport} diesel={diesel} debris={debris}/>
        </window.DashDrillModal>
      )}
      {drill?.type === 'material' && (() => {
        const mat = Store.byId('materials', drill.data.matId);
        return mat ? <MaterialAnalyticsModal mat={mat} purchases={purchases} sales={sales} onClose={closeDrill}/> : null;
      })()}
      {drill?.type === 'customer'  && <CustomerFullModal customer={drill.data} sales={sales} onClose={closeDrill}/>}
      {drill?.type === 'vendor'    && <VendorFullModal vendor={drill.data} purchases={purchases} onClose={closeDrill}/>}
      {drill?.type === 'transport' && <TransportFullModal mode={drill.data.mode} filter={drill.data.filter} purchases={purchases} sales={sales} onClose={closeDrill}/>}

      {drill?.type === 'matTurnover' && (()=>{
        const mtRows=allMaterials.map(m=>{
          const pQty=purchases.reduce((s,p)=>s+(p.items||[]).filter(i=>i.materialId===m.id).reduce((a,i)=>a+(parseFloat(i.quantity)||0),0),0);
          const sQty=sales.filter(s=>s.materialId===m.id).reduce((s,o)=>s+(parseFloat(o.quantity)||0),0);
          const rate=pQty>0?(sQty/pQty*100).toFixed(1):'0.0';
          return {name:m.name,purchased:pQty,sold:sQty,rate:parseFloat(rate),rateDisp:rate+'%',balance:pQty-sQty};
        }).filter(r=>r.purchased>0||r.sold>0).sort((a,b)=>b.rate-a.rate);
        const fast=mtRows.filter(r=>r.rate>=80);
        const slow=mtRows.filter(r=>r.rate<30);
        return (
          <window.DashDrillModal title={`Material Turnover Rate — ${matTurnoverRate}%`} subtitle="Sold ÷ Purchased — material-wise conversion efficiency" color="var(--info)" onClose={closeDrill} width={920}>
            <window.DashKPIs items={[['Turnover Rate',matTurnoverRate+'%','var(--info)'],['Purchased',fmt(totalPQty)+' T','var(--or)'],['Sold',fmt(totalSQty)+' T','var(--ok)'],['Balance',fmt(balance)+' T',balance>=0?'var(--ok)':'var(--err)'],['Fast-Moving',fast.length,'var(--ok)'],['Slow-Moving',slow.length,'var(--warn)']]}/>
            <div className="dd-2col" style={{marginBottom:14}}>
              <window.DashBTable title={`Fast-Moving Materials (≥80%) — ${fast.length}`} rows={fast} cols={[{k:'name',h:'Material'},{k:'rateDisp',h:'Turnover %',r:true,b:true,cl:'var(--ok)'},{k:'purchased',h:'Purchased (T)',r:true,f:v=>v.toFixed(3)},{k:'sold',h:'Sold (T)',r:true,f:v=>v.toFixed(3)}]}/>
              <window.DashBTable title={`Slow-Moving Materials (<30%) — ${slow.length}`} rows={[...slow].sort((a,b)=>a.rate-b.rate)} cols={[{k:'name',h:'Material'},{k:'rateDisp',h:'Turnover %',r:true,b:true,cl:'var(--warn)'},{k:'purchased',h:'Purchased (T)',r:true,f:v=>v.toFixed(3)},{k:'sold',h:'Sold (T)',r:true,f:v=>v.toFixed(3)}]}/>
            </div>
            <window.DashBTable title="All Materials — Turnover Ranking" rows={mtRows} cols={[{k:'name',h:'Material'},{k:'rateDisp',h:'Turnover %',r:true,b:true,cl:'var(--info)'},{k:'purchased',h:'Purchased (T)',r:true,f:v=>v.toFixed(3)},{k:'sold',h:'Sold (T)',r:true,f:v=>v.toFixed(3)},{k:'balance',h:'Balance (T)',r:true,f:v=>v.toFixed(3)}]} maxH={340}/>
          </window.DashDrillModal>
        );
      })()}

      {drill?.type === 'revPerTrip' && (()=>{
        const rptAllRecs=[];
        purchases.forEach(p=>(p.items||[]).forEach(i=>rptAllRecs.push({date:p.date,type:'Purchase',vehicle:p.vehicleFull||'—',transporter:p.transporter||'—',material:Store.name('materials',i.materialId)||'—',challan:p.challanNumber||'—',party:Store.name('vendors',p.vendorId)||'—',qty:parseFloat(i.quantity)||0,revenue:0})));
        sales.forEach(s=>rptAllRecs.push({date:s.date,type:'Sale',vehicle:s.vehicleFull||'—',transporter:s.transporter||'—',material:Store.name('materials',s.materialId)||'—',challan:s.challanNumber||'—',party:Store.name('customers',s.customerId)||'—',qty:parseFloat(s.quantity)||0,revenue:window.gAmt(s)}));
        const rptByVeh=(()=>{const m={};rptAllRecs.forEach(r=>{if(r.vehicle==='—')return;if(!m[r.vehicle])m[r.vehicle]={name:r.vehicle,trips:0,qty:0,revenue:0};m[r.vehicle].trips++;m[r.vehicle].qty+=r.qty;m[r.vehicle].revenue+=r.revenue;});return Object.values(m).sort((a,b)=>b.revenue-a.revenue).map(r=>({...r,revPerTrip:r.trips>0?Math.round(r.revenue/r.trips):0}));})();
        const rptByCust=(()=>{const m={};sales.forEach(s=>{const k=Store.name('customers',s.customerId)||'Unknown';if(!m[k])m[k]={name:k,trips:0,revenue:0};m[k].trips++;m[k].revenue+=window.gAmt(s);});return Object.values(m).sort((a,b)=>b.revenue-a.revenue).map(r=>({...r,revPerTrip:r.trips>0?Math.round(r.revenue/r.trips):0}));})();
        const rptByMat=(()=>{const m={};sales.forEach(s=>{const k=Store.name('materials',s.materialId)||'Unknown';if(!m[k])m[k]={name:k,trips:0,revenue:0,qty:0};m[k].trips++;m[k].revenue+=window.gAmt(s);m[k].qty+=parseFloat(s.quantity)||0;});return Object.values(m).sort((a,b)=>b.revenue-a.revenue).map(r=>({...r,revPerTrip:r.trips>0?Math.round(r.revenue/r.trips):0}));})();
        const rptSorted=[...rptAllRecs].sort((a,b)=>(b.date||'').localeCompare(a.date||''));
        return (
          <window.DashDrillModal title={`Revenue per Trip — ${C(Math.round(revPerTrip))}`} subtitle={`${totalTrips} trips · ${C(totalRev)} total revenue`} color="var(--ok)" onClose={closeDrill} width={980}>
            <window.DashKPIs items={[['Rev / Trip',C(Math.round(revPerTrip)),'var(--ok)'],['Total Revenue',C(totalRev),'var(--or)'],['Total Trips',totalTrips,'var(--info)'],['Avg Trip Size',fmt(avgTripSize)+' T','var(--txt)'],['Top Vehicle',rptByVeh[0]?.name||'—','var(--txt2)']]}/>
            <div className="dd-2col" style={{marginBottom:14}}>
              <window.DashBTable title="Vehicle-wise Revenue per Trip" rows={rptByVeh.slice(0,20)} cols={[{k:'name',h:'Vehicle',mono:true},{k:'trips',h:'Trips',r:true},{k:'revenue',h:'Revenue',r:true,cl:'var(--ok)',f:v=>C(v)},{k:'revPerTrip',h:'Rev/Trip',r:true,b:true,cl:'var(--ok)',f:v=>C(v)}]}/>
              <window.DashBTable title="Customer-wise Revenue per Trip" rows={rptByCust.slice(0,20)} cols={[{k:'name',h:'Customer'},{k:'trips',h:'Trips',r:true},{k:'revenue',h:'Revenue',r:true,cl:'var(--ok)',f:v=>C(v)},{k:'revPerTrip',h:'Rev/Trip',r:true,b:true,cl:'var(--ok)',f:v=>C(v)}]}/>
            </div>
            <window.DashBTable title="Material-wise Revenue per Trip" rows={rptByMat} cols={[{k:'name',h:'Material'},{k:'trips',h:'Trips',r:true},{k:'qty',h:'Qty (T)',r:true,f:v=>window.formatQuantity(v)},{k:'revenue',h:'Revenue',r:true,cl:'var(--ok)',f:v=>C(v)},{k:'revPerTrip',h:'Rev/Trip',r:true,b:true,cl:'var(--ok)',f:v=>C(v)}]} maxH={160}/>
            <window.DashBTable title={`Trip-wise Revenue Log — ${rptSorted.length} trips`} rows={rptSorted.slice(0,200)} cols={[{k:'date',h:'Date',f:v=>window.fmtDate(v)},{k:'type',h:'Type'},{k:'vehicle',h:'Vehicle',mono:true},{k:'transporter',h:'Transporter'},{k:'material',h:'Material'},{k:'party',h:'Party'},{k:'challan',h:'Challan',mono:true},{k:'qty',h:'Qty (T)',r:true,f:v=>v.toFixed(3)},{k:'revenue',h:'Revenue',r:true,b:true,cl:'var(--ok)',f:v=>C(v)}]} maxH={280}/>
          </window.DashDrillModal>
        );
      })()}
      </window.ErrorBoundary>}
    </div>
  );
}
window.DashboardPage = DashboardPage;
