// Vendor Ledger tab — v36: Full drill-down, CHALLAN NO. column, aligned tfoot
const { useState: vlSt, useMemo: vlMemo } = React;

// ── Local drill-down UI helpers ──────────────────────────────────────────────
const VlKV = function({ label, value, mono, bold, color }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, paddingBottom: 4, borderBottom: '1px solid rgba(0,0,0,.04)', fontSize: 11.5, gap: 8 }}>
      <span style={{ color: 'var(--txt2)', flexShrink: 0, lineHeight: 1.4 }}>{label}</span>
      <span style={{ fontWeight: bold ? 700 : 500, fontFamily: mono ? 'monospace' : 'var(--font)', color: color || 'var(--txt)', textAlign: 'right' }}>{value != null && value !== '' ? value : '—'}</span>
    </div>
  );
};

const VlSection = function({ title, color, children, bg }) {
  const c = color || 'var(--or)';
  return (
    <div style={{ background: bg || '#fff', border: '1px solid var(--bdr)', borderRadius: 8, padding: '12px 14px' }}>
      <div style={{ fontWeight: 700, fontSize: 10.5, color: c, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '.06em', borderBottom: '2px solid ' + c + '22', paddingBottom: 6 }}>{title}</div>
      {children}
    </div>
  );
};

// ── Source record lookup from entry id ───────────────────────────────────────
function vlGetSourceRecord(entry) {
  const id = entry.id;
  if (id.startsWith('p-')) {
    const purchaseId = id.slice(2);
    const p = (Store.all('purchases') || []).find(function(x) { return x.id === purchaseId; });
    return { type: 'purchase', record: p };
  }
  if (id.startsWith('d-')) {
    const dieselId = id.slice(2);
    const d = (Store.all('vendorDieselAllocations', 'group') || []).find(function(x) { return x.id === dieselId; });
    return { type: 'diesel', record: d };
  }
  if (id.startsWith('sd-')) {
    const settlements = Store.all('vendorSettlements') || [];
    for (let i = 0; i < settlements.length; i++) {
      const s = settlements[i];
      const ded = (s.deductions || []).find(function(d) { return ('sd-' + s.id + '-' + d.id) === id; });
      if (ded) return { type: 'deduction', record: ded, settlement: s };
    }
    return { type: 'deduction', record: null, settlement: null };
  }
  if (id.startsWith('sp-')) {
    const payId = id.slice(3);
    const settlements = Store.all('vendorSettlements') || [];
    for (let i = 0; i < settlements.length; i++) {
      const s = settlements[i];
      const pay = (s.payments || []).find(function(p) { return p.id === payId; });
      if (pay) return { type: 'payment', record: pay, settlement: s };
    }
    return { type: 'payment', record: null, settlement: null };
  }
  return { type: 'unknown', record: null };
}

