// OM Group ERP — Centralized Statement Engine v1
// Single source of truth for all print/PDF statements.
// Exports: StatementOverlay, DocFooter, SalesOrderStatement,
//          PurchaseBillStatement, InternalTransferStatement,
//          DebrisMovementStatement, TransportSettlementStatement, DieselStatement

// ── Print CSS (injected once) ─────────────────────────────────────────────
(function injectSECSS() {
  if (document.getElementById('om-se-css')) return;
  const s = document.createElement('style');
  s.id = 'om-se-css';
  s.textContent = `
    .se-overlay{position:fixed;inset:0;background:#5A5A5A;z-index:20000;overflow:auto;padding:24px 16px;}
    .se-toolbar{max-width:830px;margin:0 auto 12px;display:flex;align-items:center;gap:8px;}
    .se-toolbar-title{font-size:13px;font-weight:600;color:#fff;margin-right:auto;}
    .se-page{max-width:830px;margin:0 auto;background:#fff;padding:44px 48px;
      font-family:'Inter',Arial,sans-serif;color:#111;font-size:12px;line-height:1.55;
      box-shadow:0 8px 32px rgba(0,0,0,.25);}
    .se-sec{font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;
      color:#F97316;margin:0 0 7px;padding-bottom:5px;border-bottom:2px solid #FEF3E8;}
    .se-block{margin-bottom:18px;}
    .se-g2{display:grid;grid-template-columns:1fr 1fr;gap:22px;margin-bottom:18px;}
    .se-g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:18px;}
    .se-kv{display:flex;justify-content:space-between;padding:3px 0;
      border-bottom:1px solid #F3F4F6;font-size:11.5px;gap:8px;}
    .se-kl{color:#888;flex-shrink:0;line-height:1.4;}
    .se-kv2{font-weight:500;text-align:right;color:#111;word-break:break-word;
      max-width:62%;line-height:1.4;}
    .se-kv2.b{font-weight:700;} .se-kv2.or{color:#F97316;} .se-kv2.ok{color:#16A34A;} .se-kv2.rd{color:#DC2626;}
    .se-tbl{width:100%;border-collapse:collapse;font-size:11px;margin-bottom:16px;}
    .se-tbl th{background:#F9FAFB;text-align:left;padding:6px 7px;font-size:9.5px;
      text-transform:uppercase;letter-spacing:.04em;border:1px solid #E5E7EB;font-weight:700;color:#555;}
    .se-tbl td{padding:5px 7px;border:1px solid #E5E7EB;vertical-align:middle;}
    .se-tbl tr:nth-child(even) td{background:#FAFAFA;}
    .se-tbl tfoot td{background:#FFF7ED;font-weight:700;border-top:2px solid #F97316;}
    .se-trow{display:flex;justify-content:space-between;padding:4px 0;
      border-bottom:1px dashed #E5E7EB;font-size:12.5px;gap:8px;}
    .se-tfinal{border-top:2px solid #111!important;margin-top:4px;padding-top:6px!important;
      font-weight:800!important;font-size:13.5px!important;border-bottom:none!important;}
    .se-party{font-weight:700;font-size:13px;margin-bottom:4px;}
    .se-party-sub{font-size:11px;color:#555;line-height:1.6;}
    .se-footer{margin-top:32px;padding-top:12px;border-top:1px solid #E5E7EB;
      font-size:9.5px;color:#999;text-align:center;line-height:1.65;}
    .se-split-card{border-radius:8px;padding:12px 14px;}
    @media print{
      body *{visibility:hidden!important;}
      .se-page,.se-page *{visibility:visible!important;}
      .se-page{position:fixed;inset:0;box-shadow:none;padding:28px 32px;max-width:none;}
      .se-overlay,.se-toolbar{display:none!important;}
    }
  `;
  document.head.appendChild(s);
}());

// ── Helper: Key-Value row ─────────────────────────────────────────────────
function SEKv({ label, value, cls }) {
  return (
    <div className="se-kv">
      <span className="se-kl">{label}</span>
      <span className={`se-kv2${cls ? ' ' + cls : ''}`}>{value || '—'}</span>
    </div>
  );
}

// ── Helper: status badge ──────────────────────────────────────────────────
function seBadge(val) {
  if (!val) return '—';
  const v = String(val).toLowerCase();
  const c = v.includes('complet') || v.includes('paid') || v.includes('deliver') || v.includes('active') ? '#DCFCE7:#15803D'
    : v.includes('partial') || v.includes('pending') ? '#FEF9C3:#92400E'
    : v.includes('cancel') ? '#FEE2E2:#991B1B'
    : v.includes('transit') || v.includes('progress') ? '#DBEAFE:#1E40AF'
    : '#F4F3F1:#57534E';
  const [bg, color] = c.split(':');
  return <span style={{ background: bg, color, borderRadius: 99, padding: '2px 9px', fontSize: 10, fontWeight: 700 }}>{val}</span>;
}

