// erp/transport-kpi.jsx — Transport Analytics KPI Dashboard
// v38 — Consolidated KPI analytics across Normal, Debris, Stockyard transport modules
// Additive only — no existing functionality modified

const { useState: kSt, useEffect: kEf, useMemo: kMemo } = React;

// ── One-time style injection ───────────────────────────────────────────────
;(function(){
  if (document.getElementById('tkpi-css')) return;
  const s = document.createElement('style');
  s.id = 'tkpi-css';
  s.textContent = `
.tkpi-section{margin-bottom:18px}
.tkpi-hd{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:12px;gap:10px;flex-wrap:wrap}
.tkpi-ht{font-size:12.5px;font-weight:700;color:var(--txt);letter-spacing:-.01em}
.tkpi-hs{font-size:11px;color:var(--txt3);margin-top:2px}
.tkpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
@media(max-width:1100px){.tkpi-grid{grid-template-columns:repeat(4,1fr)}}
@media(max-width:840px){.tkpi-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:500px){.tkpi-grid{grid-template-columns:1fr}}

.tkc{background:#fff;border:1px solid var(--bdr);border-radius:16px;padding:15px 15px 12px;
  cursor:pointer;transition:transform .18s cubic-bezier(.16,1,.3,1),box-shadow .18s,border-color .18s;
  position:relative;overflow:hidden;display:flex;flex-direction:column;gap:7px;
  user-select:none;-webkit-tap-highlight-color:transparent;
  box-shadow:0 1px 2px rgba(0,0,0,.04),0 2px 8px rgba(0,0,0,.03)}
.tkc::after{content:'';position:absolute;inset:0;border-radius:16px;
  background:radial-gradient(ellipse at 0% 0%,var(--tkc-lt,#FFF7ED),transparent 65%);
  opacity:0;transition:opacity .2s;pointer-events:none}
.tkc:hover{transform:translateY(-2px);
  box-shadow:0 4px 16px rgba(0,0,0,.07),0 12px 32px rgba(0,0,0,.05);
  border-color:var(--tkc-c,var(--bdr))}
.tkc:hover::after{opacity:1}
.tkc:active{transform:scale(.97)!important;box-shadow:0 1px 4px rgba(0,0,0,.04)!important;
  transition:transform .08s,box-shadow .08s!important}
.tkc-top{display:flex;align-items:flex-start;justify-content:space-between}
.tkc-ic{width:34px;height:34px;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.tkc-arr{opacity:.35;margin-top:2px;flex-shrink:0;color:var(--tkc-c,var(--or));transition:opacity .18s}
.tkc:hover .tkc-arr{opacity:.7}
.tkc-lbl{font-size:9.5px;font-weight:700;color:var(--txt3);text-transform:uppercase;letter-spacing:.05em;line-height:1.3}
.tkc-val{font-size:18px;font-weight:800;color:var(--txt);letter-spacing:-.025em;line-height:1.2;
  font-variant-numeric:tabular-nums;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tkc-sub{font-size:10px;color:var(--txt3);line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tkc-hint{font-size:9px;font-weight:600;letter-spacing:.03em;margin-top:auto;padding-top:4px;
  display:flex;align-items:center;gap:3px;color:var(--tkc-c,var(--or));opacity:.6}

.tkpi-seg-bar{height:7px;border-radius:99px;overflow:hidden;display:flex;gap:1.5px;margin:3px 0 3px}
.tkpi-seg-item{height:100%;border-radius:99px;transition:flex .5s cubic-bezier(.16,1,.3,1);min-width:3px}
.tkpi-seg-leg{display:flex;gap:7px;flex-wrap:wrap}
.tkpi-seg-leg-i{display:flex;align-items:center;gap:3px;font-size:9px;color:var(--txt2);font-weight:500}
.tkpi-seg-dot{width:6px;height:6px;border-radius:50%;flex-shrink:0}

.tkpi-ov{position:fixed;inset:0;z-index:1100;display:flex;align-items:center;justify-content:center;padding:16px}
.tkpi-ov::before{content:'';position:absolute;inset:0;z-index:-1;
  background:rgba(17,17,20,.5);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);pointer-events:none}
@keyframes tkpiPop{from{opacity:0;transform:scale(.95) translateY(10px)}to{opacity:1;transform:none}}
.tkpi-popup{background:#fff;border-radius:20px;
  box-shadow:0 8px 32px rgba(0,0,0,.12),0 32px 80px rgba(0,0,0,.18);
  width:100%;max-width:780px;max-height:90vh;display:flex;flex-direction:column;
  animation:tkpiPop .28s cubic-bezier(.16,1,.3,1)}
.tkpi-ph{padding:20px 24px 16px;border-bottom:1px solid var(--bdr);display:flex;
  align-items:flex-start;justify-content:space-between;background:#FAFAF8;
  border-radius:20px 20px 0 0;flex-shrink:0}
.tkpi-pb{overflow-y:auto;flex:1;padding:20px 24px;
  scrollbar-width:thin;scrollbar-color:#D4D0CB transparent}
.tkpi-pb::-webkit-scrollbar{width:4px}
.tkpi-pb::-webkit-scrollbar-thumb{background:#D4D0CB;border-radius:4px}
.tkpi-pf{padding:12px 24px;border-top:1px solid var(--bdr);display:flex;align-items:center;
  justify-content:space-between;gap:8px;flex-shrink:0;background:#FAFAF8;border-radius:0 0 20px 20px}
.tkpi-grand{background:linear-gradient(135deg,#FFF7ED,#FEF3E8);border:1.5px solid var(--or-bdr);
  border-radius:12px;padding:14px 18px;display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
.tkpi-grandlbl{font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--or2)}
.tkpi-grandval{font-size:21px;font-weight:800;color:var(--or);letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.tkpi-modgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:14px}
@media(max-width:540px){.tkpi-modgrid{grid-template-columns:1fr}}
.tkpi-modcard{border-radius:12px;padding:13px 15px;border:1.5px solid}
.tkpi-modlbl{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px}
.tkpi-modval{font-size:16px;font-weight:800;letter-spacing:-.02em;font-variant-numeric:tabular-nums}
.tkpi-modsub{font-size:10px;margin-top:3px;opacity:.75}
.tkpi-pct{display:inline-flex;align-items:center;padding:1px 7px;border-radius:99px;font-size:9px;font-weight:700;margin-top:5px}
.tkpi-expbtn{display:flex;align-items:center;justify-content:space-between;width:100%;
  padding:9px 14px;background:#FAFAF8;border:1px solid var(--bdr);border-radius:10px;
  cursor:pointer;font-family:var(--font);font-size:12px;font-weight:600;color:var(--txt);
  transition:background .12s;margin-bottom:2px;text-align:left}
.tkpi-expbtn:hover{background:#F0EFEC}
.tkpi-expcont{border:1px solid var(--bdr);border-top:none;border-radius:0 0 10px 10px;padding:14px;margin-bottom:8px}
.tkpi-kv{display:flex;justify-content:space-between;padding:4px 0;border-bottom:1px solid #F2F0ED;font-size:11.5px}
.tkpi-kv:last-child{border-bottom:none}
.tkpi-kvk{color:var(--txt2)}
.tkpi-kvv{font-weight:600;color:var(--txt);text-align:right;font-variant-numeric:tabular-nums;margin-left:8px}
.tkpi-mtbl{width:100%;border-collapse:collapse;font-size:11px;margin-top:8px}
.tkpi-mtbl th{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--txt3);
  padding:4px 8px;text-align:left;border-bottom:1.5px solid var(--bdr);white-space:nowrap;background:#FAFAF8}
.tkpi-mtbl td{padding:5px 8px;border-bottom:1px solid #F2F0ED;color:var(--txt);
  font-variant-numeric:tabular-nums;white-space:nowrap;max-width:140px;overflow:hidden;text-overflow:ellipsis}
.tkpi-mtbl tr:last-child td{border-bottom:none}
.tkpi-mtbl tr:hover td{background:#FAFAF8}
.tkpi-empty{text-align:center;padding:28px 16px;background:#FAFAF8;border-radius:14px;border:1px dashed var(--bdr)}
.tkpi-sec-ttl{font-size:9.5px;font-weight:700;color:var(--txt3);text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px}
.tkpi-verify{margin-top:12px;padding:12px 16px;background:#F8F8F6;border-radius:12px;border:1px solid var(--bdr)}
`;
  document.head.appendChild(s);
})();