// ── Drill-down panels per transaction type ───────────────────────────────────
function VlDrillDown({ entry }) {
  const src = React.useMemo(function() { return vlGetSourceRecord(entry); }, [entry.id]);

  // ── Purchase Bill ──
  if (src.type === 'purchase') {
    if (!src.record) {
      return <div style={{ padding: '14px 16px', color: 'var(--txt2)', fontSize: 12, fontStyle: 'italic' }}>Purchase record not found (may have been deleted).</div>;
    }
    const p = src.record;
    const vendor = (Store.all('vendors') || []).find(function(v) { return v.id === p.vendorId; }) || {};
    const items = (p.items && p.items.length) ? p.items : [{ materialId: p.materialId, quantity: p.quantity, ratePerTon: p.rate, gstPercent: p.gst, subtotal: p.subtotal, gstAmount: p.gstAmount }];
    const subTotal = items.reduce(function(s, i) {
      const qty = parseFloat(i.quantity) || 0;
      const rate = parseFloat(i.ratePerTon) || 0;
      return s + (i.subtotal != null ? parseFloat(i.subtotal) : qty * rate);
    }, 0);
    const gstTotal = items.reduce(function(s, i) {
      const qty = parseFloat(i.quantity) || 0;
      const rate = parseFloat(i.ratePerTon) || 0;
      const gstPct = parseFloat(i.gstPercent != null ? i.gstPercent : i.gst) || 0;
      const sub = i.subtotal != null ? parseFloat(i.subtotal) : qty * rate;
      return s + sub * gstPct / 100; // always fresh — never trust legacy-rounded stored gstAmount
    }, 0);
    const grandTotal = subTotal + gstTotal;

    return (
      <div style={{ padding: '14px 16px', background: '#FAFAF8', borderTop: '1px solid var(--bdr)' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--or)', textTransform: 'uppercase', letterSpacing: '.07em', marginBottom: 12 }}>
          Purchase Bill — Source Transaction
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 10 }}>
          <VlSection title="General Information" color="#1D4ED8">
            <VlKV label="PO Reference" value={p.id ? p.id.slice(0, 8).toUpperCase() : null} mono bold />
            <VlKV label="Date" value={window.fmtDate(p.date)} />
            <VlKV label="Status" value={p.status} color={p.status === 'Delivered' ? 'var(--ok)' : p.status === 'Cancelled' ? 'var(--err)' : 'var(--warn)'} bold />
            <VlKV label="Company" value={Store.name('companies', p.companyId)} />
            {p.challanNumber ? <VlKV label="Challan Number" value={p.challanNumber} mono bold /> : null}
            {p.royaltyPass ? <VlKV label="Royalty Pass" value={p.royaltyPass} mono /> : null}
            <VlKV label="Settlement Status" value={p.vendorSettlementStatus || 'Pending'} />
            {p.createdBy ? <VlKV label="Created By" value={p.createdBy} /> : null}
            {p.createdAt ? <VlKV label="Created Date" value={p.createdAt} /> : null}
            {p.updatedBy ? <VlKV label="Last Modified By" value={p.updatedBy} /> : null}
            {p.updatedAt ? <VlKV label="Last Modified Date" value={p.updatedAt} /> : null}
          </VlSection>

          <VlSection title="Vendor Information" color="var(--or)">
            <VlKV label="Vendor" value={Store.name('vendors', p.vendorId)} bold />
            {p.toCustomerId ? <VlKV label="To Customer (Site)" value={Store.name('customers', p.toCustomerId)} /> : null}
            {p.pickupAddress ? <VlKV label="Pickup Address" value={p.pickupAddress} /> : null}
            {vendor.gst ? <VlKV label="GST Number" value={vendor.gst} mono /> : null}
            {vendor.mobile ? <VlKV label="Contact" value={vendor.mobile} mono /> : null}
            {vendor.contactPerson ? <VlKV label="Contact Person" value={vendor.contactPerson} /> : null}
            <VlKV label="3rd-Party Transport" value={(p.transportThirdParty === 'Yes') ? 'Yes \u2014 Settled separately' : 'No \u2014 Vendor\u2019s own'} />
          </VlSection>

          <VlSection title="Transport Information" color="#15803D">
            {p.transporterName
              ? <VlKV label="Transporter" value={p.transporterName} bold />
              : <div style={{ fontSize: 11.5, color: 'var(--txt3)', fontStyle: 'italic', marginBottom: 6 }}>No transport assigned</div>
            }
            {p.vehicleFull ? <VlKV label="Vehicle Number" value={p.vehicleFull} mono bold /> : null}
            {p.dieselSource ? <VlKV label="Diesel Source" value={p.dieselSource} /> : null}
            {p.dieselQty ? <VlKV label="Diesel Qty" value={p.dieselQty + ' L'} /> : null}
          </VlSection>
        </div>

        {/* Materials table */}
        <div style={{ marginBottom: 10 }}>
          <div style={{ fontWeight: 700, fontSize: 10.5, color: 'var(--txt2)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Materials</div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, border: '1px solid var(--bdr)', borderRadius: 6 }}>
              <thead>
                <tr style={{ background: '#F9FAFB' }}>
                  {['MATERIAL', 'QTY', 'UNIT', 'RATE', 'GST %', 'SUBTOTAL', 'GST AMT', 'TOTAL'].map(function(h, i) {
                    const right = i >= 1 && i !== 2;
                    return <th key={h} style={{ padding: '7px 10px', textAlign: right ? 'right' : 'left', fontWeight: 700, color: 'var(--txt2)', fontSize: 10.5, letterSpacing: '.05em', whiteSpace: 'nowrap' }}>{h}</th>;
                  })}
                </tr>
              </thead>
              <tbody>
                {items.map(function(it, idx) {
                  const qty = parseFloat(it.quantity) || 0;
                  const rate = parseFloat(it.ratePerTon) || 0;
                  const gstPct = parseFloat(it.gstPercent != null ? it.gstPercent : it.gst) || 0;
                  const sub = it.subtotal != null ? parseFloat(it.subtotal) : qty * rate;
                  const gstAmt = sub * gstPct / 100; // always fresh — never trust legacy-rounded stored gstAmount
                  return (
                    <tr key={idx} style={{ borderTop: '1px solid var(--bdr)' }}>
                      <td style={{ padding: '7px 10px', fontWeight: 500 }}>{Store.name('materials', it.materialId) || '—'}</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{qty.toFixed(3)}</td>
                      <td style={{ padding: '7px 10px', color: 'var(--txt2)' }}>{it.uom || 'MT'}</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(rate)}</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right' }}>{gstPct}%</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(sub)}</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(gstAmt)}</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(sub + gstAmt)}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr style={{ background: '#FFF7ED', borderTop: '2px solid var(--or-bdr)' }}>
                  <td colSpan={5} style={{ padding: '7px 10px', fontWeight: 700, fontSize: 11, color: 'var(--txt2)' }}>TOTAL</td>
                  <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(subTotal)}</td>
                  <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(gstTotal)}</td>
                  <td style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800, color: 'var(--or)', fontVariantNumeric: 'tabular-nums' }}>{window.fmtCur(grandTotal)}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Financial summary + Remarks */}
        <div style={{ display: 'grid', gridTemplateColumns: p.notes ? '1fr 2fr' : '1fr', gap: 10 }}>
          <VlSection title="Financial Summary" color="var(--or)" bg="#FFF9F5">
            <VlKV label="Subtotal" value={window.fmtCur(subTotal)} />
            <VlKV label="Total GST" value={window.fmtCur(gstTotal)} />
            {p.dieselDeduction ? <VlKV label="Diesel Deduction" value={window.fmtCur(parseFloat(p.dieselDeduction))} color="#B45309" /> : null}
            <VlKV label="Grand Total" value={window.fmtCur(grandTotal)} color="var(--or)" bold />
            <VlKV label="Payment Status" value={p.vendorSettlementStatus || 'Pending'} />
          </VlSection>
          {p.notes ? (
            <VlSection title="Remarks" color="#6B7280">
              <div style={{ fontSize: 12, color: 'var(--txt)', lineHeight: 1.6 }}>{p.notes}</div>
            </VlSection>
          ) : null}
        </div>
      </div>
    );
  }

  // ── Diesel Allocated ──
  if (src.type === 'diesel') {
    if (!src.record) {
      return <div style={{ padding: '14px 16px', color: 'var(--txt2)', fontSize: 12, fontStyle: 'italic' }}>Diesel allocation record not found.</div>;
    }
    const d = src.record;
    return (
      <div style={{ padding: '14px 16px', background: '#FFFBEB', borderTop: '1px solid #FDE68A' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, color: '#B45309', textTransform: 'uppercase', letterSpacing: '.07em', marginBottom: 12 }}>
          Diesel Allocation — Source Record
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <VlSection title="Allocation Details" color="#B45309" bg="#FFFBEB">
            <VlKV label="Date" value={window.fmtDate(d.date)} />
            <VlKV label="Vendor" value={Store.name('vendors', d.vendorId)} bold />
            <VlKV label="Company" value={Store.name('companies', d.companyId)} />
            <VlKV label="Diesel Source" value={d.dieselSource} bold />
            <VlKV label="Quantity" value={(parseFloat(d.litres) || 0) + ' L'} bold />
            <VlKV label="Amount" value={window.fmtCur(parseFloat(d.amount) || 0)} color="#B45309" bold />
            {d.remarks ? <VlKV label="Remarks" value={d.remarks} /> : null}
          </VlSection>
          {(d.createdBy || d.allocatedBy || d.createdAt) ? (
            <VlSection title="Audit Trail" color="#6B7280">
              {(d.createdBy || d.allocatedBy) ? <VlKV label="Allocated By" value={d.createdBy || d.allocatedBy} /> : null}
              {d.createdAt ? <VlKV label="Allocated At" value={d.createdAt} /> : null}
              {d.updatedBy ? <VlKV label="Modified By" value={d.updatedBy} /> : null}
              {d.updatedAt ? <VlKV label="Modified At" value={d.updatedAt} /> : null}
            </VlSection>
          ) : null}
        </div>
      </div>
    );
  }

  // ── Settlement Payment ──
  if (src.type === 'payment') {
    if (!src.record) {
      return <div style={{ padding: '14px 16px', color: 'var(--txt2)', fontSize: 12, fontStyle: 'italic' }}>Payment record not found.</div>;
    }
    const pay = src.record;
    const s = src.settlement;
    return (
      <div style={{ padding: '14px 16px', background: '#EFF6FF', borderTop: '1px solid #BFDBFE' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, color: '#1E40AF', textTransform: 'uppercase', letterSpacing: '.07em', marginBottom: 12 }}>
          Settlement Payment — Source Record
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <VlSection title="Payment Details" color="#1E40AF" bg="#EFF6FF">
            <VlKV label="Payment Date" value={window.fmtDate(pay.date)} bold />
            <VlKV label="Amount" value={window.fmtCur(parseFloat(pay.amount) || 0)} color="#1E40AF" bold />
            <VlKV label="Mode" value={pay.mode} />
            {pay.reference ? <VlKV label="Reference No." value={pay.reference} mono /> : null}
            {pay.chequeNumber ? <VlKV label={window.vsPayModeConfig ? window.vsPayModeConfig(pay.mode).refLabel : 'Payment Reference'} value={pay.chequeNumber} mono /> : null}
            {pay.bankName ? <VlKV label="Bank" value={pay.bankName} /> : null}
            {pay.remarks ? <VlKV label="Remarks" value={pay.remarks} /> : null}
          </VlSection>
          {s ? (
            <VlSection title="Settlement Context" color="#6B7280">
              <VlKV label="Settlement Ref" value={s.id ? s.id.slice(0, 8).toUpperCase() : null} mono />
              <VlKV label="Vendor" value={Store.name('vendors', s.vendorId)} />
              <VlKV label="Company" value={Store.name('companies', s.companyId)} />
              <VlKV label="Period From" value={window.fmtDate(s.periodFrom)} />
              <VlKV label="Period To" value={window.fmtDate(s.periodTo)} />
              <VlKV label="Status" value={s.status} />
              {s.paidThroughCompanyName ? <VlKV label="Paid Through" value={s.paidThroughCompanyName} /> : null}
            </VlSection>
          ) : null}
        </div>
      </div>
    );
  }

  // ── Settlement Deduction ──
  if (src.type === 'deduction') {
    if (!src.record) {
      return <div style={{ padding: '14px 16px', color: 'var(--txt2)', fontSize: 12, fontStyle: 'italic' }}>Deduction record not found.</div>;
    }
    const ded = src.record;
    const s = src.settlement;
    const txType = ded.type === 'Miscellaneous' ? (ded.customType || 'Miscellaneous') : ded.type;
    return (
      <div style={{ padding: '14px 16px', background: '#F9FAFB', borderTop: '1px solid var(--bdr)' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, color: '#6B7280', textTransform: 'uppercase', letterSpacing: '.07em', marginBottom: 12 }}>
          Settlement Deduction — Source Record
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <VlSection title="Deduction Details" color="#7C3AED">
            <VlKV label="Type" value={txType} bold />
            <VlKV label="Date" value={window.fmtDate(ded.date || (s && s.periodFrom))} />
            <VlKV label="Amount" value={window.fmtCur(parseFloat(ded.amount) || 0)} color="#DC2626" bold />
            {ded.reference ? <VlKV label="Reference" value={ded.reference} mono /> : null}
            {ded.remarks ? <VlKV label="Remarks" value={ded.remarks} /> : null}
          </VlSection>
          {s ? (
            <VlSection title="Settlement Context" color="#6B7280">
              <VlKV label="Settlement Ref" value={s.id ? s.id.slice(0, 8).toUpperCase() : null} mono />
              <VlKV label="Vendor" value={Store.name('vendors', s.vendorId)} />
              <VlKV label="Company" value={Store.name('companies', s.companyId)} />
              <VlKV label="Period From" value={window.fmtDate(s.periodFrom)} />
              <VlKV label="Period To" value={window.fmtDate(s.periodTo)} />
              <VlKV label="Status" value={s.status} />
            </VlSection>
          ) : null}
        </div>
      </div>
    );
  }

  return <div style={{ padding: '14px 16px', color: 'var(--txt2)', fontSize: 12, fontStyle: 'italic' }}>Source transaction details unavailable.</div>;
}

