// Diesel Module — Challan-Linked Bill Entry + Purchase-Based Auto Records
// Architecture: Challan Number is the single source of truth linking all diesel bills to trips.
const { useState: dsSt, useEffect: dsEf, useContext: dsCtx, useMemo: dsMemo, useRef: dsRef } = React;
const AppCtx = window.AppCtx;

// ── Diesel Quantity Formatter — 3 decimal places, universal standard ──────────
// Used everywhere diesel litres are displayed: tables, drilldowns, summaries,
// reports, CSV exports, totals. Future modules should call window.fmtDieselQty.
window.fmtDieselQty = function(v) {
  var n = parseFloat(v) || 0;
  return n.toFixed(3);
};

// ── Active Diesel Margin Helper ───────────────────────────────────────────────
// Returns the configured margin (₹/L) for a given date from dieselMarginSettings.
// Used in diesel entry form to auto-populate Margin and compute Deduction Rate.
window.getActiveDieselMargin = function(date) {
  var settings = Store.all('dieselMarginSettings') || [];
  var d = date || new Date().toISOString().slice(0, 10);
  var active = settings.filter(function(s) {
    if (s.status !== 'Active') return false;
    if (s.effectiveFrom && d < s.effectiveFrom) return false;
    if (s.effectiveTo && d > s.effectiveTo) return false;
    return true;
  });
  if (!active.length) return 0;
  return parseFloat(active[active.length - 1].defaultMargin) || 0;
};

// ── Diesel Date Period Filter ── shared preset+custom-range engine ───────────
// Matches the period-filter language used across Dashboard / Settlement
// Performance Center / Executive Dashboard: preset chips resolved to a
// {from,to} ISO range, plus a Custom Range option backed by the standard
// OM Group date pickers. Pure + reusable — exposed on window in case other
// Diesel sub-tabs (Purchase-Based, Allocation Report) need the same range.
window.DIESEL_PERIOD_OPTIONS = [
  { id: 'today',       label: 'Today' },
  { id: 'yesterday',   label: 'Yesterday' },
  { id: 'thisWeek',    label: 'This Week' },
  { id: 'lastWeek',    label: 'Last Week' },
  { id: 'thisMonth',   label: 'This Month' },
  { id: 'lastMonth',   label: 'Last Month' },
  { id: 'thisQuarter', label: 'This Quarter' },
  { id: 'lastQuarter', label: 'Last Quarter' },
  { id: 'fy',          label: 'Financial Year' },
  { id: 'prevFY',      label: 'Previous Financial Year' },
  { id: 'last30',      label: 'Last 30 Days' },
  { id: 'last90',      label: 'Last 90 Days' },
  { id: 'all',         label: 'All Time' },
  { id: 'custom',      label: 'Custom Range' },
];

function dieselFmtShort(dstr) {
  if (!dstr) return '';
  var d = new Date(dstr + 'T00:00:00');
  if (isNaN(d.getTime())) return dstr;
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  return (d.getDate() < 10 ? '0' : '') + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
}

window.getDieselPeriodRange = function(preset, cFrom, cTo) {
  var now = new Date();
  var tod = now.toISOString().slice(0, 10);
  function iso(d) { return d.toISOString().slice(0, 10); }
  function addDays(d, n) { var r = new Date(d); r.setDate(r.getDate() + n); return r; }

  if (preset === 'today')     return { from: tod, to: tod };
  if (preset === 'yesterday') { var y = addDays(now, -1); return { from: iso(y), to: iso(y) }; }
  if (preset === 'thisWeek')  { var s = addDays(now, -now.getDay()); return { from: iso(s), to: tod }; }
  if (preset === 'lastWeek')  { var eo = addDays(now, -now.getDay() - 1); var so = addDays(eo, -6); return { from: iso(so), to: iso(eo) }; }
  if (preset === 'thisMonth') return { from: tod.slice(0, 7) + '-01', to: tod };
  if (preset === 'lastMonth') {
    var fm = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    var lm = new Date(now.getFullYear(), now.getMonth(), 0);
    return { from: iso(fm), to: iso(lm) };
  }
  if (preset === 'thisQuarter') {
    var q = Math.floor(now.getMonth() / 3);
    var qs = new Date(now.getFullYear(), q * 3, 1);
    return { from: iso(qs), to: tod };
  }
  if (preset === 'lastQuarter') {
    var q2 = Math.floor(now.getMonth() / 3) - 1;
    var yr = now.getFullYear();
    if (q2 < 0) { q2 = 3; yr -= 1; }
    var qs2 = new Date(yr, q2 * 3, 1);
    var qe2 = new Date(yr, q2 * 3 + 3, 0);
    return { from: iso(qs2), to: iso(qe2) };
  }
  if (preset === 'fy' || preset === 'prevFY') {
    var fyStartYear = now.getMonth() >= 3 ? now.getFullYear() : now.getFullYear() - 1;
    if (preset === 'prevFY') fyStartYear -= 1;
    var fyFrom = fyStartYear + '-04-01';
    var fyTo   = preset === 'fy' ? tod : (fyStartYear + 1) + '-03-31';
    return { from: fyFrom, to: fyTo };
  }
  if (preset === 'last30') return { from: iso(addDays(now, -30)), to: tod };
  if (preset === 'last90') return { from: iso(addDays(now, -90)), to: tod };
  if (preset === 'custom') return { from: cFrom || '', to: cTo || '' };
  return { from: '', to: '' }; // all time
};

window.dieselInPeriod = function(dt, from, to) {
  if (!from && !to) return true;
  if (!dt) return false;
  if (from && dt < from) return false;
  if (to   && dt > to)   return false;
  return true;
};

function DieselPeriodDropdown({ preset, onChange, customFrom, customTo, onCustomChange }) {
  const [open, setOpen] = dsSt(false);
  const ref = dsRef(null);
  const panelRef = dsRef(null);

  dsEf(function() {
    function close(e) {
      if (ref.current && !ref.current.contains(e.target) &&
          panelRef.current && !panelRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', close);
    return function() { document.removeEventListener('mousedown', close); };
  }, []);

  var opt = window.DIESEL_PERIOD_OPTIONS.find(function(o) { return o.id === preset; });
  var label = (preset === 'custom' && customFrom && customTo)
    ? dieselFmtShort(customFrom) + ' – ' + dieselFmtShort(customTo)
    : (opt ? opt.label : 'All Time');
  var isActive = preset && preset !== 'all';

  function pick(id) {
    onChange(id);
    if (id !== 'custom') setOpen(false);
  }

  return (
    <div ref={ref} style={{position:'relative'}}>
      <div
        onClick={function() { setOpen(function(p) { return !p; }); }}
        className="fsel"
        style={{
          display:'flex', alignItems:'center', gap:6, cursor:'pointer',
          minWidth:172, justifyContent:'space-between',
          borderColor: open ? 'var(--or)' : (isActive ? 'var(--or-bdr)' : 'var(--bdr)'),
          background: isActive ? 'var(--or-lt)' : '#F9FAFB',
          boxShadow: open ? '0 0 0 3px rgba(249,115,22,.10)' : 'none',
        }}>
        <span style={{display:'flex',alignItems:'center',gap:6,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',fontWeight:isActive?600:400,color:isActive?'var(--or)':'var(--txt)'}}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0}}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          {label}
        </span>
        <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{flexShrink:0,color:'var(--txt3)',transform:open?'rotate(180deg)':'none',transition:'transform .15s'}}><path d="M6 9l6 6 6-6"/></svg>
      </div>
      <window.FloatingLayer anchorRef={ref} open={open} align="left" minWidth={230} panelRef={panelRef}
        style={{background:'#fff',border:'1px solid var(--or-bdr)',borderRadius:'var(--r)',boxShadow:'0 8px 24px rgba(0,0,0,.14)',overflow:'hidden'}}>
          <div style={{maxHeight:320,overflowY:'auto'}}>
            {window.DIESEL_PERIOD_OPTIONS.map(function(o) {
              var isSel = preset === o.id;
              return (
                <div key={o.id}
                  onClick={function() { pick(o.id); }}
                  style={{padding:'8px 14px',cursor:'pointer',fontSize:12.5,background:isSel?'var(--or-lt)':'#fff',color:isSel?'var(--or)':'var(--txt)',fontWeight:isSel?600:400,borderLeft:isSel?'3px solid var(--or)':'3px solid transparent',display:'flex',alignItems:'center',justifyContent:'space-between',borderBottom:'1px solid #F9FAFB',transition:'background .1s'}}
                  onMouseEnter={function(e){ if(!isSel) e.currentTarget.style.background='var(--or-lt)'; }}
                  onMouseLeave={function(e){ if(!isSel) e.currentTarget.style.background='#fff'; }}>
                  <span>{o.label}</span>
                  {isSel && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--or)" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>}
                </div>
              );
            })}
          </div>
          {preset === 'custom' && (
            <div style={{padding:'10px 12px',borderTop:'1px solid var(--bdr)',background:'#FAFAFA',display:'flex',flexDirection:'column',gap:8}}>
              <div style={{fontSize:10.5,fontWeight:700,color:'var(--txt2)',textTransform:'uppercase',letterSpacing:'.04em'}}>Custom Range</div>
              <div style={{display:'flex',alignItems:'center',gap:6}}>
                <input type="date" className="inp" value={customFrom||''} max={customTo||undefined} onChange={function(e){ onCustomChange(e.target.value, customTo); }} style={{flex:1,fontSize:12,padding:'5px 8px',height:32}}/>
                <span style={{color:'var(--txt3)',fontSize:11}}>–</span>
                <input type="date" className="inp" value={customTo||''} min={customFrom||undefined} onChange={function(e){ onCustomChange(customFrom, e.target.value); }} style={{flex:1,fontSize:12,padding:'5px 8px',height:32}}/>
              </div>
              <button type="button" className="btn btn-or btn-sm" style={{alignSelf:'flex-end'}} disabled={!customFrom||!customTo} onClick={function(){ setOpen(false); }}>Apply</button>
            </div>
          )}
      </window.FloatingLayer>
    </div>
  );
}
window.DieselPeriodDropdown = DieselPeriodDropdown;

// ── Searchable Diesel Source Dropdown ── Full Keyboard Navigation ─────────────
// Matches the ERPSelect/SearchableSelect standard used throughout the ERP.
// Tab focuses in (from Bill Date) and Tab after selection moves to Diesel Litres.
// ↓ / Enter / Space → open  |  ↑/↓ → navigate  |  Enter → select  |  Esc → close
// Typing → live filter  |  Tab → confirm selection + move to next field
function DieselSourceDropdown({ value, onChange, onAddNew, sources }) {
  const [open,     setOpen]    = dsSt(false);
  const [q,        setQ]       = dsSt('');
  const [hlIdx,    setHlIdx]   = dsSt(-1);
  const [dropDir,  setDropDir] = dsSt('down');
  const wrapRef  = dsRef(null);
  const inputRef = dsRef(null);
  const listRef  = dsRef(null);
  const panelRef = dsRef(null);

  const active   = sources.filter(function(s) { return s.status !== 'Inactive'; });
  const filtered = q ? active.filter(function(s) { return s.name.toLowerCase().includes(q.toLowerCase()); }) : active;

  // Close on outside click/mousedown
  dsEf(function() {
    function close(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target) &&
          panelRef.current && !panelRef.current.contains(e.target)) {
        setOpen(false); setQ(''); setHlIdx(-1);
      }
    }
    document.addEventListener('mousedown', close);
    return function() { document.removeEventListener('mousedown', close); };
  }, []);

  // Reset highlight when dropdown closes
  dsEf(function() { if (!open) setHlIdx(-1); }, [open]);

  // Scroll highlighted item into view
  dsEf(function() {
    if (hlIdx < 0 || !listRef.current) return;
    var items  = listRef.current.children;
    var idx    = Math.min(hlIdx, items.length - 1);
    var el     = items[idx];
    if (!el) return;
    var parent = listRef.current;
    var eTop = el.offsetTop, eBot = eTop + el.offsetHeight;
    if (eBot > parent.scrollTop + parent.clientHeight) parent.scrollTop = eBot - parent.clientHeight;
    else if (eTop < parent.scrollTop) parent.scrollTop = eTop;
  }, [hlIdx]);

  function calcDir() {
    if (!wrapRef.current) return;
    var r = wrapRef.current.getBoundingClientRect();
    setDropDir(window.innerHeight - r.bottom < 220 && r.top > 220 ? 'up' : 'down');
  }

  function pick(name) { onChange(name); setOpen(false); setQ(''); setHlIdx(-1); }

  function handleInputChange(e) {
    setQ(e.target.value);
    if (!open) { calcDir(); setOpen(true); }
    setHlIdx(0);
  }

  function handleFocus() { calcDir(); setOpen(true); setQ(''); }

  function handleKeyDown(e) {
    var optCount = filtered.length; // 'Add New' is at virtual index optCount
    if (!open) {
      if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
        e.preventDefault(); calcDir(); setOpen(true); setHlIdx(0); setQ('');
      }
      return;
    }
    if (e.key === 'Escape')    { e.preventDefault(); setOpen(false); setQ(''); setHlIdx(-1); return; }
    if (e.key === 'ArrowDown') { e.preventDefault(); setHlIdx(function(i) { return i < optCount ? i + 1 : i; }); return; }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setHlIdx(function(i) { return i > 0 ? i - 1 : 0; }); return; }
    if (e.key === 'Enter') {
      e.preventDefault();
      if (hlIdx >= 0 && hlIdx < optCount && filtered[hlIdx]) { pick(filtered[hlIdx].name); }
      else if (hlIdx === optCount) { setOpen(false); setQ(''); setHlIdx(-1); onAddNew(); }
      return;
    }
    if (e.key === 'Tab') {
      // Confirm highlighted option, then let Tab naturally move focus to Diesel Litres
      if (hlIdx >= 0 && hlIdx < optCount && filtered[hlIdx]) { pick(filtered[hlIdx].name); }
      setOpen(false); setQ(''); setHlIdx(-1);
      // Do NOT e.preventDefault() — Tab must propagate to move focus to next field
    }
  }

  var displayVal = open ? q : (value || '');

  return (
    <div ref={wrapRef} style={{position:'relative'}}>
      {/* Input-based trigger: focusable by Tab, matches all other ERP dropdowns */}
      <div style={{
        display:'flex', alignItems:'center',
        border:'1.5px solid '+(open ? 'var(--or)' : 'var(--bdr)'),
        borderRadius:9, background:'#fff',
        transition:'border-color .15s, box-shadow .15s',
        boxShadow: open ? '0 0 0 3px rgba(249,115,22,.10)' : undefined,
      }}>
        <input
          ref={inputRef}
          value={displayVal}
          onChange={handleInputChange}
          onFocus={handleFocus}
          onKeyDown={handleKeyDown}
          placeholder="Select Diesel Source"
          autoComplete="off"
          style={{
            flex:1, border:'none', outline:'none',
            padding:'7px 12px', fontSize:13,
            fontFamily:'var(--font)', height:38,
            color:'var(--txt)', background:'transparent',
            fontWeight: value && !open ? 600 : 400,
            cursor:'text',
          }}
        />
        <div style={{padding:'0 10px',display:'flex',alignItems:'center',height:38,pointerEvents:'none',transform:open?'rotate(180deg)':'none',transition:'transform .2s'}}>
          <svg width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke={open?'var(--or)':'var(--txt3)'} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
      </div>
      <window.FloatingLayer anchorRef={wrapRef} open={open} placement={dropDir} matchWidth panelRef={panelRef}
        style={{background:'#fff',border:'1px solid var(--or-bdr)',borderRadius:'var(--r)',boxShadow:'0 6px 20px rgba(0,0,0,.12)',overflow:'hidden',display:'flex',flexDirection:'column'}}>
          <div ref={listRef} style={{maxHeight:180,overflowY:'auto',overflowX:'hidden'}}>
            {filtered.length === 0 ? (
              <div style={{padding:'10px 12px',fontSize:12,color:'var(--txt3)',fontStyle:'italic',textAlign:'center'}}>
                {q ? 'No results for "'+q+'"' : 'No diesel sources available'}
              </div>
            ) : filtered.map(function(s, i) {
              var isSel = value === s.name;
              var isHl  = hlIdx === i;
              return (
                <div key={s.id}
                  onMouseDown={function(e) { e.preventDefault(); pick(s.name); }}
                  onMouseEnter={function() { setHlIdx(i); }}
                  style={{
                    padding:'8px 12px', cursor:'pointer', fontSize:12.5,
                    background: isSel || isHl ? 'var(--or-lt)' : '#fff',
                    color: isSel || isHl ? 'var(--or)' : 'var(--txt)',
                    fontWeight: isSel ? 600 : 400,
                    borderBottom:'1px solid #F9FAFB',
                    display:'flex', alignItems:'center', justifyContent:'space-between',
                    borderLeft: isSel ? '3px solid var(--or)' : '3px solid transparent',
                  }}>
                  <span>{s.name}</span>
                  {isSel && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--or)" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>}
                </div>
              );
            })}
          </div>
          <div
            onMouseDown={function(e) { e.preventDefault(); setOpen(false); setQ(''); onAddNew(); }}
            onMouseEnter={function() { setHlIdx(filtered.length); }}
            style={{
              padding:'8px 12px', cursor:'pointer', fontSize:12, fontWeight:600,
              color:'var(--or)', borderTop:'1px solid var(--bdr)',
              background: hlIdx === filtered.length ? '#FEF0E3' : '#FFF9F5',
              display:'flex', alignItems:'center', gap:6,
            }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            Add New Diesel Source
          </div>
      </window.FloatingLayer>
    </div>
  );
}

