// Transport Module — Transporter Reports + Stockyard Movements + Debris Movements
const { useState: tSt, useEffect: tEf, useContext: tCtx, useMemo: tMemo } = React;
const AppCtx = window.AppCtx;

const SH = ({title,action}) => (
  <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>
    <span style={{color:'var(--or)',fontWeight:700,fontSize:13}}>{title}</span>
    {action}
  </div>
);

// ── Generation-type badge ─────────────────────────────────────────────────
function SourceBadge({src}) {
  const cfg = {
    'Auto Generated':   {bg:'#dcfce7',color:'#15803d',label:'AUTO GENERATED'},
    'Manual Entry':     {bg:'#dbeafe',color:'#1d4ed8',label:'MANUAL ENTRY'},
    'Updated Manually': {bg:'#fef3c7',color:'#92400e',label:'UPDATED MANUALLY'},
  };
  const c = cfg[src] || {bg:'#F3F4F6',color:'#6B7280',label:'MANUAL ENTRY'};
  return <span style={{fontSize:9.5,padding:'2px 6px',borderRadius:3,fontWeight:700,background:c.bg,color:c.color,letterSpacing:'0.4px',whiteSpace:'nowrap'}}>{c.label}</span>;
}

// ── Shared drilldown detail row ──────────────────────────────────────────
function DrillKV({label, value, mono, bold, color}) {
  return (
    <div style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid rgba(0,0,0,.04)',fontSize:11.5}}>
      <span style={{color:'var(--txt2)',flexShrink:0,marginRight:8}}>{label}</span>
      <span style={{fontWeight:bold?600:500,textAlign:'right',color:color||'var(--txt)',fontFamily:'var(--font)',fontSize:mono?10.5:11.5,wordBreak:'break-all'}}>{value||'—'}</span>
    </div>
  );
}
function DrillSection({title, color, children}) {
  return (
    <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
      <div style={{fontWeight:700,fontSize:11,color:color||'var(--or)',marginBottom:10,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:`2px solid ${color||'var(--or)'}22`,paddingBottom:6}}>{title}</div>
      {children}
    </div>
  );
}

// ── Stockyard Movement Transport Report ──────────────────────────────────
function StockyardMovReport({ companyId, isGroup, onBack }) {
  window.useStoreSync();
  const SY_EMPTY = {dateFrom:'',dateTo:'',transporterId:'',materialId:'',status:'',source:''};
  const [items,   setItems]  = tSt([]);
  const [search,  setSearch] = tSt('');
  const [showFP,  setShowFP] = tSt(false);
  const [fv,      setFv]     = tSt({...SY_EMPTY});
  const [applied, setApplied]= tSt({...SY_EMPTY});
  const [expand,  setExpand] = tSt(null);
  const [pg,      setPg]     = tSt(1);
  const PER = 50;

  const allTransporters = Store.all('transporterMaster','group').filter(t=>t.status==='Active'||!t.status);
  const allMaterials    = window.filterAssigned ? window.filterAssigned(Store.all('materials'), companyId) : (Store.all('materials')||[]);

  tEf(()=>{
    function load(){
      const all = Store.all('transportEntries', companyId) || [];
      setItems(all.filter(e=>e.sourceModule==='STOCKYARD'));
    }
    load();
    return Store.on(load);
  },[companyId]);

  function applyFP(){setApplied({...fv});setPg(1);setShowFP(false);}
  function clearFP(){setFv({...SY_EMPTY});setApplied({...SY_EMPTY});setSearch('');setPg(1);}
  const activeFilters = Object.values(applied).filter(Boolean).length;

  const filtered = tMemo(()=>items.filter(it=>{
    if(search){const q=search.toLowerCase();if(![it.transporter||'',it.vehicleFull||'',it.reference||'',it._fromStockyardName||'',it._toStockyardName||'',it._stockyardName||'',it.challanNumber||''].some(v=>v.toLowerCase().includes(q)))return false;}
    if(applied.dateFrom&&it.date<applied.dateFrom)return false;
    if(applied.dateTo&&it.date>applied.dateTo)return false;
    if(applied.transporterId&&it.transporterId!==applied.transporterId)return false;
    if(applied.materialId&&it.materialId!==applied.materialId)return false;
    if(applied.status&&it.status!==applied.status)return false;
    if(applied.source&&it.source!==applied.source)return false;
    return true;
  }),[items,search,applied]);

  const syTotals = tMemo(()=>{
    const trips = filtered.length;
    const qty   = filtered.reduce((s,te)=>s+(parseFloat(te.quantity)||0),0);
    const amtNoGST = filtered.reduce((s,te)=>s+(parseFloat(te.amount)||0),0);
    const gstAmt   = filtered.reduce((s,te)=>{const b=parseFloat(te.amount)||0;const g=parseFloat(te.gstPercent)||0;return s+(b*g/100);},0);
    return {trips,qty,amtNoGST,gstAmt,amtWithGST:amtNoGST+gstAmt};
  },[filtered]);

  const totalPgs=Math.ceil(filtered.length/PER)||1;
  const paged=filtered.slice((pg-1)*PER,pg*PER);
  // expand + DATE + [COMPANY] + TRANS + VEH + MAT + QTY + UOM + PICKUP_TYPE + PICKUP_LOC + DEST_TYPE + DEST + MOV_TYPE + REF + CHALLAN + AMT_EX + GST + AMT_IN + GEN + STATUS
  const COLS = isGroup ? 20 : 19;

  const syFpFields=[
    {key:'dateFrom',    label:'Start Date',  type:'date'},
    {key:'dateTo',      label:'End Date',    type:'date'},
    {key:'status',      label:'Status',      width:120, options:['Pending','In Transit','Delivered','Cancelled'].map(s=>({value:s,label:s}))},
    {key:'source',      label:'Gen. Type',   width:160, options:['Auto Generated','Manual Entry','Updated Manually'].map(s=>({value:s,label:s}))},
    {key:'transporterId',label:'Transporter',width:160, options:allTransporters.map(t=>({value:t.id,label:t.name}))},
    {key:'materialId',  label:'Material',    width:140, options:allMaterials.map(m=>({value:m.id,label:m.name}))},
  ];

  function exportCSV(){
    const hdr=['Date','Company','Transporter','Vehicle','Material','Qty','UOM','Pickup Type','Pickup Location','Dest Type','Destination','Movement Type','Reference','Challan','Gen. Type','Status','Amount (Ex. GST)','GST %','GST Amount','Amount (Inc. GST)'];
    const rows=filtered.map(te=>{
      const base=parseFloat(te.amount)||0;
      const gstPct=parseFloat(te.gstPercent)||0;
      const gstAmt=base*gstPct/100;
      return [te.date||'',(window.ERPCompanyAttribution?window.ERPCompanyAttribution.resolveTransactionCompany(te).companyName:Store.name('companies',te.companyId))||'',te.transporter||'',te.vehicleFull||'',Store.name('materials',te.materialId)||te.material||'',te.quantity||0,te.unit||'MT',te._movementSourceType||'Stockyard',te._pickupName||te._fromStockyardName||te._stockyardName||'',te._destinationType||(te._toStockyardName?'Stockyard':''),te._destinationName||te._toStockyardName||'',te._movementLabel||te._stockMovementType||'Yard Transfer',te.reference||'',te.challanNumber||'',te.source||'Auto Generated',te.status||'Delivered',base.toFixed(2),gstPct,gstAmt.toFixed(2),(base+gstAmt).toFixed(2)].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='stockyard_transport.csv';document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1500);
    window.toast&&window.toast('Exported '+filtered.length+' records','ok');
  }

  return (
    <div>
      <div style={{marginBottom:10}}>
        <button className="btn btn-wh btn-sm" onClick={onBack} style={{display:'inline-flex',alignItems:'center',gap:5,fontWeight:500}}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
          Back to Transport Reports
        </button>
      </div>
      <div className="ph" style={{marginBottom:10}}>
        <div>
          <h1>Stockyard Movement Transport Report</h1>
          <p>Auto-generated transport records from stockyard stock movements and yard transfers</p>
        </div>
        <div className="ph-act">
          <button className={`btn btn-sm ${showFP?'btn-or':'btn-wh'}`} onClick={()=>setShowFP(p=>!p)}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
            Filters{activeFilters>0&&<span style={{background:'#fff',color:'var(--or)',borderRadius:10,padding:'0 4px',fontSize:10,fontWeight:700,marginLeft:2}}>{activeFilters}</span>}
          </button>
          <button className="btn btn-wh btn-sm" style={{fontSize:10.5}} onClick={()=>{
            const n = window.AutoTransporterEngine?.backfillStockyardEntries?.();
            window.toast&&window.toast(n>0?`Backfilled ${n} missing entries`:'All entries up to date','ok');
          }}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" 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> Backfill Missing</button>
          <button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" 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>
          <span style={{display:'inline-flex',alignItems:'center',gap:5,padding:'4px 10px',borderRadius:3,background:'#DCFCE7',color:'#15803D',fontSize:11,fontWeight:700}}>&#9679; STOCKYARD AUTO-GENERATED</span>
        </div>
      </div>
      {items.length===0&&(
        <div style={{background:'#F0FDF4',border:'1px solid #86EFAC',borderRadius:'var(--r)',padding:'16px 18px',marginBottom:12,fontSize:12,color:'#166534',lineHeight:1.7}}>
          <div style={{fontWeight:700,fontSize:13,marginBottom:5}}>No Stockyard Transport Records Yet</div>
          <div>Records auto-generate when you create a <strong>Stock Movement</strong> or <strong>Yard Transfer</strong> and select a Transporter and Vehicle in the Stockyard module.</div>
        </div>
      )}
      <window.FilterPanel show={showFP} fields={syFpFields} values={fv} onChange={(k,v)=>setFv(p=>({...p,[k]:v}))} onApply={applyFP} onRefresh={()=>{}} onExport={exportCSV} onClear={clearFP}/>
      <div className="frow">
        <div className="fs"><svg className="fs-ic" width="12" height="12" 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>
          <input value={search} onChange={e=>{setSearch(e.target.value);setPg(1);}} placeholder="Search transporter, vehicle, stockyard, reference, challan…"/>
        </div>
        {(search||activeFilters>0)&&<button className="btn btn-gh btn-sm" onClick={clearFP}>Clear All</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>
      <div className="card"><div className="tbl-w"><table className="tbl">
        <thead><tr>
          <th style={{width:28,padding:'7px 4px'}}></th>
          <th>DATE</th>{isGroup&&<th>COMPANY</th>}
          <th>TRANSPORTER</th><th>VEHICLE</th><th>MATERIAL</th>
          <th>QTY</th><th>UOM</th>
          <th>PICKUP TYPE</th><th>PICKUP LOCATION</th><th>DEST TYPE</th><th>DESTINATION</th><th>MOVEMENT TYPE</th>
          <th>REFERENCE</th><th>CHALLAN</th>
          <th style={{whiteSpace:'nowrap'}}>AMT (EX. GST)</th>
          <th style={{whiteSpace:'nowrap'}}>GST AMT</th>
          <th style={{whiteSpace:'nowrap'}}>AMT (INC. GST)</th>
          <th>GEN. TYPE</th><th>STATUS</th>
        </tr></thead>
        <tbody>
          {paged.length===0
            ?<tr className="empty"><td colSpan={COLS} style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No stockyard transport records found.</td></tr>
            :paged.map(te=>{
              const isOpen = expand===te.id;
              const base=parseFloat(te.amount)||0;
              const gstPct=parseFloat(te.gstPercent)||0;
              const gstAmt=base*gstPct/100;
              const amtWithGST=base+gstAmt;
              return [
                <tr key={te.id} style={{cursor:'pointer',background:isOpen?'#F0FDF4':undefined}} onClick={()=>setExpand(isOpen?null:te.id)}>
                  <td style={{width:28,textAlign:'center',padding:'7px 4px'}}>
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .18s',display:'block',margin:'0 auto'}}>
                      <path d="M3 1.5L7 5L3 8.5" stroke="var(--ok)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </td>
                  <td>{window.fmtDate(te.date)}</td>
                  {isGroup&&<td><span className="bdg bg-or" style={{fontSize:10,padding:'1px 5px'}}>{Store.name('companies',te.companyId)}</span></td>}
                  <td style={{fontWeight:500}}>{te.transporter||'—'}</td>
                  <td><span style={{fontFamily:'var(--font)',fontSize:11,background:'#F9FAFB',padding:'1px 5px',borderRadius:3}}>{te.vehicleFull||'—'}</span></td>
                  <td>{Store.name('materials',te.materialId)||te.material||'—'}</td>
                  <td style={{fontWeight:600}}>{window.formatQuantity(te.quantity)}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{te.unit||'MT'}</td>
                  <td style={{fontSize:11.5,color:'var(--txt2)',fontWeight:500}}>{te._movementSourceType||'Stockyard'}</td>
                  <td style={{fontSize:11.5}}>{te._pickupName||te._fromStockyardName||te._stockyardName||'—'}</td>
                  <td style={{fontSize:11.5,color:'var(--txt2)',fontWeight:500}}>{te._destinationType||(te._toStockyardName?'Stockyard':'—')}</td>
                  <td style={{fontSize:11.5}}>{te._destinationName||te._toStockyardName||'—'}</td>
                  <td><span className="bdg bg-bl" style={{fontSize:10,padding:'1px 5px'}}>{te._movementLabel||te._stockMovementType||'Yard Transfer'}</span></td>
                  <td style={{fontFamily:'var(--font)',fontSize:11.5}}>{te.reference||'—'}</td>
                  <td style={{fontFamily:'var(--font)',fontSize:11}}>{te.challanNumber||'—'}</td>
                  <td style={{fontWeight:600,color:'var(--txt)'}}>{base>0?window.fmtCur(base):'—'}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{base>0?window.fmtCur(gstAmt):'₹0'}</td>
                  <td style={{fontWeight:700,color:'var(--ok)'}}>{base>0?window.fmtCur(amtWithGST):'—'}</td>
                  <td><SourceBadge src={te.source||'Auto Generated'}/></td>
                  <td><window.Badge v={te.status||'Delivered'}/></td>
                </tr>,
                isOpen&&(
                  <tr key={te.id+'-exp'}>
                    <td colSpan={COLS} style={{padding:0,background:'#F0FDF4',borderTop:'2px solid #86EFAC'}}>
                      <div style={{padding:'14px 18px 16px'}}>
                        <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12}}>
                          <DrillSection title="Movement Information" color="#15803D">
                            <DrillKV label="Movement ID"   value={te.id?te.id.slice(0,8).toUpperCase():'—'} mono bold/>
                            <DrillKV label="Reference ID"  value={te.reference||'—'} mono/>
                            <DrillKV label="Source Module" value={te.sourceModule||'STOCKYARD'} bold/>
                            <DrillKV label="Created Date"  value={window.fmtDate(te.date)}/>
                            <DrillKV label="Created By"    value={te.createdBy||'System (Auto)'}/>
                            <DrillKV label="Movement Type" value={te._movementLabel||te._stockMovementType||'Yard Transfer'} bold/>
                          </DrillSection>
                          <DrillSection title="Transport Information" color="var(--or)">
                            <DrillKV label="Transporter"   value={te.transporter||'—'} bold/>
                            <DrillKV label="Vehicle"       value={te.vehicleFull||'—'} mono bold/>
                            <DrillKV label="Challan No."   value={te.challanNumber||'—'} mono/>
                            <DrillKV label="Trip Status"   value={te.status||'Delivered'} color="var(--ok)" bold/>
                            <DrillKV label="Gen. Type"     value={te.source||'Auto Generated'}/>
                          </DrillSection>
                          <DrillSection title="Material & Financials" color="#1D4ED8">
                            <DrillKV label="Material"      value={Store.name('materials',te.materialId)||te.material||'—'} bold/>
                            <DrillKV label="Quantity"      value={`${window.formatQuantity(te.quantity)} ${te.unit||'MT'}`} bold color="var(--or)"/>
                            <DrillKV label="Rate"          value={te.ratePerTon?`₹${window.fmtNum(te.ratePerTon)}`:'—'}/>
                            <DrillKV label="Rate Source"   value={window.TransportRateResolver?window.TransportRateResolver.appliedSource(te):'—'}/>
                            <DrillKV label="Amt (Ex. GST)" value={base>0?window.fmtCur(base):'—'} bold/>
                            <DrillKV label="GST %"         value={`${gstPct}%`}/>
                            <DrillKV label="GST Amount"    value={window.fmtCur(gstAmt)}/>
                            <DrillKV label="Amt (Inc. GST)" value={base>0?window.fmtCur(amtWithGST):'—'} color="#1D4ED8" bold/>
                            {te._transportQuantitySource&&<DrillKV label="Qty Source" value={te._transportQuantitySource} bold/>}
                          </DrillSection>
                          <DrillSection title="Route & Audit" color="#6B7280">
                            <DrillKV label="Movement Type"    value={te._movementLabel||te._stockMovementType||'Yard Transfer'} bold/>
                            <DrillKV label="Pickup Type"      value={te._movementSourceType||'Stockyard'} bold/>
                            <DrillKV label="Pickup Location"  value={te._pickupName||te._fromStockyardName||te._stockyardName||'—'} bold/>
                            <DrillKV label="Destination Type" value={te._destinationType||(te._toStockyardName?'Stockyard':'—')} bold/>
                            <DrillKV label="Destination"      value={te._destinationName||te._toStockyardName||'—'} bold/>
                            <DrillKV label="Created On"       value={te._creationTimestamp?new Date(te._creationTimestamp).toLocaleString():'—'}/>
                            <DrillKV label="Last Modified"    value={te.lastUpdated||te._lastSyncTimestamp?.slice(0,10)||'—'}/>
                            <DrillKV label="Record ID"        value={te.id?.slice(0,14)||'—'} mono/>
                          </DrillSection>
                        </div>
                      </div>
                    </td>
                  </tr>
                )
              ];
            })
          }
        </tbody>
        {filtered.length>0&&<tfoot>
          <tr style={{background:'var(--or-lt)',position:'sticky',bottom:0,zIndex:2}}>
            {/* expand + DATE [+ COMPANY] */}
            <td colSpan={isGroup?3:2} style={{borderTop:'2px solid var(--or-bdr)',padding:'9px 14px',fontSize:12,fontWeight:700,color:'var(--txt2)',whiteSpace:'nowrap'}}>TOTALS — {syTotals.trips} Trip{syTotals.trips!==1?'s':''}</td>
            {/* TRANSPORTER + VEHICLE + MATERIAL */}
            <td colSpan={3} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* QTY */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap'}}>{window.formatQuantity(syTotals.qty)}</td>
            {/* UOM + PICKUP TYPE + PICKUP LOC + DEST TYPE + DEST + MOV TYPE + REF + CHALLAN */}
            <td colSpan={8} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* AMT EX GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--txt)'}}>{window.fmtCur(syTotals.amtNoGST)}</td>
            {/* GST AMT */}
            <td style={{padding:'9px 14px',fontWeight:600,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--txt2)'}}>{window.fmtCur(syTotals.gstAmt)}</td>
            {/* AMT INC GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:13,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--or)'}}>{window.fmtCur(syTotals.amtWithGST)}</td>
            {/* GEN TYPE + STATUS */}
            <td colSpan={2} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
          </tr>
        </tfoot>}
      </table></div></div>
      {totalPgs>1&&<div className="pag"><button className="pg-b" onClick={()=>setPg(1)} disabled={pg===1}>«</button><button className="pg-b" onClick={()=>setPg(p=>p-1)} disabled={pg===1}>‹</button><span className="pg-inf">Page {pg} of {totalPgs}</span><button className="pg-b" onClick={()=>setPg(p=>p+1)} disabled={pg===totalPgs}>›</button><button className="pg-b" onClick={()=>setPg(totalPgs)} disabled={pg===totalPgs}>»</button></div>}
    </div>
  );
}

