// ═══════════════════════════════════════════════════════════════════════════════
// DIESEL ALLOCATION ENGINE — Role-Based Diesel Allocation for Multi-Role Parties
// ═══════════════════════════════════════════════════════════════════════════════
// Architecture: Every diesel record can be allocated to Transport Settlement,
// Vendor Settlement, or Split between both. Single-role parties auto-allocate.
// Multi-role parties require explicit allocation.
//
// Fields added to dieselRecords:
//   dieselAllocRole     — 'Transport' | 'Vendor' | 'Split' (default: undefined = Transport)
//   vendorAllocAmount   — ₹ allocated to vendor settlement (Split mode)
//   transportAllocAmount— ₹ allocated to transport settlement (Split mode)
//   vendorAllocLitres   — litres allocated to vendor (Split mode)
//   transportAllocLitres— litres allocated to transport (Split mode)
//   allocVendorId       — matched vendor ID for vendor allocation
//   allocHistory        — [{timestamp, fromRole, toRole, reason, changedBy, ...}]
// ═══════════════════════════════════════════════════════════════════════════════

const { useState: daSt, useMemo: daMemo, useEffect: daEf } = React;

// ── Party Role Detection ────────────────────────────────────────────────────
// Given a transporter master ID, detects if the same party also exists as a
// material vendor. Uses case-insensitive name matching with fuzzy containment
// for suffix variations like "(Gunaji)".
window.getPartyRoles = function(transporterId) {
  if (!transporterId) return { roles: [], matchedVendors: [], isMultiRole: false };
  var tm = (Store.all('transporterMaster','group')||[]).find(function(t) { return t.id === transporterId; });
  if (!tm) return { roles: ['Transporter'], matchedVendors: [], isMultiRole: false };
  var trName = (tm.name||'').toLowerCase().trim();
  if (!trName) return { roles: ['Transporter'], matchedVendors: [], isMultiRole: false };
  var matchedVendors = (Store.all('vendors')||[]).filter(function(v) {
    if (!v.name) return false;
    var vName = (v.name).toLowerCase().trim();
    if (vName === trName) return true;
    // Containment match — requires ≥5 char overlap to avoid false positives
    var shorter = vName.length < trName.length ? vName : trName;
    if (shorter.length >= 5 && (vName.includes(trName) || trName.includes(vName))) return true;
    return false;
  });
  var roles = ['Transporter'];
  if (matchedVendors.length > 0) roles.push('Vendor');
  return { roles: roles, matchedVendors: matchedVendors, isMultiRole: roles.length > 1 };
};

// ── Allocation Amount Helpers ───────────────────────────────────────────────
// Transport Settlement uses this to determine how much diesel to deduct.
window.getDieselTransportAmount = function(d) {
  var role = d.dieselAllocRole;
  if (!role || role === 'Transport') return parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
  if (role === 'Vendor') return 0;
  if (role === 'Split') return parseFloat(d.transportAllocAmount) || 0;
  return parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
};

// Vendor Settlement uses this to determine how much diesel to deduct.
window.getDieselVendorAmount = function(d) {
  var role = d.dieselAllocRole;
  if (!role || role === 'Transport') return 0;
  if (role === 'Vendor') return parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
  if (role === 'Split') return parseFloat(d.vendorAllocAmount) || 0;
  return 0;
};

// ── Vendor Diesel from dieselRecords (role-allocated) ───────────────────────
// Returns diesel records from dieselRecords allocated (fully or partially) to
// a specific vendor. Used by Vendor Settlement module.
window.getDieselRecordsForVendor = function(vendorId, periodFrom, periodTo, coId, currentSettlementId) {
  if (!vendorId || !periodFrom || !periodTo) return { records: [], total: 0, litres: 0 };
  var vendor = (Store.all('vendors')||[]).find(function(v) { return v.id === vendorId; });
  var vendorName = vendor ? (vendor.name||'').toLowerCase().trim() : '';
  if (!vendorName) return { records: [], total: 0, litres: 0 };

  var records = (Store.all('dieselRecords', 'group') || []).filter(function(d) {
    var role = d.dieselAllocRole;
    if (!role || role === 'Transport') return false;
    // Vendor match — by explicit allocVendorId or name matching
    if (d.allocVendorId) {
      if (d.allocVendorId !== vendorId) return false;
    } else {
      var trName = (d.transporterName||'').toLowerCase().trim();
      var shorter = trName.length < vendorName.length ? trName : vendorName;
      if (trName !== vendorName && !(shorter.length >= 5 && (trName.includes(vendorName) || vendorName.includes(trName)))) return false;
    }
    if (coId && coId !== 'group' && d.companyId !== coId) return false;
    var dt = (d.date || d.periodStart || '').trim();
    if (!dt || dt < periodFrom || dt > periodTo) return false;
    // Settlement lock check
    if (d.vendorSettledInId) {
      if (currentSettlementId && d.vendorSettledInId === currentSettlementId) return true;
      var existing = (Store.all('vendorSettlements')||[]).find(function(s) { return s.id === d.vendorSettledInId; });
      if (existing && existing.status !== 'Cancelled') return false;
    }
    return true;
  });

  var total = records.reduce(function(s, d) { return s + window.getDieselVendorAmount(d); }, 0);
  var litres = records.reduce(function(s, d) {
    var role = d.dieselAllocRole;
    if (role === 'Vendor') return s + (parseFloat(d.litres) || 0);
    if (role === 'Split') return s + (parseFloat(d.vendorAllocLitres) || 0);
    return s;
  }, 0);
  return { records: records, total: total, litres: litres };
};

// ── Allocation Badge ────────────────────────────────────────────────────────
function AllocBadge({ record }) {
  var role = record.dieselAllocRole;
  if (!role || role === 'Transport') return React.createElement('span', {className:'bdg bg-bl',style:{fontSize:10,padding:'1px 6px'}}, 'Transport');
  if (role === 'Vendor') return React.createElement('span', {className:'bdg bg-pu',style:{fontSize:10,padding:'1px 6px'}}, 'Vendor');
  if (role === 'Split') {
    var va = parseFloat(record.vendorAllocAmount)||0;
    var ta = parseFloat(record.transportAllocAmount)||0;
    return React.createElement('span', {className:'bdg bg-yw',style:{fontSize:10,padding:'1px 6px'},
      title:'Transport: '+window.fmtCur(ta)+' · Vendor: '+window.fmtCur(va)}, 'Split');
  }
  return null;
}
window.AllocBadge = AllocBadge;

// ── Rich Split Badge — shows the ₹ breakdown inline instead of a bare "Split" pill ──
// Used in the Allocation Report table where there's room for 3 short lines.
function SplitAllocBadge({ record }) {
  var role = record.dieselAllocRole;
  if (role !== 'Split') return React.createElement(AllocBadge, {record: record});
  var va = parseFloat(record.vendorAllocAmount)||0;
  var ta = parseFloat(record.transportAllocAmount)||0;
  var total = va + ta;
  return React.createElement('div', {style:{display:'inline-flex',flexDirection:'column',gap:1,background:'#F5F3FF',border:'1px solid #DDD6FE',borderRadius:6,padding:'4px 8px',minWidth:118}},
    React.createElement('div', {style:{fontSize:9.5,fontWeight:800,color:'#6D28D9',letterSpacing:'.03em',marginBottom:1}}, 'SPLIT ALLOCATION'),
    React.createElement('div', {style:{display:'flex',justifyContent:'space-between',fontSize:10.5,color:'#374151'}},
      React.createElement('span', null, 'Vendor'), React.createElement('span', {style:{fontWeight:700}}, window.fmtCur(va))
    ),
    React.createElement('div', {style:{display:'flex',justifyContent:'space-between',fontSize:10.5,color:'#374151'}},
      React.createElement('span', null, 'Transport'), React.createElement('span', {style:{fontWeight:700}}, window.fmtCur(ta))
    ),
    React.createElement('div', {style:{display:'flex',justifyContent:'space-between',fontSize:10.5,fontWeight:800,color:'#111827',borderTop:'1px dashed #DDD6FE',marginTop:2,paddingTop:2}},
      React.createElement('span', null, 'Total'), React.createElement('span', null, window.fmtCur(total))
    )
  );
}
window.SplitAllocBadge = SplitAllocBadge;

// ── Split Reference ID Generator ─────────────────────────────────────────────
// Format: DSL-SP-000145 — sequential, scoped across all dieselRecords.
window.genSplitRefId = function() {
  var all = Store.all('dieselRecords','group') || [];
  var max = 0;
  all.forEach(function(d) {
    if (d.splitRefId) {
      var m = /DSL-SP-(\d+)/.exec(d.splitRefId);
      if (m) { var n = parseInt(m[1],10); if (n > max) max = n; }
    }
  });
  var next = max + 1;
  return 'DSL-SP-' + String(next).padStart(6,'0');
};