// ── Analytics helpers ──────────────────────────────────────────────────────
function tkpiTotals(entries) {
  let amtNo = 0, gst = 0, qty = 0;
  const ts = new Set(), vs = new Set();
  const today = new Date().toISOString().slice(0, 10);
  let autoToday = 0, manualToday = 0;
  for (const e of entries) {
    const b = parseFloat(e.amount) || 0, g = parseFloat(e.gstPercent) || 0;
    amtNo += b; gst += b * g / 100; qty += parseFloat(e.quantity) || 0;
    if (e.transporter) ts.add(e.transporter);
    if (e.vehicleFull) vs.add(e.vehicleFull);
    const isA = e._autoGenerated || e.source === 'Auto Generated';
    if (e.date === today) { isA ? autoToday++ : manualToday++; }
  }
  return { trips: entries.length, amtNoGST: amtNo, gstAmt: gst, amtWithGST: amtNo + gst, qty, transporters: ts.size, vehicles: vs.size, autoToday, manualToday };
}

function tkpiApplyFilters(entries, f, { crusherId, customerId } = {}) {
  if (!f) return entries;
  return entries.filter(e => {
    if (f.dateFrom && e.date < f.dateFrom) return false;
    if (f.dateTo   && e.date > f.dateTo)   return false;
    if (f.status   && f.status !== ''   && e.status   !== f.status)   return false;
    if (f.source   && f.source !== ''   && e.source   !== f.source)   return false;
    if (f.materialId && f.materialId !== '' && e.materialId !== f.materialId) return false;
    if (f.transporterId && f.transporterId !== '') {
      const tn = (Store.name('transportersList', f.transporterId) || '').toLowerCase();
      const ok = e.transporterId === f.transporterId ||
        (e.transporterId === '' && tn && (e.transporter || '').toLowerCase().includes(tn));
      if (!ok) return false;
    }
    if (crusherId && f.crusherId  && f.crusherId  !== '' && e.crusherId  !== f.crusherId)  return false;
    if (customerId && f.customerId && f.customerId !== '' && e.customerId !== f.customerId) return false;
    return true;
  });
}

function tkpiTop(entries, n) {
  return [...entries].sort((a, b) => {
    const av = (parseFloat(a.amount)||0) * (1 + (parseFloat(a.gstPercent)||0) / 100);
    const bv = (parseFloat(b.amount)||0) * (1 + (parseFloat(b.gstPercent)||0) / 100);
    return bv - av;
  }).slice(0, n || 10);
}

function FC(v) { return window.fmtCur ? window.fmtCur(v) : '₹' + Math.round(v).toLocaleString('en-IN'); }
function FD(d) { return window.fmtDate ? window.fmtDate(d) : (d || '—'); }
const isAuto = e => e._autoGenerated || e.source === 'Auto Generated';

