// Vendor Settlement — Main Page (list + filters + KPIs + tabs: Settlement / Vendor Diesel / Ledger)
function VendorSettlementPage() {
  window.useStoreSync();
  const { companyId, session, navParams, clearNavParams } = React.useContext(window.AppCtx);
  const isGroup = companyId === 'group';
  const [tab, setTab] = React.useState('settlement');
  const [items, setItems] = React.useState([]);
  const [modal, setModal] = React.useState(false);
  const [editItem, setEditItem] = React.useState(null);
  const [delId, setDelId] = React.useState(null);
  const [expId, setExpId] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [fStatus, setFStatus] = React.useState('');
  const [fVendor, setFVendor] = React.useState('');
  const [fPaidThrough, setFPaidThrough] = React.useState('');
  const [periodPreset, setPeriodPreset] = React.useState('all');
  const [customFrom, setCustomFrom] = React.useState('');
  const [customTo, setCustomTo] = React.useState('');
  const periodRange = React.useMemo(function () { return window.getDieselPeriodRange(periodPreset, customFrom, customTo); }, [periodPreset, customFrom, customTo]);
  function setPeriod(id) { setPeriodPreset(id); setPg(1); }
  function setCustomRange(f, t) { setCustomFrom(f); setCustomTo(t); setPg(1); }
  const [intelVendorId, setIntelVendorId] = React.useState(null);
  const [printSettlement, setPrintSettlement] = React.useState(null);
  const [pg, setPg] = React.useState(1);
  const PER = 50;

  // Deep-link entry point — a "Open Vendor Settlement →" link from the Diesel
  // Split Allocation drilldown lands here with navParams.focusSettlementId set.
  React.useEffect(function () {
    if (navParams && navParams.focusSettlementId) {
      setTab('settlement');
      setExpId(navParams.focusSettlementId);
      clearNavParams && clearNavParams();
    }
  }, [navParams]);

  React.useEffect(function () { load(); }, [companyId]);
  function load() {
    const all = Store.all('vendorSettlements') || [];
    const vis = isGroup ? all : all.filter(function (s) { return s.companyId === companyId; });
    setItems([...vis].sort(function (a, b) { return (b.createdDate || '') > (a.createdDate || '') ? 1 : -1; }));
  }

  const vendors = React.useMemo(function () { return Store.all('vendors'); }, []);
  const companies = React.useMemo(function () { return Store.all('companies'); }, []);

  const filtered = React.useMemo(function () {
    return items.filter(function (s) {
      if (fStatus && s.status !== fStatus) return false;
      if (fVendor && s.vendorId !== fVendor) return false;
      if (fPaidThrough && s.paidThroughCompanyId !== fPaidThrough) return false;
      if (!window.dieselInPeriod(s.createdDate, periodRange.from, periodRange.to)) return false;
      if (search) {
        const q = search.toLowerCase();
        return (s.vendorName || '').toLowerCase().includes(q) || (s.periodFrom || '').includes(q) || (s.periodTo || '').includes(q) || (Store.name('companies', s.companyId) || '').toLowerCase().includes(q);
      }
      return true;
    });
  }, [items, fStatus, fVendor, fPaidThrough, periodRange, search]);

  const paged = filtered.slice((pg - 1) * PER, pg * PER);
  const totalPgs = Math.ceil(filtered.length / PER);
  const kpi = React.useMemo(function () {
    return {
      total: filtered.length,
      poCount: filtered.reduce(function (s, x) { return s + (x.poCount || 0); }, 0),
      gross: filtered.reduce(function (s, x) { return s + (x.grossPurchaseAmount || 0); }, 0),
      diesel: filtered.reduce(function (s, x) { return s + (x.dieselDeduction || 0); }, 0),
      otherDeds: filtered.reduce(function (s, x) { return s + Math.max(0, (x.totalDeductions || 0) - (x.dieselDeduction || 0)); }, 0),
      net: filtered.reduce(function (s, x) { return s + (x.netPayable || 0); }, 0),
      paid: filtered.reduce(function (s, x) { return s + (x.amountPaid || 0); }, 0),
      out: filtered.reduce(function (s, x) { return s + (x.outstandingBalance || 0); }, 0) };

  }, [filtered]);

  function openAdd() { setEditItem(null); setModal(true); }
  function openEdit(s) { setEditItem(s); setModal(true); }
  function delConfirm() {
    const s = items.find(function (x) { return x.id === delId; });
    if (s) {
      if (s.purchaseIds && s.purchaseIds.length) window.vsUpdatePurchaseSettlementStatus(s.purchaseIds, delId, 'Cancelled');
      const vd = window.vsGetVendorDiesel(s.vendorId, s.periodFrom, s.periodTo, s.companyId, delId);
      if (vd.records.length) window.vsUpdateVendorDieselStatus(vd.records, delId, 'Cancelled');
    }
    Store.del('vendorSettlements', delId);
    Store.addLog('DELETE', 'Vendor Settlement', 'Deleted');
    setDelId(null); load();
    window.toast && window.toast('Deleted', 'ok');
  }

  function exportCSV() {
    const hdr = 'Vendor,Company,Paid Through Company,From,To,Status,POs,Qty,Gross Purchase,Diesel,Other Deds,Net Payable,Paid,Outstanding';
    const rows = filtered.map(function (s) { return `"${s.vendorName}","${s.companyId === 'group' ? 'OM Group (All Companies)' : Store.name('companies', s.companyId) || ''}","${s.paidThroughCompanyName || Store.name('companies', s.paidThroughCompanyId) || ''}","${s.periodFrom}","${s.periodTo}","${s.status}","${s.poCount || 0}","${s.totalQuantity || 0}","${s.grossPurchaseAmount || 0}","${s.dieselDeduction || 0}","${(s.totalDeductions || 0) - (s.dieselDeduction || 0)}","${s.netPayable || 0}","${s.amountPaid || 0}","${s.outstandingBalance || 0}"`; }).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_settlements.csv'; a.click();
    window.toast && window.toast('Exported', 'ok');
  }

  return (
    <div>
      <div className="ph">
        <div>
          <h1>Vendor Settlement</h1>
          <p>Consolidated settlement for vendor-supplied material purchases — diesel deductions, manual deductions, and net payable calculation</p>
        </div>
        <div className="ph-act">
          {tab === 'settlement' && <>
            <button className="btn btn-wh btn-sm" onClick={exportCSV}>Export CSV</button>
            <button className="btn btn-or" onClick={openAdd}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg> New Settlement</button>
          </>}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 2, marginBottom: 12, borderBottom: '2px solid var(--bdr)' }}>
        {[['settlement', 'Settlement'], ['diesel', 'Vendor Diesel'], ['ledger', 'Vendor Ledger']].map(function (tb) {
          return <button key={tb[0]} onClick={function () { setTab(tb[0]); }} style={{ padding: '7px 18px', border: 'none', background: 'none', fontFamily: 'var(--font)', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', color: tab === tb[0] ? 'var(--or)' : 'var(--txt2)', borderBottom: tab === tb[0] ? '2px solid var(--or)' : '2px solid transparent', marginBottom: '-2px' }}>{tb[1]}</button>;
        })}
      </div>

      {tab === 'diesel' && <window.VendorDieselTab companyId={companyId} isGroup={isGroup} session={session} />}
      {tab === 'ledger' && <window.VendorLedger coId={companyId} isGroup={isGroup} />}

      {tab === 'settlement' && (
        <>
          <div className="kpi-grid" style={{ marginBottom: 10 }}>
            {[['Settlements', kpi.total, 'var(--txt)'], ['Gross Purchase', window.fmtCur(kpi.gross), 'var(--or)'], ['Net Payable', window.fmtCur(kpi.net), '#1D4ED8'], ['Outstanding', window.fmtCur(kpi.out), kpi.out > 0 ? '#DC2626' : 'var(--ok)']].map(function (row) {
              return <div key={row[0]} className="kpi"><div className="kpi-val" style={{ color: row[2] }}>{row[1]}</div><div className="kpi-lbl">{row[0]}</div></div>;
            })}
          </div>

          <div className="frow">
            <div className="fs"><svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" /></svg><input value={search} onChange={function (e) { setSearch(e.target.value); setPg(1); }} placeholder="Search vendor, period…" /></div>
            <window.FiltSelect placeholder="All Status" value={fStatus} onChange={function (v) { setFStatus(v); setPg(1); }} options={window.VS_STATUSES.map(function (s) { return {value:s,label:s}; })}/>
            <window.FiltSelect placeholder="All Vendors" value={fVendor} onChange={function (v) { setFVendor(v); setPg(1); }} options={vendors.map(function (v) { return {value:v.id,label:v.name}; })}/>
            <window.FiltSelect placeholder="All Paid Through" value={fPaidThrough} onChange={function (v) { setFPaidThrough(v); setPg(1); }} options={companies.map(function (c) { return {value:c.id,label:c.name}; })}/>
            <window.DieselPeriodDropdown preset={periodPreset} onChange={setPeriod} customFrom={customFrom} customTo={customTo} onCustomChange={setCustomRange}/>
            {(search || fStatus || fVendor || fPaidThrough || periodPreset !== 'all') && <button className="btn btn-gh btn-sm" onClick={function () { setSearch(''); setFStatus(''); setFVendor(''); setFPaidThrough(''); setPeriodPreset('all'); setCustomFrom(''); setCustomTo(''); setPg(1); }}>Clear</button>}
            <span className="f-cnt">{filtered.length} settlement{filtered.length !== 1 ? 's' : ''}</span>
          </div>

          <div className="card">
            <div className="tbl-w">
              <table className="tbl">
                <thead><tr>
                  <th style={{ width: 26 }}></th>
                  {isGroup && <th>OM GROUP COMPANY</th>}
                  <th>VENDOR</th><th>PERIOD</th><th>PAID THROUGH</th><th style={{ textAlign: 'center' }}>POs</th>
                  <th style={{ textAlign: 'right' }}>GROSS PURCHASE</th><th style={{ textAlign: 'right' }}>DIESEL</th>
                  <th style={{ textAlign: 'right' }}>OTHER DEDS</th><th style={{ textAlign: 'right' }}>NET PAYABLE</th>
                  <th style={{ textAlign: 'right' }}>PAID</th><th style={{ textAlign: 'right' }}>OUTSTANDING</th>
                  <th>STATUS</th><th>ACTIONS</th>
                </tr></thead>
                <tbody>
                  {!paged.length ? (
                    <tr className="empty"><td colSpan={isGroup ? 14 : 13} style={{ textAlign: 'center', padding: 48, color: 'var(--txt2)' }}>No vendor settlements yet. Click "+ New Settlement" to create one.</td></tr>
                  ) : paged.map(function (s) {
                    const isOpen = expId === s.id;
                    const otherD = (s.totalDeductions || 0) - (s.dieselDeduction || 0);
                    return (
                      <React.Fragment key={s.id}>
                        <tr style={{ background: isOpen ? '#FFF9F5' : undefined, cursor: 'pointer' }} onClick={function () { setExpId(isOpen ? null : s.id); }}>
                          <td style={{ textAlign: 'center' }}>▸</td>
                          {isGroup && <td><span className="bdg bg-or" style={{ fontSize: 10 }}>{s.companyId === 'group' ? 'OM Group' : Store.name('companies', s.companyId) || '—'}</span></td>}
                          <td style={{ fontWeight: 600, color: 'var(--or)', cursor: 'pointer' }} onClick={function (e) { e.stopPropagation(); setIntelVendorId(s.vendorId); }}>{s.vendorName || '—'}</td>
                          <td style={{ fontFamily: 'var(--font)', fontSize: 11, whiteSpace: 'nowrap' }}>{window.fmtDate(s.periodFrom)} – {window.fmtDate(s.periodTo)}</td>
                          <td style={{ fontSize: 11, color: 'var(--txt2)' }}>{s.paidThroughCompanyName || (s.paidThroughCompanyId ? Store.name('companies', s.paidThroughCompanyId) : '') || '—'}</td>
                          <td style={{ textAlign: 'center', fontWeight: 600 }}>{s.poCount || 0}</td>
                          <td style={{ textAlign: 'right', fontWeight: 600, color: 'var(--ok)' }}>{window.fmtCur(s.grossPurchaseAmount || 0)}</td>
                          <td style={{ textAlign: 'right', color: '#B45309' }}>{window.fmtCur(s.dieselDeduction || 0)}</td>
                          <td style={{ textAlign: 'right', color: '#DC2626' }}>{window.fmtCur(otherD)}</td>
                          <td style={{ textAlign: 'right', fontWeight: 700, color: 'var(--or)', fontSize: 13 }}>{window.fmtCur(s.netPayable || 0)}</td>
                          <td style={{ textAlign: 'right', color: 'var(--ok)' }}>{window.fmtCur(s.amountPaid || 0)}</td>
                          <td style={{ textAlign: 'right', fontWeight: (s.outstandingBalance || 0) > 0 ? 700 : 400, color: (s.outstandingBalance || 0) > 0 ? '#DC2626' : 'var(--txt3)' }}>{window.fmtCur(s.outstandingBalance || 0)}</td>
                          <td><window.VsBadge s={s.status} /></td>
                          <td onClick={function (e) { e.stopPropagation(); }}><div className="ra"><button className="btn btn-wh btn-sm" onClick={function () { openEdit(s); }}>Edit</button><button className="btn btn-wh btn-sm" onClick={function () { setPrintSettlement(s); }}>Statement</button><button className="btn btn-rd btn-sm" onClick={function () { setDelId(s.id); }}>Delete</button></div></td>
                        </tr>
                        {isOpen && <tr key={s.id + '-exp'}><td colSpan={isGroup ? 13 : 12} style={{ padding: 0, borderTop: '2px solid var(--or-bdr)' }}><window.VendorSettleDetail s={s} /></td></tr>}
                      </React.Fragment>);

                  })}
                </tbody>
                {filtered.length > 0 && (
                  <tfoot>
                    <tr style={{ background: '#FFF7ED', borderTop: '2.5px solid var(--or-bdr)' }}>
                      <td></td>
                      <td colSpan={isGroup ? 4 : 3} style={{ padding: '10px 8px', fontWeight: 700, fontSize: 11.5, color: 'var(--or)' }}>TOTALS <span style={{ fontWeight: 400, fontSize: 11, color: 'var(--txt2)', marginLeft: 8 }}>{filtered.length} settlement{filtered.length !== 1 ? 's' : ''}</span></td>
                      <td style={{ textAlign: 'center', padding: '10px 8px', fontWeight: 700 }}>{kpi.poCount}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 700, color: 'var(--ok)' }}>{window.fmtCur(kpi.gross)}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 700, color: '#B45309' }}>{kpi.diesel ? window.fmtCur(kpi.diesel) : '—'}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 700, color: '#DC2626' }}>{kpi.otherDeds ? window.fmtCur(kpi.otherDeds) : '—'}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 800, color: 'var(--or)', fontSize: 14 }}>{window.fmtCur(kpi.net)}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 700, color: 'var(--ok)' }}>{kpi.paid ? window.fmtCur(kpi.paid) : '—'}</td>
                      <td style={{ textAlign: 'right', padding: '10px 8px', fontWeight: 800, color: kpi.out > 0 ? '#DC2626' : 'var(--txt3)' }}>{kpi.out ? window.fmtCur(kpi.out) : '—'}</td>
                      <td></td><td></td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>

          {totalPgs > 1 && <div className="pag">
            <button className="pg-b" disabled={pg === 1} onClick={function () { setPg(function (p) { return p - 1; }); }}>‹</button>
            {Array.from({ length: Math.min(totalPgs, 7) }, function (_, i) { return <button key={i + 1} className={`pg-b${pg === i + 1 ? ' on' : ''}`} onClick={function () { setPg(i + 1); }}>{i + 1}</button>; })}
            <button className="pg-b" disabled={pg === totalPgs} onClick={function () { setPg(function (p) { return p + 1; }); }}>›</button>
            <span className="pg-inf">{pg}/{totalPgs}</span>
          </div>}
        </>
      )}

      {modal && <window.VendorSettleModal item={editItem} coId={companyId} isGroup={isGroup} session={session} onSaved={function () { setModal(false); load(); }} onClose={function () { setModal(false); }} />}
      {delId && <div className="mbg"><div className="mod mod-sm">
        <div className="mod-hd"><h2>Delete Vendor Settlement</h2><button className="mod-x" onClick={function () { setDelId(null); }}>×</button></div>
        <div className="mod-bd"><p style={{ fontSize: 13, lineHeight: 1.6 }}>Delete this settlement record? Linked Purchase Orders and Vendor Diesel Allocations will be released back to Pending.</p></div>
        <div className="mod-ft"><button className="btn btn-wh" onClick={function () { setDelId(null); }}>Cancel</button><button className="btn btn-rd" onClick={delConfirm}>Delete</button></div>
      </div></div>}
      {intelVendorId && <window.VendorIntelPanel vendorId={intelVendorId} coId={companyId} isGroup={isGroup} onClose={function () { setIntelVendorId(null); }} />}
      {printSettlement && <window.VendorStatementPrint settlement={printSettlement} onClose={function () { setPrintSettlement(null); }} />}
    </div>);

}

window.VendorSettlementPage = VendorSettlementPage;
