// Debris Movement — Fully commercial, dynamic integration with Material Master, Customer Master & Price Orders
// Materials: reads live from Material Master (category = 'Debris') — zero hardcoding
// Customers: reads live from Customer Master — zero hardcoding
// Pricing: auto-fetched from Price Orders via RateEngine — no manual entry allowed
// Reports: revenue analytics automatically derived from transaction data

const { useState: dbSt, useContext: dbCtx, useMemo: dbMemo } = React;

const DEST_TYPES     = ['Landfill','Site Filling','Customer Site','Disposal Yard','Stockyard','Internal Land Development','Other'];
const DISPOSAL_TYPES = ['Land Filling','Dumping','Recycling','Internal Development','Customer Use','Other'];
const DB_UOMS        = ['Ton','Cubic Meter','Kilogram'];

// ── Currency formatter ────────────────────────────────────────────────────
function dbFmtCur(v) {
  if (v === null || v === undefined || v === '' || isNaN(Number(v))) return '—';
  return '\u20B9\u00A0' + Number(v).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// ── Section heading inside modal ──────────────────────────────────────────
function DbSec({ label }) {
  return (
    <div style={{ color:'var(--or)', fontWeight:700, fontSize:13, paddingBottom:6, borderBottom:'2px solid #FEF3E8', marginBottom:12 }}>
      {label}
    </div>
  );
}

// ── Read-only pricing display field ──────────────────────────────────────
function DbROField({ label, value, color, large }) {
  return (
    <div className="fld">
      <label>{label}</label>
      <div style={{
        background:'#F5F4F2', border:'1.5px solid var(--bdr)', borderRadius:9,
        padding:'7px 12px', height:38, display:'flex', alignItems:'center',
        fontSize: large ? 15 : 13, fontWeight: large ? 700 : 500,
        color: value === '—' ? 'var(--txt3)' : (color || 'var(--txt)'),
        fontVariantNumeric:'tabular-nums', letterSpacing:'-0.01em',
      }}>
        {value}
      </div>
    </div>
  );
}

// ── Debris Transaction Drill-Down Panel ───────────────────────────────────
function DebrisRowDrill({ it, rmcPlants }) {
  const plant   = rmcPlants.find(p => p.id === it.sourcePlantId) || {};
  const dispLbl = it.disposalType === 'Other' && it.disposalTypeOther ? `${it.disposalType} (${it.disposalTypeOther})` : (it.disposalType || '—');
  const destLbl = it.destType === 'Other' && it.destTypeOther ? `${it.destType} (${it.destTypeOther})` : (it.destType || '—');
  const hasComm = it.rate && parseFloat(it.rate) > 0;
  return (
    <div style={{ padding:'12px 16px 16px', background:'#FFF9F5', borderTop:'2px solid var(--or-bdr)' }}>
      <div className="rg-4" style={{ gap:10 }}>
        <window.SYDrillSection title="Transaction Details" color="var(--or)">
          <window.SYDrillKV label="Movement ID" value={it.id ? it.id.slice(0,8).toUpperCase() : '—'} mono bold/>
          <window.SYDrillKV label="Date" value={window.fmtDate(it.date)}/>
          <window.SYDrillKV label="Company" value={Store.name('companies', it.companyId) || '—'}/>
          <window.SYDrillKV label="Material" value={it.material || '—'} bold/>
          <window.SYDrillKV label="Customer" value={it.customerName || '—'} bold/>
          <window.SYDrillKV label="Quantity" value={`${Number(it.quantity || 0).toFixed(3)} ${it.uom || 'Ton'}`} bold color="var(--or)"/>
          <window.SYDrillKV label="Challan" value={it.challanNumber || '—'} mono/>
          <window.SYDrillKV label="Status" value={it.status || 'Delivered'} color="var(--ok)" bold/>
        </window.SYDrillSection>
        <window.SYDrillSection title="Source" color="#1D4ED8">
          <window.SYDrillKV label="Source Plant" value={plant.name || '—'} bold/>
          <window.SYDrillKV label="Plant Location" value={plant.location || '—'}/>
          <window.SYDrillKV label="Plant Company" value={Store.name('companies', plant.companyId) || '—'}/>
          <window.SYDrillKV label="Plant Status" value={plant.status || '—'} color={plant.status === 'Active' ? 'var(--ok)' : 'var(--err)'}/>
        </window.SYDrillSection>
        <window.SYDrillSection title="Disposal & Destination" color="#B45309">
          <window.SYDrillKV label="Disposal Type" value={dispLbl} bold/>
          <window.SYDrillKV label="Destination Type" value={destLbl}/>
          <window.SYDrillKV label="Destination Location" value={it.destLocation || '—'} bold/>
          {it.remarks && <window.SYDrillKV label="Remarks" value={it.remarks}/>}
        </window.SYDrillSection>
        {hasComm ? (
          <window.SYDrillSection title="Commercial" color="var(--ok)">
            <window.SYDrillKV label="Rate" value={dbFmtCur(it.rate)} bold color="var(--or)"/>
            <window.SYDrillKV label="GST %" value={it.gstPct ? `${it.gstPct}%` : '0%'}/>
            <window.SYDrillKV label="Total Amount" value={dbFmtCur(it.totalAmount)} bold/>
            <window.SYDrillKV label="GST Amount" value={dbFmtCur(it.gstAmount)}/>
            <window.SYDrillKV label="Net Amount" value={dbFmtCur(it.netAmount)} bold color="var(--ok)"/>
            <window.SYDrillKV label="PO Reference" value={it.poNumber || '—'} mono/>
          </window.SYDrillSection>
        ) : (
          <window.SYDrillSection title="Logistics" color="#6B7280">
            <window.SYDrillKV label="Vehicle Number" value={it.vehicleFull || it.vehicleNumber || '—'} mono bold/>
            <window.SYDrillKV label="Transporter" value={it.transporter || '—'}/>
            {it.transporterMasterId && <window.SYDrillKV label="Transporter Ref" value={it.transporterMasterId.slice(0,8).toUpperCase()} mono/>}
            {parseFloat(it.transportRate) > 0 && <window.SYDrillKV label="Transport Rate" value={`₹${parseFloat(it.transportRate).toFixed(2)} / MT`} bold color="var(--info)"/>}
            {parseFloat(it.transportRate) > 0 && <window.SYDrillKV label="Transport Amount" value={dbFmtCur((parseFloat(it.quantity)||0) * parseFloat(it.transportRate))} bold color="var(--info)"/>}
            <window.SYDrillKV label="Created By" value={it.createdBy || '—'}/>
          </window.SYDrillSection>
        )}
      </div>
      {hasComm && (
        <div style={{ marginTop:10, padding:'6px 10px', background:'#F9FAFB', borderRadius:6, display:'flex', gap:16, flexWrap:'wrap' }}>
          <span style={{ fontSize:11, color:'var(--txt2)' }}><strong>Vehicle:</strong> {it.vehicleFull || it.vehicleNumber || '—'}</span>
          <span style={{ fontSize:11, color:'var(--txt2)' }}><strong>Transporter:</strong> {it.transporter || '—'}</span>
          {parseFloat(it.transportRate) > 0 && <span style={{ fontSize:11, color:'var(--info)', fontWeight:600 }}><strong>Transport Rate:</strong> ₹{parseFloat(it.transportRate).toFixed(2)}/MT · Amt: {dbFmtCur((parseFloat(it.quantity)||0) * parseFloat(it.transportRate))}</span>}
        </div>
      )}
    </div>
  );
}

// ── Linked Transactions Table ─────────────────────────────────────────────
function DbLinkedTable({ rows, rmcPlants }) {
  if (!rows || !rows.length) return <div style={{ fontSize:11.5, color:'var(--txt3)', fontStyle:'italic', padding:'8px 0' }}>No transactions.</div>;
  const totalQty = rows.reduce((s,r) => s + (parseFloat(r.quantity) || 0), 0);
  const totalRev = rows.reduce((s,r) => s + (parseFloat(r.netAmount) || 0), 0);
  return (
    <div style={{ overflowX:'auto', maxHeight:300, overflowY:'auto' }}>
      <table style={{ width:'100%', borderCollapse:'collapse', fontSize:11.5, minWidth:720 }}>
        <thead><tr style={{ background:'#F9FAFB' }}>
          {['Date','Plant','Customer','Vehicle','Challan','Qty','UOM','Rate','Net Amount'].map(h => (
            <th key={h} style={{ padding:'5px 8px', textAlign:'left', fontWeight:700, fontSize:10.5, color:'var(--txt2)', borderBottom:'1px solid var(--bdr)', whiteSpace:'nowrap' }}>{h}</th>
          ))}
        </tr></thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.id} style={{ borderBottom:'1px solid #F3F4F6' }}>
              <td style={{ padding:'4px 8px', whiteSpace:'nowrap' }}>{window.fmtDate(r.date)}</td>
              <td style={{ padding:'4px 8px', fontWeight:500 }}>{rmcPlants.find(p => p.id === r.sourcePlantId)?.name || '—'}</td>
              <td style={{ padding:'4px 8px', fontSize:11 }}>{r.customerName || '—'}</td>
              <td style={{ padding:'4px 8px', fontFamily:'var(--font)', fontSize:11 }}>{r.vehicleFull || r.vehicleNumber || '—'}</td>
              <td style={{ padding:'4px 8px', fontFamily:'var(--font)', fontSize:11 }}>{r.challanNumber || '—'}</td>
              <td style={{ padding:'4px 8px', fontWeight:600, color:'var(--or)' }}>{Number(r.quantity || 0).toFixed(3)}</td>
              <td style={{ padding:'4px 8px', color:'var(--txt2)', fontSize:11 }}>{r.uom || 'Ton'}</td>
              <td style={{ padding:'4px 8px', fontSize:11, color:'var(--txt2)' }}>{r.rate ? dbFmtCur(r.rate) : '—'}</td>
              <td style={{ padding:'4px 8px', fontWeight:700, color:'var(--ok)' }}>{r.netAmount ? dbFmtCur(r.netAmount) : '—'}</td>
            </tr>
          ))}
        </tbody>
        <tfoot><tr style={{ background:'#FFF7ED' }}>
          <td colSpan={5} style={{ padding:'5px 8px', fontWeight:700, fontSize:11, color:'var(--txt2)' }}>TOTAL — {rows.length} trips</td>
          <td style={{ padding:'5px 8px', fontWeight:700, color:'var(--or)' }}>{totalQty.toFixed(3)}</td>
          <td></td><td></td>
          <td style={{ padding:'5px 8px', fontWeight:700, color:'var(--ok)' }}>{dbFmtCur(totalRev)}</td>
        </tr></tfoot>
      </table>
    </div>
  );
}