// ── Diesel Allocation Section (Form Component) ─────────────────────────────
// Displayed inside the diesel entry form when the selected transporter also
// exists as a material vendor. Handles three allocation modes.
function DieselAllocationSection({ transporterId, totalAmount, totalLitres, form, setF }) {
  var partyInfo = daMemo(function() { return window.getPartyRoles(transporterId); }, [transporterId]);
  if (!partyInfo.isMultiRole) return null;

  var allocRole = form.dieselAllocRole || 'Transport';
  var vendorLabel = partyInfo.matchedVendors.length > 0 ? partyInfo.matchedVendors[0].name : 'Vendor';

  return (
    React.createElement('div', {style:{background:'#FFF7ED',border:'2px solid var(--or-bdr)',borderRadius:10,padding:'14px 16px',marginBottom:16}},
      /* Header */
      React.createElement('div', {style:{display:'flex',alignItems:'flex-start',gap:8,marginBottom:12}},
        React.createElement('svg', {width:16,height:16,viewBox:'0 0 24 24',fill:'none',stroke:'var(--or)',strokeWidth:2.5,style:{flexShrink:0,marginTop:1}},
          React.createElement('circle', {cx:12,cy:12,r:10}),
          React.createElement('line', {x1:12,y1:8,x2:12,y2:12}),
          React.createElement('line', {x1:12,y1:16,x2:12.01,y2:16})
        ),
        React.createElement('div', null,
          React.createElement('div', {style:{fontWeight:700,fontSize:13,color:'var(--or)'}}, 'Multi-Role Party Detected'),
          React.createElement('div', {style:{fontSize:11,color:'var(--txt2)',marginTop:1}},
            'This transporter also operates as Material Vendor ',
            React.createElement('strong', null, vendorLabel),
            '. Allocate diesel to the correct business role.'
          )
        )
      ),

      /* Radio options */
      React.createElement('div', {style:{fontWeight:700,fontSize:10,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}, 'ALLOCATE DIESEL TO'),
      React.createElement('div', {style:{display:'flex',gap:8,marginBottom: allocRole === 'Split' ? 14 : 0,flexWrap:'wrap'}},
        [{v:'Transport',lbl:'Transport Settlement',desc:'Full diesel deducted from transporter freight'},
         {v:'Vendor',lbl:'Vendor Settlement',desc:'Full diesel deducted from vendor payable'},
         {v:'Split',lbl:'Split Allocation',desc:'Split between both settlement modules'}
        ].map(function(opt) {
          var sel = allocRole === opt.v;
          return React.createElement('div', {key:opt.v, onClick:function() {
            setF('dieselAllocRole', opt.v);
            if (opt.v !== 'Split') {
              setF('vendorAllocAmount',''); setF('transportAllocAmount','');
              setF('vendorAllocLitres',''); setF('transportAllocLitres','');
            } else {
              var halfAmt = Math.round(totalAmount/2*100)/100;
              var halfLit = Math.round(totalLitres/2*1000)/1000;
              setF('transportAllocAmount', halfAmt);
              setF('vendorAllocAmount', Math.round((totalAmount-halfAmt)*100)/100);
              setF('transportAllocLitres', halfLit);
              setF('vendorAllocLitres', Math.round((totalLitres-halfLit)*1000)/1000);
            }
            if (partyInfo.matchedVendors.length > 0) setF('allocVendorId', partyInfo.matchedVendors[0].id);
          }, style:{flex:'1 1 140px',border:sel?'2px solid var(--or)':'1.5px solid var(--bdr)',borderRadius:8,padding:'10px 12px',cursor:'pointer',background:sel?'var(--or-lt)':'#fff',transition:'all .15s'}},
            React.createElement('div', {style:{display:'flex',alignItems:'center',gap:6,marginBottom:3}},
              React.createElement('div', {style:{width:16,height:16,borderRadius:'50%',border:sel?'5px solid var(--or)':'2px solid var(--bdr)',background:'#fff',flexShrink:0}}),
              React.createElement('span', {style:{fontWeight:700,fontSize:12,color:sel?'var(--or)':'var(--txt)'}}, opt.lbl)
            ),
            React.createElement('div', {style:{fontSize:10.5,color:'var(--txt2)',paddingLeft:22}}, opt.desc)
          );
        })
      ),

      /* Split fields */
      allocRole === 'Split' && React.createElement('div', {style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div', {style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10,paddingBottom:8,borderBottom:'1px solid var(--bdr)'}},
          React.createElement('span', {style:{fontWeight:700,fontSize:12,color:'var(--txt)'}}, 'Total Diesel Deduction'),
          React.createElement('span', {style:{fontWeight:800,fontSize:15,color:'var(--or)'}}, window.fmtCur(totalAmount))
        ),
        React.createElement('div', {className:'fg',style:{marginBottom:10}},
          React.createElement('div', {className:'fld'},
            React.createElement('label', null, 'Recover From Vendor ', React.createElement('span', {className:'req'}, '*')),
            React.createElement('input', {className:'inp',type:'number',min:0,step:0.01,
              value:form.vendorAllocAmount||'',
              onChange:function(e) {
                var va = parseFloat(e.target.value)||0;
                setF('vendorAllocAmount', e.target.value);
                // Only update vendor litres — never touch transport fields
                var pct = totalAmount > 0 ? va / totalAmount : 0;
                setF('vendorAllocLitres', Math.round(totalLitres*pct*1000)/1000);
              },
              placeholder:'₹0.00', style:{fontWeight:700}
            })
          ),
          React.createElement('div', {className:'fld'},
            React.createElement('label', null, 'Recover From Transport ', React.createElement('span', {className:'req'}, '*')),
            React.createElement('input', {className:'inp',type:'number',min:0,step:0.01,
              value:form.transportAllocAmount||'',
              onChange:function(e) {
                var ta = parseFloat(e.target.value)||0;
                setF('transportAllocAmount', e.target.value);
                // Only update transport litres — never touch vendor fields
                var pct = totalAmount > 0 ? ta / totalAmount : 0;
                setF('transportAllocLitres', Math.round(totalLitres*pct*1000)/1000);
              },
              placeholder:'₹0.00', style:{fontWeight:700}
            })
          )
        ),
        /* Balance validation */
        (function() {
          // Issue 2 fix: normalise all operands to 2dp before comparison so
          // 3dp-precision deductionAmount never produces a spurious mismatch.
          var _tot2dp = Math.round((totalAmount||0)*100)/100;
          var va = Math.round((parseFloat(form.vendorAllocAmount)||0)*100)/100;
          var ta = Math.round((parseFloat(form.transportAllocAmount)||0)*100)/100;
          var remaining = Math.round((_tot2dp - va - ta)*100)/100;
          var balanced = Math.abs(remaining) < 0.02;
          return React.createElement('div', {style:{
            background: balanced?'#DCFCE7':'#FEE2E2',
            border:'1px solid '+(balanced?'#BBF7D0':'#FECACA'),
            borderRadius:4, padding:'6px 10px', fontSize:11.5,
            color: balanced?'#166534':'#991B1B', fontWeight:600,
            display:'flex', alignItems:'center', gap:6
          }},
            balanced
              ? React.createElement(React.Fragment, null,
                  React.createElement('svg', {width:12,height:12,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:2.5},
                    React.createElement('polyline', {points:'20 6 9 17 4 12'})
                  ),
                  'Balanced — Vendor '+window.fmtCur(va)+' + Transport '+window.fmtCur(ta)+' = '+window.fmtCur(totalAmount)
                )
              : (remaining > 0 ? 'Unallocated: '+window.fmtCur(remaining)+' — must be ₹0 to save' :
                 'Over-allocated by '+window.fmtCur(Math.abs(remaining))+' — reduce amounts')
          );
        })()
      )
    )
  );
}
window.DieselAllocationSection = DieselAllocationSection;

// ── Adjust Allocation Modal ─────────────────────────────────────────────────
// Allows changing diesel allocation after creation. Records audit trail.
function AdjustAllocationModal({ record, onClose, onSaved, session }) {
  var totalAmount = parseFloat(record.deductionAmount) || parseFloat(record.amount) || 0;
  var totalLitres = parseFloat(record.litres) || 0;
  var partyInfo = window.getPartyRoles(record.transporterId);
  var [role, setRole] = daSt(record.dieselAllocRole || 'Transport');
  var [vendorAmt, setVendorAmt] = daSt(
    record.dieselAllocRole === 'Split' ? (record.vendorAllocAmount||0) :
    record.dieselAllocRole === 'Vendor' ? totalAmount : 0
  );
  var [transportAmt, setTransportAmt] = daSt(
    record.dieselAllocRole === 'Split' ? (record.transportAllocAmount||0) :
    (!record.dieselAllocRole || record.dieselAllocRole === 'Transport') ? totalAmount : 0
  );
  var [reason, setReason] = daSt('');
  var trName = record.transporterName || Store.name('transporterMaster', record.transporterId) || '—';

  function handleRoleChange(r) {
    setRole(r);
    if (r === 'Transport') { setTransportAmt(totalAmount); setVendorAmt(0); }
    else if (r === 'Vendor') { setTransportAmt(0); setVendorAmt(totalAmount); }
    else { var h = Math.round(totalAmount/2*100)/100; setTransportAmt(h); setVendorAmt(Math.round((totalAmount-h)*100)/100); }
  }

  function handleSave() {
    if (!reason.trim()) { window.toast&&window.toast('Reason for change is required','er'); return; }
    if (role === 'Split') {
      var _tot2dp = Math.round((totalAmount||0)*100)/100;
      var va = Math.round((parseFloat(vendorAmt)||0)*100)/100, ta = Math.round((parseFloat(transportAmt)||0)*100)/100;
      if (Math.abs(_tot2dp - va - ta) > 0.02) {
        window.toast&&window.toast('Vendor ('+window.fmtCur(va)+') + Transport ('+window.fmtCur(ta)+') must equal total diesel ('+window.fmtCur(_tot2dp)+')','er'); return;
      }
      vendorAmt = va; transportAmt = ta;
    }
    var rec = (Store.all('dieselRecords','group')||[]).find(function(r){ return r.id === record.id; });
    if (!rec) { window.toast&&window.toast('Record not found','er'); return; }

    var fromAlloc = { role: rec.dieselAllocRole||'Transport', vendorAmount: rec.vendorAllocAmount||0, transportAmount: rec.transportAllocAmount||(parseFloat(rec.deductionAmount)||parseFloat(rec.amount)||0) };
    var toVA = role==='Vendor'?totalAmount : role==='Split'?(parseFloat(vendorAmt)||0) : 0;
    var toTA = role==='Transport'?totalAmount : role==='Split'?(parseFloat(transportAmt)||0) : 0;
    var toAlloc = { role:role, vendorAmount:toVA, transportAmount:toTA };

    var history = (rec.allocHistory||[]).slice();
    history.push({
      id: Date.now().toString(36)+Math.random().toString(36).slice(2,6),
      timestamp: new Date().toISOString(),
      fromRole: fromAlloc.role, fromVendorAmount: fromAlloc.vendorAmount, fromTransportAmount: fromAlloc.transportAmount,
      toRole: toAlloc.role, toVendorAmount: toAlloc.vendorAmount, toTransportAmount: toAlloc.transportAmount,
      reason: reason,
      changedBy: (session&&session.userName)||'User',
    });

    var pctV = totalAmount > 0 ? toVA/totalAmount : 0;
    var updates = {
      dieselAllocRole: role,
      vendorAllocAmount: toVA,
      transportAllocAmount: toTA,
      vendorAllocLitres: Math.round(totalLitres*pctV*1000)/1000,
      transportAllocLitres: Math.round(totalLitres*(1-pctV)*1000)/1000,
      allocVendorId: partyInfo.matchedVendors.length > 0 ? partyInfo.matchedVendors[0].id : (rec.allocVendorId||''),
      allocHistory: history,
    };
    Store.update('dieselRecords', record.id, Object.assign({}, rec, updates));
    Store.addLog('UPDATE', 'Diesel Allocation', 'Adjusted: '+(rec.vehicleFull||'')+' — '+fromAlloc.role+' → '+toAlloc.role+' ('+reason+')');
    window.toast&&window.toast('Allocation adjusted','ok');
    onSaved&&onSaved();
    onClose();
  }

  return (
    React.createElement('div', {className:'mbg'},
      React.createElement('div', {className:'mod mod-md'},
        React.createElement('div', {className:'mod-hd'},
          React.createElement('h2', null, 'Adjust Diesel Allocation'),
          React.createElement('button', {className:'mod-x',onClick:onClose}, '×')
        ),
        React.createElement('div', {className:'mod-bd'},
          /* Record info */
          React.createElement('div', {style:{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 14px',marginBottom:14}},
            React.createElement('div', {className:'fg'},
              React.createElement('div', null,
                React.createElement('div', {style:{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em'}}, 'VEHICLE'),
                React.createElement('div', {style:{fontSize:13,fontWeight:700,color:'var(--txt)',marginTop:2}}, record.vehicleFull||'—')
              ),
              React.createElement('div', null,
                React.createElement('div', {style:{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em'}}, 'TRANSPORTER'),
                React.createElement('div', {style:{fontSize:13,fontWeight:600,color:'var(--txt)',marginTop:2}}, trName)
              ),
              React.createElement('div', null,
                React.createElement('div', {style:{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em'}}, 'TOTAL DIESEL'),
                React.createElement('div', {style:{fontSize:16,fontWeight:800,color:'var(--or)',marginTop:2}}, window.fmtCur(totalAmount))
              ),
              React.createElement('div', null,
                React.createElement('div', {style:{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em'}}, 'LITRES'),
                React.createElement('div', {style:{fontSize:13,fontWeight:700,color:'var(--txt)',marginTop:2}}, window.fmtDieselQty(totalLitres)+' L')
              )
            )
          ),

          /* Allocation radio */
          React.createElement('div', {style:{fontWeight:700,fontSize:10,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}, 'ALLOCATE TO'),
          React.createElement('div', {style:{display:'flex',gap:8,marginBottom:14,flexWrap:'wrap'}},
            [{v:'Transport',lbl:'Transport Settlement'},{v:'Vendor',lbl:'Vendor Settlement'},{v:'Split',lbl:'Split Allocation'}].map(function(opt) {
              var sel = role === opt.v;
              return React.createElement('div', {key:opt.v, onClick:function(){handleRoleChange(opt.v);},
                style:{flex:'1 1 120px',border:sel?'2px solid var(--or)':'1.5px solid var(--bdr)',borderRadius:8,padding:'8px 12px',cursor:'pointer',background:sel?'var(--or-lt)':'#fff',transition:'all .15s',display:'flex',alignItems:'center',gap:6}},
                React.createElement('div', {style:{width:14,height:14,borderRadius:'50%',border:sel?'4px solid var(--or)':'2px solid var(--bdr)',background:'#fff',flexShrink:0}}),
                React.createElement('span', {style:{fontWeight:600,fontSize:12,color:sel?'var(--or)':'var(--txt)'}}, opt.lbl)
              );
            })
          ),

          /* Split fields */
          role === 'Split' && React.createElement('div', {style:{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 14px',marginBottom:14}},
            React.createElement('div', {className:'fg',style:{marginBottom:8}},
              React.createElement('div', {className:'fld'},
                React.createElement('label', null, 'Vendor Allocation'),
                React.createElement('input', {className:'inp',type:'number',min:0,step:0.01,value:vendorAmt,
                  onChange:function(e){setVendorAmt(e.target.value);}})
              ),
              React.createElement('div', {className:'fld'},
                React.createElement('label', null, 'Transport Allocation'),
                React.createElement('input', {className:'inp',type:'number',min:0,step:0.01,value:transportAmt,
                  onChange:function(e){setTransportAmt(e.target.value);}})
              )
            ),
            (function(){
              var _tot2dp=Math.round((totalAmount||0)*100)/100;
              var va=Math.round((parseFloat(vendorAmt)||0)*100)/100, ta=Math.round((parseFloat(transportAmt)||0)*100)/100;
              var rem=Math.round((_tot2dp-va-ta)*100)/100;
              var ok=Math.abs(rem)<0.02;
              return React.createElement('div', {style:{fontSize:11,fontWeight:600,color:ok?'#166534':'#991B1B'}},
                ok ? 'Balanced: Vendor '+window.fmtCur(va)+' + Transport '+window.fmtCur(ta) : (rem>0?'Unallocated: '+window.fmtCur(rem):'Over-allocated')
              );
            })()
          ),

          /* Reason */
          React.createElement('div', {className:'fld'},
            React.createElement('label', null, 'Reason for Change ', React.createElement('span', {className:'req'}, '*')),
            React.createElement('input', {className:'inp',value:reason,onChange:function(e){setReason(e.target.value);},placeholder:'e.g. Incorrect initial allocation',autoFocus:true})
          ),

          /* Audit history */
          (record.allocHistory && record.allocHistory.length > 0) && React.createElement('div', {style:{marginTop:14}},
            React.createElement('div', {style:{fontWeight:700,fontSize:10,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:6}}, 'ALLOCATION HISTORY'),
            React.createElement('div', {style:{maxHeight:140,overflowY:'auto'}},
              record.allocHistory.slice().reverse().map(function(h) {
                return React.createElement('div', {key:h.id, style:{display:'flex',gap:8,padding:'5px 0',borderBottom:'1px solid #F3F4F6',fontSize:11}},
                  React.createElement('span', {style:{color:'var(--txt3)',flexShrink:0,width:120}}, new Date(h.timestamp).toLocaleString('en-IN',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'})),
                  React.createElement('span', {style:{fontWeight:600}}, h.fromRole,' → ',h.toRole),
                  h.reason && React.createElement('span', {style:{color:'var(--txt2)',fontStyle:'italic'}}, '— ',h.reason),
                  React.createElement('span', {style:{color:'var(--txt3)',marginLeft:'auto'}}, h.changedBy)
                );
              })
            )
          )
        ),
        React.createElement('div', {className:'mod-ft'},
          React.createElement('button', {className:'btn btn-wh',onClick:onClose}, 'Cancel'),
          React.createElement('button', {className:'btn btn-or',onClick:handleSave}, 'Save Allocation')
        )
      )
    )
  );
}
window.AdjustAllocationModal = AdjustAllocationModal;

// ── Link/Auto/Split badge chips — shared visual vocabulary (spec §17) ──────
function LinkChip({ children, onClick }) {
  return React.createElement('button', {onClick:onClick, style:{
    display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:700,color:'#1D4ED8',
    background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:6,padding:'5px 10px',cursor:'pointer'
  }}, children, ' →');
}
function AutoGenChip() {
  return React.createElement('span', {style:{fontSize:10,fontWeight:600,color:'#374151',background:'#F3F4F6',border:'1px solid #E5E7EB',borderRadius:4,padding:'2px 7px',display:'inline-flex',alignItems:'center',gap:3}}, 'Auto Generated');
}

// ── Split Allocation Drilldown Panel ────────────────────────────────────────
// Role-aware traceability drilldown (Transport / Vendor / Split).
// Issue 5 fix: dynamic panels per allocation type with spec-required fields.
// Issue 4 fix: auto-gen metadata (Source Module, Allocation ID, Challan,
//              Bill, Generated Time/By, Status) shown as immutable fields.
// Issue 6 fix: bidirectional navigation buttons for every linked settlement.
// Issue 8 fix: complete audit trail with old/new values and reason field.
function SplitAllocationDrilldown({ record: d, navigate }) {
  // ── Issue 5: Role-aware state ───────────────────────────────────────────
  var role = d.dieselAllocRole || 'Transport';
  var totalAmt = parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
  // Canonical amounts — single-role records use full amount for their side
  var va = role === 'Split' ? (parseFloat(d.vendorAllocAmount)    || 0) : (role === 'Vendor'    ? totalAmt : 0);
  var ta = role === 'Split' ? (parseFloat(d.transportAllocAmount) || 0) : (role === 'Transport' ? totalAmt : 0);
  var remaining = Math.round((totalAmt - va - ta) * 100) / 100;
  var balanced  = Math.abs(remaining) < 0.02;

  var trName = d.transporterName || Store.name('transporterMaster', d.transporterId) || '—';
  var partyInfo  = window.getPartyRoles(d.transporterId);
  var vendorName = partyInfo.matchedVendors.length > 0
    ? partyInfo.matchedVendors[0].name
    : (d.allocVendorId ? Store.name('vendors', d.allocVendorId) : trName);

  var vendorSettlement    = d.vendorSettledInId      ? (Store.all('vendorSettlements')||[]).find(function(s){return s.id===d.vendorSettledInId;})      : null;
  var transportSettlement = d.settledInSettlementId  ? (Store.all('settlementRecords') ||[]).find(function(s){return s.id===d.settledInSettlementId;}) : null;

  // Challan purchase for gross freight lookup
  var challanPO    = d.challanNumber ? (Store.all('purchases')||[]).find(function(p){return p.challanNumber===d.challanNumber;}) : null;
  var grossFreight = challanPO ? (parseFloat(challanPO.sub)||parseFloat(challanPO.subtotal)||0) : 0;

  // ── Row helper ────────────────────────────────────────────────────────
  function Row(label, val, color) {
    return React.createElement('div', {key:label, style:{display:'flex',justifyContent:'space-between',gap:12,padding:'4px 0',borderBottom:'1px dashed #E5E7EB',fontSize:12}},
      React.createElement('span', {style:{color:'var(--txt3)',flexShrink:0}}, label),
      React.createElement('span', {style:{fontWeight:600,color:color||'var(--txt)',textAlign:'right'}},
        val===undefined||val===null||val===''?'—':val)
    );
  }
  // Auto-gen chip (immutable badge — Issue 4)
  var autoChip = React.createElement('span',{style:{fontSize:10,fontWeight:600,color:'#374151',background:'#F3F4F6',border:'1px solid #E5E7EB',borderRadius:4,padding:'2px 7px',display:'inline-flex',alignItems:'center',gap:3}},'Auto Generated');
  // Link button (bidirectional nav — Issue 6)
  function LinkBtn(label, onClick) {
    return React.createElement('button',{onClick:onClick,style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:700,color:'#1D4ED8',background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:6,padding:'5px 10px',cursor:'pointer',marginTop:8}},label,' →');
  }

  // ── Timeline ─────────────────────────────────────────────────────────
  var timeline = [];
  timeline.push({label:'Diesel Entry Created', ts:d.date||d.periodStart, who:d.createdBy||'System', ref:d.challanNumber||d.billNumber||'—'});
  if (role==='Split') timeline.push({label:'Split Allocation Saved', ts:d.splitCreatedOn||d.date, who:d.splitCreatedBy||'System', ref:d.splitRefId||'—'});
  if (vendorSettlement)    timeline.push({label:'Vendor Settlement Linked',    ts:vendorSettlement.createdDate,    who:vendorSettlement.createdBy||'System',    ref:vendorSettlement.id.slice(0,8).toUpperCase()});
  if (transportSettlement) timeline.push({label:'Transport Settlement Linked', ts:transportSettlement.createdDate, who:transportSettlement.createdBy||'System', ref:transportSettlement.id.slice(0,8).toUpperCase()});
  (d.allocHistory||[]).forEach(function(h){
    if (h.reason==='Split Allocation Saved') return;
    timeline.push({label:'Allocation Adjusted: '+h.fromRole+' → '+h.toRole, ts:h.timestamp, who:h.changedBy, ref:h.reason});
  });

  return React.createElement('div', {style:{padding:'16px 18px 20px',background:'#FFF9F5',borderBottom:'2px solid var(--or-bdr)'}},

    // ── Panel 1: General Info + Auto-Gen Metadata (Issue 4) ─────────────
    React.createElement('div', {className:'rg-2',style:{gap:14,marginBottom:14}},
      React.createElement('div', {style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div', {style:{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}}, 'General Information'),
        Row('Allocation Type',
          role==='Split'    ? React.createElement('span',{style:{color:'#6D28D9',fontWeight:800}},'Split Allocation')
          : role==='Vendor' ? React.createElement('span',{style:{color:'#166534',fontWeight:800}},'Vendor Settlement')
          :                   React.createElement('span',{style:{color:'#1D4ED8',fontWeight:800}},'Transport Settlement')
        ),
        role==='Split' && Row('Split Reference ID', d.splitRefId||'—'),
        role==='Split' && Row('Split Created On', d.splitCreatedOn ? new Date(d.splitCreatedOn).toLocaleString('en-IN',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '—'),
        // Issue 4: immutable auto-gen metadata
        Row('Source Module',      'Diesel Allocation'),
        Row('Allocation ID',      d.id ? d.id.slice(0,8).toUpperCase() : '—'),
        Row('Diesel Entry ID',    d.id ? d.id.slice(0,8).toUpperCase() : '—'),
        Row('Source Challan',     d.challanNumber || '—'),
        Row('Source Diesel Bill', d.billNumber    || '—'),
        Row('Generated Time',     d.date ? window.fmtDate(d.date) : '—'),
        Row('Generated By',       d.createdBy || 'System'),
        Row('Status', React.createElement('span',{style:{fontSize:10,fontWeight:600,color:'#374151',background:'#F3F4F6',border:'1px solid #E5E7EB',borderRadius:4,padding:'2px 7px'}},'Generated Automatically'))
      ),
      React.createElement('div', {style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div', {style:{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}}, 'Diesel Financials'),
        Row('Company',           Store.name('companies',d.companyId)||(d.companyId==='group'?'OM Group':'—')),
        Row('Transporter',       trName),
        role!=='Transport' && Row('Vendor', vendorName),
        Row('Vehicle',           d.vehicleFull||'—'),
        Row('Material',          d.material||Store.name('materials',d.materialId)||'—'),
        Row('Diesel Source',     d.dieselSource||'—'),
        Row('Quantity / Litres', window.fmtDieselQty(parseFloat(d.litres)||0)+' L'),
        grossFreight>0 && Row('Gross Freight', window.fmtCur(grossFreight)),
        Row('Bill Rate (₹/L)',   d.ratePerLitre!==undefined   ? '₹'+parseFloat(d.ratePerLitre  ||0).toFixed(2)+'/L' : '—'),
        Row('Margin (₹/L)',      d.marginPerLitre!==undefined ? '₹'+parseFloat(d.marginPerLitre||0).toFixed(2)+'/L' : '—'),
        Row('Deduction Rate',    d.deductionRate!==undefined  ? '₹'+parseFloat(d.deductionRate ||d.ratePerLitre||0).toFixed(2)+'/L' : '—'),
        Row('Actual Fuel Cost',  d.amount!==undefined ? window.fmtCur(d.amount) : '—'),
        Row('Total Diesel Deduction', React.createElement('span',{style:{fontWeight:800,color:'var(--or)'}},window.fmtCur(totalAmt)))
      )
    ),

    // ── Panel 2A: TRANSPORT allocation detail (Issue 5) ─────────────────
    role==='Transport' && React.createElement('div', {className:'rg-2',style:{gap:14,marginBottom:14}},
      React.createElement('div', {style:{background:'#fff',border:'1.5px solid #BFDBFE',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div', {style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}},
          React.createElement('span',{style:{fontWeight:700,fontSize:11,color:'#1D4ED8',textTransform:'uppercase',letterSpacing:'.5px'}},'Transport Allocation'),
          transportSettlement && autoChip
        ),
        Row('Allocation Type',     'Transport Settlement'),
        Row('Transporter',         trName),
        grossFreight>0 && Row('Gross Freight',       window.fmtCur(grossFreight)),
        Row('Transport Deduction', React.createElement('span',{style:{color:'#1D4ED8',fontWeight:800}},window.fmtCur(ta))),
        grossFreight>0 && Row('Freight Deduction',   window.fmtCur(ta)+' of '+window.fmtCur(grossFreight)),
        Row('Transport Recovery',  window.fmtCur(ta)),
        Row('Generated Record',    autoChip),
        transportSettlement ? React.createElement(React.Fragment,null,
          Row('Settlement Number', transportSettlement.id.slice(0,8).toUpperCase()),
          Row('Linked Settlement', transportSettlement.id.slice(0,8).toUpperCase()),
          Row('Settlement Amount', window.fmtCur(transportSettlement.netPayable||0)),
          Row('Settlement Date',   transportSettlement.createdDate ? window.fmtDate(transportSettlement.createdDate) : '—'),
          Row('Settlement Status', React.createElement(window.StBadge,{s:transportSettlement.status})),
          LinkBtn('Open Transport Settlement', function(){navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id});})
        ) : React.createElement('div',{style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic',marginTop:6}},
          'Not yet in a Transport Settlement. Will automatically appear when one covering '+trName+' and this date is created.')
      ),
      // Bidirectional navigation panel (Issue 6)
      React.createElement('div', {style:{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div',{style:{fontWeight:700,fontSize:11,color:'var(--txt2)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}},'Navigation'),
        React.createElement('div',{style:{fontSize:12,color:'var(--txt2)',marginBottom:10}},'Trace this deduction across all linked modules.'),
        React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:6}},
          transportSettlement && LinkBtn('Open Transport Settlement', function(){navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id});}),
          React.createElement('button',{onClick:function(){navigate&&navigate('diesel',{focusAllocId:d.id});},style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:700,color:'var(--or)',background:'var(--or-lt)',border:'1px solid var(--or-bdr)',borderRadius:6,padding:'5px 10px',cursor:'pointer',marginTop:8}},'View in Diesel Allocation Report →')
        )
      )
    ),

    // ── Panel 2B: VENDOR allocation detail (Issue 5) ────────────────────
    role==='Vendor' && React.createElement('div', {className:'rg-2',style:{gap:14,marginBottom:14}},
      React.createElement('div', {style:{background:'#fff',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div', {style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}},
          React.createElement('span',{style:{fontWeight:700,fontSize:11,color:'#6D28D9',textTransform:'uppercase',letterSpacing:'.5px'}},'Vendor Allocation'),
          vendorSettlement && autoChip
        ),
        Row('Allocation Type',  'Vendor Settlement'),
        Row('Vendor',           vendorName),
        Row('Diesel Recovery',  React.createElement('span',{style:{color:'#166534',fontWeight:800}},window.fmtCur(va))),
        vendorSettlement && Row('Purchase Amount', window.fmtCur((vendorSettlement.purchaseRows||[]).reduce(function(s,r){return s+(r.amountWithGst||0);},0))),
        Row('Generated Record', autoChip),
        vendorSettlement ? React.createElement(React.Fragment,null,
          Row('Settlement Number', vendorSettlement.id.slice(0,8).toUpperCase()),
          Row('Linked Settlement', vendorSettlement.id.slice(0,8).toUpperCase()),
          Row('Vendor Balance',    window.fmtCur(vendorSettlement.outstandingBalance||0)),
          Row('Settlement Status', React.createElement(window.VsBadge,{s:vendorSettlement.status})),
          LinkBtn('Open Vendor Settlement', function(){navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id});})
        ) : React.createElement('div',{style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic',marginTop:6}},
          'Not yet in a Vendor Settlement. Will automatically appear when one covering '+vendorName+' and this date is created.')
      ),
      React.createElement('div', {style:{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}},
        React.createElement('div',{style:{fontWeight:700,fontSize:11,color:'var(--txt2)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}},'Navigation'),
        React.createElement('div',{style:{fontSize:12,color:'var(--txt2)',marginBottom:10}},'Trace this diesel recovery across all linked modules.'),
        React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:6}},
          vendorSettlement && LinkBtn('Open Vendor Settlement', function(){navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id});}),
          React.createElement('button',{onClick:function(){navigate&&navigate('diesel',{focusAllocId:d.id});},style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:700,color:'var(--or)',background:'var(--or-lt)',border:'1px solid var(--or-bdr)',borderRadius:6,padding:'5px 10px',cursor:'pointer',marginTop:8}},'View in Diesel Allocation Report →')
        )
      )
    ),

    // ── Panel 2C: SPLIT allocation detail (Issue 5) ─────────────────────
    role==='Split' && React.createElement(React.Fragment, null,
      // Summary banner
      React.createElement('div', {style:{background:'#F5F3FF',border:'2px solid #DDD6FE',borderRadius:8,padding:'12px 14px',marginBottom:14}},
        React.createElement('div',{style:{fontWeight:700,fontSize:11,color:'#6D28D9',marginBottom:10,paddingBottom:5,borderBottom:'2px solid #DDD6FE',textTransform:'uppercase',letterSpacing:'.5px'}},'Split Allocation Summary'),
        React.createElement('div',{style:{display:'flex',gap:12,flexWrap:'wrap'}},
          [['Total Diesel Deduction',window.fmtCur(totalAmt),'var(--or)'],
           ['Vendor Portion',window.fmtCur(va),'#166534'],
           ['Transport Portion',window.fmtCur(ta),'#1D4ED8'],
           ['Remaining',window.fmtCur(remaining),remaining===0?'#166534':'#DC2626']
          ].map(function(item){
            return React.createElement('div',{key:item[0],style:{flex:'1 1 110px',background:'#fff',border:'1px solid #DDD6FE',borderRadius:6,padding:'8px 10px'}},
              React.createElement('div',{style:{fontSize:10,color:'#6D28D9',fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:2}},item[0]),
              React.createElement('div',{style:{fontSize:15,fontWeight:800,color:item[2]}},item[1])
            );
          }),
          React.createElement('div',{style:{flex:'1 1 110px',background:balanced?'#DCFCE7':'#FEE2E2',border:'1px solid '+(balanced?'#BBF7D0':'#FECACA'),borderRadius:6,padding:'8px 10px'}},
            React.createElement('div',{style:{fontSize:10,color:balanced?'#166534':'#991B1B',fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:2}},'Status'),
            React.createElement('div',{style:{fontSize:15,fontWeight:800,color:balanced?'#166534':'#991B1B'}},balanced?'Balanced':'Unbalanced')
          )
        )
      ),
      // Settlement cards
      React.createElement('div',{className:'rg-2',style:{gap:14,marginBottom:14}},
        // Vendor Settlement Card
        React.createElement('div',{style:{background:'#fff',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'12px 14px'}},
          React.createElement('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}},
            React.createElement('span',{style:{fontWeight:700,fontSize:11,color:'#6D28D9',textTransform:'uppercase',letterSpacing:'.5px'}},'Vendor Settlement'),
            vendorSettlement && autoChip
          ),
          vendorSettlement ? React.createElement(React.Fragment,null,
            Row('Settlement Number', vendorSettlement.id.slice(0,8).toUpperCase()),
            Row('Vendor Name',       vendorSettlement.vendorName||vendorName),
            Row('Recovered Amount',  React.createElement('span',{style:{color:'#166534',fontWeight:800}},window.fmtCur(va))),
            Row('Generated Record',  autoChip),
            Row('Linked Settlement', vendorSettlement.id.slice(0,8).toUpperCase()),
            Row('Vendor Balance',    window.fmtCur(vendorSettlement.outstandingBalance||0)),
            Row('Settlement Status', React.createElement(window.VsBadge,{s:vendorSettlement.status})),
            React.createElement('div',{style:{marginTop:8}},
              LinkBtn('Open Vendor Settlement', function(){navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id});})
            )
          ) : React.createElement('div',{style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'}},
            'Not yet in a Vendor Settlement. Will appear automatically when one is created for '+vendorName+' covering this period.')
        ),
        // Transport Settlement Card
        React.createElement('div',{style:{background:'#fff',border:'1.5px solid #BFDBFE',borderRadius:8,padding:'12px 14px'}},
          React.createElement('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}},
            React.createElement('span',{style:{fontWeight:700,fontSize:11,color:'#1D4ED8',textTransform:'uppercase',letterSpacing:'.5px'}},'Transport Settlement'),
            transportSettlement && autoChip
          ),
          transportSettlement ? React.createElement(React.Fragment,null,
            Row('Settlement Number', transportSettlement.id.slice(0,8).toUpperCase()),
            Row('Transporter',       transportSettlement.transporterName||trName),
            grossFreight>0 && Row('Gross Freight', window.fmtCur(grossFreight)),
            Row('Freight Deduction', window.fmtCur(ta)),
            Row('Recovered Amount',  React.createElement('span',{style:{color:'#1D4ED8',fontWeight:800}},window.fmtCur(ta))),
            Row('Generated Record',  autoChip),
            Row('Linked Settlement', transportSettlement.id.slice(0,8).toUpperCase()),
            Row('Settlement Amount', window.fmtCur(transportSettlement.netPayable||0)),
            Row('Settlement Status', React.createElement(window.StBadge,{s:transportSettlement.status})),
            React.createElement('div',{style:{marginTop:8}},
              LinkBtn('Open Transport Settlement', function(){navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id});})
            )
          ) : React.createElement('div',{style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'}},
            'Not yet in a Transport Settlement. Will appear automatically when one is created for '+trName+' covering this period.')
        )
      )
    ),

    // ── Allocation History Timeline ──────────────────────────────────────
    React.createElement('div',{style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px',marginBottom:14}},
      React.createElement('div',{style:{fontWeight:700,fontSize:11,color:'var(--txt)',marginBottom:10,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}},'Allocation History Timeline'),
      React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:0}},
        timeline.map(function(ev,i){
          return React.createElement('div',{key:i,style:{display:'flex',gap:10,padding:'6px 0',borderLeft:'2px solid #DDD6FE',paddingLeft:12,marginLeft:4,position:'relative'}},
            React.createElement('div',{style:{position:'absolute',left:-5,top:9,width:8,height:8,borderRadius:'50%',background:'#6D28D9'}}),
            React.createElement('div',{style:{flex:1}},
              React.createElement('div',{style:{fontWeight:700,fontSize:12}},ev.label),
              React.createElement('div',{style:{fontSize:10.5,color:'var(--txt3)',marginTop:1}},
                (ev.ts?window.fmtDate((ev.ts+'').slice(0,10)):'—')+' · '+ev.who+' · Ref: '+ev.ref
              )
            )
          );
        })
      )
    ),

    // ── Audit Trail (Issue 8) ─────────────────────────────────────────────
    (d.allocHistory&&d.allocHistory.length>0) && React.createElement('div',{style:{background:'#fff',border:'1px solid #FEE2E2',borderRadius:8,padding:'12px 14px'}},
      React.createElement('div',{style:{fontWeight:700,fontSize:11,color:'#DC2626',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px'}},'Audit Trail ('+d.allocHistory.length+')'),
      React.createElement('div',{style:{overflowX:'auto'}},
        React.createElement('table',{style:{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:640}},
          React.createElement('thead',null,React.createElement('tr',null,
            ['When','Before','After','Reason','Edited By'].map(function(h){
              return React.createElement('th',{key:h,style:{background:'#F9FAFB',fontSize:10.5,fontWeight:700,textTransform:'uppercase',padding:'5px 8px',border:'1px solid var(--bdr)',textAlign:'left'}},h);
            })
          )),
          React.createElement('tbody',null,
            d.allocHistory.slice().reverse().map(function(h){
              return React.createElement('tr',{key:h.id,style:{borderBottom:'1px solid #F3F4F6'}},
                React.createElement('td',{style:{padding:'4px 8px'}},new Date(h.timestamp).toLocaleString('en-IN',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'})),
                React.createElement('td',{style:{padding:'4px 8px'}},h.fromRole+' (V:'+window.fmtCur(h.fromVendorAmount||0)+' / T:'+window.fmtCur(h.fromTransportAmount||0)+')'),
                React.createElement('td',{style:{padding:'4px 8px',fontWeight:600}},h.toRole+' (V:'+window.fmtCur(h.toVendorAmount||0)+' / T:'+window.fmtCur(h.toTransportAmount||0)+')'),
                React.createElement('td',{style:{padding:'4px 8px',color:'var(--txt2)',fontStyle:'italic'}},h.reason||'—'),
                React.createElement('td',{style:{padding:'4px 8px',color:'var(--txt3)'}},h.changedBy||'—')
              );
            })
          )
        )
      )
    )
  );
}
window.SplitAllocationDrilldown = SplitAllocationDrilldown;

// ── Allocation Report Section ───────────────────────────────────────────────
// Summary of diesel allocation status — displayed as a tab in diesel page.
function DieselAllocationReport({ companyId, isGroup, focusRecordId, navigate, periodFrom, periodTo }) {
  window.useStoreSync();
  var [search, setSearch] = daSt('');
  var [fRole, setFRole] = daSt('');
  var [fStatus, setFStatus] = daSt('');
  var [expId, setExpId] = daSt(focusRecordId || null);
  daEf(function(){ if (focusRecordId) setExpId(focusRecordId); }, [focusRecordId]);

  // ── Standardized Date Range Filter (shared DieselPeriodDropdown) ──────────
  var [periodPreset, setPeriodPreset] = daSt('all');
  var [customFrom, setCustomFrom] = daSt('');
  var [customTo, setCustomTo] = daSt('');
  var periodRange = daMemo(function() { return window.getDieselPeriodRange(periodPreset, customFrom, customTo); }, [periodPreset, customFrom, customTo]);
  function setAllocPeriod(id) { setPeriodPreset(id); }
  function setAllocCustomRange(f, t) { setCustomFrom(f); setCustomTo(t); }

  var records = daMemo(function() {
    return (Store.all('dieselRecords', companyId) || []).slice().sort(function(a,b){return (b.date||'')>(a.date||'')?1:-1;});
  }, [companyId]);

  var filtered = daMemo(function() {
    return records.filter(function(d) {
      if (fRole) {
        var role = d.dieselAllocRole || 'Transport';
        if (role !== fRole) return false;
      }
      if (fStatus === 'allocated') { if (!d.dieselAllocRole) return false; }
      if (fStatus === 'unallocated') {
        var info = window.getPartyRoles(d.transporterId);
        if (!info.isMultiRole) return false;
        if (d.dieselAllocRole) return false;
      }
      if (search) {
        var q = search.toLowerCase();
        var trName = d.transporterName || Store.name('transporterMaster', d.transporterId) || '';
        if (![trName, d.vehicleFull||'', d.challanNumber||''].some(function(v){return String(v).toLowerCase().includes(q);})) return false;
      }
      if (!window.dieselInPeriod(d.date||d.periodStart, periodRange.from, periodRange.to)) return false;
      return true;
    });
  }, [records, search, fRole, fStatus, periodRange]);

  // Filtered totals (for sticky footer — updates with every filter change)
  var filteredTotals = daMemo(function() {
    var dieselAmt = 0, transportAmt = 0, vendorAmt = 0, pendingAmt = 0;
    filtered.forEach(function(d) {
      var amt = parseFloat(d.deductionAmount)||parseFloat(d.amount)||0;
      dieselAmt += amt;
      transportAmt += window.getDieselTransportAmount(d);
      vendorAmt += window.getDieselVendorAmount(d);
      var info = window.getPartyRoles(d.transporterId);
      if (info.isMultiRole && !d.dieselAllocRole) pendingAmt += amt;
    });
    return { dieselAmt: dieselAmt, transportAmt: transportAmt, vendorAmt: vendorAmt, pendingAmt: pendingAmt };
  }, [filtered]);

  // All-records KPI totals
  var totals = daMemo(function() {
    var total=0, vendorAlloc=0, transportAlloc=0, pending=0, multiRoleCount=0;
    records.forEach(function(d) {
      var amt = parseFloat(d.deductionAmount)||parseFloat(d.amount)||0;
      total += amt;
      var role = d.dieselAllocRole;
      if (!role || role === 'Transport') { transportAlloc += amt; }
      else if (role === 'Vendor') { vendorAlloc += amt; }
      else if (role === 'Split') { vendorAlloc += (parseFloat(d.vendorAllocAmount)||0); transportAlloc += (parseFloat(d.transportAllocAmount)||0); }
      var info = window.getPartyRoles(d.transporterId);
      if (info.isMultiRole) { multiRoleCount++; if (!role) pending += amt; }
    });
    return {total:total,vendorAlloc:vendorAlloc,transportAlloc:transportAlloc,pending:pending,multiRoleCount:multiRoleCount};
  }, [records]);

  return React.createElement('div', null,
    /* KPI row */
    React.createElement('div', {className:'kpi-grid',style:{marginBottom:14}},
      [{lbl:'TOTAL DIESEL',val:window.fmtCur(totals.total),bg:'#FFF7ED',color:'var(--or)'},
       {lbl:'TRANSPORT ALLOCATION',val:window.fmtCur(totals.transportAlloc),bg:'#DBEAFE',color:'#1D4ED8'},
       {lbl:'VENDOR ALLOCATION',val:window.fmtCur(totals.vendorAlloc),bg:'#EDE9FE',color:'#6D28D9'},
       {lbl:'PENDING (MULTI-ROLE)',val:window.fmtCur(totals.pending),bg:totals.pending>0?'#FEE2E2':'#DCFCE7',color:totals.pending>0?'#991B1B':'#166534'}
      ].map(function(k) {
        return React.createElement('div', {key:k.lbl,className:'kpi',style:{background:k.bg}},
          React.createElement('div', {className:'kpi-lbl'}, k.lbl),
          React.createElement('div', {className:'kpi-val',style:{color:k.color}}, k.val)
        );
      })
    ),
    /* Filters */
    React.createElement('div', {className:'frow'},
      React.createElement('div', {className:'fs'},
        React.createElement('svg', {className:'fs-ic',width:12,height:12,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:2.5},
          React.createElement('circle', {cx:11,cy:11,r:8}), React.createElement('path', {d:'M21 21l-4.35-4.35'})
        ),
        React.createElement('input', {value:search,onChange:function(e){setSearch(e.target.value);},placeholder:'Search transporter, vehicle…'})
      ),
      React.createElement('select', {className:'fsel',value:fRole,onChange:function(e){setFRole(e.target.value);}},
        React.createElement('option', {value:''}, 'All Roles'),
        React.createElement('option', {value:'Transport'}, 'Transport'),
        React.createElement('option', {value:'Vendor'}, 'Vendor'),
        React.createElement('option', {value:'Split'}, 'Split')
      ),
      React.createElement('select', {className:'fsel',value:fStatus,onChange:function(e){setFStatus(e.target.value);}},
        React.createElement('option', {value:''}, 'All Status'),
        React.createElement('option', {value:'allocated'}, 'Allocated'),
        React.createElement('option', {value:'unallocated'}, 'Pending Allocation')
      ),
      React.createElement(window.DieselPeriodDropdown, {preset:periodPreset, onChange:setAllocPeriod, customFrom:customFrom, customTo:customTo, onCustomChange:setAllocCustomRange}),
      React.createElement('span', {className:'f-cnt'}, filtered.length+' records')
    ),
    /* Table */
    React.createElement('div', {className:'card'},
      React.createElement('div', {className:'tbl-w'},
        React.createElement('table', {className:'tbl'},
          React.createElement('thead', null,
            React.createElement('tr', null,
              React.createElement('th', {style:{width:20}}),
              isGroup && React.createElement('th', null, 'COMPANY'),
              React.createElement('th', null, 'DATE'),
              React.createElement('th', null, 'TRANSPORTER'),
              React.createElement('th', null, 'VEHICLE'),
              React.createElement('th', null, 'TOTAL'),
              React.createElement('th', null, 'ALLOCATION'),
              React.createElement('th', null, 'TRANSPORT'),
              React.createElement('th', null, 'VENDOR'),
              React.createElement('th', null, 'STATUS')
            )
          ),
          React.createElement('tbody', null,
            filtered.length === 0
              ? React.createElement('tr', {className:'empty'}, React.createElement('td', {colSpan: isGroup ? 10 : 9, style:{textAlign:'center',padding:40}}, 'No records'))
              : filtered.map(function(d) {
                  var amt = parseFloat(d.deductionAmount)||parseFloat(d.amount)||0;
                  var role = d.dieselAllocRole||'Transport';
                  var tAmt = window.getDieselTransportAmount(d);
                  var vAmt = window.getDieselVendorAmount(d);
                  var info = window.getPartyRoles(d.transporterId);
                  var trName = d.transporterName||Store.name('transporterMaster',d.transporterId)||'—';
                  var isOpen = expId === d.id;
                  return React.createElement(React.Fragment, {key:d.id},
                    React.createElement('tr', {style:{background:isOpen?'#FFF9F5':undefined,cursor:'pointer'}, onClick:function(){ setExpId(isOpen?null:d.id); }},
                      React.createElement('td', {style:{textAlign:'center',width:20,color:'var(--txt3)'}}, isOpen?'▾':'▸'),
                      isGroup && React.createElement('td', null, React.createElement('span',{className:'bdg bg-or',style:{fontSize:10}},Store.name('companies',d.companyId))),
                      React.createElement('td', null, window.fmtDate(d.date||d.periodStart)),
                      React.createElement('td', {style:{fontWeight:500}}, trName, info.isMultiRole && React.createElement('span',{style:{fontSize:9,marginLeft:4,padding:'1px 4px',borderRadius:3,background:'#FEF3C7',color:'#92400E',fontWeight:700}},'MULTI-ROLE')),
                      React.createElement('td', null, React.createElement('span',{style:{fontFamily:'var(--font)',fontSize:11,background:'#F9FAFB',padding:'1px 5px',borderRadius:3}},d.vehicleFull||'—')),
                      React.createElement('td', {style:{fontWeight:700,color:'var(--or)'}}, window.fmtCur(amt)),
                      React.createElement('td', null, React.createElement(SplitAllocBadge, {record:d})),
                      React.createElement('td', {style:{fontWeight:600,color:'#1D4ED8'}}, tAmt>0?window.fmtCur(tAmt):'—'),
                      React.createElement('td', {style:{fontWeight:600,color:'#6D28D9'}}, vAmt>0?window.fmtCur(vAmt):'—'),
                      React.createElement('td', null,
                        info.isMultiRole && !d.dieselAllocRole
                          ? React.createElement('span',{className:'bdg bg-rd',style:{fontSize:10,padding:'1px 6px'}},'Pending')
                          : React.createElement('span',{className:'bdg bg-gn',style:{fontSize:10,padding:'1px 6px'}},'Allocated')
                      )
                    ),
                    isOpen && React.createElement('tr', {key:d.id+'-exp'},
                      React.createElement('td', {colSpan: isGroup ? 10 : 9, style:{padding:0,borderTop:'2px solid var(--or-bdr)'}},
                        React.createElement(SplitAllocationDrilldown, {record:d, navigate:navigate})
                      )
                    )
                  );
                })
          ),
          /* ── Sticky total footer — 1 td per column, no colSpan ── */
          React.createElement('tfoot', null,
            React.createElement('tr', null,
              /* Expand column spacer */
              React.createElement('td'),
              /* Label cell always in first column */
              isGroup && React.createElement('td', {style:{fontWeight:700,fontSize:11,color:'var(--txt2)'}},
                'TOTALS — '+filtered.length+' records'
              ),
              /* DATE (non-group: label here) */
              React.createElement('td', {style:{fontWeight:700,fontSize:11,color:'var(--txt2)'}},
                !isGroup ? 'TOTALS — '+filtered.length+' records' : ''
              ),
              /* TRANSPORTER */
              React.createElement('td'),
              /* VEHICLE */
              React.createElement('td'),
              /* TOTAL */
              React.createElement('td', {style:{fontWeight:800,color:'var(--or)'}},
                window.fmtCur(filteredTotals.dieselAmt)
              ),
              /* ALLOCATION */
              React.createElement('td'),
              /* TRANSPORT */
              React.createElement('td', {style:{fontWeight:700,color:'#1D4ED8'}},
                filteredTotals.transportAmt > 0 ? window.fmtCur(filteredTotals.transportAmt) : '—'
              ),
              /* VENDOR */
              React.createElement('td', {style:{fontWeight:700,color:'#6D28D9'}},
                filteredTotals.vendorAmt > 0 ? window.fmtCur(filteredTotals.vendorAmt) : '—'
              ),
              /* STATUS */
              React.createElement('td', {style:{fontWeight:700,color:filteredTotals.pendingAmt>0?'#991B1B':'var(--txt3)'}},
                filteredTotals.pendingAmt > 0 ? window.fmtCur(filteredTotals.pendingAmt) : '—'
              )
            )
          )
        )
      )
    )
  );
}
window.DieselAllocationReport = DieselAllocationReport;

// ═══════════════════════════════════════════════════════════════════════════════
// ALLOCATION & SETTLEMENT TRACEABILITY PANEL
// Complete lifecycle audit section added to Bill-Based Diesel Entries drill-down.
// Covers: Allocation Type badge · Allocation Summary KPIs · Role-specific
// settlement cards (Transport / Vendor / Split) · Allocation Timeline ·
// Linked Transactions · Financial Breakdown · Audit Information ·
// Expandable Allocation History · Intelligent Status Indicators · Validation.
// ═══════════════════════════════════════════════════════════════════════════════
function AllocationTraceabilityPanel({ record: d, navigate }) {
  var [histOpen, setHistOpen] = daSt(false);

  // ── Core amounts ─────────────────────────────────────────────────────────
  var role       = d.dieselAllocRole || 'Transport';
  var totalAmt   = parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
  var actualCost = parseFloat(d.amount) || 0;
  var litres     = parseFloat(d.litres) || 0;
  var dedRate    = parseFloat(d.deductionRate) || parseFloat(d.ratePerLitre) || 0;
  var marginPerL = parseFloat(d.marginPerLitre) || 0;
  var marginAmt  = Math.round(marginPerL * litres * 100) / 100;

  var va = role === 'Split'     ? (parseFloat(d.vendorAllocAmount)    || 0) : (role === 'Vendor'    ? totalAmt : 0);
  var ta = role === 'Split'     ? (parseFloat(d.transportAllocAmount) || 0) : (role === 'Transport' ? totalAmt : 0);
  var remaining  = Math.round((totalAmt - va - ta) * 100) / 100;
  var balanced   = Math.abs(remaining) < 0.02;
  var allocPct   = totalAmt > 0 ? Math.round((va + ta) / totalAmt * 100) : 100;

  // ── Party names ───────────────────────────────────────────────────────────
  var trName     = d.transporterName || Store.name('transporterMaster', d.transporterId) || '—';
  var partyInfo  = window.getPartyRoles(d.transporterId);
  var vendorName = partyInfo.matchedVendors.length > 0
    ? partyInfo.matchedVendors[0].name
    : (d.allocVendorId ? Store.name('vendors', d.allocVendorId) : trName);

  // ── Linked records (live, no cache) ───────────────────────────────────────
  var vendorSettlement    = d.vendorSettledInId
    ? (Store.all('vendorSettlements') || []).find(function(s){ return s.id === d.vendorSettledInId; })
    : null;
  var transportSettlement = d.settledInSettlementId
    ? (Store.all('settlementRecords') || []).find(function(s){ return s.id === d.settledInSettlementId; })
    : null;
  var challanPO = d.challanNumber
    ? (Store.all('purchases') || []).find(function(p){ return p.challanNumber === d.challanNumber; })
    : null;
  var grossFreight = challanPO
    ? (parseFloat(challanPO.sub) || parseFloat(challanPO.subtotal) || 0)
    : (parseFloat(d.challanGross) || 0);

  // ── Settlement financials ─────────────────────────────────────────────────
  var tsPaid       = transportSettlement && transportSettlement.status === 'Paid' ? ta : 0;
  var tsOutstanding = ta - tsPaid;
  var vsOutstanding = vendorSettlement ? (parseFloat(vendorSettlement.outstandingBalance) || 0) : va;
  var vsPaid        = va - vsOutstanding;
  var recoveredAmt  = tsPaid + vsPaid;
  var pendingRecovery = Math.max(0, totalAmt - recoveredAmt);

  // ── Intelligent status ────────────────────────────────────────────────────
  var statusLabel, statusColor, statusBg;
  if (!d.dieselAllocRole && partyInfo.isMultiRole) {
    statusLabel = 'Pending Allocation'; statusColor = '#991B1B'; statusBg = '#FEE2E2';
  } else if (role === 'Split') {
    var vPd = vendorSettlement && vendorSettlement.status === 'Paid';
    var tPd = transportSettlement && transportSettlement.status === 'Paid';
    if (vPd && tPd)       { statusLabel = 'Recovered';          statusColor = '#166534'; statusBg = '#DCFCE7'; }
    else if (vPd || tPd)  { statusLabel = 'Partially Recovered'; statusColor = '#92400E'; statusBg = '#FEF3C7'; }
    else if (vendorSettlement && transportSettlement) { statusLabel = 'Split Generated'; statusColor = '#6D28D9'; statusBg = '#EDE9FE'; }
    else                  { statusLabel = 'Allocated';           statusColor = '#1D4ED8'; statusBg = '#DBEAFE'; }
  } else if (role === 'Vendor') {
    if (!vendorSettlement)                               { statusLabel = 'Allocated';  statusColor = '#1D4ED8'; statusBg = '#DBEAFE'; }
    else if (vendorSettlement.status === 'Paid')         { statusLabel = 'Recovered';  statusColor = '#166534'; statusBg = '#DCFCE7'; }
    else if (vendorSettlement.status === 'Cancelled')    { statusLabel = 'Cancelled';  statusColor = '#6B7280'; statusBg = '#F3F4F6'; }
    else                                                 { statusLabel = 'Vendor Generated'; statusColor = '#6D28D9'; statusBg = '#EDE9FE'; }
  } else {
    if (!transportSettlement)                            { statusLabel = 'Allocated';  statusColor = '#1D4ED8'; statusBg = '#DBEAFE'; }
    else if (transportSettlement.status === 'Paid')      { statusLabel = 'Recovered';  statusColor = '#166534'; statusBg = '#DCFCE7'; }
    else if (transportSettlement.status === 'Cancelled') { statusLabel = 'Cancelled';  statusColor = '#6B7280'; statusBg = '#F3F4F6'; }
    else                                                 { statusLabel = 'Transport Generated'; statusColor = '#1D4ED8'; statusBg = '#DBEAFE'; }
  }

  // ── Type badge config ────────────────────────────────────────────────────
  var typeBadge = role === 'Split'
    ? { label:'Split Allocation',     color:'#6D28D9', bg:'#EDE9FE', border:'#DDD6FE' }
    : role === 'Vendor'
    ? { label:'Vendor Settlement',    color:'#6D28D9', bg:'#F5F3FF', border:'#DDD6FE' }
    : { label:'Transport Settlement', color:'#1D4ED8', bg:'#EFF6FF', border:'#BFDBFE' };

  // ── Chronological timeline ────────────────────────────────────────────────
  var timeline = [];
  timeline.push({ label:'Diesel Entry Created',          ts:d.date||d.periodStart,             who:d.createdBy||'System',                     module:'Diesel',               ref:d.billNumber||d.challanNumber||'—', done:true });
  if (d.dieselAllocRole) {
    timeline.push({ label:'Allocation Selected — '+role, ts:d.splitCreatedOn||d.date,           who:d.splitCreatedBy||d.createdBy||'System',   module:'Diesel Allocation',    ref:d.splitRefId||role,                done:true });
  }
  if (transportSettlement) {
    timeline.push({ label:'Transport Settlement Generated', ts:transportSettlement.createdDate,  who:transportSettlement.createdBy||'System',   module:'Transport Settlement', ref:transportSettlement.id.slice(0,8).toUpperCase(), done:true });
  }
  if (vendorSettlement) {
    timeline.push({ label:'Vendor Settlement Generated',    ts:vendorSettlement.createdDate,     who:vendorSettlement.createdBy||'System',      module:'Vendor Settlement',    ref:vendorSettlement.id.slice(0,8).toUpperCase(),    done:true });
  }
  if (vendorSettlement && vendorSettlement.status === 'Paid') {
    timeline.push({ label:'Vendor Settlement Paid',         ts:vendorSettlement.paidDate||vendorSettlement.modifiedDate,  who:vendorSettlement.paidBy||'System',    module:'Vendor Settlement',    ref:window.fmtCur(va), done:true });
  }
  if (transportSettlement && transportSettlement.status === 'Paid') {
    timeline.push({ label:'Transport Settlement Paid',      ts:transportSettlement.paidDate||transportSettlement.modifiedDate, who:transportSettlement.paidBy||'System', module:'Transport Settlement', ref:window.fmtCur(ta), done:true });
  }
  if (recoveredAmt >= totalAmt - 0.02 && totalAmt > 0) {
    timeline.push({ label:'Payment Completed',              ts:null,                             who:'System',                                  module:'ERP',                  ref:window.fmtCur(totalAmt), done:true });
  }

  // ── Validation flags ─────────────────────────────────────────────────────
  var allocationMissing   = !d.dieselAllocRole && partyInfo.isMultiRole;
  var tSettlementMissing  = (role === 'Transport' || role === 'Split') && !transportSettlement;
  var vSettlementMissing  = (role === 'Vendor'    || role === 'Split') && !vendorSettlement;

  // ── SVG Icon System ──────────────────────────────────────────────────────
  function ic(paths, color, size) {
    var sz = size || 13;
    var nodes = paths.map(function(p, ki) {
      return React.createElement(p[0], Object.assign({ key:ki }, p[1]));
    });
    return React.createElement.apply(React, [
      'svg', { width:sz, height:sz, viewBox:'0 0 24 24', fill:'none',
        stroke:color||'currentColor', strokeWidth:2,
        strokeLinecap:'round', strokeLinejoin:'round',
        style:{flexShrink:0,display:'inline-block',verticalAlign:'middle'} }
    ].concat(nodes));
  }
  var IC = {
    trace:   [['circle',{cx:'11',cy:'11',r:'8'}],['path',{d:'m21 21-4.35-4.35'}]],
    warn:    [['path',{d:'M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z'}],['line',{x1:'12',y1:'9',x2:'12',y2:'13'}],['path',{d:'M12 17h.01'}]],
    chart:   [['line',{x1:'18',y1:'20',x2:'18',y2:'10'}],['line',{x1:'12',y1:'20',x2:'12',y2:'4'}],['line',{x1:'6',y1:'20',x2:'6',y2:'14'}]],
    truck:   [['rect',{x:'1',y:'3',width:'15',height:'13'}],['path',{d:'M16 8h4l3 3v5h-7V8z'}],['circle',{cx:'5.5',cy:'18.5',r:'2.5'}],['circle',{cx:'18.5',cy:'18.5',r:'2.5'}]],
    building:[['path',{d:'M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z'}],['polyline',{points:'9 22 9 12 15 12 15 22'}]],
    split:   [['polyline',{points:'16 3 21 3 21 8'}],['line',{x1:'4',y1:'20',x2:'21',y2:'3'}],['polyline',{points:'21 16 21 21 16 21'}],['line',{x1:'15',y1:'15',x2:'21',y2:'21'}]],
    clock:   [['circle',{cx:'12',cy:'12',r:'10'}],['polyline',{points:'12 6 12 12 16 14'}]],
    link:    [['path',{d:'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71'}],['path',{d:'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'}]],
    wallet:  [['rect',{x:'1',y:'4',width:'22',height:'16',rx:'2'}],['path',{d:'M16 12h.01'}]],
    shield:  [['path',{d:'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z'}]],
    clip:    [['path',{d:'M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2'}],['rect',{x:'8',y:'2',width:'8',height:'4',rx:'1'}]],
    gear:    [['circle',{cx:'12',cy:'12',r:'3'}],['path',{d:'M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z'}]],
    arrow:   [['line',{x1:'5',y1:'12',x2:'19',y2:'12'}],['polyline',{points:'12 5 19 12 12 19'}]],
    check:   [['circle',{cx:'12',cy:'12',r:'10'}],['path',{d:'m9 12 2 2 4-4'}]],
    file:    [['path',{d:'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'}],['polyline',{points:'14 2 14 8 20 8'}],['line',{x1:'16',y1:'13',x2:'8',y2:'13'}],['line',{x1:'16',y1:'17',x2:'8',y2:'17'}]],
    fuel:    [['path',{d:'M3 22V8l6-6h6l6 6v14H3z'}],['path',{d:'M9 22V12h6v10'}]]
  };

  // ── Helpers ───────────────────────────────────────────────────────────────
  function Row(label, val, color) {
    return React.createElement('div', { key:label, style:{display:'flex',justifyContent:'space-between',gap:12,padding:'4px 0',borderBottom:'1px dashed #E5E7EB',fontSize:11.5} },
      React.createElement('span', { style:{color:'var(--txt3)',flexShrink:0} }, label),
      React.createElement('span', { style:{fontWeight:600,color:color||'var(--txt)',textAlign:'right'} },
        (val===undefined||val===null||val==='') ? '—' : val)
    );
  }
  function SHdr(title, color, iconName) {
    return React.createElement('div', { style:{fontWeight:700,fontSize:10.5,color:color||'var(--txt2)',marginBottom:8,paddingBottom:6,borderBottom:'1px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px',display:'flex',alignItems:'center',gap:6} },
      iconName && IC[iconName] && ic(IC[iconName], color||'var(--txt3)', 12),
      title
    );
  }
  function LinkBtn(label, onClick) {
    return React.createElement('button', { onClick:onClick, style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:700,color:'#1D4ED8',background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:6,padding:'5px 10px',cursor:'pointer',fontFamily:'var(--font)'} },
      ic(IC.link,'#1D4ED8',12), label, ic(IC.arrow,'#1D4ED8',11)
    );
  }
  function AutoChip() {
    return React.createElement('span', { style:{fontSize:10,fontWeight:600,color:'#374151',background:'#F3F4F6',border:'1px solid var(--bdr)',borderRadius:4,padding:'2px 7px',display:'inline-flex',alignItems:'center',gap:4} },
      ic(IC.gear,'#6B7280',11), 'Auto Generated'
    );
  }

  // ── Split summary detail rows ─────────────────────────────────────────────
  var splitVendorPct    = totalAmt > 0 ? Math.round(va / totalAmt * 100) : 0;
  var splitTransportPct = totalAmt > 0 ? Math.round(ta / totalAmt * 100) : 0;
  var splitGenStatus    = vendorSettlement && transportSettlement ? 'Both Generated'
    : vendorSettlement ? 'Vendor Only' : transportSettlement ? 'Transport Only' : 'Pending';

  // ═══════════════════════════════════════════════════════════════════════════
  return React.createElement('div', { style:{marginTop:14,border:'1px solid var(--bdr)',borderRadius:10,overflow:'hidden',background:'#FAFAFA',boxShadow:'0 1px 4px rgba(0,0,0,.05)'} },

    // ── Panel header — light, native ERP card style ───────────────────────
    React.createElement('div', { style:{background:'#fff',borderBottom:'1px solid var(--bdr)',padding:'12px 16px',display:'flex',alignItems:'center',justifyContent:'space-between',flexWrap:'wrap',gap:8} },
      React.createElement('div', { style:{display:'flex',alignItems:'center',gap:10} },
        React.createElement('div', { style:{width:30,height:30,borderRadius:7,background:'var(--or-lt)',border:'1px solid var(--or-bdr)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0} },
          ic(IC.trace,'var(--or)',14)
        ),
        React.createElement('div', null,
          React.createElement('div', { style:{fontSize:12.5,fontWeight:700,color:'var(--txt)',letterSpacing:'.01em'} }, 'Allocation & Settlement Traceability'),
          React.createElement('div', { style:{fontSize:10,color:'var(--txt3)',marginTop:1} }, 'End-to-end lifecycle · live data')
        )
      ),
      React.createElement('div', { style:{display:'flex',alignItems:'center',gap:7,flexWrap:'wrap'} },
        React.createElement('span', { style:{fontSize:11,fontWeight:600,color:typeBadge.color,background:typeBadge.bg,border:'1px solid '+typeBadge.border,borderRadius:20,padding:'3px 10px'} }, typeBadge.label),
        React.createElement('span', { style:{fontSize:11,fontWeight:600,color:statusColor,background:statusBg,border:'1px solid '+statusColor+'33',borderRadius:20,padding:'3px 10px'} }, statusLabel)
      )
    ),

    React.createElement('div', { style:{padding:'14px 16px 18px'} },

      // ── Validation warnings ───────────────────────────────────────────
      (allocationMissing || (!allocationMissing && tSettlementMissing) || (!allocationMissing && vSettlementMissing)) && React.createElement('div', { style:{display:'flex',flexDirection:'column',gap:6,marginBottom:14} },
        allocationMissing && React.createElement('div', { style:{background:'#FFFBEB',border:'1px solid #FCD34D',borderRadius:8,padding:'10px 12px',fontSize:11.5,color:'#92400E',display:'flex',gap:9,alignItems:'flex-start'} },
          React.createElement('span', { style:{flexShrink:0,marginTop:1} }, ic(IC.warn,'#D97706',14)),
          React.createElement('div', null,
            React.createElement('strong', null, 'Allocation record not generated. '),
            'This is a multi-role party. Use the Adjust button to assign this diesel to Transport, Vendor, or Split.'
          )
        ),
        !allocationMissing && tSettlementMissing && React.createElement('div', { style:{background:'#FFF7ED',border:'1px solid #FDBA74',borderRadius:8,padding:'10px 12px',fontSize:11.5,color:'#92400E',display:'flex',gap:9,alignItems:'flex-start'} },
          React.createElement('span', { style:{flexShrink:0,marginTop:1} }, ic(IC.warn,'#D97706',14)),
          React.createElement('div', null,
            React.createElement('strong', null, 'Expected Transport Settlement not found. '),
            'This deduction will appear automatically in the next Transport Settlement created for '+trName+'.'
          )
        ),
        !allocationMissing && vSettlementMissing && React.createElement('div', { style:{background:'#F5F3FF',border:'1px solid #C4B5FD',borderRadius:8,padding:'10px 12px',fontSize:11.5,color:'#5B21B6',display:'flex',gap:9,alignItems:'flex-start'} },
          React.createElement('span', { style:{flexShrink:0,marginTop:1} }, ic(IC.warn,'#7C3AED',14)),
          React.createElement('div', null,
            React.createElement('strong', null, 'Expected Vendor Settlement not found. '),
            'This deduction will appear automatically in the next Vendor Settlement created for '+vendorName+'.'
          )
        )
      ),

      // ── Allocation Summary KPIs ───────────────────────────────────────
      React.createElement('div', { style:{marginBottom:14} },
        SHdr('Allocation Summary', 'var(--or)', 'chart'),
        React.createElement('div', { style:{display:'flex',gap:10,flexWrap:'wrap'} },
          [['Total Diesel Deduction', window.fmtCur(totalAmt),        'var(--or)', '#FFF7ED', '#FEF3C7'],
           ['Actual Fuel Cost',       window.fmtCur(actualCost),      '#166534',  '#F0FDF4', '#BBF7D0'],
           ['Diesel Margin',          marginAmt>0?window.fmtCur(marginAmt):'—', '#B45309', '#FFFBEB', '#FDE68A'],
           ['Deduction Rate',         dedRate>0?'₹'+dedRate.toFixed(2)+'/L':'—', '#374151', '#F9FAFB', '#E5E7EB'],
           ['Allocated Amount',       window.fmtCur(va+ta),           '#1D4ED8',  '#EFF6FF', '#BFDBFE'],
           ['Allocation %',           allocPct+'%',                   '#166534',  '#F0FDF4', '#BBF7D0'],
           ['Remaining Balance',      remaining!==0?window.fmtCur(Math.abs(remaining)):'₹0.00', remaining!==0?'#991B1B':'#166534', remaining!==0?'#FEF2F2':'#F0FDF4', remaining!==0?'#FECACA':'#BBF7D0']
          ].map(function(item) {
            return React.createElement('div', { key:item[0], style:{flex:'1 1 100px',background:item[3],border:'1px solid '+item[4],borderRadius:8,padding:'8px 12px',minWidth:90} },
              React.createElement('div', { style:{fontSize:9.5,color:item[2],fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:3} }, item[0]),
              React.createElement('div', { style:{fontSize:13,fontWeight:800,color:item[2]} }, item[1])
            );
          })
        )
      ),

      // ── Role-specific: TRANSPORT ──────────────────────────────────────
      role === 'Transport' && React.createElement('div', { style:{marginBottom:14} },
        SHdr('Transport Settlement Recovery', '#1D4ED8', 'truck'),
        React.createElement('div', { className:'dd-2col', style:{gap:12} },
          React.createElement('div', { style:{background:'#fff',border:'1.5px solid #BFDBFE',borderRadius:8,padding:'12px 14px'} },
            React.createElement('div', { style:{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:8} },
              React.createElement('span', { style:{fontSize:11,fontWeight:700,color:'#1D4ED8',display:'flex',alignItems:'center',gap:5} }, ic(IC.truck,'#1D4ED8',12), 'Recovered From Transport'),
              transportSettlement && AutoChip()
            ),
            Row('Transporter Name',         trName),
            Row('Transport Settlement No.', transportSettlement ? transportSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Settlement Date',          transportSettlement ? (transportSettlement.createdDate ? window.fmtDate(transportSettlement.createdDate) : '—') : '—'),
            Row('Settlement Status',        transportSettlement
              ? React.createElement(window.StBadge, { s:transportSettlement.status })
              : React.createElement('span', { style:{color:'var(--txt3)',fontSize:11,fontStyle:'italic'} }, 'Not Yet Generated')),
            Row('Transport Settlement ID',  transportSettlement ? transportSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Generated Automatically',  'Yes'),
            transportSettlement && React.createElement('div', { style:{marginTop:8} },
              LinkBtn('Open Transport Settlement', function(){ navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id}); })
            )
          ),
          React.createElement('div', { style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
            SHdr('Recovery Status', '#1D4ED8'),
            Row('Transport Deduction', React.createElement('span',{style:{color:'#1D4ED8',fontWeight:800}},window.fmtCur(ta))),
            Row('Current Paid',        window.fmtCur(tsPaid),        '#166534'),
            Row('Current Outstanding', window.fmtCur(tsOutstanding), tsOutstanding>0?'#991B1B':'#166534'),
            Row('Current Balance',     window.fmtCur(tsOutstanding))
          )
        )
      ),

      // ── Role-specific: VENDOR ─────────────────────────────────────────
      role === 'Vendor' && React.createElement('div', { style:{marginBottom:14} },
        SHdr('Vendor Settlement Recovery', '#6D28D9', 'building'),
        React.createElement('div', { className:'dd-2col', style:{gap:12} },
          React.createElement('div', { style:{background:'#fff',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'12px 14px'} },
            React.createElement('div', { style:{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:8} },
              React.createElement('span', { style:{fontSize:11,fontWeight:700,color:'#6D28D9',display:'flex',alignItems:'center',gap:5} }, ic(IC.building,'#6D28D9',12), 'Recovered From Vendor'),
              vendorSettlement && AutoChip()
            ),
            Row('Vendor Name',           vendorName),
            Row('Vendor Settlement No.', vendorSettlement ? vendorSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Settlement Date',       vendorSettlement ? (vendorSettlement.createdDate ? window.fmtDate(vendorSettlement.createdDate) : '—') : '—'),
            Row('Settlement Status',     vendorSettlement
              ? React.createElement(window.VsBadge, { s:vendorSettlement.status })
              : React.createElement('span', { style:{color:'var(--txt3)',fontSize:11,fontStyle:'italic'} }, 'Not Yet Generated')),
            Row('Vendor Settlement ID',  vendorSettlement ? vendorSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Generated Automatically', 'Yes'),
            vendorSettlement && React.createElement('div', { style:{marginTop:8} },
              LinkBtn('Open Vendor Settlement', function(){ navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id}); })
            )
          ),
          React.createElement('div', { style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
            SHdr('Recovery Status', '#6D28D9'),
            Row('Diesel Recovery', React.createElement('span',{style:{color:'#6D28D9',fontWeight:800}},window.fmtCur(va))),
            Row('Paid',            window.fmtCur(vsPaid),        '#166534'),
            Row('Outstanding',     window.fmtCur(vsOutstanding), vsOutstanding>0?'#991B1B':'#166534'),
            Row('Balance',         window.fmtCur(vsOutstanding))
          )
        )
      ),

      // ── Role-specific: SPLIT ──────────────────────────────────────────
      role === 'Split' && React.createElement('div', { style:{marginBottom:14} },
        SHdr('Split Allocation Detail', '#6D28D9', 'split'),
        // Summary banner
        React.createElement('div', { style:{background:'#F5F3FF',border:'1px solid #DDD6FE',borderRadius:8,padding:'10px 14px',marginBottom:12} },
          React.createElement('div', { style:{display:'flex',flexWrap:'wrap',gap:10,marginBottom:10} },
            [['Total Diesel Deduction',window.fmtCur(totalAmt),'var(--or)'],
             ['Vendor %',splitVendorPct+'%','#6D28D9'],
             ['Transport %',splitTransportPct+'%','#1D4ED8'],
             ['Vendor Amount',window.fmtCur(va),'#166534'],
             ['Transport Amount',window.fmtCur(ta),'#1D4ED8'],
             ['Split Ratio',splitVendorPct+'% / '+splitTransportPct+'%','#374151']
            ].map(function(item){
              return React.createElement('div', { key:item[0], style:{flex:'1 1 100px',background:'#fff',border:'1px solid #DDD6FE',borderRadius:6,padding:'7px 10px'} },
                React.createElement('div', { style:{fontSize:9.5,color:'#6D28D9',fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:2} }, item[0]),
                React.createElement('div', { style:{fontSize:13,fontWeight:800,color:item[2]} }, item[1])
              );
            })
          ),
          React.createElement('div', { style:{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'4px 12px'} },
            Row('Split Reference ID',   d.splitRefId||'—'),
            Row('Created Date',         d.splitCreatedOn ? window.fmtDate(d.splitCreatedOn) : '—'),
            Row('Created By',           d.splitCreatedBy||d.createdBy||'System'),
            Row('Generation Status',    splitGenStatus),
            Row('Vendor Settlement ID', vendorSettlement ? vendorSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Transport Settlement ID', transportSettlement ? transportSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Vendor Settlement Status', vendorSettlement ? React.createElement(window.VsBadge,{s:vendorSettlement.status}) : React.createElement('span',{style:{color:'var(--txt3)',fontStyle:'italic',fontSize:11}},'Not Generated')),
            Row('Transport Settlement Status', transportSettlement ? React.createElement(window.StBadge,{s:transportSettlement.status}) : React.createElement('span',{style:{color:'var(--txt3)',fontStyle:'italic',fontSize:11}},'Not Generated')),
            Row('Outstanding Vendor Balance',    window.fmtCur(vsOutstanding)),
            Row('Outstanding Transport Balance', window.fmtCur(tsOutstanding))
          )
        ),
        // Side-by-side settlement cards
        React.createElement('div', { className:'dd-2col', style:{gap:12} },
          // Vendor Portion
          React.createElement('div', { style:{background:'#fff',border:'1.5px solid #DDD6FE',borderRadius:8,padding:'12px 14px'} },
            React.createElement('div', { style:{fontWeight:700,fontSize:11,color:'#6D28D9',marginBottom:8,display:'flex',justifyContent:'space-between',alignItems:'center'} },
              React.createElement('span', { style:{display:'flex',alignItems:'center',gap:5} }, ic(IC.building,'#6D28D9',12), 'Vendor Portion'),
              vendorSettlement && AutoChip()
            ),
            Row('Settlement Number', vendorSettlement ? vendorSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Amount',  React.createElement('span',{style:{color:'#166534',fontWeight:800}},window.fmtCur(va))),
            Row('Vendor',  vendorName),
            Row('Status',  vendorSettlement ? React.createElement(window.VsBadge,{s:vendorSettlement.status}) : React.createElement('span',{style:{color:'var(--txt3)',fontStyle:'italic',fontSize:11}},'Not Generated')),
            Row('Paid',        window.fmtCur(vsPaid),        '#166534'),
            Row('Outstanding', window.fmtCur(vsOutstanding), vsOutstanding>0?'#991B1B':'#166534'),
            React.createElement('div', { style:{marginTop:8} },
              vendorSettlement
                ? LinkBtn('Open Vendor Settlement', function(){ navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id}); })
                : React.createElement('div',{style:{fontSize:11,color:'var(--txt3)',fontStyle:'italic'}},'Auto-generates in next Vendor Settlement for '+vendorName)
            )
          ),
          // Transport Portion
          React.createElement('div', { style:{background:'#fff',border:'1.5px solid #BFDBFE',borderRadius:8,padding:'12px 14px'} },
            React.createElement('div', { style:{fontWeight:700,fontSize:11,color:'#1D4ED8',marginBottom:8,display:'flex',justifyContent:'space-between',alignItems:'center'} },
              React.createElement('span', { style:{display:'flex',alignItems:'center',gap:5} }, ic(IC.truck,'#1D4ED8',12), 'Transport Portion'),
              transportSettlement && AutoChip()
            ),
            Row('Settlement Number', transportSettlement ? transportSettlement.id.slice(0,8).toUpperCase() : '—'),
            Row('Amount',  React.createElement('span',{style:{color:'#1D4ED8',fontWeight:800}},window.fmtCur(ta))),
            Row('Transporter', trName),
            Row('Status',  transportSettlement ? React.createElement(window.StBadge,{s:transportSettlement.status}) : React.createElement('span',{style:{color:'var(--txt3)',fontStyle:'italic',fontSize:11}},'Not Generated')),
            Row('Paid',        window.fmtCur(tsPaid),        '#166534'),
            Row('Outstanding', window.fmtCur(tsOutstanding), tsOutstanding>0?'#991B1B':'#166534'),
            React.createElement('div', { style:{marginTop:8} },
              transportSettlement
                ? LinkBtn('Open Transport Settlement', function(){ navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id}); })
                : React.createElement('div',{style:{fontSize:11,color:'var(--txt3)',fontStyle:'italic'}},'Auto-generates in next Transport Settlement for '+trName)
            )
          )
        )
      ),

      // ── Allocation Timeline ───────────────────────────────────────────
      React.createElement('div', { style:{marginBottom:14,background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
        SHdr('Allocation Timeline', 'var(--txt2)', 'clock'),
        React.createElement('div', { style:{position:'relative',paddingLeft:22} },
          React.createElement('div', { style:{position:'absolute',left:7,top:6,bottom:6,width:2,background:'#E5E7EB',borderRadius:1} }),
          timeline.map(function(ev, i) {
            return React.createElement('div', { key:i, style:{position:'relative',marginBottom:10,paddingLeft:14} },
              React.createElement('div', { style:{position:'absolute',left:-8,top:4,width:10,height:10,borderRadius:'50%',background:ev.done?'#1D4ED8':'#E5E7EB',border:'2px solid #fff',boxShadow:'0 0 0 2px '+(ev.done?'#BFDBFE':'#D1D5DB')} }),
              React.createElement('div', { style:{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:8} },
                React.createElement('div', null,
                  React.createElement('div', { style:{fontWeight:700,fontSize:12,color:'var(--txt)'} }, ev.label),
                  React.createElement('div', { style:{fontSize:10.5,color:'var(--txt3)',marginTop:1} },
                    [ev.ts ? window.fmtDate((ev.ts+'').slice(0,10)) : null, ev.who, ev.module, 'Ref: '+ev.ref].filter(Boolean).join(' · ')
                  )
                ),
                React.createElement('span', { style:{fontSize:10,fontWeight:600,color:ev.done?'#166534':'var(--txt3)',background:ev.done?'#DCFCE7':'#F3F4F6',border:'1px solid '+(ev.done?'#BBF7D0':'var(--bdr)'),borderRadius:12,padding:'2px 8px',flexShrink:0,whiteSpace:'nowrap',display:'inline-flex',alignItems:'center',gap:4} },
                  ev.done ? ic(IC.check,'#166534',10) : ic(IC.clock,'var(--txt3)',10),
                  ev.done ? 'Done' : 'Pending'
                )
              )
            );
          })
        )
      ),

      // ── Linked Transactions ───────────────────────────────────────────
      React.createElement('div', { style:{marginBottom:14,background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
        SHdr('Related Transactions', 'var(--txt2)', 'link'),
        React.createElement('div', { style:{display:'flex',flexWrap:'wrap',gap:8} },
          challanPO && React.createElement('button', {
            onClick:function(){ navigate&&navigate('purchases',{focusPurchaseId:challanPO.id}); },
            style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:600,color:'#374151',background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'6px 10px',cursor:'pointer',fontFamily:'var(--font)'}
          }, ic(IC.file,'#6B7280',12), 'PO: ', React.createElement('span',{style:{fontFamily:'var(--font)',fontWeight:700}}, d.challanNumber)),
          transportSettlement && React.createElement('button', {
            onClick:function(){ navigate&&navigate('transportsettlement',{focusSettlementId:transportSettlement.id}); },
            style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:600,color:'#1D4ED8',background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:6,padding:'6px 10px',cursor:'pointer',fontFamily:'var(--font)'}
          }, ic(IC.truck,'#1D4ED8',12), 'Transport Settlement: ', React.createElement('span',{style:{fontFamily:'var(--font)',fontWeight:700}}, transportSettlement.id.slice(0,8).toUpperCase())),
          vendorSettlement && React.createElement('button', {
            onClick:function(){ navigate&&navigate('vendorsettlement',{focusSettlementId:vendorSettlement.id}); },
            style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:600,color:'#6D28D9',background:'#F5F3FF',border:'1px solid #DDD6FE',borderRadius:6,padding:'6px 10px',cursor:'pointer',fontFamily:'var(--font)'}
          }, ic(IC.building,'#6D28D9',12), 'Vendor Settlement: ', React.createElement('span',{style:{fontFamily:'var(--font)',fontWeight:700}}, vendorSettlement.id.slice(0,8).toUpperCase())),
          React.createElement('button', {
            onClick:function(){ navigate&&navigate('diesel',{focusAllocId:d.id}); },
            style:{display:'inline-flex',alignItems:'center',gap:5,fontSize:11,fontWeight:600,color:'var(--or)',background:'var(--or-lt)',border:'1px solid var(--or-bdr)',borderRadius:6,padding:'6px 10px',cursor:'pointer',fontFamily:'var(--font)'}
          }, ic(IC.fuel,'var(--or)',12), 'Allocation Report')
        ),
        !challanPO && !transportSettlement && !vendorSettlement && React.createElement('div', { style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'} }, 'No linked transactions yet.')
      ),

      // ── Financial Breakdown ───────────────────────────────────────────
      React.createElement('div', { style:{marginBottom:14,background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
        SHdr('Financial Breakdown', 'var(--txt2)', 'wallet'),
        React.createElement('div', { className:'dd-2col', style:{gap:12} },
          React.createElement('div', null,
            grossFreight>0 && Row('Gross Freight',      window.fmtCur(grossFreight), '#166534'),
            Row('Actual Fuel Cost',   window.fmtCur(actualCost), 'var(--or)'),
            Row('Diesel Margin',      marginAmt>0?window.fmtCur(marginAmt):'—', '#B45309'),
            Row('Deduction Rate',     dedRate>0?'₹'+dedRate.toFixed(2)+'/L':'—'),
            ta>0 && Row('Transport Deduction', window.fmtCur(ta), '#1D4ED8'),
            va>0 && Row('Vendor Deduction',    window.fmtCur(va), '#6D28D9')
          ),
          React.createElement('div', null,
            Row('Net Recoverable',    window.fmtCur(totalAmt), 'var(--or)'),
            Row('Recovered Amount',   window.fmtCur(recoveredAmt), recoveredAmt>0?'#166534':'var(--txt)'),
            Row('Pending Recovery',   window.fmtCur(pendingRecovery), pendingRecovery>0?'#991B1B':'#166534'),
            Row('Variance',           window.fmtCur(Math.abs(totalAmt - recoveredAmt - pendingRecovery)))
          )
        )
      ),

      // ── Audit Information ─────────────────────────────────────────────
      React.createElement('div', { style:{marginBottom:14,background:'#F8FAFC',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'} },
        SHdr('Audit Information', 'var(--txt2)', 'shield'),
        React.createElement('div', { className:'dd-2col', style:{gap:12} },
          React.createElement('div', null,
            Row('Transaction ID',   d.id ? d.id.slice(0,8).toUpperCase() : '—'),
            Row('Allocation ID',    d.id ? d.id.slice(0,8).toUpperCase() : '—'),
            Row('Settlement IDs',   [transportSettlement?transportSettlement.id.slice(0,8).toUpperCase():null, vendorSettlement?vendorSettlement.id.slice(0,8).toUpperCase():null].filter(Boolean).join(', ')||'—'),
            Row('Company',          Store.name('companies',d.companyId)||'—'),
            Row('Auto Generated',   'Yes — Diesel Allocation Engine')
          ),
          React.createElement('div', null,
            Row('Created By',   d.createdBy   || 'System'),
            Row('Modified By',  d.modifiedBy  || '—'),
            Row('Created On',   d.date ? window.fmtDate(d.date) : '—'),
            Row('Modified On',  d.modifiedDate ? window.fmtDate(d.modifiedDate) : '—'),
            Row('Version',      d.version ? 'v'+d.version : 'v1')
          )
        )
      ),

      // ── Expandable Allocation History ─────────────────────────────────
      React.createElement('div', { style:{background:'#fff',border:'1px solid var(--bdr)',borderRadius:8,overflow:'hidden'} },
        React.createElement('button', {
          onClick:function(){ setHistOpen(function(o){ return !o; }); },
          style:{width:'100%',display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 14px',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)'}
        },
          React.createElement('div', { style:{display:'flex',alignItems:'center',gap:8} },
            ic(IC.clip,'var(--txt3)',13),
            React.createElement('span', { style:{fontWeight:700,fontSize:10.5,color:'var(--txt)',textTransform:'uppercase',letterSpacing:'.5px'} }, 'Allocation History'),
            React.createElement('span', { style:{fontSize:10,background:'#F3F4F6',borderRadius:10,padding:'1px 7px',color:'var(--txt2)',fontWeight:600} }, (d.allocHistory && d.allocHistory.length) || 0)
          ),
          React.createElement('span', { style:{fontSize:11,color:'var(--txt3)',transform:histOpen?'rotate(180deg)':'none',transition:'transform .15s'} }, '▼')
        ),
        histOpen && React.createElement('div', { style:{borderTop:'1px solid var(--bdr)',padding:'12px 14px'} },
          (!d.allocHistory || d.allocHistory.length === 0)
            ? React.createElement('div', { style:{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic',padding:'4px 0'} }, 'No changes recorded — original allocation unchanged.')
            : d.allocHistory.slice().reverse().map(function(h, i) {
                var num = d.allocHistory.length - i;
                return React.createElement('div', { key:h.id||i, style:{borderBottom:'1px dashed #E5E7EB',paddingBottom:10,marginBottom:10} },
                  React.createElement('div', { style:{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:4} },
                    React.createElement('span', { style:{fontSize:11,fontWeight:700,color:'var(--txt)'} }, 'Change #'+num),
                    React.createElement('span', { style:{fontSize:10.5,color:'var(--txt3)'} }, new Date(h.timestamp).toLocaleString('en-IN',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}))
                  ),
                  React.createElement('div', { style:{display:'flex',gap:8,flexWrap:'wrap',marginBottom:4,alignItems:'center'} },
                    React.createElement('span', { style:{fontSize:11,background:'#FEE2E2',color:'#991B1B',borderRadius:4,padding:'2px 7px',fontWeight:600} }, 'Before: '+h.fromRole+' (V:'+window.fmtCur(h.fromVendorAmount||0)+' / T:'+window.fmtCur(h.fromTransportAmount||0)+')'),
                    React.createElement('span', { style:{fontSize:12,color:'var(--txt3)'} }, '→'),
                    React.createElement('span', { style:{fontSize:11,background:'#DCFCE7',color:'#166534',borderRadius:4,padding:'2px 7px',fontWeight:600} }, 'After: '+h.toRole+' (V:'+window.fmtCur(h.toVendorAmount||0)+' / T:'+window.fmtCur(h.toTransportAmount||0)+')')
                  ),
                  React.createElement('div', { style:{fontSize:11,color:'var(--txt2)'} },
                    React.createElement('span', { style:{fontWeight:600} }, 'Reason: '), h.reason||'—',
                    React.createElement('span', { style:{marginLeft:12,color:'var(--txt3)'} }, '— '+h.changedBy)
                  )
                );
              })
        )
      )
    )
  );
}
window.AllocationTraceabilityPanel = AllocationTraceabilityPanel;
