// Vendor Intelligence Panel — drill-down opened by clicking a Vendor Settlement's vendor name.
// Tabs: Overview · Purchase History · Diesel · Adjustments · Payments · Timeline · Documents
const { useState: viSt, useMemo: viMemo } = React;

function VipKV({ label, value, bold, mono, color }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', borderBottom: '1px dashed var(--bdr)', fontSize: 12 }}>
    <span style={{ color: 'var(--txt2)' }}>{label}</span>
    <span style={{ fontWeight: bold ? 700 : 500, fontFamily: mono ? 'var(--font)' : 'inherit', color: color || 'var(--txt)' }}>{value}</span>
  </div>;
}

function VendorIntelPanel({ vendorId, coId, isGroup, onClose }) {
  const [tab, setTab] = viSt('overview');
  const vendor = Store.byId('vendors', vendorId);

  const allPurchases = viMemo(function () {
    return (Store.all('purchases') || []).filter(function (p) { return p.vendorId === vendorId && (isGroup || p.companyId === coId); }).sort(function (a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [vendorId, coId, isGroup]);

  const allSettlements = viMemo(function () {
    return (Store.all('vendorSettlements') || []).filter(function (s) { return s.vendorId === vendorId && (isGroup || s.companyId === coId); }).sort(function (a, b) { return (b.createdDate || '') > (a.createdDate || '') ? 1 : -1; });
  }, [vendorId, coId, isGroup]);

  const allDiesel = viMemo(function () {
    return (Store.all('vendorDieselAllocations', 'group') || []).filter(function (d) { return d.vendorId === vendorId && (isGroup || d.companyId === coId); }).sort(function (a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [vendorId, coId, isGroup]);

  const totalPurchaseValue = allPurchases.reduce(function (s, p) { return s + window.gAmt(p); }, 0);
  const totalOutstanding = allSettlements.reduce(function (s, x) { return s + (parseFloat(x.outstandingBalance) || 0); }, 0);
  const totalDieselAmt = allDiesel.reduce(function (s, d) { return s + (parseFloat(d.amount) || 0); }, 0);

  const allDeductions = viMemo(function () {
    const out = [];
    allSettlements.forEach(function (s) { (s.deductions || []).forEach(function (d) { out.push(Object.assign({}, d, { settlementId: s.id, period: s.periodFrom + ' – ' + s.periodTo })); }); });
    return out.sort(function (a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [allSettlements]);

  const allPayments = viMemo(function () {
    const out = [];
    allSettlements.forEach(function (s) { (s.payments || []).forEach(function (p) { out.push(Object.assign({}, p, { settlementId: s.id, period: s.periodFrom + ' – ' + s.periodTo })); }); });
    return out.sort(function (a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [allSettlements]);

  const timeline = viMemo(function () {
    const events = [];
    allSettlements.forEach(function (s) {
      events.push({ date: s.createdDate, label: 'Settlement Created', by: s.createdBy, ref: s.id.slice(0, 8).toUpperCase() });
      (s.statusHistory || []).forEach(function (h) { events.push({ date: h.changedAt, label: 'Status → ' + h.status, by: h.changedBy, ref: s.id.slice(0, 8).toUpperCase() }); });
      (s.payments || []).forEach(function (p) { events.push({ date: p.date, label: 'Payment Recorded (' + window.fmtCur(p.amount) + ')', by: s.paidBy || '—', ref: p.reference || p.chequeNumber || '—' }); });
    });
    return events.filter(function (e) { return e.date; }).sort(function (a, b) { return (b.date || '') > (a.date || '') ? 1 : -1; });
  }, [allSettlements]);

  const TABS = [['overview', 'Overview'], ['purchases', 'Purchase History'], ['diesel', 'Diesel'], ['adjustments', 'Adjustments'], ['payments', 'Payments'], ['timeline', 'Timeline'], ['documents', 'Documents']];

  return (
    <div className="mbg" onClick={onClose}>
      <div className="mod mod-xl" onClick={function (e) { e.stopPropagation(); }} style={{ maxHeight: '92vh' }}>
        <div className="mod-hd"><h2>{vendor?.name || 'Vendor'} — Intelligence Panel</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <div style={{ display: 'flex', gap: 2, padding: '0 18px', borderBottom: '2px solid var(--bdr)', flexWrap: 'wrap' }}>
          {TABS.map(function (tb) {
            return <button key={tb[0]} onClick={function () { setTab(tb[0]); }} style={{ padding: '8px 14px', 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>
        <div className="mod-bd" style={{ paddingTop: 16 }}>
          {tab === 'overview' && (
            <div className="rg-2" style={{ gap: 14 }}>
              <div style={{ background: '#fff', border: '1px solid var(--bdr)', borderRadius: 6, padding: 14 }}>
                <div style={{ fontWeight: 700, fontSize: 11, color: 'var(--or)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Vendor Profile</div>
                <VipKV label="Name" value={vendor?.name || '—'} bold />
                <VipKV label="GST" value={vendor?.gst || '—'} mono />
                <VipKV label="Contact Person" value={vendor?.contactPerson || '—'} />
                <VipKV label="Phone" value={vendor?.mobile || '—'} mono />
                <VipKV label="Address" value={vendor?.address || '—'} />
              </div>
              <div style={{ background: '#fff', border: '1px solid var(--bdr)', borderRadius: 6, padding: 14 }}>
                <div style={{ fontWeight: 700, fontSize: 11, color: 'var(--or)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Financial Snapshot</div>
                <VipKV label="Total Purchase Value" value={window.fmtCur(totalPurchaseValue)} bold color="var(--ok)" />
                <VipKV label="Total Vendor Diesel" value={window.fmtCur(totalDieselAmt)} color="#B45309" />
                <VipKV label="Vendor Settlements" value={allSettlements.length} />
                <VipKV label="Outstanding Balance" value={window.fmtCur(totalOutstanding)} bold color={totalOutstanding > 0 ? '#DC2626' : 'var(--ok)'} />
              </div>
            </div>
          )}
          {tab === 'purchases' && (
            <div className="card"><div className="tbl-w"><table className="tbl">
              <thead><tr><th>DATE</th><th>CHALLAN</th><th>MATERIAL</th><th>QTY</th><th>AMOUNT</th><th>VENDOR SETTLEMENT</th><th>STATUS</th></tr></thead>
              <tbody>{allPurchases.length === 0 ? <tr className="empty"><td colSpan={7} style={{ textAlign: 'center', padding: 30, color: 'var(--txt2)' }}>No purchase orders for this vendor.</td></tr> : allPurchases.map(function (p) {
                const amt = window.gAmt(p);
                const qty = p.items ? p.items.reduce(function (s, i) { return s + (parseFloat(i.quantity) || 0); }, 0) : parseFloat(p.quantity) || 0;
                return (
                  <tr key={p.id}>
                    <td>{window.fmtDate(p.date)}</td>
                    <td style={{ fontFamily: 'var(--font)' }}>{p.challanNumber || '—'}</td>
                    <td>{Store.name('materials', p.items?.[0]?.materialId || p.materialId) || '—'}</td>
                    <td>{window.formatQuantity(qty)}</td>
                    <td style={{ fontWeight: 600 }}>{window.fmtCur(amt)}</td>
                    <td>{p.createVendorSettlement === 'Yes' ? (p.transportThirdParty === 'Yes' ? <span style={{ fontSize: 10, color: 'var(--txt3)' }}>Excluded (3rd-party transport)</span> : <window.VsPurchaseStatusBadge status={p.vendorSettlementStatus || 'Pending'} />) : <span style={{ fontSize: 10, color: 'var(--txt3)' }}>Not Enabled</span>}</td>
                    <td><window.Badge v={p.status} /></td>
                  </tr>);

              })}</tbody>
            </table></div></div>
          )}
          {tab === 'diesel' && (
            <div className="card"><div className="tbl-w"><table className="tbl">
              <thead><tr><th>DATE</th><th>SOURCE</th><th style={{ textAlign: 'right' }}>LITRES</th><th style={{ textAlign: 'right' }}>RATE</th><th style={{ textAlign: 'right' }}>AMOUNT</th><th>ALLOCATION STATUS</th></tr></thead>
              <tbody>{allDiesel.length === 0 ? <tr className="empty"><td colSpan={6} style={{ textAlign: 'center', padding: 30, color: 'var(--txt2)' }}>No diesel allocated to this vendor.</td></tr> : allDiesel.map(function (d) {
                return (
                  <tr key={d.id}>
                    <td>{window.fmtDate(d.date)}</td>
                    <td>{d.dieselSource || '—'}</td>
                    <td style={{ textAlign: 'right' }}>{(parseFloat(d.litres) || 0).toFixed(2)} L</td>
                    <td style={{ textAlign: 'right' }}>{window.fmtCur(d.ratePerLitre || 0)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 700, color: '#B45309' }}>{window.fmtCur(d.amount || 0)}</td>
                    <td><window.VendorDieselBadge settled={!!d.settledInVendorSettlementId} /></td>
                  </tr>);

              })}</tbody>
              {allDiesel.length > 0 && <tfoot><tr style={{ background: '#FFFBEB' }}><td colSpan={4} style={{ fontWeight: 700, padding: 8 }}>TOTAL ALLOCATED</td><td style={{ textAlign: 'right', fontWeight: 800, color: '#B45309', padding: 8 }}>{window.fmtCur(totalDieselAmt)}</td><td></td></tr></tfoot>}
            </table></div></div>
          )}
          {tab === 'adjustments' && (
            <div className="card"><div className="tbl-w"><table className="tbl">
              <thead><tr><th>DATE</th><th>TYPE</th><th style={{ textAlign: 'right' }}>AMOUNT</th><th>REASON</th><th>CREATED BY</th><th>SETTLEMENT PERIOD</th></tr></thead>
              <tbody>{allDeductions.length === 0 ? <tr className="empty"><td colSpan={6} style={{ textAlign: 'center', padding: 30, color: 'var(--txt2)' }}>No adjustments recorded.</td></tr> : allDeductions.map(function (d) {
                return (
                  <tr key={d.settlementId + d.id}>
                    <td>{d.date ? window.fmtDate(d.date) : '—'}</td>
                    <td><window.VsDedBadge type={d.type === 'Miscellaneous' ? d.customType || 'Miscellaneous' : d.type} /></td>
                    <td style={{ textAlign: 'right', fontWeight: 700, color: '#DC2626' }}>{window.fmtCur(d.amount)}</td>
                    <td style={{ color: 'var(--txt2)' }}>{d.remarks || '—'}</td>
                    <td>{d.createdBy || '—'}</td>
                    <td style={{ fontSize: 11 }}>{d.period}</td>
                  </tr>);

              })}</tbody>
            </table></div></div>
          )}
          {tab === 'payments' && (
            <div className="card"><div className="tbl-w"><table className="tbl">
              <thead><tr><th>DATE</th><th style={{ textAlign: 'right' }}>AMOUNT</th><th>MODE</th><th>REFERENCE</th><th>PAYMENT REFERENCE</th><th>SETTLEMENT PERIOD</th></tr></thead>
              <tbody>{allPayments.length === 0 ? <tr className="empty"><td colSpan={6} style={{ textAlign: 'center', padding: 30, color: 'var(--txt2)' }}>No payments recorded.</td></tr> : allPayments.map(function (p) {
                return (
                  <tr key={p.settlementId + p.id}>
                    <td>{window.fmtDate(p.date)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ok)' }}>{window.fmtCur(p.amount)}</td>
                    <td>{p.mode}</td>
                    <td style={{ fontFamily: 'var(--font)' }}>{p.reference || '—'}</td>
                    <td style={{ fontFamily: 'var(--font)' }}>{p.chequeNumber || '—'}</td>
                    <td style={{ fontSize: 11 }}>{p.period}</td>
                  </tr>);

              })}</tbody>
            </table></div></div>
          )}
          {tab === 'timeline' && (
            <div style={{ position: 'relative', paddingLeft: 20 }}>
              {timeline.length === 0 ? <div style={{ textAlign: 'center', padding: 30, color: 'var(--txt2)' }}>No audit history yet.</div> : timeline.map(function (e, i) {
                return (
                  <div key={i} style={{ position: 'relative', paddingBottom: 16, borderLeft: i === timeline.length - 1 ? 'none' : '2px solid var(--bdr)', marginLeft: -1 }}>
                    <div style={{ position: 'absolute', left: -6, top: 2, width: 10, height: 10, borderRadius: '50%', background: 'var(--or)' }}></div>
                    <div style={{ marginLeft: 16 }}>
                      <div style={{ fontSize: 12, fontWeight: 600 }}>{e.label}</div>
                      <div style={{ fontSize: 11, color: 'var(--txt2)' }}>{e.date} · {e.by} · Ref {e.ref}</div>
                    </div>
                  </div>);

              })}
            </div>
          )}
          {tab === 'documents' && (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--txt2)', fontSize: 12.5 }}>
              No documents attached yet. Vendor invoices, delivery challans, or proof-of-delivery scans can be attached here once a file-upload integration is connected.
            </div>
          )}
        </div>
      </div>
    </div>);

}

window.VendorIntelPanel = VendorIntelPanel;