// ── Challan Search Dropdown ───────────────────────────────────────────────────
// Single source of truth: filters purchases (challans) by company → transporter → vehicle.
// Excludes fully-settled challans. Auto-populates all downstream fields on selection.
function ChallanSearchDropdown({ companyId, isGroup, transporterId, vehicleFull, periodFrom, periodTo, value, onChange, disabled }) {
  const [open, setOpen] = dsSt(false);
  const [q,    setQ]    = dsSt('');
  const ref = dsRef(null);
  const panelRef = dsRef(null);

  dsEf(function() {
    function close(e) {
      if (ref.current && !ref.current.contains(e.target) &&
          panelRef.current && !panelRef.current.contains(e.target)) { setOpen(false); setQ(''); }
    }
    document.addEventListener('mousedown', close);
    return function() { document.removeEventListener('mousedown', close); };
  }, []);

  // Resolve transporter name for name-based matching (handles legacy data)
  const masterName = dsMemo(function() {
    if (!transporterId) return '';
    var rec = (Store.all('transporterMaster','group')||[]).find(function(t){return t.id===transporterId;});
    return rec ? (rec.name||'').toLowerCase().trim() : '';
  }, [transporterId]);

  const challans = dsMemo(function() {
    const purchases = Store.all('purchases') || [];
    return purchases.filter(function(p) {
      if (!p.challanNumber || p.status === 'Cancelled') return false;
      // Company filter
      if (!isGroup && p.companyId !== companyId) return false;
      if (isGroup && companyId && companyId !== 'group' && p.companyId !== companyId) return false;
      // Transporter filter (multi-strategy match)
      if (transporterId) {
        var byMId  = p.transporterMasterId === transporterId;
        var byName = masterName && (p.transporterName||'').toLowerCase().trim() === masterName;
        if (!byMId && !byName) return false;
      }
      // Vehicle filter
      if (vehicleFull && p.vehicleFull !== vehicleFull) return false;
      // Date range filter
      if (periodFrom && p.date < periodFrom) return false;
      if (periodTo   && p.date > periodTo)   return false;
      // Exclude fully settled
      if (p.settlementStatus === 'Fully Settled') return false;
      return true;
    }).sort(function(a,b){ return (b.date||'')>(a.date||'')?1:-1; });
  }, [companyId, isGroup, transporterId, vehicleFull, masterName, periodFrom, periodTo]);

  const filtered = q ? challans.filter(function(c) {
    var ql  = q.toLowerCase();
    var fi  = (c.items||[])[0];
    var mat = fi ? (Store.name('materials', fi.materialId)||'') : '';
    var qty = (c.items||[]).reduce(function(s,i){return s+(parseFloat(i.quantity)||0);},0);
    var gr  = parseFloat(c.sub)||parseFloat(c.subtotal)||0;
    var vnd = Store.name('vendors', c.vendorId)||'';
    return (c.challanNumber||'').toLowerCase().includes(ql)
        || (c.date||'').includes(ql)
        || (c.vehicleFull||'').toLowerCase().includes(ql)
        || mat.toLowerCase().includes(ql)
        || window.formatQuantityRaw(qty).includes(ql)
        || vnd.toLowerCase().includes(ql)
        || window.fmtCur(gr).includes(ql);
  }) : challans;

  const selected = challans.find(function(c){ return c.challanNumber === value; });

  function pick(ch) {
    onChange(ch); // pass full purchase object for auto-fill
    setOpen(false); setQ('');
  }

  var needsTransporter = !transporterId;
  var needsVehicle     = transporterId && !vehicleFull;
  var placeholder = disabled ? '—' : needsTransporter ? 'Select transporter first' : needsVehicle ? 'Select vehicle first' : 'Select Challan';

  return (
    <div ref={ref} style={{position:'relative',opacity:disabled?0.55:1}}>
      <div
        onClick={disabled ? null : function() { if (!needsTransporter && !needsVehicle) setOpen(function(p){return !p;}); }}
        style={{display:'flex',alignItems:'center',justifyContent:'space-between',border:'1px solid '+(open?'var(--or)':'var(--bdr)'),borderRadius:'var(--r)',padding:'5px 10px',minHeight:38,cursor:disabled||needsTransporter||needsVehicle?'not-allowed':'pointer',background:disabled?'#F5F4F2':'#fff',fontSize:13,userSelect:'none',color:selected?'var(--txt)':'var(--txt3)',transition:'border .1s'}}>
        <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
          {selected ? selected.challanNumber + ' — ' + window.fmtDate(selected.date) : placeholder}
        </span>
        {!disabled && !needsTransporter && !needsVehicle && (
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0,marginLeft:4,color:'var(--txt2)',transform:open?'rotate(180deg)':'none',transition:'transform .15s'}}><path d="M6 9l6 6 6-6"/></svg>
        )}
      </div>
      <window.FloatingLayer anchorRef={ref} open={open} matchWidth minWidth={320} panelRef={panelRef}
        style={{background:'#fff',border:'1px solid var(--or-bdr)',borderRadius:'var(--r)',boxShadow:'0 8px 24px rgba(0,0,0,.14)',overflow:'hidden',display:'flex',flexDirection:'column'}}>
          <div style={{padding:'6px 8px',borderBottom:'1px solid var(--bdr)',background:'#FAFAFA'}}>
            <div style={{position:'relative'}}>
              <svg style={{position:'absolute',left:7,top:'50%',transform:'translateY(-50%)',color:'var(--txt3)',pointerEvents:'none'}} width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
              <input autoFocus value={q} onChange={function(e){setQ(e.target.value);}} onClick={function(e){e.stopPropagation();}} placeholder="Search challan, vehicle, material, date, vendor…" style={{width:'100%',border:'1px solid var(--bdr)',borderRadius:'var(--r)',padding:'4px 8px 4px 26px',fontSize:12,outline:'none',fontFamily:'var(--font)',height:28,background:'#fff'}}/>
            </div>
          </div>
          <div style={{maxHeight:300,overflowY:'auto'}}>
            {filtered.length === 0 ? (
              <div style={{padding:'14px 12px',fontSize:12,color:'var(--txt3)',textAlign:'center',fontStyle:'italic'}}>{q?'No challans matching "'+q+'"':'No available challans for this vehicle'}</div>
            ) : filtered.map(function(ch) {
              var isSel      = value === ch.challanNumber;
              var fi         = (ch.items||[])[0];
              var matName    = fi ? (Store.name('materials', fi.materialId)||'—') : '—';
              var qty        = (ch.items||[]).reduce(function(s,i){return s+(parseFloat(i.quantity)||0);},0);
              var gross      = parseFloat(ch.sub)||parseFloat(ch.subtotal)||0;
              var stStatus   = ch.settlementStatus;
              var vendorName = Store.name('vendors', ch.vendorId)||'';
              return (
                <div key={ch.id} onClick={function(){pick(ch);}} style={{padding:'10px 12px',cursor:'pointer',borderBottom:'1px solid #F3F4F6',background:isSel?'var(--or-lt)':'#fff',transition:'background .1s'}}>
                  {/* Row 1: Challan No + Date + Status badge */}
                  <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:4}}>
                    <span style={{fontFamily:'var(--font)',fontWeight:700,fontSize:12.5,color:isSel?'var(--or)':'var(--txt)'}}>{ch.challanNumber}</span>
                    <div style={{display:'flex',alignItems:'center',gap:6}}>
                      {stStatus && stStatus !== 'Pending' && (
                        <span style={{fontSize:9.5,padding:'1px 5px',borderRadius:3,background:stStatus==='Partially Settled'?'#FEF3C7':'#DCFCE7',color:stStatus==='Partially Settled'?'#92400E':'#166534',fontWeight:700}}>{stStatus}</span>
                      )}
                      <span style={{fontSize:10.5,color:'var(--txt2)',fontWeight:500}}>{window.fmtDate(ch.date)}</span>
                    </div>
                  </div>
                  {/* Row 2: Vehicle · Material · Qty */}
                  <div style={{display:'flex',gap:6,fontSize:11,color:'var(--txt2)',flexWrap:'wrap',alignItems:'center',marginBottom:3}}>
                    {ch.vehicleFull && <span style={{fontFamily:'var(--font)',fontSize:10.5,background:'#F3F4F6',padding:'1px 5px',borderRadius:3,color:'var(--txt)',fontWeight:600}}>{ch.vehicleFull}</span>}
                    {matName && matName !== '—' && <><span style={{color:'var(--txt3)'}}>·</span><span>{matName}</span></>}
                    {qty > 0 && <><span style={{color:'var(--txt3)'}}>·</span><span style={{fontWeight:600}}>{window.formatQuantity(qty)} MT</span></>}
                  </div>
                  {/* Row 3: Vendor + Gross Freight */}
                  <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',fontSize:11}}>
                    <span style={{color:'var(--txt3)',fontSize:10}}>{vendorName ? 'Vendor: '+vendorName : ''}</span>
                    <span style={{color:'var(--ok)',fontWeight:700,fontSize:12}}>{window.fmtCur(gross)}</span>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{padding:'6px 10px',fontSize:11,color:'var(--txt3)',background:'#F9FAFB',borderTop:'1px solid var(--bdr)',display:'flex',gap:6,flexWrap:'wrap',alignItems:'center'}}>
            <span>{challans.length} challan{challans.length!==1?'s':''} available</span>
            {(periodFrom||periodTo) && <span style={{color:'var(--or)',fontWeight:600}}>· Filtered by date range</span>}
            <span>· Fully settled excluded</span>
          </div>
      </window.FloatingLayer>
    </div>
  );
}

