/* ============================================================
   ELECTROMED — Sales (Invoices · Quotations · Sleep Tests)
   ============================================================ */
function Sales({ branch, go }) {
  const [mode, setMode] = useState('Invoices');
  return (
    <div className="view-enter">
      <PageHead eyebrow="02 · Sales Management" title="Sales"
        sub="Quotations, GST & non-GST invoicing, sleep-test bookings and the guided sale workflow."
        actions={
          <div className="tabs">
            {['Invoices', 'Quotations', 'Sleep Tests'].map((m) => (
              <button key={m} className={cls('tab', mode === m && 'active')} onClick={() => setMode(m)}>{m}</button>
            ))}
          </div>
        } />
      {mode === 'Invoices'   && <InvoicesView branch={branch} />}
      {mode === 'Quotations' && window.Quotations  && <window.Quotations branch={branch} />}
      {mode === 'Sleep Tests'&& window.SleepTests  && <window.SleepTests branch={branch} />}
    </div>
  );
}

function InvoicesView({ branch }) {
  const { PKR } = window.DATA;
  const [tab, setTab] = useState('All');
  const [q,   setQ]   = useState('');
  const [sel, setSel] = useState(null);
  const [wf,  setWf]  = useState(false);

  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: invoices, loading, error, refetch } = useInvoices(bf);

  const list = invoices.filter((i) =>
    (tab === 'All' || i.status === tab) &&
    ((i.invoice_number || '').toLowerCase().includes(q.toLowerCase()) ||
     (i.customer_name  || '').toLowerCase().includes(q.toLowerCase()) ||
     (i.serial         || '').toLowerCase().includes(q.toLowerCase()))
  );

  const sum = (k) => invoices.reduce((s, i) => s + parseFloat(i[k] || 0), 0);
  const outstanding = sum('amount') - sum('received');

  if (loading) return <div className="card card-pad" style={{ textAlign: 'center', padding: 40 }}>Loading invoices…</div>;
  if (error)   return <div className="card card-pad" style={{ color: 'var(--bad)' }}>Error: {error}</div>;

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.sales size={18} />} label="Invoiced (Total)" value={PKR(sum('amount'))} sub="this month" />
        <StatCard icon={<Icons.check size={18} />} label="Received"         value={PKR(sum('received'))} />
        <StatCard icon={<Icons.clock size={18} />} label="Outstanding"      value={PKR(Math.max(0, outstanding))} accent />
        <StatCard icon={<Icons.doc   size={18} />} label="Invoices"         value={invoices.length} />
      </div>

      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <Tabs tabs={['All', 'Paid', 'Partial', 'Unpaid', 'Overdue']} value={tab} onChange={setTab} />
          <div className="row" style={{ gap: 10 }}>
            <SearchBox value={q} onChange={setQ} placeholder="Invoice, customer or serial…" w={240} />
            {window.can('sales','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setWf(true)}>New Sale</Btn>}
          </div>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr>
              <th>Invoice</th><th>Customer</th><th>Device / Serial</th><th>Tax</th><th>Amount</th><th>Received</th><th>Salesperson</th><th>Status</th>
            </tr></thead>
            <tbody>
              {list.map((i) => (
                <tr key={i.id} style={{ cursor: 'pointer' }} onClick={() => setSel(i)}>
                  <td className="mono" style={{ fontWeight: 700 }}>{i.invoice_number}</td>
                  <td style={{ fontWeight: 600 }}>{i.customer_name}</td>
                  <td>
                    <div style={{ fontWeight: 600 }}>{i.device}</div>
                    <div className="tiny muted mono">{i.serial}</div>
                  </td>
                  <td><Badge kind={i.gst ? 'info' : 'idle'}>{i.gst ? 'GST 17%' : 'Non-GST'}</Badge></td>
                  <td className="mono" style={{ fontWeight: 700 }}>{PKR(i.amount)}</td>
                  <td className="mono muted">{PKR(i.received)}</td>
                  <td className="tiny">{i.rep}</td>
                  <td><Badge kind={window.statusKind(i.status)}>{i.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {!list.length && <div className="ph-img" style={{ height: 120, margin: 18 }}>no invoices match</div>}
      </div>

      {sel && <InvoiceDetail i={sel} onClose={() => { setSel(null); refetch(); }} />}
      {wf  && <SaleWorkflow  branch={branch} onClose={() => { setWf(false);  refetch(); }} />}
    </div>
  );
}

function InvoiceDetail({ i, onClose }) {
  const D = window.DATA; const { PKR } = D;
  const { data: companies } = useCompanies();
  const defaultCo = { name: 'Electromed Corporation', letterhead: 'Respiratory & Sleep Care', addr: 'Karachi', phone: '', email: '', ntn: '—', strn: '—', gstRate: 17, bank: '—', color: 'var(--forest-2)' };
  const [companyId, setCompanyId] = useState(i.company || i.company_id || '');
  React.useEffect(() => { if (!companyId && companies.length) setCompanyId(companies[0].id); }, [companies.length]);
  const [gst, setGst] = useState(!!i.gst);
  const docRef = useRef(null);
  const co = companies.find((c) => c.id === companyId) || defaultCo;
  const net  = parseFloat(i.amount  || 0);
  const recv = parseFloat(i.received || 0);
  const base = gst ? Math.round(net / (1 + (co.gstRate || 17) / 100)) : net;
  const tax  = gst ? net - base : 0;
  const bal  = net - recv;

  const [payOpen, setPayOpen] = useState(false);

  return (
    <Modal wide title={`Invoice ${i.invoice_number}`} sub={`${i.customer_name} · ${i.date}`} onClose={onClose}
      foot={<>
        <Btn variant="ghost" icon={<Icons.download size={16} />} onClick={() => window.printDocument && window.printDocument(docRef.current)}>Download PDF</Btn>
        <Btn variant="ghost" icon={<Icons.print   size={16} />} onClick={() => window.printDocument && window.printDocument(docRef.current)}>Print</Btn>
        <WaSendBtn docType="Invoice" docId={i.id} />
        {bal > 0 && <Btn variant="primary" icon={<Icons.pay size={16} />} onClick={() => setPayOpen(true)}>Record Payment</Btn>}
      </>}>

      {payOpen && <RecordInvoicePayment invoice={i} balance={bal} onClose={() => setPayOpen(false)} onSaved={onClose} />}

      <div className="row no-print" style={{ gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        {companies.length > 0 && (
          <label className="fld" style={{ flex: 1, minWidth: 220 }}><span>Company Letterhead</span>
            <select className="input-block" value={companyId} onChange={(e) => setCompanyId(e.target.value)}>
              {companies.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </label>
        )}
        <label className="fld" style={{ minWidth: 160 }}><span>Invoice Type</span>
          <div className="tabs" style={{ width: '100%', display: 'flex' }}>
            {[['GST', true], ['Non-GST', false]].map(([t, v]) => (
              <button key={t} className={cls('tab', gst === v && 'active')} style={{ flex: 1 }} onClick={() => setGst(v)}>{t}</button>
            ))}
          </div>
        </label>
      </div>

      <div ref={docRef} style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', background: co.color || 'var(--forest-2)', color: '#fff', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div className="row" style={{ gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,.12)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>{co.name}</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.7)', marginTop: 2 }}>{co.letterhead || 'Respiratory & Sleep Care'}</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.55)', marginTop: 6, lineHeight: 1.5 }}>{co.addr}<br />{co.phone} · {co.email}</div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: '.04em' }}>{gst ? 'TAX INVOICE' : 'INVOICE'}</div>
            <div className="tiny mono" style={{ color: 'rgba(255,255,255,.8)', marginTop: 4 }}>{i.invoice_number}</div>
            <div className="tiny" style={{ color: 'rgba(255,255,255,.55)', marginTop: 6 }}>{i.date}</div>
          </div>
        </div>

        <div style={{ padding: '16px 22px', display: 'flex', justifyContent: 'space-between', gap: 18, flexWrap: 'wrap', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 4 }}>BILL TO</div>
            <div style={{ fontWeight: 700 }}>{i.customer_name}</div>
            {i.doctor && <div className="tiny muted">Ref. Doctor · {i.doctor}</div>}
            <div className="tiny muted">Salesperson · {i.rep || '—'}</div>
          </div>
          {gst && (
            <div style={{ textAlign: 'right' }}>
              <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 4 }}>SELLER TAX</div>
              <div className="tiny mono">NTN · {co.ntn || '—'}</div>
              {co.strn && <div className="tiny mono">STRN · {co.strn}</div>}
            </div>
          )}
        </div>

        <table className="tbl" style={{ fontSize: 13 }}>
          <thead><tr><th>Description</th><th>Serial</th><th>Warranty</th><th style={{ textAlign: 'right' }}>{gst ? 'Taxable' : 'Amount'}</th></tr></thead>
          <tbody>
            <tr>
              <td style={{ fontWeight: 600 }}>{i.device}</td>
              <td className="mono tiny">{i.serial}</td>
              <td className="tiny">{i.warranty}</td>
              <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(base)}</td>
            </tr>
          </tbody>
        </table>

        <div style={{ padding: '14px 22px', display: 'flex', justifyContent: 'flex-end' }}>
          <div style={{ width: 280 }}>
            <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0' }}><span className="muted tiny">Subtotal</span><span className="mono" style={{ fontWeight: 600 }}>{PKR(base)}</span></div>
            {gst
              ? <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line)' }}><span className="muted tiny">GST @ {co.gstRate || 17}%</span><span className="mono" style={{ fontWeight: 600 }}>{PKR(tax)}</span></div>
              : <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line)' }}><span className="muted tiny">Sales tax</span><span className="mono tiny muted">Not applicable</span></div>
            }
            <div className="row" style={{ justifyContent: 'space-between', padding: '10px 0 4px' }}><span style={{ fontWeight: 800 }}>Total</span><span className="mono" style={{ fontWeight: 800, fontSize: 16 }}>{PKR(net)}</span></div>
            <div className="row" style={{ justifyContent: 'space-between', padding: '4px 0' }}><span className="muted tiny">Received</span><span className="mono tiny">{PKR(recv)}</span></div>
          </div>
        </div>

        <div className="row" style={{ justifyContent: 'space-between', padding: '12px 22px', background: bal > 0 ? 'var(--bad-bg)' : 'var(--ok-bg)' }}>
          <span style={{ fontWeight: 700, color: bal > 0 ? 'var(--bad)' : 'var(--ok)' }}>{bal > 0 ? 'Balance Due' : 'Fully Paid'}</span>
          <span className="mono" style={{ fontWeight: 800, fontSize: 18, color: bal > 0 ? 'var(--bad)' : 'var(--ok)' }}>{PKR(Math.max(0, bal))}</span>
        </div>
        <div className="tiny muted" style={{ padding: '10px 22px', borderTop: '1px solid var(--line)' }}>
          {gst ? 'Tax invoice issued under the Sales Tax Act. ' : 'Non-GST invoice — sales tax not charged. '}
          {co.bank ? `Bank · ${co.bank}` : ''}
        </div>
      </div>
    </Modal>
  );
}

/* Record a payment against a specific invoice → updates received + customer outstanding */
function RecordInvoicePayment({ invoice, balance, onClose, onSaved }) {
  const { PKR } = window.DATA;
  const [amount, setAmount] = useState(String(Math.round(balance)));
  const [mode,   setMode]   = useState('Cash');
  const [ref,    setRef]    = useState('');
  const [busy,   setBusy]   = useState(false);

  const save = async () => {
    const amt = parseFloat((amount || '').replace(/[^0-9.]/g, '')) || 0;
    if (amt <= 0)        { window.toast('Enter an amount greater than zero', 'warn'); return; }
    if (amt > balance + 0.5) { window.toast(`Amount exceeds balance due (${PKR(balance)})`, 'warn'); return; }
    setBusy(true);
    try {
      await api.createPayment({
        invoice_id:    invoice.id,
        customer_id:   invoice.customer_id || null,
        customer_name: invoice.customer_name || '',
        amount:        amt,
        mode,
        ref:           ref || '',
        type:          'Sale Invoice',
        payment_date:  new Date().toISOString().slice(0, 10),
      });
      window.toast('Payment of ' + PKR(amt) + ' recorded', 'ok');
      onSaved && onSaved();   // closes the invoice + refetches the list
    } catch (err) {
      window.toast(err.message || 'Failed to record payment', 'error');
    } finally { setBusy(false); }
  };

  return (
    <Modal title="Record Payment" sub={`${invoice.invoice_number} · ${invoice.customer_name}`} onClose={onClose}
      foot={<>
        <Btn variant="ghost" onClick={onClose} disabled={busy}>Cancel</Btn>
        <Btn variant="primary" icon={<Icons.check size={16} />} onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Confirm Payment'}</Btn>
      </>}>
      <div style={{ display: 'grid', gap: 14 }}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '10px 14px', background: 'var(--bad-bg)', borderRadius: 10 }}>
          <span style={{ fontWeight: 700, color: 'var(--bad)' }}>Balance Due</span>
          <span className="mono" style={{ fontWeight: 800, color: 'var(--bad)' }}>{PKR(balance)}</span>
        </div>
        <label className="fld"><span>Amount Received</span>
          <div style={{ position: 'relative' }}>
            <input className="input-block mono" value={amount} onChange={e => setAmount(e.target.value)} style={{ paddingRight: 62 }} />
            <button type="button" onClick={() => setAmount(String(Math.round(balance)))}
              style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', padding: '4px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 12, background: 'var(--lime-700)', color: '#fff' }}>Full</button>
          </div>
        </label>
        <label className="fld"><span>Payment Mode</span>
          <div className="tabs" style={{ width: '100%', display: 'flex' }}>
            {['Cash', 'Cheque', 'Bank Transfer'].map(t => <button key={t} type="button" className={cls('tab', mode === t && 'active')} style={{ flex: 1 }} onClick={() => setMode(t)}>{t}</button>)}
          </div>
        </label>
        <label className="fld"><span>Reference # <span className="tiny muted">(optional)</span></span>
          <input className="input-block mono" value={ref} onChange={e => setRef(e.target.value)} placeholder="Cheque / transaction no." />
        </label>
      </div>
    </Modal>
  );
}