// ── Print Overlay Shell ───────────────────────────────────────────────────
function StatementOverlay({ onClose, children, title }) {
  return (
    <div className="se-overlay">
      <div className="se-toolbar">
        <span className="se-toolbar-title">{title}</span>
        <button className="btn btn-wh" onClick={onClose}>Close</button>
        <button className="btn btn-or" onClick={() => window.print()}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/>
            <rect x="6" y="14" width="12" height="8"/>
          </svg>
          Print / Save PDF
        </button>
      </div>
      <div className="se-page">{children}</div>
    </div>
  );
}

// ── Doc Footer ────────────────────────────────────────────────────────────
function DocFooter({ user, docId }) {
  return (
    <div className="se-footer">
      <div>Generated on {new Date().toLocaleString('en-IN')} · By {user || 'System'} · OM Group ERP v36</div>
      {docId && <div>Document Ref: {String(docId).slice(0, 8).toUpperCase()}</div>}
      <div style={{ marginTop: 2, fontStyle: 'italic' }}>Confidential — System-generated document. For authorised use only.</div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 1. SALES ORDER STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function SalesOrderStatement({ order, onClose, session }) {
  const o = order;
  const customer = Store.byId('customers', o.customerId) || {};
  const rows = o.items && o.items.length ? o.items : [{
    material: o.material || o.materialName, quantity: o.quantity,
    uom: o.uom, ratePerTon: o.rate || o.ratePerTon,
    gst: o.gstPct || o.gst || 0,
    amount: o.subtotal || (parseFloat(o.quantity) || 0) * (parseFloat(o.rate || o.ratePerTon) || 0),
  }];
  const sub = rows.reduce((s, r) => s + (parseFloat(r.amount) || (parseFloat(r.quantity) || 0) * (parseFloat(r.ratePerTon || r.rate) || 0)), 0);
  const gstTotal = rows.reduce((s, r) => {
    const a = parseFloat(r.amount) || (parseFloat(r.quantity) || 0) * (parseFloat(r.ratePerTon || r.rate) || 0);
    return s + a * (parseFloat(r.gst || o.gstPct || 0) / 100);
  }, 0);

  return (
    <StatementOverlay onClose={onClose} title="Sales Order Statement">
      <window.DocHeader companyId={o.companyId} docTitle="Sales Order Statement" docMeta={[
        ['Order / Challan', o.challanNumber || (o.id || '').slice(0, 8).toUpperCase()],
        ['Date', window.fmtDate(o.date)],
        ['Status', o.status || '—'],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g2">
        <div className="se-block">
          <div className="se-sec">Bill To — Customer</div>
          <div className="se-party">{customer.name || o.customerName || '—'}</div>
          {customer.gst && <div className="se-party-sub">GST: {customer.gst}</div>}
          {customer.address && <div className="se-party-sub">{customer.address}</div>}
          {customer.mobile && <div className="se-party-sub">Phone: {customer.mobile}</div>}
        </div>
        <div className="se-block">
          <div className="se-sec">Delivery & Transport</div>
          <SEKv label="Site / Delivery" value={o.deliveryAddress || o.site || '—'} />
          <SEKv label="Vehicle No." value={o.vehicleNumber || o.vehicle || '—'} />
          <SEKv label="Transporter" value={o.transporterName || '—'} />
          <SEKv label="Challan No." value={o.challanNumber || '—'} />
          <SEKv label="Crusher" value={o.crusherName || '—'} />
        </div>
      </div>

      <div className="se-sec">Material Details</div>
      <table className="se-tbl">
        <thead><tr>
          <th>#</th><th>Material</th>
          <th style={{ textAlign: 'right' }}>Qty</th><th>UOM</th>
          <th style={{ textAlign: 'right' }}>Rate (₹)</th>
          <th style={{ textAlign: 'right' }}>Amount (₹)</th>
          <th style={{ textAlign: 'right' }}>GST%</th>
          <th style={{ textAlign: 'right' }}>Total (₹)</th>
        </tr></thead>
        <tbody>
          {rows.map((r, i) => {
            const a = parseFloat(r.amount) || (parseFloat(r.quantity) || 0) * (parseFloat(r.ratePerTon || r.rate) || 0);
            const gp = parseFloat(r.gst || o.gstPct || 0);
            return (
              <tr key={i}>
                <td>{i + 1}</td>
                <td style={{ fontWeight: 600 }}>{r.material || r.materialName || '—'}</td>
                <td style={{ textAlign: 'right' }}>{Number(r.quantity || 0).toFixed(3)}</td>
                <td>{r.uom || 'Ton'}</td>
                <td style={{ textAlign: 'right' }}>{window.fmtCur(r.ratePerTon || r.rate)}</td>
                <td style={{ textAlign: 'right' }}>{window.fmtCur(a)}</td>
                <td style={{ textAlign: 'right' }}>{gp}%</td>
                <td style={{ textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(a * (1 + gp / 100))}</td>
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={5} style={{ textAlign: 'right' }}>Grand Total</td>
            <td style={{ textAlign: 'right' }}>{window.fmtCur(sub)}</td>
            <td></td>
            <td style={{ textAlign: 'right', color: '#F97316' }}>{window.fmtCur(window.gAmt(o))}</td>
          </tr>
        </tfoot>
      </table>

      <div className="se-g2">
        <div>
          <div className="se-sec">Financial Summary</div>
          <div className="se-trow"><span>Subtotal (Pre-GST)</span><strong>{window.fmtCur(sub)}</strong></div>
          <div className="se-trow"><span>GST Amount</span><strong>{window.fmtCur(gstTotal)}</strong></div>
          <div className="se-trow"><span>Payment Status</span><span>{seBadge(o.paymentStatus || o.status)}</span></div>
          <div className="se-trow se-tfinal"><span>Grand Total</span><span style={{ color: '#F97316' }}>{window.fmtCur(window.gAmt(o))}</span></div>
        </div>
        <div>
          <div className="se-sec">Audit Information</div>
          <SEKv label="Transaction ID" value={(o.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Company" value={Store.name('companies', o.companyId) || '—'} />
          <SEKv label="Created By" value={o.createdBy || (session && session.name) || '—'} />
          <SEKv label="Order Date" value={window.fmtDate(o.date)} />
          <SEKv label="Status" value={o.status} />
          {o.remarks && <SEKv label="Remarks" value={o.remarks} />}
        </div>
      </div>
      <DocFooter user={session && session.name} docId={o.id} />
    </StatementOverlay>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 2. PURCHASE BILL STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function PurchaseBillStatement({ purchase, onClose, session }) {
  const p = purchase;
  const vendor = Store.byId('vendors', p.vendorId) || {};
  const rows = p.items && p.items.length ? p.items : [{
    material: p.material || p.materialName, quantity: p.quantity,
    uom: p.uom || 'Ton', ratePerTon: p.rate || p.ratePerTon,
    gstPct: p.gstPct || p.gst || 0, subtotal: p.sub || p.subtotal,
    gstAmount: p.gstAmount || 0,
  }];
  const sub = window.gSub(p);
  const gstAmt = window.gGst(p);
  const total = window.gAmt(p);
  const diesel = parseFloat(p.dieselDeduction) || 0;

  return (
    <StatementOverlay onClose={onClose} title="Purchase Bill Statement">
      <window.DocHeader companyId={p.companyId} docTitle="Purchase Bill Statement" docMeta={[
        ['Challan No.', p.challanNumber || '—'],
        ['Bill No.', p.billNumber || '—'],
        ['Date', window.fmtDate(p.date)],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g2">
        <div className="se-block">
          <div className="se-sec">Vendor</div>
          <div className="se-party">{vendor.name || p.vendorName || Store.name('vendors', p.vendorId) || '—'}</div>
          {vendor.gst && <div className="se-party-sub">GST: {vendor.gst}</div>}
          {vendor.address && <div className="se-party-sub" style={{ maxWidth: 260 }}>{vendor.address}</div>}
          {vendor.mobile && <div className="se-party-sub">Phone: {vendor.mobile}</div>}
        </div>
        <div className="se-block">
          <div className="se-sec">Transport & Logistics</div>
          <SEKv label="Vehicle No." value={p.vehicleFull || p.vehicleNumber || p.vehicle || '—'} />
          <SEKv label="Transporter" value={p.transporterName || '—'} />
          <SEKv label="Pickup / Crusher" value={p.crusherName || p.pickupLocation || '—'} />
          <SEKv label="Royalty Pass" value={p.royaltyPass || '—'} />
          <SEKv label="Challan No." value={p.challanNumber || '—'} />
        </div>
      </div>

      <div className="se-sec">Purchase Details</div>
      <table className="se-tbl" style={{ marginBottom: 18 }}>
        <thead><tr>
          <th>Material</th><th>Company</th>
          <th style={{ textAlign: 'right' }}>Qty</th><th>UOM</th>
          <th style={{ textAlign: 'right' }}>Rate (₹)</th>
          <th style={{ textAlign: 'right' }}>Subtotal (₹)</th>
          <th style={{ textAlign: 'right' }}>GST%</th>
          <th style={{ textAlign: 'right' }}>Total (₹)</th>
        </tr></thead>
        <tbody>
          {rows.map((r, i) => {
            const rSub = parseFloat(r.subtotal) || (parseFloat(r.quantity) || 0) * (parseFloat(r.ratePerTon) || 0);
            const rGst = rSub * (parseFloat(r.gstPct || p.gstPct || p.gst || 0) / 100); // always fresh — never trust legacy-rounded stored gstAmount
            return (
              <tr key={i}>
                <td style={{ fontWeight: 600 }}>{r.material || r.materialName || Store.name('materials', r.materialId) || '—'}</td>
                <td style={{ fontSize: 10.5 }}>{Store.name('companies', p.companyId) || '—'}</td>
                <td style={{ textAlign: 'right' }}>{Number(r.quantity || 0).toFixed(3)}</td>
                <td>{r.uom || 'Ton'}</td>
                <td style={{ textAlign: 'right' }}>{window.fmtCur(r.ratePerTon)}</td>
                <td style={{ textAlign: 'right' }}>{window.fmtCur(rSub)}</td>
                <td style={{ textAlign: 'right' }}>{r.gstPct || p.gstPct || p.gst || 0}%</td>
                <td style={{ textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(rSub + rGst)}</td>
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={5} style={{ textAlign: 'right' }}>Grand Total</td>
            <td style={{ textAlign: 'right' }}>{window.fmtCur(sub)}</td>
            <td></td>
            <td style={{ textAlign: 'right', color: '#F97316' }}>{window.fmtCur(total)}</td>
          </tr>
        </tfoot>
      </table>

      <div className="se-g2">
        <div>
          <div className="se-sec">Financial Summary</div>
          <div className="se-trow"><span>Purchase Subtotal</span><strong>{window.fmtCur(sub)}</strong></div>
          <div className="se-trow"><span>GST Amount</span><strong>{window.fmtCur(gstAmt)}</strong></div>
          <div className="se-trow"><span>Gross Purchase Value</span><strong>{window.fmtCur(total)}</strong></div>
          {diesel > 0 && <div className="se-trow"><span>Diesel Deduction</span><strong style={{ color: '#B45309' }}>− {window.fmtCur(diesel)}</strong></div>}
          <div className="se-trow se-tfinal"><span>Net Payable</span><span style={{ color: '#F97316' }}>{window.fmtCur(total - diesel)}</span></div>
        </div>
        <div>
          <div className="se-sec">Audit & Settlement</div>
          <SEKv label="Transaction ID" value={(p.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Company" value={Store.name('companies', p.companyId) || '—'} />
          <SEKv label="Settlement Status" value={p.vendorSettlementStatus || p.settlementStatus || 'Unsettled'} />
          <SEKv label="Status" value={p.status} />
          {p.notes && <SEKv label="Notes" value={p.notes} />}
        </div>
      </div>
      <DocFooter user={session && session.name} docId={p.id} />
    </StatementOverlay>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 3. INTERNAL TRANSFER STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function InternalTransferStatement({ transfer, onClose, session }) {
  const t = transfer;
  const fromCo = Store.name('companies', t.fromCompanyId) || t.fromCompany || '—';
  const toCo = Store.name('companies', t.toCompanyId) || t.toCompany || '—';
  const rows = t.items && t.items.length ? t.items : [{
    material: t.material || t.materialName, quantity: t.quantity,
    uom: t.uom || 'Ton', transferRate: t.transferRate || t.rate,
    lineAmount: t.totalValue || t.lineAmount || 0,
  }];

  return (
    <StatementOverlay onClose={onClose} title="Internal Transfer Statement">
      <window.DocHeader companyId={t.fromCompanyId} docTitle="Internal Transfer Statement" docMeta={[
        ['Ref No.', (t.id || '').slice(0, 8).toUpperCase()],
        ['Transfer Date', window.fmtDate(t.date || t.transferDate)],
        ['Status', t.status || '—'],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g2">
        <div className="se-block">
          <div className="se-sec">Source</div>
          <SEKv label="Company" value={fromCo} cls="b" />
          <SEKv label="Stockyard" value={t.fromStockyardName || t.fromStockyard || '—'} />
          <SEKv label="Location" value={t.fromLocation || '—'} />
        </div>
        <div className="se-block">
          <div className="se-sec">Destination</div>
          <SEKv label="Company" value={toCo} cls="b" />
          <SEKv label="Stockyard" value={t.toStockyardName || t.toStockyard || '—'} />
          <SEKv label="Location" value={t.toLocation || '—'} />
        </div>
      </div>

      <div className="se-sec">Transfer Details</div>
      <table className="se-tbl" style={{ marginBottom: 18 }}>
        <thead><tr>
          <th>Material</th>
          <th style={{ textAlign: 'right' }}>Qty</th><th>UOM</th>
          <th style={{ textAlign: 'right' }}>Rate (₹)</th>
          <th style={{ textAlign: 'right' }}>Line Amount (₹)</th>
          <th>Vehicle No.</th><th>Driver</th><th>Challan No.</th>
        </tr></thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i}>
              <td style={{ fontWeight: 600 }}>{r.material || r.materialName || Store.name('materials', r.materialId) || '—'}</td>
              <td style={{ textAlign: 'right' }}>{Number(r.quantity || 0).toFixed(3)}</td>
              <td>{r.uom || 'Ton'}</td>
              <td style={{ textAlign: 'right' }}>{window.fmtCur(r.transferRate || r.rate || 0)}</td>
              <td style={{ textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(r.lineAmount || r.totalValue || 0)}</td>
              <td>{t.vehicleNumber || t.vehicle || '—'}</td>
              <td>{t.driverName || t.driver || '—'}</td>
              <td>{t.challanNumber || '—'}</td>
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={3} style={{ textAlign: 'right' }}>Total Transfer Value</td>
            <td></td>
            <td style={{ textAlign: 'right', color: '#F97316' }}>{window.fmtCur(t.totalValue || rows.reduce((s, r) => s + (parseFloat(r.lineAmount || r.totalValue) || 0), 0))}</td>
            <td colSpan={3}></td>
          </tr>
        </tfoot>
      </table>

      <div className="se-g2">
        <div>
          <div className="se-sec">Transfer Info</div>
          <SEKv label="Transfer Type" value={t._autoGenerated ? 'Auto-Generated' : 'Manual'} />
          <SEKv label="Internal Ref." value={t.internalRef || (t.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Transfer Value" value={window.fmtCur(t.totalValue)} cls="or" />
          <SEKv label="Status" value={t.status} />
          {t.approvedBy && <SEKv label="Approved By" value={t.approvedBy} />}
        </div>
        <div>
          <div className="se-sec">Audit Information</div>
          <SEKv label="Transaction ID" value={(t.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Source Company" value={fromCo} />
          <SEKv label="Dest. Company" value={toCo} />
          <SEKv label="Created By" value={t.createdBy || (session && session.name) || '—'} />
          {t.remarks && <SEKv label="Remarks" value={t.remarks} />}
        </div>
      </div>
      <DocFooter user={session && session.name} docId={t.id} />
    </StatementOverlay>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 4. DEBRIS MOVEMENT STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function DebrisMovementStatement({ movement, onClose, session }) {
  const m = movement;
  const plant = Store.byId('rmcPlants', m.sourcePlantId) || {};
  const netAmt = parseFloat(m.netAmount) || 0;
  const gstPct = parseFloat(m.gstPct) || 0;
  const gstAmt = netAmt * (gstPct / 100);
  const total = netAmt + gstAmt;

  return (
    <StatementOverlay onClose={onClose} title="Debris Movement Statement">
      <window.DocHeader companyId={m.companyId} docTitle="Debris Movement Statement" docMeta={[
        ['Movement ID', (m.id || '').slice(0, 8).toUpperCase()],
        ['Date', window.fmtDate(m.date)],
        ['Status', m.status || 'Completed'],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g2">
        <div className="se-block">
          <div className="se-sec">Source (Plant)</div>
          <div className="se-party">{plant.name || '—'}</div>
          {plant.location && <div className="se-party-sub">{plant.location}</div>}
          <SEKv label="Company" value={Store.name('companies', m.companyId) || '—'} />
          <SEKv label="Customer" value={m.customerName || '—'} />
        </div>
        <div className="se-block">
          <div className="se-sec">Destination & Disposal</div>
          <SEKv label="Destination Type" value={m.destType || '—'} cls="b" />
          <SEKv label="Destination Location" value={m.destLocation || '—'} />
          <SEKv label="Disposal Type" value={m.disposalType || '—'} />
          {m.remarks && <SEKv label="Remarks" value={m.remarks} />}
        </div>
      </div>

      <div className="se-sec">Movement Details</div>
      <table className="se-tbl" style={{ marginBottom: 18 }}>
        <thead><tr>
          <th>Material</th>
          <th style={{ textAlign: 'right' }}>Qty</th><th>UOM</th>
          <th>Vehicle No.</th><th>Driver</th><th>Challan No.</th>
          <th style={{ textAlign: 'right' }}>Rate (₹)</th>
          <th style={{ textAlign: 'right' }}>Net Amount (₹)</th>
        </tr></thead>
        <tbody>
          <tr>
            <td style={{ fontWeight: 600 }}>{m.material || '—'}</td>
            <td style={{ textAlign: 'right' }}>{Number(m.quantity || 0).toFixed(3)}</td>
            <td>{m.uom || 'Ton'}</td>
            <td>{m.vehicleNumber || m.vehicle || '—'}</td>
            <td>{m.driverName || m.driver || '—'}</td>
            <td>{m.challanNumber || '—'}</td>
            <td style={{ textAlign: 'right' }}>{window.fmtCur(m.rate || 0)}</td>
            <td style={{ textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(netAmt)}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={6} style={{ textAlign: 'right' }}>GST ({gstPct}%)</td>
            <td colSpan={2} style={{ textAlign: 'right' }}>{window.fmtCur(gstAmt)}</td>
          </tr>
          <tr>
            <td colSpan={6} style={{ textAlign: 'right', color: '#F97316' }}>Total with GST</td>
            <td colSpan={2} style={{ textAlign: 'right', color: '#F97316' }}>{window.fmtCur(total)}</td>
          </tr>
        </tfoot>
      </table>

      <div className="se-g2">
        <div>
          <div className="se-sec">Financial Summary</div>
          <div className="se-trow"><span>Net Amount</span><strong>{window.fmtCur(netAmt)}</strong></div>
          <div className="se-trow"><span>GST ({gstPct}%)</span><strong>{window.fmtCur(gstAmt)}</strong></div>
          <div className="se-trow se-tfinal"><span>Total</span><span style={{ color: '#F97316' }}>{window.fmtCur(total)}</span></div>
        </div>
        <div>
          <div className="se-sec">Audit Information</div>
          <SEKv label="Movement ID" value={(m.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Company" value={Store.name('companies', m.companyId) || '—'} />
          <SEKv label="Created By" value={m.createdBy || (session && session.name) || '—'} />
          <SEKv label="Status" value={m.status || 'Completed'} />
        </div>
      </div>
      <DocFooter user={session && session.name} docId={m.id} />
    </StatementOverlay>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 5. TRANSPORT SETTLEMENT STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function TransportSettlementStatement({ settlement, onClose, session }) {
  const s = settlement;
  const tripRows = s.challanRows || s.tripRows || [];

  return (
    <StatementOverlay onClose={onClose} title="Transport Settlement Statement">
      <window.DocHeader companyId={s.paidThroughCompanyId || s.companyId} docTitle="Transport Settlement Statement" docMeta={[
        ['Settlement No.', (s.id || '').slice(0, 8).toUpperCase()],
        ['Period', window.fmtDate(s.periodFrom) + ' – ' + window.fmtDate(s.periodTo)],
        ['Status', s.status || '—'],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g2">
        <div className="se-block">
          <div className="se-sec">Transporter</div>
          <div className="se-party">{s.transporterName || '—'}</div>
          {s.transporterGst && <div className="se-party-sub">GST: {s.transporterGst}</div>}
          {s.transporterAddress && <div className="se-party-sub">{s.transporterAddress}</div>}
        </div>
        <div className="se-block">
          <div className="se-sec">Settlement Period</div>
          <SEKv label="Period From" value={window.fmtDate(s.periodFrom)} />
          <SEKv label="Period To" value={window.fmtDate(s.periodTo)} />
          <SEKv label="Total Trips" value={String(s.tripCount || 0)} />
          <SEKv label="Settlement Date" value={s.settlementDate ? window.fmtDate(s.settlementDate) : '—'} />
          <SEKv label="Paid Through" value={s.paidThroughCompanyName || Store.name('companies', s.paidThroughCompanyId) || '—'} />
        </div>
      </div>

      {tripRows.length > 0 && (
        <div className="se-block">
          <div className="se-sec">Trip Details ({tripRows.length} trips)</div>
          <table className="se-tbl">
            <thead><tr>
              <th>Date</th><th>Challan</th><th>Vehicle</th><th>Material</th>
              <th style={{ textAlign: 'right' }}>Qty</th>
              <th style={{ textAlign: 'right' }}>Freight (₹)</th>
              <th style={{ textAlign: 'right' }}>Diesel Ded. (₹)</th>
              <th style={{ textAlign: 'right' }}>Net (₹)</th>
            </tr></thead>
            <tbody>
              {tripRows.map((r, i) => {
                const fr = parseFloat(r.freight || r.grossFreight || 0);
                const dd = parseFloat(r.dieselDeduction || 0);
                return (
                  <tr key={i}>
                    <td>{window.fmtDate(r.date)}</td>
                    <td>{r.challanNumber || r.challan || '—'}</td>
                    <td>{r.vehicleFull || r.vehicle || '—'}</td>
                    <td>{r.material || '—'}</td>
                    <td style={{ textAlign: 'right' }}>{Number(r.quantity || 0).toFixed(2)}</td>
                    <td style={{ textAlign: 'right' }}>{window.fmtCur(fr)}</td>
                    <td style={{ textAlign: 'right' }}>{window.fmtCur(dd)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 600 }}>{window.fmtCur(fr - dd)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      <div className="se-g2">
        <div>
          <div className="se-sec">Financial Summary</div>
          <div className="se-trow"><span>Gross Freight</span><strong style={{ color: '#16A34A' }}>{window.fmtCur(s.grossFreight || 0)}</strong></div>
          <div className="se-trow"><span>Diesel Deduction</span><strong style={{ color: '#B45309' }}>− {window.fmtCur(s.dieselDeduction || 0)}</strong></div>
          {(s.otherDeductions || s.totalDeductions - s.dieselDeduction || 0) > 0 &&
            <div className="se-trow"><span>Other Deductions</span><strong style={{ color: '#DC2626' }}>− {window.fmtCur(Math.max(0, (s.totalDeductions || 0) - (s.dieselDeduction || 0)))}</strong></div>}
          <div className="se-trow se-tfinal"><span>Net Payable</span><span style={{ color: '#F97316' }}>{window.fmtCur(s.netPayable || 0)}</span></div>
        </div>
        <div>
          <div className="se-sec">Payment Details</div>
          {(s.payments || []).length === 0
            ? <div style={{ fontSize: 11, color: '#999', fontStyle: 'italic', padding: '6px 0' }}>No payments recorded</div>
            : (s.payments || []).map((p, i) => (
              <div key={i} className="se-trow">
                <span style={{ fontSize: 11 }}>{window.fmtDate(p.date)} · {p.mode}{p.reference ? ' · ' + p.reference : ''}</span>
                <strong>{window.fmtCur(p.amount)}</strong>
              </div>
            ))}
          <div className="se-trow" style={{ marginTop: 4 }}><span>Amount Paid</span><strong style={{ color: '#16A34A' }}>{window.fmtCur(s.amountPaid || 0)}</strong></div>
          <div className="se-trow se-tfinal"><span>Outstanding Balance</span><span style={{ color: (s.outstandingBalance || 0) > 0 ? '#DC2626' : '#16A34A' }}>{window.fmtCur(s.outstandingBalance || 0)}</span></div>
        </div>
      </div>
      {s.notes && <div style={{ marginTop: 16, fontSize: 11, color: '#555' }}><strong>Notes:</strong> {s.notes}</div>}
      <DocFooter user={session && session.name} docId={s.id} />
    </StatementOverlay>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// 6. DIESEL ALLOCATION STATEMENT
// ═══════════════════════════════════════════════════════════════════════════
function DieselStatement({ record, onClose, session }) {
  const d = record;
  const allocRole = d.dieselAllocRole || 'Transport';
  const litres = parseFloat(d.litres) || 0;
  const billRate = parseFloat(d.ratePerLitre || d.billRate || d.rate) || 0;
  const actualCost = parseFloat(d.amount || d.actualCost) || litres * billRate;
  const transportDed = parseFloat(d.deductionAmount || d.transportAllocAmount || d.transporterDeduction) || 0;
  const vendorAlloc = parseFloat(d.vendorAllocAmount) || 0;

  return (
    <StatementOverlay onClose={onClose} title="Diesel Allocation Statement">
      <window.DocHeader companyId={d.companyId} docTitle="Diesel Allocation Statement" docMeta={[
        ['Bill No.', d.billNumber || '—'],
        ['Challan No.', d.challanNumber || '—'],
        ['Date', window.fmtDate(d.date || d.periodStart)],
        ['Print Date', new Date().toLocaleDateString('en-IN')],
      ]} />

      <div className="se-g3">
        <div className="se-block">
          <div className="se-sec">Diesel Source</div>
          <SEKv label="Source" value={d.dieselSource || d.source || '—'} cls="b" />
          <SEKv label="Bill No." value={d.billNumber || '—'} />
          <SEKv label="Challan No." value={d.challanNumber || '—'} />
        </div>
        <div className="se-block">
          <div className="se-sec">Vehicle & Party</div>
          <SEKv label="Vehicle No." value={d.vehicleNumber || d.vehicle || '—'} cls="b" />
          <SEKv label="Transporter" value={d.transporterName || Store.name('transporterMaster', d.transporterId) || '—'} />
          <SEKv label="Vendor" value={d.vendorName || Store.name('vendors', d.vendorId) || '—'} />
        </div>
        <div className="se-block">
          <div className="se-sec">Allocation</div>
          <SEKv label="Allocation Type" value={allocRole} cls="b" />
          <SEKv label="Quantity" value={window.formatQuantity(litres) + ' L'} />
          <SEKv label="Bill Rate" value={'₹' + billRate.toFixed(2) + '/L'} />
        </div>
      </div>

      <div className="se-sec">Financial Details</div>
      <table className="se-tbl" style={{ marginBottom: 18 }}>
        <thead><tr>
          <th>Qty (L)</th>
          <th style={{ textAlign: 'right' }}>Bill Rate (₹/L)</th>
          <th style={{ textAlign: 'right' }}>Actual Fuel Cost (₹)</th>
          <th style={{ textAlign: 'right' }}>Margin (₹/L)</th>
          <th style={{ textAlign: 'right' }}>Transport Deduction (₹)</th>
          <th style={{ textAlign: 'right' }}>Vendor Allocation (₹)</th>
        </tr></thead>
        <tbody>
          <tr>
            <td style={{ fontWeight: 600 }}>{window.formatQuantity(litres)} L</td>
            <td style={{ textAlign: 'right' }}>{window.fmtCur(billRate)}</td>
            <td style={{ textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(actualCost)}</td>
            <td style={{ textAlign: 'right', color: '#B45309' }}>{window.fmtCur(d.marginPerLitre || d.margin || 0)}</td>
            <td style={{ textAlign: 'right', color: '#DC2626' }}>{window.fmtCur(transportDed)}</td>
            <td style={{ textAlign: 'right', color: '#7C3AED' }}>{window.fmtCur(vendorAlloc)}</td>
          </tr>
        </tbody>
      </table>

      {allocRole === 'Split' && (
        <div className="se-g2" style={{ marginBottom: 18 }}>
          <div className="se-split-card" style={{ background: '#F0F9FF', border: '1px solid #BAE6FD' }}>
            <div style={{ fontWeight: 700, fontSize: 10.5, color: '#0369A1', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.04em' }}>Transport Recovery</div>
            <SEKv label="Transport Deduction" value={window.fmtCur(transportDed)} />
            <SEKv label="Settlement Ref." value={d.allocTransportSettlementRef || '—'} />
            <SEKv label="Status" value={d.allocTransportStatus || 'Pending'} />
          </div>
          <div className="se-split-card" style={{ background: '#F5F3FF', border: '1px solid #C4B5FD' }}>
            <div style={{ fontWeight: 700, fontSize: 10.5, color: '#6D28D9', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.04em' }}>Vendor Recovery</div>
            <SEKv label="Vendor Allocation" value={window.fmtCur(vendorAlloc)} />
            <SEKv label="Settlement Ref." value={d.allocVendorSettlementRef || '—'} />
            <SEKv label="Status" value={d.allocVendorStatus || 'Pending'} />
          </div>
        </div>
      )}

      <div className="se-g2">
        <div>
          <div className="se-sec">Financial Summary</div>
          <div className="se-trow"><span>Actual Fuel Cost</span><strong>{window.fmtCur(actualCost)}</strong></div>
          <div className="se-trow"><span>Transport Deduction</span><strong style={{ color: '#DC2626' }}>{window.fmtCur(transportDed)}</strong></div>
          {vendorAlloc > 0 && <div className="se-trow"><span>Vendor Allocation</span><strong style={{ color: '#7C3AED' }}>{window.fmtCur(vendorAlloc)}</strong></div>}
          <div className="se-trow se-tfinal"><span>Total Deduction</span><span style={{ color: '#F97316' }}>{window.fmtCur(transportDed + vendorAlloc)}</span></div>
        </div>
        <div>
          <div className="se-sec">Audit Information</div>
          <SEKv label="Diesel Entry ID" value={(d.id || '').slice(0, 8).toUpperCase()} cls="b" />
          <SEKv label="Allocation Type" value={allocRole} />
          <SEKv label="Company" value={Store.name('companies', d.companyId) || '—'} />
          <SEKv label="Source Module" value="Diesel Allocation" />
          {d.remarks && <SEKv label="Remarks" value={d.remarks} />}
        </div>
      </div>
      <DocFooter user={session && session.name} docId={d.id} />
    </StatementOverlay>
  );
}

// ── Export all ────────────────────────────────────────────────────────────
Object.assign(window, {
  StatementOverlay,
  DocFooter,
  SalesOrderStatement,
  PurchaseBillStatement,
  InternalTransferStatement,
  DebrisMovementStatement,
  TransportSettlementStatement,
  DieselStatement,
});
