// Transporter Settlement — Challan-Centric Architecture

// ── Company Selector with Logo ───────────────────────────────────────────────
const OM_LOGO_SRC = 'uploads/OM GROUP ONLY LOGO-9de09387.png';
function OmLogoImg({size=32}) {
  return <img src={OM_LOGO_SRC} alt="OM Group" width={size} height={size} style={{display:'block',objectFit:'contain',flexShrink:0}} />;
}
function CompanyDropdown({value, onChange, companies}) {
  const [open, setOpen] = stSt(false);
  const ref = React.useRef();
  const panelRef = React.useRef();
  stEf(() => {
    if (!open) return;
    function handler(e) {
      if (ref.current && !ref.current.contains(e.target) &&
          panelRef.current && !panelRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);
  const opts = [{value:'group',label:'OM Group — All Companies',logo:true}, ...(companies||[]).map(c=>({value:c.id,label:c.name,logo:false}))];
  const sel = opts.find(o=>o.value===(value||'group')) || opts[0];
  const row = {display:'flex',alignItems:'center',gap:10,padding:'8px 10px',cursor:'pointer',fontSize:13};
  return (
    <div ref={ref} style={{position:'relative'}}>
      <div className="sel" onClick={()=>setOpen(o=>!o)} style={{display:'flex',alignItems:'center',gap:9,cursor:'pointer',userSelect:'none'}}>
        {sel.logo ? <OmLogoImg size={32}/> : <span style={{width:32,height:32,display:'inline-block'}}/>}
        <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{sel.label}</span>
        <svg width="10" height="6" viewBox="0 0 10 6" fill="none" style={{flexShrink:0,opacity:.5}}><path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </div>
      <window.FloatingLayer anchorRef={ref} open={open} matchWidth panelRef={panelRef}
        style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:6,boxShadow:'0 4px 16px rgba(0,0,0,.10)',maxHeight:220,overflowY:'auto'}}>
          {opts.map(o=>(
            <div key={o.value} onMouseDown={()=>{onChange(o.value);setOpen(false);}} style={{...row,background:o.value===sel.value?'#FFF7ED':'#fff'}}>
              {o.logo ? <OmLogoImg size={32}/> : <span style={{width:32,height:32,display:'inline-block'}}/>}
              <span style={{fontSize:13,color:'#111'}}>{o.label}</span>
              {o.value===sel.value && <svg style={{marginLeft:'auto',flexShrink:0}} width="12" height="12" viewBox="0 0 12 12"><path d="M2 6l3 3 5-5" stroke="#F97316" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" fill="none"/></svg>}
            </div>
          ))}
      </window.FloatingLayer>
    </div>
  );
}
window.CompanyDropdown = CompanyDropdown;
window.OmLogoImg       = OmLogoImg;
// Every settlement is built from Transport Entries as the single source of truth.
// Sources: transportEntries with sourceModule = undefined/SALES, STOCKYARD, or DEBRIS.
// Flow: Transporter → Vehicle → Date Range → Trip Table (all modules) → Settlement
const { useState: stSt, useEffect: stEf, useContext: stCtx, useMemo: stMemo } = React;

// ── Constants ────────────────────────────────────────────────────────────────
const ST_STATUSES  = ['Draft','Under Review','Approved','Paid','Cancelled'];
const DED_TYPES    = ['Royalty','RTO','Advance Paid','Penalty','Vehicle Repair','Tyre Recovery','Fuel Advance','Other'];
const LGR_TX_TYPES = ['All Types','Freight Earned','Diesel Issued','Royalty','RTO','Advance Paid','Penalty','Vehicle Repair','Tyre Recovery','Fuel Advance','Other Deduction','Settlement Payment'];

// ── Resolve transporter name from master ─────────────────────────────────────
function _stResolveTransporterName(transporterMasterId) {
  const rec = (Store.all('transporterMaster','group')||[]).find(t=>t.id===transporterMasterId);
  return (rec?.name||'').toLowerCase().trim();
}

// ── CHALLAN-CENTRIC HELPERS ───────────────────────────────────────────────────

// Returns all transport entries for a given transporter+vehicle+date range across ALL modules.
// Sources: Sales Order (no sourceModule), Stockyard (sourceModule='STOCKYARD'), Debris (sourceModule='DEBRIS').
// The freight amount used is always te.amount — the finalized transport payable from each module.
function stGetChallansForSettlement(transporterMasterId, vehicleFull, periodFrom, periodTo, coId) {
  if (!transporterMasterId || !periodFrom || !periodTo) return [];
  const masterName = _stResolveTransporterName(transporterMasterId);
  return (Store.all('transportEntries')||[]).filter(function(te) {
    if (te.status === 'Cancelled') return false;
    // Company filter
    if (coId && coId !== 'group' && te.companyId !== coId) return false;
    // Transporter match — by master ID or resolved name
    const byMId  = te._transporterMasterId === transporterMasterId || te.transporterId === transporterMasterId;
    const byName = masterName && (te.transporter||te.transporterName||'').toLowerCase().trim() === masterName;
    if (!byMId && !byName) return false;
    // Vehicle filter (if specified)
    if (vehicleFull && te.vehicleFull !== vehicleFull) return false;
    // Date range
    if (te.date < periodFrom || te.date > periodTo) return false;
    return true;
  }).sort(function(a,b){ return (a.date||'')>(b.date||'')?1:-1; });
}

// ── TRANSPORTER-LEVEL DIESEL AGGREGATION ────────────────────────────────────
// Diesel belongs to the Transporter, not to individual challans.
// Fetches ALL diesel entries for a transporter within the settlement period.
//
// Matching criteria:
//   Required : Transporter (by ID or name) + Date Range
//   Optional : Vehicle (when a specific vehicle is selected in the settlement)
//   Company  : All companies when coId='group'; single company otherwise
//   Excluded : Records already locked to a different active settlement
//
// Petrol pump, challan number, vendor — irrelevant. Never used for matching.

function stGetDieselForTransporter(transporterMasterId, periodFrom, periodTo, vehicleFull, coId, currentSettlementId) {
  if (!transporterMasterId || !periodFrom || !periodTo) return { records:[], total:0, litres:0, companies:[] };
  var masterName = _stResolveTransporterName(transporterMasterId);

  var records = (Store.all('dieselRecords', 'group') || []).filter(function(d) {
    // Allocation role filter — skip records allocated entirely to Vendor Settlement
    if (d.dieselAllocRole === 'Vendor') return false;
    // Transporter match — by ID or resolved name
    var byId   = d.transporterId === transporterMasterId;
    var byName = masterName && (d.transporterName || '').toLowerCase().trim() === masterName;
    if (!byId && !byName) return false;
    // Company filter (skip when group mode — include all companies)
    if (coId && coId !== 'group' && d.companyId !== coId) return false;
    // Vehicle filter (only when a specific vehicle is selected)
    if (vehicleFull && (d.vehicleFull || '').trim() !== vehicleFull.trim()) return false;
    // Date range
    var dt = (d.date || d.periodStart || '').trim();
    if (!dt || dt < periodFrom || dt > periodTo) return false;
    // Availability — not locked to another active settlement
    if (!d.settledInSettlementId) return true;
    if (currentSettlementId && d.settledInSettlementId === currentSettlementId) return true;
    var existing = (Store.all('settlementRecords') || []).find(function(sr) { return sr.id === d.settledInSettlementId; });
    return !existing || existing.status === 'Cancelled';
  });

  var total  = records.reduce(function(s,d){ return s + (window.getDieselTransportAmount ? window.getDieselTransportAmount(d) : (parseFloat(d.deductionAmount)||parseFloat(d.amount)||0)); }, 0);
  var litres = records.reduce(function(s,d){ return s+(parseFloat(d.litres)||0); }, 0);
  var cos = [];
  records.forEach(function(d){ if (d.companyId && cos.indexOf(d.companyId)===-1) cos.push(d.companyId); });
  return { records:records, total:total, litres:litres, companies:cos };
}

// Returns all distinct vehicles that have trips for a given transporter in a period.
function stGetVehiclesForTransporter(transporterMasterId, coId) {
  if (!transporterMasterId) return [];
  const masterName = _stResolveTransporterName(transporterMasterId);
  const vehicleSet = new Set();

  // From all transport modules (Sales Order, Stockyard, Debris) — unified vehicle list
  (Store.all('transportEntries')||[]).forEach(function(te) {
    if (!te.vehicleFull || te.status === 'Cancelled') return;
    if (coId && coId !== 'group' && te.companyId !== coId) return;
    const byMId  = te._transporterMasterId === transporterMasterId || te.transporterId === transporterMasterId;
    const byName = masterName && (te.transporter||te.transporterName||'').toLowerCase().trim() === masterName;
    if (byMId || byName) vehicleSet.add(te.vehicleFull);
  });

  // Also add from vehicle master for this transporter
  (Store.all('vehicleMaster','group')||[]).filter(function(v){
    return v.transporterId === transporterMasterId && (v.status==='Active'||!v.status);
  }).forEach(function(v){ vehicleSet.add(v.vehicleNumber); });

  return Array.from(vehicleSet).sort();
}

// Build a challan-wise trip table.
// Diesel is sourced from transporter-level aggregation (stGetDieselForTransporter),
// not matched per challan. Pass the pre-fetched transporterDiesel result.
function stBuildChallanTable(challans, transporterMasterId, currentSettlementId, periodFrom, periodTo, transporterDiesel) {
  var rows = challans.map(function(ch) {
    // Transport Report fields — ch.amount is the freight payable to the transporter.
    // Never use sales order or purchase subtotals here.
    var matName = Store.name('materials', ch.materialId)||ch.material||'—';
    var qty     = parseFloat(ch.quantity)||0;
    var rate    = parseFloat(ch.rate)||parseFloat(ch.ratePerTon)||parseFloat(ch.transportRate)||0;
    var gross   = parseFloat(ch.amount)||parseFloat(ch.transportAmount)||0;
    var _policy = stGetVehiclePolicy(ch.vehicleFull);
    var _pm     = stCalcPolicyMargin(_policy, qty, gross);
    var effectiveGross = _pm.adjustedGross;
    var _isInternal = _policy && _policy.settlementMode==='Internal Company Settlement';
    // Map sourceModule to display label
    var _srcMod   = ch.sourceModule || 'SALES';
    var _srcLabel = _srcMod === 'STOCKYARD' ? 'Stockyard Movement'
                  : _srcMod === 'DEBRIS'    ? 'Debris Movement'
                  : 'Sales Order';
    // Challan display: fall back to short record ID for records without a challan number
    var _challanDisplay = ch.challanNumber || ('#' + ch.id.slice(0,6).toUpperCase());
    return {
      purchaseId:          ch.id,
      salesOrderId:        ch.id,
      transportEntryId:    ch.id,
      challanNumber:       ch.challanNumber,
      challanDisplay:      _challanDisplay,
      sourceModule:        _srcMod,
      sourceLabel:         _srcLabel,
      date:                ch.date,
      vehicleFull:         ch.vehicleFull,
      companyId:           ch.companyId,
      material:            matName,
      quantity:            qty,
      freightRate:         rate,
      grossFreight:        effectiveGross,
      actualGross:         gross,
      marginAmount:        _pm.marginAmount,
      marginPerUnit:       _pm.marginPerUnit,
      policy:              _policy || null,
      settlementMode:      _isInternal ? 'Internal Company Settlement' : 'Direct Transporter Payment',
      receivingCompanyId:  _isInternal ? (_policy.receivingCompanyId||null) : null,
      dieselAmount:        0,
      dieselLitres:        0,
      dieselRecords:       [],
      dieselCompanies:     [],
      netFreight:          effectiveGross,
      settlementStatus:    ch.settlementStatus || 'Pending',
      vendorName:          Store.name('vendors', ch.vendorId)||'',
      customer:            stResolveCustomer(ch),
    };
  });

  // ── Distribute transporter-level diesel to rows by vehicle match ─────────────
  // Diesel is owned by the transporter, not by individual challans.
  // We distribute records to rows only for display purposes (vehicle grouping).
  // The settlement total is always the full transporter diesel for the period.
  var dsl = transporterDiesel || { records:[], total:0, litres:0, companies:[] };
  if (dsl.records.length > 0 && rows.length > 0) {
    dsl.records.forEach(function(d) {
      var dVehicle = (d.vehicleFull || '').trim();
      var dedAmt   = window.getDieselTransportAmount ? window.getDieselTransportAmount(d) : (parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0);
      if (dedAmt <= 0) return; // Skip records with zero transport allocation
      // Vehicle match → assign to that vehicle's row(s); else assign to first row
      var target = null;
      if (dVehicle) {
        target = rows.find(function(r){ return (r.vehicleFull||'').trim() === dVehicle; });
      }
      if (!target) target = rows[0];
      target.dieselAmount  = (target.dieselAmount  || 0) + dedAmt;
      target.dieselLitres  = (target.dieselLitres  || 0) + (parseFloat(d.litres)||0);
      target.dieselRecords = (target.dieselRecords || []).concat([d]);
      if (d.companyId && (target.dieselCompanies||[]).indexOf(d.companyId)===-1) {
        target.dieselCompanies = (target.dieselCompanies||[]).concat([d.companyId]);
      }
    });
    // Recalculate netFreight for all rows after diesel distribution
    rows.forEach(function(r) {
      r.netFreight = Math.max(0, r.grossFreight - r.dieselAmount);
    });
  }

  return rows;
}

// Totals computed from challan table rows (policy-aware)
function stCalcChallanTotals(rows, deds) {
  const gross       = rows.reduce(function(s,r){ return s+(r.grossFreight||0); },0);
  const actualGross = rows.reduce(function(s,r){ return s+(r.actualGross!==undefined?r.actualGross:(r.grossFreight||0)); },0);
  const totalMargin = rows.reduce(function(s,r){ return s+(r.marginAmount||0); },0);
  const dslAmt      = rows.reduce(function(s,r){ return s+(r.dieselAmount||0); },0);
  const manDeds     = deds.reduce(function(s,d){ return s+(parseFloat(d.amount)||0); },0);
  const totalD      = dslAmt + manDeds;
  const net         = Math.max(0, gross - totalD);
  const qty         = rows.reduce(function(s,r){ return s+(r.quantity||0); },0);
  const hasInternal = rows.some(function(r){ return r.settlementMode==='Internal Company Settlement'; });
  return { gross, actualGross, totalMargin, dslAmt, manDeds, totalD, net, qty, tripCount:rows.length, hasInternal };
}

// Legacy helpers (kept for existing settlement records compatibility)
function stGetTrips(transporterMasterId, periodFrom, periodTo, coId) {
  if (!transporterMasterId || !periodFrom || !periodTo) return [];
  const masterName = _stResolveTransporterName(transporterMasterId);
  return (Store.all('transportEntries')||[]).filter(te => {
    if (te._transporterMasterId && te._transporterMasterId === transporterMasterId) {}
    else if (te.transporterId && te.transporterId === transporterMasterId) {}
    else if (masterName) {
      const teDirectName  = (te.transporter||te.transporterName||'').toLowerCase().trim();
      const teOldListName = te.transporterId ? (Store.name('transportersList',te.transporterId)||'').toLowerCase().trim() : '';
      const teName = teDirectName || teOldListName;
      if (!teName || teName !== masterName) return false;
    } else return false;
    if (coId && coId !== 'group' && te.companyId !== coId) return false;
    if (te.date < periodFrom || te.date > periodTo) return false;
    return te.status !== 'Cancelled';
  });
}

function stGetDiesel(transporterMasterId, periodFrom, periodTo, coId) {
  if (!transporterMasterId || !periodFrom || !periodTo) return [];
  const masterName = _stResolveTransporterName(transporterMasterId);
  const bill = (Store.all('dieselRecords')||[]).filter(d => {
    const byId   = d.transporterId === transporterMasterId;
    const byName = masterName && (d.transporterName||'').toLowerCase().trim() === masterName;
    if (!byId && !byName) return false;
    if (coId && coId !== 'group' && d.companyId !== coId) return false;
    const dt = d.date||d.periodStart||'';
    return dt >= periodFrom && dt <= periodTo;
  }).map(d=>({...d,_dieselType:'Bill-Based'}));
  const purch = (Store.all('purchases')||[]).filter(p => {
    if ((parseFloat(p.dieselQty)||0) <= 0 || !p.dieselSource) return false;
    if (coId && coId !== 'group' && p.companyId !== coId) return false;
    if (p.date < periodFrom || p.date > periodTo) return false;
    const byMId  = p.transporterMasterId === transporterMasterId;
    const byName = masterName && (p.transporterName||'').toLowerCase().trim() === masterName;
    return byMId || byName;
  }).map(p=>({ id:'pd-'+p.id, transporterId:p.transporterMasterId||'', transporterName:p.transporterName||'',
    vehicleFull:p.vehicleFull||'', dieselSource:p.dieselSource||'', litres:parseFloat(p.dieselQty)||0,
    ratePerLitre:0, amount:0, periodStart:p.date, periodEnd:p.date, date:p.date,
    companyId:p.companyId, _purchaseId:p.id, challanNumber:p.challanNumber||'', _dieselType:'Purchase-Based' }));
  return [...bill, ...purch];
}

function stCalcTotals(trips, diesel, deds) {
  const gross    = trips.reduce((s,t)  => s + (parseFloat(t.amount)||0), 0);
  const billDsl  = diesel.filter(d=>d._dieselType!=='Purchase-Based').reduce((s,d)=>s+(parseFloat(d.deductionAmount)||parseFloat(d.amount)||0),0);
  const purchDsl = diesel.filter(d=>d._dieselType==='Purchase-Based').reduce((s,d)=>s+(parseFloat(d.amount)||0),0);
  const dslAmt   = billDsl + purchDsl;
  const manDeds  = deds.reduce((s,d)   => s + (parseFloat(d.amount)||0), 0);
  const totalD   = dslAmt + manDeds;
  return { gross, dslAmt, billDsl, purchDsl, manDeds, totalD, net: Math.max(0, gross - totalD) };
}

// ── Mark / release diesel records after a settlement is saved ────────────────
// Finalized settlements (Approved/Paid) lock their diesel records so they
// cannot be double-deducted in future settlements.
// Cancelled or downgraded settlements release them.
function stUpdateDieselSettlementStatus(challanRows, settlementId, settlementStatus) {
  if (!challanRows || !challanRows.length || !settlementId) return;
  var isFinalized = ['Approved','Paid'].includes(settlementStatus);
  var today = new Date().toISOString().slice(0,10);
  challanRows.forEach(function(row) {
    (row.dieselRecords || []).forEach(function(d) {
      if (!d.id || d.id.indexOf('pd-') === 0) return; // skip purchase-based virtual records
      var dieselRec = (Store.all('dieselRecords','group') || []).find(function(r){ return r.id === d.id; });
      if (!dieselRec) return;
      if (isFinalized) {
        Store.update('dieselRecords', d.id, Object.assign({}, dieselRec, {
          settledInSettlementId: settlementId,
          settledDate: today,
        }));
      } else if (dieselRec.settledInSettlementId === settlementId) {
        var released = Object.assign({}, dieselRec);
        delete released.settledInSettlementId;
        delete released.settledDate;
        Store.update('dieselRecords', d.id, released);
      }
    });
  });
}

// Update settlement status on Transport Report entries after a settlement is saved
function stUpdateChallanSettlementStatus(challanRows, settlementId, settlementStatus) {
  if (!challanRows || !challanRows.length) return;
  var isFinalized = ['Approved','Paid'].includes(settlementStatus);
  var today = new Date().toISOString().slice(0,10);
  challanRows.forEach(function(row) {
    var id = row.transportEntryId || row.salesOrderId || row.purchaseId;
    if (!id) return;
    var newStatus = isFinalized ? 'Fully Settled' : 'Partially Settled';
    // Primary: update Transport Entry (source of truth for freight)
    var teRec = (Store.all('transportEntries')||[]).find(function(r){ return r.id===id; });
    if (teRec) {
      if (teRec.settlementStatus === 'Fully Settled' && teRec.lastSettlementId !== settlementId) return;
      Store.update('transportEntries', id, {
        ...teRec,
        settlementStatus: newStatus,
        lastSettlementId: settlementId,
        lastSettlementDate: today,
      });
      return;
    }
    // Fallback: Sales Orders (for settlements created before this migration)
    var soRec = (Store.all('salesOrders')||[]).find(function(r){ return r.id===id; });
    if (soRec) {
      if (soRec.settlementStatus === 'Fully Settled' && soRec.lastSettlementId !== settlementId) return;
      Store.update('salesOrders', id, {
        ...soRec,
        settlementStatus: newStatus,
        lastSettlementId: settlementId,
        lastSettlementDate: today,
      });
      return;
    }
    // Fallback: purchases (for very old settlement records)
    var pRec = (Store.all('purchases')||[]).find(function(r){ return r.id===id; });
    if (!pRec) return;
    if (pRec.settlementStatus === 'Fully Settled' && pRec.lastSettlementId !== settlementId) return;
    Store.update('purchases', id, {
      ...pRec,
      settlementStatus: newStatus,
      lastSettlementId: settlementId,
      lastSettlementDate: today,
    });
  });
}

// ── Settlement Policy Engine ────────────────────────────────────────────────────
// Reads policy from Vehicle Master → Settlement Policy Master.
// Never hardcodes vehicle numbers, company names, or margins.

function stGetVehiclePolicy(vehicleFull) {
  if (!vehicleFull) return null;
  var veh = (Store.all('vehicleMaster','group')||[]).find(function(v){ return v.vehicleNumber===vehicleFull; });
  if (!veh || !veh.settlementPolicyId) return null;
  return (Store.all('settlementPolicies','group')||[]).find(function(p){ return p.id===veh.settlementPolicyId; }) || null;
}

function stCalcPolicyMargin(policy, qty, baseGross) {
  if (!policy || policy.settlementMode!=='Internal Company Settlement') return {marginAmount:0,adjustedGross:baseGross,marginPerUnit:0};
  var mv = parseFloat(policy.marginValue)||0;
  var marginAmount = 0; var marginPerUnit = 0;
  if (policy.marginType==='Per Ton')        { marginAmount=mv*qty; marginPerUnit=mv; }
  else if (policy.marginType==='Fixed Amount') { marginAmount=mv; marginPerUnit=qty>0?mv/qty:0; }
  else if (policy.marginType==='Percentage')   { marginAmount=baseGross*mv/100; marginPerUnit=qty>0?marginAmount/qty:0; }
  return {marginAmount, adjustedGross:baseGross+marginAmount, marginPerUnit};
}

// ── Dynamic Customer Resolution ────────────────────────────────────────────────
// Resolves customer/destination from any transport entry without hardcoding.
// SALES     → customerName / customers master via customerId
// STOCKYARD → _destinationType=Customer: _destinationName/_destinationId
//              otherwise (Internal Transfer): fromStockyard → toStockyard
// DEBRIS    → _destLocation or _destType
// Future    → expose _destinationName/_destinationType on the entry
function stResolveCustomer(te) {
  var src = te.sourceModule || 'SALES';
  if (src === 'STOCKYARD') {
    if (te._destinationType === 'Customer') {
      return te._destinationName || (te._destinationId ? (Store.name('customers', te._destinationId) || '') : '') || '—';
    }
    var from = te._fromStockyardName || te._stockyardName || '';
    var to   = te._toStockyardName   || te._destinationName || '';
    if (from && to) return from + ' → ' + to;
    if (from) return from;
    return te._destinationName || 'Internal Transfer';
  }
  if (src === 'DEBRIS') {
    return te._destLocation || te._destType || 'Debris Disposal';
  }
  return te.customerName || (te.customerId ? (Store.name('customers', te.customerId) || '') : '') || '—';
}

// ── Ledger builder (unchanged — backward compatible) ─────────────────────────
function stBuildLedger(transporterId, coId, from, to, txTypeFilter) {
  if (!transporterId) return [];
  const entries = [];
  (Store.all('transportEntries')||[]).filter(te => {
    const byId   = te._transporterMasterId === transporterId || te.transporterId === transporterId;
    const _lgr_mn = _stResolveTransporterName(transporterId);
    const byName = _lgr_mn && (te.transporter||te.transporterName||'').toLowerCase().trim() === _lgr_mn;
    if (!byId && !byName) return false;
    if (coId && coId !== 'group' && te.companyId !== coId) return false;
    if (from && te.date < from) return false;
    if (to   && te.date > to  ) return false;
    return te.status !== 'Cancelled';
  }).forEach(te => {
    var _sm = te.sourceModule;
    var _srcModule = _sm === 'STOCKYARD' ? 'Stockyard Movement'
                   : _sm === 'DEBRIS'   ? 'Debris Movement'
                   : 'Sales Order';
    entries.push({
      id:'t-'+te.id, date:te.date, txType:'Freight Earned',
      desc:(te.challanNumber||te.vehicleFull||'—')+' | '+(Store.name('materials',te.materialId)||te.material||''),
      debit:0, credit:parseFloat(te.amount)||0,
      ref:te.challanNumber||'—', vehicleNo:te.vehicleFull||'',
      coId:te.companyId, srcId:te.id, srcModule:_srcModule,
    });
  });
  const _lgr_masterName = _stResolveTransporterName(transporterId);
  const _lgr_billDiesel = (Store.all('dieselRecords')||[]).filter(d => {
    const byId   = d.transporterId === transporterId;
    const byName = _lgr_masterName && (d.transporterName||'').toLowerCase().trim() === _lgr_masterName;
    if (!byId && !byName) return false;
    if (coId && coId !== 'group' && d.companyId !== coId) return false;
    const dt = d.date||d.periodStart||'';
    if (from && dt < from) return false;
    if (to   && dt > to  ) return false;
    return true;
  });
  const _lgr_purchDiesel = (Store.all('purchases')||[]).filter(p => {
    if ((parseFloat(p.dieselQty)||0)<=0||!p.dieselSource) return false;
    if (coId && coId !== 'group' && p.companyId !== coId) return false;
    const byMId  = p.transporterMasterId === transporterId;
    const byName = _lgr_masterName && (p.transporterName||'').toLowerCase().trim() === _lgr_masterName;
    if (!byMId && !byName) return false;
    if (from && p.date < from) return false;
    if (to   && p.date > to  ) return false;
    return true;
  }).map(p=>({ id:'pd-'+p.id, date:p.date, dieselSource:p.dieselSource, vehicleFull:p.vehicleFull||'',
    litres:parseFloat(p.dieselQty)||0, amount:0, companyId:p.companyId, _dieselType:'Purchase-Based' }));
  [..._lgr_billDiesel, ..._lgr_purchDiesel].forEach(d => entries.push({
    id:'d-'+d.id, date:d.date||d.periodStart||'', txType:'Diesel Issued',
    desc:(d._dieselType?'['+d._dieselType+'] ':'')+(d.vehicleFull||'—')+' | '+(d.dieselSource||'')+' | '+(d.litres||0)+'L',
    debit:parseFloat(d.deductionAmount)||parseFloat(d.amount)||0, credit:0,
    ref:d.vehicleFull||'—', vehicleNo:d.vehicleFull||'',
    coId:d.companyId, srcId:d.id,
    srcModule: d._dieselType==='Purchase-Based' ? 'Purchases (Diesel)' : 'Diesel',
  }));
  (Store.all('settlementRecords')||[]).filter(s => {
    if (s.transporterId !== transporterId) return false;
    if (coId && coId !== 'group' && s.companyId !== coId) return false;
    return true;
  }).forEach(s => {
    (s.deductions||[]).forEach(ded => {
      const dt = ded.date||s.periodFrom||'';
      if (from && dt < from) return;
      if (to   && dt > to  ) return;
      const txType = ded.type==='Other' ? (ded.customType||'Other Deduction') : ded.type;
      entries.push({ id:'sd-'+s.id+'-'+ded.id, date:dt, txType,
        desc:txType+(ded.remarks?' — '+ded.remarks:'')+' | Settlement '+s.periodFrom+'–'+s.periodTo,
        debit:parseFloat(ded.amount)||0, credit:0, ref:ded.reference||s.id.slice(0,8),
        vehicleNo:'', coId:s.companyId, srcId:s.id, srcModule:'Settlement', settlementId:s.id,
      });
    });
    const paid = parseFloat(s.amountPaid)||0;
    if (paid > 0) {
      const pd = s.paidDate||s.periodTo||'';
      if ((!from||pd>=from) && (!to||pd<=to)) entries.push({
        id:'sp-'+s.id, date:pd, txType:'Settlement Payment',
        desc:'Payment — '+s.periodFrom+' to '+s.periodTo,
        debit:paid, credit:0, ref:s.id.slice(0,8),
        vehicleNo:'', coId:s.companyId, srcId:s.id, srcModule:'Settlement', settlementId:s.id,
      });
    }
  });
  entries.sort((a,b) => a.date>b.date ? 1 : a.date<b.date ? -1 : 0);
  let bal = 0;
  const withBal = entries.map(e => { bal += e.credit - e.debit; return {...e, bal}; });
  return txTypeFilter && txTypeFilter !== 'All Types'
    ? withBal.filter(e => e.txType === txTypeFilter)
    : withBal;
}

// ── Badges ───────────────────────────────────────────────────────────────────
// Source Module badge — shown in trip tables
function SourceModuleBadge({src}) {
  const cfg = {
    'STOCKYARD': {bg:'#DCFCE7',color:'#15803D',label:'Stockyard'},
    'DEBRIS':    {bg:'#FEF3C7',color:'#B45309',label:'Debris Mvmt'},
  };
  const c = cfg[src] || {bg:'#EDE9FE',color:'#6D28D9',label:'Sales Order'};
  return <span style={{fontSize:9,padding:'2px 6px',borderRadius:3,fontWeight:700,background:c.bg,color:c.color,letterSpacing:'0.3px',whiteSpace:'nowrap'}}>{c.label}</span>;
}
function StBadge({s}) {
  const m = {Draft:{bg:'#F3F4F6',color:'#374151'},'Under Review':{bg:'#FEF3C7',color:'#92400E'},Approved:{bg:'#DCFCE7',color:'#166534'},Paid:{bg:'#DBEAFE',color:'#1E40AF'},Cancelled:{bg:'#FEE2E2',color:'#991B1B'}};
  const c = m[s]||m.Draft;
  return <span style={{fontSize:11,fontWeight:700,padding:'2px 8px',borderRadius:3,background:c.bg,color:c.color}}>{s}</span>;
}
function DedBadge({type}) {
  const cl = {Royalty:'#7C3AED',RTO:'#1D4ED8','Advance Paid':'#D97706',Penalty:'#DC2626','Vehicle Repair':'#0369A1','Tyre Recovery':'#059669','Fuel Advance':'#B45309'};
  const c = cl[type]||'#6B7280';
  return <span style={{fontSize:10,fontWeight:700,padding:'1px 6px',borderRadius:3,background:c+'22',color:c}}>{type}</span>;
}
function ChallanStatusBadge({status}) {
  const cfg = {
    'Pending':           {bg:'#F3F4F6',color:'#374151'},
    'Partially Settled': {bg:'#FEF3C7',color:'#92400E'},
    'Fully Settled':     {bg:'#DCFCE7',color:'#166534'},
  };
  const c = cfg[status]||cfg['Pending'];
  return <span style={{fontSize:10,fontWeight:700,padding:'2px 6px',borderRadius:3,background:c.bg,color:c.color,whiteSpace:'nowrap'}}>{status||'Pending'}</span>;
}

// ── Expandable Settlement Detail ──────────────────────────────────────────────
function SettleDetail({s}) {
  const { navigate } = React.useContext(window.AppCtx) || {};
  // ── Split Allocation Traceability — diesel records locked to THIS settlement
  // via settledInSettlementId, restricted to Split/Vendor-role-adjacent records
  // that still carry a transport share (spec §7, §9).
  const splitDiesel = React.useMemo(function() {
    return (Store.all('dieselRecords','group')||[]).filter(function(d) {
      return d.settledInSettlementId === s.id && d.dieselAllocRole === 'Split';
    });
  }, [s.id]);
  const SplitDieselSection = splitDiesel.length > 0 && (
    <div style={{background:'#fff',border:'1px solid #DDD6FE',borderRadius:6,padding:'10px 12px',marginTop:12}}>
      <div style={{fontWeight:700,fontSize:11,color:'#6D28D9',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}}>🟣 Split Allocation Diesel ({splitDiesel.length})</div>
      <div style={{overflowX:'auto'}}>
        <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:760}}>
          <thead><tr>{['Date','Vehicle','Challan','Vendor Share','Transport Share','Total',''].map(h=><th key={h} style={{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',textAlign:'left'}}>{h}</th>)}</tr></thead>
          <tbody>{splitDiesel.map(function(d) {
            var total = parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
            return (
              <tr key={d.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                <td style={{padding:'4px 8px'}}>{window.fmtDate(d.date)}</td>
                <td style={{padding:'4px 8px',fontFamily:'var(--font)'}}>{d.vehicleFull||'—'}</td>
                <td style={{padding:'4px 8px',fontFamily:'var(--font)'}}>{d.challanNumber||'—'}</td>
                <td style={{padding:'4px 8px',color:'var(--txt2)'}}>{window.fmtCur(d.vendorAllocAmount||0)}</td>
                <td style={{padding:'4px 8px',fontWeight:700,color:'#1D4ED8'}}>{window.fmtCur(d.transportAllocAmount||0)}</td>
                <td style={{padding:'4px 8px',fontWeight:700}}>{window.fmtCur(total)}</td>
                <td style={{padding:'4px 8px'}}><button className="btn btn-gh btn-sm" onClick={function(){ navigate && navigate('diesel',{focusAllocId:d.id}); }}>🔗 View →</button></td>
              </tr>);
          })}</tbody>
        </table>
      </div>
      <div style={{fontSize:10.5,color:'var(--txt3)',marginTop:6}}>These diesel deductions were generated automatically from a Diesel Split Allocation and included in this settlement's diesel total.</div>
    </div>
  );
  // If the settlement has challan rows stored, use challan-centric view
  const hasChallanRows = s.challanRows && s.challanRows.length > 0;

  if (hasChallanRows) {
    // New challan-centric display
    const rows = s.challanRows;
    const t    = stCalcChallanTotals(rows, s.deductions||[]);
    const H = ({c,right}) => <th style={{background:'#F9FAFB',fontSize:10,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',whiteSpace:'nowrap',textAlign:right?'right':'left',position:'sticky',top:0,zIndex:2}}>{c}</th>;
    const D = ({c,fw,col,right,mono}) => <td style={{padding:'4px 8px',fontFamily:mono?'var(--font)':'inherit',fontWeight:fw||400,color:col||'var(--txt)',textAlign:right?'right':'left',fontSize:12}}>{c}</td>;

    return (
      <div style={{padding:'14px 16px 18px',background:'#FFF9F5',borderBottom:'2px solid var(--or-bdr)'}}>
        {/* Policy banner — shown for Internal Settlement */}
        {t.hasInternal && (function(){
          var intlRows = rows.filter(function(r){return r.settlementMode==='Internal Company Settlement';});
          var rcIds = [...new Set(intlRows.map(function(r){return r.receivingCompanyId;}).filter(Boolean))];
          var policyNames = [...new Set(intlRows.map(function(r){return r.policy&&r.policy.policyName;}).filter(Boolean))];
          return (
            <div style={{background:'#F5F3FF',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'10px 14px',marginBottom:12,display:'flex',flexDirection:'column',gap:6}}>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#6D28D9" strokeWidth="2" style={{flexShrink:0}}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                <span style={{fontWeight:700,fontSize:12,color:'#6D28D9'}}>Internal Settlement — {intlRows.length} trip{intlRows.length!==1?'s':''} via configured policy</span>
              </div>
              <div className="rg-3" style={{gap:8}}>
                {[['Policy', policyNames.join(', ')||'—'],['Receiving Company',rcIds.map(function(id){return Store.name('companies',id)||id;}).join(', ')||'—'],['Margin Applied',window.fmtCur(t.totalMargin)]].map(function(row){
                  return <div key={row[0]} style={{fontSize:11,color:'#5B21B6'}}><span style={{color:'#7C3AED',fontWeight:600}}>{row[0]}: </span>{row[1]}</div>;
                })}
              </div>
              <div style={{fontSize:11,color:'#6D28D9'}}>
                Net settlement amount ({window.fmtCur(t.net)}) is transferred to the receiving company, not paid directly to the transporter.
              </div>
            </div>
          );
        })()}
        {/* Challan-wise trip table */}
        <div style={{marginBottom:14}}>
          <div style={{fontWeight:700,fontSize:11,color:'var(--or)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #FEF3E8',textTransform:'uppercase',letterSpacing:'.5px'}}>
            Trip-wise Settlement ({rows.length} Trips)
          </div>
          <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'min(360px,44vh)',borderRadius:6,border:'1px solid var(--bdr)'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:700}}>
              <thead><tr>
                <H c="Challan No."/><H c="Date"/><H c="Source"/>{s.companyId==='group'&&<H c="Company"/>}<H c="Customer"/><H c="Vehicle"/><H c="Material"/>
                <H c="Qty" right/><H c="Gross Freight" right/><H c="Diesel" right/>
                <H c="Net Freight" right/><H c="Status"/>
              </tr></thead>
              <tbody>
                {rows.map(function(row,i) {
                  var isSettled = row.settlementStatus === 'Fully Settled';
                  return (
                    <tr key={row.challanNumber+i} style={{borderBottom:'1px solid #F3F4F6',background:isSettled?'#F0FDF4':'#fff'}}>
                      <D c={<span style={{fontFamily:'var(--font)',fontWeight:700,fontSize:11}}>{row.challanDisplay||row.challanNumber||'—'}</span>}/>
                      <D c={window.fmtDate(row.date)}/>
                      <td style={{padding:'4px 8px'}}><SourceModuleBadge src={row.sourceModule||'SALES'}/></td>
                      {s.companyId==='group'&&<D c={<span className="bdg bg-or" style={{fontSize:9,padding:'1px 4px'}}>{Store.name('companies',row.companyId)||'—'}</span>}/>}<D c={row.customer||'—'}/><D c={row.vehicleFull} mono/>
                      <D c={row.material}/>
                      <D c={window.formatQuantity(row.quantity)+' MT'} right/>
                      <D c={window.fmtCur(row.grossFreight)} fw={600} col="var(--ok)" right/>
                      <D c={row.dieselAmount>0?window.fmtCur(row.dieselAmount):'—'} col={row.dieselAmount>0?'#B45309':'var(--txt3)'} right/>
                      <D c={window.fmtCur(row.netFreight)} fw={700} col="var(--or)" right/>
                      <td style={{padding:'4px 8px'}}><ChallanStatusBadge status={row.settlementStatus}/></td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr style={{background:'#FFF7ED'}}>
                  <td colSpan={s.companyId==='group'?7:6} style={{textAlign:'right',padding:'6px 8px',fontWeight:700,fontSize:11,color:'var(--txt2)'}}>TOTALS</td>
                  <td style={{padding:'6px 8px',textAlign:'right',fontWeight:700}}>{window.formatQuantity(t.qty)} MT</td>
                  <td style={{padding:'6px 8px',textAlign:'right',fontWeight:800,color:'var(--ok)'}}>{window.fmtCur(t.gross)}</td>
                  <td style={{padding:'6px 8px',textAlign:'right',fontWeight:700,color:'#B45309'}}>{t.dslAmt?window.fmtCur(t.dslAmt):'—'}</td>
                  <td style={{padding:'6px 8px',textAlign:'right',fontWeight:800,color:'var(--or)',fontSize:13}}>{window.fmtCur(t.net)}</td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Summary + Deductions */}
        <div className="rg-2" style={{gap:12,marginBottom:s.deductions&&s.deductions.length?12:0}}>
          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
            <div style={{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:10,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}}>Settlement Summary</div>
            {[
              ['Total Trips', rows.length+' trips', 'var(--txt)'],
              ...(t.totalMargin>0?[['Actual Freight',window.fmtCur(t.actualGross),'var(--ok)'],['Policy Margin','+ '+window.fmtCur(t.totalMargin),'#6D28D9']]:[]),
              ['Gross Freight', window.fmtCur(t.gross), 'var(--ok)'],
              ['Diesel Deductions', t.dslAmt?'− '+window.fmtCur(t.dslAmt):'None', '#B45309'],
              ['Manual Deductions', t.manDeds?'− '+window.fmtCur(t.manDeds):'None', '#DC2626'],
              ['Total Deductions', '− '+window.fmtCur(t.totalD), '#DC2626'],
            ].map(function(row){
              return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:12}}>
                <span style={{color:'var(--txt2)'}}>{row[0]}</span>
                <span style={{fontWeight:600,color:row[2]}}>{row[1]}</span>
              </div>;
            })}
            <div style={{display:'flex',justifyContent:'space-between',padding:'8px 0',borderTop:'2px solid var(--txt)',marginTop:4}}>
              <span style={{fontWeight:700,fontSize:13}}>NET PAYABLE</span>
              <span style={{fontWeight:800,fontSize:16,color:'var(--or)'}}>{window.fmtCur(t.net)}</span>
            </div>
            {(parseFloat(s.amountPaid)||0) > 0 && <>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:12,color:'var(--txt2)',marginTop:4}}>
                <span>Amount Paid</span><span style={{color:'var(--ok)',fontWeight:600}}>− {window.fmtCur(s.amountPaid)}</span>
              </div>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:12,fontWeight:700,marginTop:2}}>
                <span>Outstanding</span><span style={{color:(s.outstandingBalance||0)>0?'#DC2626':'var(--ok)'}}>{window.fmtCur(s.outstandingBalance||0)}</span>
              </div>
            </>}
          </div>

          <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
            <div style={{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',paddingBottom:5,borderBottom:'2px solid var(--bdr)'}}>Settlement Info</div>
            {[
              ['Company', s.companyId==='group'?'OM Group (All Companies)':(Store.name('companies',s.companyId)||'—')],
              ['Paid Through Company', s.paidThroughCompanyName||(s.paidThroughCompanyId?Store.name('companies',s.paidThroughCompanyId):'—')||'—'],
              ['Transporter', s.transporterName||'—'],
              ['Vehicle Filter', s.vehicleFull||'All Vehicles'],
              ['Period', window.fmtDate(s.periodFrom)+' – '+window.fmtDate(s.periodTo)],
              ['Status', ''],
              ['Created', s.createdDate?window.fmtDate(s.createdDate):'—'],
              ['Created By', s.createdBy||'—'],
            ].map(function(row){
              if (row[0]==='Status') return <div key="Status" style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:12}}>
                <span style={{color:'var(--txt2)'}}>Status</span><StBadge s={s.status}/>
              </div>;
              return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:12}}>
                <span style={{color:'var(--txt2)'}}>{row[0]}</span><span style={{fontWeight:500}}>{row[1]}</span>
              </div>;
            })}
          </div>
        </div>

        {(s.deductions||[]).length > 0 && (
          <div style={{background:'#fff',border:'1px solid #FEE2E2',borderRadius:6,padding:'10px 12px'}}>
            <div style={{fontWeight:700,fontSize:11,color:'#DC2626',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}}>Manual Deductions ({s.deductions.length})</div>
            <div style={{overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:400}}>
                <thead><tr>{['Type','Amount','Reference','Date','Remarks'].map(h=><th key={h} style={{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',textAlign:'left'}}>{h}</th>)}</tr></thead>
                <tbody>
                  {s.deductions.map(d=>(
                    <tr key={d.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                      <td style={{padding:'4px 8px'}}><DedBadge type={d.type==='Other'?(d.customType||'Other'):d.type}/></td>
                      <td style={{padding:'4px 8px',fontWeight:700,color:'#DC2626',textAlign:'right'}}>{window.fmtCur(d.amount)}</td>
                      <td style={{padding:'4px 8px',fontFamily:'var(--font)',fontSize:11}}>{d.reference||'—'}</td>
                      <td style={{padding:'4px 8px'}}>{d.date?window.fmtDate(d.date):'—'}</td>
                      <td style={{padding:'4px 8px',color:'var(--txt2)'}}>{d.remarks||'—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
        {SplitDieselSection}
      </div>
    );
  }

  // Legacy display (for settlements created before the challan-centric upgrade)
  const trips       = stGetTrips (s.transporterId, s.periodFrom, s.periodTo, s.companyId);
  const diesel      = stGetDiesel(s.transporterId, s.periodFrom, s.periodTo, s.companyId);
  const billDiesel  = diesel.filter(d=>d._dieselType!=='Purchase-Based');
  const purchDiesel = diesel.filter(d=>d._dieselType==='Purchase-Based');
  const t           = stCalcTotals(trips, diesel, s.deductions||[]);
  const H = ({c}) => <th style={{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',whiteSpace:'nowrap'}}>{c}</th>;
  const D = ({c,fw,col,right}) => <td style={{padding:'4px 8px',fontFamily:'var(--font)',fontWeight:fw||400,color:col||'var(--txt)',textAlign:right?'right':'left',fontSize:12}}>{c}</td>;
  return (
    <div style={{padding:'14px 16px 18px',background:'#FFF9F5',borderBottom:'2px solid var(--or-bdr)'}}>
      <div className="rg-3" style={{gap:12,marginBottom:14}}>
        <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
          <div style={{fontWeight:700,fontSize:11,color:'var(--or)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #FEF3E8',textTransform:'uppercase',letterSpacing:'.5px'}}>Trips ({trips.length})</div>
          {!trips.length ? <div style={{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'}}>No trips in this period</div> : (
            <div style={{overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:420}}>
                <thead><tr>{['Date','Challan','Vehicle','Material','Qty','Amount'].map(h=><H key={h} c={h}/>)}</tr></thead>
                <tbody>
                  {trips.map(te=><tr key={te.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <D c={window.fmtDate(te.date)}/><D c={te.challanNumber||'—'}/><D c={te.vehicleFull||'—'}/>
                    <D c={Store.name('materials',te.materialId)||te.material||'—'}/>
                    <D c={window.fmtNum(te.quantity)+' '+(te.unit||'MT')} right/><D c={window.fmtCur(te.amount)} fw={700} col="var(--ok)" right/>
                  </tr>)}
                </tbody>
                <tfoot><tr style={{background:'#FFF7ED'}}><td colSpan={5} style={{textAlign:'right',padding:'5px 8px',fontWeight:700,fontSize:11,color:'var(--txt2)'}}>GROSS FREIGHT</td><td style={{textAlign:'right',padding:'5px 8px',fontWeight:800,color:'var(--or)',fontSize:13}}>{window.fmtCur(t.gross)}</td></tr></tfoot>
              </table>
            </div>
          )}
        </div>
        <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
          <div style={{fontWeight:700,fontSize:11,color:'#B45309',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #FEF3C7',textTransform:'uppercase',letterSpacing:'.5px'}}>Diesel ({diesel.length})</div>
          {!diesel.length ? <div style={{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'}}>No diesel records in period</div> : (
            <div style={{overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:360}}>
                <thead><tr>{['Vehicle','Source','Type','Litres','Rate','Amount'].map(h=><H key={h} c={h}/>)}</tr></thead>
                <tbody>{diesel.map(d=>{
                  const isPurch=d._dieselType==='Purchase-Based';
                  return <tr key={d.id} style={{borderBottom:'1px solid #F3F4F6',background:isPurch?'#F0F7FF':'#fff'}}>
                    <D c={d.vehicleFull||'—'}/><D c={d.dieselSource||'—'}/>
                    <D c={<span style={{fontSize:10,fontWeight:700,padding:'1px 5px',borderRadius:3,background:isPurch?'#DBEAFE':'#FEF3C7',color:isPurch?'#1D4ED8':'#92400E'}}>{isPurch?'Purchase':'Bill'}</span>}/>
                    <D c={window.fmtNum(d.litres)} right/>
                    <D c={isPurch?'—':window.fmtCur(d.ratePerLitre)} right/>
                    <D c={isPurch?<span style={{fontSize:10,color:'var(--txt3)',fontStyle:'italic'}}>qty only</span>:window.fmtCur(d.amount)} fw={isPurch?400:700} col={isPurch?'var(--txt3)':'#B45309'} right/>
                  </tr>;
                })}</tbody>
                <tfoot>
                  {billDiesel.length>0&&<tr style={{background:'#FFFBEB'}}><td colSpan={5} style={{textAlign:'right',padding:'5px 8px',fontWeight:700,fontSize:10.5,color:'#92400E'}}>BILL-BASED DIESEL</td><td style={{textAlign:'right',padding:'5px 8px',fontWeight:800,color:'#B45309'}}>{window.fmtCur(t.billDsl)}</td></tr>}
                  <tr style={{background:'#FFFBEB'}}><td colSpan={5} style={{textAlign:'right',padding:'5px 8px',fontWeight:700,fontSize:11,color:'var(--txt2)'}}>DIESEL TOTAL</td><td style={{textAlign:'right',padding:'5px 8px',fontWeight:800,color:'#B45309',fontSize:13}}>{window.fmtCur(t.dslAmt)}</td></tr>
                </tfoot>
              </table>
            </div>
          )}
        </div>
        <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
          <div style={{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:10,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}}>Settlement Summary</div>
          {[['Gross Freight',window.fmtCur(t.gross),'var(--ok)'],['Diesel (Bill-Based)',t.billDsl?'− '+window.fmtCur(t.billDsl):'None','#B45309'],['Other Deductions',t.manDeds?'− '+window.fmtCur(t.manDeds):'None','#DC2626'],['Total Deductions','− '+window.fmtCur(t.totalD),'#DC2626']].map(([lbl,val,col])=>(
            <div key={lbl} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:12}}>
              <span style={{color:'var(--txt2)'}}>{lbl}</span>
              <span style={{fontWeight:600,color:col}}>{val}</span>
            </div>
          ))}
          <div style={{display:'flex',justifyContent:'space-between',padding:'8px 0',borderTop:'2px solid var(--txt)',marginTop:4}}>
            <span style={{fontWeight:700,fontSize:13}}>NET PAYABLE</span>
            <span style={{fontWeight:800,fontSize:16,color:'var(--or)'}}>{window.fmtCur(t.net)}</span>
          </div>
        </div>
      </div>
      {(s.deductions||[]).length > 0 && (
        <div style={{background:'#fff',border:'1px solid #FEE2E2',borderRadius:6,padding:'10px 12px'}}>
          <div style={{fontWeight:700,fontSize:11,color:'#DC2626',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}}>Manual Deductions ({s.deductions.length})</div>
          <div style={{overflowX:'auto'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:400}}>
              <thead><tr>{['Type','Amount','Reference','Date','Remarks'].map(h=><th key={h} style={{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',textAlign:'left'}}>{h}</th>)}</tr></thead>
              <tbody>{s.deductions.map(d=>(
                <tr key={d.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                  <td style={{padding:'4px 8px'}}><DedBadge type={d.type==='Other'?(d.customType||'Other'):d.type}/></td>
                  <td style={{padding:'4px 8px',fontWeight:700,color:'#DC2626',textAlign:'right'}}>{window.fmtCur(d.amount)}</td>
                  <td style={{padding:'4px 8px',fontFamily:'var(--font)',fontSize:11}}>{d.reference||'—'}</td>
                  <td style={{padding:'4px 8px'}}>{d.date?window.fmtDate(d.date):'—'}</td>
                  <td style={{padding:'4px 8px',color:'var(--txt2)'}}>{d.remarks||'—'}</td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}
      {SplitDieselSection}
    </div>
  );
}

// ── Settlement Create / Edit Modal (Challan-Centric) ─────────────────────────
function SettleModal({item, coId, isGroup, session, onSaved, onClose}) {
  const blank = {companyId:isGroup?'group':coId, paidThroughCompanyId:isGroup?'':coId, transporterId:'', vehicleFull:'', periodFrom:'', periodTo:'', status:'Draft', amountPaid:0, notes:''};
  const [form,  setF0]  = stSt(item ? {...item} : {...blank});
  const [deds,  setDeds] = stSt(item?.deductions||[]);
  const [tick,  setTick] = stSt(0); // force refresh

  // Live reactivity: re-compute diesel totals whenever any store data changes
  // (catches diesel edits, additions, deletions without requiring a manual refresh)
  stEf(function() {
    var unsub = Store.on(function() { setTick(function(t){ return t+1; }); });
    return unsub;
  }, []);

  const companies    = Store.all('companies');
  const transporters = Store.all('transporterMaster','group');
  const eff = isGroup ? form.companyId : coId;

  const sf = (k,v) => setF0(p=>({...p,[k]:v, ...(k==='transporterId'?{vehicleFull:''}:{}), ...(k==='companyId'&&v!=='group'?{paidThroughCompanyId:v}:{})}));

  // Available vehicles for selected transporter
  const availableVehicles = stMemo(function(){
    if (!form.transporterId) return [];
    return stGetVehiclesForTransporter(form.transporterId, eff);
  }, [form.transporterId, eff, tick]);

  // Challans (from sales orders — new source of truth) for selected transporter+vehicle+period
  const challans = stMemo(function(){
    if (!form.transporterId || !form.periodFrom || !form.periodTo) return [];
    return stGetChallansForSettlement(form.transporterId, form.vehicleFull||'', form.periodFrom, form.periodTo, eff);
  }, [form.transporterId, form.vehicleFull, form.periodFrom, form.periodTo, eff, tick]);

  // Transporter-level diesel: all diesel records for this transporter+period
  // Diesel belongs to the transporter, not to individual challans.
  const transporterDiesel = stMemo(function(){
    if (!form.transporterId || !form.periodFrom || !form.periodTo) return { records:[], total:0, litres:0, companies:[] };
    return stGetDieselForTransporter(form.transporterId, form.periodFrom, form.periodTo, form.vehicleFull||'', eff, item ? item.id : null);
  }, [form.transporterId, form.vehicleFull, form.periodFrom, form.periodTo, eff, tick]);

  // Challan-wise table rows (diesel distributed by vehicle from transporter total)
  const challanRows = stMemo(function(){
    return stBuildChallanTable(challans, form.transporterId, item ? item.id : null, form.periodFrom, form.periodTo, transporterDiesel);
  }, [challans, form.transporterId, form.periodFrom, form.periodTo, transporterDiesel, tick]);

  // Totals
  const t = stMemo(function(){
    return stCalcChallanTotals(challanRows, deds);
  }, [challanRows, deds]);

  const showPreview = form.transporterId && form.periodFrom && form.periodTo;

  // Check for duplicate settlement (same transporter + overlapping period)
  const duplicateWarning = stMemo(function(){
    if (!form.transporterId || !form.periodFrom || !form.periodTo) return null;
    const existing = (Store.all('settlementRecords')||[]).filter(function(s){
      if (item && s.id === item.id) return false; // ignore self when editing
      if (s.transporterId !== form.transporterId) return false;
      if (s.status === 'Cancelled') return false;
      // Overlap check
      return s.periodFrom <= form.periodTo && s.periodTo >= form.periodFrom;
    });
    return existing.length > 0 ? existing[0] : null;
  }, [form.transporterId, form.periodFrom, form.periodTo, item]);

  function addDed(){setDeds(p=>[...p,{id:window.uid(),type:'Royalty',customType:'',amount:'',remarks:'',reference:'',date:''}]);}
  function updDed(i,k,v){setDeds(p=>p.map((d,j)=>j===i?{...d,[k]:v}:d));}
  function remDed(i){setDeds(p=>p.filter((_,j)=>j!==i));}

  function save(e){
    e.preventDefault();
    if(isGroup && !form.companyId){window.toast&&window.toast('Please select a company or OM Group','er');return;}
    if(!form.transporterId){window.toast&&window.toast('Select a transporter','er');return;}
    if(!form.periodFrom||!form.periodTo){window.toast&&window.toast('Set settlement period','er');return;}
    if(!form.paidThroughCompanyId){window.toast&&window.toast('Select the Paid Through Company (which company is making the payment)','er');return;}

    // Duplicate detection
    if (duplicateWarning && !item) {
      window.toast&&window.toast('A settlement already exists for this transporter overlapping this period. Please check before creating.','er');
      return;
    }

    const trp = transporters.find(x=>x.id===form.transporterId);
    const now = new Date().toISOString().slice(0,16).replace('T',' ');
    const prevHist = item?.statusHistory||[];
    const newHist  = item&&item.status===form.status ? prevHist : [...prevHist,{status:form.status,changedBy:session?.userName||'System',changedAt:now,remarks:''}];

    const data = {
      ...form,
      transporterName:   trp?.name||'',
      deductions:        deds,
      challanRows:       challanRows,   // Store challan-wise breakdown
      paidThroughCompanyId:   form.paidThroughCompanyId||'',
      paidThroughCompanyName: form.paidThroughCompanyId ? (Store.name('companies',form.paidThroughCompanyId)||'') : '',
      grossFreight:      t.gross,
      dieselDeduction:   t.dslAmt,
      totalDeductions:   t.totalD,
      netPayable:        t.net,
      outstandingBalance:Math.max(0, t.net-(parseFloat(form.amountPaid)||0)),
      amountPaid:        parseFloat(form.amountPaid)||0,
      tripCount:         t.tripCount,
      totalQuantity:     t.qty,
      statusHistory:     newHist,
      paidDate:     form.status==='Paid'&&!item?.paidDate     ? new Date().toISOString().slice(0,10) : (item?.paidDate||''),
      approvedDate: form.status==='Approved'&&!item?.approvedDate ? new Date().toISOString().slice(0,10) : (item?.approvedDate||''),
      approvedBy:   form.status==='Approved'&&!item?.approvedBy   ? (session?.userName||'') : (item?.approvedBy||''),
      createdDate:  item?.createdDate||new Date().toISOString().slice(0,10),
      createdBy:    item?.createdBy||(session?.userName||''),
    };

    let settlementId;
    if(item){
      Store.update('settlementRecords',item.id,data);
      Store.addLog('UPDATE','Settlement','Updated: '+(trp?.name||''));
      settlementId = item.id;
    } else {
      settlementId = Store.add('settlementRecords',data);
      Store.addLog('CREATE','Settlement','Created: '+(trp?.name||''));
    }

    // Update challan settlement status on sales order records
    if (challanRows.length > 0) {
      stUpdateChallanSettlementStatus(challanRows, settlementId||item?.id, form.status);
    }
    // Lock / release diesel records based on settlement status
    if (challanRows.length > 0) {
      stUpdateDieselSettlementStatus(challanRows, settlementId||item?.id, form.status);
    }

    // Create / update internal settlement records if any challan rows use Internal Settlement policy
    var _sid = settlementId || item?.id;
    if (_sid && challanRows.some(function(r){return r.settlementMode==='Internal Company Settlement';})) {
      // Remove existing internal settlements for this settlement (will recreate)
      (Store.all('internalSettlements')||[]).filter(function(is){return is.parentSettlementId===_sid;}).forEach(function(is){Store.del('internalSettlements',is.id);});
      // Group internal rows by receiving company
      var _intlRows = challanRows.filter(function(r){return r.settlementMode==='Internal Company Settlement';});
      var _byRco = {};
      _intlRows.forEach(function(r){
        var k = r.receivingCompanyId||'unknown';
        if (!_byRco[k]) _byRco[k] = [];
        _byRco[k].push(r);
      });
      Object.keys(_byRco).forEach(function(rcCoId){
        var rrows = _byRco[rcCoId];
        var pol = rrows[0].policy;
        var _totalActual = rrows.reduce(function(s,r){return s+(r.actualGross||r.grossFreight||0);},0);
        var _totalMargin = rrows.reduce(function(s,r){return s+(r.marginAmount||0);},0);
        var _totalDiesel = rrows.reduce(function(s,r){return s+(r.dieselAmount||0);},0);
        var _netIntl     = rrows.reduce(function(s,r){return s+r.netFreight;},0);
        Store.add('internalSettlements',{
          parentSettlementId: _sid,
          date: new Date().toISOString().slice(0,10),
          sourceCompanyId: form.companyId,
          receivingCompanyId: rcCoId,
          settlementPolicyId: pol ? pol.id : '',
          policyName: pol ? pol.policyName : '',
          vehicleFull: form.vehicleFull||'Multiple',
          transporterId: form.transporterId,
          transporterName: trp?.name||'',
          totalFreight: _totalActual+_totalMargin,
          actualFreight: _totalActual,
          totalMargin: _totalMargin,
          dieselDeduction: _totalDiesel,
          netInternalAmount: _netIntl,
          tripCount: rrows.length,
          status: ['Approved','Paid'].includes(form.status)?'Received':'Pending',
          challanRows: rrows,
          createdBy: session?.userName||'System',
          createdAt: new Date().toISOString().slice(0,10),
          settlementStatus: form.status,
        });
      });
    }

    window.toast&&window.toast(item?'Settlement updated':'Settlement created','ok');
    onSaved();
  }

  const iSt = {width:'100%',height:26,border:'1px solid var(--bdr)',borderRadius:'var(--r)',fontSize:12,fontFamily:'var(--font)',outline:'none',padding:'0 6px',background:'#fff'};

  return (
    <div className="mbg">
      <div className="mod mod-xl">
        <div className="mod-hd"><h2>{item?'Edit Settlement':'New Transporter Settlement'}</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <form onSubmit={save} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
          <div className="mod-bd">

            {/* ── Step 1: Company + Transporter + Vehicle ── */}
            <div className="fg" style={{marginBottom:12}}>
              {isGroup&&<div className="fld"><label>Company <span style={{fontSize:10,fontWeight:400,color:'var(--txt3)'}}>— which company's trips?</span></label><CompanyDropdown value={form.companyId||'group'} onChange={v=>sf('companyId',v)} companies={companies}/></div>}
              <div className="fld">
                <label>Paid Through Company <span className="req">*</span> <span style={{fontSize:10,fontWeight:400,color:'var(--txt3)'}}>— who is making the payment?</span></label>
                <window.FormSelect placeholder="Select paying company…" value={form.paidThroughCompanyId||''} onChange={v=>sf('paidThroughCompanyId',v)} options={companies.map(function(c){return {value:c.id,label:c.name};})}/>
              </div>
              <div className="fld">
                <label>Transporter <span className="req">*</span></label>
                <window.FormSelect placeholder="Select Transporter" value={form.transporterId||''} onChange={v=>sf('transporterId',v)} options={transporters.map(t=>({value:t.id,label:t.name}))}/>
              </div>
              <div className="fld">
                <label>Vehicle <span style={{fontSize:11,color:'var(--txt3)',fontWeight:400}}>(leave blank for all vehicles)</span></label>
                <window.FormSelect placeholder={form.transporterId?'All Vehicles':'Select transporter first'} value={form.vehicleFull||''} onChange={v=>sf('vehicleFull',v)} disabled={!form.transporterId} options={availableVehicles.map(function(v){return {value:v,label:v};})}/>
              </div>
              <div className="fld"><label>Status</label><window.FormSelect value={form.status||'Draft'} onChange={v=>sf('status',v)} options={ST_STATUSES.map(s=>({value:s,label:s}))}/></div>
              <div className="fld"><label>Period From <span className="req">*</span></label><input className="inp" type="date" value={form.periodFrom||''} onChange={e=>sf('periodFrom',e.target.value)} required/></div>
              <div className="fld"><label>Period To <span className="req">*</span></label><input className="inp" type="date" value={form.periodTo||''} onChange={e=>sf('periodTo',e.target.value)} required/></div>
            </div>

            {/* ── Duplicate warning ── */}
            {duplicateWarning && (
              <div style={{background:'#FEF3C7',border:'1px solid #FDE68A',borderRadius:6,padding:'10px 14px',marginBottom:12,display:'flex',alignItems:'center',gap:8,fontSize:12,color:'#92400E'}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0}}><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
                <span><strong>Duplicate Warning:</strong> A settlement already exists for this transporter covering the period {window.fmtDate(duplicateWarning.periodFrom)} – {window.fmtDate(duplicateWarning.periodTo)} (Status: {duplicateWarning.status}). Verify before proceeding.</span>
              </div>
            )}

            {/* ── Challan-wise Trip Table ── */}
            {showPreview && (
              <>
                {challans.length === 0 ? (
                  <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'20px',marginBottom:12,textAlign:'center',color:'var(--txt2)',fontSize:12}}>
                    No challans found for the selected transporter{form.vehicleFull?' / '+form.vehicleFull:''} in this period.
                    {!form.vehicleFull&&<span style={{display:'block',marginTop:4,fontSize:11,color:'var(--txt3)'}}>Try selecting a specific vehicle or widening the date range.</span>}
                  </div>
                ) : (
                  <div style={{marginBottom:14}}>
                    <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
                      <span style={{fontSize:12,fontWeight:700,color:'var(--txt)',letterSpacing:'-.01em'}}>
                        Trip-wise Settlement — {challans.length} Challan{challans.length!==1?'s':''}
                        {form.vehicleFull&&<span style={{fontSize:11,fontWeight:500,color:'var(--txt2)',marginLeft:8}}>· {form.vehicleFull}</span>}
                      </span>
                    </div>
                    <div style={{overflowX:'auto',overflowY:'auto',maxHeight:'min(360px,42vh)',border:'1.5px solid var(--bdr)',borderRadius:'var(--r)',background:'#fff'}}>
                      <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:680}}>
                        <thead>
                          <tr style={{background:'#FAFAF8'}}>
                            {(eff==='group'
                              ? ['CHALLAN NO.','DATE','SOURCE','COMPANY','CUSTOMER','VEHICLE','MATERIAL','QTY','GROSS FREIGHT','DIESEL','NET FREIGHT','STATUS']
                              : ['CHALLAN NO.','DATE','SOURCE','CUSTOMER','VEHICLE','MATERIAL','QTY','GROSS FREIGHT','DIESEL','NET FREIGHT','STATUS']
                            ).map(function(h,i){
                              var right = ['QTY','GROSS FREIGHT','DIESEL','NET FREIGHT'].includes(h);
                              return <th key={h} style={{padding:'8px 10px',textAlign:right?'right':'left',fontSize:10,fontWeight:700,color:'var(--txt3)',borderBottom:'1.5px solid var(--bdr)',whiteSpace:'nowrap',letterSpacing:'.06em',background:'#FAFAF8',position:'sticky',top:0,zIndex:2}}>{h}</th>;
                            })}
                          </tr>
                        </thead>
                        <tbody>
                          {challanRows.map(function(row,i){
                            var isSettled = row.settlementStatus === 'Fully Settled';
                            return (
                              <tr key={row.challanNumber+i} style={{borderBottom:'1px solid #F3F4F6',background:isSettled?'#F0FDF4':'#fff'}}>
                                <td style={{padding:'7px 10px',fontFamily:'var(--font)',fontWeight:700,fontSize:11.5,color:'var(--or)'}}>{row.challanDisplay||row.challanNumber||'—'}</td>
                                <td style={{padding:'7px 10px',whiteSpace:'nowrap',fontSize:11.5}}>{window.fmtDate(row.date)}</td>
                                <td style={{padding:'7px 10px'}}><SourceModuleBadge src={row.sourceModule||'SALES'}/></td>
                                {eff==='group'&&<td style={{padding:'7px 10px'}}><span className="bdg bg-or" style={{fontSize:9,padding:'1px 5px'}}>{Store.name('companies',row.companyId)||'—'}</span></td>}
                                <td style={{padding:'7px 10px',fontSize:11.5,maxWidth:150,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={row.customer||'—'}>{row.customer||'—'}</td>
                                <td style={{padding:'7px 10px',fontFamily:'var(--font)',fontSize:11}}>{row.vehicleFull}</td>
                                <td style={{padding:'7px 10px',fontSize:11.5,color:'var(--txt2)'}}>{row.material}</td>
                                <td style={{padding:'7px 10px',textAlign:'right',fontWeight:500,fontVariantNumeric:'tabular-nums'}}>{window.formatQuantity(row.quantity)}</td>
                                <td style={{padding:'7px 10px',textAlign:'right',fontWeight:600,color:'var(--ok)',fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(row.grossFreight)}</td>
                                <td style={{padding:'7px 10px',textAlign:'right',fontVariantNumeric:'tabular-nums'}}>
                                  {row.dieselAmount > 0
                                    ? <span style={{fontWeight:600,color:'#B45309'}} title={(row.dieselRecords||[]).length+' diesel record(s) for '+row.vehicleFull}>{window.fmtCur(row.dieselAmount)}</span>
                                    : <span style={{fontSize:10,fontStyle:'italic',color:'var(--txt3)'}}>—</span>}
                                </td>
                                <td style={{padding:'7px 10px',textAlign:'right',fontWeight:700,color:'var(--or)',fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(row.netFreight)}</td>
                                <td style={{padding:'7px 10px'}}><ChallanStatusBadge status={row.settlementStatus}/></td>
                              </tr>
                            );
                          })}
                        </tbody>
                        <tfoot>
                          <tr style={{background:'#FFF7ED',borderTop:'1.5px solid var(--or-bdr)'}}>
                            <td colSpan={eff==='group'?7:6} style={{padding:'8px 10px',fontWeight:700,fontSize:11,color:'var(--txt2)'}}>TOTALS — {t.tripCount} trips</td>
                            <td style={{padding:'8px 10px',textAlign:'right',fontWeight:700,fontVariantNumeric:'tabular-nums'}}>{window.formatQuantity(t.qty)} MT</td>
                            <td style={{padding:'8px 10px',textAlign:'right',fontWeight:800,color:'var(--ok)',fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(t.gross)}</td>
                            <td style={{padding:'8px 10px',textAlign:'right',fontWeight:700,color:'#B45309',fontVariantNumeric:'tabular-nums'}}>{t.dslAmt?window.fmtCur(t.dslAmt):'—'}</td>
                            <td style={{padding:'8px 10px',textAlign:'right',fontWeight:800,color:'var(--or)',fontSize:13,fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(t.net)}</td>
                            <td></td>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                    {/* Diesel info */}
                    {t.dslAmt === 0 ? (
                      <div style={{marginTop:6,fontSize:11,color:'var(--txt3)',display:'flex',alignItems:'center',gap:5}}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                        <span>No diesel entries found for this transporter in the selected period. Add entries via <strong>Diesel → Add Entry</strong> with the correct transporter and date.</span>
                      </div>
                    ) : (
                      <div style={{marginTop:6,fontSize:11,color:'#92400E',display:'flex',alignItems:'center',gap:5}}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                        <span>Diesel deductions are calculated automatically from Diesel Entries for the selected transporter and settlement period.</span>
                      </div>
                    )}
                    {(function(){
                      var allCos = (transporterDiesel.companies||[]);
                      var hasXco = allCos.some(function(c){ return c !== eff; });
                      if (!hasXco || allCos.length < 2) return null;
                      return (
                        <div style={{marginTop:6,fontSize:11,color:'#6D28D9',display:'flex',alignItems:'center',gap:6,background:'#FAF5FF',border:'1px solid #DDD6FE',borderRadius:5,padding:'5px 10px'}}>
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0}}><path d="M8 3H5a2 2 0 00-2 2v3"/><path d="M21 3h-3a2 2 0 00-2 2v3"/><path d="M3 16v3a2 2 0 002 2h3"/><path d="M16 21h3a2 2 0 002-2v-3"/></svg>
                          <span><strong>Cross-company diesel consolidated</strong> — records from {allCos.map(function(c){return Store.name('companies',c)||c;}).join(', ')} included in this settlement total.</span>
                        </div>
                      );
                    })()}
                  </div>
                )}

                {/* Summary bar */}
                <div style={{background:'#F0F7FF',border:'1px solid #BFDBFE',borderRadius:6,padding:'10px 14px',marginBottom:14}}>
                  <div style={{fontSize:11,fontWeight:700,color:'#1D4ED8',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}}>
                    Settlement Summary · {t.tripCount} Trips · {window.formatQuantity(t.qty)} MT
                  </div>
                  <div className={t.hasInternal?'rg-4':'rg-5'} style={{gap:8}}>
                    {[
                      ...(t.hasInternal?[['Actual Freight',window.fmtCur(t.actualGross),'var(--ok)'],['Policy Margin',window.fmtCur(t.totalMargin),'#6D28D9']]
                        :[['Gross Freight',window.fmtCur(t.gross),'var(--ok)']]),
                      ...(t.hasInternal?[['Adj. Freight',window.fmtCur(t.gross),'#059669']]:[] ),
                      ['Diesel',    window.fmtCur(t.dslAmt),  '#B45309'],
                      [t.hasInternal?'Net → Receiving Co':'Net Payable', window.fmtCur(t.net), t.hasInternal?'#6D28D9':'var(--or)'],
                    ].map(function(row){
                      return (
                        <div key={row[0]} style={{background:'#fff',border:'1px solid #DBEAFE',borderRadius:4,padding:'7px 8px',textAlign:'center'}}>
                          <div className="kpi-val" style={{fontSize:14,fontWeight:700,color:row[2]}}>{row[1]}</div>
                          <div style={{fontSize:10,color:'var(--txt2)',marginTop:2}}>{row[0]}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </>
            )}

            {/* ── Manual Deductions ── */}
            <div style={{marginBottom:12}}>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
                <span style={{fontSize:12,fontWeight:600}}>Manual Deductions</span>
                <button type="button" className="btn btn-wh btn-sm" onClick={addDed}><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 Deduction</button>
              </div>
              {!deds.length ? <div style={{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic',padding:'4px 0'}}>No deductions. Add Royalty, RTO, Advances, Penalties, etc.</div> : (
                <div style={{overflowX:'auto'}}>
                  <table style={{width:'100%',borderCollapse:'collapse',fontSize:12,minWidth:500}}>
                    <thead><tr>{['Type','Amount','Reference','Date','Remarks',''].map((h,i)=><th key={i} style={{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',textAlign:'left'}}>{h}</th>)}</tr></thead>
                    <tbody>
                      {deds.map((d,i)=>(
                        <tr key={d.id}>
                          <td style={{padding:'3px 5px',width:130}}><window.FormSelect value={d.type} onChange={v=>updDed(i,'type',v)} options={DED_TYPES.map(t=>({value:t,label:t}))} style={{minWidth:0}}/></td>
                          <td style={{padding:'3px 5px',width:90}}><input type="number" value={d.amount} onChange={e=>updDed(i,'amount',e.target.value)} placeholder="0" min="0" step="0.01" style={{...iSt}}/></td>
                          <td style={{padding:'3px 5px',width:110}}><input value={d.reference} onChange={e=>updDed(i,'reference',e.target.value)} placeholder="Ref no." style={{...iSt}}/></td>
                          <td style={{padding:'3px 5px',width:120}}><input type="date" value={d.date} onChange={e=>updDed(i,'date',e.target.value)} style={{...iSt}}/></td>
                          <td style={{padding:'3px 5px'}}>
                            {d.type==='Other' ? (
                              <div style={{display:'flex',gap:4}}>
                                <input value={d.customType||''} onChange={e=>updDed(i,'customType',e.target.value)} placeholder="Type name…" style={{...iSt,width:100}}/>
                                <input value={d.remarks} onChange={e=>updDed(i,'remarks',e.target.value)} placeholder="Remarks…" style={{...iSt}}/>
                              </div>
                            ) : <input value={d.remarks} onChange={e=>updDed(i,'remarks',e.target.value)} placeholder="Remarks…" style={{...iSt}}/>}
                          </td>
                          <td style={{padding:'3px 5px',textAlign:'center',width:28}}><button type="button" onClick={()=>remDed(i)} style={{border:'none',background:'none',color:'var(--err)',cursor:'pointer',fontSize:16,lineHeight:1}}>×</button></td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            <div className="fg">
              <div className="fld"><label>Amount Paid (₹)</label><input className="inp" type="number" value={form.amountPaid||''} onChange={e=>sf('amountPaid',e.target.value)} placeholder="0" min="0" step="0.01"/></div>
              <div className="fld full"><label>Notes</label><textarea className="tarea" value={form.notes||''} onChange={e=>sf('notes',e.target.value)} placeholder="Internal notes…" style={{minHeight:44}}/></div>
            </div>
          </div>
          <div className="mod-ft">
            <button type="button" className="btn btn-wh" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-or">{item?'Update Settlement':'Create Settlement'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Ledger Section (unchanged) ────────────────────────────────────────────────
function SettleLedger({coId, isGroup}) {
  const [fTr,setFTr]=stSt(''); const [fFrom,setFFrom]=stSt(''); const [fTo,setFTo]=stSt('');
  const [fType,setFType]=stSt(''); const [expId,setExpId]=stSt(null); const [tick,setTick]=stSt(0);
  stEf(()=>{ const u=Store.on(()=>setTick(t=>t+1)); return u; },[]);
  const transporters = Store.all('transporterMaster','group');
  const entries = stMemo(()=>stBuildLedger(fTr, isGroup?'':coId, fFrom, fTo, fType),[fTr,coId,fFrom,fTo,fType,tick]);
  const selTr   = transporters.find(t=>t.id===fTr);
  const kpi     = stMemo(()=>{
    if(!entries.length) return null;
    return { credit:entries.reduce((s,e)=>s+e.credit,0), debit:entries.reduce((s,e)=>s+e.debit,0),
      bal:entries[entries.length-1]?.bal||0,
      freight:entries.filter(e=>e.txType==='Freight Earned').reduce((s,e)=>s+e.credit,0),
      diesel:entries.filter(e=>e.txType==='Diesel Issued').reduce((s,e)=>s+e.debit,0) };
  },[entries]);
  const TX_CLR = {'Freight Earned':{bg:'#DCFCE7',color:'#166534'},'Diesel Issued':{bg:'#FEF3C7',color:'#92400E'},'Settlement Payment':{bg:'#DBEAFE',color:'#1E40AF'}};

  function exportCSV(){
    const hdr='Date,Ref,Type,Description,Debit,Credit,Balance,Company';
    const rows=entries.map(e=>`"${e.date}","${e.ref}","${e.txType}","${e.desc}","${e.debit||''}","${e.credit||''}","${e.bal}","${Store.name('companies',e.coId)||''}"`).join('\n');
    const blob=new Blob([hdr+'\n'+rows],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`ledger_${selTr?.name||'transporter'}.csv`;a.click();
    window.toast&&window.toast('Ledger exported','ok');
  }

  return (
    <div>
      <div className="frow">
        <window.FiltSelect placeholder="Select Transporter…" value={fTr} onChange={v=>setFTr(v)} style={{minWidth:200}} options={transporters.map(t=>({value:t.id,label:t.name}))}/>
        <input className="inp" type="date" value={fFrom} onChange={e=>setFFrom(e.target.value)} style={{width:140,height:30}}/>
        <input className="inp" type="date" value={fTo} onChange={e=>setFTo(e.target.value)} style={{width:140,height:30}}/>
        <window.FiltSelect value={fType} onChange={v=>setFType(v)} style={{minWidth:160}} options={LGR_TX_TYPES.map(t=>({value:t==='All Types'?'':t,label:t}))}/>
        {fTr&&entries.length>0&&<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 className="f-cnt">{fTr?entries.length+' entries':''}</span>
      </div>

      {!fTr ? (
        <div style={{textAlign:'center',padding:'64px 20px',color:'var(--txt2)'}}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{color:'var(--txt3)',marginBottom:12}}><path d="M9 11l3 3L22 4"/><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
          <div style={{fontSize:13,fontWeight:500}}>Select a transporter to view their ledger</div>
          <div style={{fontSize:11.5,marginTop:4,color:'var(--txt3)'}}>Chronological history of all freight, diesel, deductions, and payments</div>
        </div>
      ) : (
        <>
          {kpi && (
            <div className="kpi-grid" style={{marginBottom:10}}>
              {[['Total Freight',window.fmtCur(kpi.freight),'var(--ok)'],['Total Diesel',window.fmtCur(kpi.diesel),'#B45309'],['Total Credits',window.fmtCur(kpi.credit),'#166534'],['Total Debits',window.fmtCur(kpi.debit),'#DC2626'],['Balance',window.fmtCur(kpi.bal),kpi.bal>=0?'var(--ok)':'#DC2626']].map(([l,v,c])=>(
                <div key={l} className="kpi"><div className="kpi-val" style={{color:c,fontSize:15}}>{v}</div><div className="kpi-lbl">{l}</div></div>
              ))}
            </div>
          )}
          {!entries.length ? (
            <div style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No ledger entries for {selTr?.name} in the selected range.</div>
          ) : (
            <div className="card">
              <div className="tbl-w">
                <table className="tbl">
                  <thead><tr>
                    <th style={{width:26}}></th><th>DATE</th><th>REF</th><th>TYPE</th><th>DESCRIPTION</th>
                    <th style={{textAlign:'right'}}>DEBIT</th><th style={{textAlign:'right'}}>CREDIT</th>
                    <th style={{textAlign:'right'}}>BALANCE</th><th>COMPANY</th>
                  </tr></thead>
                  <tbody>
                    {entries.map(e=>{
                      const isOpen=expId===e.id; const bc=TX_CLR[e.txType];
                      return (
                        <React.Fragment key={e.id}>
                          <tr style={{cursor:'pointer',background:isOpen?'#FFF9F5':e.txType==='Freight Earned'?'#FAFFF8':undefined}} onClick={()=>setExpId(isOpen?null:e.id)}>
                            <td style={{textAlign:'center',padding:'5px 4px'}}><svg width="9" height="9" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .15s',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 style={{fontWeight:500,whiteSpace:'nowrap'}}>{window.fmtDate(e.date)}</td>
                            <td style={{fontFamily:'var(--font)',fontSize:11}}>{e.ref}</td>
                            <td>{bc?<span style={{fontSize:10.5,fontWeight:700,padding:'2px 7px',borderRadius:3,...bc}}>{e.txType}</span>:<DedBadge type={e.txType}/>}</td>
                            <td style={{fontSize:11.5,color:'var(--txt2)',maxWidth:200,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{e.desc}</td>
                            <td style={{textAlign:'right',fontWeight:e.debit?600:400,color:e.debit?'#DC2626':'var(--txt3)'}}>{e.debit?window.fmtCur(e.debit):'—'}</td>
                            <td style={{textAlign:'right',fontWeight:e.credit?600:400,color:e.credit?'var(--ok)':'var(--txt3)'}}>{e.credit?window.fmtCur(e.credit):'—'}</td>
                            <td style={{textAlign:'right',fontWeight:700,color:e.bal>=0?'var(--ok)':'#DC2626'}}>{window.fmtCur(e.bal)}</td>
                            <td style={{fontSize:10.5,color:'var(--txt2)'}}>{Store.name('companies',e.coId)||'—'}</td>
                          </tr>
                          {isOpen&&<tr key={e.id+'-x'}><td colSpan={9} style={{padding:'8px 14px 12px',background:'#FFF9F5',borderTop:'1px solid var(--or-bdr)'}}>
                            <div className="rg-3" style={{gap:10}}>
                              <div><div style={{fontSize:10,color:'var(--txt2)',fontWeight:700,textTransform:'uppercase',letterSpacing:'.5px',marginBottom:3}}>Source Module</div><div style={{fontSize:12,fontWeight:500}}>{e.srcModule}</div></div>
                              <div><div style={{fontSize:10,color:'var(--txt2)',fontWeight:700,textTransform:'uppercase',letterSpacing:'.5px',marginBottom:3}}>Vehicle</div><div style={{fontSize:12,fontFamily:'var(--font)'}}>{e.vehicleNo||'—'}</div></div>
                              <div><div style={{fontSize:10,color:'var(--txt2)',fontWeight:700,textTransform:'uppercase',letterSpacing:'.5px',marginBottom:3}}>Settlement Ref</div><div style={{fontSize:11,fontFamily:'var(--font)',color:'var(--txt2)'}}>{e.settlementId||'—'}</div></div>
                            </div>
                          </td></tr>}
                        </React.Fragment>
                      );
                    })}
                  </tbody>
                  <tfoot><tr style={{background:'#F9FAFB',fontWeight:700}}>
                    <td colSpan={5} style={{textAlign:'right',paddingRight:8,fontSize:11,color:'var(--txt2)'}}>TOTALS</td>
                    <td style={{textAlign:'right',color:'#DC2626'}}>{window.fmtCur(entries.reduce((s,e)=>s+e.debit,0))}</td>
                    <td style={{textAlign:'right',color:'var(--ok)'}}>{window.fmtCur(entries.reduce((s,e)=>s+e.credit,0))}</td>
                    <td style={{textAlign:'right',color:entries[entries.length-1]?.bal>=0?'var(--ok)':'#DC2626'}}>{window.fmtCur(entries[entries.length-1]?.bal||0)}</td>
                    <td></td>
                  </tr></tfoot>
                </table>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ── Main Settlement Page ──────────────────────────────────────────────────────
function TransportSettlementPage() {
  window.useStoreSync();
  const {companyId, session, navParams, clearNavParams} = stCtx(window.AppCtx);
  const isGroup = companyId === 'group';
  const [tab,setTab]=stSt('settlement');
  const [items,setItems]=stSt([]);
  const [modal,setModal]=stSt(false);
  const [editItem,setEditItem]=stSt(null);
  const [delId,setDelId]=stSt(null);
  const [stStatement,setStStatement]=stSt(null);
  const [expId,setExpId]=stSt(null);
  const [search,setSearch]=stSt('');
  const [fStatus,setFStatus]=stSt('');
  const [fTr,setFTr]=stSt('');
  const [fVehicle,setFVehicle]=stSt('');
  const [fPaidThrough,setFPaidThrough]=stSt('');
  const [periodPreset,setPeriodPreset]=stSt('all');
  const [customFrom,setCustomFrom]=stSt('');
  const [customTo,setCustomTo]=stSt('');
  const periodRange = stMemo(()=>window.getDieselPeriodRange(periodPreset, customFrom, customTo),[periodPreset, customFrom, customTo]);
  function setPeriod(id){setPeriodPreset(id);setPg(1);}
  function setCustomRange(f,t){setCustomFrom(f);setCustomTo(t);setPg(1);}
  const [pg,setPg]=stSt(1);
  const PER = 50;

  // Deep-link entry point — a "Open Transport Settlement →" link from the
  // Diesel Split Allocation drilldown lands here with navParams.focusSettlementId.
  stEf(function(){
    if (navParams && navParams.focusSettlementId) {
      setTab('settlement');
      setExpId(navParams.focusSettlementId);
      clearNavParams && clearNavParams();
    }
  }, [navParams]);

  stEf(()=>{ load(); },[companyId]);
  function load(){
    const all = Store.all('settlementRecords')||[];
    const vis = isGroup ? all : all.filter(s=>s.companyId===companyId);
    setItems([...vis].sort((a,b)=>(b.createdDate||'')>(a.createdDate||'')?1:-1));
  }

  const transporters = stMemo(()=>Store.all('transporterMaster','group'),[]);
  const companies = stMemo(()=>Store.all('companies'),[]);

  // Vehicles for selected transporter filter
  const filterVehicles = stMemo(function(){
    if (!fTr) return [];
    return stGetVehiclesForTransporter(fTr, isGroup?'group':companyId);
  }, [fTr, companyId, isGroup]);

  const filtered = stMemo(()=>items.filter(s=>{
    if(fStatus&&s.status!==fStatus) return false;
    if(fTr&&s.transporterId!==fTr) return false;
    if(fVehicle&&s.vehicleFull&&s.vehicleFull!==fVehicle) return false;
    if(fPaidThrough&&s.paidThroughCompanyId!==fPaidThrough) return false;
    if(!window.dieselInPeriod(s.createdDate, periodRange.from, periodRange.to)) return false;
    if(search){const q=search.toLowerCase();return(s.transporterName||'').toLowerCase().includes(q)||(s.periodFrom||'').includes(q)||(s.periodTo||'').includes(q)||(s.vehicleFull||'').toLowerCase().includes(q)||(Store.name('companies',s.companyId)||'').toLowerCase().includes(q);}
    return true;
  }),[items,fStatus,fTr,fVehicle,fPaidThrough,periodRange,search]);

  const paged = filtered.slice((pg-1)*PER, pg*PER);
  const totalPgs = Math.ceil(filtered.length/PER);
  const kpi = stMemo(()=>({
    total:filtered.length,
    trips:filtered.reduce((s,x)=>s+(x.tripCount||0),0),
    gross:filtered.reduce((s,x)=>s+(x.grossFreight||0),0),
    diesel:filtered.reduce((s,x)=>s+(x.dieselDeduction||0),0),
    otherDeds:filtered.reduce((s,x)=>s+Math.max(0,(x.totalDeductions||0)-(x.dieselDeduction||0)),0),
    net:filtered.reduce((s,x)=>s+(x.netPayable||0),0),
    paid:filtered.reduce((s,x)=>s+(x.amountPaid||0),0),
    out:filtered.reduce((s,x)=>s+(x.outstandingBalance||0),0),
  }),[filtered]);

  function openAdd(){setEditItem(null);setModal(true);}
  function openEdit(s){setEditItem(s);setModal(true);}
  function delConfirm(){
    // Release any diesel records locked by this settlement before deleting
    var s = items.find(function(x){ return x.id === delId; });
    if (s && s.challanRows && s.challanRows.length) {
      stUpdateDieselSettlementStatus(s.challanRows, delId, 'Cancelled');
    }
    // Remove associated internal settlement records
    (Store.all('internalSettlements')||[]).filter(function(is){return is.parentSettlementId===delId;}).forEach(function(is){Store.del('internalSettlements',is.id);});
    Store.del('settlementRecords',delId);
    Store.addLog('DELETE','Settlement','Deleted');
    setDelId(null);
    load();
    window.toast&&window.toast('Deleted','ok');
  }

  function exportCSV(){
    const hdr='Transporter,Vehicle,Company,Paid Through Company,From,To,Status,Trips,Qty,Gross Freight,Diesel,Other Deds,Net Payable,Paid,Outstanding';
    const rows=filtered.map(s=>`"${s.transporterName}","${s.vehicleFull||'All'}","${s.companyId==='group'?'OM Group (All Companies)':Store.name('companies',s.companyId)||''}","${s.paidThroughCompanyName||Store.name('companies',s.paidThroughCompanyId)||''}","${s.periodFrom}","${s.periodTo}","${s.status}","${s.tripCount||0}","${s.totalQuantity||0}","${s.grossFreight||0}","${s.dieselDeduction||0}","${(s.totalDeductions||0)-(s.dieselDeduction||0)}","${s.netPayable||0}","${s.amountPaid||0}","${s.outstandingBalance||0}"`).join('\n');
    const blob=new Blob([hdr+'\n'+rows],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='settlements.csv';a.click();
    window.toast&&window.toast('Exported','ok');
  }

  return (
    <div>
      <div className="ph">
        <div>
          <h1>Transporter Settlement</h1>
          <p>Consolidated settlement for all transport trips — Sales Orders, Stockyard Movements, and Debris Movements — with diesel deductions and net payable calculation</p>
        </div>
        <div className="ph-act">
          {tab==='settlement'&&<>
            <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> New Settlement</button>
          </>}
        </div>
      </div>

      {/* Tabs */}
      <div style={{display:'flex',gap:2,marginBottom:12,borderBottom:'2px solid var(--bdr)'}}>
        {[['settlement','Settlement'],['ledger','Ledger']].map(([id,lbl])=>(
          <button key={id} onClick={()=>setTab(id)} style={{padding:'7px 18px',border:'none',background:'none',fontFamily:'var(--font)',fontSize:12.5,fontWeight:600,cursor:'pointer',color:tab===id?'var(--or)':'var(--txt2)',borderBottom:tab===id?'2px solid var(--or)':'2px solid transparent',marginBottom:'-2px',transition:'color .1s'}}>{lbl}</button>
        ))}
      </div>

      {tab==='ledger' ? <SettleLedger coId={companyId} isGroup={isGroup}/> : (
        <>
          <div className="kpi-grid" style={{marginBottom:10}}>
            {[['Settlements',kpi.total,'var(--txt)'],['Gross Freight',window.fmtCur(kpi.gross),'var(--or)'],['Net Payable',window.fmtCur(kpi.net),'#1D4ED8'],['Outstanding',window.fmtCur(kpi.out),kpi.out>0?'#DC2626':'var(--ok)']].map(([l,v,c])=>(
              <div key={l} className="kpi"><div className="kpi-val" style={{color:c}}>{v}</div><div className="kpi-lbl">{l}</div></div>
            ))}
          </div>

          <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, period…"/></div>
            <window.FiltSelect placeholder="All Status" value={fStatus} onChange={v=>{setFStatus(v);setPg(1);}} options={ST_STATUSES.map(s=>({value:s,label:s}))}/>
            <window.FiltSelect placeholder="All Transporters" value={fTr} onChange={v=>{setFTr(v);setFVehicle('');setPg(1);}} options={transporters.map(t=>({value:t.id,label:t.name}))}/>
            {fTr && filterVehicles.length > 0 && (
              <window.FiltSelect placeholder="All Vehicles" value={fVehicle} onChange={v=>{setFVehicle(v);setPg(1);}} options={filterVehicles.map(function(v){return {value:v,label:v};})}/>
            )}
            <window.FiltSelect placeholder="All Paid Through" value={fPaidThrough} onChange={v=>{setFPaidThrough(v);setPg(1);}} options={companies.map(function(c){return {value:c.id,label:c.name};})}/>
            <window.DieselPeriodDropdown preset={periodPreset} onChange={setPeriod} customFrom={customFrom} customTo={customTo} onCustomChange={setCustomRange}/>
            {(search||fStatus||fTr||fVehicle||fPaidThrough||periodPreset!=='all')&&<button className="btn btn-gh btn-sm" onClick={()=>{setSearch('');setFStatus('');setFTr('');setFVehicle('');setFPaidThrough('');setPeriodPreset('all');setCustomFrom('');setCustomTo('');setPg(1);}}>Clear</button>}
            <span className="f-cnt">{filtered.length} settlement{filtered.length!==1?'s':''}</span>
          </div>

          <div className="card">
            <div className="tbl-w">
              <table className="tbl">
                <thead><tr>
                  <th style={{width:26}}></th>
                  {isGroup&&<th>OM GROUP COMPANY</th>}
                  <th>TYPE</th>
                  <th>TRANSPORTER</th><th>VEHICLE</th><th>PERIOD</th><th>PAID THROUGH</th><th style={{textAlign:'center'}}>TRIPS</th>
                  <th style={{textAlign:'right'}}>GROSS FREIGHT</th><th style={{textAlign:'right'}}>DIESEL</th>
                  <th style={{textAlign:'right'}}>OTHER DEDS</th><th style={{textAlign:'right'}}>NET PAYABLE</th>
                  <th style={{textAlign:'right'}}>PAID</th><th style={{textAlign:'right'}}>OUTSTANDING</th>
                  <th>STATUS</th><th>ACTIONS</th>
                </tr></thead>
                <tbody>
                  {!paged.length ? (
                    <tr className="empty"><td colSpan={isGroup?15:14} style={{textAlign:'center',padding:48,color:'var(--txt2)'}}>No settlements yet. Click "+ New Settlement" to create one.</td></tr>
                  ) : paged.map(s=>{
                    const isOpen=expId===s.id;
                    const otherD=(s.totalDeductions||0)-(s.dieselDeduction||0);
                    return (
                      <React.Fragment key={s.id}>
                        <tr style={{background:isOpen?'#FFF9F5':undefined,cursor:'pointer'}} onClick={()=>setExpId(isOpen?null:s.id)}>
                          <td style={{textAlign:'center',padding:'5px 4px'}}><svg width="9" height="9" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .15s',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>
                          {isGroup&&<td><span className="bdg bg-or" style={{fontSize:10}}>{s.companyId==='group'?'OM Group (All)':Store.name('companies',s.companyId)||'—'}</span></td>}
                          <td>{(s.challanRows||[]).some(function(r){return r.settlementMode==='Internal Company Settlement';}) ? <span style={{fontSize:10,fontWeight:700,padding:'2px 7px',borderRadius:3,background:'#EDE9FE',color:'#6D28D9'}}>Internal</span> : <span style={{fontSize:10,fontWeight:700,padding:'2px 7px',borderRadius:3,background:'#DCFCE7',color:'#166534'}}>Standard</span>}</td>
                          <td style={{fontWeight:600}}>{s.transporterName||'—'}</td>
                          <td style={{fontFamily:'var(--font)',fontSize:11}}>{s.vehicleFull||<span style={{color:'var(--txt3)',fontStyle:'italic',fontSize:10}}>All vehicles</span>}</td>
                          <td style={{fontFamily:'var(--font)',fontSize:11,whiteSpace:'nowrap'}}>{window.fmtDate(s.periodFrom)} – {window.fmtDate(s.periodTo)}</td>
                          <td style={{fontSize:11,color:'var(--txt2)'}}>{s.paidThroughCompanyName||(s.paidThroughCompanyId?Store.name('companies',s.paidThroughCompanyId):'')||'—'}</td>
                          <td style={{textAlign:'center',fontWeight:600}}>{s.tripCount||0}</td>
                          <td style={{textAlign:'right',fontWeight:600,color:'var(--ok)'}}>{window.fmtCur(s.grossFreight||0)}</td>
                          <td style={{textAlign:'right',color:'#B45309'}}>{window.fmtCur(s.dieselDeduction||0)}</td>
                          <td style={{textAlign:'right',color:'#DC2626'}}>{window.fmtCur(otherD)}</td>
                          <td style={{textAlign:'right',fontWeight:700,color:'var(--or)',fontSize:13}}>{window.fmtCur(s.netPayable||0)}</td>
                          <td style={{textAlign:'right',color:'var(--ok)'}}>{window.fmtCur(s.amountPaid||0)}</td>
                          <td style={{textAlign:'right',fontWeight:(s.outstandingBalance||0)>0?700:400,color:(s.outstandingBalance||0)>0?'#DC2626':'var(--txt3)'}}>{window.fmtCur(s.outstandingBalance||0)}</td>
                          <td><StBadge s={s.status}/></td>
                          <td onClick={e=>e.stopPropagation()}><div className="ra"><button className="btn btn-wh btn-sm" onClick={()=>openEdit(s)}>Edit</button><button className="btn btn-wh btn-sm" onClick={()=>setStStatement(s)}>Statement</button><button className="btn btn-rd btn-sm" onClick={()=>setDelId(s.id)}>Delete</button></div></td>
                        </tr>
                        {isOpen&&<tr key={s.id+'-exp'}><td colSpan={isGroup?14:13} style={{padding:0,borderTop:'2px solid var(--or-bdr)'}}><SettleDetail s={s}/></td></tr>}
                      </React.Fragment>
                    );
                  })}
                </tbody>
                {filtered.length>0&&(
                  <tfoot>
                    <tr style={{background:'#FFF7ED',borderTop:'2.5px solid var(--or-bdr)'}}>
                      <td style={{padding:'10px 8px'}}></td>
                      <td colSpan={isGroup?6:5} style={{padding:'10px 8px 10px 12px',fontWeight:700,fontSize:11.5,color:'var(--or)',letterSpacing:'.04em',whiteSpace:'nowrap'}}>
                        TOTALS
                        <span style={{fontWeight:400,fontSize:11,color:'var(--txt2)',marginLeft:8}}>{filtered.length} settlement{filtered.length!==1?'s':''}</span>
                      </td>
                      <td style={{textAlign:'center',padding:'10px 8px',fontWeight:700,fontSize:13,color:'var(--txt)',fontVariantNumeric:'tabular-nums'}}>{kpi.trips}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:700,color:'var(--ok)',fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(kpi.gross)}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:700,color:'#B45309',fontVariantNumeric:'tabular-nums'}}>{kpi.diesel?window.fmtCur(kpi.diesel):'—'}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:700,color:'#DC2626',fontVariantNumeric:'tabular-nums'}}>{kpi.otherDeds?window.fmtCur(kpi.otherDeds):'—'}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:800,color:'var(--or)',fontSize:14,fontVariantNumeric:'tabular-nums'}}>{window.fmtCur(kpi.net)}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:700,color:'var(--ok)',fontVariantNumeric:'tabular-nums'}}>{kpi.paid?window.fmtCur(kpi.paid):'—'}</td>
                      <td style={{textAlign:'right',padding:'10px 8px',fontWeight:800,color:kpi.out>0?'#DC2626':'var(--txt3)',fontVariantNumeric:'tabular-nums'}}>{kpi.out?window.fmtCur(kpi.out):'—'}</td>
                      <td style={{padding:'10px 8px'}}></td>
                      <td style={{padding:'10px 8px'}}></td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>

          {totalPgs>1&&<div className="pag">
            <button className="pg-b" disabled={pg===1} onClick={()=>setPg(p=>p-1)}>‹</button>
            {Array.from({length:Math.min(totalPgs,7)},(_,i)=><button key={i+1} className={`pg-b${pg===i+1?' on':''}`} onClick={()=>setPg(i+1)}>{i+1}</button>)}
            <button className="pg-b" disabled={pg===totalPgs} onClick={()=>setPg(p=>p+1)}>›</button>
            <span className="pg-inf">{pg}/{totalPgs}</span>
          </div>}
        </>
      )}

      {modal&&<SettleModal item={editItem} coId={companyId} isGroup={isGroup} session={session} onSaved={()=>{setModal(false);load();}} onClose={()=>setModal(false)}/>}
      {delId&&<div className="mbg"><div className="mod mod-sm">
        <div className="mod-hd"><h2>Delete Settlement</h2><button className="mod-x" onClick={()=>setDelId(null)}>×</button></div>
        <div className="mod-bd"><p style={{fontSize:13,lineHeight:1.6}}>Delete this settlement record? Transport Reports and Diesel records are <strong>not affected</strong>. Challan settlement status will not be automatically reverted.</p></div>
        <div className="mod-ft"><button className="btn btn-wh" onClick={()=>setDelId(null)}>Cancel</button><button className="btn btn-rd" onClick={delConfirm}>Delete</button></div>
      </div></div>}
      {stStatement&&<window.TransportSettlementStatement settlement={stStatement} onClose={()=>setStStatement(null)} session={session}/>}
    </div>
  );
}

// ── Settlement Policy Engine — single source of truth for ALL modules ────────
// Transport Report, Dashboard, Exports, and every future module calls this.
// Never hardcodes vehicle numbers, company names, margins, or modes.
// Architecture: Vehicle Master → Settlement Policy Master → Margin → Final Rate
window.SettlementEngine = {
  /** Look up the active settlement policy for a vehicle number */
  getPolicy: stGetVehiclePolicy,
  /** Calculate margin given a policy, quantity and base gross amount */
  calcMargin: stCalcPolicyMargin,
  /**
   * Full adjustment result for one transport entry row.
   * Returns {hasPolicy, baseGross, marginAmount, marginPerUnit, adjustedGross,
   *          policyName, marginType, marginValue, receivingCompanyId, policy}
   */
  getAdjustedRate: function(vehicleFull, qty, baseGross) {
    var policy = stGetVehiclePolicy(vehicleFull);
    var isInternal = !!(policy && policy.status === 'Active' && policy.settlementMode === 'Internal Company Settlement');
    if (!isInternal) {
      return { hasPolicy:false, baseGross:baseGross, marginAmount:0, marginPerUnit:0, adjustedGross:baseGross, policy:null };
    }
    var margin = stCalcPolicyMargin(policy, qty, baseGross);
    return {
      hasPolicy:         true,
      policy:            policy,
      baseGross:         baseGross,
      marginAmount:      margin.marginAmount,
      marginPerUnit:     margin.marginPerUnit,
      adjustedGross:     margin.adjustedGross,
      policyName:        policy.policyName,
      marginType:        policy.marginType,
      marginValue:       policy.marginValue,
      receivingCompanyId:policy.receivingCompanyId,
    };
  },
};

window.TransportSettlementPage = TransportSettlementPage;