const SALE_STEPS = [
  { t: 'Sales Inquiry',          d: 'Walk-in · phone · referral' },
  { t: 'Items',                  d: 'Machines, accessories, spares & consumables' },
  { t: 'Salesperson Assigned',   d: 'Owner of the deal' },
  { t: 'Delivery & Installation',d: 'On-site setup & demo' },
  { t: 'Payment',                d: 'Cash / cheque / bank' },
  { t: 'Generate Orders',        d: 'Invoice · rental · service' },
];

function SaleWorkflow({ branch = 'All', onClose }) {
  const D = window.DATA; const { PKR } = D;
  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: customers } = useCustomers(bf);
  const { data: products  } = useProducts(bf);
  const { data: doctors   } = useDoctors();
  const { data: users     } = useUsers();
  const { data: companies } = useCompanies();
  const [step, setStep] = useState(0);
  const [custId,     setCustId]     = useState('');
  const [rep,        setRep]        = useState('');
  const [doctor,     setDoctor]     = useState('—');
  const [mode,       setMode]       = useState('Bank Transfer');
  const [gst,        setGstFlag]    = useState(true);
  const [companyId,  setCompany]    = useState('');
  const [quote,      setQuote]      = useState(false);
  const [items,      setItems]      = useState([]);
  const [amountPaid, setAmountPaid] = useState('');
  const [payRef,     setPayRef]     = useState('');
  const [busy,       setBusy]       = useState(false);

  const catalog = products;

  React.useEffect(() => { if (users.length && !rep)      setRep(users[0].name); },    [users.length]);
  React.useEffect(() => { if (companies.length && !companyId) setCompany(companies[0].id); }, [companies.length]);

  React.useEffect(() => {
    if (catalog.length && !items.length) {
      const firstMachine = catalog.find(p => (p.item_type || p.type) === 'Machine') || catalog[0];
      if (firstMachine && window.lineFromProduct) {
        setItems([window.lineFromProduct(firstMachine, 'Sale')]);
      }
    }
  }, [catalog.length]);

  const last = step === SALE_STEPS.length - 1;

  const submit = async () => {
    if (!items.length) return;
    setBusy(true);
    let saved = false;
    try {
      const cust    = customers.find(c => c.id === custId);
      const today   = new Date().toISOString().slice(0, 10);
      const invNum  = 'INV-' + Date.now().toString().slice(-6);
      const paid    = parseFloat((amountPaid || '').replace(/[^0-9.]/g, '')) || 0;

      // Build device label from ALL line items (multi-line support)
      const deviceLabel = items.map(it => {
        const name = it.desc || it.name || '—';
        return (it.qty > 1 ? it.qty + '× ' : '') + name;
      }).join(', ');

      // "Raise a formal quotation first?" → Yes: record a formal quote for this sale
      if (quote) {
        try {
          const selCo = companies.find(c => c.id === companyId);
          const valid = new Date(); valid.setDate(valid.getDate() + 30);
          await api.createQuotation({
            customer_id:   custId || null,
            customer_name: cust ? cust.name : '',
            rep,
            doctor:        doctor !== '—' ? doctor : null,
            company:       selCo ? selCo.name : null,
            gst:           gst ? 1 : 0,
            validity:      valid.toISOString().slice(0, 10),
            status:        'Converted',  // raised and immediately fulfilled by this sale
            subtotal:      Math.round(sub),
            tax_amount:    Math.round(taxAmt),
            total:         Math.round(total),
            branch_id:     branch !== 'All' ? branch : null,
            items: items.map(it => ({
              type:            it.type || 'Machine',
              fulfilment:      it.fulfilment || 'Sale',
              description:     it.desc || it.name || '',
              category:        it.type || null,
              quantity:        Number(it.qty) || 1,
              rate:            Number(it.rate) || 0,
              plan:            it.plan || null,
              deposit:         Number(it.deposit) || 0,
              warranty:        it.warranty && it.warranty !== '—' ? it.warranty : null,
              serial_required: it.serialReq ? 1 : 0,
            })),
          });
        } catch (qErr) {
          window.toast('Sale will proceed, but the quotation could not be saved: ' + (qErr.message || ''), 'warn');
        }
      }

      await api.createInvoice({
        invoice_number: invNum,
        customer_id:    custId || null,
        customer_name:  cust ? cust.name : '',
        device:         deviceLabel,
        serial:         '',
        warranty:       '1 year',
        amount:         total,
        received:       paid,
        gst:            gst ? 1 : 0,
        rep,
        doctor,
        status: total > 0 && paid >= total ? 'Paid' : paid > 0 ? 'Partial' : 'Unpaid',
        date:    today,
        company: companyId,
        branch_id: branch !== 'All' ? branch : null,
        notes:   JSON.stringify(items.map(it => ({ sku: it.sku || '', name: it.desc || it.name, qty: it.qty || 1, rate: it.rate || 0 }))),
      });

      if (paid > 0) {
        await api.createPayment({
          payment_ref:  'PMT-' + Date.now().toString().slice(-6),
          customer_id:  custId || null,
          customer_name: cust ? cust.name : '',
          amount:       paid,
          mode,
          ref:          payRef || '',
          type:         'Sale Invoice',
          payment_date: today,
          status:       'completed',
          branch_id:    branch !== 'All' ? branch : null,
        });
      }

      saved = true;
      window.toast(quote ? `Quotation raised & Invoice ${invNum} created` : 'Invoice ' + invNum + ' created', 'ok');
    } catch (err) {
      console.error('[SaleWorkflow submit]', err);
      window.toast(err.message || 'Failed to create invoice', 'error');
    } finally {
      setBusy(false);
    }
    if (saved) onClose();
  };

  const patch = (ix, p) => setItems((it) => it.map((x, i) => i === ix ? { ...x, ...p } : x));
  const setType = (ix, type) => {
    if (window.emptyLine) patch(ix, window.emptyLine(type, catalog));
  };
  const setProduct = (ix, name) => {
    const p = catalog.find(c => c.name === name);
    if (!p) return;
    const cur = items[ix];
    const t   = p.item_type || p.type || 'Machine';
    const ful = (D.fulfilmentByType && D.fulfilmentByType[t] && D.fulfilmentByType[t].includes(cur.fulfilment))
      ? cur.fulfilment : ((D.fulfilmentByType && D.fulfilmentByType[t]) ? D.fulfilmentByType[t][0] : 'Sale');
    if (window.lineFromProduct) patch(ix, window.lineFromProduct(p, ful));
  };
  const setFul = (ix, ful) => {
    const p = catalog.find(c => c.name === items[ix].desc);
    if (p && window.lineFromProduct) patch(ix, window.lineFromProduct(p, ful));
  };
  const remove = (ix) => setItems((it) => it.filter((_, i) => i !== ix));
  const add    = () => {
    if (window.emptyLine) setItems((it) => [...it, window.emptyLine('Machine', catalog)]);
  };

  const draftItems = items.map((it) => ({ ...it, gst }));
  const draft  = { items: draftItems, company: companyId, gst };
  const sub    = D.quoteSubtotal ? D.quoteSubtotal(draftItems) : items.reduce((s, it) => s + (it.rate || 0) * (it.qty || 1), 0);
  const taxAmt = D.quoteTax ? (gst ? D.quoteTax(draftItems) : 0) : (gst ? Math.round(sub * 0.17) : 0);
  const total  = sub + taxAmt;
  const orders = D.splitQuote ? D.splitQuote(draft) : [];
  const serialLines = items.filter((it) => it.serialReq && it.fulfilment === 'Sale');

  return (
    <Modal wide title="New Sale" sub="Guided sale workflow · one sale can mix machines, accessories, rentals & services" onClose={onClose}
      foot={<>
        <Btn variant="ghost" onClick={step ? () => setStep(step - 1) : onClose}>{step ? 'Back' : 'Cancel'}</Btn>
        <Btn variant="primary" icon={last ? <Icons.check size={16} /> : <Icons.chevR size={16} />}
          onClick={last ? submit : () => setStep(step + 1)}
          disabled={!items.length || busy}>{busy ? 'Saving…' : last ? 'Finish & Notify' : 'Continue'}</Btn>
      </>}>

      <div className="row" style={{ gap: 0, marginBottom: 22 }}>
        {SALE_STEPS.map((s, ix) => (
          <React.Fragment key={ix}>
            <div style={{ width: 28, height: 28, borderRadius: 50, display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12.5, flexShrink: 0,
              background: ix < step ? 'var(--lime)' : ix === step ? 'var(--ink)' : 'var(--surface-3)',
              color: ix <= step ? (ix < step ? 'var(--forest-2)' : '#fff') : 'var(--ink-3)' }}>
              {ix < step ? <Icons.check size={15} stroke={3} /> : ix + 1}
            </div>
            {ix < SALE_STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: ix < step ? 'var(--lime)' : 'var(--line-2)', margin: '0 3px' }} />}
          </React.Fragment>
        ))}
      </div>
      <div style={{ textAlign: 'center', marginBottom: 18 }}>
        <div style={{ fontWeight: 800, fontSize: 17 }}>{SALE_STEPS[step].t}</div>
        <div className="tiny muted" style={{ marginTop: 3 }}>{SALE_STEPS[step].d}</div>
      </div>

      {step === 0 && (
        <div style={{ display: 'grid', gap: 14 }}>
          <label className="fld"><span>Customer</span>
            <select className="input-block" value={custId} onChange={e => setCustId(e.target.value)}>
              <option value="">— Select customer —</option>
              {customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </label>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Inquiry Source</span>
              <select className="input-block">
                <option>Walk-in</option><option>Phone</option><option>Hospital Tender</option><option>Doctor Referral</option>
              </select>
            </label>
            <label className="fld"><span>Referring Doctor</span>
              <select className="input-block" value={doctor} onChange={e => setDoctor(e.target.value)}>
                <option value="—">—</option>
                {doctors.map(d => <option key={d.id} value={d.name}>{d.name}</option>)}
              </select>
            </label>
          </div>
          <label className="fld"><span>Requirement</span><textarea className="input-block" rows="2" placeholder="Patient needs CPAP for moderate sleep apnea…" /></label>
        </div>
      )}

      {step === 1 && (
        <div style={{ display: 'grid', gap: 12 }}>
          <div className="row" style={{ gap: 10, padding: '11px 14px', background: 'var(--surface-2)', borderRadius: 12, justifyContent: 'space-between' }}>
            <span className="row" style={{ gap: 9, fontWeight: 600 }}><Icons.receipt size={18} style={{ color: 'var(--lime-700)' }} />Raise a formal quotation first?</span>
            <div className="tabs" style={{ display: 'flex' }}>
              {[['Yes', true], ['Skip', false]].map(([t, v]) => <button key={t} className={cls('tab', quote === v && 'active')} onClick={() => setQuote(v)}>{t}</button>)}
            </div>
          </div>
          <div className="row" style={{ justifyContent: 'space-between', marginTop: 2 }}>
            <span style={{ fontWeight: 800, fontSize: 14 }}>Line Items</span>
            <span className="tiny muted">{items.length} item{items.length > 1 ? 's' : ''}</span>
          </div>
          <div style={{ display: 'grid', gap: 10 }}>
            {items.map((it, ix) => window.LineRow
              ? <window.LineRow key={ix} it={it} ix={ix} products={catalog} onType={setType} onProduct={setProduct} onFul={setFul} onPatch={patch} onRemove={remove} canRemove={items.length > 1} />
              : <div key={ix} className="tiny muted" style={{ padding: 8 }}>{it.desc} × {it.qty}</div>
            )}
          </div>
          <button className="btn btn-ghost btn-sm" style={{ border: '1px dashed var(--line-2)', width: '100%', justifyContent: 'center', padding: '10px' }} onClick={add}>
            <Icons.plus size={15} stroke={2.5} />Add line item
          </button>
          <div className="row" style={{ justifyContent: 'space-between', padding: '11px 14px', background: 'var(--surface-2)', borderRadius: 12 }}>
            <span className="tiny muted">Subtotal{taxAmt > 0 ? ' + GST' : ''}</span>
            <span className="mono" style={{ fontWeight: 800, fontSize: 15 }}>{PKR(total)}</span>
          </div>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: 'grid', gap: 14 }}>
          <label className="fld"><span>Assign Salesperson</span>
            <select className="input-block" value={rep} onChange={e => setRep(e.target.value)}>
              {users.map(u => <option key={u.id} value={u.name}>{u.name}</option>)}
              {!users.length && ['Kamran Ali', 'Ali Raza', 'Imtiaz Baig', 'Sana Yousuf'].map(n => <option key={n}>{n}</option>)}
            </select>
          </label>
          <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}>
            <Icons.user size={20} style={{ color: 'var(--lime-700)' }} />
            <div><div style={{ fontWeight: 700 }}>{rep} owns this deal</div><div className="tiny muted">Commission & team-wise targets update automatically.</div></div>
          </div>
        </div>
      )}

      {step === 3 && (
        <div style={{ display: 'grid', gap: 14 }}>
          <label className="fld"><span>Delivered & Installed By</span>
            <select className="input-block">
              <option>Kamran Ali (KHI)</option><option>Ali Raza (LHR)</option><option>Imtiaz Baig (ISB)</option><option>Courier</option>
            </select>
          </label>
          {serialLines.length > 0 ? (
            <div>
              <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 8 }}>SERIAL ASSIGNMENT · {serialLines.length} serialised machine{serialLines.length > 1 ? 's' : ''}</div>
              <div style={{ display: 'grid', gap: 8 }}>
                {serialLines.flatMap((it) => Array.from({ length: it.qty }, (_, u) => ({ it, u }))).map(({ it, u }, i) => (
                  <div key={i} className="row" style={{ gap: 10, justifyContent: 'space-between', padding: '9px 12px', border: '1px solid var(--line)', borderRadius: 11 }}>
                    <span style={{ minWidth: 0 }}><span style={{ fontWeight: 600, fontSize: 13.5, display: 'block' }}>{it.desc}{it.qty > 1 ? ` · unit ${u + 1}/${it.qty}` : ''}</span><span className="tiny muted">{it.warranty}</span></span>
                    <input className="input-block mono" style={{ width: 140, padding: '7px 9px' }} defaultValue={`${(it.cat || 'XX').slice(0, 2).toUpperCase()}-${44193 + i}`} />
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div className="tiny muted">No serialised machines on this sale.</div>
          )}
        </div>
      )}

      {step === 4 && (
        <div style={{ display: 'grid', gap: 14 }}>
          <label className="fld"><span>Payment Mode</span>
            <div className="tabs" style={{ width: '100%', display: 'flex' }}>
              {['Cash', 'Cheque', 'Bank Transfer'].map(t => <button key={t} className={cls('tab', mode === t && 'active')} style={{ flex: 1 }} onClick={() => setMode(t)}>{t}</button>)}
            </div>
          </label>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Amount Received</span>
              <div style={{ position: 'relative' }}>
                <input className="input-block mono" value={amountPaid} onChange={e => setAmountPaid(e.target.value)} placeholder={'Rs ' + Number(total).toLocaleString('en-PK')} style={{ paddingRight: 62 }} />
                <button type="button" onClick={() => setAmountPaid(String(Math.round(total)))}
                  style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', padding: '4px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 12, background: 'var(--lime-700)', color: '#fff' }}>
                  Full
                </button>
              </div>
            </label>
            <label className="fld"><span>Reference #</span><input className="input-block mono" value={payRef} onChange={e => setPayRef(e.target.value)} placeholder="HBL-xxxxxx" /></label>
          </div>
          {orders.some && orders.some((o) => o.kind === 'Rental') && (
            <div className="row" style={{ gap: 10, padding: '11px 14px', background: 'var(--warn-bg)', borderRadius: 12 }}>
              <Icons.rental size={18} style={{ color: 'var(--warn)', flexShrink: 0 }} />
              <div className="tiny" style={{ fontWeight: 600 }}>Rental lines also collect a refundable security deposit.</div>
            </div>
          )}
        </div>
      )}

      {step === 5 && (
        <div style={{ display: 'grid', gap: 14 }}>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {companies.length > 0 && (
              <label className="fld"><span>Invoice Company</span>
                <select className="input-block" value={companyId} onChange={e => setCompany(e.target.value)}>
                  {companies.map(c => <option key={c.id} value={c.id}>{c.short || c.name}</option>)}
                </select>
              </label>
            )}
            <label className="fld"><span>Invoice Type</span>
              <div className="tabs" style={{ width: '100%', display: 'flex' }}>
                {[['GST', true], ['Non-GST', false]].map(([t, v]) => <button key={t} className={cls('tab', gst === v && 'active')} style={{ flex: 1 }} onClick={() => setGstFlag(v)}>{t}</button>)}
              </div>
            </label>
          </div>
          {orders.length > 0 ? (
            <>
              <div className="row" style={{ gap: 8, padding: '11px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}>
                <Icons.swap size={18} style={{ color: 'var(--lime-700)', flexShrink: 0 }} />
                <div className="tiny" style={{ fontWeight: 600 }}>This sale generates <b>{orders.length} order{orders.length > 1 ? 's' : ''}</b>.</div>
              </div>
              <div className="grid" style={{ gridTemplateColumns: orders.length > 1 ? '1fr 1fr' : '1fr', gap: 10 }}>
                {orders.map((o) => window.OrderCard ? <window.OrderCard key={o.no} o={o} generated /> : <div key={o.no} className="card card-pad tiny">{o.no} · {o.kind}</div>)}
              </div>
              <div className="row" style={{ justifyContent: 'space-between', padding: '11px 14px', background: 'var(--surface-2)', borderRadius: 12 }}>
                <span style={{ fontWeight: 700 }}>Combined value</span>
                <span className="mono" style={{ fontWeight: 800, fontSize: 16 }}>{PKR(orders.reduce((s, o) => s + (o.total || 0), 0))}</span>
              </div>
            </>
          ) : (
            <div className="tiny muted">Add items in step 2 to generate orders.</div>
          )}
        </div>
      )}
    </Modal>
  );
}

window.Sales = Sales;
window.InvoiceDetail = InvoiceDetail;