// ── Segmented distribution bar ─────────────────────────────────────────────
function TKSegBar({ n, d, s }) {
  const total = n + d + s;
  if (!total) return <div className="tkpi-seg-bar"><div className="tkpi-seg-item" style={{flex:1,background:'#E5E4E2'}}/></div>;
  return (
    <div>
      <div className="tkpi-seg-bar">
        {n > 0 && <div className="tkpi-seg-item" style={{flex:n, background:'#F97316'}}/>}
        {d > 0 && <div className="tkpi-seg-item" style={{flex:d, background:'#8B5CF6'}}/>}
        {s > 0 && <div className="tkpi-seg-item" style={{flex:s, background:'#0EA5E9'}}/>}
      </div>
      <div className="tkpi-seg-leg">
        {n > 0 && <span className="tkpi-seg-leg-i"><span className="tkpi-seg-dot" style={{background:'#F97316'}}/>{(n/total*100).toFixed(0)}% Normal</span>}
        {d > 0 && <span className="tkpi-seg-leg-i"><span className="tkpi-seg-dot" style={{background:'#8B5CF6'}}/>{(d/total*100).toFixed(0)}% Debris</span>}
        {s > 0 && <span className="tkpi-seg-leg-i"><span className="tkpi-seg-dot" style={{background:'#0EA5E9'}}/>{(s/total*100).toFixed(0)}% Stockyard</span>}
      </div>
    </div>
  );
}

// ── KPI card ──────────────────────────────────────────────────────────────
function TKCard({ title, value, subtitle, icon, color, lt, onClick, children }) {
  return (
    <div className="tkc" style={{'--tkc-c': color, '--tkc-lt': lt}} onClick={onClick}>
      <div className="tkc-top">
        <div className="tkc-ic" style={{background: lt, color}}>{icon}</div>
        <svg className="tkc-arr" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
      </div>
      <div className="tkc-lbl">{title}</div>
      {value != null && <div className="tkc-val">{value}</div>}
      {children}
      {subtitle && <div className="tkc-sub">{subtitle}</div>}
      <div className="tkc-hint">
        <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
        Click for details
      </div>
    </div>
  );
}

// ── KV row ────────────────────────────────────────────────────────────────
function TKKV({ k, v, bold, color }) {
  return (
    <div className="tkpi-kv">
      <span className="tkpi-kvk">{k}</span>
      <span className="tkpi-kvv" style={bold ? {color: color || 'var(--or)'} : color ? {color} : {}}>{v}</span>
    </div>
  );
}

