// Purchases Module — Standard filter panel + correct column order
const { useState: pSt, useEffect: pEf, useContext: pCtx, useMemo: pMemo, useRef: pRef } = React;
const AppCtx = window.AppCtx;

const PSH = ({ title, action }) =>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, paddingBottom: 7, borderBottom: '2px solid #FEF3E8' }}>
    <span style={{ color: 'var(--or)', fontWeight: 700, fontSize: 13 }}>{title}</span>
    {action}
  </div>;


// ── Searchable dropdown for Transporter / Vehicle ───────────────────────────
function PurchaseSearchSelect({ options, value, onChange, placeholder, noOptionsMsg, inputStyle }) {
  const [open, setOpen] = pSt(false);
  const [query, setQuery] = pSt('');
  const [dropDir, setDropDir] = pSt('down');
  const inputRef = pRef(null);
  const wrapRef = pRef(null);

  const currentOpt = pMemo(() => options.find((o) => o.value === value), [options, value]);

  const filtered = pMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return options;
    return options.filter((o) => o.label.toLowerCase().includes(q));
  }, [options, query]);

  pEf(() => {
    if (!open) return;
    function handler(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) {
        setOpen(false);setQuery('');
      }
    }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  function calcDir() {if (wrapRef.current) {var r = wrapRef.current.getBoundingClientRect();setDropDir(window.innerHeight - r.bottom < 220 && r.top > 220 ? 'up' : 'down');}}
  function handleInputChange(e) {setQuery(e.target.value);if (!open) {calcDir();}setOpen(true);}
  function handleFocus() {calcDir();setOpen(true);setQuery('');}
  function handleSelect(opt) {onChange(opt.value, opt.label);setOpen(false);setQuery('');}
  function handleClear(e) {e.stopPropagation();onChange('', '');setQuery('');inputRef.current && inputRef.current.focus();}

  const displayVal = open ? query : currentOpt ? currentOpt.label : '';

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', border: `1px solid ${open ? 'var(--or)' : 'var(--bdr)'}`, borderRadius: 'var(--r)', background: '#fff', transition: 'border .1s' }}>
        <input
          ref={inputRef}
          value={displayVal}
          onChange={handleInputChange}
          onFocus={handleFocus}
          placeholder={placeholder || '— Search & Select —'}
          autoComplete="off"
          style={{ flex: 1, border: 'none', outline: 'none', padding: '5px 9px', fontSize: 12, fontFamily: 'var(--font)', height: 34, color: 'var(--txt)', background: 'transparent', fontWeight: currentOpt && !open ? 600 : 400, ...(inputStyle || {}) }} />
        
        {value &&
        <button type="button" onClick={handleClear} title="Clear" style={{ background: 'none', border: 'none', padding: '0 4px 0 0', cursor: 'pointer', color: 'var(--txt3)', fontSize: 16, lineHeight: 1, display: 'flex', alignItems: 'center', height: 34 }}>×</button>
        }
        <div style={{ padding: '0 8px', color: 'var(--txt3)', fontSize: 10, display: 'flex', alignItems: 'center', height: 34, pointerEvents: 'none' }}>▼</div>
      </div>
      {open &&
      <div style={{ position: 'absolute', ...(dropDir === 'up' ? { bottom: 'calc(100% + 3px)' } : { top: 'calc(100% + 3px)' }), left: 0, right: 0, background: '#fff', border: '1px solid var(--bdr)', borderRadius: 'var(--r)', boxShadow: '0 6px 18px rgba(0,0,0,.14)', zIndex: 600, maxHeight: 220, overflowY: 'auto', overflowX: 'hidden' }}>
          {filtered.length === 0 ?
        <div style={{ padding: '10px 12px', fontSize: 12, color: 'var(--txt3)', textAlign: 'center', fontStyle: 'italic' }}>{noOptionsMsg || 'No results found'}</div> :
        filtered.map((opt) =>
        <div key={opt.value}
        onMouseDown={(e) => {e.preventDefault();handleSelect(opt);}}
        style={{ padding: '7px 10px', fontSize: 12, cursor: 'pointer', borderBottom: '1px solid #F3F4F6', background: opt.value === value ? 'var(--or-lt)' : '#fff', color: opt.value === value ? 'var(--or)' : 'var(--txt)', fontWeight: opt.value === value ? 600 : 400, ...(inputStyle ? { fontFamily: inputStyle.fontFamily || 'var(--font)' } : {}) }}>
          {opt.label}</div>
        )
        }
        </div>
      }
    </div>);

}

// ── Purchase drill-down helper components ────────────────────────────────────
const PoDrillKV = ({label,value,mono,bold,color}) => (
  <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?600:500,textAlign:'right',color:color||'var(--txt)',fontFamily:'var(--font)',fontSize:mono?10.5:11.5,wordBreak:'break-all',lineHeight:1.4,maxWidth:'60%'}}>{value||'—'}</span>
  </div>
);
const PoDrillSection = ({title,color,children,bg}) => (
  <div style={{background:bg||'#fff',border:'1px solid var(--bdr)',borderRadius:8,padding:'12px 14px'}}>
    <div style={{fontWeight:700,fontSize:10.5,color:color||'var(--or)',marginBottom:10,textTransform:'uppercase',letterSpacing:'.06em',borderBottom:`2px solid ${color||'var(--or)'}22`,paddingBottom:6}}>{title}</div>
    {children}
  </div>
);