// ── Debris Movement Transport Report ─────────────────────────────────────
function DebrisMovReport({ companyId, isGroup, onBack }) {
  window.useStoreSync();
  const DB_EMPTY = {dateFrom:'',dateTo:'',transporterId:'',materialId:'',destType:'',disposalType:'',status:'',source:''};
  const [items,  setItems]  = tSt([]);
  const [search, setSearch] = tSt('');
  const [showFP, setShowFP] = tSt(false);
  const [fv,     setFv]     = tSt({...DB_EMPTY});
  const [applied,setApplied]= tSt({...DB_EMPTY});
  const [expand, setExpand] = tSt(null);
  const [pg,     setPg]     = tSt(1);
  const PER = 50;

  const allTransporters = Store.all('transporterMaster','group').filter(t=>t.status==='Active'||!t.status);
  const allMaterials    = window.filterAssigned ? window.filterAssigned(Store.all('materials'), companyId) : (Store.all('materials')||[]);
  const rmcPlants       = Store.all('rmcPlants')||[];

  tEf(()=>{
    function load(){
      const all = Store.all('transportEntries', companyId) || [];
      setItems(all.filter(e=>e.sourceModule==='DEBRIS'));
    }
    load();
    return Store.on(load);
  },[companyId]);

  function applyFP(){setApplied({...fv});setPg(1);setShowFP(false);}
  function clearFP(){setFv({...DB_EMPTY});setApplied({...DB_EMPTY});setSearch('');setPg(1);}
  const activeFilters = Object.values(applied).filter(Boolean).length;

  // Unique dest types and disposal types from data for filter options
  const destTypeOpts  = tMemo(()=>[...new Set(items.map(i=>i._destType||'').filter(Boolean))].sort().map(v=>({value:v,label:v})),[items]);
  const disposalOpts  = tMemo(()=>[...new Set(items.map(i=>i._disposalType||'').filter(Boolean))].sort().map(v=>({value:v,label:v})),[items]);

  const filtered = tMemo(()=>items.filter(it=>{
    if(search){const q=search.toLowerCase();if(![it.transporter||'',it.vehicleFull||'',it.challanNumber||'',it._sourcePlantName||'',it._destLocation||'',it.material||'',it._destType||''].some(v=>v.toLowerCase().includes(q)))return false;}
    if(applied.dateFrom&&it.date<applied.dateFrom)return false;
    if(applied.dateTo&&it.date>applied.dateTo)return false;
    if(applied.transporterId&&it.transporterId!==applied.transporterId)return false;
    if(applied.materialId&&(it.materialId||'')!==applied.materialId)return false;
    if(applied.destType&&(it._destType||'')!==applied.destType)return false;
    if(applied.disposalType&&(it._disposalType||'')!==applied.disposalType)return false;
    if(applied.status&&it.status!==applied.status)return false;
    if(applied.source&&it.source!==applied.source)return false;
    return true;
  }),[items,search,applied]);

  const dbTotals = tMemo(()=>{
    const trips = filtered.length;
    const qty   = filtered.reduce((s,te)=>s+(parseFloat(te.quantity)||0),0);
    const amtNoGST = filtered.reduce((s,te)=>s+(parseFloat(te.amount)||0),0);
    const gstAmt   = filtered.reduce((s,te)=>{const b=parseFloat(te.amount)||0;const g=parseFloat(te.gstPercent)||0;return s+(b*g/100);},0);
    return {trips,qty,amtNoGST,gstAmt,amtWithGST:amtNoGST+gstAmt};
  },[filtered]);

  const totalPgs=Math.ceil(filtered.length/PER)||1;
  const paged=filtered.slice((pg-1)*PER,pg*PER);
  // expand + DATE + [COMPANY] + TRANS + VEH + SRC PLANT + DEST TYPE + DEST LOC + MAT + QTY + UOM + RATE + AMT_EX + GST + AMT_IN + CHALLAN + DISPOSAL + GEN + STATUS
  const COLS = isGroup ? 19 : 18;

  const dbFpFields=[
    {key:'dateFrom',     label:'Start Date',   type:'date'},
    {key:'dateTo',       label:'End Date',     type:'date'},
    {key:'status',       label:'Status',       width:120, options:['Pending','In Transit','Delivered','Cancelled'].map(s=>({value:s,label:s}))},
    {key:'source',       label:'Gen. Type',    width:160, options:['Auto Generated','Manual Entry','Updated Manually'].map(s=>({value:s,label:s}))},
    {key:'transporterId',label:'Transporter',  width:160, options:allTransporters.map(t=>({value:t.id,label:t.name}))},
    {key:'materialId',   label:'Material',     width:140, options:allMaterials.map(m=>({value:m.id,label:m.name}))},
    {key:'destType',     label:'Dest. Type',   width:140, options:destTypeOpts},
    {key:'disposalType', label:'Disposal Type',width:140, options:disposalOpts},
  ];

  function exportCSV(){
    const hdr=['Date','Company','Transporter','Vehicle','Source Plant','Dest Type','Dest Location','Material','Qty','UOM','Transport Rate (₹/MT)','Amount (Ex. GST)','GST %','GST Amount','Amount (Inc. GST)','Challan','Disposal Type','Gen. Type','Status'];
    const rows=filtered.map(te=>{
      const coName=Store.name('companies',te.companyId)||'';
      const plantName=te._sourcePlantName||(te._sourcePlantId?rmcPlants.find(p=>p.id===te._sourcePlantId)?.name:'')||'';
      const base=parseFloat(te.amount)||0;
      const gstPct=parseFloat(te.gstPercent)||0;
      const gstAmt=base*gstPct/100;
      return [te.date||'',coName,te.transporter||'',te.vehicleFull||'',plantName,te._destType||'',te._destLocation||'',te.material||'',te.quantity||0,te.unit||'Ton',te.ratePerTon||0,base.toFixed(2),gstPct,gstAmt.toFixed(2),(base+gstAmt).toFixed(2),te.challanNumber||'',te._disposalType||'',te.source||'Auto Generated',te.status||'Delivered'].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='debris_transport.csv';document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1500);
    window.toast&&window.toast('Exported '+filtered.length+' records','ok');
  }

  return (
    <div>
      <div style={{marginBottom:10}}>
        <button className="btn btn-wh btn-sm" onClick={onBack} style={{display:'inline-flex',alignItems:'center',gap:5,fontWeight:500}}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
          Back to Transport Reports
        </button>
      </div>
      <div className="ph" style={{marginBottom:10}}>
        <div>
          <h1>Debris Movement Transport Report</h1>
          <p>Auto-generated transport records from debris disposal movements</p>
        </div>
        <div className="ph-act">
          <button className={`btn btn-sm ${showFP?'btn-or':'btn-wh'}`} onClick={()=>setShowFP(p=>!p)}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
            Filters{activeFilters>0&&<span style={{background:'#fff',color:'var(--or)',borderRadius:10,padding:'0 4px',fontSize:10,fontWeight:700,marginLeft:2}}>{activeFilters}</span>}
          </button>
          <button className="btn btn-wh btn-sm" style={{fontSize:10.5}} onClick={()=>{
            const n = window.AutoTransporterEngine?.backfillDebrisEntries?.();
            window.toast&&window.toast(n>0?`Backfilled ${n} missing entries`:'All entries up to date','ok');
          }}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" 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> Backfill Missing</button>
          <button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" 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>
          <span style={{display:'inline-flex',alignItems:'center',gap:5,padding:'4px 10px',borderRadius:3,background:'#FFF7ED',color:'var(--or)',fontSize:11,fontWeight:700}}>&#9679; DEBRIS AUTO-GENERATED</span>
        </div>
      </div>
      {items.length===0&&(
        <div style={{background:'#FFF9F5',border:'1px solid var(--or-bdr)',borderRadius:'var(--r)',padding:'16px 18px',marginBottom:12,fontSize:12,color:'var(--or)',lineHeight:1.7}}>
          <div style={{fontWeight:700,fontSize:13,marginBottom:5}}>No Debris Transport Records Yet</div>
          <div>Records auto-generate when you create a <strong>Debris Movement</strong> with a Transporter and Vehicle selected (via Transporter Master).</div>
        </div>
      )}
      <window.FilterPanel show={showFP} fields={dbFpFields} values={fv} onChange={(k,v)=>setFv(p=>({...p,[k]:v}))} onApply={applyFP} onRefresh={()=>{}} onExport={exportCSV} onClear={clearFP}/>
      <div className="frow">
        <div className="fs"><svg className="fs-ic" width="12" height="12" 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>
          <input value={search} onChange={e=>{setSearch(e.target.value);setPg(1);}} placeholder="Search transporter, vehicle, plant, challan, material…"/>
        </div>
        {(search||activeFilters>0)&&<button className="btn btn-gh btn-sm" onClick={clearFP}>Clear All</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>
      <div className="card"><div className="tbl-w"><table className="tbl">
        <thead><tr>
          <th style={{width:28,padding:'7px 4px'}}></th>
          <th>DATE</th>{isGroup&&<th>COMPANY</th>}
          <th>TRANSPORTER</th><th>VEHICLE</th>
          <th>SOURCE PLANT</th><th>DEST TYPE</th><th>DEST LOCATION</th>
          <th>MATERIAL</th><th>QTY</th><th>UOM</th>
          <th>RATE</th>
          <th style={{whiteSpace:'nowrap'}}>AMT (EX. GST)</th>
          <th style={{whiteSpace:'nowrap'}}>GST AMT</th>
          <th style={{whiteSpace:'nowrap'}}>AMT (INC. GST)</th>
          <th>CHALLAN</th><th>DISPOSAL TYPE</th>
          <th>GEN. TYPE</th><th>STATUS</th>
        </tr></thead>
        <tbody>
          {paged.length===0
            ?<tr className="empty"><td colSpan={COLS} style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No debris transport records found. Records auto-generate when Debris Movements are created with a Transporter and Vehicle.</td></tr>
            :paged.map(te=>{
              const isOpen = expand===te.id;
              const coName = Store.name('companies',te.companyId)||'—';
              const plantName = te._sourcePlantName||(te._sourcePlantId?rmcPlants.find(p=>p.id===te._sourcePlantId)?.name:'—')||'—';
              const base=parseFloat(te.amount)||0;
              const gstPct=parseFloat(te.gstPercent)||0;
              const gstAmt=base*gstPct/100;
              const amtWithGST=base+gstAmt;
              return [
                <tr key={te.id} style={{cursor:'pointer',background:isOpen?'#FFF9F5':undefined}} onClick={()=>setExpand(isOpen?null:te.id)}>
                  <td style={{width:28,textAlign:'center',padding:'7px 4px'}}>
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .18s',display:'block',margin:'0 auto'}}>
                      <path d="M3 1.5L7 5L3 8.5" stroke="var(--or)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </td>
                  <td>{window.fmtDate(te.date)}</td>
                  {isGroup&&<td><span className="bdg bg-or" style={{fontSize:10,padding:'1px 5px'}}>{coName}</span></td>}
                  <td style={{fontWeight:500}}>{te.transporter||'—'}</td>
                  <td><span style={{fontFamily:'var(--font)',fontSize:11,background:'#F9FAFB',padding:'1px 5px',borderRadius:3}}>{te.vehicleFull||'—'}</span></td>
                  <td style={{fontSize:11.5}}>{plantName}</td>
                  <td style={{fontSize:11}}>{te._destType||'—'}</td>
                  <td style={{fontSize:11.5,color:'var(--txt2)'}}>{te._destLocation||'—'}</td>
                  <td>{te.material||'—'}</td>
                  <td style={{fontWeight:600}}>{window.formatQuantity(te.quantity)}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{te.unit||'Ton'}</td>
                  <td style={{fontWeight:600,color:'var(--info)',fontSize:12}}>{te.ratePerTon ? `₹${window.fmtNum(te.ratePerTon)}/MT` : '—'}</td>
                  <td style={{fontWeight:600,color:'var(--txt)'}}>{base>0?window.fmtCur(base):'—'}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{base>0?window.fmtCur(gstAmt):'₹0'}</td>
                  <td style={{fontWeight:700,color:'var(--ok)'}}>{base>0?window.fmtCur(amtWithGST):'—'}</td>
                  <td style={{fontFamily:'var(--font)',fontSize:11}}>{te.challanNumber||'—'}</td>
                  <td style={{fontSize:11,color:'var(--txt2)'}}>{te._disposalType||'—'}</td>
                  <td><SourceBadge src={te.source||'Auto Generated'}/></td>
                  <td><window.Badge v={te.status||'Delivered'}/></td>
                </tr>,
                isOpen&&(
                  <tr key={te.id+'-exp'}>
                    <td colSpan={COLS} style={{padding:0,background:'#FFF9F5',borderTop:'2px solid var(--or-bdr)'}}>
                      <div style={{padding:'14px 18px 16px'}}>
                        <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12}}>

                          <DrillSection title="Debris Information" color="var(--or)">
                            <DrillKV label="Debris Movement ID" value={te._debrisMovementId?te._debrisMovementId.slice(0,8).toUpperCase():'—'} mono bold/>
                            <DrillKV label="Reference ID"       value={te.reference||te.challanNumber||'—'} mono/>
                            <DrillKV label="Company"            value={coName} bold/>
                            <DrillKV label="Generation Type"    value={te.source||'Auto Generated'} bold color="#15803d"/>
                            <DrillKV label="Date"               value={window.fmtDate(te.date)}/>
                          </DrillSection>

                          <DrillSection title="Source & Destination" color="#1D4ED8">
                            <DrillKV label="Source Plant"       value={plantName} bold/>
                            <DrillKV label="Destination Type"   value={te._destType||'—'} bold/>
                            <DrillKV label="Destination"        value={te._destLocation||'—'}/>
                            <DrillKV label="Disposal Type"      value={te._disposalType||'—'} bold/>
                          </DrillSection>

                          <DrillSection title="Material & Financials" color="#B45309">
                            <DrillKV label="Material"        value={te.material||'—'} bold/>
                            <DrillKV label="Quantity"        value={`${window.formatQuantity(te.quantity)} ${te.unit||'Ton'}`} bold color="var(--or)"/>
                            <DrillKV label="Transport Rate"  value={te.ratePerTon ? `₹${window.fmtNum(te.ratePerTon)}/MT` : '—'} bold color="var(--info)"/>
                            <DrillKV label="Rate Source"     value={window.TransportRateResolver?window.TransportRateResolver.appliedSource(te):'—'}/>
                            <DrillKV label="Amt (Ex. GST)"   value={base>0?window.fmtCur(base):'—'} bold/>
                            <DrillKV label="GST %"           value={`${gstPct}%`}/>
                            <DrillKV label="GST Amount"      value={window.fmtCur(gstAmt)}/>
                            <DrillKV label="Amt (Inc. GST)"  value={base>0?window.fmtCur(amtWithGST):'—'} bold color="var(--ok)"/>
                            <DrillKV label="Transporter"     value={te.transporter||'—'} bold/>
                            <DrillKV label="Vehicle"         value={te.vehicleFull||'—'} mono bold/>
                            <DrillKV label="Challan No."     value={te.challanNumber||'—'} mono/>
                          </DrillSection>

                          <DrillSection title="System Information" color="#6B7280">
                            <DrillKV label="Trip Status"   value={te.status||'Delivered'} color="var(--ok)" bold/>
                            <DrillKV label="Created Date"  value={te._creationTimestamp?new Date(te._creationTimestamp).toLocaleString():'—'}/>
                            <DrillKV label="Last Updated"  value={te.lastUpdated||'—'}/>
                            <DrillKV label="Gen. Type"     value={te.source||'Auto Generated'} bold color="#15803d"/>
                            <DrillKV label="Record ID"     value={te.id?.slice(0,14)||'—'} mono/>
                          </DrillSection>

                        </div>
                      </div>
                    </td>
                  </tr>
                )
              ];
            })
          }
        </tbody>
        {filtered.length>0&&<tfoot>
          <tr style={{background:'var(--or-lt)',position:'sticky',bottom:0,zIndex:2}}>
            {/* expand + DATE [+ COMPANY] */}
            <td colSpan={isGroup?3:2} style={{borderTop:'2px solid var(--or-bdr)',padding:'9px 14px',fontSize:12,fontWeight:700,color:'var(--txt2)',whiteSpace:'nowrap'}}>TOTALS — {dbTotals.trips} Trip{dbTotals.trips!==1?'s':''}</td>
            {/* TRANS + VEH + SRC PLANT + DEST TYPE + DEST LOC + MAT */}
            <td colSpan={6} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* QTY */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap'}}>{window.formatQuantity(dbTotals.qty)}</td>
            {/* UOM + RATE */}
            <td colSpan={2} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* AMT EX GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--txt)'}}>{window.fmtCur(dbTotals.amtNoGST)}</td>
            {/* GST AMT */}
            <td style={{padding:'9px 14px',fontWeight:600,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--txt2)'}}>{window.fmtCur(dbTotals.gstAmt)}</td>
            {/* AMT INC GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:13,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--or)'}}>{window.fmtCur(dbTotals.amtWithGST)}</td>
            {/* CHALLAN + DISPOSAL + GEN TYPE + STATUS */}
            <td colSpan={4} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
          </tr>
        </tfoot>}
      </table></div></div>
      {totalPgs>1&&<div className="pag"><button className="pg-b" onClick={()=>setPg(1)} disabled={pg===1}>«</button><button className="pg-b" onClick={()=>setPg(p=>p-1)} disabled={pg===1}>‹</button><span className="pg-inf">Page {pg} of {totalPgs}</span><button className="pg-b" onClick={()=>setPg(p=>p+1)} disabled={pg===totalPgs}>›</button><button className="pg-b" onClick={()=>setPg(totalPgs)} disabled={pg===totalPgs}>»</button></div>}
    </div>
  );
}