// ── Helper: breakdown table ───────────────────────────────────────────────
function DbBreakTable({ title, rows, col1, col2, col3, c2color }) {
  return (
    <div>
      <div style={{ fontWeight:700, fontSize:12, marginBottom:7 }}>{title}</div>
      <table style={{ width:'100%', borderCollapse:'collapse', fontSize:11.5 }}>
        <thead><tr style={{ background:'#F9FAFB' }}>
          {[col1, col2, col3].filter(Boolean).map(h => (
            <th key={h} style={{ padding:'5px 8px', textAlign:h === col1 ? 'left' : 'right', fontWeight:700, fontSize:10.5, color:'var(--txt2)', borderBottom:'1px solid var(--bdr)' }}>{h}</th>
          ))}
        </tr></thead>
        <tbody>
          {rows.length === 0
            ? <tr><td colSpan={3} style={{ padding:'8px', color:'var(--txt3)', fontStyle:'italic', fontSize:11 }}>No data</td></tr>
            : rows.map((r, i) => (
              <tr key={i} style={{ borderBottom:'1px solid #F3F4F6' }}>
                <td style={{ padding:'4px 8px', fontWeight:500 }}>{r[0]}</td>
                <td style={{ padding:'4px 8px', textAlign:'right', fontWeight:600, color:c2color || 'var(--or)' }}>{r[1]}</td>
                {col3 && <td style={{ padding:'4px 8px', textAlign:'right', color:'var(--txt2)' }}>{r[2]}</td>}
              </tr>
            ))
          }
        </tbody>
      </table>
    </div>
  );
}

// ── Plant Drill-Down Modal ────────────────────────────────────────────────
function DbPlantModal({ plantId, allItems, rmcPlants, onClose }) {
  const plant    = rmcPlants.find(p => p.id === plantId) || { id:plantId, name:plantId };
  const txns     = allItems.filter(i => i.sourcePlantId === plantId);
  const totalQty = txns.reduce((s,i) => s + (parseFloat(i.quantity) || 0), 0);
  const totalRev = txns.reduce((s,i) => s + (parseFloat(i.netAmount) || 0), 0);
  const vehicles = [...new Set(txns.map(i => i.vehicleFull || i.vehicleNumber).filter(Boolean))];
  const matBreak = dbMemo(() => {
    const m = {};
    txns.forEach(i => {
      const k = i.material || 'Unknown';
      if (!m[k]) m[k] = { qty:0, trips:0, rev:0 };
      m[k].qty += parseFloat(i.quantity) || 0;
      m[k].trips++;
      m[k].rev += parseFloat(i.netAmount) || 0;
    });
    return Object.entries(m).map(([k,v]) => [k, v.qty.toFixed(3), `${v.trips} trips · ${dbFmtCur(v.rev)}`]).sort((a,b) => parseFloat(b[1]) - parseFloat(a[1]));
  }, [txns]);
  const dispBreak = dbMemo(() => {
    const m = {};
    txns.forEach(i => { const k = i.disposalType || 'Unknown'; if (!m[k]) m[k]={qty:0,trips:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; });
    return Object.entries(m).map(([k,v]) => [k, v.qty.toFixed(3), v.trips+' trips']);
  }, [txns]);
  return (
    <window.SYDrillModal title={plant.name || plantId} subtitle={`Plant Intelligence — ${txns.length} trips · ${window.formatQuantity(totalQty)} T · ${dbFmtCur(totalRev)}`} color="var(--or)" onClose={onClose} width={920}>
      <div className="dd-4col" style={{marginBottom:14}}>
        {[['Total Trips',txns.length,'var(--or)'],['Total Quantity',window.formatQuantity(totalQty)+' T','var(--info)'],['Total Revenue',dbFmtCur(totalRev),'var(--ok)'],['Vehicles Used',vehicles.length,'#6D28D9']].map(([l,v,c]) => (
          <div key={l} style={{ background:'#F9FAFB', border:'1px solid var(--bdr)', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:16, fontWeight:700, color:c }}>{v}</div>
            <div style={{ fontSize:11, color:'var(--txt2)', marginTop:2 }}>{l}</div>
          </div>
        ))}
      </div>
      <div className="dd-2col" style={{marginBottom:14}}>
        <DbBreakTable title="Material Breakdown" rows={matBreak} col1="Material" col2="Quantity" col3="Details" c2color="var(--or)"/>
        <DbBreakTable title="Disposal Breakdown" rows={dispBreak} col1="Disposal Type" col2="Quantity" col3="Trips" c2color="#B45309"/>
      </div>
      <div style={{ marginBottom:8, fontWeight:700, fontSize:12 }}>All Transactions — {txns.length} records</div>
      <DbLinkedTable rows={[...txns].sort((a,b) => (b.date||'').localeCompare(a.date||''))} rmcPlants={rmcPlants}/>
    </window.SYDrillModal>
  );
}

// ── Material Drill-Down Modal ─────────────────────────────────────────────
function DbMaterialModal({ material, allItems, rmcPlants, onClose }) {
  const txns     = allItems.filter(i => i.material === material);
  const totalQty = txns.reduce((s,i) => s + (parseFloat(i.quantity) || 0), 0);
  const totalRev = txns.reduce((s,i) => s + (parseFloat(i.netAmount) || 0), 0);
  const ratedTxns = txns.filter(i => i.rate && parseFloat(i.rate) > 0);
  const avgRate  = ratedTxns.length > 0 ? ratedTxns.reduce((s,i) => s + (parseFloat(i.rate) || 0), 0) / ratedTxns.length : 0;
  const custBreak = dbMemo(() => {
    const m = {};
    txns.forEach(i => { const k = i.customerName || 'Unknown'; if (!m[k]) m[k]={rev:0,qty:0}; m[k].rev+=parseFloat(i.netAmount)||0; m[k].qty+=parseFloat(i.quantity)||0; });
    return Object.entries(m).map(([k,v]) => [k, dbFmtCur(v.rev), window.formatQuantity(v.qty)+' T']).sort((a,b) => parseFloat(b[1].replace(/[^\d.]/g,''))-parseFloat(a[1].replace(/[^\d.]/g,'')));
  }, [txns]);
  const plantBreak = dbMemo(() => {
    const m = {};
    txns.forEach(i => { const k = i.sourcePlantId||'unknown'; if(!m[k])m[k]={qty:0,trips:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; });
    return Object.entries(m).map(([k,v]) => [rmcPlants.find(p=>p.id===k)?.name||k, v.qty.toFixed(3), v.trips+' trips']).sort((a,b)=>parseFloat(b[1])-parseFloat(a[1]));
  }, [txns]);
  return (
    <window.SYDrillModal title={material} subtitle={`Material Intelligence — ${txns.length} trips · ${window.formatQuantity(totalQty)} T · ${dbFmtCur(totalRev)}`} color="#B45309" onClose={onClose} width={920}>
      <div className="dd-4col" style={{marginBottom:14}}>
        {[['Total Trips',txns.length,'var(--or)'],['Total Quantity',window.formatQuantity(totalQty)+' T','#B45309'],['Total Revenue',dbFmtCur(totalRev),'var(--ok)'],['Avg. Rate',avgRate>0?dbFmtCur(avgRate):'—','var(--info)']].map(([l,v,c]) => (
          <div key={l} style={{ background:'#F9FAFB', border:'1px solid var(--bdr)', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:16, fontWeight:700, color:c }}>{v}</div>
            <div style={{ fontSize:11, color:'var(--txt2)', marginTop:2 }}>{l}</div>
          </div>
        ))}
      </div>
      <div className="dd-2col" style={{marginBottom:14}}>
        <DbBreakTable title="Revenue by Customer" rows={custBreak} col1="Customer" col2="Revenue" col3="Quantity" c2color="var(--ok)"/>
        <DbBreakTable title="Plant Distribution" rows={plantBreak} col1="Plant" col2="Quantity" col3="Trips" c2color="#B45309"/>
      </div>
      <div style={{ marginBottom:8, fontWeight:700, fontSize:12 }}>All Transactions — {txns.length} records</div>
      <DbLinkedTable rows={[...txns].sort((a,b) => (b.date||'').localeCompare(a.date||''))} rmcPlants={rmcPlants}/>
    </window.SYDrillModal>
  );
}

// ── Disposal Drill-Down Modal ─────────────────────────────────────────────
function DbDisposalModal({ disposalType, allItems, rmcPlants, onClose }) {
  const txns     = allItems.filter(i => i.disposalType === disposalType);
  const totalQty = txns.reduce((s,i) => s + (parseFloat(i.quantity) || 0), 0);
  const vehicles = [...new Set(txns.map(i => i.vehicleFull || i.vehicleNumber).filter(Boolean))];
  const plants   = [...new Set(txns.map(i => i.sourcePlantId).filter(Boolean))];
  const locBreak = dbMemo(() => { const m={}; txns.forEach(i=>{const k=i.destLocation||'Unknown';if(!m[k])m[k]={qty:0,trips:0};m[k].qty+=parseFloat(i.quantity)||0;m[k].trips++;}); return Object.entries(m).map(([k,v])=>[k,v.qty.toFixed(3),v.trips+' trips']).sort((a,b)=>parseFloat(b[1])-parseFloat(a[1])); }, [txns]);
  const matBreak = dbMemo(() => { const m={}; txns.forEach(i=>{const k=i.material||'Unknown';if(!m[k])m[k]={qty:0};m[k].qty+=parseFloat(i.quantity)||0;}); return Object.entries(m).map(([k,v])=>[k,v.qty.toFixed(3)]).sort((a,b)=>parseFloat(b[1])-parseFloat(a[1])); }, [txns]);
  const coBreak  = dbMemo(() => { const m={}; txns.forEach(i=>{const k=Store.name('companies',i.companyId)||i.companyId;if(!m[k])m[k]={qty:0,trips:0};m[k].qty+=parseFloat(i.quantity)||0;m[k].trips++;}); return Object.entries(m).map(([k,v])=>[k,v.qty.toFixed(3),v.trips+' trips']).sort((a,b)=>parseFloat(b[1])-parseFloat(a[1])); }, [txns]);
  return (
    <window.SYDrillModal title={disposalType} subtitle={`Disposal Analysis — ${txns.length} trips · ${window.formatQuantity(totalQty)} T`} color="#6D28D9" onClose={onClose} width={920}>
      <div className="dd-4col" style={{marginBottom:14}}>
        {[['Total Trips',txns.length,'var(--or)'],['Total Quantity',window.formatQuantity(totalQty)+' T','#6D28D9'],['Vehicles Used',vehicles.length,'var(--info)'],['Plants Involved',plants.length,'var(--ok)']].map(([l,v,c]) => (
          <div key={l} style={{ background:'#F9FAFB', border:'1px solid var(--bdr)', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:16, fontWeight:700, color:c }}>{v}</div>
            <div style={{ fontSize:11, color:'var(--txt2)', marginTop:2 }}>{l}</div>
          </div>
        ))}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14, marginBottom:14 }}>
        <DbBreakTable title="Destination Locations" rows={locBreak} col1="Location" col2="Quantity" col3="Trips" c2color="#6D28D9"/>
        <DbBreakTable title="Material Breakdown" rows={matBreak} col1="Material" col2="Quantity" c2color="#B45309"/>
        <DbBreakTable title="Company Breakdown" rows={coBreak} col1="Company" col2="Quantity" col3="Trips" c2color="var(--ok)"/>
      </div>
      <div style={{ marginBottom:8, fontWeight:700, fontSize:12 }}>All Transactions — {txns.length} records</div>
      <DbLinkedTable rows={[...txns].sort((a,b) => (b.date||'').localeCompare(a.date||''))} rmcPlants={rmcPlants}/>
    </window.SYDrillModal>
  );
}