function PurchasesPage() {
  window.useStoreSync();
  const { companyId, session } = pCtx(AppCtx);
  const isGroup = companyId === 'group';
  const [items, setItems] = pSt([]);
  const [search, setSearch] = pSt('');
  const [showFP, setShowFP] = pSt(false);
  const [fv, setFv] = pSt({ dateFrom: '', dateTo: '', status: '', vendorId: '', materialId: '', crusherId: '' });
  const [applied, setApplied] = pSt({ dateFrom: '', dateTo: '', status: '', vendorId: '', materialId: '', crusherId: '' });
  const [page, setPage] = pSt(1);
  const [modal, setModal] = pSt(false);
  const [editId, setEditId] = pSt(null);
  const [delId, setDelId] = pSt(null);
  const [form, setForm] = pSt({});
  const [gridItems, setGrid] = pSt([newRow()]);
  const [poExpand, setPoExpand] = pSt(null);
  const [poStatement, setPoStatement] = pSt(null);
  const [overrideRate, setOverrideRate] = pSt(false);
  const [activePO, setActivePO] = pSt(null);
  const poIsInitialEditLoad = pRef(false);
  const PER = 50;

  const vendors = window.filterAssigned(Store.all('vendors'), companyId);
  const materials = window.filterAssigned(Store.all('materials'), companyId);
  const crushers = window.filterAssigned(Store.all('crushers'), companyId);
  const customers = window.filterAssigned(Store.all('customers'), companyId);
  // Transporter Master — live sync so additions/changes in TM reflect instantly
  const [tmAll, setTmAll] = pSt(() => Store.all('transporterMaster', 'group'));
  const [allVehMaster, setAllVehMaster] = pSt(() => Store.all('vehicleMaster', 'group') || []);
  const [dieselSources, setDieselSources] = pSt(() => Store.all('dieselSources') || []);
  pEf(() => {
    const unsub = Store.on(() => {
      setTmAll(Store.all('transporterMaster', 'group'));
      setAllVehMaster(Store.all('vehicleMaster', 'group') || []);
      setDieselSources(Store.all('dieselSources') || []);
    });
    return unsub;
  }, []);
  const tmActive = tmAll.filter((t) => t.status === 'Active' || !t.status);
  const tmVehicles = pMemo(() => form.transporterMasterId ?
  allVehMaster.filter((v) => v.transporterId === form.transporterMasterId && (v.status === 'Active' || !v.status)) :
  [], [allVehMaster, form.transporterMasterId]);

  pEf(() => {load();return Store.on(load);}, [companyId]);

  // ── Auto-fill: watch vendor + company, fetch active PO, populate rates ──
  // Uses RateEngine.getPurchaseRate per row so the full fallback chain
  // (site-specific → general PO) is applied for every material individually.
  pEf(() => {
    if (!modal) {setActivePO(null);return;}
    const coId = isGroup ? form.companyId || '' : companyId;
    if (!coId || !form.vendorId || !window.RateEngine) {setActivePO(null);return;}
    const po = window.RateEngine.getActivePO(coId, 'vendor', form.vendorId, form.toCustomerId);
    setActivePO(po ? { poNumber: po.poNumber, siteSpecific: !!po.siteSpecific, toCustomerName: po.toCustomerName||'' } : null);
    if (!overrideRate && po) {
      setGrid((prev) => prev.map((row) => {
        if (!row.materialId) return row;
        // Use getPurchaseRate (not po.rates.find) so the site-specific → general
        // fallback applies per material, not just at the PO level.
        const rateData = window.RateEngine.getPurchaseRate(coId, form.vendorId, row.materialId, form.toCustomerId || '');
        if (!rateData) return { ...row, _autoFilled: false };
        const qty = parseFloat(row.quantity) || 0, rate = rateData.rate, gp = (rateData.gst != null && rateData.gst !== '') ? parseFloat(rateData.gst) : 5;
        const sub = qty * rate, gstA = Math.round(sub * gp / 100);
        return { ...row, ratePerTon: rate, gstPercent: String(gp), subtotal: sub, gstAmount: gstA, total: sub + gstA, _autoFilled: true, _autoRate: rate, _autoPO: rateData.poNumber };
      }));
    }
  }, [form.vendorId, form.companyId, form.toCustomerId, modal, overrideRate, companyId, isGroup]);
  // ── Auto-fill: Pickup Address from Vendor Master ──────────────────────────
  pEf(() => {
    if (!modal) return;
    if (!form.vendorId) { setForm(p => ({ ...p, pickupAddress: '' })); return; }
    if (poIsInitialEditLoad.current) { poIsInitialEditLoad.current = false; return; }
    const _vendor = Store.byId('vendors', form.vendorId);
    setForm(p => ({ ...p, pickupAddress: _vendor?.address || '' }));
  }, [form.vendorId, modal]);
  function load() {setItems(Store.all('purchases', companyId));}

  function newRow() {return { id: window.uid(), materialId: '', crusherSite: '', uom: 'MT', quantity: '', ratePerTon: '', gstPercent: '5', subtotal: 0, gstAmount: 0, total: 0 };}

  function applyFP() {setApplied({ ...fv });setPage(1);setShowFP(false);}
  function clearFP() {const e = { dateFrom: '', dateTo: '', status: '', vendorId: '', materialId: '', crusherId: '' };setFv(e);setApplied(e);setSearch('');setPage(1);}
  function refreshFP() {load();window.toast && window.toast('Refreshed', 'ok');}

  const filtered = pMemo(() => {
    return items.filter((it) => {
      if (search) {
        const q = search.toLowerCase();
        if (![it.challanNumber, it.vehicleFull, it.royaltyPass].some((v) => String(v || '').toLowerCase().includes(q)) &&
        !Store.name('vendors', it.vendorId).toLowerCase().includes(q)) return false;
      }
      if (applied.dateFrom && it.date < applied.dateFrom) return false;
      if (applied.dateTo && it.date > applied.dateTo) return false;
      if (applied.status && it.status !== applied.status) return false;
      if (applied.vendorId && it.vendorId !== applied.vendorId) return false;
      if (applied.materialId && !it.items?.some((i) => i.materialId === applied.materialId)) return false;
      if (applied.crusherId && !it.items?.some((i) => i.crusherSite === applied.crusherId)) return false;
      return true;
    });
  }, [items, search, applied]);

  const activeFilters = Object.values(applied).filter(Boolean).length;
  // GST/total figures are recalculated fresh per row (never trusted from
  // stored fields) so historical per-line rounding can never leak into this
  // report total — see window.GstEngine.recalcRecord.
  const poRecalc = pMemo(() => window.GstEngine.sumRecalc(filtered), [filtered]);
  const poTotals = pMemo(() => ({
    qty: filtered.reduce((s, p) => s + (p.items ? p.items.reduce((a, i) => a + (parseFloat(i.quantity) || 0), 0) : 0), 0),
    amtNoGST: poRecalc.subtotal,
    gstAmt: poRecalc.gstAmount,
    amtWithGST: poRecalc.total,
  }), [filtered, poRecalc]);
  const totalPgs = Math.max(1, Math.ceil(filtered.length / PER));
  const paged = filtered.slice((page - 1) * PER, page * PER);

  function updateRow(idx, key, val) {
    const coId = isGroup ? form.companyId || '' : companyId;
    setGrid((prev) => prev.map((r, i) => {
      if (i !== idx) return r;
      const updated = { ...r, [key]: val };
      // Auto-fill rate + GST when material is selected and override is off.
      // Routes through RateEngine.getPurchaseRate so the full fallback chain
      // (site-specific PO → general PO) applies per material — this is the
      // single source of truth for all purchase rate lookups.
      if (key === 'materialId' && val && !overrideRate && coId && form.vendorId && window.RateEngine) {
        const rateData = window.RateEngine.getPurchaseRate(coId, form.vendorId, val, form.toCustomerId || '');
        if (rateData) {
          const qty = parseFloat(updated.quantity) || 0, rate = rateData.rate, gp = (rateData.gst != null && rateData.gst !== '') ? parseFloat(rateData.gst) : 5;
          const sub = qty * rate, gstA = sub * gp / 100; // exact — GST is never rounded
          updated.ratePerTon = rate; updated.gstPercent = String(gp);
          updated.subtotal = sub; updated.gstAmount = gstA; updated.total = sub + gstA;
          updated._autoFilled = true; updated._autoRate = rate; updated._autoPO = rateData.poNumber;
        } else {
          updated._autoFilled = false;
        }
      }
      const canRecalc = key === 'quantity' || key === 'gstPercent' || (key === 'ratePerTon' && (overrideRate || !updated._autoFilled));
      if (canRecalc) {
        const qty = parseFloat(updated.quantity) || 0, rate = parseFloat(updated.ratePerTon) || 0, gp = parseFloat(updated.gstPercent) || 0;
        const sub = qty * rate, gstA = sub * gp / 100; // exact — GST is never rounded
        updated.subtotal = sub; updated.gstAmount = gstA; updated.total = sub + gstA;
      }
      return updated;
    }));
  }
  function addRow() {setGrid((p) => [...p, newRow()]);}
  function removeRow(i) {setGrid((p) => p.filter((_, j) => j !== i));}

  const totals = pMemo(() => {
    const sub = gridItems.reduce((s, r) => s + (parseFloat(r.subtotal) || 0), 0);
    const gst = gridItems.reduce((s, r) => s + (parseFloat(r.gstAmount) || 0), 0);
    return { sub, gst, total: sub + gst };
  }, [gridItems]);

  function openAdd() {
    const ls = (Store.loadState && Store.loadState('purchases')) || { state: 'OK' };
    if (ls.state === 'ERROR' || ls.state === 'BLOCKED') {
      window.toast && window.toast('Data storage is currently unsafe. Your existing data has been protected. Please open Data Health before continuing.', 'er');
      return;
    }
    poIsInitialEditLoad.current = false;
    setForm({ date: new Date().toISOString().slice(0, 10), status: 'Delivered', transporterName: '', transporterMasterId: '', vehicleFull: '', companyId: isGroup ? '' : companyId, toCustomerId: '', transportThirdParty: 'No', createVendorSettlement: 'No' });
    setGrid([newRow()]);setEditId(null);setModal(true);
    setOverrideRate(false);setActivePO(null);
  }
  function openEdit(po) {
    poIsInitialEditLoad.current = true;
    setForm({ ...po });
    setGrid(po.items?.length ? po.items.map((i) => ({ ...i })) : [newRow()]);
    setEditId(po.id);setModal(true);
    setOverrideRate(false);setActivePO(null);
  }
  const setF = (k, v) => setForm((p) => ({ ...p, [k]: v }));

  function handleSave(e) {
    e.preventDefault();
    const coErr = window.requireGroupCompany(isGroup, form.companyId);
    if (coErr) {window.toast && window.toast(coErr, 'er');return;}
    if (!form.transporterMasterId) {window.toast && window.toast('Please select a Transporter.', 'er');return;}
    if (!form.vehicleFull) {window.toast && window.toast('Please select a Vehicle.', 'er');return;}
    // Record rate overrides to audit log
    if (overrideRate && window.RateEngine) {
      const coId = isGroup ? form.companyId || companyId : companyId;
      gridItems.forEach((row) => {
        if (row._autoFilled && row._autoRate != null && parseFloat(row.ratePerTon) !== parseFloat(row._autoRate)) {
          window.RateEngine.recordOverride({
            companyId: coId, partyType: 'vendor', partyId: form.vendorId,
            materialId: row.materialId, materialName: Store.name('materials', row.materialId),
            poNumber: row._autoPO || '', autoRate: row._autoRate,
            overrideRate: parseFloat(row.ratePerTon),
            userName: Store.data.session?.userName
          });
        }
      });
    }
    const record = { ...form, items: gridItems, ...totals };
    if (editId) {Store.update('purchases', editId, record);Store.addLog('UPDATE', 'Purchase', `Updated ${form.challanNumber}`);} else
    {Store.add('purchases', record);Store.addLog('CREATE', 'Purchase', `Created ${form.challanNumber}`);}
    setModal(false);load();window.toast && window.toast(editId ? 'Updated' : 'Purchase created', 'ok');
  }
  function handleDelete() {Store.del('purchases', delId);Store.addLog('DELETE', 'Purchase', 'Deleted');setDelId(null);load();window.toast && window.toast('Deleted', 'ok');}

  // Standard Export — the default, visible to every employee. Never includes
  // Rate or any figure derived from it (Subtotal / GST / Total are all
  // rate-derived, so they're excluded here too).
  function exportStandard() {
    // Canonical source-company attribution (erp/company-attribution.js).
    // REPORT SCOPE ≠ TRANSACTION COMPANY: the column is resolved per record,
    // never from the active company selector.
    const _q  = v => '"' + String(v==null?'':v).replace(/"/g,'""') + '"';
    const _co = r => window.ERPCompanyAttribution
      ? window.ERPCompanyAttribution.resolveTransactionCompany(r).companyName
      : (Store.name('companies', r && r.companyId) || 'Unassigned');
    const _coHdr = isGroup ? 'OM Group Company,' : '';
    const _coCell = r => isGroup ? _q(_co(r)) + ',' : '';
    const hdr = _coHdr + 'Date,Vendor,Material,Vehicle No,Quantity,UOM,Challan No,Subtotal (Pre-GST),GST Amount,Total+GST,Status';
    // Subtotal/GST/Total are read via the same GstEngine.recalcRecord used by
    // Confidential Export and the on-screen table — each row's own record (p),
    // never recalculated differently or borrowed from another transaction.
    // Rate itself is deliberately omitted — this is the one thing that stays hidden.
    const rows = filtered.map((p) => {
      const mat = p.items?.[0];const matName = mat ? Store.name('materials', mat.materialId) : '';
      const qty = p.items ? p.items.reduce((s, i) => s + (parseFloat(i.quantity) || 0), 0) : 0;
      const c = window.GstEngine.recalcRecord(p);
      return _coCell(p) + [p.date, Store.name('vendors', p.vendorId), matName, p.vehicleFull || '', window.formatQuantityRaw(qty), mat?.uom || 'MT', p.challanNumber || '', c.subtotal, c.gstAmount, c.total, p.status].map(_q).join(',');
    }).join('\r\n');
    const blob = new Blob(['\uFEFF' + hdr + '\r\n' + rows], { type: 'text/csv;charset=utf-8' });const a = document.createElement('a');a.href = URL.createObjectURL(blob);a.download = 'purchases.csv';a.click();
    Store.addLog('EXPORT', 'Purchase', `Standard export: ${filtered.length} records`);
    window.toast && window.toast('CSV exported', 'ok');
  }
  // Confidential Export — same content as the export this module has always
  // produced (Rate-derived pricing included), gated behind the Confidential
  // Export permission. Every row is built straight from its own transaction
  // record (`p`), so rates can never shift, mix, or inherit across rows.
  function exportConfidential() {
    const rows = filtered.map((p) => {
      const c = window.GstEngine.recalcRecord(p);
      return { id: p.id, subtotal: c.subtotal, gstAmount: c.gstAmount, total: c.total, _p: p, _c: c };
    });
    const check = window.ExportPermission ? window.ExportPermission.validateExportIntegrity(rows, { rateKeys: ['subtotal', 'total'] }) : { ok: true };
    if (!check.ok) { window.toast && window.toast(check.reason || 'Export blocked — data integrity check failed', 'er'); return; }
    // Canonical source-company attribution (erp/company-attribution.js).
    // REPORT SCOPE ≠ TRANSACTION COMPANY: the column is resolved per record,
    // never from the active company selector.
    const _q  = v => '"' + String(v==null?'':v).replace(/"/g,'""') + '"';
    const _co = r => window.ERPCompanyAttribution
      ? window.ERPCompanyAttribution.resolveTransactionCompany(r).companyName
      : (Store.name('companies', r && r.companyId) || 'Unassigned');
    const _coHdr = isGroup ? 'OM Group Company,' : '';
    const _coCell = r => isGroup ? _q(_co(r)) + ',' : '';
    const hdr = _coHdr + 'Date,Vendor,Material,Vehicle No,Quantity,UOM,Challan No,Rate,Subtotal (Pre-GST),GST Amount,Total+GST,Status';
    // Rate is read directly off the original purchase's first line item —
    // the exact value stored when this purchase was created. Never
    // recalculated, never pulled from the current Material/Price Master.
    const csvRows = rows.map(({ _p: p, _c: c }) => {
      const mat = p.items?.[0];const matName = mat ? Store.name('materials', mat.materialId) : '';
      const qty = p.items ? p.items.reduce((s, i) => s + (parseFloat(i.quantity) || 0), 0) : 0;
      const rate = mat?.ratePerTon ?? '';
      return _coCell(p) + [p.date, Store.name('vendors', p.vendorId), matName, p.vehicleFull || '', window.formatQuantityRaw(qty), mat?.uom || 'MT', p.challanNumber || '', rate, c.subtotal, c.gstAmount, c.total, p.status].map(_q).join(',');
    }).join('\r\n');
    const blob = new Blob(['\uFEFF' + hdr + '\r\n' + csvRows], { type: 'text/csv;charset=utf-8' });const a = document.createElement('a');a.href = URL.createObjectURL(blob);a.download = 'purchases_confidential.csv';a.click();
    Store.addLog('EXPORT', 'Purchase', `Confidential export: ${filtered.length} records`);
    window.toast && window.toast('Confidential CSV exported', 'ok');
  }
  const exportCSV = exportStandard;
  const canExportConfidential = !!(window.ExportPermission && window.ExportPermission.canExportConfidential(session));

  const fpFields = [
  { key: 'dateFrom', label: 'Start Date', type: 'date' },
  { key: 'dateTo', label: 'End Date', type: 'date' },
  { key: 'status', label: 'Status', width: 120, options: (window.STATUS_OPTIONS || ['Pending', 'Delivered', 'Cancelled']).map((s) => ({ value: s, label: s })) },
  { key: 'vendorId', label: 'Vendor', width: 160, options: vendors.map((v) => ({ value: v.id, label: v.name })) },
  { key: 'materialId', label: 'Material', width: 130, options: materials.map((m) => ({ value: m.id, label: m.name })) },
  { key: 'crusherId', label: 'Crusher', width: 150, options: crushers.map((c) => ({ value: c.id, label: c.name })) }];


  return (
    <div>
      <div className="ph">
        <div><h1>Purchases</h1><p>Incoming material purchase orders</p></div>
        <div className="ph-act">
          <button className={`btn btn-sm ${showFP ? 'btn-or' : 'btn-wh'}`} onClick={() => setShowFP((p) => !p)}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3" /></svg>
            Filters {activeFilters > 0 && <span style={{ background: '#fff', color: 'var(--or)', borderRadius: 10, padding: '0 4px', fontSize: 10, fontWeight: 700, marginLeft: 2 }}>{activeFilters}</span>}
          </button>
          <window.ExportMenu onStandard={exportStandard} onConfidential={exportConfidential} canConfidential={canExportConfidential} label="Export CSV" />
          <button className="btn btn-or" onClick={openAdd} disabled={(() => { const ls = (Store.loadState && Store.loadState('purchases')) || { state: 'OK' }; return ls.state === 'ERROR' || ls.state === 'BLOCKED'; })()} title="Purchases storage is locked — open Data Health to inspect before adding new records"><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> Add Purchase</button>
        </div>
      </div>

      <window.FilterPanel show={showFP} fields={fpFields} values={fv}
      onChange={(k, v) => setFv((p) => ({ ...p, [k]: v }))}
      onApply={applyFP} onRefresh={refreshFP} onExport={exportCSV} onClear={clearFP} />

      <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={(e) => {setSearch(e.target.value);setPage(1);}} placeholder="Search challan, vehicle, vendor…" />
        </div>
        {(search || activeFilters > 0) && <button className="btn btn-gh btn-sm" onClick={clearFP}>Clear All</button>}
        <span className="f-cnt">{filtered.length} records</span>
      </div>

      {/* Table */}
      <div className="card">
        <div className="tbl-w">
          <table className="tbl">
            <thead>
              <tr><th style={{ width: 26, padding: '7px 4px' }}></th><th>DATE</th>{isGroup && <th>OM GROUP COMPANY</th>}<th>VENDOR</th><th>MATERIAL</th><th>VEHICLE NO.</th><th>QUANTITY</th><th>UOM</th><th>CHALLAN NO.</th><th style={{whiteSpace:'nowrap'}}>AMOUNT</th><th style={{whiteSpace:'nowrap'}}>AMT + GST</th><th>STATUS</th><th>ACTIONS</th></tr>
            </thead>
            <tbody>
              {paged.length === 0 ?
              <tr className="empty"><td colSpan={12 + (isGroup ? 1 : 0)} style={{ textAlign: 'center', padding: 34, color: 'var(--txt2)' }}>{(() => {
                // EMPTY and ERROR are different states and must never be shown as the same thing.
                const ls = (Store.loadState && Store.loadState('purchases')) || { state: 'OK' };
                if (ls.state === 'LOADING') return <span>Loading purchase records…</span>;
                if (ls.state === 'ERROR' || ls.state === 'BLOCKED') return (
                  <span style={{ color: '#991B1B', fontWeight: 600 }}>
                    Purchase data could not be loaded. <strong>No records have been deleted.</strong><br />
                    <span style={{ fontWeight: 400, fontSize: 12 }}>Storage read failure ({ls.detail && (ls.detail.reason || 'write blocked by fail-safe')}) — the stored records are locked against overwriting. Open <strong>Data Health</strong> to inspect and recover.</span>
                  </span>
                );
                const total = (Store.data.purchases || []).length;
                if (total === 0) return <span>No purchase records exist yet in this company database.</span>;
                if (items.length === 0) return <span>No purchase records for the selected company scope — {total} record{total !== 1 ? 's' : ''} exist in other companies.</span>;
                return <span>No purchase records match the current filters — {items.length} record{items.length !== 1 ? 's' : ''} available in this scope.</span>;
              })()}</td></tr> :
              paged.map((po) => {
                const isOpen = poExpand === po.id;
                const firstItem = po.items?.[0];
                const matName = firstItem ? Store.name('materials', firstItem.materialId) : Store.name('materials', po.materialId);
                const totalQty = po.items ? po.items.reduce((s, i) => s + (parseFloat(i.quantity) || 0), 0) : 0;
                const uom = firstItem?.uom || 'MT';
                return (
                  <React.Fragment key={po.id}>
                      <tr>
                        <td style={{ textAlign: 'center', padding: '5px 4px', cursor: 'pointer', width: 26 }} onClick={() => setPoExpand(isOpen ? null : po.id)}>
                          <span style={{ color: 'var(--or)', fontSize: 9, display: 'inline-block', transition: 'transform .15s', transform: isOpen ? 'rotate(90deg)' : 'none' }}>&#9658;</span>
                        </td>
                        <td>{window.fmtDate(po.date)}</td>
                        {isGroup && <td><span className="bdg bg-or" style={{ fontSize: 10, padding: '1px 5px' }}>{Store.name('companies', po.companyId)}</span></td>}
                        <td style={{ fontWeight: 500 }}>{Store.name('vendors', po.vendorId)}</td>
                        <td>{matName || '—'}</td>
                        <td><span style={{ fontFamily: 'var(--font)', fontSize: 11, background: '#F9FAFB', padding: '1px 5px', borderRadius: 3 }}>{po.vehicleFull || '—'}</span></td>
                        <td style={{ fontWeight: 600 }}>{window.formatQuantity(totalQty)}</td>
                        <td style={{ color: 'var(--txt2)' }}>{uom}</td>
                        <td style={{ fontFamily: 'var(--font)', fontSize: 11.5 }}>{po.challanNumber || '—'}</td>
                        <td style={{ fontWeight: 600 }}>{window.fmtCur(window.gSub(po))}</td>
                        <td style={{ fontWeight: 700, color: 'var(--ok)' }}>{window.fmtCur(window.gAmt(po))}</td>
                        <td><window.Badge v={po.status} /></td>
                        <td><div className="ra"><button className="btn btn-wh btn-sm" onClick={() => openEdit(po)}>Edit</button><button className="btn btn-wh btn-sm" onClick={() => setPoStatement(po)}>Statement</button><button className="btn btn-rd btn-sm" onClick={() => setDelId(po.id)}>Delete</button></div></td>
                      </tr>
                      {isOpen && (() => {
                      const _vend = Store.byId('vendors', po.vendorId)||{};
                      const _subTotal = (po.items||[]).reduce((s,i)=>(s+(parseFloat(i.quantity)||0)*(parseFloat(i.ratePerTon)||0)),0);
                      const _gstTotal = window.gGst(po);
                      return (
                        <tr key={po.id+'-exp'}>
                          <td colSpan={12+(isGroup?1:0)} style={{padding:0,background:'#FAFAF8',borderTop:'2px solid var(--or-bdr)'}}>
                            <div style={{padding:'14px 18px 16px'}}>

                              {/* Row 1: General • Vendor • Transport */}
                              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:10,marginBottom:10}}>
                                <PoDrillSection title="General Information" color="#1D4ED8">
                                  <PoDrillKV label="PO Reference" value={po.id?po.id.slice(0,8).toUpperCase():'—'} mono bold/>
                                  <PoDrillKV label="Date" value={window.fmtDate(po.date)}/>
                                  <PoDrillKV label="Status" value={po.status}
                                    color={po.status==='Delivered'?'var(--ok)':po.status==='Cancelled'?'var(--err)':'var(--warn)'} bold/>
                                  <PoDrillKV label="Company" value={Store.name('companies',po.companyId)}/>
                                  {po.challanNumber && <PoDrillKV label="Challan Number" value={po.challanNumber} mono/>}
                                  {po.royaltyPass  && <PoDrillKV label="Royalty Pass"   value={po.royaltyPass}   mono/>}
                                  <PoDrillKV label="Vendor Settlement" value={po.createVendorSettlement==='Yes' ? (po.vendorSettlementStatus||'Pending') : 'Not Enabled'} bold color={po.createVendorSettlement==='Yes' ? 'var(--ok)' : 'var(--txt3)'}/>
                                  {po.createdBy   && <PoDrillKV label="Created By"    value={po.createdBy}/>}
                                </PoDrillSection>

                                <PoDrillSection title="Vendor Information" color="var(--or)">
                                  <PoDrillKV label="Vendor" value={Store.name('vendors',po.vendorId)} bold/>
                                  {po.toCustomerId && <PoDrillKV label="To Customer (Site)" value={Store.name('customers',po.toCustomerId)} bold color="var(--info)"/>}
                                  {po.pickupAddress && <PoDrillKV label="Pickup Address" value={po.pickupAddress}/>}
                                  {_vend.address   && !po.pickupAddress && <PoDrillKV label="Vendor Address" value={_vend.address}/>}
                                  {_vend.gst       && <PoDrillKV label="GST Number"     value={_vend.gst}     mono/>}
                                  {_vend.mobile    && <PoDrillKV label="Contact"        value={_vend.mobile}   mono/>}
                                  {_vend.contactPerson && <PoDrillKV label="Contact Person" value={_vend.contactPerson}/>}
                                </PoDrillSection>

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

                              {/* Material Details */}
                              <div style={{marginBottom:10}}>
                                <div style={{fontWeight:700,fontSize:10.5,color:'var(--or)',marginBottom:7,textTransform:'uppercase',letterSpacing:'.06em'}}>Material Details</div>
                                <table style={{width:'100%',borderCollapse:'collapse',fontSize:12,border:'1px solid var(--bdr)',borderRadius:6,overflow:'hidden'}}>
                                  <thead><tr style={{background:'#F9FAFB'}}>
                                    {['MATERIAL','CRUSHER SITE','QTY','UOM','RATE ₹/T','GST %','GST AMT','LINE TOTAL'].map(h=>(
                                      <th key={h} style={{padding:'6px 8px',textAlign:['QTY','RATE ₹/T','GST AMT','LINE TOTAL'].includes(h)?'right':'left',fontWeight:700,fontSize:10.5,color:'var(--txt3)',borderBottom:'1px solid var(--bdr)',textTransform:'uppercase',letterSpacing:'.04em'}}>{h}</th>
                                    ))}
                                  </tr></thead>
                                  <tbody>
                                    {(po.items||[]).map((it,i)=>(
                                      <tr key={i} style={{borderBottom:'1px solid #F3F4F6'}}>
                                        <td style={{padding:'6px 8px',fontWeight:500}}>{Store.name('materials',it.materialId)||'—'}</td>
                                        <td style={{padding:'6px 8px',color:'var(--txt2)',fontSize:11.5}}>{Store.name('crushers',it.crusherSite)||'—'}</td>
                                        <td style={{padding:'6px 8px',textAlign:'right',fontWeight:600}}>{window.formatQuantity(it.quantity)}</td>
                                        <td style={{padding:'6px 8px',color:'var(--txt2)'}}>{it.uom||'MT'}</td>
                                        <td style={{padding:'6px 8px',textAlign:'right'}}>{window.fmtCur(it.ratePerTon||0)}</td>
                                        <td style={{padding:'6px 8px',color:'var(--txt2)'}}>{it.gstPercent||0}%</td>
                                        <td style={{padding:'6px 8px',textAlign:'right'}}>{window.fmtCur(window.gItemAmt(it)-(Number(it.quantity||0)*Number(it.ratePerTon||0)))}</td>
                                        <td style={{padding:'6px 8px',textAlign:'right',fontWeight:600,color:'var(--or)'}}>{window.fmtCur(window.gItemAmt(it))}</td>
                                      </tr>
                                    ))}
                                    {(!po.items||po.items.length===0)&&(
                                      <tr><td colSpan="8" style={{padding:'14px',textAlign:'center',color:'var(--txt3)',fontStyle:'italic',fontSize:11}}>No item details available</td></tr>
                                    )}
                                  </tbody>
                                </table>
                              </div>

                              {/* Financial Summary + Remarks */}
                              <div style={{display:'grid',gridTemplateColumns:po.notes?'1fr 2fr':'1fr',gap:10}}>
                                <PoDrillSection title="Financial Summary" color="var(--or)" bg="#FFF9F5">
                                  <PoDrillKV label="Subtotal"    value={window.fmtCur(_subTotal)}/>
                                  <PoDrillKV label="Total GST"   value={window.fmtCur(_gstTotal)}/>
                                  <PoDrillKV label="Grand Total" value={window.fmtCur(window.gAmt(po))} color="var(--or)" bold/>
                                </PoDrillSection>
                                {po.notes && (
                                  <PoDrillSection title="Remarks" color="#6B7280">
                                    <div style={{fontSize:12,color:'var(--txt)',lineHeight:1.6}}>{po.notes}</div>
                                  </PoDrillSection>
                                )}
                              </div>

                            </div>
                          </td>
                        </tr>
                      );
                    })()}
                    
                    </React.Fragment>);

              })}
            </tbody>
            {filtered.length > 0 && <tfoot>
              <tr style={{ background: 'var(--or-lt)', position: 'sticky', bottom: 0, zIndex: 2 }}>
                {/* expand + DATE + [COMPANY] + VENDOR + MATERIAL + VEHICLE */}
                <td colSpan={isGroup ? 6 : 5} style={{ borderTop: '2px solid var(--or-bdr)', padding: '9px 14px', fontSize: 12, fontWeight: 700, color: 'var(--txt2)', whiteSpace: 'nowrap' }}>
                  TOTALS — {filtered.length} Record{filtered.length !== 1 ? 's' : ''}
                </td>
                {/* QUANTITY */}
                <td style={{ padding: '9px 14px', fontWeight: 700, fontSize: 12, borderTop: '2px solid var(--or-bdr)', whiteSpace: 'nowrap' }}>{window.formatQuantity(poTotals.qty)}</td>
                {/* UOM */}
                <td style={{ borderTop: '2px solid var(--or-bdr)', padding: '9px 6px', color: 'var(--txt2)', fontSize: 11 }}>MT</td>
                {/* CHALLAN */}
                <td style={{ borderTop: '2px solid var(--or-bdr)' }}></td>
                {/* AMOUNT (w/o GST) */}
                <td style={{ padding: '9px 14px', fontWeight: 700, fontSize: 12, borderTop: '2px solid var(--or-bdr)', whiteSpace: 'nowrap', color: 'var(--txt)' }}>{window.fmtCur(poTotals.amtNoGST)}</td>
                {/* AMT + GST */}
                <td style={{ padding: '9px 14px', fontWeight: 700, fontSize: 13, borderTop: '2px solid var(--or-bdr)', whiteSpace: 'nowrap', color: 'var(--or)' }}>{window.fmtCur(poTotals.amtWithGST)}</td>
                {/* STATUS + ACTIONS */}
                <td colSpan={2} style={{ borderTop: '2px solid var(--or-bdr)' }}></td>
              </tr>
            </tfoot>}
          </table>
        </div>
      </div>

      {totalPgs > 1 && <div className="pag"><button className="pg-b" onClick={() => setPage(1)} disabled={page === 1}>«</button><button className="pg-b" onClick={() => setPage((p) => p - 1)} disabled={page === 1}>‹</button><span className="pg-inf">Page {page} of {totalPgs}</span><button className="pg-b" onClick={() => setPage((p) => p + 1)} disabled={page === totalPgs}>›</button><button className="pg-b" onClick={() => setPage(totalPgs)} disabled={page === totalPgs}>»</button></div>}

      {/* Add/Edit Modal */}
      {modal &&
      <div className="mbg">
          <div className="mod mod-xl" style={{ maxHeight: '92vh' }}>
            <div className="mod-hd"><h2>{editId ? 'Edit' : 'Add'} Purchase Order</h2><button className="mod-x" onClick={() => setModal(false)}>×</button></div>
            <form onSubmit={handleSave}>
              <div className="mod-bd">
                {isGroup && <window.GroupCompanyField value={form.companyId} onChange={(v) => setF('companyId', v)} />}
                <PSH title="Purchase Details" />
                {/* Row 1: Vendor, Order Date, Status */}
                <div className="fg3" style={{ marginBottom: 10 }}>
                  <div className="fld"><label>Vendor <span className="req">*</span></label><window.FormSelect placeholder="Select Vendor" value={form.vendorId || ''} onChange={(v) => setF('vendorId', v)} options={vendors.map((v) => ({value:v.id,label:v.name}))}/></div>
                  <div className="fld"><label>Order Date <span className="req">*</span></label><input className="inp" type="date" value={form.date || ''} onChange={(e) => setF('date', e.target.value)} required /></div>
                  <div className="fld"><label>Status <span className="req">*</span></label><window.FormSelect value={form.status || 'Pending'} onChange={(v) => setF('status', v)} options={['Pending', 'Delivered', 'Cancelled'].map((s) => ({value:s,label:s}))}/></div>
                </div>
                {/* To Customer — optional, for site-specific rate lookup */}
                <div className="fg3" style={{marginBottom:10}}>
                  <div className="fld">
                    <label>To Customer <span style={{fontSize:10,color:'var(--txt3)',fontWeight:400}}>(site-specific rate, optional)</span></label>
                    <window.FormSelect placeholder="— None (use general vendor rate) —" value={form.toCustomerId||''} onChange={v => setF('toCustomerId', v)} options={customers.map(c => ({value:c.id,label:c.name}))}/>
                  </div>
                  {form.toCustomerId && (
                    <div style={{gridColumn:'span 2',display:'flex',alignItems:'flex-end',paddingBottom:6}}>
                      <div style={{fontSize:11.5,color:'var(--info)',display:'flex',alignItems:'center',gap:6,fontWeight:500}}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/></svg>
                        Rate will be looked up for <strong style={{marginLeft:3}}>{Store.name('customers', form.toCustomerId)}</strong> — falls back to general vendor rate if no site-specific PO found.
                      </div>
                    </div>
                  )}
                </div>
                {/* Row 2: Pickup Address, Challan Number */}
                <div className="fg" style={{ marginBottom: 10 }}>
                  <div className="fld"><label>Pickup Address</label><input className="inp" value={form.pickupAddress || ''} onChange={(e) => setF('pickupAddress', e.target.value)} placeholder={form.vendorId ? 'No pickup address in Vendor Master — enter manually' : 'Auto-populated when vendor is selected'} /></div>
                  <div className="fld"><label>Challan Number</label><input className="inp" value={form.challanNumber || ''} onChange={(e) => setF('challanNumber', e.target.value)} placeholder="CH-0001" /></div>
                </div>
                {/* Row 2b: Transporter + Vehicle (both required) */}
                <div className="fg3" style={{ marginBottom: 10 }}>
                  <div className="fld">
                    <label>Transporter Name <span className="req">*</span></label>
                    <window.SearchableSelect
                    options={tmActive.map((t) => ({ value: t.id, label: t.name }))}
                    value={form.transporterMasterId || ''}
                    onChange={(v, label) => setForm((p) => ({ ...p, transporterMasterId: v, transporterName: label || '', vehicleFull: '' }))}
                    placeholder="Search transporter…"
                    noOptionsMsg={tmActive.length === 0 ? 'No active transporters — add them in Transporter Master first' : 'No transporter matches'} />
                  
                    {tmActive.length === 0 && <div style={{ fontSize: 10.5, color: 'var(--warn)', marginTop: 3 }}><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',flexShrink:0,marginRight:4}}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>No active transporters found. Add transporters in Transporter Master first.</div>}
                  </div>
                  <div className="fld">
                    <label>Vehicle Number <span className="req">*</span>{tmVehicles.length > 0 && <span style={{ fontSize: 10, color: 'var(--txt2)', fontWeight: 400, marginLeft: 4 }}>({tmVehicles.length} vehicles)</span>}</label>
                    <window.SearchableSelect
                    options={tmVehicles.map((v) => ({ value: v.vehicleNumber, label: v.vehicleNumber + (v.vehicleType ? ' (' + v.vehicleType + ')' : '') }))}
                    value={form.vehicleFull || ''}
                    onChange={(v) => setF('vehicleFull', v)}
                    placeholder={!form.transporterMasterId ? 'Select a transporter first…' : tmVehicles.length === 0 ? 'No active vehicles for this transporter' : 'Search vehicle number…'}
                    noOptionsMsg={!form.transporterMasterId ? 'Select a transporter first' : 'No vehicles match'}
                    inputStyle={{ fontFamily: 'var(--font)', fontWeight: 600 }} />
                  
                  </div>
                </div>
                {/* Row 3: Royalty Pass, Diesel Source, Diesel Qty */}
                <div className="fg3" style={{ marginBottom: 16 }}>
                  <div className="fld"><label>Royalty Pass</label><input className="inp" value={form.royaltyPass || ''} onChange={(e) => setF('royaltyPass', e.target.value)} placeholder="RP-10001" /></div>
                  <div className="fld"><label>Diesel Source</label><window.FormSelect placeholder="Select Source" value={form.dieselSource || ''} onChange={(v) => setF('dieselSource', v)} options={dieselSources.filter((s) => s.status !== 'Inactive').map((s) => ({value:s.name,label:s.name}))}/></div>
                  <div className="fld"><label>Diesel Quantity (Litres)</label><input className="inp" type="number" value={form.dieselQty || ''} onChange={(e) => setF('dieselQty', e.target.value)} placeholder="0" min="0" /></div>
                </div>
                {/* Row 3b: Vendor Settlement linkage — Transport arrangement + settlement flag */}
                <div className="fg3" style={{ marginBottom: 16 }}>
                  <div className="fld">
                    <label>Transport <span style={{fontSize:10,color:'var(--txt3)',fontWeight:400}}>(who arranged transport?)</span></label>
                    <window.FormSelect value={form.transportThirdParty || 'No'} onChange={(v) => setF('transportThirdParty', v)} options={[{value:'No',label:"No — Vendor's Own Transport"},{value:'Yes',label:'Yes — Third-Party Transporter'}]}/>
                    <span style={{fontSize:10.5,color:'var(--txt2)',marginTop:3,display:'block'}}>Third-party transport trips are settled in Transporter Settlement. The vendor material cost is settled in Vendor Settlement when "Create Vendor Settlement" is Yes.</span>
                  </div>
                  <div className="fld">
                    <label>Create Vendor Settlement</label>
                    <window.FormSelect value={form.createVendorSettlement || 'No'} onChange={(v) => setF('createVendorSettlement', v)} options={[{value:'No',label:'No'},{value:'Yes',label:'Yes'}]}/>
                    <span style={{fontSize:10.5,color:'var(--txt2)',marginTop:3,display:'block'}}>Yes generates a linked Vendor Settlement entry once this order is delivered/completed.</span>
                  </div>
                </div>
                {/* Item Details */}
                <PSH title="Item Details" action={<button type="button" className="btn btn-or btn-sm" onClick={addRow}><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> Add Item</button>} />
                {/* Auto-fill rate banner */}
                {activePO &&
              <div style={{ background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 4, padding: '8px 12px', marginBottom: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
                    <span style={{ fontSize: 11.5, fontWeight: 600, color: '#166534' }}><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',marginRight:4}}><path d="M5 13l4 4L19 7"/></svg>AUTO-FILL ACTIVE — Rates from <span style={{ fontFamily: 'var(--font)' }}>{activePO.poNumber}</span>{activePO.siteSpecific && <span style={{marginLeft:7,fontSize:10,background:'#DCFCE7',color:'#166534',padding:'1px 6px',borderRadius:4,fontWeight:700,letterSpacing:'.03em'}}>SITE-SPECIFIC{activePO.toCustomerName ? ` · ${activePO.toCustomerName}` : ''}</span>}</span>
                    <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 12 }}>
                      <input type="checkbox" checked={overrideRate} onChange={(e) => setOverrideRate(e.target.checked)} style={{ accentColor: 'var(--warn)' }} />
                      <span style={{ color: 'var(--txt2)', fontWeight: 500 }}>Override Auto-Filled Rate</span>
                    </label>
                  </div>
              }
                {!activePO && form.vendorId &&
              <div style={{ background: '#FFFBF5', border: '1px solid var(--or-bdr)', borderRadius: 4, padding: '7px 12px', marginBottom: 10, fontSize: 11.5, color: 'var(--txt2)' }}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',flexShrink:0,marginRight:4}}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>No active Price Order found for this vendor. Enter rates manually or create a Price Order first.
                  </div>
              }
                <div className="ig">
                  {/* table-layout:fixed is set via .ig table CSS.
                      colgroup pixel widths lock every column absolutely —
                      no value, no material name, no conversion result can
                      shrink or stretch a neighbour column. */}
                  <table style={{ tableLayout: 'fixed', width: '100%' }}>
                    <colgroup>
                      <col style={{ width: '20%' }} />{/* Material        */}
                      <col style={{ width: '15%' }} />{/* Crusher Site    */}
                      <col style={{ width: '10%' }} />{/* UOM             */}
                      <col style={{ width: '10%' }} />{/* Quantity        */}
                      <col style={{ width: '12%' }} />{/* Conversion ─ FIXED */}
                      <col style={{ width: '16%' }} />{/* Rate Per Ton ─ FIXED */}
                      <col style={{ width: '8%'  }} />{/* GST %           */}
                      <col style={{ width: '9%'  }} />{/* Amount (read)   */}
                      <col style={{ width: '4%'  }} />{/* ×               */}}
                    </colgroup>
                    <thead>
                      <tr>
                        <th>Material</th>
                        <th>Crusher Site</th>
                        <th>UOM</th>
                        <th>Quantity</th>
                        <th>Conversion</th>
                        <th>Rate Per Ton ₹</th>
                        <th>GST %</th>
                        <th style={{textAlign:'right'}}>Amount ₹</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody>
                      {gridItems.map((row, idx) => {
                        const rowAmt = (parseFloat(row.quantity)||0) * (parseFloat(row.ratePerTon)||0);
                        return (
                          <tr key={row.id}>
                            {/* Material */}
                            <td><select value={row.materialId} onChange={(e) => updateRow(idx, 'materialId', e.target.value)} style={{ width: '100%' }}><option value="">Select</option>{materials.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}</select></td>
                            {/* Crusher Site */}
                            <td><select value={row.crusherSite} onChange={(e) => updateRow(idx, 'crusherSite', e.target.value)} style={{ width: '100%' }}><option value="">Select</option>{crushers.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}</select></td>
                            {/* UOM */}
                            <td><select value={row.uom||'MT'} onChange={(e) => updateRow(idx, 'uom', e.target.value)} style={{ width: '100%', minWidth: 56 }}><option value="MT">MT</option><option value="Ton">Ton</option><option value="CUM">CUM</option><option value="CFT">CFT</option><option value="Kg">Kg</option></select></td>
                            {/* Quantity */}
                            <td>
                              <input type="number" value={row.quantity} onChange={(e) => updateRow(idx, 'quantity', e.target.value)} style={{ width: '100%' }} min="0" step="0.001" placeholder="0.000" />
                            </td>
                            {/* Conversion — dedicated fixed-width column.
                                Two-line twoLine badge; always same height via reserved line 2.
                                overflow:hidden on the td (from .ig tbody td CSS) clips any overflow. */}
                            <td style={{ verticalAlign: 'middle', padding: '4px 6px' }}>
                              {!!window.ConversionBadge
                                ? <window.ConversionBadge materialId={row.materialId} qty={row.quantity} rate={row.ratePerTon} unit={row.uom} twoLine />
                                : null}
                            </td>
                            {/* Rate Per Ton — fixed width; AUTO label has fixed 14px height slot */}
                            <td style={{ padding: '5px 6px' }}>
                              <input type="number" value={row.ratePerTon}
                                onChange={(e) => (overrideRate || !row._autoFilled) && updateRow(idx, 'ratePerTon', e.target.value)}
                                readOnly={!!(row._autoFilled && !overrideRate)}
                                style={{ width: '100%', background: row._autoFilled && !overrideRate ? '#F0FDF4' : '#fff', cursor: row._autoFilled && !overrideRate ? 'not-allowed' : 'text' }}
                                min="0" step="0.01" placeholder="0.00" />
                              {/* Fixed-height status label — always 14px so all rows match */}
                              <div style={{ height: 14, overflow: 'hidden', fontSize: 9, fontWeight: 700, lineHeight: '14px', marginTop: 1, whiteSpace: 'nowrap' }}>
                                {row._autoFilled && !overrideRate
                                  ? <span style={{ color: '#166534', display:'inline-flex', alignItems:'center', gap:2 }}>AUTO <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg></span>
                                  : row._autoFilled && overrideRate
                                    ? <span style={{ color: '#92400E' }}>OVERRIDE</span>
                                    : null}
                              </div>
                            </td>
                            {/* GST % */}
                            <td><input type="number" value={row.gstPercent} onChange={(e) => updateRow(idx, 'gstPercent', e.target.value)} style={{ width: '100%' }} min="0" max="28" placeholder="5" /></td>
                            {/* Amount (read-only) */}
                            <td style={{ textAlign: 'right' }}>
                              <span className="ro" style={{ fontWeight: 600, color: 'var(--or)', fontSize: 11.5 }}>{window.fmtCur(rowAmt)}</span>
                            </td>
                            {/* Delete */}
                            <td style={{ textAlign: 'center' }}>
                              {gridItems.length > 1 && <button type="button" onClick={() => removeRow(idx)} style={{ background: 'none', border: 'none', color: 'var(--err)', cursor: 'pointer', fontSize: 18, padding: '0 4px', lineHeight: 1 }}>×</button>}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                    <tfoot>
                      <tr><td colSpan="6" style={{ textAlign: 'right', fontWeight: 600, color: 'var(--txt2)', background: '#F9FAFB', padding: '6px 8px', borderTop: '1px solid var(--bdr)' }}>Subtotal:</td><td colSpan="2" style={{ fontWeight: 700, background: '#F9FAFB', padding: '6px 8px', borderTop: '1px solid var(--bdr)', textAlign:'right' }}>{window.fmtCur(totals.sub)}</td><td style={{ background: '#F9FAFB', borderTop: '1px solid var(--bdr)' }}></td></tr>
                      <tr><td colSpan="6" style={{ textAlign: 'right', fontWeight: 600, color: 'var(--txt2)', background: '#F9FAFB', padding: '5px 8px' }}>GST:</td><td colSpan="2" style={{ fontWeight: 700, background: '#F9FAFB', padding: '5px 8px', textAlign:'right' }}>{window.fmtCur(totals.gst)}</td><td style={{ background: '#F9FAFB' }}></td></tr>
                      <tr><td colSpan="6" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--or)', background: '#F9FAFB', padding: '6px 8px' }}>Total:</td><td colSpan="2" style={{ fontWeight: 700, fontSize: 13, color: 'var(--or)', background: '#F9FAFB', padding: '6px 8px', textAlign:'right' }}>{window.fmtCur(totals.total)}</td><td style={{ background: '#F9FAFB' }}></td></tr>
                    </tfoot>
                  </table>
                </div>
              </div>
              <div className="mod-ft"><button type="button" className="btn btn-wh" onClick={() => setModal(false)}>Cancel</button><button type="submit" className="btn btn-or">{editId ? 'Update Purchase' : 'Create Purchase Order'}</button></div>
            </form>
          </div>
        </div>
      }
      {delId && <window.Confirm onOk={handleDelete} onCancel={() => setDelId(null)} />}
      {poStatement && <window.PurchaseBillStatement purchase={poStatement} onClose={() => setPoStatement(null)} session={null} />}
    </div>);

}
window.PurchasesPage = PurchasesPage;