// ── Main Vendor Ledger component ─────────────────────────────────────────────
function VendorLedger({ coId, isGroup }) {
  const [fVn, setFVn] = vlSt('');
  const [periodPreset, setPeriodPreset] = vlSt('all');
  const [customFrom, setCustomFrom] = vlSt('');
  const [customTo, setCustomTo] = vlSt('');
  const periodRange = vlMemo(function() { return window.getDieselPeriodRange(periodPreset, customFrom, customTo); }, [periodPreset, customFrom, customTo]);
  const fFrom = periodRange.from;
  const fTo = periodRange.to;
  const [expId, setExpId] = vlSt(null);
  const vendors = window.filterAssigned(Store.all('vendors'), isGroup ? '' : coId);
  const entries = vlMemo(function() { return window.vsBuildLedger(fVn, isGroup ? '' : coId, fFrom, fTo); }, [fVn, coId, fFrom, fTo, isGroup]);
  const selVn = vendors.find(function(v) { return v.id === fVn; });
  const kpi = vlMemo(function() {
    if (!entries.length) return null;
    return {
      credit: entries.reduce(function(s, e) { return s + e.credit; }, 0),
      debit: entries.reduce(function(s, e) { return s + e.debit; }, 0),
      bal: entries[entries.length - 1]?.bal || 0,
      purchases: entries.filter(function(e) { return e.txType === 'Purchase Bill'; }).reduce(function(s, e) { return s + e.credit; }, 0),
      diesel: entries.filter(function(e) { return e.txType === 'Diesel Allocated'; }).reduce(function(s, e) { return s + e.debit; }, 0)
    };
  }, [entries]);

  const footTotals = vlMemo(function() {
    const totalDebit = entries.reduce(function(s, e) { return s + e.debit; }, 0);
    const totalCredit = entries.reduce(function(s, e) { return s + e.credit; }, 0);
    const diesel = entries.filter(function(e) { return e.txType === 'Diesel Allocated'; }).reduce(function(s, e) { return s + e.debit; }, 0);
    const payments = entries.filter(function(e) { return e.txType === 'Settlement Payment'; }).reduce(function(s, e) { return s + e.debit; }, 0);
    const manual = entries.filter(function(e) { return !['Purchase Bill', 'Diesel Allocated', 'Settlement Payment'].includes(e.txType); }).reduce(function(s, e) { return s + e.debit; }, 0);
    return {
      debit: totalDebit, credit: totalCredit,
      purchases: entries.filter(function(e) { return e.txType === 'Purchase Bill'; }).reduce(function(s, e) { return s + e.credit; }, 0),
      diesel: diesel, payments: payments, manual: manual,
      balance: entries.length ? (entries[entries.length - 1]?.bal || 0) : 0,
      count: entries.length
    };
  }, [entries]);

  const TX_CLR = { 'Purchase Bill': { bg: '#DCFCE7', color: '#166534' }, 'Diesel Allocated': { bg: '#FEF3C7', color: '#92400E' }, 'Settlement Payment': { bg: '#DBEAFE', color: '#1E40AF' } };

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

  const tdBase = { padding: '9px 14px', fontVariantNumeric: 'tabular-nums' };

  return (
    <div>
      <div className="frow">
        <window.FiltSelect placeholder="Select Vendor…" value={fVn} onChange={function(v) { setFVn(v); setExpId(null); }} style={{ minWidth: 200 }} options={vendors.map(function(v) { return {value:v.id,label:v.name}; })}/>
        <window.DieselPeriodDropdown preset={periodPreset} onChange={setPeriodPreset} customFrom={customFrom} customTo={customTo} onCustomChange={function(f,t){ setCustomFrom(f); setCustomTo(t); }}/>
        {fVn && entries.length > 0 && <button className="btn btn-wh btn-sm" onClick={exportCSV}>Export CSV</button>}
        <span className="f-cnt">{fVn ? entries.length + ' entries' : ''}</span>
      </div>

      {!fVn ? (
        <div style={{ textAlign: 'center', padding: '64px 20px', color: 'var(--txt2)' }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>Select a vendor to view their payable ledger</div>
          <div style={{ fontSize: 11.5, marginTop: 4, color: 'var(--txt3)' }}>Chronological history of purchases, diesel, deductions, and payments</div>
        </div>
      ) : (
        <>
          {kpi && (
            <div className="kpi-grid" style={{ marginBottom: 10 }}>
              {[['Total Purchases', window.fmtCur(kpi.purchases), 'var(--ok)'], ['Total Diesel', window.fmtCur(kpi.diesel), '#B45309'], ['Total Credits', window.fmtCur(kpi.credit), '#166534'], ['Total Debits', window.fmtCur(kpi.debit), '#DC2626'], ['Balance Owed', window.fmtCur(kpi.bal), kpi.bal >= 0 ? 'var(--ok)' : '#DC2626']].map(function(row) {
                return <div key={row[0]} className="kpi"><div className="kpi-val" style={{ color: row[2], fontSize: 15 }}>{row[1]}</div><div className="kpi-lbl">{row[0]}</div></div>;
              })}
            </div>
          )}

          <div className="card">
            <div className="tbl-w">
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width: 32 }}></th>
                    <th>DATE</th>
                    <th>CHALLAN NO.</th>
                    <th>TYPE</th>
                    <th>DESCRIPTION</th>
                    <th style={{ textAlign: 'right' }}>DEBIT</th>
                    <th style={{ textAlign: 'right' }}>CREDIT</th>
                    <th style={{ textAlign: 'right' }}>BALANCE</th>
                    <th>COMPANY</th>
                  </tr>
                </thead>
                <tbody>
                  {entries.length === 0
                    ? <tr className="empty"><td colSpan={9} style={{ textAlign: 'center', padding: 40, color: 'var(--txt2)' }}>No ledger entries for {selVn?.name} in the selected range.</td></tr>
                    : entries.map(function(e) {
                        const isOpen = expId === e.id;
                        const bc = TX_CLR[e.txType];
                        // Only Purchase Bill entries have an actual challan number
                        const challanDisplay = e.txType === 'Purchase Bill' ? (e.ref && e.ref !== '—' ? e.ref : '—') : '—';
                        return (
                          <React.Fragment key={e.id}>
                            <tr
                              style={{ cursor: 'pointer', background: isOpen ? '#FFF9F5' : undefined }}
                              onClick={function() { setExpId(isOpen ? null : e.id); }}
                            >
                              <td style={{ textAlign: 'center', color: isOpen ? 'var(--or)' : 'var(--txt3)', fontSize: 11, transition: 'color .15s', userSelect: 'none' }}>
                                {isOpen ? '▾' : '▸'}
                              </td>
                              <td style={{ fontWeight: 500, whiteSpace: 'nowrap' }}>{window.fmtDate(e.date)}</td>
                              <td style={{ fontFamily: 'monospace', fontSize: 11, color: challanDisplay !== '—' ? 'var(--txt)' : 'var(--txt3)' }}>{challanDisplay}</td>
                              <td>
                                {bc
                                  ? <span style={{ fontSize: 10.5, fontWeight: 700, padding: '2px 7px', borderRadius: 3, ...bc }}>{e.txType}</span>
                                  : <window.VsDedBadge type={e.txType} />
                                }
                              </td>
                              <td style={{ fontSize: 11.5, color: 'var(--txt2)', maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.desc}</td>
                              <td style={{ textAlign: 'right', fontWeight: e.debit ? 600 : 400, color: e.debit ? '#DC2626' : 'var(--txt3)' }}>{e.debit ? window.fmtCur(e.debit) : '—'}</td>
                              <td style={{ textAlign: 'right', fontWeight: e.credit ? 600 : 400, color: e.credit ? 'var(--ok)' : 'var(--txt3)' }}>{e.credit ? window.fmtCur(e.credit) : '—'}</td>
                              <td style={{ textAlign: 'right', fontWeight: 700, color: e.bal >= 0 ? 'var(--ok)' : '#DC2626' }}>{window.fmtCur(e.bal)}</td>
                              <td style={{ fontSize: 10.5, color: 'var(--txt2)' }}>{Store.name('companies', e.coId) || '—'}</td>
                            </tr>
                            {isOpen && (
                              <tr style={{ background: '#FAFAF8' }}>
                                <td colSpan={9} style={{ padding: 0, borderBottom: '2px solid var(--or-bdr)' }}>
                                  <VlDrillDown entry={e} />
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })}
                </tbody>
                <tfoot>
                  <tr>
                    {/* One <td> per column — ensures perfect alignment regardless of column widths */}
                    <td style={{ ...tdBase }}></td>
                    <td style={{ ...tdBase, fontWeight: 700, fontSize: 11, color: 'var(--txt2)', whiteSpace: 'nowrap' }}>
                      {footTotals.count} {footTotals.count === 1 ? 'entry' : 'entries'}
                    </td>
                    <td style={{ ...tdBase }}></td>
                    <td style={{ ...tdBase }}></td>
                    <td style={{ ...tdBase, fontWeight: 700, fontSize: 11, color: 'var(--txt2)', letterSpacing: '.04em' }}>TOTALS</td>
                    <td style={{ ...tdBase, textAlign: 'right', fontWeight: 700, color: '#DC2626' }}>{window.fmtCur(footTotals.debit)}</td>
                    <td style={{ ...tdBase, textAlign: 'right', fontWeight: 700, color: 'var(--ok)' }}>{window.fmtCur(footTotals.credit)}</td>
                    <td style={{ ...tdBase, textAlign: 'right', fontWeight: 800, color: footTotals.balance >= 0 ? 'var(--ok)' : '#DC2626' }}>{window.fmtCur(footTotals.balance)}</td>
                    <td style={{ ...tdBase }}></td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.VendorLedger = VendorLedger;