// ── Customer Drill-Down Modal ─────────────────────────────────────────────
function DbCustomerModal({ customerId, customerName, allItems, rmcPlants, onClose }) {
  const txns     = allItems.filter(i => i.customerId === customerId || i.customerName === customerName);
  const totalQty = txns.reduce((s,i) => s + (parseFloat(i.quantity) || 0), 0);
  const totalRev = txns.reduce((s,i) => s + (parseFloat(i.netAmount) || 0), 0);
  const ratedTxns = txns.filter(i => i.rate && parseFloat(i.rate) > 0);
  const avgRate  = ratedTxns.length > 0 ? ratedTxns.reduce((s,i) => s + (parseFloat(i.rate) || 0), 0) / ratedTxns.length : 0;
  const matBreak = dbMemo(() => {
    const m = {};
    txns.forEach(i => { const k=i.material||'Unknown'; if(!m[k])m[k]={rev:0,qty:0,trips:0}; m[k].rev+=parseFloat(i.netAmount)||0; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; });
    return Object.entries(m).map(([k,v]) => [k, dbFmtCur(v.rev), window.formatQuantity(v.qty)+' T']).sort((a,b)=>parseFloat(b[1].replace(/[^\d.]/g,''))-parseFloat(a[1].replace(/[^\d.]/g,'')));
  }, [txns]);
  return (
    <window.SYDrillModal title={customerName || customerId} subtitle={`Customer Intelligence — ${txns.length} trips · ${window.formatQuantity(totalQty)} T · ${dbFmtCur(totalRev)}`} color="var(--ok)" onClose={onClose} width={920}>
      <div className="dd-4col" style={{marginBottom:14}}>
        {[['Total Trips',txns.length,'var(--or)'],['Total Quantity',window.formatQuantity(totalQty)+' T','var(--info)'],['Total Revenue',dbFmtCur(totalRev),'var(--ok)'],['Avg. Rate',avgRate>0?dbFmtCur(avgRate):'—','#B45309']].map(([l,v,c]) => (
          <div key={l} style={{ background:'#F9FAFB', border:'1px solid var(--bdr)', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:16, fontWeight:700, color:c }}>{v}</div>
            <div style={{ fontSize:11, color:'var(--txt2)', marginTop:2 }}>{l}</div>
          </div>
        ))}
      </div>
      <DbBreakTable title="Revenue by Material" rows={matBreak} col1="Material" col2="Revenue" col3="Quantity" c2color="var(--ok)"/>
      <div style={{ marginTop:14, marginBottom:8, fontWeight:700, fontSize:12 }}>All Transactions — {txns.length} records</div>
      <DbLinkedTable rows={[...txns].sort((a,b) => (b.date||'').localeCompare(a.date||''))} rmcPlants={rmcPlants}/>
    </window.SYDrillModal>
  );
}

