// Vendor Settlement — Create/Edit modal + expandable detail row
const { useState: vmSt, useEffect: vmEf, useMemo: vmMemo } = React;

// ── Expandable detail for a saved Vendor Settlement row ──────────────────────────────────────
function VendorSettleDetail({ s }) {
  const { navigate } = React.useContext(window.AppCtx) || {};
  const rows = s.purchaseRows || [];
  const t = window.vsCalcTotals(rows, { total: s.dieselDeduction || 0 }, s.deductions || []);
  // ── Split Allocation Traceability — diesel records locked to THIS settlement
  // via vendorSettledInId, restricted to ones carrying Split/Vendor role
  // allocation metadata (spec §7–8: cross-module traceability + drilldown).
  const splitDiesel = React.useMemo(function () {
    return (Store.all('dieselRecords', 'group') || []).filter(function (d) {
      return d.vendorSettledInId === s.id && (d.dieselAllocRole === 'Split' || d.dieselAllocRole === 'Vendor');
    });
  }, [s.id]);
  const H = ({ c, right }) => <th style={{ background: '#F9FAFB', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', whiteSpace: 'nowrap', textAlign: right ? 'right' : 'left' }}>{c}</th>;
  const D = ({ c, fw, col, right, mono }) => <td style={{ padding: '4px 8px', fontFamily: mono ? 'var(--font)' : 'inherit', fontWeight: fw || 400, color: col || 'var(--txt)', textAlign: right ? 'right' : 'left', fontSize: 12 }}>{c}</td>;
  return (
    <div style={{ padding: '14px 16px 18px', background: '#FFF9F5', borderBottom: '2px solid var(--or-bdr)' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontWeight: 700, fontSize: 11, color: 'var(--or)', marginBottom: 8, paddingBottom: 5, borderBottom: '2px solid #FEF3E8', textTransform: 'uppercase', letterSpacing: '.5px' }}>Purchase Orders ({rows.length})</div>
        {!rows.length ? <div style={{ fontSize: 11.5, color: 'var(--txt3)', fontStyle: 'italic' }}>No purchase lines recorded on this settlement.</div> : (
          <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: 'min(360px,44vh)', borderRadius: 6, border: '1px solid var(--bdr)' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, minWidth: 900 }}>
              <thead><tr><H c="PO No." /><H c="Date" /><H c="Material" /><H c="Qty" right /><H c="Rate" right /><H c="GST" right /><H c="Amount" right /><H c="Amt+GST" right /><H c="Challan" /><H c="Vehicle" /><H c="Crusher" /><H c="Customer" /><H c="Status" /></tr></thead>
              <tbody>
                {rows.map(function (row, i) {
                  const isSettled = row.settlementStatus === 'Fully Settled';
                  return (
                    <tr key={row.purchaseId + i} style={{ borderBottom: '1px solid #F3F4F6', background: isSettled ? '#F0FDF4' : '#fff' }}>
                      <D c={<span style={{ fontFamily: 'var(--font)', fontWeight: 700 }}>{row.poNo}</span>} />
                      <D c={window.fmtDate(row.date)} />
                      <D c={row.material} />
                      <D c={window.formatQuantity(row.quantity)} right />
                      <D c={window.fmtCur(row.rate)} right />
                      <D c={row.gstPct + '%'} right />
                      <D c={window.fmtCur(row.amount)} right />
                      <D c={window.fmtCur(row.amountWithGst)} fw={700} col="var(--ok)" right />
                      <D c={row.challanNumber} mono />
                      <D c={row.vehicleFull} mono />
                      <D c={row.crusher} />
                      <D c={row.customer} />
                      <td style={{ padding: '4px 8px' }}><window.VsPurchaseStatusBadge status={row.settlementStatus} /></td>
                    </tr>);

                })}
              </tbody>
              <tfoot><tr style={{ background: '#FFF7ED' }}><td colSpan={3} style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 700, fontSize: 11, color: 'var(--txt2)' }}>TOTALS</td><td style={{ padding: '6px 8px', textAlign: 'right', fontWeight: 700 }}>{window.formatQuantity(t.qty)}</td><td colSpan={3}></td><td></td><td style={{ padding: '6px 8px', textAlign: 'right', fontWeight: 800, color: 'var(--ok)' }}>{window.fmtCur(t.gross)}</td><td colSpan={4}></td></tr></tfoot>
            </table>
          </div>
        )}
      </div>
      <div className="rg-2" style={{ gap: 12, marginBottom: (s.deductions || []).length || (s.payments || []).length ? 12 : 0 }}>
        <div style={{ background: '#fff', border: '1px solid var(--bdr)', borderRadius: 6, padding: '10px 12px' }}>
          <div style={{ fontWeight: 700, fontSize: 11, color: 'var(--txt)', marginBottom: 10, paddingBottom: 5, borderBottom: '2px solid var(--bdr)', textTransform: 'uppercase', letterSpacing: '.5px' }}>Settlement Summary</div>
          {[
          ['Gross Purchase Amount', window.fmtCur(t.gross), 'var(--ok)'],
          ['Vendor Diesel', t.dsl ? '− ' + window.fmtCur(t.dsl) : 'None', '#B45309'],
          ['Manual Deductions', t.manDeds ? '− ' + window.fmtCur(t.manDeds) : 'None', '#DC2626'],
          ['Total Deductions', '− ' + window.fmtCur(t.totalD), '#DC2626']].
          map(function (row) {
            return <div key={row[0]} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, paddingBottom: 4, borderBottom: '1px dashed var(--bdr)', fontSize: 12 }}><span style={{ color: 'var(--txt2)' }}>{row[0]}</span><span style={{ fontWeight: 600, color: row[2] }}>{row[1]}</span></div>;
          })}
          {s.dieselDeductionEnabled === 'No' ? <div style={{ fontSize: 10.5, color: 'var(--txt3)', marginTop: -2, marginBottom: 4 }}>Diesel deduction disabled for this settlement.</div> : (t.dsl > 0 && s.dieselCompanyName) ? <div style={{ fontSize: 10.5, color: 'var(--txt3)', marginTop: -2, marginBottom: 4 }}>Diesel sourced from: <strong>{s.dieselCompanyName}</strong></div> : null}
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderTop: '2px solid var(--txt)', marginTop: 4 }}>
            <span style={{ fontWeight: 700, fontSize: 13 }}>NET PAYABLE</span><span style={{ fontWeight: 800, fontSize: 16, color: 'var(--or)' }}>{window.fmtCur(t.net)}</span>
          </div>
          {(parseFloat(s.amountPaid) || 0) > 0 && <>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--txt2)', marginTop: 4 }}><span>Amount Paid</span><span style={{ color: 'var(--ok)', fontWeight: 600 }}>− {window.fmtCur(s.amountPaid)}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, fontWeight: 700, marginTop: 2 }}><span>Outstanding</span><span style={{ color: (s.outstandingBalance || 0) > 0 ? '#DC2626' : 'var(--ok)' }}>{window.fmtCur(s.outstandingBalance || 0)}</span></div>
          </>}
        </div>
        <div style={{ background: '#fff', border: '1px solid var(--bdr)', borderRadius: 6, padding: '10px 12px' }}>
          <div style={{ fontWeight: 700, fontSize: 11, color: 'var(--txt)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px', paddingBottom: 5, borderBottom: '2px solid var(--bdr)' }}>Settlement Info</div>
          {[
          ['Company', s.companyId === 'group' ? 'OM Group (All Companies)' : Store.name('companies', s.companyId) || '—'],
          ['Paid Through Company', s.paidThroughCompanyName || Store.name('companies', s.paidThroughCompanyId) || '—'],
          ['Vendor', s.vendorName || '—'],
          ['Period', window.fmtDate(s.periodFrom) + ' – ' + window.fmtDate(s.periodTo)],
          ['Status', ''],
          ['Created', s.createdDate ? window.fmtDate(s.createdDate) : '—'],
          ['Created By', s.createdBy || '—'],
          ['Approved By', s.approvedBy || '—']].
          map(function (row) {
            if (row[0] === 'Status') return <div key="Status" style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, paddingBottom: 4, borderBottom: '1px dashed var(--bdr)', fontSize: 12 }}><span style={{ color: 'var(--txt2)' }}>Status</span><window.VsBadge s={s.status} /></div>;
            return <div key={row[0]} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, paddingBottom: 4, borderBottom: '1px dashed var(--bdr)', fontSize: 12 }}><span style={{ color: 'var(--txt2)' }}>{row[0]}</span><span style={{ fontWeight: 500 }}>{row[1]}</span></div>;
          })}
        </div>
      </div>
      {(s.deductions || []).length > 0 && (
        <div style={{ background: '#fff', border: '1px solid #FEE2E2', borderRadius: 6, padding: '10px 12px', marginBottom: (s.payments || []).length ? 12 : 0 }}>
          <div style={{ fontWeight: 700, fontSize: 11, color: '#DC2626', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Manual Deductions ({s.deductions.length})</div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, minWidth: 500 }}>
              <thead><tr>{['Type', 'Amount', 'Reference', 'Date', 'Created By', 'Remarks'].map(function (h) { return <th key={h} style={{ background: '#F9FAFB', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', textAlign: 'left' }}>{h}</th>; })}</tr></thead>
              <tbody>{s.deductions.map(function (d) {
                return (
                  <tr key={d.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                    <td style={{ padding: '4px 8px' }}><window.VsDedBadge d={d} /></td>
                    <td style={{ padding: '4px 8px', fontWeight: 700, color: '#DC2626', textAlign: 'right' }}>{window.fmtCur(d.amount)}</td>
                    <td style={{ padding: '4px 8px', fontFamily: 'var(--font)', fontSize: 11 }}>{d.reference || '—'}</td>
                    <td style={{ padding: '4px 8px' }}>{d.date ? window.fmtDate(d.date) : '—'}</td>
                    <td style={{ padding: '4px 8px', color: 'var(--txt2)' }}>{d.createdBy || '—'}</td>
                    <td style={{ padding: '4px 8px', color: 'var(--txt2)' }}>{d.remarks || '—'}</td>
                  </tr>);

              })}</tbody>
            </table>
          </div>
        </div>
      )}
      {(s.payments || []).length > 0 && (
        <div style={{ background: '#fff', border: '1px solid #BFDBFE', borderRadius: 6, padding: '10px 12px' }}>
          <div style={{ fontWeight: 700, fontSize: 11, color: '#1D4ED8', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Payments ({s.payments.length})</div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, minWidth: 560 }}>
              <thead><tr>{['Date', 'Amount', 'Mode', 'Reference', 'Payment Reference', 'Remarks'].map(function (h) { return <th key={h} style={{ background: '#F9FAFB', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', textAlign: 'left' }}>{h}</th>; })}</tr></thead>
              <tbody>{s.payments.map(function (p) {
                return (
                  <tr key={p.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                    <td style={{ padding: '4px 8px' }}>{window.fmtDate(p.date)}</td>
                    <td style={{ padding: '4px 8px', fontWeight: 700, color: 'var(--ok)' }}>{window.fmtCur(p.amount)}</td>
                    <td style={{ padding: '4px 8px' }}>{p.mode}</td>
                    <td style={{ padding: '4px 8px', fontFamily: 'var(--font)' }}>{p.reference || '—'}</td>
                    <td style={{ padding: '4px 8px', fontFamily: 'var(--font)' }}>{p.chequeNumber || '—'}</td>
                    <td style={{ padding: '4px 8px', color: 'var(--txt2)' }}>{p.remarks || '—'}</td>
                  </tr>);

              })}</tbody>
            </table>
          </div>
        </div>
      )}

      {splitDiesel.length > 0 && (
        <div style={{ background: '#fff', border: '1px solid #DDD6FE', borderRadius: 6, padding: '10px 12px', marginTop: 12 }}>
          <div style={{ fontWeight: 700, fontSize: 11, color: '#6D28D9', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>🟣 Split Allocation Diesel ({splitDiesel.length})</div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, minWidth: 760 }}>
              <thead><tr>{['Date', 'Vehicle', 'Transporter', 'Challan', 'Role', 'Vendor Share', 'Transport Share', 'Total', ''].map(function (h) { return <th key={h} style={{ background: '#F9FAFB', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', textAlign: 'left' }}>{h}</th>; })}</tr></thead>
              <tbody>{splitDiesel.map(function (d) {
                var total = parseFloat(d.deductionAmount) || parseFloat(d.amount) || 0;
                return (
                  <tr key={d.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                    <td style={{ padding: '4px 8px' }}>{window.fmtDate(d.date)}</td>
                    <td style={{ padding: '4px 8px', fontFamily: 'var(--font)' }}>{d.vehicleFull || '—'}</td>
                    <td style={{ padding: '4px 8px' }}>{d.transporterName || '—'}</td>
                    <td style={{ padding: '4px 8px', fontFamily: 'var(--font)' }}>{d.challanNumber || '—'}</td>
                    <td style={{ padding: '4px 8px' }}><window.AllocBadge record={d} /></td>
                    <td style={{ padding: '4px 8px', fontWeight: 700, color: '#6D28D9' }}>{window.fmtCur(d.vendorAllocAmount || total)}</td>
                    <td style={{ padding: '4px 8px', color: 'var(--txt2)' }}>{d.dieselAllocRole === 'Split' ? window.fmtCur(d.transportAllocAmount || 0) : '—'}</td>
                    <td style={{ padding: '4px 8px', fontWeight: 700 }}>{window.fmtCur(total)}</td>
                    <td style={{ padding: '4px 8px' }}>
                      <button className="btn btn-gh btn-sm" onClick={function () { navigate && navigate('diesel', { focusAllocId: d.id }); }}>🔗 View →</button>
                    </td>
                  </tr>);
              })}</tbody>
            </table>
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--txt3)', marginTop: 6 }}>These diesel deductions were generated automatically from a Diesel Split Allocation and included in this settlement's diesel total.</div>
        </div>
      )}
    </div>);

}

// ── Create / Edit Vendor Settlement modal ────────────────────────────────────────────────────
function VendorSettleModal({ item, coId, isGroup, session, onSaved, onClose }) {
  // Shared CompanyDropdown from settlements.jsx (same component as Transporter Settlement)
  const CompanyDrop = window.CompanyDropdown;
  const blank = { companyId: isGroup ? 'group' : coId, paidThroughCompanyId: isGroup ? '' : coId, vendorId: '', periodFrom: '', periodTo: '', status: 'Pending', notes: '', dieselDeductionEnabled: 'Yes', dieselCompanyId: '' };
  const [form, setF0] = vmSt(item ? { ...item } : { ...blank });
  const [deds, setDeds] = vmSt(item?.deductions || []);
  const [payments, setPayments] = vmSt(item?.payments || []);
  const [confirmNegative, setConfirmNegative] = vmSt(false);
  const [tick, setTick] = vmSt(0);

  vmEf(function () { const unsub = Store.on(function () { setTick(function (t) { return t + 1; }); }); return unsub; }, []);

  const companies = Store.all('companies');
  const vendors = window.filterAssigned(Store.all('vendors'), isGroup ? form.companyId || '' : coId);
  const eff = isGroup ? form.companyId : coId;

  const sf = (k, v) => setF0(function (p) { return { ...p, [k]: v, ...(k === 'companyId' && v !== 'group' ? { paidThroughCompanyId: v } : {}) }; });

  const eligibleAudit = vmMemo(function () {
    if (!form.vendorId || !form.periodFrom || !form.periodTo) return { eligible: [], vendorLinked: [], matchedVendor: 0, rejects: {} };
    return window.vsAuditEligiblePurchases(form.vendorId, form.periodFrom, form.periodTo, eff, item ? item.id : null);
  }, [form.vendorId, form.periodFrom, form.periodTo, eff, tick]);
  const eligiblePurchases = eligibleAudit.eligible;

  const purchaseRows = vmMemo(function () { return window.vsBuildPurchaseRows(eligiblePurchases); }, [eligiblePurchases, tick]);

  // Diesel is deducted from a company independently selectable from the Purchase Order company —
  // real OM Group operations often issue diesel from a different group company than the one that
  // raised the PO. dieselCompanyId is blank by default (falls back to the settlement/PO company,
  // i.e. the original behaviour) so existing settlements are unaffected until a user opts in.
  const dieselEnabled = (form.dieselDeductionEnabled || 'Yes') === 'Yes';
  const dieselCoId = form.dieselCompanyId || eff;
  const vendorDiesel = vmMemo(function () {
    if (!dieselEnabled || !form.vendorId || !form.periodFrom || !form.periodTo) return { records: [], total: 0, litres: 0 };
    return window.vsGetVendorDiesel(form.vendorId, form.periodFrom, form.periodTo, dieselCoId, item ? item.id : null);
  }, [dieselEnabled, form.vendorId, form.periodFrom, form.periodTo, dieselCoId, tick]);

  const t = vmMemo(function () { return window.vsCalcTotals(purchaseRows, vendorDiesel, deds); }, [purchaseRows, vendorDiesel, deds]);
  const amountPaid = vmMemo(function () { return payments.reduce(function (s, p) { return s + (parseFloat(p.amount) || 0); }, 0); }, [payments]);
  const outstanding = Math.max(0, t.net - amountPaid);
  const showPreview = form.vendorId && form.periodFrom && form.periodTo;

  const duplicateWarning = vmMemo(function () {
    if (!form.vendorId || !form.periodFrom || !form.periodTo) return null;
    // Scoped to the SAME company — a vendor settled for OM Transport is not a duplicate of the
    // same vendor settled for OM Enterprises over the same period (valid multi-company behaviour).
    // An OM Group (all-companies) settlement overlaps every company, so it always warns.
    // This is a WARNING only — it never removes Purchase Orders from the settlement.
    const vsIds = window.vsResolveVendorIds(form.vendorId).ids;
    const wantCo = window.vsResolveCompanyId(eff);
    const existing = (Store.all('vendorSettlements', 'group') || []).filter(function (s) {
      if (item && s.id === item.id) return false;
      if (vsIds.indexOf(s.vendorId) === -1) return false;
      if (s.status === 'Cancelled') return false;
      if (window.vsResolveCompanyId(s.companyId) !== wantCo && s.companyId !== 'group' && wantCo !== 'group') return false;
      return s.periodFrom <= form.periodTo && s.periodTo >= form.periodFrom;
    });
    return existing.length > 0 ? existing[0] : null;
  }, [form.vendorId, form.periodFrom, form.periodTo, eff, item, tick]);

  function addDed() { setDeds(function (p) { return [...p, { id: window.uid(), type: 'Adjustment', customType: '', othersDescription: '', amount: '', remarks: '', reference: '', date: new Date().toISOString().slice(0, 10), createdBy: session?.userName || '' }]; }); }
  function updDed(i, k, v) { setDeds(function (p) { return p.map(function (d, j) { return j === i ? { ...d, [k]: v } : d; }); }); }
  function remDed(i) { setDeds(function (p) { return p.filter(function (_, j) { return j !== i; }); }); }

  function addPayment() { setPayments(function (p) { return [...p, { id: window.uid(), amount: '', mode: 'Bank Transfer', reference: '', chequeNumber: '', date: new Date().toISOString().slice(0, 10), remarks: '' }]; }); }
  function updPayment(i, k, v) { setPayments(function (p) { return p.map(function (x, j) { return j === i ? { ...x, [k]: v } : x; }); }); }
  function remPayment(i) { setPayments(function (p) { return p.filter(function (_, j) { return j !== i; }); }); }

  function save(e) {
    e.preventDefault();
    if (isGroup && !form.companyId) { window.toast && window.toast('Please select a company or OM Group', 'er'); return; }
    if (!form.vendorId) { window.toast && window.toast('Select a vendor', 'er'); return; }
    if (!form.periodFrom || !form.periodTo) { window.toast && window.toast('Set settlement period', 'er'); return; }
    if (!form.paidThroughCompanyId) { window.toast && window.toast('Select the Paid Through Company', 'er'); return; }
    // Validate Others deductions have a description
    for (let i = 0; i < deds.length; i++) {
      if (deds[i].type === 'Others' && !(deds[i].othersDescription || '').trim()) {
        window.toast && window.toast('Please enter the adjustment description for deduction #' + (i + 1) + '.', 'er'); return;
      }
    }
    if (duplicateWarning && !item) { window.toast && window.toast('A settlement already exists for this vendor overlapping this period.', 'er'); return; }
    if (t.dsl > t.gross) { window.toast && window.toast('Diesel deduction cannot exceed gross purchase amount for this vendor.', 'er'); return; }
    // Payment-mode-driven instrument/reference validation — centralized via vsPayModeConfig so
    // Cheque/Bank Transfer/RTGS/NEFT (and any future mode) are enforced without per-mode code here.
    for (let i = 0; i < payments.length; i++) {
      const cfg = window.vsPayModeConfig(payments[i].mode);
      if (cfg.refRequired && !(payments[i].chequeNumber || '').trim()) {
        window.toast && window.toast('Payment #' + (i + 1) + ': ' + cfg.refLabel + ' is required.', 'er');
        return;
      }
    }
    // Duplicate payment reference check (within this settlement + across all vendor settlements)
    const refs = payments.map(function (p) { return (p.reference || p.chequeNumber || '').trim(); }).filter(Boolean);
    if (new Set(refs).size !== refs.length) { window.toast && window.toast('Duplicate payment reference within this settlement.', 'er'); return; }
    const allOtherRefs = (Store.all('vendorSettlements') || []).filter(function (s) { return !item || s.id !== item.id; }).flatMap(function (s) { return (s.payments || []).map(function (p) { return (p.reference || p.chequeNumber || '').trim(); }); }).filter(Boolean);
    const dupAcrossSettlements = refs.some(function (r) { return allOtherRefs.includes(r); });
    if (dupAcrossSettlements) { window.toast && window.toast('Payment reference already used in another settlement.', 'er'); return; }
    if (t.net < 0 && !confirmNegative) { setConfirmNegative(true); return; }

    const vendor = Store.byId('vendors', form.vendorId);
    const now = new Date().toISOString().slice(0, 16).replace('T', ' ');
    const prevHist = item?.statusHistory || [];
    const newHist = item && item.status === form.status ? prevHist : [...prevHist, { status: form.status, changedBy: session?.userName || 'System', changedAt: now, remarks: '' }];
    const purchaseIds = purchaseRows.map(function (r) { return r.purchaseId; }).filter(function (v, i, a) { return a.indexOf(v) === i; });

    const data = {
      ...form,
      vendorName: vendor?.name || '',
      deductions: deds,
      payments: payments,
      purchaseRows: purchaseRows,
      purchaseIds: purchaseIds,
      paidThroughCompanyName: form.paidThroughCompanyId ? Store.name('companies', form.paidThroughCompanyId) || '' : '',
      grossPurchaseAmount: t.gross,
      dieselDeduction: t.dsl,
      dieselDeductionEnabled: dieselEnabled ? 'Yes' : 'No',
      dieselCompanyId: dieselEnabled ? dieselCoId : '',
      dieselCompanyName: dieselEnabled ? (dieselCoId === 'group' ? 'OM Group (All Companies)' : Store.name('companies', dieselCoId) || '') : '',
      totalDeductions: t.totalD,
      netPayable: t.net,
      amountPaid: amountPaid,
      outstandingBalance: outstanding,
      poCount: t.rowCount,
      totalQuantity: t.qty,
      statusHistory: newHist,
      approvedDate: form.status !== 'Pending' && !item?.approvedDate ? new Date().toISOString().slice(0, 10) : item?.approvedDate || '',
      approvedBy: form.status !== 'Pending' && !item?.approvedBy ? session?.userName || '' : item?.approvedBy || '',
      paidBy: amountPaid > 0 ? session?.userName || '' : item?.paidBy || '',
      paidDate: amountPaid > 0 ? new Date().toISOString().slice(0, 10) : item?.paidDate || '',
      createdDate: item?.createdDate || new Date().toISOString().slice(0, 10),
      createdBy: item?.createdBy || session?.userName || '',
      editedBy: item ? session?.userName || '' : item?.editedBy || '',
      settlementDate: new Date().toISOString().slice(0, 10),
    };

    let settlementId;
    if (item) { Store.update('vendorSettlements', item.id, data); Store.addLog('UPDATE', 'Vendor Settlement', 'Updated: ' + (vendor?.name || '')); settlementId = item.id; }
    else { settlementId = Store.add('vendorSettlements', data); Store.addLog('CREATE', 'Vendor Settlement', 'Created: ' + (vendor?.name || '')); }

    if (purchaseIds.length) window.vsUpdatePurchaseSettlementStatus(purchaseIds, settlementId, form.status);
    if (vendorDiesel.records.length) window.vsUpdateVendorDieselStatus(vendorDiesel.records, settlementId, form.status);

    window.toast && window.toast(item ? 'Vendor settlement updated' : 'Vendor settlement created', 'ok');
    onSaved();
  }

  const iSt = { width: '100%', height: 26, border: '1px solid var(--bdr)', borderRadius: 'var(--r)', fontSize: 12, fontFamily: 'var(--font)', outline: 'none', padding: '0 6px', background: '#fff' };

  return (
    <div className="mbg">
      <div className="mod mod-xl">
        <div className="mod-hd"><h2>{item ? 'Edit Vendor Settlement' : 'New Vendor Settlement'}</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, overflow: 'hidden' }}>
          <div className="mod-bd">
            <div className="fg" style={{ marginBottom: 12 }}>
              {isGroup && <div className="fld"><label>Company</label><CompanyDrop value={form.companyId || 'group'} onChange={function (v) { sf('companyId', v); }} companies={companies} /></div>}
              <div className="fld"><label>Paid Through Company <span className="req">*</span></label><window.FormSelect placeholder="Select paying company…" value={form.paidThroughCompanyId || ''} onChange={function (v) { sf('paidThroughCompanyId', v); }} options={companies.map(function (c) { return {value:c.id,label:c.name}; })}/></div>
              <div className="fld"><label>Vendor <span className="req">*</span></label><window.FormSelect placeholder="Select Vendor" value={form.vendorId || ''} onChange={function (v) { sf('vendorId', v); }} options={vendors.map(function (v) { return {value:v.id,label:v.name}; })}/></div>
              <div className="fld"><label>Status</label><window.FormSelect value={form.status || 'Pending'} onChange={function (v) { sf('status', v); }} options={window.VS_STATUSES.map(function (s) { return {value:s,label:s}; })}/></div>
              <div className="fld"><label>Period From <span className="req">*</span></label><input className="inp" type="date" value={form.periodFrom || ''} onChange={function (e) { sf('periodFrom', e.target.value); }} required /></div>
              <div className="fld"><label>Period To <span className="req">*</span></label><input className="inp" type="date" value={form.periodTo || ''} onChange={function (e) { sf('periodTo', e.target.value); }} required /></div>
              <div className="fld">
                <label>Diesel Deduction</label>
                <window.FormSelect value={form.dieselDeductionEnabled || 'Yes'} onChange={function (v) { sf('dieselDeductionEnabled', v); }} options={[{ value: 'Yes', label: 'Yes' }, { value: 'No', label: 'No' }]} />
                <span style={{ fontSize: 10.5, color: 'var(--txt2)', marginTop: 3, display: 'block' }}>No excludes vendor diesel entirely from this settlement.</span>
              </div>
              {dieselEnabled && (
                <div className="fld">
                  <label>Diesel Deduction Company</label>
                  <window.FormSelect placeholder={'Same as Purchase Order Company' + (eff && eff !== 'group' ? ' (' + (Store.name('companies', eff) || '') + ')' : '')} value={form.dieselCompanyId || ''} onChange={function (v) { sf('dieselCompanyId', v); }} options={companies.map(function (c) { return { value: c.id, label: c.name }; })} />
                  <span style={{ fontSize: 10.5, color: 'var(--txt2)', marginTop: 3, display: 'block' }}>Fetches vendor diesel from this company instead of the Purchase Order company, when diesel was actually issued elsewhere.</span>
                </div>
              )}
            </div>

            {duplicateWarning && (
              <div style={{ background: '#FEF3C7', border: '1px solid #FDE68A', borderRadius: 6, padding: '10px 14px', marginBottom: 12, fontSize: 12, color: '#92400E' }}>
                <strong>Duplicate Warning:</strong> A settlement already exists for this vendor covering {window.fmtDate(duplicateWarning.periodFrom)} – {window.fmtDate(duplicateWarning.periodTo)} (Status: {duplicateWarning.status}).
              </div>
            )}

            {showPreview && (
              <>
                {purchaseRows.length === 0 ? (
                  <window.VsNoPoDiagnostic audit={eligibleAudit} coId={eff} />
                ) : (
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 8 }}>Purchase Orders — {purchaseRows.length} line{purchaseRows.length !== 1 ? 's' : ''}</div>
                    <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: 'min(320px,40vh)', border: '1.5px solid var(--bdr)', borderRadius: 'var(--r)', background: '#fff' }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, minWidth: 820 }}>
                        <thead><tr style={{ background: '#FAFAF8' }}>{['PO NO.', 'DATE', 'MATERIAL', 'QTY', 'RATE', 'AMOUNT', 'AMT+GST', 'CHALLAN', 'VEHICLE', 'STATUS'].map(function (h) { const right = ['QTY', 'RATE', 'AMOUNT', 'AMT+GST'].includes(h); return <th key={h} style={{ padding: '7px 9px', textAlign: right ? 'right' : 'left', fontSize: 10, fontWeight: 700, color: 'var(--txt3)', borderBottom: '1.5px solid var(--bdr)', whiteSpace: 'nowrap' }}>{h}</th>; })}</tr></thead>
                        <tbody>
                          {purchaseRows.map(function (row, i) {
                            return (
                              <tr key={row.purchaseId + i} style={{ borderBottom: '1px solid #F3F4F6' }}>
                                <td style={{ padding: '6px 9px', fontFamily: 'var(--font)', fontWeight: 700, color: 'var(--or)' }}>{row.poNo}</td>
                                <td style={{ padding: '6px 9px', whiteSpace: 'nowrap' }}>{window.fmtDate(row.date)}</td>
                                <td style={{ padding: '6px 9px' }}>{row.material}</td>
                                <td style={{ padding: '6px 9px', textAlign: 'right' }}>{window.formatQuantity(row.quantity)}</td>
                                <td style={{ padding: '6px 9px', textAlign: 'right' }}>{window.fmtCur(row.rate)}</td>
                                <td style={{ padding: '6px 9px', textAlign: 'right', color: 'var(--ok)' }}>{window.fmtCur(row.amount)}</td>
                                <td style={{ padding: '6px 9px', textAlign: 'right', fontWeight: 700 }}>{window.fmtCur(row.amountWithGst)}</td>
                                <td style={{ padding: '6px 9px', fontFamily: 'var(--font)' }}>{row.challanNumber}</td>
                                <td style={{ padding: '6px 9px', fontFamily: 'var(--font)' }}>{row.vehicleFull}</td>
                                <td style={{ padding: '6px 9px' }}><window.VsPurchaseStatusBadge status={row.settlementStatus} /></td>
                              </tr>);

                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                <div style={{ background: '#F0F7FF', border: '1px solid #BFDBFE', borderRadius: 6, padding: '10px 14px', marginBottom: 14 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#1D4ED8', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Settlement Summary · {t.rowCount} lines · {window.formatQuantity(t.qty)} MT</div>
                  <div className="rg-4" style={{ gap: 8 }}>
                    {[['Gross Purchase', window.fmtCur(t.gross), 'var(--ok)'], ['Vendor Diesel', window.fmtCur(t.dsl), '#B45309'], ['Manual Deductions', window.fmtCur(t.manDeds), '#DC2626'], ['Net Payable', window.fmtCur(t.net), t.net < 0 ? '#DC2626' : 'var(--or)']].map(function (row) {
                      return <div key={row[0]} style={{ background: '#fff', border: '1px solid #DBEAFE', borderRadius: 4, padding: '7px 8px', textAlign: 'center' }}><div style={{ fontSize: 14, fontWeight: 700, color: row[2] }}>{row[1]}</div><div style={{ fontSize: 10, color: 'var(--txt2)', marginTop: 2 }}>{row[0]}</div></div>;
                    })}
                  </div>
                  {t.net < 0 && <div style={{ marginTop: 8, fontSize: 11.5, color: '#DC2626', fontWeight: 600 }}>⚠ Net payable is negative — deductions exceed gross purchase amount. You will be asked to confirm on save.</div>}
                </div>
              </>
            )}

            <div style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>Manual Deductions</span>
                <button type="button" className="btn btn-wh btn-sm" onClick={addDed}>+ Add Deduction</button>
              </div>
              {!deds.length ? <div style={{ fontSize: 11.5, color: 'var(--txt3)', fontStyle: 'italic' }}>No deductions. Add Adjustment, Advance, RTO, Royalty Recovery, Penalty, etc.</div> : (
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 560 }}>
                    <thead><tr>{['Type', 'Amount', 'Reference', 'Date', 'Remarks', ''].map(function (h, i) { return <th key={i} style={{ background: '#F9FAFB', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', textAlign: 'left' }}>{h}</th>; })}</tr></thead>
                    <tbody>
                      {deds.map(function (d, i) {
                        return (
                          <tr key={d.id}>
                            <td style={{ padding: '3px 5px', width: 150 }}>
                              <select value={d.type} onChange={function (e) { updDed(i, 'type', e.target.value); }} style={iSt}>
                                {window.VS_DED_TYPES.map(function (ty) { return <option key={ty} value={ty}>{ty}</option>; })}
                              </select>
                              {d.type === 'Others' && (
                                <input
                                  value={d.othersDescription || ''}
                                  onChange={function (e) { updDed(i, 'othersDescription', e.target.value); }}
                                  placeholder="Enter adjustment name (e.g. Loading Charges, Labour Recovery, Fuel Difference…)"
                                  style={{ ...iSt, marginTop: 3, width: '100%', border: (d.othersDescription || '').trim() ? '1px solid var(--bdr)' : '1px solid #DC2626' }}
                                />
                              )}
                              {d.type === 'Others' && !(d.othersDescription || '').trim() && (
                                <span style={{ fontSize: 10, color: '#DC2626', display: 'block', marginTop: 2 }}>Please enter the adjustment description.</span>
                              )}
                            </td>
                            <td style={{ padding: '3px 5px', width: 90 }}><input type="number" value={d.amount} onChange={function (e) { updDed(i, 'amount', e.target.value); }} min="0" step="0.01" style={iSt} /></td>
                            <td style={{ padding: '3px 5px', width: 110 }}><input value={d.reference} onChange={function (e) { updDed(i, 'reference', e.target.value); }} placeholder="Ref no." style={iSt} /></td>
                            <td style={{ padding: '3px 5px', width: 120 }}><input type="date" value={d.date} onChange={function (e) { updDed(i, 'date', e.target.value); }} style={iSt} /></td>
                            <td style={{ padding: '3px 5px' }}>
                              {d.type === 'Miscellaneous'
                                ? <div style={{ display: 'flex', gap: 4 }}><input value={d.customType || ''} onChange={function (e) { updDed(i, 'customType', e.target.value); }} placeholder="Type name…" style={{ ...iSt, width: 100 }} /><input value={d.remarks} onChange={function (e) { updDed(i, 'remarks', e.target.value); }} placeholder="Remarks…" style={iSt} /></div>
                                : <input value={d.remarks} onChange={function (e) { updDed(i, 'remarks', e.target.value); }} placeholder="Remarks…" style={iSt} />}
                            </td>
                            <td style={{ padding: '3px 5px', textAlign: 'center', width: 28 }}><button type="button" onClick={function () { remDed(i); }} style={{ border: 'none', background: 'none', color: 'var(--err)', cursor: 'pointer', fontSize: 16 }}>×</button></td>
                          </tr>);

                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            <div style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>Payments</span>
                <button type="button" className="btn btn-wh btn-sm" onClick={addPayment}>+ Add Payment</button>
              </div>
              {!payments.length ? <div style={{ fontSize: 11.5, color: 'var(--txt3)', fontStyle: 'italic' }}>No payments recorded yet. Supports multiple / partial payments.</div> : (
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 700 }}>
                    <thead><tr>{['Date', 'Amount', 'Mode', 'Reference', 'Payment Reference', 'Remarks', ''].map(function (h, i) { return <th key={i} style={{ background: '#F9FAFB', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', padding: '5px 8px', border: '1px solid var(--bdr)', textAlign: 'left' }}>{h}</th>; })}</tr></thead>
                    <tbody>
                      {payments.map(function (p, i) {
                        const payCfg = window.vsPayModeConfig(p.mode);
                        const refMissing = payCfg.refRequired && !(p.chequeNumber || '').trim();
                        return (
                          <tr key={p.id}>
                            <td style={{ padding: '3px 5px', width: 120 }}><input type="date" value={p.date} onChange={function (e) { updPayment(i, 'date', e.target.value); }} style={iSt} /></td>
                            <td style={{ padding: '3px 5px', width: 90 }}><input type="number" value={p.amount} onChange={function (e) { updPayment(i, 'amount', e.target.value); }} min="0" step="0.01" style={iSt} /></td>
                            <td style={{ padding: '3px 5px', width: 120 }}><select value={p.mode} onChange={function (e) { updPayment(i, 'mode', e.target.value); }} style={iSt}>{window.VS_PAY_MODES.map(function (m) { return <option key={m} value={m}>{m}</option>; })}</select></td>
                            <td style={{ padding: '3px 5px', width: 110 }}><input value={p.reference} onChange={function (e) { updPayment(i, 'reference', e.target.value); }} placeholder="Ref no." style={iSt} /></td>
                            <td style={{ padding: '3px 5px', width: 110 }}>
                              <input value={p.chequeNumber} onChange={function (e) { updPayment(i, 'chequeNumber', e.target.value); }} placeholder={payCfg.refPlaceholder} style={{ ...iSt, border: refMissing ? '1px solid #DC2626' : '1px solid var(--bdr)', background: payCfg.refDisabled ? '#F9FAFB' : '#fff' }} disabled={payCfg.refDisabled} title={payCfg.refLabel} />
                              {refMissing && <span style={{ fontSize: 10, color: '#DC2626', display: 'block', marginTop: 2 }}>{payCfg.refLabel} is required</span>}
                            </td>
                            <td style={{ padding: '3px 5px' }}><input value={p.remarks} onChange={function (e) { updPayment(i, 'remarks', e.target.value); }} placeholder="Remarks…" style={iSt} /></td>
                            <td style={{ padding: '3px 5px', textAlign: 'center', width: 28 }}><button type="button" onClick={function () { remPayment(i); }} style={{ border: 'none', background: 'none', color: 'var(--err)', cursor: 'pointer', fontSize: 16 }}>×</button></td>
                          </tr>);

                      })}
                    </tbody>
                    <tfoot><tr style={{ background: '#F0FDF4' }}><td colSpan={1} style={{ padding: '6px 8px', fontWeight: 700, fontSize: 11 }}>TOTAL PAID</td><td style={{ padding: '6px 8px', fontWeight: 800, color: 'var(--ok)' }}>{window.fmtCur(amountPaid)}</td><td colSpan={5}></td></tr></tfoot>
                  </table>
                </div>
              )}
              {showPreview && <div style={{ marginTop: 8, fontSize: 12, fontWeight: 700 }}>Outstanding Balance: <span style={{ color: outstanding > 0 ? '#DC2626' : 'var(--ok)' }}>{window.fmtCur(outstanding)}</span></div>}
            </div>

            <div className="fg"><div className="fld full"><label>Notes</label><textarea className="tarea" value={form.notes || ''} onChange={function (e) { sf('notes', e.target.value); }} placeholder="Internal notes…" style={{ minHeight: 44 }} /></div></div>
          </div>
          <div className="mod-ft">
            <button type="button" className="btn btn-wh" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-or">{item ? 'Update Settlement' : 'Create Settlement'}</button>
          </div>
        </form>
      </div>
      {confirmNegative && (
        <div className="mbg" style={{ zIndex: 10001 }}>
          <div className="mod mod-sm">
            <div className="mod-hd"><h2>Confirm Negative Net Payable</h2><button className="mod-x" onClick={function () { setConfirmNegative(false); }}>×</button></div>
            <div className="mod-bd"><p style={{ fontSize: 13, lineHeight: 1.6 }}>Deductions exceed the gross purchase amount, producing a negative net payable of <strong style={{ color: '#DC2626' }}>{window.fmtCur(t.net)}</strong>. This means the vendor owes OM Group money. Continue?</p></div>
            <div className="mod-ft"><button className="btn btn-wh" onClick={function () { setConfirmNegative(false); }}>Cancel</button><button className="btn btn-rd" onClick={function () { save({ preventDefault: function () {} }); }}>Confirm & Save</button></div>
          </div>
        </div>
      )}
    </div>);

}

window.VendorSettleDetail = VendorSettleDetail;
window.VendorSettleModal = VendorSettleModal;