// ============================================================
// TRANSPORTER REPORTS PAGE
// ============================================================
function TransportPage() {
  window.useStoreSync();
  const {companyId}=tCtx(AppCtx);
  const isGroup = companyId==='group';
  const [activeTab,setActiveTab]=tSt('transport');
  const [items,setItems]=tSt([]);
  const [engStats,setEngStats]=tSt(()=>window.AutoTransporterEngine?.getStats()||null);
  const [search,setSearch]=tSt('');
  const [showFP,setShowFP]=tSt(false);
  const [fv,setFv]=tSt({dateFrom:'',dateTo:'',status:'',transporterId:'',crusherId:'',customerId:'',materialId:'',source:''});
  const [applied,setApplied]=tSt({dateFrom:'',dateTo:'',status:'',transporterId:'',crusherId:'',customerId:'',materialId:'',source:''});
  const [page,setPage]=tSt(1);
  const [modal,setModal]=tSt(false);
  const [editId,setEditId]=tSt(null);
  const [delId,setDelId]=tSt(null);
  const [expand,setExpand]=tSt(null);
  const [form,setForm]=tSt({});
  const PER=50;
  const transporters=Store.all('transportersList',companyId);
  const crushers=window.filterAssigned(Store.all('crushers'),companyId);
  const customers=window.filterAssigned(Store.all('customers'),companyId);
  const materials=window.filterAssigned(Store.all('materials'),companyId);

  // ── Transport Master — live sync so form always reflects current TM data ───────
  const [tpTmAll, setTpTmAll] = tSt(()=>Store.all('transporterMaster','group'));
  const [tpAllVeh, setTpAllVeh] = tSt(()=>Store.all('vehicleMaster','group')||[]);
  tEf(()=>{
    const unsub=Store.on(()=>{
      setTpTmAll(Store.all('transporterMaster','group'));
      setTpAllVeh(Store.all('vehicleMaster','group')||[]);
    });
    return unsub;
  },[]);
  const tpTmActive=tpTmAll.filter(t=>t.status==='Active'||!t.status);
  const tpTmVehicles=tMemo(()=>form.transporterMasterId
    ?tpAllVeh.filter(v=>v.transporterId===form.transporterMasterId&&(v.status==='Active'||!v.status))
    :[],[tpAllVeh,form.transporterMasterId]);

  tEf(()=>{load();},[companyId]);
  tEf(()=>{
    if(!window.AutoTransporterEngine)return;
    const unsub=window.AutoTransporterEngine.onUpdate(s=>setEngStats({...s}));
    return unsub;
  },[]);

  // Exclude STOCKYARD and DEBRIS entries — they appear in their own tabs
  function load(){
    const all=Store.all('transportEntries',companyId)||[];
    setItems(all.filter(e=>e.sourceModule!=='STOCKYARD'&&e.sourceModule!=='DEBRIS'));
  }

  function applyFP(){setApplied({...fv});setPage(1);setShowFP(false);}
  function clearFP(){const e={dateFrom:'',dateTo:'',status:'',transporterId:'',crusherId:'',customerId:'',materialId:'',source:''};setFv(e);setApplied(e);setSearch('');setPage(1);}

  const filtered=tMemo(()=>items.filter(it=>{
    if(search){const q=search.toLowerCase();
      const _cuSrch=it.customerName||(it.customerId?Store.name('customers',it.customerId):'')||'';
      if(![it.challanNumber,it.vehicleFull,it.transporter,it.crusherName,_cuSrch].some(v=>String(v||'').toLowerCase().includes(q))
        &&!Store.name('transportersList',it.transporterId).toLowerCase().includes(q))return false;}
    if(applied.dateFrom&&it.date<applied.dateFrom)return false;
    if(applied.dateTo&&it.date>applied.dateTo)return false;
    if(applied.status&&it.status!==applied.status)return false;
    if(applied.transporterId){
      const _selName=(Store.name('transportersList',applied.transporterId)||'').toLowerCase();
      const _nameOk=it.transporterId===applied.transporterId||(it.transporterId===''&&_selName&&(it.transporter||'').toLowerCase().includes(_selName));
      if(!_nameOk)return false;
    }
    if(applied.crusherId&&it.crusherId!==applied.crusherId)return false;
    if(applied.customerId&&it.customerId!==applied.customerId)return false;
    if(applied.materialId&&it.materialId!==applied.materialId)return false;
    if(applied.source&&it.source!==applied.source)return false;
    return true;
  }),[items,search,applied]);

  const activeFilters=Object.values(applied).filter(Boolean).length;
  const totalPgs=Math.ceil(filtered.length/PER);
  const paged=filtered.slice((page-1)*PER,page*PER);
  const autoCount=items.filter(i=>i._autoGenerated).length;
  const manualCount=items.filter(i=>!i._autoGenerated).length;
  const tpTotals=tMemo(()=>{
    const trips=filtered.length;
    const qty=filtered.reduce((s,te)=>s+(parseFloat(te.quantity)||0),0);
    const baseAmt=filtered.reduce((s,te)=>s+(parseFloat(te.amount)||0),0);
    const amt=window.SettlementEngine?filtered.reduce((s,te)=>{
      const _q=parseFloat(te.quantity)||0;
      const _b=parseFloat(te.amount)||0;
      const _se=window.SettlementEngine.getAdjustedRate(te.vehicleFull,_q,_b);
      return s+(_se.hasPolicy?_se.adjustedGross:_b);
    },0):baseAmt;
    const gstAmt=filtered.reduce((s,te)=>{const b=parseFloat(te.amount)||0;const g=parseFloat(te.gstPercent)||0;return s+(b*g/100);},0);
    return {trips,qty,amt,baseAmt,gstAmt,amtWithGST:amt+gstAmt};
  },[filtered]);

  function setF(k,v){setForm(p=>{
    const n={...p,[k]:v};
    if(k==='transporterMasterId'){n.vehicleFull='';const _tr=tpTmAll.find(t=>t.id===v);if(_tr)n.transporter=_tr.name;}
    if(k==='quantity'||k==='ratePerTon'){const qty=parseFloat(k==='quantity'?v:n.quantity)||0;const rate=parseFloat(k==='ratePerTon'?v:n.ratePerTon)||0;n.amount=window.TransportRateResolver?window.TransportRateResolver.amountFor(qty,rate):qty*rate;if(k==='ratePerTon'){n._rateAutoFilled=false;n._rateManualOverride=true;n.rateResolutionMethod='MANUAL_OVERRIDE';n.rateSnapshotAt=new Date().toISOString();}}
    // Rate resolution is DATE-DRIVEN: the applicable rate is the one effective on
    // the trip date, never "the latest rate". Editing an existing record never
    // re-resolves — its snapshot is immutable unless the user types a new rate.
    if(k==='crusherId'||k==='customerId'||k==='materialId'||k==='date'){
      const cid=k==='crusherId'?v:n.crusherId;
      const custId=k==='customerId'?v:n.customerId;
      const matId=k==='materialId'?v:n.materialId;
      const dt=k==='date'?v:n.date;
      const TRR=window.TransportRateResolver;
      const locked=!!(editId&&TRR&&TRR.hasSnapshot(p)&&k!=='date');
      if(TRR&&cid&&custId&&matId&&dt&&!locked){
        const res=TRR.resolve({date:dt,companyId:n.companyId||companyId,crusherId:cid,destinationType:'Customer',destinationId:custId,materialId:matId});
        if(res.found){
          const snap=TRR.snapshotFields(res,{quantity:n.quantity,date:dt,uom:n.unit});
          Object.assign(n,snap);n._rateAutoFilled=true;n._rateManualOverride=false;n._rateNote=res.message;
        }else{n._rateAutoFilled=false;n._rateNote=res.message||'';}
      }else if(!locked){n._rateAutoFilled=false;n._rateNote='';}
    }
    return n;
  });}

  function openAdd(){setForm({date:new Date().toISOString().slice(0,10),status:'Delivered',unit:'MT',source:'Manual Entry',companyId:isGroup?'':companyId,_rateAutoFilled:false,transporterMasterId:'',vehicleFull:''});setEditId(null);setModal(true);}
  function openEdit(it){setForm({...it});setEditId(it.id);setModal(true);}

  function handleSave(e){
    e.preventDefault();
    const coErr=window.requireGroupCompany&&window.requireGroupCompany(isGroup,form.companyId);
    if(coErr){window.toast&&window.toast(coErr,'er');return;}
    if(!form.transporterMasterId){window.toast&&window.toast('Please select a Transporter.','er');return;}
    if(!form.vehicleFull){window.toast&&window.toast('Please select a Vehicle.','er');return;}
    const saveData={...form,lastUpdated:new Date().toISOString().slice(0,10)};
    // Resolve transporter name from Transport Master
    const _tmRec=tpTmAll.find(t=>t.id===form.transporterMasterId);
    if(_tmRec)saveData.transporter=_tmRec.name;
    if(!saveData.source)saveData.source='Manual Entry';
    if(saveData._autoGenerated&&saveData.source==='Auto Generated')saveData.source='Updated Manually';
    if(saveData.customerId&&!saveData.customerName)saveData.customerName=Store.name('customers',saveData.customerId)||'';
    if(saveData.crusherId&&!saveData.crusherName)saveData.crusherName=Store.name('crushers',saveData.crusherId)||'';
    // Snapshot the applied rate onto the transaction so no future rate-master
    // change can ever reprice this trip. Existing snapshots are preserved.
    const _TRR=window.TransportRateResolver;
    if(_TRR){
      if(!editId)saveData.entryType=saveData.entryType||'MANUAL';
      if(!_TRR.hasSnapshot(saveData)&&saveData.crusherId&&saveData.customerId&&saveData.materialId&&saveData.date){
        const _res=_TRR.resolve({date:saveData.date,companyId:saveData.companyId||companyId,crusherId:saveData.crusherId,destinationType:'Customer',destinationId:saveData.customerId,materialId:saveData.materialId});
        Object.assign(saveData,_TRR.snapshotFields(_res,{quantity:saveData.quantity,date:saveData.date,uom:saveData.unit}));
      }
      saveData.amount=_TRR.amountFor(saveData.quantity,_TRR.readApplied(saveData));
      if(!saveData.rateSnapshotAt)saveData.rateSnapshotAt=new Date().toISOString();
      saveData._rateImmutable=true;
    }
    if(editId){Store.update('transportEntries',editId,saveData);Store.addLog('UPDATE','Transporter Reports',`Updated ${form.challanNumber||form.vehicleFull}`);}
    else{Store.add('transportEntries',saveData);Store.addLog('CREATE','Transporter Reports',`Created ${form.challanNumber||form.vehicleFull}`);}
    setModal(false);load();window.toast&&window.toast(editId?'Updated':'Created','ok');
  }

  function handleDelete(){Store.del('transportEntries',delId);Store.addLog('DELETE','Transporter Reports','Deleted');setDelId(null);load();window.toast&&window.toast('Deleted','ok');}

  function exportCSV(){
    const hdr='Date,OM Group Company,Transporter,Vehicle No,Challan No,Crusher (Pickup),Customer (Delivery),Material,Qty,UOM,Base Rate,Settlement Margin/MT,Settlement Rate,Base Amount,Settlement Amount,Settlement Policy,Status,Source,Last Updated';
    const rows=filtered.map(te=>{
      const trName=te.transporter||(te.transporterId?Store.name('transportersList',te.transporterId):'')||'';
      const crName=te.crusherName||(te.crusherId?Store.name('crushers',te.crusherId):'')||'';
      const cuName=te.customerName||(te.customerId?Store.name('customers',te.customerId):'')||'';
      const coName=(window.ERPCompanyAttribution?window.ERPCompanyAttribution.resolveTransactionCompany(te).companyName:Store.name('companies',te.companyId))||'Unassigned';
      const _csvQty=parseFloat(te.quantity)||0;
      const _csvBase=parseFloat(te.amount)||0;
      const _csvRate=parseFloat(te.ratePerTon)||0;
      const _csvSe=window.SettlementEngine?window.SettlementEngine.getAdjustedRate(te.vehicleFull,_csvQty,_csvBase):{hasPolicy:false};
      const _csvMargin=_csvSe.hasPolicy?(_csvSe.marginPerUnit||0):0;
      const _csvFinalRate=_csvSe.hasPolicy&&_csvQty>0?_csvSe.adjustedGross/_csvQty:_csvRate;
      const _csvFinalAmt=_csvSe.hasPolicy?_csvSe.adjustedGross:_csvBase;
      const _csvPolicy=_csvSe.hasPolicy?(_csvSe.policyName||'—'):'—';
      return `"${te.date}","${coName}","${trName}","${te.vehicleFull||''}","${te.challanNumber||''}","${crName}","${cuName}","${Store.name('materials',te.materialId)||''}","${_csvQty}","${te.unit||'MT'}","${_csvRate}","${_csvMargin.toFixed(2)}","${_csvFinalRate.toFixed(2)}","${_csvBase.toFixed(2)}","${_csvFinalAmt.toFixed(2)}","${_csvPolicy}","${te.status||''}","${te.source||'Manual Entry'}","${te.lastUpdated||''}"`;
    }).join('\n');
    const blob=new Blob([hdr+'\n'+rows],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='transporter_reports.csv';a.click();
    window.toast&&window.toast('CSV exported','ok');
  }

  const fpFields=[
    {key:'dateFrom',label:'Start Date',type:'date'},{key:'dateTo',label:'End Date',type:'date'},
    {key:'status',label:'Status',width:120,options:['Pending','In Transit','Delivered','Cancelled'].map(s=>({value:s,label:s}))},
    {key:'source',label:'Source',width:150,options:['Auto Generated','Manual Entry','Updated Manually'].map(s=>({value:s,label:s}))},
    {key:'crusherId',label:'Crusher',width:140,options:crushers.map(c=>({value:c.id,label:c.name}))},
    {key:'customerId',label:'Customer (Delivery)',width:170,options:customers.map(c=>({value:c.id,label:c.name}))},
    {key:'materialId',label:'Material',width:120,options:materials.map(m=>({value:m.id,label:m.name}))},
    {key:'transporterId',label:'Transporter',width:150,options:transporters.map(t=>({value:t.id,label:t.name}))},
  ];

  const Sel=({label,k,opts,req})=><div className="fld"><label>{label}{req&&<span className="req">*</span>}</label><window.FormSelect placeholder={'Select '+label} value={form[k]||''} onChange={v=>setF(k,v)} options={opts.map(o=>({value:o.id||o.value,label:o.name||o.label}))}/></div>;
  const calcQty=parseFloat(form.quantity)||0;const calcRate=parseFloat(form.ratePerTon)||0;
  const isAutoRec=!!form._autoGenerated;

  // ── Tab routing ──────────────────────────────────────────────────────────
  if (activeTab==='stockyard') return <StockyardMovReport companyId={companyId} isGroup={isGroup} onBack={()=>setActiveTab('transport')}/>;
  if (activeTab==='debris')   return <DebrisMovReport    companyId={companyId} isGroup={isGroup} onBack={()=>setActiveTab('transport')}/>;

  return (
    <div>
      {/* ── Tab bar — no NEW badges ── */}
      <div style={{display:'flex',gap:0,marginBottom:14,borderBottom:'2px solid var(--bdr)'}}>
        {[
          ['transport','Transporter Reports'],
          ['stockyard','Stockyard Movements'],
          ['debris',   'Debris Movements'],
        ].map(([tab,lbl])=>(
          <button key={tab} onClick={()=>setActiveTab(tab)} style={{padding:'7px 16px',border:'none',borderBottom:activeTab===tab?'3px solid var(--or)':'3px solid transparent',background:'none',cursor:'pointer',fontFamily:'var(--font)',fontSize:12.5,fontWeight:activeTab===tab?700:500,color:activeTab===tab?'var(--or)':'var(--txt2)',marginBottom:'-2px',transition:'all .12s'}}>
            {lbl}
          </button>
        ))}
      </div>

      {typeof window.TransportKPIDashboard === 'function' && <window.TransportKPIDashboard companyId={companyId} filters={applied}/>}

      <div className="ph">
        <div><h1>Transporter Reports</h1><p>Transport trip records — {autoCount} auto-generated from Sales Orders · {manualCount} manual</p></div>
        <div className="ph-act">
          <button className={`btn btn-sm ${showFP?'btn-or':'btn-wh'}`} onClick={()=>setShowFP(p=>!p)}><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg> Filters{activeFilters>0&&<span style={{background:'#fff',color:'var(--or)',borderRadius:10,padding:'0 4px',fontSize:10,fontWeight:700,marginLeft:2}}>{activeFilters}</span>}</button>
          <button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" 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-or" onClick={openAdd}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Add Entry</button>
        </div>
      </div>

      {/* Auto-Gen Engine Status */}
      <div style={{background:'#F0FDF4',border:'1px solid #86EFAC',borderRadius:'var(--r)',padding:'10px 14px',marginBottom:10,display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
        <div style={{display:'flex',alignItems:'center',gap:7,flexShrink:0}}>
          <div style={{width:7,height:7,borderRadius:'50%',background:'#16a34a',flexShrink:0}}/>
          <span style={{fontWeight:700,fontSize:11.5,color:'#15803d',letterSpacing:'0.3px'}}>AUTO GENERATION ENGINE</span>
          <span style={{fontSize:9.5,padding:'2px 6px',borderRadius:3,fontWeight:700,background:'#bbf7d0',color:'#15803d'}}>ACTIVE</span>
        </div>
        <div style={{display:'flex',gap:16,flexWrap:'wrap',fontSize:11.5,color:'#166534'}}>
          <span>Auto Generated: <strong style={{color:'#15803d'}}>{engStats?.autoCount??autoCount}</strong></span>
          <span>Manual Records: <strong style={{color:'#15803d'}}>{engStats?.manualCount??manualCount}</strong></span>
          <span>Source Sales Orders: <strong style={{color:'#15803d'}}>{engStats?.totalSalesOrders??'—'}</strong></span>
          <span>Last Sync: <strong style={{color:'#15803d'}}>{engStats?.timestamp?new Date(engStats.timestamp).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'}):'—'}</strong></span>
        </div>
        <button className="btn btn-wh btn-sm" style={{marginLeft:'auto',fontSize:10.5}} onClick={()=>{
          window.AutoTransporterEngine?.run();
          setTimeout(()=>{window.AutoTransporterEngine?.backfillStockyardEntries?.();window.AutoTransporterEngine?.backfillDebrisEntries?.();}, 800);
          window.toast&&window.toast('Engine sync + backfill triggered','ok');
        }}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" 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> Sync Now</button>
      </div>

      <window.FilterPanel show={showFP} fields={fpFields} values={fv} onChange={(k,v)=>setFv(p=>({...p,[k]:v}))} onApply={applyFP} onRefresh={load} onExport={exportCSV} onClear={clearFP}/>

      <div className="frow">
        <div className="fs"><svg className="fs-ic" width="12" height="12" 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><input value={search} onChange={e=>{setSearch(e.target.value);setPage(1);}} placeholder="Search vehicle, challan, transporter…"/></div>
        {(search||activeFilters>0)&&<button className="btn btn-gh btn-sm" onClick={clearFP}>Clear All</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>

      <div className="card"><div className="tbl-w"><table className="tbl">
        <thead><tr>
          <th style={{width:28,padding:'7px 4px'}}></th><th>DATE</th>{isGroup&&<th>OM GROUP COMPANY</th>}<th>TRANSPORTER</th>
          <th>VEHICLE NO.</th><th>CHALLAN NO.</th><th>CRUSHER (PICKUP)</th>
          <th>CUSTOMER (DELIVERY)</th>
          <th>MATERIAL</th><th>QTY</th><th>UOM</th>
          <th>RATE</th><th style={{whiteSpace:'nowrap'}}>AMT (EX. GST)</th><th style={{whiteSpace:'nowrap'}}>GST AMT</th><th style={{whiteSpace:'nowrap'}}>AMT (INC. GST)</th><th>STATUS</th>
          <th>SOURCE</th><th>LAST UPDATED</th><th>ACTIONS</th>
        </tr></thead>
        <tbody>
          {paged.length===0
            ?<tr className="empty"><td colSpan={isGroup?19:18} style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No transporter report entries found.</td></tr>
            :paged.map(te=>{
              const isOpen=expand===te.id;
              const trName=te.transporter||(te.transporterId?Store.name('transportersList',te.transporterId):'')||'—';
              const crName=te.crusherName||(te.crusherId?Store.name('crushers',te.crusherId):'')||'—';
              const coName=Store.name('companies',te.companyId)||te.companyId||'—';
              const matName=Store.name('materials',te.materialId)||te.material||'—';
              const cuName=te.customerName||(te.customerId?Store.name('customers',te.customerId):'')||'—';
              const custRec=te.customerId?Store.byId('customers',te.customerId):null;
              // Settlement Policy Engine — single source of truth, called once per row
              const _te_qty=parseFloat(te.quantity)||0;
              const _te_base=parseFloat(te.amount)||0;
              const _te_se=window.SettlementEngine?window.SettlementEngine.getAdjustedRate(te.vehicleFull,_te_qty,_te_base):{hasPolicy:false,baseGross:_te_base,adjustedGross:_te_base,marginPerUnit:0};
              const _te_hp=_te_se.hasPolicy;
              const _te_baseRate=parseFloat(te.ratePerTon)||0;
              const _te_dispRate=_te_hp&&_te_qty>0?_te_se.adjustedGross/_te_qty:_te_baseRate;
              const _te_dispAmt=_te_hp?_te_se.adjustedGross:_te_base;
              const _te_mpu=_te_hp?(_te_se.marginPerUnit||0):0;
              const _te_gstPct=parseFloat(te.gstPercent)||0;
              const _te_gstAmt=_te_dispAmt*_te_gstPct/100;
              return [
                <tr key={te.id} style={{background:isOpen?'#FFF9F5':undefined,cursor:'pointer'}} onClick={()=>setExpand(isOpen?null:te.id)}>
                  <td style={{width:28,textAlign:'center',padding:'7px 4px'}}>
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .18s',color:'var(--or)',display:'block',margin:'0 auto'}}><path d="M3 1.5L7 5L3 8.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </td>
                  <td>{window.fmtDate(te.date)}</td>
                  {isGroup&&<td><span className="bdg bg-or" style={{fontSize:10,padding:'1px 5px'}}>{coName}</span></td>}
                  <td style={{fontWeight:500}}>{trName}</td>
                  <td><span style={{fontFamily:'var(--font)',fontSize:11,background:'#F9FAFB',padding:'1px 5px',borderRadius:3}}>{te.vehicleFull||'—'}</span></td>
                  <td style={{fontFamily:'var(--font)',fontSize:11.5}}>{te.challanNumber||'—'}</td>
                  <td style={{fontSize:12}}>{crName}</td>
                  <td style={{fontSize:12}}>{cuName}</td>
                  <td style={{fontSize:12}}>{matName}</td>
                  <td style={{fontWeight:600}}>{window.formatQuantity(te.quantity)}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{te.unit||'MT'}</td>
                  <td>{_te_hp?(<span style={{display:'flex',flexDirection:'column',gap:1}}><span style={{color:'var(--txt2)',fontSize:11}}>{window.fmtCur(_te_baseRate)}</span><span style={{fontSize:10,fontWeight:700,color:'#6D28D9',whiteSpace:'nowrap'}}>+{window.fmtCur(_te_mpu)} → {window.fmtCur(_te_dispRate)}</span></span>):window.fmtCur(te.ratePerTon)}</td>
                  <td style={{fontWeight:600}}>{_te_hp?(<span style={{display:'flex',flexDirection:'column',gap:1}}><span style={{color:'var(--txt2)',fontSize:11}}>{window.fmtCur(_te_base)}</span><span style={{fontWeight:700,color:'#6D28D9'}}>{window.fmtCur(_te_dispAmt)}</span></span>):window.fmtCur(te.amount)}</td>
                  <td style={{color:'var(--txt2)',fontSize:11.5}}>{_te_gstPct>0?window.fmtCur(_te_gstAmt):'₹0'}</td>
                  <td style={{fontWeight:700,color:'var(--ok)'}}>{window.fmtCur(_te_dispAmt+_te_gstAmt)}</td>
                  <td><window.Badge v={te.status}/></td>
                  <td><SourceBadge src={te.source}/></td>
                  <td style={{fontSize:11,color:'var(--txt2)'}}>{te.lastUpdated||te._lastSyncTimestamp?.slice(0,10)||'—'}</td>
                  <td onClick={e=>e.stopPropagation()}><div className="ra">
                    <button className="btn btn-wh btn-sm" onClick={()=>openEdit(te)}>Edit</button>
                    <button className="btn btn-rd btn-sm" onClick={()=>setDelId(te.id)}>Delete</button>
                  </div></td>
                </tr>,
                isOpen&&(
                  <tr key={te.id+'-exp'}>
                    <td colSpan={isGroup?17:16} style={{padding:0,background:'#FFF9F5',borderTop:'2px solid var(--or-bdr)'}}>
                      <div className="rg-3" style={{padding:'16px 18px 18px'}}>
                        <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
                          <div style={{fontWeight:700,fontSize:11,color:'var(--or)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:'2px solid #FEF3E8',paddingBottom:6}}>Transport Information</div>
                          {[['Transporter',trName],['Vehicle No.',te.vehicleFull||'—'],['Challan No.',te.challanNumber||'—'],['Date',window.fmtDate(te.date)],['Status',te.status||'—'],['Source Type',te.source||'Manual Entry'],['Created',te._creationTimestamp?new Date(te._creationTimestamp).toLocaleString():'—'],['Last Updated',te.lastUpdated||te._lastSyncTimestamp?.slice(0,10)||'—']].map(([lbl,val])=>(
                            <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #FEF3E8',fontSize:11.5}}>
                              <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                              <span style={{fontWeight:500,textAlign:'right',color:'var(--txt)',marginLeft:8}}>{val}</span>
                            </div>
                          ))}
                        </div>
                        <div style={{display:'flex',flexDirection:'column',gap:12}}>
                          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px',flex:1}}>
                            <div style={{fontWeight:700,fontSize:11,color:'#D97706',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:'2px solid #FEF3C7',paddingBottom:6}}>Pickup Information</div>
                            {[['Crusher (Pickup)',crName],['Source Company',coName],['Material',matName],['Quantity',`${window.formatQuantity(te.quantity)} ${te.unit||'MT'}`]].map(([lbl,val])=>(
                              <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #FEF3C7',fontSize:11.5}}>
                                <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                                <span style={{fontWeight:500,textAlign:'right',color:'var(--txt)',marginLeft:8}}>{val}</span>
                              </div>
                            ))}
                          </div>
                          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px',flex:1}}>
                            <div style={{fontWeight:700,fontSize:11,color:'#15803D',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:'2px solid #DCFCE7',paddingBottom:6}}>Delivery Information</div>
                            {[['Customer (Delivery)',cuName],['Destination Company',coName],['Delivery Address',custRec?.address||'—']].map(([lbl,val])=>(
                              <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #DCFCE7',fontSize:11.5}}>
                                <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                                <span style={{fontWeight:500,textAlign:'right',color:'var(--txt)',marginLeft:8}}>{val}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                        <div style={{display:'flex',flexDirection:'column',gap:12}}>
                          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
                            <div style={{fontWeight:700,fontSize:11,color:'#1D4ED8',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:'2px solid #DBEAFE',paddingBottom:6}}>Rate &amp; Value</div>
                            {[
                              ['Quantity',`${window.formatQuantity(te.quantity)} ${te.unit||'MT'}`],
                              ['Base Rate / Ton',`₹${window.fmtNum(_te_baseRate)}`],
                              ...(_te_hp?[['Settlement Margin',`+₹${window.fmtNum(_te_mpu)}/MT · ${_te_se.policyName||'Policy'}`],['Final Rate / Ton',`₹${window.fmtNum(_te_dispRate)}`]]:[]),
                              [_te_hp?'Base Amount':'Amount',window.fmtCur(_te_base)],
                              ...(_te_hp?[['Settlement Amount',window.fmtCur(_te_dispAmt)]]:[]),
                            ].map(([lbl,val])=>(
                              <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #DBEAFE',fontSize:11.5}}>
                                <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                                <span style={{fontWeight:600,textAlign:'right',color:lbl.includes('Settlement')||lbl.includes('Final')?'#6D28D9':'#1D4ED8',marginLeft:8}}>{val}</span>
                              </div>
                            ))}
                            <div style={{marginTop:8,padding:'8px 10px',background:_te_hp?'#F5F3FF':'#EFF6FF',borderRadius:4,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                              <span style={{fontSize:10.5,color:_te_hp?'#6D28D9':'#1D4ED8',fontWeight:700,letterSpacing:'0.3px'}}>{_te_hp?'SETTLEMENT AMOUNT':'TRANSPORT VALUE'}</span>
                              <span className="kpi-val" style={{fontSize:16,fontWeight:700,color:_te_hp?'#6D28D9':'#1D4ED8',display:'inline-block'}}>{window.fmtCur(_te_dispAmt)}</span>
                            </div>
                            {_te_hp&&_te_se&&_te_se.policy&&(
                              <div style={{marginTop:8,padding:'7px 10px',background:'#F5F3FF',borderRadius:4,border:'1px solid #DDD6FE',fontSize:11}}>
                                <div style={{fontWeight:700,color:'#6D28D9',marginBottom:3}}>Policy: {_te_se.policyName}</div>
                                <div style={{display:'flex',gap:10,flexWrap:'wrap',color:'#5B21B6'}}>
                                  <span>Margin: {_te_se.policy.marginType==='Per Ton'?`₹${_te_se.marginValue}/MT`:_te_se.policy.marginType==='Percentage'?`${_te_se.marginValue}%`:`₹${_te_se.marginValue} fixed`}</span>
                                  <span>Receiving: {Store.name('companies',_te_se.receivingCompanyId)||'—'}</span>
                                </div>
                              </div>
                            )}
                          </div>
                          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
                            <div style={{fontWeight:700,fontSize:11,color:'#6B21A8',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',borderBottom:'2px solid #EDE9FE',paddingBottom:6}}>Linked Records</div>
                            {(()=>{
                              const _so  = te._salesId ? Store.byId('salesOrders', te._salesId)||{} : {};
                              const _soNum = _so.soNumber||_so.orderNumber||_so.challanNumber||(_so.id?_so.id.slice(0,10).toUpperCase():null);
                              const _soCustomer = _so.customerId ? Store.name('customers',_so.customerId)||'—' : (te.customerName||'—');
                              const _soStatus   = _so.status||'—';
                              const _settled = (Store.all('settlementRecords')||[]).find(s=>s.transportEntryId===te.id);
                              const _settlementStatus = _settled ? (_settled.status||'Settled') : (te._settled ? 'Settled' : 'Not Settled');
                              const _settlementColor  = _settled||te._settled ? 'var(--ok)' : 'var(--txt3)';
                              return [
                                ['Sales Order',    _soNum||(_so.id?'#'+_so.id.slice(0,8).toUpperCase():'—')],
                                ['Customer',       _soCustomer],
                                ['Crusher (Pickup)', crName],
                                ['SO Status',      _soStatus],
                                ['Settlement',     _settlementStatus],
                                ['Origin',         te._autoGenerated?'Auto — Sales Order':'Manual Entry'],
                              ].map(([lbl,val])=>{
                                const _c = lbl==='Settlement' ? _settlementColor : lbl==='SO Status'&&val==='Delivered' ? 'var(--ok)' : val==='—'?'var(--txt3)':'var(--txt)';
                                return (
                                  <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #EDE9FE',fontSize:11.5}}>
                                    <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                                    <span style={{fontWeight:lbl==='Settlement'||lbl==='Customer'||lbl==='Sales Order'?600:500,textAlign:'right',marginLeft:8,color:_c,fontFamily:'var(--font)',fontSize:11.5,maxWidth:'55%',wordBreak:'break-word'}}>{val}</span>
                                  </div>
                                );
                              });
                            })()}
                          </div>
                        </div>
                      </div>
                      {te._autoGenerated&&(
                        <div className="rg-2" style={{padding:'0 18px 16px'}}>
                          <div style={{background:'#F0FDF4',border:'1px solid #86EFAC',borderRadius:6,padding:'12px 14px'}}>
                            <div style={{fontWeight:700,fontSize:11,color:'#15803D',marginBottom:10,textTransform:'uppercase',letterSpacing:'.5px'}}>Auto-Generation Match Signals</div>
                            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:te._matchScore!=null?10:0}}>
                              {[['Challan Match',te._matchedChallan],['Vehicle Match',te._matchedVehicle],['Material Match',te._matchedMaterial],['Date Match',te._matchedDate]].map(([lbl,ok])=>(
                                <div key={lbl} style={{display:'flex',alignItems:'center',gap:7,padding:'6px 8px',borderRadius:4,background:ok?'#DCFCE7':'#F3F4F6'}}>
                                  <span style={{display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,width:16}}>{ok?<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>:<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#D1D5DB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/></svg>}</span>
                                  <span style={{fontSize:11.5,fontWeight:ok?600:400,color:ok?'#15803D':'#9CA3AF'}}>{lbl}</span>
                                </div>
                              ))}
                            </div>
                            {te._matchScore!=null&&(
                              <div style={{padding:'6px 10px',background:'#fff',borderRadius:4,display:'flex',justifyContent:'space-between',alignItems:'center',border:'1px solid #86EFAC'}}>
                                <span style={{fontSize:11,color:'#15803D',fontWeight:700,letterSpacing:'0.3px'}}>MATCH CONFIDENCE</span>
                                <span style={{fontSize:12,fontWeight:700,color:'#15803D'}}>{window.AutoTransporterEngine?.priorityLabel?.(te._matchPriority)||String(te._matchScore)}</span>
                              </div>
                            )}
                          </div>
                          <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
                            <div style={{fontWeight:700,fontSize:11,color:'var(--txt2)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}}>Audit Information</div>
                            {[['Created On',te._creationTimestamp?new Date(te._creationTimestamp).toLocaleString():'—'],['Last Sync',te._lastSyncTimestamp?new Date(te._lastSyncTimestamp).toLocaleString():'—'],['Last Updated',te.lastUpdated||'—'],['Record ID',te.id?.slice(0,14)||'—']].map(([lbl,val])=>(
                              <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px solid #E5E7EB',fontSize:11.5}}>
                                <span style={{color:'var(--txt2)',flexShrink:0}}>{lbl}</span>
                                <span style={{fontWeight:500,textAlign:'right',color:'var(--txt)',marginLeft:8,fontFamily:'var(--font)',fontSize:lbl==='Record ID'?10.5:11.5}}>{val}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      {!te._autoGenerated&&(
                        <div style={{padding:'0 18px 16px'}}>
                          <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'12px 14px'}}>
                            <div style={{fontWeight:700,fontSize:11,color:'var(--txt2)',marginBottom:10,textTransform:'uppercase',letterSpacing:'.5px'}}>Audit Information</div>
                            <div className="rg-4">
                              {[['Source Type',te.source||'Manual Entry'],['Created',te._creationTimestamp?new Date(te._creationTimestamp).toLocaleString():'—'],['Last Updated',te.lastUpdated||'—'],['Record ID',te.id?.slice(0,14)||'—']].map(([lbl,val])=>(
                                <div key={lbl}>
                                  <div style={{fontSize:10,color:'var(--txt2)',marginBottom:2,textTransform:'uppercase',letterSpacing:'0.4px'}}>{lbl}</div>
                                  <div style={{fontSize:12,fontWeight:500,color:'var(--txt)',fontFamily:'var(--font)'}}>{val}</div>
                                </div>
                              ))}
                            </div>
                          </div>
                        </div>
                      )}
                    </td>
                  </tr>
                )
              ];
            })
          }
        </tbody>
        {filtered.length>0&&<tfoot>
          <tr style={{background:'var(--or-lt)',position:'sticky',bottom:0,zIndex:2}}>
            <td style={{borderTop:'2px solid var(--or-bdr)',padding:'9px 8px'}}></td>
            <td colSpan={isGroup?7:6} style={{padding:'9px 14px',fontSize:12,fontWeight:700,color:'var(--txt2)',whiteSpace:'nowrap',borderTop:'2px solid var(--or-bdr)'}}>
              TOTALS — {tpTotals.trips} Trip{tpTotals.trips!==1?'s':''}
            </td>
            {/* MATERIAL col — empty */}
            <td style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* QTY col — total quantity */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap'}}>{window.formatQuantity(tpTotals.qty)}</td>
            {/* UOM col — empty */}
            <td style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* RATE col — empty */}
            <td style={{borderTop:'2px solid var(--or-bdr)'}}></td>
            {/* AMT EX. GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap'}}>{tpTotals.baseAmt!==tpTotals.amt?(<span style={{display:'flex',flexDirection:'column',gap:1}}><span style={{color:'var(--txt2)',fontSize:11,fontWeight:500}}>{window.fmtCur(tpTotals.baseAmt)}</span><span style={{color:'#6D28D9',fontWeight:700}}>{window.fmtCur(tpTotals.amt)}</span></span>):<span style={{color:'var(--txt)'}}>{window.fmtCur(tpTotals.amt)}</span>}</td>
            {/* GST AMT */}
            <td style={{padding:'9px 14px',fontWeight:600,fontSize:12,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--txt2)'}}>{window.fmtCur(tpTotals.gstAmt)}</td>
            {/* AMT INC. GST */}
            <td style={{padding:'9px 14px',fontWeight:700,fontSize:13,borderTop:'2px solid var(--or-bdr)',whiteSpace:'nowrap',color:'var(--or)'}}>{window.fmtCur(tpTotals.amtWithGST)}</td>
            {/* STATUS + SOURCE + LAST UPDATED + ACTIONS */}
            <td colSpan={4} style={{borderTop:'2px solid var(--or-bdr)'}}></td>
          </tr>
        </tfoot>}
      </table></div></div>
      {totalPgs>1&&<div className="pag"><button className="pg-b" onClick={()=>setPage(1)} disabled={page===1}>«</button><button className="pg-b" onClick={()=>setPage(p=>p-1)} disabled={page===1}>‹</button><span className="pg-inf">Page {page} of {totalPgs}</span><button className="pg-b" onClick={()=>setPage(p=>p+1)} disabled={page===totalPgs}>›</button><button className="pg-b" onClick={()=>setPage(totalPgs)} disabled={page===totalPgs}>»</button></div>}

      {modal&&(
        <div className="mbg">
          <div className="mod mod-lg" style={{maxHeight:'92vh'}}>
            <div className="mod-hd">
              <div>
                <h2>{editId?'Edit':'Add'} Transporter Report Entry</h2>
                {isAutoRec&&<div style={{fontSize:11,color:'var(--or)',marginTop:2}}>Auto-generated from Purchase — editing will mark as "Updated Manually"</div>}
              </div>
              <button className="mod-x" onClick={()=>setModal(false)}>×</button>
            </div>
            <form onSubmit={handleSave}>
              <div className="mod-bd">
                {isGroup&&<window.GroupCompanyField value={form.companyId} onChange={v=>setForm(p=>({...p,companyId:v}))}/>}
                <div style={{marginBottom:16}}>
                  <SH title="Trip Details"/>
                  <div className="fg">
                    <div className="fld">
                      <label>Transporter Name <span className="req">*</span></label>
                      <window.SearchableSelect
                        options={tpTmActive.map(t=>({value:t.id,label:t.name}))}
                        value={form.transporterMasterId||''}
                        onChange={(v,label)=>setForm(p=>({...p,transporterMasterId:v,transporter:label||'',vehicleFull:''}))}
                        placeholder="Search transporter…"
                        noOptionsMsg={tpTmActive.length===0?'No active transporters — add in Transporter Master first':'No transporter matches'}/>
                      {tpTmActive.length===0&&<div style={{fontSize:10.5,color:'var(--warn)',marginTop:3}}><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',flexShrink:0,marginRight:4}}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>No active transporters found.</div>}
                    </div>
                    <div className="fld"><label>Date <span className="req">*</span></label><input className="inp" type="date" value={form.date||''} onChange={e=>setF('date',e.target.value)} required/></div>
                    <div className="fld">
                      <label>Vehicle Number <span className="req">*</span>{tpTmVehicles.length>0&&<span style={{fontSize:10,color:'var(--txt2)',fontWeight:400,marginLeft:4}}>({tpTmVehicles.length} vehicles)</span>}</label>
                      <window.SearchableSelect
                        options={tpTmVehicles.map(v=>({value:v.vehicleNumber,label:v.vehicleNumber+(v.vehicleType?' ('+v.vehicleType+')':'')}))} 
                        value={form.vehicleFull||''}
                        onChange={v=>setF('vehicleFull',v)}
                        placeholder={!form.transporterMasterId?'Select a transporter first…':tpTmVehicles.length===0?'No active vehicles for this transporter':'Search vehicle number…'}
                        noOptionsMsg={!form.transporterMasterId?'Select a transporter first':'No vehicles match'}
                        inputStyle={{fontFamily:'var(--font)',fontWeight:600}}/>
                      {form.transporterMasterId&&tpTmVehicles.length===0&&<div style={{fontSize:10.5,color:'var(--warn)',marginTop:3}}>No active vehicles found for this transporter.</div>}
                    </div>
                    <div className="fld"><label>Status</label><window.FormSelect value={form.status||'Delivered'} onChange={v=>setF('status',v)} options={['Pending','In Transit','Delivered','Cancelled'].map(s=>({value:s,label:s}))}/></div>
                    <div className="fld"><label>Challan Number</label><input className="inp" value={form.challanNumber||''} onChange={e=>setF('challanNumber',e.target.value)} placeholder="TC-0001"/></div>
                  </div>
                </div>
                <div style={{marginBottom:16}}>
                  <SH title="Route &amp; Material"/>
                  <div className="fg">
                    <Sel label="Crusher (Pickup Point)" k="crusherId" opts={crushers} req/>
                    <Sel label="Customer (Delivery Point)" k="customerId" opts={customers}/>
                    <Sel label="Material" k="materialId" opts={materials} req/>
                    <div className="fld"><label>Unit</label><window.FormSelect value={form.unit||'MT'} onChange={v=>setF('unit',v)} options={[{value:'MT',label:'MT'},{value:'Ton',label:'Ton'},{value:'CUM',label:'CUM'},{value:'CFT',label:'CFT'}]}/></div>
                    <div className="fld"><label>Quantity <span className="req">*</span></label><input className="inp" type="number" value={form.quantity||''} onChange={e=>setF('quantity',e.target.value)} placeholder="0.000" min="0" step="0.001" required/></div>
                    <div className="fld"><label>Rate Per Ton (₹) <span className="req">*</span></label><input className="inp" type="number" value={form.ratePerTon||''} onChange={e=>setF('ratePerTon',e.target.value)} placeholder="0.00" min="0" step="0.01" required/>{form._rateAutoFilled?<span style={{fontSize:10.5,color:'#3B82F6',display:'block',marginTop:2}}>Applicable rate for {window.fmtDate?window.fmtDate(form.date):form.date} — source: {form.rateEffectiveFrom||'open'} → {form.rateEffectiveTo||'Open'}</span>:(form._rateNote?<span style={{fontSize:10.5,color:'var(--warn)',display:'block',marginTop:2}}>{form._rateNote}</span>:(form._rateManualOverride?<span style={{fontSize:10.5,color:'var(--txt2)',display:'block',marginTop:2}}>Manual rate — will be stored as the applied rate for this trip.</span>:null))}</div>
                  </div>
                </div>
                {isAutoRec&&(
                  <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:'var(--r)',padding:'10px 14px',marginBottom:12}}>
                    <div style={{fontWeight:700,fontSize:10.5,marginBottom:6,color:'var(--txt2)',textTransform:'uppercase'}}>System Information (Read Only)</div>
                    <div style={{display:'flex',gap:16,flexWrap:'wrap',fontSize:11.5,color:'var(--txt2)'}}>
                      <span>Source Sales Order: <code style={{fontSize:10.5,background:'#F3F4F6',padding:'0 4px',borderRadius:3}}>{(form._salesId||form._purchaseId||'').slice(0,14)}…</code></span>
                      <span>Auto-Generated: <strong>{form._creationTimestamp?.slice(0,10)||'—'}</strong></span>
                    </div>
                  </div>
                )}
                <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'14px 16px',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                  <div>
                    <div style={{fontSize:11.5,color:'var(--txt2)',marginBottom:3}}>Calculated Amount</div>
                    <div className="kpi-val" style={{fontSize:22,fontWeight:700,color:'var(--or)'}}>{window.fmtCur(form.amount||0)}</div>
                    <div style={{fontSize:11,color:'var(--txt2)',marginTop:2}}>{window.formatQuantity(calcQty)} × ₹{calcRate.toFixed(2)}/ton</div>
                  </div>
                  <div style={{width:60,height:60,borderRadius:'50%',background:'var(--or-lt)',display:'flex',alignItems:'center',justifyContent:'center'}}>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--or)" strokeWidth="2"><rect x="1" y="3" width="15" height="13" rx="1"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
                  </div>
                </div>
              </div>
              <div className="mod-ft"><button type="button" className="btn btn-wh" onClick={()=>setModal(false)}>Cancel</button><button type="submit" className="btn btn-or">{editId?'Update':'Create Entry'}</button></div>
            </form>
          </div>
        </div>
      )}
      {delId&&<window.Confirm onOk={handleDelete} onCancel={()=>setDelId(null)}/>}
    </div>
  );
}

// ============================================================
// TRANSPORTERS LIST
// ============================================================
function TransportersListPage() {
  return (
    <window.CRUDPage title="Transporter Companies" subtitle="Registered transport companies" entityKey="transportersList" searchFields={['name','mobile']}
      columns={[{key:'name',label:'Transporter Name',render:v=><strong>{v}</strong>},{key:'mobile',label:'Mobile'},{key:'vehicleCount',label:'Vehicles',number:true},{key:'status',label:'Status',badge:true}]}
      filters={[{key:'status',label:'Status',options:[{value:'Active',label:'Active'},{value:'Inactive',label:'Inactive'}]}]}
      fields={[{key:'name',label:'Transporter Name',required:true,full:true},{key:'mobile',label:'Mobile Number',type:'tel'},{key:'vehicleCount',label:'Number of Vehicles',type:'number',min:'0'},{key:'status',label:'Status',type:'select',default:'Active',options:[{value:'Active',label:'Active'},{value:'Inactive',label:'Inactive'}]}]}
      addLabel="Add Transporter"
    />
  );
}

// ============================================================
// TRANSPORT RATES PAGE
// ============================================================
function RatesPage() {
  window.useStoreSync();
  const {companyId}=tCtx(AppCtx);
  const [items,setItems]=tSt([]);const [search,setSearch]=tSt('');const [fCrusher,setFCrusher]=tSt('');const [fCustomer,setFCustomer]=tSt('');const [fMat,setFMat]=tSt('');const [fDestType,setFDestType]=tSt('');const [page,setPage]=tSt(1);const [modal,setModal]=tSt(false);const [editId,setEditId]=tSt(null);const [delId,setDelId]=tSt(null);
  const [form,setForm]=tSt({});
  const PER=50;
  const [scan,setScan]=tSt(null);
  function runScan(){const T=window.TransportRateResolver;if(!T)return;setScan(T.buildRepairPlan({companyId:companyId&&companyId!=='group'?companyId:''}));}
  function scanCSV(){const T=window.TransportRateResolver;const blob=new Blob(['\uFEFF'+T.repairPlanCSV(scan)],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='transport_rate_integrity_scan.csv';a.click();}
  function applyScan(){const T=window.TransportRateResolver;if(!window.confirm('Restore '+scan.affected+' transport transaction(s) to the rate that was effective on their own transaction date?\n\nEach change keeps a reversible repair record with its pre-repair rate and amount.'))return;const res=T.applyRepairPlan(scan);setScan(null);window.toast&&window.toast(res.repaired+' record(s) repaired, '+res.skipped+' skipped','ok');}
  const DEST_TYPES=['Customer','Stockyard','Crusher','RMC Plant','Vendor','Disposal Site','Other'];
  const DEST_TYPE_BADGE={Customer:'bg-bl',Stockyard:'bg-gn',Vendor:'bg-pu','RMC Plant':'bg-or',Crusher:'bg-gy','Disposal Site':'bg-yw',Other:'bg-yw'};
  const crushers=window.filterAssigned(Store.all('crushers'),companyId);const customers=window.filterAssigned(Store.all('customers'),companyId);const materials=window.filterAssigned(Store.all('materials'),companyId);
  const vendors=window.filterAssigned(Store.all('vendors'),companyId);
  const stockyards=window.filterAssigned(Store.all('stockyards'),companyId);
  const rmcPlants=Store.all('rmcPlants',companyId)||[];
  tEf(()=>{setItems(Store.all('transportRates',companyId));},[companyId]);
  function load(){setItems(Store.all('transportRates',companyId));}
  function crName(r){return r.crusherName||(r.crusherId?Store.name('crushers',r.crusherId):'—');}
  function cuName(r){return r.destinationName||r.customerName||(r.customerId?Store.name('customers',r.customerId):'—');}
  function maName(r){return r.materialName||(r.materialId?Store.name('materials',r.materialId):'—');}
  function rDestType(r){return r.destinationType||'Customer';}
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const destOptions=tMemo(()=>{const dt=form.destinationType;if(dt==='Customer')return customers.map(c=>({value:c.id,label:c.name}));if(dt==='Stockyard')return stockyards.map(s=>({value:s.id,label:s.name}));if(dt==='Crusher')return crushers.map(c=>({value:c.id,label:c.name}));if(dt==='RMC Plant')return rmcPlants.map(r=>({value:r.id,label:r.name}));if(dt==='Vendor')return vendors.map(v=>({value:v.id,label:v.name}));return[];},[form.destinationType,customers,stockyards,crushers,rmcPlants,vendors]);
  const allCrushers=[...new Set(items.map(r=>crName(r)))].sort();
  const allCustomers=[...new Set(items.map(r=>cuName(r)))].sort();
  const allMats=[...new Set(items.map(r=>maName(r)))].sort();
  const filtered=tMemo(()=>items.filter(r=>{
    const cn=crName(r),cu=cuName(r),mn=maName(r),dt=rDestType(r);
    if(search){const q=search.toLowerCase();if(![cn,cu,mn,dt].some(s=>s.toLowerCase().includes(q)))return false;}
    if(fCrusher&&cn!==fCrusher)return false;if(fCustomer&&cu!==fCustomer)return false;if(fMat&&mn!==fMat)return false;
    if(fDestType&&dt!==fDestType)return false;
    return true;
  }),[items,search,fCrusher,fCustomer,fMat,fDestType]);
  const paged=filtered.slice((page-1)*PER,page*PER);const totalPgs=Math.ceil(filtered.length/PER);
  function openAdd(){setForm({effectiveFrom:new Date().toISOString().slice(0,10),effectiveTo:'2026-12-31',destinationType:'Customer'});setEditId(null);setModal(true);}
  function openEdit(r){setForm({...r});setEditId(r.id);setModal(true);}
  function setF(k,v){setForm(p=>({...p,[k]:v}));}
  function handleSave(e){e.preventDefault();const destName=form.destinationName||form.customerName||'';let data={...form,crusherName:form.crusherName||'',destinationType:form.destinationType||'Customer',destinationName:destName,customerName:destName,materialName:form.materialName||'',status:form.status||'Active'};
    const TRR=window.TransportRateResolver;
    if(TRR){
      const v=TRR.validateRate(data,editId||null);
      if(!v.ok){window.toast&&window.toast(v.errors[0],'er');return;}
      if(v.warnings.length&&!window.confirm(v.warnings[0]+'\n\nContinue saving the rate master?'))return;
      data=TRR.stampAudit(data,editId?Store.byId('transportRates',editId):null,editId?'UPDATE':'CREATE');
    }
    if(editId){Store.update('transportRates',editId,data);}else{Store.add('transportRates',data);}
    // NOTE: no cascade. A rate-master change never mutates historical transport
    // transactions — they keep the rate that was applied on their own date.
    setModal(false);load();window.toast&&window.toast(editId?'Rate updated — historical transactions unchanged':'Rate created','ok');}
  function handleDelete(){const _r=Store.byId('transportRates',delId);const used=_r&&window.TransportRateResolver?window.TransportRateResolver.txnsInPeriod(_r,window.TransportRateResolver.dateOnly(_r.effectiveFrom),window.TransportRateResolver.dateOnly(_r.effectiveTo)).length:0;
    if(used>0){Store.update('transportRates',delId,{status:'Archived',archivedAt:new Date().toISOString()});Store.addLog('UPDATE','Transport Rate','Archived rate (used by '+used+' transport transaction(s)) — their applied rates are retained.');window.toast&&window.toast('Rate archived — '+used+' historical transaction(s) keep their applied rate','ok');}
    else{Store.del('transportRates',delId);Store.addLog('DELETE','Transport Rate','Deleted unused rate');window.toast&&window.toast('Deleted','ok');}
    setDelId(null);load();}
  function exportCSV(){const hdr='Crusher,Destination Type,Destination,Material,Rate Per Ton,Effective From,Effective To,Status';const rows=filtered.map((r)=>`"${crName(r)}","${rDestType(r)}","${cuName(r)}","${maName(r)}","${r.ratePerTon}","${r.effectiveFrom||''}","${r.effectiveTo||''}","${r.status||'Active'}"`).join('\n');const blob=new Blob([hdr+'\n'+rows],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='transport_rates.csv';a.click();window.toast&&window.toast('Exported','ok');}
  return (
    <div>
      <div className="ph"><div><h1>Transport Rates</h1><p>Universal rate matrix: crusher pickup → any destination — {filtered.length} rates</p></div><div className="ph-act"><button className="btn btn-wh btn-sm" onClick={runScan} title="Check every transport transaction against the rate that was effective on its own date">Rate Integrity Scan</button><button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" 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-or" onClick={openAdd}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Create Rate</button></div></div>
      <div className="frow" style={{flexWrap:'wrap'}}>
        <div className="fs"><svg className="fs-ic" width="12" height="12" 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><input value={search} onChange={e=>{setSearch(e.target.value);setPage(1);}} placeholder="Search crusher, customer, material…"/></div>
        <window.FiltSelect placeholder="All Crushers" value={fCrusher} onChange={v=>{setFCrusher(v);setPage(1);}} options={allCrushers.map(c=>({value:c,label:c}))}/>
        <window.FiltSelect placeholder="All Types" value={fDestType} onChange={v=>{setFDestType(v);setPage(1);}} options={DEST_TYPES.map(t=>({value:t,label:t}))}/>
        <window.FiltSelect placeholder="All Destinations" value={fCustomer} onChange={v=>{setFCustomer(v);setPage(1);}} options={allCustomers.map(c=>({value:c,label:c}))}/>
        <window.FiltSelect placeholder="All Materials" value={fMat} onChange={v=>{setFMat(v);setPage(1);}} options={allMats.map(m=>({value:m,label:m}))}/>
        {(search||fCrusher||fCustomer||fMat||fDestType)&&<button className="btn btn-gh btn-sm" onClick={()=>{setSearch('');setFCrusher('');setFCustomer('');setFMat('');setFDestType('');setPage(1);}}>Clear</button>}
        <span className="f-cnt">{filtered.length} rates</span>
      </div>
      <div className="card"><div className="tbl-w"><table className="tbl"><thead><tr><th style={{width:40,textAlign:'center'}}>SR.</th><th>CRUSHER (PICKUP)</th><th>TYPE</th><th>DESTINATION</th><th>MATERIAL</th><th>RATE PER TON (₹)</th><th>EFFECTIVE FROM</th><th>EFFECTIVE TO</th><th>STATE</th><th>ACTIONS</th></tr></thead><tbody>
        {paged.length===0?<tr className="empty"><td colSpan="10" style={{textAlign:'center',padding:36,color:'var(--txt2)'}}>No rates found</td></tr>
        :paged.map((r,idx)=>(
          <tr key={r.id}>
            <td style={{textAlign:'center',color:'var(--txt2)',fontWeight:500}}>{(page-1)*PER+idx+1}</td>
            <td style={{fontWeight:500}}>{crName(r)}</td>
            <td><span className={`bdg ${DEST_TYPE_BADGE[rDestType(r)]||'bg-gy'}`} style={{fontSize:9.5,padding:'2px 7px',whiteSpace:'nowrap'}}>{rDestType(r)}</span></td>
            <td style={{fontWeight:500}}>{cuName(r)}</td>
            <td><span className="bdg bg-or" style={{fontSize:10.5}}>{maName(r)}</span></td>
            <td style={{fontWeight:700,color:'var(--or)',fontSize:13}}>₹{window.fmtNum(r.ratePerTon)}/Ton</td>
            <td style={{fontSize:12}}>{r.effectiveFrom?window.fmtDate(r.effectiveFrom):'—'}</td>
            <td style={{fontSize:12,color:'var(--txt2)'}}>{r.effectiveTo?window.fmtDate(r.effectiveTo):'Open'}</td>
            <td>{(()=>{const TRR=window.TransportRateResolver;const st=r.status||'Active';if(st==='Archived')return <span className="bdg bg-nd" style={{fontSize:9.5}}>Archived</span>;const live=TRR?TRR.isEffectiveOn(r,TRR.todayBusiness()):true;const future=TRR&&r.effectiveFrom&&TRR.dateOnly(r.effectiveFrom)>TRR.todayBusiness();return <span className={'bdg '+(live?'bg-ok':future?'bg-or':'bg-nd')} style={{fontSize:9.5}}>{live?'Active today':future?'Scheduled':'Expired'}</span>;})()}</td>
            <td><div className="ra"><button className="btn btn-wh btn-sm" onClick={()=>openEdit(r)}>Edit</button><button className="btn btn-rd btn-sm" onClick={()=>setDelId(r.id)}>Delete</button></div></td>
          </tr>
        ))}
      </tbody></table></div></div>
      {totalPgs>1&&<div className="pag"><button className="pg-b" onClick={()=>setPage(1)} disabled={page===1}>«</button><button className="pg-b" onClick={()=>setPage(p=>p-1)} disabled={page===1}>‹</button><span className="pg-inf">Page {pg} of {totalPgs}</span><button className="pg-b" onClick={()=>setPage(p=>p+1)} disabled={page===totalPgs}>›</button><button className="pg-b" onClick={()=>setPage(totalPgs)} disabled={page===totalPgs}>»</button></div>}
      {modal&&(
        <div className="mbg">
          <div className="mod mod-md">
            <div className="mod-hd"><h2>{editId?'Edit':'Create'} Transport Rate</h2><button className="mod-x" onClick={()=>setModal(false)}>×</button></div>
            <form onSubmit={handleSave}>
              <div className="mod-bd" style={{display:'flex',flexDirection:'column',gap:10}}>
                <div className="fld"><label>Crusher (Pickup Point) <span className="req">*</span></label><input className="inp" list="cr-list" value={form.crusherName||''} onChange={e=>setF('crusherName',e.target.value)} required placeholder="Select or type crusher name"/><datalist id="cr-list">{crushers.map(c=><option key={c.id} value={c.name}/>)}</datalist></div>
                <div className="fg">
                  <div className="fld"><label>Destination Type <span className="req">*</span></label><window.FormSelect placeholder="Select Type" value={form.destinationType||''} onChange={v=>setForm(p=>({...p,destinationType:v,destinationName:'',destinationId:'',customerName:''}))} options={DEST_TYPES.map(t=>({value:t,label:t}))}/></div>
                  <div className="fld"><label>Destination{form.destinationType?<span style={{fontSize:10,color:'var(--txt3)',fontWeight:400,marginLeft:4}}>({form.destinationType})</span>:null} <span className="req">*</span></label>
                    {(!form.destinationType||form.destinationType==='Other'||form.destinationType==='Disposal Site')
                      ?<input className="inp" value={form.destinationName||''} onChange={e=>setForm(p=>({...p,destinationName:e.target.value,customerName:e.target.value}))} required={!!form.destinationType} disabled={!form.destinationType} placeholder={!form.destinationType?'Select Destination Type first':form.destinationType==='Other'?'Enter destination name (e.g. Port Warehouse Goa)':'Enter disposal site name'}/>
                      :<><input className="inp" list="dest-dyn-list" value={form.destinationName||''} onChange={e=>{const name=e.target.value;const match=destOptions.find(o=>o.label===name);setForm(p=>({...p,destinationName:name,destinationId:match?match.value:'',customerName:name}));}} required placeholder={'Search '+form.destinationType+'...'}/><datalist id="dest-dyn-list">{destOptions.map(o=><option key={o.value} value={o.label}/>)}</datalist></>
                    }
                  </div>
                </div>
                <div className="fld"><label>Material <span className="req">*</span></label><input className="inp" list="ma-list" value={form.materialName||''} onChange={e=>setF('materialName',e.target.value)} required placeholder="Select or type material name"/><datalist id="ma-list">{materials.map(m=><option key={m.id} value={m.name}/>)}</datalist></div>
                <div className="fld"><label>Rate Per Ton (₹) <span className="req">*</span></label><input className="inp" type="number" value={form.ratePerTon||''} onChange={e=>setF('ratePerTon',parseFloat(e.target.value)||'')} required min="1" step="0.01" placeholder="0.00"/></div>
                <div className="fg">
                  <div className="fld"><label>Effective From</label><input className="inp" type="date" value={form.effectiveFrom||''} onChange={e=>setF('effectiveFrom',e.target.value)}/></div>
                  <div className="fld"><label>Effective To</label><input className="inp" type="date" value={form.effectiveTo||''} onChange={e=>setF('effectiveTo',e.target.value)}/></div>
                </div>
                <window.CompanyAssignmentSection form={form} setForm={setForm}/>
              </div>
              <div className="mod-ft"><button type="button" className="btn btn-wh" onClick={()=>setModal(false)}>Cancel</button><button type="submit" className="btn btn-or">{editId?'Update Rate':'Create Rate'}</button></div>
            </form>
          </div>
        </div>
      )}
      {delId&&<window.Confirm onOk={handleDelete} onCancel={()=>setDelId(null)}/>}
      {scan&&(
        <div className="mbg">
          <div className="mod mod-md">
            <div className="mod-hd"><h2>Rate Integrity Scan</h2><button className="mod-x" onClick={()=>setScan(null)}>×</button></div>
            <div className="mod-bd">
              <p style={{fontSize:12.5,color:'var(--txt2)',marginBottom:10}}>Scanned <strong>{scan.scanned}</strong> transport transaction(s) against the rate that was effective on each transaction's own date. Records already correct, records with no rate history, and manual overrides are left untouched.</p>
              {scan.affected===0
                ? <div style={{background:'#F0FDF4',border:'1px solid #BBF7D0',borderRadius:6,padding:'12px 14px',fontSize:13,fontWeight:600,color:'#15803D'}}>No mismatches found — every transaction carries the rate applicable on its own date.</div>
                : <div>
                    <div style={{background:'#FEF3C7',border:'1px solid #FDE68A',borderRadius:6,padding:'10px 14px',fontSize:12.5,marginBottom:10}}><strong>{scan.affected}</strong> transaction(s) hold a rate that differs from the rate effective on their transaction date. Review the CSV before applying — the repair is deterministic and each record keeps a reversible pre-repair snapshot.</div>
                    <div className="tbl-w" style={{maxHeight:260,overflow:'auto'}}><table className="tbl"><thead><tr><th>DATE</th><th>CHALLAN</th><th>MATERIAL</th><th>DESTINATION</th><th>STORED</th><th>APPLICABLE</th><th>EXPECTED AMT</th></tr></thead><tbody>
                      {scan.rows.slice(0,25).map(r=>(<tr key={r.id}><td style={{fontSize:12}}>{window.fmtDate(r.date)}</td><td style={{fontSize:11.5}}>{r.challanNumber||'—'}</td><td style={{fontSize:11.5}}>{r.material}</td><td style={{fontSize:11.5}}>{r.destination}</td><td style={{fontWeight:600}}>₹{window.fmtNum(r.currentRate)}</td><td style={{fontWeight:700,color:'var(--or)'}}>₹{window.fmtNum(r.historicalRate)}</td><td>{window.fmtCur(r.expectedAmount)}</td></tr>))}
                    </tbody></table></div>
                    {scan.rows.length>25&&<div style={{fontSize:11.5,color:'var(--txt2)',marginTop:6}}>Showing first 25 of {scan.rows.length} — download the CSV for the full list.</div>}
                  </div>}
            </div>
            <div className="mod-ft"><button type="button" className="btn btn-wh" onClick={()=>setScan(null)}>Close</button>{scan.affected>0&&<><button type="button" className="btn btn-wh" onClick={scanCSV}>Download CSV</button><button type="button" className="btn btn-or" onClick={applyScan}>Apply Repair ({scan.affected})</button></>}</div>
          </div>
        </div>
      )}
    </div>
  );
}

window.TransportPage=TransportPage;
window.TransportersListPage=TransportersListPage;
window.RatesPage=RatesPage;