// ── KPI Drill-Down Modal ──────────────────────────────────────────────────
function DbKPIModal({ type, allItems, rmcPlants, activePlants, onClose }) {
  const totalQty = allItems.reduce((s,i) => s + (parseFloat(i.quantity) || 0), 0);
  const totalRev = allItems.reduce((s,i) => s + (parseFloat(i.netAmount) || 0), 0);

  if (type === 'trips' || type === 'qty') {
    const byPlant = dbMemo(() => {
      const m = {};
      allItems.forEach(i => { const k=i.sourcePlantId||'unknown'; if(!m[k])m[k]={qty:0,trips:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; });
      return Object.entries(m).map(([k,v]) => [rmcPlants.find(p=>p.id===k)?.name||k, v.qty.toFixed(3), v.trips]).sort((a,b)=>parseFloat(b[1])-parseFloat(a[1]));
    }, [allItems]);
    return (
      <window.SYDrillModal title={type==='trips'?'Total Trips Breakdown':'Total Quantity Breakdown'} subtitle={`${allItems.length} trips · ${window.formatQuantity(totalQty)} T total`} color="var(--or)" onClose={onClose}>
        <DbBreakTable title="By Plant" rows={byPlant} col1="Plant" col2="Quantity (T)" col3="Trips" c2color="var(--or)"/>
      </window.SYDrillModal>
    );
  }

  if (type === 'revenue') {
    const byMat = dbMemo(() => {
      const m = {};
      allItems.forEach(i => { const k=i.material||'Unknown'; if(!m[k])m[k]={rev:0,qty:0}; m[k].rev+=parseFloat(i.netAmount)||0; m[k].qty+=parseFloat(i.quantity)||0; });
      return Object.entries(m).map(([k,v]) => [k, dbFmtCur(v.rev), window.formatQuantity(v.qty)+' T']).sort((a,b)=>parseFloat(b[1].replace(/[^\d.]/g,''))-parseFloat(a[1].replace(/[^\d.]/g,'')));
    }, [allItems]);
    const byCust = dbMemo(() => {
      const m = {};
      allItems.forEach(i => { const k=i.customerName||'Unknown'; if(!m[k])m[k]={rev:0,trips:0}; m[k].rev+=parseFloat(i.netAmount)||0; m[k].trips++; });
      return Object.entries(m).map(([k,v]) => [k, dbFmtCur(v.rev), v.trips+' trips']).sort((a,b)=>parseFloat(b[1].replace(/[^\d.]/g,''))-parseFloat(a[1].replace(/[^\d.]/g,'')));
    }, [allItems]);
    const byCo = dbMemo(() => {
      const m = {};
      allItems.forEach(i => { const k=Store.name('companies',i.companyId)||i.companyId||'Unknown'; if(!m[k])m[k]={rev:0}; m[k].rev+=parseFloat(i.netAmount)||0; });
      return Object.entries(m).map(([k,v]) => [k, dbFmtCur(v.rev)]).sort((a,b)=>parseFloat(b[1].replace(/[^\d.]/g,''))-parseFloat(a[1].replace(/[^\d.]/g,'')));
    }, [allItems]);
    return (
      <window.SYDrillModal title="Total Revenue Breakdown" subtitle={`${dbFmtCur(totalRev)} from ${allItems.filter(i=>i.netAmount).length} commercial trips`} color="var(--ok)" onClose={onClose} width={920}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14 }}>
          <DbBreakTable title="Revenue by Material" rows={byMat} col1="Material" col2="Revenue" col3="Quantity" c2color="#B45309"/>
          <DbBreakTable title="Revenue by Customer" rows={byCust} col1="Customer" col2="Revenue" col3="Trips" c2color="var(--ok)"/>
          <DbBreakTable title="Revenue by Company" rows={byCo} col1="Company" col2="Revenue" c2color="var(--info)"/>
        </div>
      </window.SYDrillModal>
    );
  }

  if (type === 'plants') {
    return (
      <window.SYDrillModal title="Active Plants" subtitle={`${activePlants.length} active plants`} color="var(--ok)" onClose={onClose}>
        <div className="tbl-w">
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
            <thead><tr style={{ background:'#F9FAFB' }}>
              {['Plant','Company','Location','Status'].map(h => <th key={h} style={{ padding:'6px 8px', textAlign:'left', fontWeight:700, fontSize:10.5, color:'var(--txt2)', borderBottom:'1px solid var(--bdr)' }}>{h}</th>)}
            </tr></thead>
            <tbody>{activePlants.map(p => (
              <tr key={p.id} style={{ borderBottom:'1px solid #F3F4F6' }}>
                <td style={{ padding:'5px 8px', fontWeight:600 }}>{p.name}</td>
                <td style={{ padding:'5px 8px', fontSize:11 }}>{Store.name('companies',p.companyId)}</td>
                <td style={{ padding:'5px 8px', fontSize:11, color:'var(--txt2)' }}>{p.location||'—'}</td>
                <td style={{ padding:'5px 8px' }}><window.Badge v={p.status}/></td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      </window.SYDrillModal>
    );
  }
  return null;
}

// ── Main Page ─────────────────────────────────────────────────────────────
function DebrisMovementPage() {
  window.useStoreSync();
  const { companyId, session } = dbCtx(window.AppCtx);
  const isGroup = companyId === 'group';

  const [items,      setItems]      = dbSt([]);
  const [search,     setSearch]     = dbSt('');
  const [fComp,      setFComp]      = dbSt('');
  const [fPlant,     setFPlant]     = dbSt('');
  const [fMat,       setFMat]       = dbSt('');
  const [fCust,      setFCust]      = dbSt('');
  const [periodPreset, setPeriodPreset] = dbSt('all');
  const [customFrom,   setCustomFrom]   = dbSt('');
  const [customTo,     setCustomTo]     = dbSt('');
  const periodRange = dbMemo(() => 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 [view,       setView]       = dbSt('list');
  const [page,       setPage]       = dbSt(1);
  const [modal,      setModal]      = dbSt(false);
  const [editId,     setEditId]     = dbSt(null);
  const [delId,      setDelId]      = dbSt(null);
  const [dbStatement, setDbStatement] = dbSt(null);
  const [form,       setForm]       = dbSt({});
  const [expId,      setExpId]      = dbSt(null);
  const [plantDrill, setPlantDrill] = dbSt(null);
  const [matDrill,   setMatDrill]   = dbSt(null);
  const [dispDrill,  setDispDrill]  = dbSt(null);
  const [custDrill,  setCustDrill]  = dbSt(null); // { id, name }
  const [kpiDrill,   setKpiDrill]   = dbSt(null);
  const PER = 50;

  // ── Masters — always live, never hardcoded ────────────────────────────
  const companies     = Store.all('companies');
  const rmcPlants     = Store.all('rmcPlants') || [];
  // Debris materials: live from Material Master, filtered by category
  const allDebrisMats = (Store.all('materials', 'group') || []).filter(m => m.category === 'Debris');
  // Transporter Master
  const tmAll         = Store.all('transporterMaster', 'group');
  const tmActive      = tmAll.filter(t => t.status === 'Active' || !t.status);
  const tmVehicles    = form.transporterMasterId
    ? (Store.all('vehicleMaster', 'group') || []).filter(v => v.transporterId === form.transporterMasterId && (v.status === 'Active' || !v.status))
    : [];

  React.useEffect(() => { load(); }, [companyId]);
  function load() { setItems(Store.all('debrisMovements') || []); }
  const setF = (k, v) => setForm(p => ({ ...p, [k]: v }));

  // ── Auto-pricing: computed every render from Price Orders — no manual input ──
  // Smart Price Resolution Engine (rate-engine.js) — same centralized lookup Sales
  // Orders/Purchases use, called here in diagnostic mode so a miss always explains why.
  let pricingCalc = { found: false };
  let priceDiag = null;
  if (window.RateEngine && form.companyId && form.companyId !== 'group' && form.customerId && form.materialId) {
    priceDiag = window.RateEngine.getSaleRateDiagnostic(form.companyId, form.customerId, form.materialId);
    if (priceDiag.found) {
      const priceData = priceDiag.rate;
      const qty = parseFloat(form.quantity) || 0;
      const rate = priceData.rate;
      const gstPct = parseFloat(priceData.gst) || 0;
      const totalAmount = qty * rate;
      const gstAmount   = totalAmount * gstPct / 100;
      const netAmount   = totalAmount + gstAmount;
      pricingCalc = { found:true, rate, gstPct, totalAmount, gstAmount, netAmount, poNumber:priceData.poNumber, poId:priceData.poId };
    }
  }

  // ── Data slices ───────────────────────────────────────────────────────
  const baseItems = dbMemo(() =>
    isGroup ? items : items.filter(i => i.companyId === companyId),
    [items, companyId]
  );

  const matNamesInUse  = dbMemo(() => [...new Set(baseItems.map(i => i.material).filter(Boolean))].sort(), [baseItems]);
  const custNamesInUse = dbMemo(() => [...new Set(baseItems.map(i => i.customerName).filter(Boolean))].sort(), [baseItems]);

  const filtered = dbMemo(() => baseItems.filter(it => {
    if (search) {
      const q = search.toLowerCase();
      if (![it.challanNumber, it.vehicleFull, it.vehicleNumber, it.destLocation, it.transporter, it.customerName, it.material].some(v => String(v||'').toLowerCase().includes(q))) return false;
    }
    if (fComp  && it.companyId      !== fComp)  return false;
    if (fPlant && it.sourcePlantId  !== fPlant) return false;
    if (fMat   && it.material       !== fMat)   return false;
    if (fCust  && it.customerName   !== fCust)  return false;
    if (!window.dieselInPeriod(it.date, periodRange.from, periodRange.to)) return false;
    return true;
  }), [baseItems, search, fComp, fPlant, fMat, fCust, periodRange]);

  const totalPgs = Math.ceil(filtered.length / PER) || 1;
  const paged    = filtered.slice((page-1)*PER, page*PER);
  const totalQty = dbMemo(() => filtered.reduce((s,i) => s + (parseFloat(i.quantity)||0), 0), [filtered]);
  const totalRev = dbMemo(() => filtered.reduce((s,i) => s + (parseFloat(i.netAmount)||0), 0), [filtered]);
  const activePlants = rmcPlants.filter(p => p.status === 'Active');

  // ── Report summaries (all derived, no duplication) ────────────────────
  const plantSummary = dbMemo(() => {
    const m = {};
    baseItems.forEach(i => { const k=i.sourcePlantId||'unknown'; if(!m[k])m[k]={plantId:k,qty:0,trips:0,rev:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; m[k].rev+=parseFloat(i.netAmount)||0; });
    return Object.values(m).sort((a,b) => b.qty - a.qty);
  }, [baseItems]);

  const matSummary = dbMemo(() => {
    const m = {};
    baseItems.forEach(i => { const k=i.material||'Unknown'; if(!m[k])m[k]={material:k,qty:0,trips:0,rev:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; m[k].rev+=parseFloat(i.netAmount)||0; });
    return Object.values(m).sort((a,b) => b.qty - a.qty);
  }, [baseItems]);

  const custSummary = dbMemo(() => {
    const m = {};
    baseItems.forEach(i => { const k=i.customerName||'Unknown'; if(!m[k])m[k]={customerName:k,customerId:i.customerId||'',qty:0,trips:0,rev:0}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; m[k].rev+=parseFloat(i.netAmount)||0; });
    return Object.values(m).sort((a,b) => b.rev - a.rev);
  }, [baseItems]);

  const disposalSummary = dbMemo(() => {
    const m = {};
    baseItems.forEach(i => { const k=i.disposalType||'Unknown'; if(!m[k])m[k]={type:k,qty:0,trips:0,vehicles:new Set()}; m[k].qty+=parseFloat(i.quantity)||0; m[k].trips++; if(i.vehicleFull||i.vehicleNumber)m[k].vehicles.add(i.vehicleFull||i.vehicleNumber); });
    return Object.values(m).map(r => ({...r, vehicles:r.vehicles.size})).sort((a,b) => b.qty - a.qty);
  }, [baseItems]);

  const avgRate = dbMemo(() => {
    const rt = baseItems.filter(i => i.rate && parseFloat(i.rate) > 0);
    return rt.length > 0 ? rt.reduce((s,i) => s + (parseFloat(i.rate)||0), 0) / rt.length : 0;
  }, [baseItems]);

  // ── CRUD handlers ─────────────────────────────────────────────────────
  function openAdd() {
    setForm({
      date: new Date().toISOString().slice(0,10),
      uom: 'Ton', status: 'Delivered',
      companyId: isGroup ? '' : companyId,
      transporterMasterId:'', transporter:'', vehicleFull:'', vehicleNumber:'', transportRate:'',
      customerId:'', customerName:'', materialId:'', material:'',
    });
    setEditId(null); setModal(true);
  }

  function openEdit(it) {
    // Resolve materialId from name for legacy records without materialId
    let materialId = it.materialId || '';
    if (!materialId && it.material) {
      const found = allDebrisMats.find(m => m.name === it.material);
      if (found) materialId = found.id;
    }
    setForm({ ...it, materialId });
    setEditId(it.id); setModal(true);
  }

  function handleSave(e) {
    e.preventDefault();
    if (!form.companyId || form.companyId === 'group') { window.toast&&window.toast('Please select a Company.','er'); return; }
    if (!form.customerId)                              { window.toast&&window.toast('Please select a Customer / Buyer.','er'); return; }
    if (!form.materialId)                              { window.toast&&window.toast('Please select a Debris Material.','er'); return; }
    if (!form.quantity || parseFloat(form.quantity) <= 0) { window.toast&&window.toast('Quantity must be greater than zero.','er'); return; }
    if (!pricingCalc.found) {
      window.toast&&window.toast((priceDiag && priceDiag.message) || 'No active price found for this Company / Customer / Material. Create a Customer Price Order first.','er');
      return;
    }
    if (!form.transporterMasterId) { window.toast&&window.toast('Please select a Transporter.','er'); return; }
    if (!form.vehicleFull)         { window.toast&&window.toast('Please select a Vehicle.','er'); return; }
    if (!form.transportRate || parseFloat(form.transportRate) <= 0) { window.toast&&window.toast('Transport Rate (₹/MT) is required and must be greater than zero.','er'); return; }

    const saveData = {
      ...form,
      vehicleNumber: form.vehicleFull || form.vehicleNumber || '',
      // Commercial fields — sourced from Price Orders only, never manual
      rate:        pricingCalc.rate,
      gstPct:      pricingCalc.gstPct,
      totalAmount: pricingCalc.totalAmount,
      gstAmount:   pricingCalc.gstAmount,
      netAmount:   pricingCalc.netAmount,
      poNumber:    pricingCalc.poNumber,
      poId:        pricingCalc.poId,
    };
    if (editId) {
      Store.update('debrisMovements', editId, saveData);
      Store.addLog('UPDATE','Debris Movement',`Updated ${form.challanNumber||editId}`);
    } else {
      Store.add('debrisMovements', saveData);
      Store.addLog('CREATE','Debris Movement',`Created ${form.challanNumber||''} — ${form.customerName||''} — ${dbFmtCur(pricingCalc.netAmount)}`);
    }
    setModal(false); load();
    window.toast&&window.toast(editId ? 'Updated' : 'Movement created','ok');
    setTimeout(() => window.AutoTransporterEngine?.backfillDebrisEntries?.(), 300);
  }

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

  function exportCSV() {
    const hdr = 'Date,Company,Customer,Source Plant,Dest Type,Dest Location,Material,Vehicle,Challan,Qty,UOM,Transport Rate (₹/MT),Transport Amount,Rate,GST%,Total Amt,GST Amt,Net Amount,Transporter,Disposal Type,PO Reference';
    const rows = filtered.map(i =>
      [i.date, Store.name('companies',i.companyId), i.customerName||'', rmcPlants.find(p=>p.id===i.sourcePlantId)?.name||i.sourcePlantId||'', i.destType||'', i.destLocation||'', i.material||'', i.vehicleFull||i.vehicleNumber||'', i.challanNumber||'', i.quantity||0, i.uom||'', i.transportRate||'', ((parseFloat(i.quantity)||0)*(parseFloat(i.transportRate)||0)).toFixed(2), i.rate||'', i.gstPct||'', i.totalAmount||'', i.gstAmount||'', i.netAmount||'', i.transporter||'', i.disposalType||'', i.poNumber||''].map(v=>`"${String(v).replace(/"/g,'""')}"`).join(',')
    ).join('\n');
    const blob = new Blob([hdr+'\n'+rows],{type:'text/csv'});
    const a = document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='debris_movements.csv'; a.click();
    window.toast&&window.toast('Exported','ok');
  }

  const toggleRow = id => setExpId(v => v === id ? null : id);

  // Customers for the form — live from Customer Master, scoped to selected company
  const formCustomers = (Store.all('customers', (form.companyId && form.companyId !== 'group') ? form.companyId : companyId) || []);

  // The material's unit (for rate label)
  const selectedMatUnit = allDebrisMats.find(m => m.id === form.materialId)?.unit || 'Ton';

  // ── Render ─────────────────────────────────────────────────────────────
  return (
    <div>
      <div className="ph">
        <div>
          <h1>Debris Movement</h1>
          <p>Commercial debris tracking — linked live to Material Master, Customers &amp; Price Orders</p>
        </div>
        <div className="ph-act">
          <button className={`btn btn-sm ${view==='list'?'btn-or':'btn-wh'}`} onClick={() => setView('list')}>List</button>
          <button className={`btn btn-sm ${view==='reports'?'btn-or':'btn-wh'}`} onClick={() => setView('reports')}>Reports</button>
          <button className="btn btn-wh btn-sm" onClick={exportCSV}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Export CSV
          </button>
          <button className="btn btn-or" onClick={openAdd}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            Add Movement
          </button>
        </div>
      </div>

      {/* ── Standardized Date Range Filter ── */}
      <div className="frow" style={{marginBottom:0}}>
        <window.DieselPeriodDropdown preset={periodPreset} onChange={setPeriod} customFrom={customFrom} customTo={customTo} onCustomChange={setCustomRange}/>
      </div>

      {/* ── KPI strip ── */}
      <div className="dd-4col" style={{marginBottom:12}}>
        {[
          { key:'trips',   lbl:'Total Trips',     val:filtered.length,           clr:'var(--or)' },
          { key:'qty',     lbl:'Total Qty Moved',  val:window.formatQuantity(totalQty)+' T',  clr:'var(--txt)' },
          { key:'revenue', lbl:'Total Revenue',    val:dbFmtCur(totalRev),        clr:'var(--ok)' },
          { key:'plants',  lbl:'Active Plants',    val:activePlants.length,       clr:'var(--info)' },
        ].map((k,i) => (
          <div key={i} className="kpi"
            onClick={() => setKpiDrill(k.key)}
            style={{ cursor:'pointer', borderTop:`3px solid ${k.clr}`, userSelect:'none' }}
            onMouseEnter={e => e.currentTarget.style.boxShadow='0 2px 8px rgba(0,0,0,.10)'}
            onMouseLeave={e => e.currentTarget.style.boxShadow=''}>
            <div className="kpi-val" style={{ color:k.clr }}>{k.val}</div>
            <div className="kpi-lbl">{k.lbl}</div>
            <div style={{ fontSize:10, color:k.clr, marginTop:3, fontWeight:600 }}>View details →</div>
          </div>
        ))}
      </div>

      {/* ── REPORTS VIEW ── */}
      {view === 'reports' ? (
        <div className="dd-2col">

          {/* Revenue by Material */}
          <div className="card">
            <div className="card-hd"><h3>Revenue by Material</h3><span style={{ fontSize:11.5, color:'var(--txt2)' }}>Click row to drill down</span></div>
            {matSummary.length === 0
              ? <div style={{ padding:24, textAlign:'center', color:'var(--txt2)', fontSize:12 }}>No data yet.</div>
              : <div className="tbl-w"><table className="tbl">
                  <thead><tr><th style={{ width:28 }}></th><th>MATERIAL</th><th>QUANTITY</th><th>TRIPS</th><th style={{ textAlign:'right' }}>REVENUE</th></tr></thead>
                  <tbody>{matSummary.map(r => (
                    <tr key={r.material} onClick={() => setMatDrill(r.material)} style={{ cursor:'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background='#FFF3E8'}
                      onMouseLeave={e => e.currentTarget.style.background=''}>
                      <td style={{ textAlign:'center', padding:'0 8px' }}><window.SYChevron open={false} color="#B45309"/></td>
                      <td style={{ fontWeight:500 }}>{r.material}</td>
                      <td style={{ fontWeight:600, color:'#B45309' }}>{r.qty.toFixed(3)}</td>
                      <td style={{ color:'var(--txt2)' }}>{r.trips}</td>
                      <td style={{ textAlign:'right', fontWeight:700, color:'var(--ok)' }}>{r.rev > 0 ? dbFmtCur(r.rev) : '—'}</td>
                    </tr>
                  ))}</tbody>
                </table></div>
            }
          </div>

          {/* Revenue by Customer */}
          <div className="card">
            <div className="card-hd"><h3>Revenue by Customer</h3><span style={{ fontSize:11.5, color:'var(--txt2)' }}>Click row to drill down</span></div>
            {custSummary.length === 0
              ? <div style={{ padding:24, textAlign:'center', color:'var(--txt2)', fontSize:12 }}>No customers yet.</div>
              : <div className="tbl-w"><table className="tbl">
                  <thead><tr><th style={{ width:28 }}></th><th>CUSTOMER</th><th>QUANTITY</th><th>TRIPS</th><th style={{ textAlign:'right' }}>REVENUE</th></tr></thead>
                  <tbody>{custSummary.map(r => (
                    <tr key={r.customerName} onClick={() => setCustDrill({ id:r.customerId, name:r.customerName })} style={{ cursor:'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background='#F0FDF4'}
                      onMouseLeave={e => e.currentTarget.style.background=''}>
                      <td style={{ textAlign:'center', padding:'0 8px' }}><window.SYChevron open={false} color="var(--ok)"/></td>
                      <td style={{ fontWeight:500 }}>{r.customerName}</td>
                      <td style={{ fontWeight:600, color:'var(--ok)' }}>{r.qty.toFixed(3)}</td>
                      <td style={{ color:'var(--txt2)' }}>{r.trips}</td>
                      <td style={{ textAlign:'right', fontWeight:700, color:'var(--ok)' }}>{r.rev > 0 ? dbFmtCur(r.rev) : '—'}</td>
                    </tr>
                  ))}</tbody>
                </table></div>
            }
          </div>

          {/* Plant-wise Summary */}
          <div className="card">
            <div className="card-hd"><h3>Plant-wise Summary</h3><span style={{ fontSize:11.5, color:'var(--txt2)' }}>Click row to drill down</span></div>
            {plantSummary.length === 0
              ? <div style={{ padding:24, textAlign:'center', color:'var(--txt2)', fontSize:12 }}>No data yet.</div>
              : <div className="tbl-w"><table className="tbl">
                  <thead><tr><th style={{ width:28 }}></th><th>PLANT NAME</th><th>COMPANY</th><th>QUANTITY</th><th>TRIPS</th><th style={{ textAlign:'right' }}>REVENUE</th></tr></thead>
                  <tbody>{plantSummary.map(r => (
                    <tr key={r.plantId} onClick={() => setPlantDrill(r.plantId)} style={{ cursor:'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background='#FFF7ED'}
                      onMouseLeave={e => e.currentTarget.style.background=''}>
                      <td style={{ textAlign:'center', padding:'0 8px' }}><window.SYChevron open={false}/></td>
                      <td style={{ fontWeight:500 }}>{rmcPlants.find(p=>p.id===r.plantId)?.name||r.plantId}</td>
                      <td style={{ fontSize:11 }}>{Store.name('companies',(rmcPlants.find(p=>p.id===r.plantId)||{}).companyId)||'—'}</td>
                      <td style={{ fontWeight:600, color:'var(--or)' }}>{r.qty.toFixed(3)}</td>
                      <td style={{ color:'var(--txt2)' }}>{r.trips}</td>
                      <td style={{ textAlign:'right', fontWeight:700, color:'var(--ok)' }}>{r.rev > 0 ? dbFmtCur(r.rev) : '—'}</td>
                    </tr>
                  ))}</tbody>
                </table></div>
            }
          </div>

          {/* Disposal Summary */}
          <div className="card">
            <div className="card-hd"><h3>Disposal Summary</h3><span style={{ fontSize:11.5, color:'var(--txt2)' }}>Click row to drill down</span></div>
            {disposalSummary.length === 0
              ? <div style={{ padding:24, textAlign:'center', color:'var(--txt2)', fontSize:12 }}>No data yet.</div>
              : <div className="tbl-w"><table className="tbl">
                  <thead><tr><th style={{ width:28 }}></th><th>DISPOSAL TYPE</th><th>QUANTITY</th><th>TRIPS</th><th>VEHICLES</th></tr></thead>
                  <tbody>{disposalSummary.map(r => (
                    <tr key={r.type} onClick={() => setDispDrill(r.type)} style={{ cursor:'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background='#F5F3FF'}
                      onMouseLeave={e => e.currentTarget.style.background=''}>
                      <td style={{ textAlign:'center', padding:'0 8px' }}><window.SYChevron open={false} color="#6D28D9"/></td>
                      <td style={{ fontWeight:500 }}>{r.type}</td>
                      <td style={{ fontWeight:600, color:'#6D28D9' }}>{r.qty.toFixed(3)}</td>
                      <td style={{ color:'var(--txt2)' }}>{r.trips}</td>
                      <td style={{ color:'var(--txt2)' }}>{r.vehicles}</td>
                    </tr>
                  ))}</tbody>
                </table></div>
            }
          </div>

          {/* Revenue Analytics summary card */}
          <div className="card" style={{ gridColumn:'span 2' }}>
            <div className="card-hd"><h3>Revenue Analytics</h3><span style={{ fontSize:11.5, color:'var(--txt2)' }}>Automatically derived from all transactions</span></div>
            <div style={{ padding:'14px 18px' }}>
              <div className="dd-4col" style={{marginBottom:16}}>
                {[
                  ['Total Revenue',     dbFmtCur(baseItems.reduce((s,i)=>s+(parseFloat(i.netAmount)||0),0)), 'var(--ok)'],
                  ['Total Qty Moved',   baseItems.reduce((s,i)=>s+(parseFloat(i.quantity)||0),0).toFixed(1)+' T', 'var(--or)'],
                  ['Avg. Selling Rate', avgRate > 0 ? dbFmtCur(avgRate) : '—', '#B45309'],
                  ['Commercial Trips',  baseItems.filter(i=>i.netAmount&&parseFloat(i.netAmount)>0).length, 'var(--info)'],
                ].map(([l,v,c]) => (
                  <div key={l} style={{ background:'#F9FAFB', border:'1px solid var(--bdr)', borderRadius:8, padding:'12px 14px' }}>
                    <div style={{ fontSize:18, fontWeight:700, color:c }}>{v}</div>
                    <div style={{ fontSize:11, color:'var(--txt2)', marginTop:3 }}>{l}</div>
                  </div>
                ))}
              </div>
              {allDebrisMats.length === 0 && (
                <div style={{ background:'#FFFBEB', border:'1px solid #FDE68A', borderRadius:8, padding:'10px 14px', fontSize:12, color:'#92400E' }}>
                  <strong>Setup required:</strong> No materials with <strong>Category = Debris</strong> found in Material Master. Go to <strong>Materials</strong> → Add or edit a material → set <strong>Material Category = Debris</strong>. The material will automatically appear here and in Price Orders.
                </div>
              )}
            </div>
          </div>
        </div>

      ) : (
        /* ── LIST VIEW ── */
        <>
          <div className="frow">
            <div className="fs">
              <svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
              <input value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} placeholder="Search challan, vehicle, customer, material…"/>
            </div>
            {isGroup && (
              <window.FiltSelect placeholder="All Companies" value={fComp} onChange={v => { setFComp(v); setPage(1); }} options={companies.map(c => ({value:c.id,label:c.name}))}/>
            )}
            <window.FiltSelect placeholder="All Plants" value={fPlant} onChange={v => { setFPlant(v); setPage(1); }} options={rmcPlants.map(p => ({value:p.id,label:p.name}))}/>
            <window.FiltSelect placeholder="All Materials" value={fMat} onChange={v => { setFMat(v); setPage(1); }} options={matNamesInUse.map(m => ({value:m,label:m}))}/>
            <window.FiltSelect placeholder="All Customers" value={fCust} onChange={v => { setFCust(v); setPage(1); }} options={custNamesInUse.map(c => ({value:c,label:c}))}/>
            {(search || fComp || fPlant || fMat || fCust) && (
              <button className="btn btn-gh btn-sm" onClick={() => { setSearch(''); setFComp(''); setFPlant(''); setFMat(''); setFCust(''); setPeriodPreset('all'); setCustomFrom(''); setCustomTo(''); 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:28 }}></th>
                  <th style={{ width:46, textAlign:'center' }}>SR.</th>
                  <th>DATE</th>
                  {isGroup && <th>COMPANY</th>}
                  <th>SOURCE PLANT</th>
                  <th>CUSTOMER</th>
                  <th>MATERIAL</th>
                  <th>VEHICLE NO</th>
                  <th>CHALLAN NO</th>
                  <th>QTY</th>
                  <th>UOM</th>
                  <th style={{ textAlign:'right' }}>NET AMOUNT</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 debris movements found.</td></tr>
                    : paged.map((it, idx) => {
                        const isExp = expId === it.id;
                        return (
                          <React.Fragment key={it.id}>
                            <tr onClick={() => toggleRow(it.id)} style={{ cursor:'pointer', background:isExp?'#FFF7ED':'' }}>
                              <td style={{ textAlign:'center', padding:'0 8px' }}><window.SYChevron open={isExp}/></td>
                              <td style={{ textAlign:'center', color:'var(--txt2)', fontWeight:500 }}>{(page-1)*PER+idx+1}</td>
                              <td style={{ whiteSpace:'nowrap' }}>{window.fmtDate(it.date)}</td>
                              {isGroup && <td><span className="bdg bg-or" style={{ fontSize:10, padding:'1px 5px' }}>{Store.name('companies',it.companyId)}</span></td>}
                              <td style={{ fontWeight:500 }}>{rmcPlants.find(p=>p.id===it.sourcePlantId)?.name||'—'}</td>
                              <td style={{ fontSize:11.5 }}>{it.customerName || <span style={{ color:'var(--txt3)', fontSize:11 }}>—</span>}</td>
                              <td>{it.material||'—'}</td>
                              <td style={{ fontFamily:'var(--font)', fontSize:11 }}>{it.vehicleFull||it.vehicleNumber||'—'}</td>
                              <td style={{ fontFamily:'var(--font)', fontSize:11.5 }}>{it.challanNumber||'—'}</td>
                              <td style={{ fontWeight:600 }}>{Number(it.quantity||0).toFixed(3)}</td>
                              <td style={{ color:'var(--txt2)', fontSize:11.5 }}>{it.uom||'Ton'}</td>
                              <td style={{ textAlign:'right', fontWeight:700, color:it.netAmount?'var(--ok)':'var(--txt3)', fontSize:12 }}>
                                {it.netAmount ? dbFmtCur(it.netAmount) : '—'}
                              </td>
                              <td onClick={e => e.stopPropagation()}>
                                <div className="ra">
                                  <button className="btn btn-wh btn-sm" onClick={() => openEdit(it)}>Edit</button>
                                  <button className="btn btn-wh btn-sm" onClick={() => setDbStatement(it)}>Statement</button>
                                  <button className="btn btn-rd btn-sm" onClick={() => setDelId(it.id)}>Delete</button>
                                </div>
                              </td>
                            </tr>
                            {isExp && (
                              <tr><td colSpan={12+(isGroup?1:0)} style={{ padding:0, borderBottom:'2px solid var(--or-bdr)' }}>
                                <DebrisRowDrill it={it} rmcPlants={rmcPlants}/>
                              </td></tr>
                            )}
                          </React.Fragment>
                        );
                      })
                  }
                </tbody>
                {filtered.length>0&&(
                  <tfoot><tr style={{background:'#FFF7ED'}}>
                    <td colSpan={8+(isGroup?1:0)} style={{fontWeight:700,fontSize:11.5,color:'var(--txt2)',padding:'8px 10px',borderTop:'2px solid var(--or-bdr)'}}>TOTALS — {filtered.length} record{filtered.length!==1?'s':''}</td>
                    <td style={{fontWeight:700,color:'var(--or)',padding:'8px 10px',borderTop:'2px solid var(--or-bdr)'}}>{totalQty.toFixed(3)}</td>
                    <td style={{color:'var(--txt2)',fontSize:11,padding:'8px 10px',borderTop:'2px solid var(--or-bdr)'}}>Ton</td>
                    <td style={{textAlign:'right',fontWeight:700,color:'var(--ok)',padding:'8px 10px',borderTop:'2px solid var(--or-bdr)'}}>{dbFmtCur(totalRev)}</td>
                    <td style={{borderTop:'2px solid var(--or-bdr)'}}></td>
                  </tr></tfoot>
                )}
              </table>
            </div>
          </div>

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

      {/* ── Drill-down modals ── */}
      {plantDrill && <DbPlantModal plantId={plantDrill} allItems={baseItems} rmcPlants={rmcPlants} onClose={() => setPlantDrill(null)}/>}
      {matDrill   && <DbMaterialModal material={matDrill} allItems={baseItems} rmcPlants={rmcPlants} onClose={() => setMatDrill(null)}/>}
      {dispDrill  && <DbDisposalModal disposalType={dispDrill} allItems={baseItems} rmcPlants={rmcPlants} onClose={() => setDispDrill(null)}/>}
      {custDrill  && <DbCustomerModal customerId={custDrill.id} customerName={custDrill.name} allItems={baseItems} rmcPlants={rmcPlants} onClose={() => setCustDrill(null)}/>}
      {kpiDrill   && <DbKPIModal type={kpiDrill} allItems={baseItems} rmcPlants={rmcPlants} activePlants={activePlants} onClose={() => setKpiDrill(null)}/>}

      {/* ── Add / Edit Modal ── */}
      {modal && (
        <div className="mbg">
          <div className="mod mod-xl" style={{ maxHeight:'92vh' }}>
            <div className="mod-hd">
              <h2>{editId ? 'Edit' : 'Add'} Debris Movement</h2>
              <button className="mod-x" onClick={() => setModal(false)}>×</button>
            </div>
            <form onSubmit={handleSave}>
              <div className="mod-bd" style={{ display:'flex', flexDirection:'column', gap:0 }}>

                {/* ── Basic Information ── */}
                <DbSec label="Basic Information"/>
                <div className="fg" style={{ marginBottom:16 }}>
                  <div className="fld">
                    <label>Company <span className="req">*</span></label>
                    <window.FormSelect placeholder="— Select Company —"
                      value={form.companyId||''}
                      onChange={v => setForm(p => ({ ...p, companyId:v, customerId:'', customerName:'', materialId:'', material:'' }))}
                      options={companies.map(c => ({value:c.id,label:c.name}))}/>
                  </div>
                  <div className="fld">
                    <label>Date <span className="req">*</span></label>
                    <input className="inp" type="date" value={form.date||''} onChange={e => setF('date',e.target.value)} required/>
                  </div>
                </div>

                {/* ── Source Plant ── */}
                <DbSec label="Source Information"/>
                <div className="fld" style={{ marginBottom:16 }}>
                  <label>Source Plant <span className="req">*</span></label>
                  <window.FormSelect placeholder="— Select RMC Plant —" value={form.sourcePlantId||''} onChange={v => setF('sourcePlantId',v)} options={[
                    ...rmcPlants.filter(p => p.status === 'Active').map(p => ({value:p.id,label:p.name + ' (' + Store.name('companies',p.companyId) + ')'})),
                    ...rmcPlants.filter(p => p.status !== 'Active').map(p => ({value:p.id,label:p.name + ' (Inactive)'}))
                  ]}/>
                  {rmcPlants.length === 0 && <span style={{ fontSize:11, color:'var(--err)', marginTop:4, display:'block' }}>No plants found. Add plants in the RMC Plants module first.</span>}
                </div>

                {/* ── Commercial: Customer & Material ── */}
                <DbSec label="Commercial Information"/>
                <div className="fg" style={{ marginBottom:12 }}>
                  <div className="fld">
                    <label>Customer / Buyer <span className="req">*</span></label>
                    <window.SearchableSelect
                      options={formCustomers.map(c => ({ value:c.id, label:c.name }))}
                      value={form.customerId||''}
                      onChange={(v, label) => setForm(p => ({ ...p, customerId:v, customerName:label||'' }))}
                      placeholder="Search & select customer…"
                      noOptionsMsg="No customers — add them in Customer Master first"
                    />
                  </div>
                  <div className="fld">
                    <label>Debris Material <span className="req">*</span></label>
                    <window.SearchableSelect
                      options={allDebrisMats.map(m => ({ value:m.id, label:m.name }))}
                      value={form.materialId||''}
                      onChange={(v, label) => setForm(p => ({ ...p, materialId:v, material:label||'' }))}
                      placeholder={allDebrisMats.length === 0 ? 'No Debris materials — set Category = Debris in Material Master' : 'Search debris materials…'}
                      noOptionsMsg={allDebrisMats.length === 0 ? 'Go to Materials → set Category = Debris' : 'No match'}
                    />
                    {allDebrisMats.length === 0 && (
                      <span style={{ fontSize:10.5, color:'var(--err)', marginTop:3, display:'block' }}>
                        No materials with Category = Debris. Go to <strong>Material Master</strong> and set Category = Debris.
                      </span>
                    )}
                  </div>
                </div>

                {/* Pricing status banner */}
                {form.customerId && form.materialId && form.companyId && form.companyId !== 'group' && (
                  pricingCalc.found ? (
                    <div style={{ background:'#F0FDF4', border:'1px solid #86EFAC', borderRadius:'var(--r)', padding:'9px 14px', display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
                      <div style={{ width:7, height:7, borderRadius:'50%', background:'#16a34a', flexShrink:0 }}/>
                      <div style={{ fontSize:11.5, color:'#15803d', lineHeight:1.5 }}>
                        <strong>Rate auto-fetched from PO {pricingCalc.poNumber}</strong> — all pricing is read-only and recalculates instantly.
                      </div>
                    </div>
                  ) : (
                    <div style={{ background:'#FFF1F2', border:'1px solid #FDA4AF', borderRadius:'var(--r)', padding:'9px 14px', display:'flex', alignItems:'flex-start', gap:10, marginBottom:12 }}>
                      <div style={{ width:7, height:7, borderRadius:'50%', background:'var(--err)', flexShrink:0, marginTop:4 }}/>
                      <div style={{ fontSize:11.5, color:'var(--err)', lineHeight:1.5 }}>
                        <strong>No active price found</strong> for Company: <strong>{Store.name('companies', form.companyId)}</strong> · Customer: <strong>{form.customerName || Store.name('customers', form.customerId)}</strong> · Material: <strong>{form.material || Store.name('materials', form.materialId)}</strong>.
                        <div style={{ marginTop:3 }}>{priceDiag && priceDiag.message ? priceDiag.message : 'Create a Customer Price Order in Price Orders first.'}</div>
                        <div style={{ marginTop:3 }}>Submission is blocked until a price is available.</div>
                      </div>
                    </div>
                  )
                )}

                {/* Read-only pricing fields */}
                <div className="fg3" style={{ marginBottom:12 }}>
                  <DbROField label={`Rate (₹ / ${selectedMatUnit})`} value={pricingCalc.found ? `\u20B9 ${Number(pricingCalc.rate).toFixed(2)}` : '—'} color="var(--or)"/>
                  <DbROField label="GST %" value={pricingCalc.found ? `${pricingCalc.gstPct}%` : '—'} color="var(--txt2)"/>
                  <DbROField label="PO Reference" value={pricingCalc.poNumber || '—'} color="var(--txt3)"/>
                </div>

                {/* ── Quantity ── */}
                <DbSec label="Quantity &amp; UOM"/>
                <div className="fg3" style={{ marginBottom:12 }}>
                  <div className="fld">
                    <label>Quantity <span className="req">*</span></label>
                    <input className="inp" type="number" value={form.quantity||''} onChange={e => setF('quantity',e.target.value)} required min="0.001" step="0.001" placeholder="0.000"/>
                  </div>
                  <div className="fld">
                    <label>UOM <span className="req">*</span></label>
                    <window.FormSelect value={form.uom||'Ton'} onChange={v => setF('uom',v)} options={DB_UOMS.map(u => ({value:u,label:u}))}/>
                  </div>
                  <div className="fld">
                    <label>Challan Number</label>
                    <input className="inp" value={form.challanNumber||''} onChange={e => setF('challanNumber',e.target.value)} placeholder="CH-001"/>
                  </div>
                </div>

                {/* Auto-calculated amounts — visible when pricing is resolved and qty entered */}
                {pricingCalc.found && parseFloat(form.quantity) > 0 && (
                  <div style={{ background:'#F0FDF4', border:'1px solid #BBF7D0', borderRadius:'var(--r)', padding:'12px 16px', marginBottom:14 }}>
                    <div style={{ fontSize:10.5, fontWeight:700, color:'#166534', marginBottom:9, textTransform:'uppercase', letterSpacing:'.05em' }}>Calculated Amounts — Read Only</div>
                    <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
                      {[
                        ['Total Amount',   dbFmtCur(pricingCalc.totalAmount), 'var(--txt)', 15],
                        [`GST (${pricingCalc.gstPct}%)`, dbFmtCur(pricingCalc.gstAmount), 'var(--txt2)', 15],
                        ['Net Amount',     dbFmtCur(pricingCalc.netAmount),   'var(--ok)',  17],
                      ].map(([l,v,c,fs]) => (
                        <div key={l}>
                          <div style={{ fontSize:10, color:'var(--txt2)', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em', marginBottom:3 }}>{l}</div>
                          <div style={{ fontSize:fs, fontWeight:700, color:c, fontVariantNumeric:'tabular-nums' }}>{v}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* ── Destination ── */}
                <DbSec label="Destination Information"/>
                <div className="fg" style={{ marginBottom:14 }}>
                  <div className="fld">
                    <label>Destination Type <span className="req">*</span></label>
                    <window.FormSelect placeholder="— Select Type —" value={form.destType||''} onChange={v => setF('destType',v)} options={DEST_TYPES.map(t => ({value:t,label:t}))}/>
                    {form.destType === 'Other' && <input className="inp" style={{ marginTop:6 }} value={form.destTypeOther||''} onChange={e => setF('destTypeOther',e.target.value)} placeholder="Specify destination type…"/>}
                  </div>
                  <div className="fld">
                    <label>Destination Location</label>
                    <input className="inp" value={form.destLocation||''} onChange={e => setF('destLocation',e.target.value)} placeholder="e.g. Vasco Landfill"/>
                  </div>
                </div>

                {/* ── Transport ── */}
                <DbSec label="Transport &amp; Vehicle"/>
                <div className="fg" style={{ marginBottom:14 }}>
                  <div className="fld">
                    <label>Transporter Name <span className="req">*</span></label>
                    <window.SearchableSelect
                      options={tmActive.map(t => ({ value:t.id, label:t.name }))}
                      value={form.transporterMasterId||''}
                      onChange={(v, label) => setForm(p => ({ ...p, transporterMasterId:v, transporter:label||'', vehicleFull:'', vehicleNumber:'' }))}
                      placeholder="Search & select transporter…"
                      noOptionsMsg={tmActive.length === 0 ? 'No active transporters — add in Transporter Master first' : 'No match'}
                    />
                    {tmActive.length === 0 && <span style={{ fontSize:10.5, color:'var(--err)', 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.SearchableSelect
                      options={tmVehicles.map(v => ({ value:v.vehicleNumber, label:v.vehicleNumber+(v.vehicleType?' ('+v.vehicleType+')':'') }))}
                      value={form.vehicleFull||''}
                      onChange={v => setForm(p => ({ ...p, vehicleFull:v, vehicleNumber:v }))}
                      placeholder={!form.transporterMasterId ? 'Select a transporter first…' : tmVehicles.length === 0 ? 'No active vehicles for this transporter' : 'Search vehicle number…'}
                      noOptionsMsg={!form.transporterMasterId ? 'Select a transporter first' : 'No vehicles match'}
                      inputStyle={{ fontFamily:'var(--font)', fontWeight:600 }}
                    />
                    {form.transporterMasterId && tmVehicles.length === 0 && <span style={{ fontSize:10.5, color:'var(--warn)', marginTop:3, display:'block' }}>No active vehicles. Add vehicles in Transporter Master → Vehicles.</span>}
                  </div>
                </div>
                <div className="fld" style={{ marginBottom:8 }}>
                  <label>Transport Rate (₹/MT) <span className="req">*</span></label>
                  <input className="inp" type="number" value={form.transportRate||''} onChange={e => setF('transportRate', e.target.value)} required min="0.01" step="0.01" placeholder="e.g. 140, 175, 250, 310"/>
                  <span style={{ fontSize:10.5, color:'var(--txt2)', marginTop:3, display:'block' }}>Rate paid to transporter per metric ton — independent of customer selling rate</span>
                </div>
                {parseFloat(form.transportRate) > 0 && parseFloat(form.quantity) > 0 && (
                  <div style={{ marginBottom:14, padding:'8px 12px', background:'#EFF6FF', border:'1px solid #BFDBFE', borderRadius:6, display:'flex', gap:12, alignItems:'center', flexWrap:'wrap' }}>
                    <span style={{ fontSize:11, color:'#1E40AF', fontWeight:700 }}>Transport Cost:</span>
                    <span style={{ fontSize:14, fontWeight:700, color:'#1D4ED8' }}>{dbFmtCur((parseFloat(form.quantity)||0) * (parseFloat(form.transportRate)||0))}</span>
                    <span style={{ fontSize:11, color:'var(--txt2)' }}>{window.formatQuantity(form.quantity)} MT × ₹{parseFloat(form.transportRate).toFixed(2)}/MT</span>
                  </div>
                )}

                {/* ── Disposal ── */}
                <DbSec label="Disposal Information"/>
                <div className="fg" style={{ marginBottom:14 }}>
                  <div className="fld">
                    <label>Disposal Type <span className="req">*</span></label>
                    <window.FormSelect placeholder="— Select Disposal Type —" value={form.disposalType||''} onChange={v => setF('disposalType',v)} options={DISPOSAL_TYPES.map(t => ({value:t,label:t}))}/>
                    {form.disposalType === 'Other' && <input className="inp" style={{ marginTop:6 }} value={form.disposalTypeOther||''} onChange={e => setF('disposalTypeOther',e.target.value)} placeholder="Specify disposal type…"/>}
                  </div>
                  <div className="fld">
                    <label>Remarks</label>
                    <input className="inp" value={form.remarks||''} onChange={e => setF('remarks',e.target.value)} placeholder="Optional remarks…"/>
                  </div>
                </div>

                {/* Auto-generation notice */}
                {form.transporterMasterId && form.vehicleFull && (
                  <div style={{ background:'#F0FDF4', border:'1px solid #86EFAC', borderRadius:'var(--r)', padding:'9px 14px', display:'flex', alignItems:'center', gap:10 }}>
                    <div style={{ width:7, height:7, borderRadius:'50%', background:'#16a34a', flexShrink:0 }}/>
                    <div style={{ fontSize:11.5, color:'#15803d', lineHeight:1.5 }}>
                      <strong>Transport record will be auto-generated</strong> — this movement will appear in Transport Reports immediately upon save.
                    </div>
                  </div>
                )}
              </div>

              <div className="mod-ft">
                <button type="button" className="btn btn-wh" onClick={() => setModal(false)}>Cancel</button>
                <button type="submit" className="btn btn-or"
                  disabled={!!(form.customerId && form.materialId && form.companyId && form.companyId !== 'group' && !pricingCalc.found)}>
                  {editId ? 'Update Movement' : 'Create Movement'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {delId && <window.Confirm onOk={handleDelete} onCancel={() => setDelId(null)}/>}
      {dbStatement && <window.DebrisMovementStatement movement={dbStatement} onClose={() => setDbStatement(null)} session={session} />}
    </div>
  );
}
window.DebrisMovementPage = DebrisMovementPage;