// ── Purchase-Based Diesel Tab ─────────────────────────────────────────────────
function PurchaseBasedDieselTab({ companyId, isGroup, tmAll, sources, periodFrom, periodTo }) {
  const [purchases, setPurchases] = dsSt(function() { return Store.all('purchases') || []; });
  const [search,    setSearch]    = dsSt('');
  const [fTrans,    setFTrans]    = dsSt('');
  const [fSrc,      setFSrc]      = dsSt('');
  const [expand,    setExpand]    = dsSt(null);
  const [page,      setPage]      = dsSt(1);
  const PER = 50;

  dsEf(function() {
    var unsub = Store.on(function() { setPurchases(Store.all('purchases') || []); });
    return unsub;
  }, []);

  const tmActive      = tmAll.filter(function(t) { return t.status === 'Active' || !t.status; });
  const activeSources = sources.filter(function(s) { return s.status !== 'Inactive'; });

  const dieselPurchases = dsMemo(function() {
    return (purchases || []).filter(function(p) {
      if ((parseFloat(p.dieselQty) || 0) <= 0 || !p.dieselSource) return false;
      if (!isGroup && p.companyId !== companyId) return false;
      return true;
    }).slice().sort(function(a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [purchases, companyId, isGroup]);

  const filtered = dsMemo(function() {
    return dieselPurchases.filter(function(p) {
      if (search) {
        var q = search.toLowerCase();
        if (![(p.challanNumber || ''), (p.vehicleFull || ''), (p.transporterName || ''), (p.dieselSource || '')].some(function(v) { return v.toLowerCase().includes(q); })) return false;
      }
      if (fTrans && p.transporterMasterId !== fTrans) return false;
      if (fSrc   && p.dieselSource        !== fSrc)   return false;
      if (!window.dieselInPeriod(p.date, periodFrom, periodTo)) return false;
      return true;
    });
  }, [dieselPurchases, search, fTrans, fSrc, periodFrom, periodTo]);

  const totalLitres = filtered.reduce(function(s, p) { return s + (parseFloat(p.dieselQty) || 0); }, 0);
  const totalPgs    = Math.ceil(filtered.length / PER);
  const paged       = filtered.slice((page - 1) * PER, page * PER);

  return (
    <div>
      <div style={{background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:'var(--r)',padding:'10px 14px',marginBottom:10,display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1D4ED8" strokeWidth="2" style={{flexShrink:0}}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        <span style={{fontSize:11.5,color:'#1E40AF',fontWeight:600}}>Auto-Generated from Sales Orders</span>
        <span style={{fontSize:11.5,color:'#1E40AF'}}>Records are derived automatically from Sales Orders where Diesel Quantity &gt; 0. To modify, edit the source Sales Order.</span>
        <span style={{marginLeft:'auto',fontSize:12,fontWeight:700,color:'#1D4ED8',whiteSpace:'nowrap'}}>{filtered.length} records · {window.fmtDieselQty(totalLitres)} L total</span>
      </div>

      <div className="frow">
        <div className="fs">
          <svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={function(e) { setSearch(e.target.value); setPage(1); }} placeholder="Search challan, vehicle, transporter, source…"/>
        </div>
        <window.FiltSelect placeholder="All Transporters" value={fTrans} onChange={function(v) { setFTrans(v); setPage(1); }} options={tmActive.map(function(t) { return {value:t.id,label:t.name}; })}/>
        <window.FiltSelect placeholder="All Sources" value={fSrc} onChange={function(v) { setFSrc(v); setPage(1); }} options={activeSources.map(function(s) { return {value:s.name,label:s.name}; })}/>
        {(search || fTrans || fSrc) && <button className="btn btn-gh btn-sm" onClick={function() { setSearch(''); setFTrans(''); setFSrc(''); setPage(1); }}>Clear</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>

      <div className="card">
        <div className="tbl-w">
          <table className="tbl">
            <thead><tr>
              <th style={{width:26}}></th>
              {isGroup && <th>OM GROUP COMPANY</th>}
              <th>DATE</th><th>PURCHASE ID</th><th>CHALLAN NO.</th>
              <th>TRANSPORTER</th><th>VEHICLE NO.</th>
              <th>DIESEL SOURCE</th><th>DIESEL QTY</th><th>TYPE</th>
            </tr></thead>
            <tbody>
              {paged.length === 0
                ? <tr className="empty"><td colSpan={9 + (isGroup ? 1 : 0)} style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No purchase-based diesel records found.</td></tr>
                : paged.map(function(p) {
                  var isOpen = expand === p.id;
                  return (
                    <React.Fragment key={p.id}>
                      <tr style={{cursor:'pointer', background: isOpen ? '#EFF6FF' : undefined}} onClick={function() { setExpand(isOpen ? null : p.id); }}>
                        <td style={{textAlign:'center', padding:'5px 4px'}}>
                          <svg width="9" height="9" viewBox="0 0 10 10" fill="none" style={{transform: isOpen ? 'rotate(90deg)' : 'none', transition:'transform .15s', color:'var(--info)', display:'block', margin:'0 auto'}}><path d="M3 1.5L7 5L3 8.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </td>
                        {isGroup && <td><span className="bdg bg-or" style={{fontSize:10, padding:'1px 5px'}}>{Store.name('companies', p.companyId)}</span></td>}
                        <td>{window.fmtDate(p.date)}</td>
                        <td style={{fontFamily:'var(--font)', fontSize:11, color:'var(--txt2)'}}>{p.id ? p.id.slice(0, 8).toUpperCase() : '—'}</td>
                        <td style={{fontFamily:'var(--font)', fontSize:11.5}}>{p.challanNumber || '—'}</td>
                        <td style={{fontWeight:500}}>{p.transporterName || '—'}</td>
                        <td><span style={{fontFamily:'var(--font)', fontSize:11, background:'#F9FAFB', padding:'1px 5px', borderRadius:3}}>{p.vehicleFull || '—'}</span></td>
                        <td style={{fontSize:11.5, color:'var(--txt2)'}}>{p.dieselSource || '—'}</td>
                        <td><strong>{window.fmtDieselQty(p.dieselQty)}</strong> L</td>
                        <td><span className="bdg bg-bl" style={{fontSize:10, padding:'1px 6px'}}>Auto-Generated</span></td>
                      </tr>
                      {isOpen && (
                        <tr key={p.id + '-exp'}>
                          <td colSpan={9 + (isGroup ? 1 : 0)} style={{padding:0, background:'#EFF6FF', borderTop:'2px solid #BFDBFE'}}>
                            <div style={{padding:'14px 16px 18px'}}>
                              <div className="rg-3" style={{gap:12}}>
                                <div style={{background:'#fff', border:'1px solid var(--bdr)', borderRadius:6, padding:'10px 12px'}}>
                                  <div style={{fontWeight:700, fontSize:11, color:'var(--or)', marginBottom:8, paddingBottom:5, borderBottom:'2px solid #FEF3E8', textTransform:'uppercase', letterSpacing:'.5px'}}>Purchase Information</div>
                                  {[['Purchase ID', p.id ? p.id.slice(0, 8).toUpperCase() : '—', true], ['Challan No.', p.challanNumber || '—', true], ['Purchase Date', window.fmtDate(p.date), false], ['Company', Store.name('companies', p.companyId) || '—', false]].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex', justifyContent:'space-between', marginBottom:5, fontSize:12, borderBottom:'1px dashed var(--bdr)', paddingBottom:4}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span>
                                      <span style={{fontWeight: row[2] ? 700 : 500, fontFamily:'var(--font)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                </div>
                                <div style={{background:'#fff', border:'1px solid var(--bdr)', borderRadius:6, padding:'10px 12px'}}>
                                  <div style={{fontWeight:700, fontSize:11, color:'#1D4ED8', marginBottom:8, paddingBottom:5, borderBottom:'2px solid #DBEAFE', textTransform:'uppercase', letterSpacing:'.5px'}}>Transport Information</div>
                                  {[['Transporter', p.transporterName || '—', false], ['Vehicle No.', p.vehicleFull || '—', true]].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex', justifyContent:'space-between', marginBottom:5, fontSize:12, borderBottom:'1px dashed var(--bdr)', paddingBottom:4}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span>
                                      <span style={{fontWeight: row[2] ? 700 : 500, fontFamily:'var(--font)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                </div>
                                <div style={{background:'#fff', border:'1px solid var(--bdr)', borderRadius:6, padding:'10px 12px'}}>
                                  <div style={{fontWeight:700, fontSize:11, color:'#B45309', marginBottom:8, paddingBottom:5, borderBottom:'2px solid #FEF3C7', textTransform:'uppercase', letterSpacing:'.5px'}}>Diesel Information</div>
                                  {[['Diesel Source', p.dieselSource || '—', false], ['Diesel Quantity', window.fmtDieselQty(p.dieselQty) + ' L', false], ['Record Type', 'Purchase-Based (Auto)', false], ['Created By', 'System — Purchase Entry', false]].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex', justifyContent:'space-between', marginBottom:5, fontSize:12, borderBottom:'1px dashed var(--bdr)', paddingBottom:4}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span>
                                      <span style={{fontWeight: row[2] ? 700 : 500}}>{row[1]}</span>
                                    </div>;
                                  })}
                                  <div style={{marginTop:8, padding:'6px 8px', background:'#FFFBEB', border:'1px solid #FEF3C7', borderRadius:4, fontSize:11, color:'#92400E'}}>
                                    To edit, modify the source Purchase Entry.
                                  </div>
                                </div>
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })
              }
            </tbody>
            {paged.length > 0 && (
              <tfoot><tr>
                <td colSpan={7 + (isGroup ? 1 : 0)} style={{fontWeight:700, color:'var(--txt2)', padding:'7px 10px', background:'#EFF6FF', fontSize:11}}>PAGE TOTALS</td>
                <td style={{fontWeight:700, padding:'7px 10px', background:'#EFF6FF', color:'#1D4ED8'}}>{window.fmtDieselQty(paged.reduce(function(s, p) { return s + (parseFloat(p.dieselQty) || 0); }, 0))} L</td>
                <td style={{background:'#EFF6FF'}}></td>
              </tr></tfoot>
            )}
          </table>
        </div>
      </div>

      {totalPgs > 1 && (
        <div className="pag">
          <button className="pg-b" onClick={function() { setPage(1); }} disabled={page === 1}>«</button>
          <button className="pg-b" onClick={function() { setPage(function(p) { return p - 1; }); }} disabled={page === 1}>‹</button>
          <span className="pg-inf">Page {page} of {totalPgs}</span>
          <button className="pg-b" onClick={function() { setPage(function(p) { return p + 1; }); }} disabled={page === totalPgs}>›</button>
          <button className="pg-b" onClick={function() { setPage(totalPgs); }} disabled={page === totalPgs}>»</button>
        </div>
      )}
    </div>
  );
}

// ── Main Diesel Page ──────────────────────────────────────────────────────────
function DieselPage() {
  window.useStoreSync();
  const { companyId, navigate: appNavigate, navParams, clearNavParams } = dsCtx(AppCtx);
  const isGroup = companyId === 'group';

  const [activeTab, setActiveTab] = dsSt('bill');
  const [focusAllocId, setFocusAllocId] = dsSt(null);

  // Deep-link entry point — a Vendor/Transport Settlement "View in Diesel
  // Allocation" link lands here with navParams.focusAllocId set.
  dsEf(function() {
    if (navParams && navParams.focusAllocId) {
      setActiveTab('allocation');
      setFocusAllocId(navParams.focusAllocId);
      clearNavParams && clearNavParams();
    }
  }, [navParams]);
  const [items,  setItems]  = dsSt([]);
  const [search, setSearch] = dsSt('');
  const [fTrans, setFTrans] = dsSt('');
  const [fSrc,   setFSrc]   = dsSt('');
  const [page,   setPage]   = dsSt(1);
  const [periodPreset, setPeriodPreset] = dsSt('all');
  const [customFrom,   setCustomFrom]   = dsSt('');
  const [customTo,     setCustomTo]     = dsSt('');
  const periodRange = dsMemo(function() { return window.getDieselPeriodRange(periodPreset, customFrom, customTo); }, [periodPreset, customFrom, customTo]);
  function setPeriod(id) { setPeriodPreset(id); setPage(1); }
  function setCustomRange(f, t) { setCustomFrom(f); setCustomTo(t); setPage(1); }

  const [modal,     setModal]     = dsSt(false);
  const [editId,    setEditId]    = dsSt(null);
  const [delId,     setDelId]     = dsSt(null);
  const [dsStatement, setDsStatement] = dsSt(null);
  const [expand,    setExpand]    = dsSt(null);
  const [adjustAllocId, setAdjustAllocId] = dsSt(null);
  const [form,      setForm]      = dsSt({});
  const [formDraft, setFormDraft] = dsSt(null);

  const [srcModal, setSrcModal] = dsSt(false);
  const [srcForm,  setSrcForm]  = dsSt({ name:'', contactPerson:'', contactNumber:'', address:'', status:'Active' });

  const [sources,       setSources]       = dsSt(function() { return Store.all('dieselSources') || []; });
  const [marginSettings,setMarginSettings]= dsSt(function() { return Store.all('dieselMarginSettings') || []; });
  const [showMgnCfg,   setShowMgnCfg]    = dsSt(false);
  const [mgnModal,     setMgnModal]      = dsSt(false);
  const [mgnEditId,    setMgnEditId]     = dsSt(null);
  const [mgnForm,      setMgnForm]       = dsSt({});
  const [tmAll,         setTmAll]         = dsSt(function() { return Store.all('transporterMaster','group') || []; });
  const [allVehMaster,  setAllVehMaster]  = dsSt(function() { return Store.all('vehicleMaster','group')  || []; });

  dsEf(function() { load(); }, [companyId]);
  dsEf(function() {
    var unsub = Store.on(function() {
      setSources(Store.all('dieselSources') || []);
      setMarginSettings(Store.all('dieselMarginSettings') || []);
      setTmAll(Store.all('transporterMaster','group') || []);
      setAllVehMaster(Store.all('vehicleMaster','group') || []);
      setItems(Store.all('dieselRecords', companyId));
    });
    return unsub;
  }, [companyId]);

  function load() { setItems(Store.all('dieselRecords', companyId)); }
  function loadSources() { setSources(Store.all('dieselSources') || []); }

  const tmActive   = tmAll.filter(function(t) { return t.status === 'Active' || !t.status; });
  const tmVehicles = dsMemo(function() {
    if (!form.transporterId) return [];
    return allVehMaster.filter(function(v) {
      return v.transporterId === form.transporterId && (v.status === 'Active' || !v.status);
    });
  }, [allVehMaster, form.transporterId]);

  const PER = 50;

  const filtered = dsMemo(function() {
    return items.filter(function(it) {
      if (search) {
        const q = search.toLowerCase();
        const trName = it.transporterName
          || Store.name('transporterMaster', it.transporterId)
          || Store.name('transportersList',  it.transporterId)
          || '';
        if (![it.vehicleFull, it.dieselSource, trName, it.challanNumber||'', it.billNumber||''].some(function(v) {
          return String(v||'').toLowerCase().includes(q);
        })) return false;
      }
      if (fTrans && it.transporterId !== fTrans) return false;
      if (fSrc   && it.dieselSource  !== fSrc)  return false;
      if (!window.dieselInPeriod(it.date||it.periodStart, periodRange.from, periodRange.to)) return false;
      return true;
    });
  }, [items, search, fTrans, fSrc, periodRange]);

  const totalPgs    = Math.ceil(filtered.length / PER);
  const paged       = filtered.slice((page-1)*PER, page*PER);
  const totalLitres = filtered.reduce(function(s,d) { return s + (parseFloat(d.litres)||0); }, 0);
  const totalAmount = filtered.reduce(function(s,d) { return s + (parseFloat(d.amount)||0); }, 0);
  const totalDeduction = filtered.reduce(function(s,d) {
    var ded = parseFloat(d.deductionAmount) || Math.round((parseFloat(d.litres)||0)*(parseFloat(d.deductionRate)||parseFloat(d.ratePerLitre)||0)*1000)/1000 || 0;
    return s + ded;
  }, 0);

  // ── Form helpers ──────────────────────────────────────────────────────────
  function setF(k, v) {
    setForm(function(p) {
      var n = Object.assign({}, p, { [k]: v });

      // Transporter change → clear vehicle, challan, and allocation
      if (k === 'transporterId') {
        var trp = tmAll.find(function(t) { return t.id === v; });
        n.transporterName = trp ? trp.name : '';
        n.vehicleFull     = '';
        n.challanNumber   = '';
        n.challanRef      = '';
        n._challanData    = null;
        // Auto-detect allocation role
        var partyRoles = window.getPartyRoles(v);
        if (partyRoles.isMultiRole) {
          n.dieselAllocRole = n.dieselAllocRole || '';
          if (partyRoles.matchedVendors.length > 0) n.allocVendorId = partyRoles.matchedVendors[0].id;
        } else {
          n.dieselAllocRole = 'Transport';
          n.vendorAllocAmount = ''; n.transportAllocAmount = '';
          n.vendorAllocLitres = ''; n.transportAllocLitres = '';
          n.allocVendorId = '';
        }
      }

      // Vehicle change → clear challan
      if (k === 'vehicleFull') {
        n.challanNumber = '';
        n.challanRef    = '';
        n._challanData  = null;
      }

      // Period change → clear challan so list reloads with new date range
      if (k === 'periodFrom' || k === 'periodTo') {
        n.challanNumber = '';
        n.challanRef    = '';
        n._challanData  = null;
      }

      // Challan selection → auto-fill everything from the purchase record
      if (k === '_challanData' && v) {
        var ch         = v; // full purchase object
        var fi         = (ch.items||[])[0];
        var matName    = fi ? (Store.name('materials', fi.materialId)||'') : '';
        var qty        = (ch.items||[]).reduce(function(s,i){return s+(parseFloat(i.quantity)||0);},0);
        var rate       = fi ? (parseFloat(fi.ratePerTon)||0) : 0;
        var gross      = parseFloat(ch.sub)||parseFloat(ch.subtotal)||0;
        var trp        = tmAll.find(function(t){return t.id===ch.transporterMasterId;});

        n.challanNumber     = ch.challanNumber || '';
        n.challanRef        = ch.id            || '';
        n.challanDate       = ch.date          || '';
        n.challanMaterial   = matName;
        n.challanQty        = qty;
        n.challanRate       = rate;
        n.challanGross      = gross;
        n.challanVendor     = Store.name('vendors', ch.vendorId) || '';
        // Auto-fill vehicle and transporter if not already set
        if (!p.vehicleFull)    n.vehicleFull     = ch.vehicleFull || '';
        if (!p.transporterId)  {
          n.transporterId   = ch.transporterMasterId || '';
          n.transporterName = trp ? trp.name : (ch.transporterName||'');
        }
        // Set bill date to challan date as default (user can override)
        if (!p.date) n.date = ch.date || '';
        // Company
        if (isGroup && !p.companyId) n.companyId = ch.companyId || '';
      }

      // Auto-calculate dual-rate amounts:
      // amount          = litres × billRate     (actual P&L diesel expense)
      // deductionAmount = litres × deductionRate (recovered from transporter in settlement)
      if (k === 'litres' || k === 'ratePerLitre' || k === 'marginPerLitre') {
        var L = parseFloat(k === 'litres'         ? v : n.litres)         || 0;
        var R = parseFloat(k === 'ratePerLitre'   ? v : n.ratePerLitre)   || 0;
        var M = parseFloat(k === 'marginPerLitre' ? v : n.marginPerLitre) || 0;
        n.deductionRate   = Math.round((R + M) * 100) / 100;
        n.amount          = Math.round(L * R * 1000) / 1000;
        n.deductionAmount = Math.round(L * n.deductionRate * 1000) / 1000;
      }
      return n;
    });
  }

  function openAdd() {
    var today = new Date().toISOString().slice(0, 10);
    var activeMgn = window.getActiveDieselMargin(today);
    setForm({
      date: today,
      marginPerLitre: activeMgn,
      periodFrom: '',
      periodTo: '',
      companyId: isGroup ? '' : companyId,
      // Challan fields (new)
      challanNumber: '', challanRef: '', challanDate: '',
      challanMaterial: '', challanQty: 0, challanRate: 0, challanGross: 0,
      challanVendor: '', _challanData: null,
      // Diesel fields
      billNumber: '', remarks: '',
    });
    setEditId(null); setModal(true);
  }

  function openEdit(d) {
    setForm(Object.assign({}, d));
    setEditId(d.id); setModal(true);
  }

  function handleSave(e) {
    e.preventDefault();
    var coErr = window.requireGroupCompany(isGroup, form.companyId);
    if (coErr)             { window.toast&&window.toast(coErr, 'er'); return; }
    if (!form.transporterId){ window.toast&&window.toast('Please select a Transporter', 'er'); return; }
    if (!form.vehicleFull)  { window.toast&&window.toast('Please select a Vehicle', 'er'); return; }
    if (!form.dieselSource) { window.toast&&window.toast('Please select a Diesel Source', 'er'); return; }

    // Challan validation
    if (form.challanNumber) {
      // Verify challan belongs to selected transporter
      var challanPurchase = (Store.all('purchases')||[]).find(function(p){ return p.challanNumber === form.challanNumber; });
      if (challanPurchase) {
        // ── Issue 1 ROOT-CAUSE FIX: Multi-strategy transporter identity comparison ─
        // Previously only checked transporterMasterId + exact name equality, which
        // failed when: (a) old purchases stored transporterId instead of
        // transporterMasterId, (b) name had trailing spaces or casing differences,
        // (c) challan had no transporter info recorded at all.
        // Fix: check all known ID fields + case-insensitive name + containment match.
        // Bypass entirely when challan carries zero transporter info (no ID, no name).
        var trp = tmAll.find(function(t){return t.id===form.transporterId;});
        var masterName = trp ? (trp.name||'').toLowerCase().trim() : '';
        var challanTrName = (challanPurchase.transporterName||'').toLowerCase().trim();
        var hasAnyTrInfo = !!(challanPurchase.transporterMasterId || challanPurchase.transporterId || challanTrName);
        var idMatch = (challanPurchase.transporterMasterId && challanPurchase.transporterMasterId === form.transporterId) ||
                      (challanPurchase.transporterId      && challanPurchase.transporterId      === form.transporterId);
        var nameExact = masterName && challanTrName && challanTrName === masterName;
        var nameContain = masterName.length >= 5 && challanTrName.length >= 5 &&
                          (challanTrName.includes(masterName) || masterName.includes(challanTrName));
        var challanTrMatch = !hasAnyTrInfo || idMatch || nameExact || nameContain;
        if (!challanTrMatch) {
          window.toast&&window.toast('Challan '+form.challanNumber+' belongs to a different transporter. Cannot save.', 'er');
          return;
        }
        // Multiple diesel bills per challan is valid — no blocking duplicate check
      }
    }

    var trp = tmAll.find(function(t) { return t.id === form.transporterId; });
    var dieselData = Object.assign({}, form, {
      date:            form.date || form.periodStart,
      periodStart:     form.date || form.periodStart,
      periodEnd:       form.date || form.periodEnd || form.periodStart,
      transporterName: trp ? trp.name : (form.transporterName || ''),
    });
    // Ensure dual-rate fields are always consistent on save
    var _billR = parseFloat(dieselData.ratePerLitre) || 0;
    var _mgn   = parseFloat(dieselData.marginPerLitre) || 0;
    var _lits  = parseFloat(dieselData.litres) || 0;
    dieselData.deductionRate   = Math.round((_billR + _mgn) * 100) / 100;
    dieselData.amount          = Math.round(_lits * _billR * 1000) / 1000;
    dieselData.deductionAmount = Math.round(_lits * dieselData.deductionRate * 1000) / 1000;
    // Allocation fields — ensure they are saved
    if (dieselData.dieselAllocRole === 'Split') {
      // ── Issue 2 ROOT-CAUSE FIX: round all amounts to 2dp before comparison ──
      // deductionAmount is computed with 3dp (Math.round(L*R*1000)/1000) while user
      // enters allocation amounts to 2dp. Without 2dp normalisation the difference
      // can be e.g. 0.015 which exceeds the old 0.01 threshold → false failure.
      var _dedAmt2dp = Math.round((parseFloat(dieselData.deductionAmount)||0) * 100) / 100;
      var _vaAmt     = Math.round((parseFloat(dieselData.vendorAllocAmount)||0)    * 100) / 100;
      var _taAmt     = Math.round((parseFloat(dieselData.transportAllocAmount)||0) * 100) / 100;
      if (Math.abs(_dedAmt2dp - _vaAmt - _taAmt) > 0.02) {
        window.toast&&window.toast(
          'Vendor ('+window.fmtCur(_vaAmt)+') + Transport ('+window.fmtCur(_taAmt)+
          ') must equal total diesel ('+window.fmtCur(_dedAmt2dp)+')','er');
        return;
      }
      dieselData.deductionAmount      = _dedAmt2dp;
      dieselData.vendorAllocAmount    = _vaAmt;
      dieselData.transportAllocAmount = _taAmt;
      // ── Split Allocation Traceability metadata ──────────────────────────
      // Every split gets a permanent reference ID + creation stamp the first
      // time it is saved as Split. Re-saves (edits that stay Split) keep the
      // original refId/createdOn — only the audit trail (allocHistory) grows.
      if (!editId || !dieselData.splitRefId) {
        dieselData.splitRefId = dieselData.splitRefId || window.genSplitRefId();
        dieselData.splitCreatedOn = dieselData.splitCreatedOn || new Date().toISOString();
        dieselData.splitCreatedBy = dieselData.splitCreatedBy || 'System';
        dieselData.splitAutoGenerated = true;
      }
      if (!dieselData.allocHistory || !dieselData.allocHistory.length) {
        dieselData.allocHistory = [{
          id: Date.now().toString(36)+Math.random().toString(36).slice(2,6),
          timestamp: new Date().toISOString(),
          fromRole: '—', fromVendorAmount: 0, fromTransportAmount: 0,
          toRole: 'Split', toVendorAmount: _vaAmt, toTransportAmount: _taAmt,
          reason: 'Split Allocation Saved',
          changedBy: 'System',
        }];
      }
    } else if (dieselData.dieselAllocRole === 'Vendor') {
      dieselData.vendorAllocAmount = dieselData.deductionAmount;
      dieselData.transportAllocAmount = 0;
    } else {
      // Transport (default) or single-role
      dieselData.dieselAllocRole = dieselData.dieselAllocRole || 'Transport';
      dieselData.vendorAllocAmount = 0;
      dieselData.transportAllocAmount = dieselData.deductionAmount;
    }
    // Remove internal UI-only fields
    delete dieselData._challanData;

    if (editId) {
      Store.update('dieselRecords', editId, dieselData);
      Store.addLog('UPDATE', 'Diesel', 'Updated: ' + form.vehicleFull + (form.challanNumber?' ['+form.challanNumber+']':''));
    } else {
      Store.add('dieselRecords', dieselData);
      Store.addLog('CREATE', 'Diesel', 'Created: ' + form.vehicleFull + (form.challanNumber?' ['+form.challanNumber+']':''));
    }
    setModal(false); load();
    window.toast&&window.toast(editId ? 'Updated' : 'Created', 'ok');
  }

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

  // ── Source modal — no stacking ──────────────────────────────────────────
  function handleAddNewSource() {
    setFormDraft(Object.assign({}, form));
    setModal(false);
    setSrcModal(true);
  }

  function cancelSrcModal() {
    setSrcModal(false);
    if (formDraft !== null) {
      setForm(formDraft);
      setFormDraft(null);
      setModal(true);
    }
  }

  function setSF(k, v) { setSrcForm(function(p) { return Object.assign({}, p, { [k]: v }); }); }

  function handleCreateSource(e) {
    e.preventDefault();
    var name = (srcForm.name || '').trim();
    if (!name) { window.toast&&window.toast('Source name is required', 'er'); return; }
    var dup = sources.some(function(s) { return s.name.toLowerCase() === name.toLowerCase(); });
    if (dup) { window.toast&&window.toast('A source with this name already exists', 'er'); return; }
    Store.add('dieselSources', Object.assign({}, srcForm, { name: name }));
    Store.addLog('CREATE', 'Diesel Source', 'Created: ' + name);
    loadSources();
    setSrcModal(false);
    setSrcForm({ name:'', contactPerson:'', contactNumber:'', address:'', status:'Active' });
    window.toast&&window.toast('"' + name + '" created and selected', 'ok');
    if (formDraft !== null) {
      setForm(Object.assign({}, formDraft, { dieselSource: name }));
      setFormDraft(null);
      setModal(true);
    }
  }

  function exportCSV() {
    // Canonical source-company attribution (erp/company-attribution.js) —
    // resolved per diesel record, never from the active company selector.
    var _q  = function(v){ return '"' + String(v==null?'':v).replace(/"/g,'""') + '"'; };
    var _co = function(r){ return window.ERPCompanyAttribution
      ? window.ERPCompanyAttribution.resolveTransactionCompany(r).companyName
      : (Store.name('companies', r && r.companyId) || 'Unassigned'); };
    var hdr = (isGroup ? 'OM Group Company,' : '') + 'Date,Bill No.,Challan No.,Vehicle,Transporter,Source,Litres,Rate,Amount';
    var rows = filtered.map(function(d) {
      var trName = d.transporterName || Store.name('transporterMaster', d.transporterId) || Store.name('transportersList', d.transporterId) || '';
      return (isGroup ? _q(_co(d)) + ',' : '') + [d.date||d.periodStart||'', d.billNumber||'', d.challanNumber||'', d.vehicleFull||'', trName, d.dieselSource||'', parseFloat(d.litres||0).toFixed(3), d.ratePerLitre||'', d.amount||''].map(_q).join(',');
    }).join('\r\n');
    var blob = new Blob(['\uFEFF'+hdr+'\r\n'+rows], {type:'text/csv;charset=utf-8'});
    var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'diesel.csv'; a.click();
    window.toast&&window.toast('CSV exported', 'ok');
  }

  var calcL            = parseFloat(form.litres)         || 0;
  var calcR            = parseFloat(form.ratePerLitre)   || 0;
  var calcM            = parseFloat(form.marginPerLitre) || 0;
  var calcDeductRate   = Math.round((calcR + calcM) * 100) / 100;
  var calcBillAmt      = Math.round(calcL * calcR * 1000) / 1000;
  var calcDeductAmt    = Math.round(calcL * calcDeductRate * 1000) / 1000;
  var calcMarginEarned = Math.round((calcDeductAmt - calcBillAmt) * 1000) / 1000;

  // ── Challan info panel (read-only, shows after challan selected) ──────────
  var hasChallanInfo = form.challanNumber && form.challanDate;

  return (
    <div>
      <div className="ph">
        <div>
          <h1>Diesel</h1>
          <p>{activeTab === 'bill' ? 'Bill-Based Diesel Entries — linked to challans as the single source of truth' : 'Purchase-Based Diesel Entries — automatically derived from Purchase transactions with diesel quantity'}</p>
        </div>
        <div className="ph-act">
          {activeTab === 'bill' && (
            <>
              <div style={{display:'flex',gap:12,fontSize:12,color:'var(--txt2)',marginRight:6}}>
                <span>Total: <strong style={{color:'var(--txt)'}}>{window.fmtDieselQty(totalLitres)} L</strong></span>
                <span>Fuel Cost: <strong style={{color:'var(--or)'}}>{window.fmtCur(totalAmount)}</strong></span>
              <span>Deduction: <strong style={{color:'#1D4ED8'}}>{window.fmtCur(totalDeduction)}</strong></span>
              </div>
              <button className="btn btn-wh btn-sm" onClick={exportCSV}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> Export CSV</button>
              <button className="btn btn-or" onClick={openAdd}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Add Entry</button>
            </>
          )}
        </div>
      </div>

      {/* ── Diesel Margin Settings (collapsible) ── */}
      <div style={{marginBottom:10}}>
        <button onClick={function(){setShowMgnCfg(function(p){return !p;});}} style={{display:'flex',alignItems:'center',gap:7,background:'none',border:'1px solid var(--bdr)',borderRadius:'var(--r)',padding:'6px 12px',cursor:'pointer',fontFamily:'var(--font)',fontSize:12,fontWeight:600,color:'var(--txt2)',transition:'all .15s'}}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg>
          Diesel Margin Settings
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{transform:showMgnCfg?'rotate(180deg)':'none',transition:'transform .2s'}}><path d="M6 9l6 6 6-6"/></svg>
          {(function(){
            var act=marginSettings.filter(function(s){return s.status==='Active';});
            if(!act.length)return null;
            return <span style={{background:'var(--or-lt)',color:'var(--or)',border:'1px solid var(--or-bdr)',borderRadius:3,fontSize:10,padding:'1px 6px',fontWeight:700}}>₹{parseFloat(act[act.length-1].defaultMargin||0).toFixed(2)}/L active</span>;
          })()}
        </button>
        {showMgnCfg && (
          <div style={{marginTop:6,background:'#fff',border:'1px solid var(--bdr)',borderRadius:'var(--r)',overflow:'hidden',boxShadow:'var(--sh-card)'}}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 14px 8px',borderBottom:'1px solid var(--bdr)',background:'#FAFAFA'}}>
              <div>
                <div style={{fontWeight:700,fontSize:12.5,color:'var(--txt)'}}>Diesel Margin Configuration</div>
                <div style={{fontSize:11,color:'var(--txt2)',marginTop:1}}>Margin added on top of Bill Rate to derive Transporter Deduction Rate.</div>
              </div>
              <button className="btn btn-or btn-sm" onClick={function(){setMgnForm({effectiveFrom:'',effectiveTo:'',defaultMargin:'',status:'Active'});setMgnEditId(null);setMgnModal(true);}}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Add
              </button>
            </div>
            <div className="tbl-w">
              <table className="tbl">
                <thead><tr><th>DEFAULT MARGIN (₹/L)</th><th>EFFECTIVE FROM</th><th>EFFECTIVE TO</th><th>STATUS</th><th>ACTIONS</th></tr></thead>
                <tbody>
                  {marginSettings.length===0
                    ?<tr className="empty"><td colSpan={5} style={{textAlign:'center',padding:20,color:'var(--txt2)'}}>No margin settings. Add one to enable dual-rate diesel tracking.</td></tr>
                    :marginSettings.map(function(ms){
                      var isAct=ms.status==='Active';
                      return(
                        <tr key={ms.id} style={{background:isAct?'#FFFBF5':undefined}}>
                          <td><strong style={{fontSize:13.5,color:isAct?'var(--or)':'var(--txt)'}}>₹{parseFloat(ms.defaultMargin||0).toFixed(2)}/L</strong>{isAct&&<span style={{marginLeft:6,fontSize:9.5,background:'#DCFCE7',color:'#166534',padding:'1px 5px',borderRadius:3,fontWeight:700}}>ACTIVE</span>}</td>
                          <td>{ms.effectiveFrom?window.fmtDate(ms.effectiveFrom):'—'}</td>
                          <td>{ms.effectiveTo?window.fmtDate(ms.effectiveTo):'Ongoing'}</td>
                          <td><span className={'bdg '+(isAct?'bg-ok':'bg-nd')} style={{fontSize:10,padding:'1px 6px'}}>{ms.status}</span></td>
                          <td><div className="ra">
                            <button className="btn btn-wh btn-sm" onClick={function(){setMgnForm(Object.assign({},ms));setMgnEditId(ms.id);setMgnModal(true);}}>Edit</button>
                            <button className="btn btn-rd btn-sm" onClick={function(){Store.del('dieselMarginSettings',ms.id);setMarginSettings(Store.all('dieselMarginSettings')||[]);window.toast&&window.toast('Deleted','ok');}}>Delete</button>
                          </div></td>
                        </tr>
                      );
                    })
                  }
                </tbody>
              </table>
            </div>
            <div style={{padding:'7px 14px',background:'#F9FAFB',borderTop:'1px solid var(--bdr)',fontSize:11,color:'var(--txt2)'}}>
              Deduction Rate = Bill Rate + Margin. Dashboard always uses Bill Rate for P&amp;L. Settlement uses Deduction Rate.
            </div>
          </div>
        )}
      </div>

      {/* ── Tabs ── */}
      <div style={{display:'flex',gap:2,marginBottom:12,borderBottom:'2px solid var(--bdr)'}}>
        {[['bill','Bill-Based Diesel Entries'],['purchase','Purchase-Based Diesel Entries'],['allocation','Allocation Report']].map(function(pair) {
          var id = pair[0]; var lbl = pair[1];
          return <button key={id} onClick={function(){setActiveTab(id);}} style={{padding:'7px 18px',border:'none',background:'none',fontFamily:'var(--font)',fontSize:12.5,fontWeight:600,cursor:'pointer',color:activeTab===id?'var(--or)':'var(--txt2)',borderBottom:activeTab===id?'2px solid var(--or)':'2px solid transparent',marginBottom:'-2px',transition:'color .1s'}}>{lbl}</button>;
        })}
      </div>

      {activeTab === 'purchase' && <PurchaseBasedDieselTab companyId={companyId} isGroup={isGroup} tmAll={tmAll} sources={sources} periodFrom={periodRange.from} periodTo={periodRange.to}/>}

      {activeTab === 'allocation' && <window.DieselAllocationReport companyId={companyId} isGroup={isGroup} focusRecordId={focusAllocId} navigate={appNavigate} periodFrom={periodRange.from} periodTo={periodRange.to}/>}

      {activeTab === 'bill' && <React.Fragment>

      {/* ── Filter row ── */}
      <div className="frow">
        <div className="fs">
          <svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={function(e){setSearch(e.target.value);setPage(1);}} placeholder="Search challan, bill no., vehicle, transporter, source…"/>
        </div>
        <window.FiltSelect placeholder="All Transporters" value={fTrans} onChange={function(v){setFTrans(v);setPage(1);}} options={tmActive.map(function(t){return {value:t.id,label:t.name};})}/>
        <window.FiltSelect placeholder="All Sources" value={fSrc} onChange={function(v){setFSrc(v);setPage(1);}} options={sources.filter(function(s){return s.status!=='Inactive';}).map(function(s){return {value:s.name,label:s.name};})}/>
        <DieselPeriodDropdown preset={periodPreset} onChange={setPeriod} customFrom={customFrom} customTo={customTo} onCustomChange={setCustomRange}/>
        {(search||fTrans||fSrc||periodPreset!=='all')&&<button className="btn btn-gh btn-sm" onClick={function(){setSearch('');setFTrans('');setFSrc('');setPeriodPreset('all');setCustomFrom('');setCustomTo('');setPage(1);}}>Clear</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>

      {/* ── Table ── */}
      <div className="card">
        <div className="tbl-w">
          <table className="tbl">
            <thead><tr>
              <th style={{width:26}}></th>
              {isGroup&&<th>OM GROUP COMPANY</th>}
              <th>DATE</th><th>BILL NO.</th><th>CHALLAN NO.</th><th>VEHICLE NO.</th>
              <th>TRANSPORTER</th><th>DIESEL SOURCE</th>
              <th>LITRES</th><th>BILL RATE</th><th>ACTUAL FUEL COST</th><th>TRANSPORTER<br/>DEDUCTION</th><th>ALLOCATION</th><th>ACTIONS</th>
            </tr></thead>
            <tbody>
              {paged.length===0
                ?<tr className="empty"><td colSpan={12+(isGroup?1:0)} style={{textAlign:'center',padding:40,color:'var(--txt2)'}}>No diesel records found</td></tr>
                :paged.map(function(d){
                  var trName = d.transporterName || Store.name('transporterMaster',d.transporterId) || Store.name('transportersList',d.transporterId) || '—';
                  var isOpen = expand === d.id;
                  var linkedSettlements = (Store.all('settlementRecords')||[]).filter(function(s) {
                    var trMatch = s.transporterId === d.transporterId ||
                      (d.transporterName && (s.transporterName||'').toLowerCase().trim() === (d.transporterName||'').toLowerCase().trim());
                    if (!trMatch) return false;
                    var dDate = d.date || d.periodStart || '';
                    return s.periodFrom <= dDate && s.periodTo >= dDate;
                  });
                  return (
                    <React.Fragment key={d.id}>
                      <tr style={{background: isOpen ? '#FFF9F5' : undefined, cursor:'pointer'}} onClick={function(){setExpand(isOpen ? null : d.id);}}>
                        <td style={{textAlign:'center',padding:'5px 4px'}}>
                          <svg width="9" height="9" viewBox="0 0 10 10" fill="none" style={{transform:isOpen?'rotate(90deg)':'none',transition:'transform .15s',color:'var(--or)',display:'block',margin:'0 auto'}}><path d="M3 1.5L7 5L3 8.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </td>
                        {isGroup&&<td><span className="bdg bg-or" style={{fontSize:10,padding:'1px 5px'}}>{Store.name('companies',d.companyId)}</span></td>}
                        <td>{window.fmtDate(d.date||d.periodStart)}</td>
                        <td style={{fontFamily:'var(--font)',fontSize:11,color:'var(--txt2)'}}>{d.billNumber||'—'}</td>
                        <td>
                          {d.challanNumber
                            ? <span style={{fontFamily:'var(--font)',fontSize:11.5,fontWeight:600,color:'var(--or)'}}>{d.challanNumber}</span>
                            : <span style={{fontSize:11,color:'var(--txt3)',fontStyle:'italic'}}>No challan</span>
                          }
                        </td>
                        <td><span style={{fontFamily:'var(--font)',fontSize:11,background:'#F9FAFB',padding:'1px 5px',borderRadius:3}}>{d.vehicleFull||'—'}</span></td>
                        <td>{trName}</td>
                        <td style={{fontSize:11.5,color:'var(--txt2)'}}>{d.dieselSource||'—'}</td>
                        <td><strong>{window.fmtDieselQty(d.litres)}</strong> L</td>
                        <td>
                          <span>₹{d.ratePerLitre}/L</span>
                          {(parseFloat(d.marginPerLitre)||0)>0 && <span style={{display:'block',fontSize:9.5,color:'var(--ok)',fontWeight:600}}>+₹{parseFloat(d.marginPerLitre).toFixed(2)} margin</span>}
                        </td>
                        <td style={{fontWeight:600,color:'var(--or)'}}>{window.fmtCur(d.amount)}</td>
                        <td style={{fontWeight:600,color:'#1D4ED8'}}>{window.fmtCur(parseFloat(d.deductionAmount)||Math.round((parseFloat(d.litres)||0)*(parseFloat(d.deductionRate)||parseFloat(d.ratePerLitre)||0)*1000)/1000)}</td>
                        <td><window.AllocBadge record={d}/></td>
                        <td onClick={function(e){e.stopPropagation();}}><div className="ra">
                          <button className="btn btn-wh btn-sm" onClick={function(){openEdit(d);}}>Edit</button>
                          {window.getPartyRoles(d.transporterId).isMultiRole && <button className="btn btn-gh btn-sm" onClick={function(){setAdjustAllocId(d.id);}}>Adjust</button>}
                          <button className="btn btn-wh btn-sm" onClick={function(){setDsStatement(d);}}>Statement</button>
                          <button className="btn btn-rd btn-sm" onClick={function(){setDelId(d.id);}}>Delete</button>
                        </div></td>
                      </tr>
                      {isOpen && (
                        <tr key={d.id+'-exp'}>
                          <td colSpan={12+(isGroup?1:0)} style={{padding:0,borderTop:'2px solid var(--or-bdr)'}}>
                            <div style={{padding:'14px 16px 18px',background:'#FFF9F5'}}>
                              <div className="rg-4" style={{gap:10,marginBottom:12}}>
                                <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
                                  <div style={{fontWeight:700,fontSize:10.5,color:'var(--or)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #FEF3E8',textTransform:'uppercase',letterSpacing:'.5px'}}>Challan Reference</div>
                                  {[['Challan No.', d.challanNumber||'—'], ['Challan Date', d.challanDate?window.fmtDate(d.challanDate):'—'], ['Material', d.challanMaterial||'—'], ['Quantity', d.challanQty?(window.formatQuantity(parseFloat(d.challanQty))+' MT'):'—'], ['Gross Freight', d.challanGross?window.fmtCur(d.challanGross):'—']].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:11.5}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span><span style={{fontWeight:500,fontFamily:'var(--font)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                </div>
                                <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
                                  <div style={{fontWeight:700,fontSize:10.5,color:'#1D4ED8',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #DBEAFE',textTransform:'uppercase',letterSpacing:'.5px'}}>Vehicle</div>
                                  {[['Vehicle No.', d.vehicleFull||'—'], ['Transporter', trName]].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:11.5}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span><span style={{fontWeight:500,fontFamily:'var(--font)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                </div>
                                <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
                                  <div style={{fontWeight:700,fontSize:10.5,color:'#B45309',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #FEF3C7',textTransform:'uppercase',letterSpacing:'.5px'}}>Diesel Bill</div>
                                  {[['Bill No.', d.billNumber||'—'], ['Bill Date', window.fmtDate(d.date||d.periodStart)], ['Source', d.dieselSource||'—'], ['Quantity', window.fmtDieselQty(d.litres)+' L'], ['Bill Rate', '₹'+(d.ratePerLitre||0)+'/L'], ['Margin', (parseFloat(d.marginPerLitre)||0)>0?'₹'+parseFloat(d.marginPerLitre).toFixed(2)+'/L':'—'], ['Deduction Rate', '₹'+(d.deductionRate||d.ratePerLitre||0)+'/L'], ['Actual Cost', window.fmtCur(d.amount)], ['Transporter Deduction', window.fmtCur(parseFloat(d.deductionAmount)||parseFloat(d.amount)||0)]].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:11.5}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span><span style={{fontWeight:row[0]==='Actual Cost'||row[0]==='Transporter Deduction'?700:500,color:row[0]==='Actual Cost'?'var(--or)':row[0]==='Transporter Deduction'?'#1D4ED8':'var(--txt)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                  {d.remarks&&<div style={{marginTop:6,fontSize:11,color:'var(--txt2)',fontStyle:'italic'}}>{d.remarks}</div>}
                                </div>
                                <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
                                  <div style={{fontWeight:700,fontSize:10.5,color:'var(--txt2)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.5px'}}>Company &amp; Audit</div>
                                  {[['Company', Store.name('companies',d.companyId)||'—'], ['Type', 'Bill-Based (Manual)'], ['Record ID', d.id ? d.id.slice(0,8).toUpperCase() : '—']].map(function(row) {
                                    return <div key={row[0]} style={{display:'flex',justifyContent:'space-between',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:11.5}}>
                                      <span style={{color:'var(--txt2)'}}>{row[0]}</span><span style={{fontWeight:500,fontFamily:'var(--font)'}}>{row[1]}</span>
                                    </div>;
                                  })}
                                </div>
                              </div>
                              {linkedSettlements.length > 0 && (
                                <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px'}}>
                                  <div style={{fontWeight:700,fontSize:10.5,color:'#6D28D9',marginBottom:8,paddingBottom:5,borderBottom:'2px solid #EDE9FE',textTransform:'uppercase',letterSpacing:'.5px'}}>Settlement Reference</div>
                                  <div style={{overflowX:'auto'}}><table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5}}>
                                    <thead><tr style={{background:'#F9FAFB'}}>{['Settlement ID','Period','Status','Net Payable'].map(function(h){return <th key={h} style={{padding:'5px 8px',textAlign:'left',fontWeight:700,fontSize:10.5,color:'var(--txt2)',borderBottom:'1px solid var(--bdr)'}}>{h}</th>;})}</tr></thead>
                                    <tbody>{linkedSettlements.map(function(s){ return <tr key={s.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                                      <td style={{padding:'4px 8px',fontFamily:'var(--font)',fontSize:11}}>{s.id.slice(0,8).toUpperCase()}</td>
                                      <td style={{padding:'4px 8px'}}>{window.fmtDate(s.periodFrom)} – {window.fmtDate(s.periodTo)}</td>
                                      <td style={{padding:'4px 8px'}}><span className="bdg" style={{fontSize:10,padding:'1px 6px',borderRadius:3,background:s.status==='Paid'?'#DBEAFE':s.status==='Approved'?'#DCFCE7':'#F3F4F6',color:s.status==='Paid'?'#1E40AF':s.status==='Approved'?'#166534':'#374151'}}>{s.status}</span></td>
                                      <td style={{padding:'4px 8px',fontWeight:600,color:'var(--or)'}}>{window.fmtCur(s.netPayable||0)}</td>
                                    </tr>; })}
                                    </tbody>
                                  </table></div>
                                </div>
                              )}
                              <window.AllocationTraceabilityPanel record={d} navigate={appNavigate}/>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })
              }
            </tbody>
            {paged.length>0&&(
              <tfoot><tr>
                <td colSpan={7+(isGroup?1:0)} style={{fontWeight:700,color:'var(--txt2)',padding:'7px 10px',background:'#F9FAFB',fontSize:11}}>PAGE TOTALS</td>
                <td style={{fontWeight:700,padding:'7px 10px',background:'#F9FAFB'}}>{window.fmtDieselQty(paged.reduce(function(s,d){return s+(parseFloat(d.litres)||0);},0))} L</td>
                <td style={{background:'#F9FAFB'}}></td>
                <td style={{fontWeight:700,color:'var(--or)',padding:'7px 10px',background:'#F9FAFB'}}>{window.fmtCur(paged.reduce(function(s,d){return s+(parseFloat(d.amount)||0);},0))}</td>
                <td style={{fontWeight:700,color:'#1D4ED8',padding:'7px 10px',background:'#F9FAFB'}}>{window.fmtCur(paged.reduce(function(s,d){var ded=parseFloat(d.deductionAmount)||Math.round((parseFloat(d.litres)||0)*(parseFloat(d.deductionRate)||parseFloat(d.ratePerLitre)||0)*1000)/1000||0;return s+ded;},0))}</td>
                <td style={{background:'#F9FAFB'}}></td>
                <td style={{background:'#F9FAFB'}}></td>
              </tr></tfoot>
            )}
          </table>
        </div>
      </div>

      {totalPgs>1&&(
        <div className="pag">
          <button className="pg-b" onClick={function(){setPage(1);}} disabled={page===1}>«</button>
          <button className="pg-b" onClick={function(){setPage(function(p){return p-1;});}} disabled={page===1}>‹</button>
          <span className="pg-inf">Page {page} of {totalPgs}</span>
          <button className="pg-b" onClick={function(){setPage(function(p){return p+1;});}} disabled={page===totalPgs}>›</button>
          <button className="pg-b" onClick={function(){setPage(totalPgs);}} disabled={page===totalPgs}>»</button>
        </div>
      )}

      </React.Fragment>}

      {/* ── Bill-Based Diesel Entry Modal ────────────────────────────────────── */}
      {modal&&(
        <div className="mbg">
          <div className="mod mod-lg">
            <div className="mod-hd">
              <h2>{editId?'Edit':'Add'} Diesel Entry</h2>
              <button className="mod-x" onClick={function(){setModal(false);}}>×</button>
            </div>
            <form onSubmit={handleSave} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
              <div className="mod-bd">

                {isGroup&&<window.GroupCompanyField value={form.companyId} onChange={function(v){setF('companyId',v);}}/>}

                {/* ── STEP 1: Vehicle Details ─────────────────────────────── */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>Vehicle Details</div>
                <div className="fg" style={{marginBottom:16}}>
                  <div className="fld">
                    <label>Transporter <span className="req">*</span></label>
                    <window.FormSelect placeholder="Select Transporter" value={form.transporterId||''} onChange={function(v){setF('transporterId',v);}} options={tmActive.map(function(t){return {value:t.id,label:t.name};})}/>
                    {tmActive.length===0&&<span style={{fontSize:11,color:'#B45309',marginTop:3,display:'block'}}>No active transporters — add them in Transporter Master first</span>}
                  </div>
                  <div className="fld">
                    <label>Vehicle Number <span className="req">*</span></label>
                    <window.FormSelect placeholder={!form.transporterId ? 'Select transporter first' : tmVehicles.length===0 ? 'No active vehicles for this transporter' : 'Select Vehicle'} value={form.vehicleFull||''} onChange={function(v){setF('vehicleFull',v);}} disabled={!form.transporterId} style={{fontFamily:'var(--font)',fontWeight:600,letterSpacing:'0.3px'}} options={tmVehicles.map(function(v){return {value:v.vehicleNumber,label:v.vehicleNumber+(v.vehicleType?' ('+v.vehicleType+')':'')};})}/>
                    {form.transporterId&&tmVehicles.length===0&&<span style={{fontSize:11,color:'#B45309',marginTop:3,display:'block'}}>No active vehicles — add vehicles in Transporter Master</span>}
                  </div>
                </div>

                {/* ── STEP 2: Challan Reference ────────────────────────────── */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8',display:'flex',alignItems:'center',gap:8}}>
                  Challan Reference
                  <span style={{fontSize:10,fontWeight:600,color:'var(--txt3)',background:'#F3F4F6',padding:'2px 7px',borderRadius:20}}>SINGLE SOURCE OF TRUTH</span>
                </div>
                {/* ── Date Range Filter — narrows challan list before searching ── */}
                <div style={{background:'#F0F7FF',border:'1px solid #BFDBFE',borderRadius:8,padding:'10px 12px',marginBottom:10}}>
                  <div style={{fontSize:10.5,fontWeight:700,color:'#1D4ED8',marginBottom:8,textTransform:'uppercase',letterSpacing:'.04em',display:'flex',alignItems:'center',gap:5}}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                    Date Range Filter
                    <span style={{fontSize:9.5,fontWeight:500,color:'#3B82F6',marginLeft:2}}>— loads only challans in this period</span>
                  </div>
                  <div className="fg" style={{marginBottom:0}}>
                    <div className="fld">
                      <label>Period From</label>
                      <input className="inp" type="date" value={form.periodFrom||''} onChange={function(e){setF('periodFrom',e.target.value);}}/>
                    </div>
                    <div className="fld">
                      <label>Period To</label>
                      <input className="inp" type="date" value={form.periodTo||''} onChange={function(e){setF('periodTo',e.target.value);}}/>
                    </div>
                  </div>
                </div>
                <div className="fld" style={{marginBottom: hasChallanInfo ? 10 : 16}}>
                  <label>Challan Number <span style={{fontSize:11,color:'var(--txt3)',fontWeight:400}}>(select to auto-fill all fields)</span></label>
                  <ChallanSearchDropdown
                    companyId={form.companyId||companyId}
                    isGroup={isGroup}
                    transporterId={form.transporterId||''}
                    vehicleFull={form.vehicleFull||''}
                    periodFrom={form.periodFrom||''}
                    periodTo={form.periodTo||''}
                    value={form.challanNumber||''}
                    onChange={function(ch){ setF('_challanData', ch); }}
                    disabled={!form.transporterId||!form.vehicleFull}
                  />
                  {!form.challanNumber && form.transporterId && form.vehicleFull && (
                    <span style={{fontSize:11,color:'var(--txt3)',marginTop:3,display:'block'}}>Optional but strongly recommended — links this diesel bill to the trip challan</span>
                  )}
                </div>

                {/* ── Auto-filled Challan Info Panel ────────────────────────── */}
                {hasChallanInfo && (
                  <div style={{background:'#F0F7FF',border:'1px solid #BFDBFE',borderRadius:8,padding:'12px 14px',marginBottom:16}}>
                    <div style={{fontSize:11,fontWeight:700,color:'#1D4ED8',marginBottom:8,textTransform:'uppercase',letterSpacing:'.5px',display:'flex',alignItems:'center',gap:6}}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
                      Auto-Filled from Challan — Read Only
                    </div>
                    <div className="rg-3" style={{gap:8}}>
                      {[
                        ['Challan No.', form.challanNumber],
                        ['Challan Date', window.fmtDate(form.challanDate)],
                        ['Material', form.challanMaterial||'—'],
                        ['Quantity', form.challanQty?(window.formatQuantity(parseFloat(form.challanQty))+' MT'):'—'],
                        ['Freight Rate', form.challanRate?window.fmtCur(form.challanRate)+'/MT':'—'],
                        ['Gross Freight', form.challanGross?window.fmtCur(form.challanGross):'—'],
                      ].map(function(row) {
                        return (
                          <div key={row[0]} style={{background:'#fff',border:'1px solid #DBEAFE',borderRadius:5,padding:'6px 10px'}}>
                            <div style={{fontSize:9.5,color:'#1D4ED8',fontWeight:700,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:2}}>{row[0]}</div>
                            <div style={{fontSize:12.5,fontWeight:600,color:'var(--txt)',fontFamily:'var(--font)'}}>{row[1]||'—'}</div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* ── STEP 3: Diesel Bill Details ───────────────────────────── */}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>Diesel Bill Details</div>

                <div className="fg" style={{marginBottom:12}}>
                  <div className="fld">
                    <label>Bill Number</label>
                    <input className="inp" value={form.billNumber||''} onChange={function(e){setF('billNumber',e.target.value);}} placeholder="e.g. PP-1024"/>
                  </div>
                  <div className="fld">
                    <label>Bill Date <span className="req">*</span></label>
                    <input className="inp" type="date" value={form.date||''} onChange={function(e){setF('date',e.target.value);}} required/>
                  </div>
                </div>

                <div className="fld" style={{marginBottom:12}}>
                  <label>Diesel Source <span className="req">*</span></label>
                  <DieselSourceDropdown value={form.dieselSource||''} onChange={function(v){setF('dieselSource',v);}} onAddNew={handleAddNewSource} sources={sources}/>
                </div>
                <div className="fg" style={{marginBottom:12}}>
                  <div className="fld">
                    <label>Diesel in Litres <span className="req">*</span></label>
                    <input className="inp" type="number" value={form.litres||''} onChange={function(e){setF('litres',e.target.value);}} placeholder="0" min="0" step="0.001" required/>
                  </div>
                  <div className="fld">
                    <label>Actual Bill Rate (₹/L) <span className="req">*</span></label>
                    <input className="inp" type="number" value={form.ratePerLitre||''} onChange={function(e){setF('ratePerLitre',e.target.value);}} placeholder="0.00" min="0" step="0.01" required/>
                    <span style={{fontSize:10.5,color:'var(--txt3)',marginTop:2,display:'block'}}>Rate on petrol pump invoice</span>
                  </div>
                </div>
                <div className="fg" style={{marginBottom:12}}>
                  <div className="fld">
                    <label>Diesel Margin (₹/L)</label>
                    <input className="inp" type="number" value={form.marginPerLitre||''} onChange={function(e){setF('marginPerLitre',e.target.value);}} placeholder="0.00" min="0" step="0.01"/>
                    <span style={{fontSize:10.5,color:'var(--txt3)',marginTop:2,display:'block'}}>Auto-filled from Margin Settings</span>
                  </div>
                  <div className="fld">
                    <label>Deduction Rate (₹/L)</label>
                    <div style={{border:'1.5px solid var(--bdr)',borderRadius:9,padding:'7px 12px',height:38,background:'#F9FAFB',fontSize:13,fontWeight:700,color:'var(--txt)',display:'flex',alignItems:'center',gap:6}}>
                      ₹{calcDeductRate.toFixed(2)}/L
                      {calcM > 0 && <span style={{fontSize:10,background:'#DCFCE7',color:'#166534',padding:'1px 5px',borderRadius:3,fontWeight:600}}>+₹{calcM.toFixed(2)} margin</span>}
                    </div>
                    <span style={{fontSize:10.5,color:'var(--txt3)',marginTop:2,display:'block'}}>Used in Transporter Settlement</span>
                  </div>
                </div>
                <div className="fld" style={{marginBottom:16}}>
                  <label>Remarks</label>
                  <input className="inp" value={form.remarks||''} onChange={function(e){setF('remarks',e.target.value);}} placeholder="Optional notes…"/>
                </div>

                {/* ── Diesel Allocation Section (multi-role parties) ── */}
                {form.transporterId && <window.DieselAllocationSection
                  transporterId={form.transporterId}
                  totalAmount={calcDeductAmt}
                  totalLitres={calcL}
                  form={form}
                  setF={setF}
                />}

                {/* ── Calculated amount panel ── */}
                <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'14px 16px'}}>
                  <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:12,flexWrap:'wrap'}}>
                    <div>
                      <div style={{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em',marginBottom:3}}>Actual Diesel Cost (P&amp;L)</div>
                      <div className="kpi-val" style={{fontSize:22,fontWeight:700,color:'var(--or)'}}>{window.fmtCur(calcBillAmt)}</div>
                      <div style={{fontSize:11,color:'var(--txt2)',marginTop:2}}>{calcL.toFixed(3)} L × ₹{calcR.toFixed(2)}/L</div>
                    </div>
                    {calcM > 0 && (
                      <div>
                        <div style={{fontSize:10,fontWeight:700,color:'var(--txt3)',textTransform:'uppercase',letterSpacing:'.05em',marginBottom:3}}>Transporter Deduction</div>
                        <div className="kpi-val" style={{fontSize:22,fontWeight:700,color:'#1D4ED8'}}>{window.fmtCur(calcDeductAmt)}</div>
                        <div style={{fontSize:11,color:'var(--txt2)',marginTop:2}}>{calcL.toFixed(3)} L × ₹{calcDeductRate.toFixed(2)}/L</div>
                      </div>
                    )}
                    {calcM > 0 && (
                      <div>
                        <div style={{fontSize:10,fontWeight:700,color:'#166534',textTransform:'uppercase',letterSpacing:'.05em',marginBottom:3}}>Margin Earned</div>
                        <div className="kpi-val" style={{fontSize:22,fontWeight:700,color:'var(--ok)'}}>{window.fmtCur(calcMarginEarned)}</div>
                        <div style={{fontSize:11,color:'var(--txt2)',marginTop:2}}>{calcL.toFixed(3)} L × ₹{calcM.toFixed(2)}/L</div>
                      </div>
                    )}
                    {hasChallanInfo && form.challanGross > 0 && (
                      <div style={{textAlign:'right',background:'#DCFCE7',border:'1px solid #BBF7D0',borderRadius:6,padding:'8px 12px'}}>
                        <div style={{fontSize:10,color:'#166534',fontWeight:700,marginBottom:2}}>GROSS FREIGHT</div>
                        <div className="kpi-val" style={{fontSize:16,fontWeight:700,color:'#15803D'}}>{window.fmtCur(form.challanGross)}</div>
                        <div style={{fontSize:10,color:'#166534',marginTop:2}}>Net: {window.fmtCur(Math.max(0,(form.challanGross||0)-(calcBillAmt||0)))}</div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
              <div className="mod-ft">
                <button type="button" className="btn btn-wh" onClick={function(){setModal(false);}}>Cancel</button>
                <button type="submit" className="btn btn-or">{editId?'Update':'Create Entry'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Create Diesel Source Modal ── */}
      {srcModal&&(
        <div className="mbg">
          <div className="mod mod-sm">
            <div className="mod-hd">
              <h2>Create Diesel Source</h2>
              <button className="mod-x" onClick={cancelSrcModal}>×</button>
            </div>
            <form onSubmit={handleCreateSource} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
              <div className="mod-bd">
                {formDraft!==null&&(
                  <div style={{background:'#FFF7ED',border:'1px solid var(--or-bdr)',borderRadius:4,padding:'7px 10px',marginBottom:12,fontSize:11.5,color:'var(--or)',display:'flex',alignItems:'center',gap:6}}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                    Diesel entry saved as draft — will be restored after source creation.
                  </div>
                )}
                <div style={{color:'var(--or)',fontWeight:700,fontSize:13,marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>Source Details</div>
                <div className="fld" style={{marginBottom:12}}>
                  <label>Diesel Source Name <span className="req">*</span></label>
                  <input className="inp" value={srcForm.name} onChange={function(e){setSF('name',e.target.value);}} placeholder="e.g. Pooja Petroleum" autoFocus required/>
                </div>
                <div className="fg" style={{marginBottom:12}}>
                  <div className="fld"><label>Contact Person</label><input className="inp" value={srcForm.contactPerson} onChange={function(e){setSF('contactPerson',e.target.value);}} placeholder="Optional"/></div>
                  <div className="fld"><label>Contact Number</label><input className="inp" value={srcForm.contactNumber} onChange={function(e){setSF('contactNumber',e.target.value);}} placeholder="Optional"/></div>
                </div>
                <div className="fld" style={{marginBottom:12}}>
                  <label>Address</label>
                  <input className="inp" value={srcForm.address} onChange={function(e){setSF('address',e.target.value);}} placeholder="Optional"/>
                </div>
                <div className="fld">
                  <label>Status</label>
                  <window.FormSelect value={srcForm.status} onChange={function(v){setSF('status',v);}} options={[{value:'Active',label:'Active'},{value:'Inactive',label:'Inactive'}]}/>
                </div>
              </div>
              <div className="mod-ft">
                <button type="button" className="btn btn-wh" onClick={cancelSrcModal}>Cancel &amp; Return</button>
                <button type="submit" className="btn btn-or">Create &amp; Return to Entry</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Diesel Margin Settings Modal ── */}
      {mgnModal&&(
        <div className="mbg">
          <div className="mod mod-sm">
            <div className="mod-hd">
              <h2>{mgnEditId?'Edit':'Add'} Diesel Margin Setting</h2>
              <button className="mod-x" onClick={function(){setMgnModal(false);}}>×</button>
            </div>
            <form onSubmit={function(e){
              e.preventDefault();
              var mgn=parseFloat(mgnForm.defaultMargin);
              if(isNaN(mgn)||mgn<0){window.toast&&window.toast('Enter a valid margin (≥0)','er');return;}
              var rec={defaultMargin:mgn,effectiveFrom:mgnForm.effectiveFrom||'',effectiveTo:mgnForm.effectiveTo||'',status:mgnForm.status||'Active'};
              if(mgnEditId){Store.update('dieselMarginSettings',mgnEditId,Object.assign({},mgnForm,rec));Store.addLog('UPDATE','DieselMargin','Updated ₹'+mgn+'/L');}
              else{Store.add('dieselMarginSettings',rec);Store.addLog('CREATE','DieselMargin','Created ₹'+mgn+'/L');}
              setMarginSettings(Store.all('dieselMarginSettings')||[]);
              setMgnModal(false);
              window.toast&&window.toast(mgnEditId?'Updated':'Created','ok');
            }} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
              <div className="mod-bd">
                <div style={{background:'#FFF7ED',border:'1px solid var(--or-bdr)',borderRadius:6,padding:'9px 12px',marginBottom:14,fontSize:11.5,color:'#92400E'}}>
                  <strong>Deduction Rate = Bill Rate + Margin.</strong> Set margin to ₹0.00 to make deduction rate equal to bill rate.
                </div>
                <div className="fg" style={{marginBottom:12}}>
                  <div className="fld">
                    <label>Default Margin (₹/L) <span className="req">*</span></label>
                    <input className="inp" type="number" value={mgnForm.defaultMargin||''} onChange={function(e){setMgnForm(function(p){return Object.assign({},p,{defaultMargin:e.target.value});});}} placeholder="e.g. 0.50" min="0" step="0.01" required autoFocus/>
                  </div>
                  <div className="fld">
                    <label>Status</label>
                    <window.FormSelect value={mgnForm.status||'Active'} onChange={function(v){setMgnForm(function(p){return Object.assign({},p,{status:v});}); }} options={[{value:'Active',label:'Active'},{value:'Inactive',label:'Inactive'}]}/>
                  </div>
                </div>
                <div className="fg" style={{marginBottom:4}}>
                  <div className="fld">
                    <label>Effective From</label>
                    <input className="inp" type="date" value={mgnForm.effectiveFrom||''} onChange={function(e){setMgnForm(function(p){return Object.assign({},p,{effectiveFrom:e.target.value});});}}/>
                  </div>
                  <div className="fld">
                    <label>Effective To <span style={{fontSize:11,color:'var(--txt3)',fontWeight:400}}>(optional)</span></label>
                    <input className="inp" type="date" value={mgnForm.effectiveTo||''} onChange={function(e){setMgnForm(function(p){return Object.assign({},p,{effectiveTo:e.target.value});});}}/>
                  </div>
                </div>
              </div>
              <div className="mod-ft">
                <button type="button" className="btn btn-wh" onClick={function(){setMgnModal(false);}}>Cancel</button>
                <button type="submit" className="btn btn-or">{mgnEditId?'Update':'Create Setting'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {delId&&<window.Confirm onOk={handleDelete} onCancel={function(){setDelId(null);}}/>}
      {dsStatement&&<window.DieselStatement record={dsStatement} onClose={function(){setDsStatement(null);}} session={null}/>}

      {/* ── Adjust Allocation Modal ── */}
      {adjustAllocId && (function() {
        var rec = items.find(function(d){return d.id===adjustAllocId;});
        if (!rec) return null;
        return <window.AdjustAllocationModal record={rec} onClose={function(){setAdjustAllocId(null);}} onSaved={function(){load();}} />;
      })()}
    </div>
  );
}

window.DieselPage = DieselPage;