// ── Module expandable section (inside popup) ───────────────────────────────
function TKModSection({ label, raw, totals, color, lt, bdr, expanded, onToggle }) {
  const top  = tkpiTop(raw, 10);
  const dates = raw.map(e => e.date || '').filter(Boolean).sort();
  const uniqT = [...new Set(raw.map(e => e.transporter || '').filter(Boolean))];
  const uniqV = [...new Set(raw.map(e => e.vehicleFull  || '').filter(Boolean))];
  const autoC = raw.filter(isAuto).length;
  return (
    <div>
      <button className="tkpi-expbtn" onClick={onToggle}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <span style={{width:8,height:8,borderRadius:'50%',background:color,flexShrink:0,display:'inline-block'}}/>
          <span>{label}</span>
          <span style={{fontSize:10.5,color:'var(--txt3)',fontWeight:400}}>· {totals.trips} trips · {FC(totals.amtWithGST)}</span>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
          style={{transform:expanded?'rotate(180deg)':'none',transition:'transform .18s',flexShrink:0}}>
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </button>
      {expanded && (
        <div className="tkpi-expcont">
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:12}}>
            <div>
              <TKKV k="Trips" v={totals.trips.toLocaleString()}/>
              <TKKV k="Amount (Ex. GST)" v={FC(totals.amtNoGST)}/>
              <TKKV k="GST Amount" v={FC(totals.gstAmt)}/>
              <TKKV k="Amount (Inc. GST)" v={FC(totals.amtWithGST)} bold/>
              <TKKV k="Avg per Trip" v={totals.trips > 0 ? FC(totals.amtWithGST / totals.trips) : '—'}/>
            </div>
            <div>
              <TKKV k="Transporters" v={uniqT.length}/>
              <TKKV k="Vehicles" v={uniqV.length}/>
              <TKKV k="Auto Generated" v={autoC} color="#15803D"/>
              <TKKV k="Manual Entry" v={totals.trips - autoC}/>
              {dates.length > 0 && <TKKV k="Date Range" v={`${FD(dates[0])} — ${FD(dates[dates.length-1])}`}/>}
            </div>
          </div>
          {top.length > 0 && (
            <>
              <div style={{fontSize:9.5,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em',marginBottom:5}}>
                Top {top.length} Costliest Trips
              </div>
              <table className="tkpi-mtbl">
                <thead><tr><th>Date</th><th>Transporter</th><th>Vehicle</th><th>Challan</th><th style={{textAlign:'right'}}>Inc. GST</th></tr></thead>
                <tbody>
                  {top.map((e, i) => {
                    const b = parseFloat(e.amount)||0, g = b*(parseFloat(e.gstPercent)||0)/100;
                    return (
                      <tr key={e.id || i}>
                        <td>{FD(e.date)}</td>
                        <td>{e.transporter||'—'}</td>
                        <td style={{fontSize:10}}><span style={{background:'#F9FAFB',padding:'1px 4px',borderRadius:3}}>{e.vehicleFull||'—'}</span></td>
                        <td style={{fontSize:10,color:'var(--txt2)'}}>{e.challanNumber||'—'}</td>
                        <td style={{textAlign:'right',fontWeight:700,color}}>{FC(b+g)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </>
          )}
        </div>
      )}
    </div>
  );
}

// ── Module badge ───────────────────────────────────────────────────────────
function ModBadge({ mod }) {
  const cfg = {
    Debris:    {bg:'#EDE9FE',color:'#6D28D9'},
    Stockyard: {bg:'#E0F2FE',color:'#0369A1'},
    Normal:    {bg:'#FFF7ED',color:'#C2410C'},
  };
  const c = cfg[mod] || cfg.Normal;
  return <span style={{fontSize:9,padding:'1px 5px',borderRadius:3,fontWeight:700,background:c.bg,color:c.color}}>{mod}</span>;
}

// ── Drill-down popup ───────────────────────────────────────────────────────
function TKPopup({ type, C, N, D, S, NR, DR, SR, extra, filt, onClose }) {
  const [exp, setExp] = kSt({normal:false,debris:false,stockyard:false});
  const toggle = k => setExp(p => ({...p,[k]:!p[k]}));

  const MODS = [
    {key:'normal',   label:'Normal Transport',     totals:N, raw:NR, color:'#F97316', lt:'#FFF7ED', bdr:'#FED7AA', text:'#C2410C'},
    {key:'debris',   label:'Debris Movement',      totals:D, raw:DR, color:'#8B5CF6', lt:'#F5F3FF', bdr:'#DDD6FE', text:'#6D28D9'},
    {key:'stockyard',label:'Stockyard Movement',   totals:S, raw:SR, color:'#0EA5E9', lt:'#F0F9FF', bdr:'#BAE6FD', text:'#0369A1'},
  ];

  const TYPE_CFG = {
    amtInc:      { title:'Transport Amount (Including GST)',      sub:'Total consolidated transport spend including GST',
                   grandLbl:'Grand Total (Inc. GST)',  grandVal:FC(C.amtWithGST),
                   modVal:t=>FC(t.amtWithGST), modSub:t=>`${t.trips} trips · GST: ${FC(t.gstAmt)}` },
    amtEx:       { title:'Transport Amount (Excluding GST)',       sub:'Base transport expense before GST',
                   grandLbl:'Grand Total (Ex. GST)',   grandVal:FC(C.amtNoGST),
                   modVal:t=>FC(t.amtNoGST),   modSub:t=>`${t.trips} trips` },
    trips:       { title:'Total Transport Trips',                  sub:'All operational movements across Normal, Debris, and Stockyard',
                   grandLbl:'Total Trips',             grandVal:C.trips.toLocaleString(),
                   modVal:t=>t.trips.toLocaleString(), modSub:t=>FC(t.amtWithGST), noVerify:true },
    avgCost:     { title:'Average Cost per Trip',                  sub:'Total transport cost (Inc. GST) ÷ total trips',
                   grandLbl:'Average per Trip',        grandVal:C.trips>0?FC(C.amtWithGST/C.trips):'—',
                   modVal:t=>t.trips>0?FC(t.amtWithGST/t.trips):'—', modSub:t=>`${t.trips} trips`, noVerify:true },
    highModule:  { title:'Highest Cost Module',                    sub:'Module contributing the most to consolidated transport spend',
                   grandLbl:'Highest Module',          grandVal:extra.highestModule?.name||'—' },
    distribution:{ title:'Transport Cost Distribution',            sub:'Cost breakdown across all transport modules',
                   grandLbl:'Total Transport Cost',    grandVal:FC(C.amtWithGST) },
    autoGen:     { title:'Auto Generated Records — Today',         sub:`Records auto-generated today (${new Date().toLocaleDateString('en-IN',{day:'numeric',month:'short',year:'numeric'})})`,
                   grandLbl:'Total Auto Generated Today', grandVal:((extra.autoToday?.normal||0)+(extra.autoToday?.debris||0)+(extra.autoToday?.stockyard||0)).toString() },
    settlements: { title:'Pending Settlements',                    sub:'Transport trips across all modules not yet settled',
                   grandLbl:'Unsettled Trips',         grandVal:(extra.pendingCount||0).toLocaleString() },
  };
  const T = TYPE_CFG[type] || TYPE_CFG.amtInc;

  function exportCSV() {
    const all = [
      ...NR.map(e=>({...e,_mod:'Normal'})),
      ...DR.map(e=>({...e,_mod:'Debris'})),
      ...SR.map(e=>({...e,_mod:'Stockyard'})),
    ].sort((a,b)=>(b.date||'').localeCompare(a.date||''));
    const hdr = ['Module','Date','Company','Transporter','Vehicle','Challan','Amount (Ex. GST)','GST %','GST Amt','Amount (Inc. GST)','Status','Gen. Type'];
    const rows = all.map(e => {
      const b=parseFloat(e.amount)||0, gp=parseFloat(e.gstPercent)||0, ga=b*gp/100;
      return [e._mod, e.date||'', Store.name('companies',e.companyId)||'', e.transporter||'', e.vehicleFull||'',
        e.challanNumber||'', b.toFixed(2), gp, ga.toFixed(2), (b+ga).toFixed(2), e.status||'', e.source||'']
        .map(v=>'"'+String(v).replace(/"/g,'""')+'"');
    });
    const csv = '\uFEFF'+[hdr.map(h=>'"'+h+'"').join(','),...rows.map(r=>r.join(','))].join('\r\n');
    const blob = new Blob([csv],{type:'text/csv;charset=utf-8'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `transport_consolidated_${new Date().toISOString().slice(0,10)}.csv`;
    document.body.appendChild(a); a.click();
    setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1500);
    window.toast && window.toast('Exported consolidated CSV','ok');
  }

  // ── Type-specific body content ──────────────────────────────────────────
  function renderExtra() {
    if (type === 'highModule') {
      const ranked = [...MODS].sort((a,b)=>b.totals.amtWithGST-a.totals.amtWithGST);
      return (
        <div style={{marginBottom:14}}>
          {ranked.map((m,i)=>(
            <div key={m.key} style={{background:m.lt,border:`1.5px solid ${m.bdr}`,borderRadius:12,padding:'12px 16px',marginBottom:8,display:'flex',alignItems:'center',justifyContent:'space-between'}}>
              <div style={{display:'flex',alignItems:'center',gap:10}}>
                <div style={{width:26,height:26,borderRadius:7,background:m.color,color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:12,flexShrink:0}}>{i+1}</div>
                <div>
                  <div style={{fontSize:12.5,fontWeight:700,color:'var(--txt)'}}>{m.label}</div>
                  <div style={{fontSize:10.5,color:'var(--txt3)',marginTop:1}}>{m.totals.trips} trips</div>
                </div>
              </div>
              <div style={{textAlign:'right'}}>
                <div style={{fontSize:15,fontWeight:800,color:m.color}}>{FC(m.totals.amtWithGST)}</div>
                <div style={{fontSize:10,color:'var(--txt3)',marginTop:1}}>{C.amtWithGST>0?(m.totals.amtWithGST/C.amtWithGST*100).toFixed(1):0}% of total</div>
              </div>
            </div>
          ))}
        </div>
      );
    }

    if (type === 'distribution') {
      return (
        <div style={{marginBottom:14}}>
          <div style={{marginBottom:10}}>
            <TKSegBar n={N.amtWithGST} d={D.amtWithGST} s={S.amtWithGST}/>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:10}}>
            {MODS.map(m=>(
              <div key={m.key} style={{background:m.lt,border:`1.5px solid ${m.bdr}`,borderRadius:12,padding:'12px 14px'}}>
                <div style={{fontSize:9,fontWeight:700,textTransform:'uppercase',letterSpacing:'.05em',color:m.color,marginBottom:4}}>{m.label}</div>
                <div style={{fontSize:16,fontWeight:800,color:m.color}}>{FC(m.totals.amtWithGST)}</div>
                <div style={{fontSize:10,color:m.text,marginTop:3,opacity:.8}}>
                  {C.amtWithGST>0?(m.totals.amtWithGST/C.amtWithGST*100).toFixed(1):0}% · {m.totals.trips} trips
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (type === 'avgCost') {
      return (
        <div style={{background:'#F5F3FF',border:'1.5px solid #DDD6FE',borderRadius:12,padding:'14px 18px',marginBottom:14}}>
          <div style={{fontSize:9.5,fontWeight:700,textTransform:'uppercase',letterSpacing:'.06em',color:'#7C3AED',marginBottom:8}}>Calculation</div>
          <div style={{display:'flex',alignItems:'center',gap:10,flexWrap:'wrap',marginBottom:10}}>
            <span style={{fontSize:13,fontWeight:600,color:'var(--txt)'}}>{FC(C.amtWithGST)}</span>
            <span style={{fontSize:18,color:'var(--txt3)',fontWeight:300}}>÷</span>
            <span style={{fontSize:13,fontWeight:600,color:'var(--txt)'}}>{C.trips} trips</span>
            <span style={{fontSize:18,color:'var(--txt3)',fontWeight:300}}>=</span>
            <span style={{fontSize:15,fontWeight:800,color:'#7C3AED'}}>{C.trips>0?FC(C.amtWithGST/C.trips):'—'}</span>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}}>
            {MODS.map(m=>(
              <div key={m.key} style={{background:'#fff',borderRadius:8,padding:'8px 10px',textAlign:'center',border:`1px solid ${m.bdr}`}}>
                <div style={{fontSize:9,fontWeight:700,color:m.color,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:3}}>
                  {m.label.split(' ')[0]}
                </div>
                <div style={{fontSize:14,fontWeight:800,color:m.color}}>{m.totals.trips>0?FC(m.totals.amtWithGST/m.totals.trips):'—'}</div>
                <div style={{fontSize:9,color:'var(--txt3)',marginTop:2}}>{m.totals.trips} trips</div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (type === 'autoGen') {
      const allRaw = [...NR.map(e=>({...e,_mod:'Normal'})),...DR.map(e=>({...e,_mod:'Debris'})),...SR.map(e=>({...e,_mod:'Stockyard'}))];
      const recent = allRaw.filter(isAuto).sort((a,b)=>(b._creationTimestamp||'').localeCompare(a._creationTimestamp||'')).slice(0,15);
      const at = extra.autoToday || {};
      return (
        <div style={{marginBottom:14}}>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:10,marginBottom:12}}>
            {[{label:'Normal (Today)',v:at.normal||0,color:'#F97316',lt:'#FFF7ED',bdr:'#FED7AA'},
              {label:'Debris (Today)', v:at.debris||0, color:'#8B5CF6',lt:'#F5F3FF',bdr:'#DDD6FE'},
              {label:'Stockyard (Today)',v:at.stockyard||0,color:'#0EA5E9',lt:'#F0F9FF',bdr:'#BAE6FD'}].map(m=>(
              <div key={m.label} style={{background:m.lt,border:`1.5px solid ${m.bdr}`,borderRadius:12,padding:'12px 14px',textAlign:'center'}}>
                <div style={{fontSize:9,fontWeight:700,textTransform:'uppercase',letterSpacing:'.05em',color:m.color,marginBottom:5}}>{m.label}</div>
                <div style={{fontSize:22,fontWeight:800,color:m.color}}>{m.v}</div>
              </div>
            ))}
          </div>
          {recent.length > 0 && (
            <>
              <div className="tkpi-sec-ttl">Recent Auto-Generated Records</div>
              <table className="tkpi-mtbl">
                <thead><tr><th>Date</th><th>Module</th><th>Transporter</th><th>Vehicle</th></tr></thead>
                <tbody>
                  {recent.map((e,i)=>(
                    <tr key={e.id||i}>
                      <td>{FD(e.date)}</td>
                      <td><ModBadge mod={e._mod}/></td>
                      <td>{e.transporter||'—'}</td>
                      <td style={{fontSize:10}}>{e.vehicleFull||'—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}
        </div>
      );
    }

    if (type === 'settlements') {
      const ids = new Set((extra.settlements||[]).map(s=>s.transportEntryId));
      const allRaw = [...NR.map(e=>({...e,_mod:'Normal'})),...DR.map(e=>({...e,_mod:'Debris'})),...SR.map(e=>({...e,_mod:'Stockyard'}))];
      const unsettled = allRaw.filter(e=>!ids.has(e.id)&&!e._settled);
      const settled   = allRaw.filter(e=>ids.has(e.id)||e._settled);
      const uAmt = unsettled.reduce((s,e)=>{const b=parseFloat(e.amount)||0;return s+b+b*(parseFloat(e.gstPercent)||0)/100;},0);
      return (
        <div style={{marginBottom:14}}>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:12}}>
            <div style={{background:'#FEF2F2',border:'1.5px solid #FCA5A5',borderRadius:12,padding:'12px 16px'}}>
              <div style={{fontSize:9,fontWeight:700,textTransform:'uppercase',letterSpacing:'.05em',color:'#DC2626',marginBottom:4}}>Unsettled Trips</div>
              <div style={{fontSize:21,fontWeight:800,color:'#DC2626'}}>{unsettled.length}</div>
              <div style={{fontSize:10.5,color:'#EF4444',marginTop:2}}>{FC(uAmt)}</div>
            </div>
            <div style={{background:'#F0FDF4',border:'1.5px solid #86EFAC',borderRadius:12,padding:'12px 16px'}}>
              <div style={{fontSize:9,fontWeight:700,textTransform:'uppercase',letterSpacing:'.05em',color:'#16A34A',marginBottom:4}}>Settled Trips</div>
              <div style={{fontSize:21,fontWeight:800,color:'#16A34A'}}>{settled.length}</div>
              <div style={{fontSize:10.5,color:'#22C55E',marginTop:2}}>{allRaw.length>0?(settled.length/allRaw.length*100).toFixed(0):0}% complete</div>
            </div>
          </div>
          {unsettled.length > 0 && (
            <>
              <div className="tkpi-sec-ttl">Unsettled Trips (up to 15)</div>
              <table className="tkpi-mtbl">
                <thead><tr><th>Date</th><th>Module</th><th>Transporter</th><th>Vehicle</th><th style={{textAlign:'right'}}>Inc. GST</th></tr></thead>
                <tbody>
                  {unsettled.slice(0,15).map((e,i)=>{
                    const b=parseFloat(e.amount)||0,g=b*(parseFloat(e.gstPercent)||0)/100;
                    return (
                      <tr key={e.id||i}>
                        <td>{FD(e.date)}</td>
                        <td><ModBadge mod={e._mod}/></td>
                        <td>{e.transporter||'—'}</td>
                        <td style={{fontSize:10}}>{e.vehicleFull||'—'}</td>
                        <td style={{textAlign:'right',fontWeight:700,color:'#DC2626'}}>{FC(b+g)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </>
          )}
        </div>
      );
    }

    return null;
  }

  const showModCards   = !!T.modVal;
  const showDrillDown  = type === 'amtInc' || type === 'amtEx' || type === 'trips';
  const showVerify     = type === 'amtInc' || type === 'amtEx';

  return ReactDOM.createPortal(
    <div className="tkpi-ov" onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div className="tkpi-popup">
        {/* Header */}
        <div className="tkpi-ph">
          <div style={{minWidth:0}}>
            <h2 style={{fontSize:14,fontWeight:800,color:'var(--txt)',letterSpacing:'-.02em',margin:0}}>{T.title}</h2>
            <p style={{fontSize:11.5,color:'var(--txt3)',margin:'4px 0 0'}}>{T.sub}</p>
          </div>
          <button className="mod-x" onClick={onClose} style={{flexShrink:0,marginLeft:16}}/>
        </div>

        {/* Body */}
        <div className="tkpi-pb">
          {/* Grand total bar */}
          <div className="tkpi-grand">
            <div>
              <div className="tkpi-grandlbl">{T.grandLbl}</div>
              <div className="tkpi-grandval">{T.grandVal}</div>
              {filt && (filt.dateFrom || filt.dateTo) && (
                <div style={{fontSize:10,color:'var(--or)',opacity:.7,marginTop:2}}>
                  {filt.dateFrom&&filt.dateTo?`${FD(filt.dateFrom)} — ${FD(filt.dateTo)}`:filt.dateFrom?`From ${FD(filt.dateFrom)}`:`To ${FD(filt.dateTo)}`}
                </div>
              )}
            </div>
            <div style={{textAlign:'right',flexShrink:0}}>
              <div style={{fontSize:9.5,color:'var(--or2)',fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em'}}>Total Trips</div>
              <div style={{fontSize:19,fontWeight:800,color:'var(--or)',letterSpacing:'-.02em'}}>{C.trips}</div>
              <div style={{fontSize:9.5,color:'var(--txt3)',marginTop:1}}>across 3 modules</div>
            </div>
          </div>

          {/* Module summary cards */}
          {showModCards && (
            <div className="tkpi-modgrid">
              {MODS.map(m=>(
                <div key={m.key} className="tkpi-modcard" style={{background:m.lt,borderColor:m.bdr}}>
                  <div className="tkpi-modlbl" style={{color:m.color}}>{m.label}</div>
                  <div className="tkpi-modval" style={{color:m.color}}>{T.modVal(m.totals)}</div>
                  <div className="tkpi-modsub" style={{color:m.text}}>{T.modSub(m.totals)}</div>
                  {type!=='trips' && (
                    <span className="tkpi-pct" style={{background:`${m.color}22`,color:m.text}}>
                      {C.amtWithGST>0?(m.totals.amtWithGST/C.amtWithGST*100).toFixed(1):0}%
                    </span>
                  )}
                </div>
              ))}
            </div>
          )}

          {/* Type-specific content */}
          {renderExtra()}

          {/* Expandable module drill-downs */}
          {showDrillDown && (
            <div>
              <div className="tkpi-sec-ttl">Detailed Module Breakdown</div>
              {MODS.map(m=>(
                <TKModSection key={m.key} label={m.label} raw={m.raw} totals={m.totals}
                  color={m.color} lt={m.lt} bdr={m.bdr}
                  expanded={exp[m.key]} onToggle={()=>toggle(m.key)}/>
              ))}
            </div>
          )}

          {/* Reconciliation / Verification */}
          {showVerify && (
            <div className="tkpi-verify">
              <div className="tkpi-sec-ttl" style={{marginBottom:6}}>Reconciliation</div>
              {type==='amtInc' ? (
                <>
                  <TKKV k="Normal Transport (Inc. GST)" v={FC(N.amtWithGST)}/>
                  <TKKV k="Debris Movement (Inc. GST)"  v={FC(D.amtWithGST)}/>
                  <TKKV k="Stockyard Movement (Inc. GST)" v={FC(S.amtWithGST)}/>
                  <div style={{borderTop:'2px solid var(--bdr)',marginTop:7,paddingTop:7,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                    <span style={{fontSize:12,fontWeight:700}}>Grand Total (Inc. GST)</span>
                    <span style={{fontSize:14,fontWeight:800,color:'var(--or)'}}>{FC(C.amtWithGST)}</span>
                  </div>
                </>
              ) : (
                <>
                  <TKKV k="Normal Transport (Ex. GST)"    v={FC(N.amtNoGST)}/>
                  <TKKV k="Debris Movement (Ex. GST)"     v={FC(D.amtNoGST)}/>
                  <TKKV k="Stockyard Movement (Ex. GST)"  v={FC(S.amtNoGST)}/>
                  <div style={{borderTop:'2px solid var(--bdr)',marginTop:7,paddingTop:7,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                    <span style={{fontSize:12,fontWeight:700}}>Grand Total (Ex. GST)</span>
                    <span style={{fontSize:14,fontWeight:800,color:'var(--info)'}}>{FC(C.amtNoGST)}</span>
                  </div>
                </>
              )}
              <div style={{textAlign:'right',fontSize:10,color:'var(--ok)',marginTop:5,fontWeight:600}}>
                ✓ Reconciles with KPI card value
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="tkpi-pf">
          <div style={{fontSize:11,color:'var(--txt3)'}}>
            {C.trips} trips · {FC(C.amtWithGST)} total (Inc. GST)
          </div>
          <div style={{display:'flex',gap:8}}>
            <button className="btn btn-wh btn-sm" onClick={exportCSV}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              Export CSV
            </button>
            <button className="btn btn-wh btn-sm btn-close" onClick={onClose}>Close</button>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ── Main KPI Dashboard ─────────────────────────────────────────────────────
function TransportKPIDashboard({ companyId, filters }) {
  const [allEntries,  setAllEntries]  = kSt([]);
  const [settlements, setSettlements] = kSt([]);
  const [popup,       setPopup]       = kSt(null);

  kEf(() => {
    function load() {
      setAllEntries(Store.all('transportEntries', companyId) || []);
      setSettlements(Store.all('settlementRecords') || []);
    }
    load();
    return Store.on(load);
  }, [companyId]);

  const { NR, DR, SR, N, D, S, C } = kMemo(() => {
    const f = filters || {};
    // Split by module
    const nr = allEntries.filter(e => e.sourceModule !== 'STOCKYARD' && e.sourceModule !== 'DEBRIS');
    const dr = allEntries.filter(e => e.sourceModule === 'DEBRIS');
    const sr = allEntries.filter(e => e.sourceModule === 'STOCKYARD');
    // Apply filters: crusherId/customerId only relevant to normal module
    const nrF = tkpiApplyFilters(nr, f, {crusherId:true, customerId:true});
    const drF = tkpiApplyFilters(dr, f);
    const srF = tkpiApplyFilters(sr, f);
    const n = tkpiTotals(nrF), d = tkpiTotals(drF), s = tkpiTotals(srF);
    return {
      NR:nrF, DR:drF, SR:srF, N:n, D:d, S:s,
      C:{ trips:n.trips+d.trips+s.trips, amtNoGST:n.amtNoGST+d.amtNoGST+s.amtNoGST,
          gstAmt:n.gstAmt+d.gstAmt+s.gstAmt, amtWithGST:n.amtWithGST+d.amtWithGST+s.amtWithGST }
    };
  }, [allEntries, filters]);

  const today = new Date().toISOString().slice(0,10);
  const autoToday = kMemo(()=>({
    normal:    NR.filter(e=>e.date===today&&isAuto(e)).length,
    debris:    DR.filter(e=>e.date===today&&isAuto(e)).length,
    stockyard: SR.filter(e=>e.date===today&&isAuto(e)).length,
  }), [NR, DR, SR, today]);

  const pendingData = kMemo(()=>{
    if (!settlements.length) return null; // hide card when no settlement records exist
    const ids = new Set(settlements.map(s=>s.transportEntryId));
    return [...NR,...DR,...SR].filter(e=>!ids.has(e.id)&&!e._settled).length;
  }, [NR, DR, SR, settlements]);

  const highestModule = kMemo(()=>[
    {name:'Normal Transport',   amt:N.amtWithGST},
    {name:'Debris Movement',    amt:D.amtWithGST},
    {name:'Stockyard Movement', amt:S.amtWithGST},
  ].sort((a,b)=>b.amt-a.amt)[0], [N,D,S]);

  const avgCost = C.trips > 0 ? C.amtWithGST / C.trips : 0;

  const ICONS = {
    rupee: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>,
    card:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>,
    truck: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="3" width="15" height="13" rx="1"/><path d="M16 8h4l3 3v3h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
    avg:   <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>,
    top:   <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>,
    pie:   <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.21 15.89A10 10 0 118 2.83"/><path d="M22 12A10 10 0 0012 2v10z"/></svg>,
    sync:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>,
    clock: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  };

  const hasData = C.trips > 0;

  const popupExtra = { highestModule, avgCost, autoToday, pendingCount: pendingData, settlements };

  return (
    <div className="tkpi-section">
      {/* Section header */}
      <div className="tkpi-hd">
        <div>
          <div className="tkpi-ht">Transport Analytics Overview</div>
          <div className="tkpi-hs">
            Consolidated · Normal Transport · Debris Movement · Stockyard Movement
            {hasData && ` — ${C.trips} trips · ${FC(C.amtWithGST)}`}
          </div>
        </div>
        {filters && (filters.dateFrom || filters.dateTo) && (
          <div style={{display:'flex',alignItems:'center',gap:5,fontSize:11,color:'var(--txt3)',flexShrink:0}}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
            {filters.dateFrom&&filters.dateTo?`${FD(filters.dateFrom)} — ${FD(filters.dateTo)}`:filters.dateFrom?`From ${FD(filters.dateFrom)}`:`To ${FD(filters.dateTo)}`}
          </div>
        )}
      </div>

      {!hasData ? (
        <div className="tkpi-empty">
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{margin:'0 auto 10px',display:'block',opacity:.3}}>
            <rect x="1" y="3" width="15" height="13" rx="1"/><path d="M16 8h4l3 3v3h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/>
          </svg>
          <div style={{fontWeight:600,fontSize:13,color:'var(--txt2)',marginBottom:4}}>No transport activity found for the selected filters</div>
          <div style={{fontSize:11.5,color:'var(--txt3)'}}>Adjust filters or add transport records to see analytics</div>
        </div>
      ) : (
        <div className="tkpi-grid">
          {/* 1 · Amount Inc. GST */}
          <TKCard title="Transport Amount (Inc. GST)" value={FC(C.amtWithGST)}
            subtitle={`${C.trips} trips · GST: ${FC(C.gstAmt)}`}
            icon={ICONS.rupee} color="#F97316" lt="#FFF7ED"
            onClick={()=>setPopup('amtInc')}/>

          {/* 2 · Amount Ex. GST */}
          <TKCard title="Transport Amount (Ex. GST)" value={FC(C.amtNoGST)}
            subtitle="Base transport expense before GST"
            icon={ICONS.card} color="#2563EB" lt="#EFF6FF"
            onClick={()=>setPopup('amtEx')}/>

          {/* 3 · Total Trips */}
          <TKCard title="Total Transport Trips" value={C.trips.toLocaleString()}
            subtitle={`N: ${N.trips} · Debris: ${D.trips} · SY: ${S.trips}`}
            icon={ICONS.truck} color="#16A34A" lt="#F0FDF4"
            onClick={()=>setPopup('trips')}/>

          {/* 4 · Avg Cost / Trip */}
          <TKCard title="Average Cost per Trip" value={avgCost > 0 ? FC(avgCost) : '—'}
            subtitle="Total cost ÷ total trips"
            icon={ICONS.avg} color="#7C3AED" lt="#F5F3FF"
            onClick={()=>setPopup('avgCost')}/>

          {/* 5 · Highest Module */}
          <TKCard title="Highest Cost Module"
            value={highestModule.amt > 0 ? highestModule.name : '—'}
            subtitle={highestModule.amt > 0
              ? `${FC(highestModule.amt)} · ${C.amtWithGST>0?(highestModule.amt/C.amtWithGST*100).toFixed(1):0}%`
              : 'No transport data'}
            icon={ICONS.top} color="#D97706" lt="#FFFBEB"
            onClick={()=>setPopup('highModule')}/>

          {/* 6 · Cost Distribution */}
          <TKCard title="Cost Distribution"
            icon={ICONS.pie} color="#0EA5E9" lt="#F0F9FF"
            onClick={()=>setPopup('distribution')}>
            <TKSegBar n={N.amtWithGST} d={D.amtWithGST} s={S.amtWithGST}/>
          </TKCard>

          {/* 7 · Auto Generated Today */}
          <TKCard title="Auto Generated Today"
            value={(autoToday.normal+autoToday.debris+autoToday.stockyard).toString()}
            subtitle={`Normal: ${autoToday.normal} · Debris: ${autoToday.debris} · SY: ${autoToday.stockyard}`}
            icon={ICONS.sync} color="#15803D" lt="#F0FDF4"
            onClick={()=>setPopup('autoGen')}/>

          {/* 8 · Pending Settlements — only shown when settlement records exist */}
          {pendingData !== null && (
            <TKCard title="Pending Settlements"
              value={pendingData > 0 ? pendingData.toLocaleString() : 'All Settled'}
              subtitle={pendingData > 0 ? 'Trips awaiting settlement' : 'No pending settlements'}
              icon={ICONS.clock}
              color={pendingData > 0 ? '#DC2626' : '#16A34A'}
              lt={pendingData > 0 ? '#FEF2F2' : '#F0FDF4'}
              onClick={()=>setPopup('settlements')}/>
          )}
        </div>
      )}

      {/* Drill-down popup */}
      {popup && (
        <TKPopup type={popup}
          C={C} N={N} D={D} S={S} NR={NR} DR={DR} SR={SR}
          extra={popupExtra} filt={filters}
          onClose={()=>setPopup(null)}/>
      )}
    </div>
  );
}

window.TransportKPIDashboard = TransportKPIDashboard;
