/* ============================================================
   ELECTROMED — Payments & Finance
   Invoice-linked payment allocation with receipt, audit trail
   ============================================================ */
function Payments({ branch }) {
  const { PKR } = window.DATA;
  const [tab, setTab] = useState('All');
  const [q, setQ] = useState('');
  const [rec, setRec] = useState(false);

  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: branchList } = useBranches();
  const { data: allPayments, refetch: refetchPayments } = usePayments(bf);
  const { data: customers, refetch: refetchCustomers } = useCustomers(bf);

  const branchObj = branch === 'All' ? null
    : branchList.find(b => String(b.id) === String(branch));

  const modeColor = { Cash: 'ok', Cheque: 'info', 'Bank Transfer': 'idle', Online: 'ok' };

  const filtered = allPayments.filter((p) =>
    (!branchObj || p.branch_id === branchObj.id) &&
    (tab === 'All' || p.mode === tab) &&
    ((p.payment_ref||'').toLowerCase().includes(q.toLowerCase()) ||
     (p.customer_name||'').toLowerCase().includes(q.toLowerCase()))
  );

  const collected = allPayments.reduce((s, p) => s + parseFloat(p.amount||0), 0);
  const byMode = ['Cash', 'Cheque', 'Bank Transfer'].map((m) => ({
    label: m.split(' ')[0],
    value: allPayments.filter(p => p.mode === m).reduce((s, p) => s + parseFloat(p.amount||0), 0),
  }));
  const dues = customers.filter(c => (c.outstanding||0) > 0)
    .sort((a,b) => (b.outstanding||0) - (a.outstanding||0));

  const { data: allRentals } = useRentals(bf);
  const depositsHeld = (allRentals || []).reduce((s, r) => s + parseFloat(r.deposit || 0), 0);

  const [receiptData, setReceiptData] = useState(null);

  const handleSaved = (receipt) => {
    refetchPayments();
    refetchCustomers();   // outstanding balances changed — refresh the dues ledger
    setRec(false);
    if (receipt) setReceiptData(receipt);
  };

  return (
    <div className="view-enter">
      <PageHead eyebrow="06 · Payments & Finance" title="Payments & Finance"
        sub="Invoice-linked receipts with automatic balance update, audit log and SMS/WhatsApp notification."
        actions={<>
          <Btn variant="ghost" icon={<Icons.download size={16} />}>Collection Report</Btn>
          {window.can('payments','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setRec(true)}>Record Payment</Btn>}
        </>} />

      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.pay size={18} />} label="Collected (Total)" value={PKR(collected)} accent />
        <StatCard icon={<Icons.clock size={18} />} label="Outstanding Dues" value={PKR(dues.reduce((s,c)=>s+(c.outstanding||0),0))} sub={`${dues.length} customers`} />
        <StatCard icon={<Icons.shield size={18} />} label="Deposits Held" value={PKR(depositsHeld)} sub="refundable" />
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.6fr 1fr', alignItems: 'start', marginBottom: 18 }}>
        <div className="card">
          <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
            <Tabs tabs={['All', 'Cash', 'Cheque', 'Bank Transfer']} value={tab} onChange={setTab} />
            <SearchBox value={q} onChange={setQ} placeholder="Receipt or customer…" w={200} />
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl">
              <thead><tr><th>Receipt</th><th>Customer</th><th>Invoice</th><th>Mode / Ref</th><th>Date</th><th>Amount</th></tr></thead>
              <tbody>
                {filtered.map(p => (
                  <tr key={p.id || p.payment_ref} style={{ cursor: 'pointer' }}
                    onClick={async () => {
                      try {
                        const r = await api.getPaymentReceipt(p.id);
                        setReceiptData(r.receipt);
                      } catch {}
                    }}>
                    <td className="mono" style={{ fontWeight: 700 }}>{p.payment_ref}</td>
                    <td style={{ fontWeight: 600 }}>{p.customer_name}</td>
                    <td className="mono tiny muted">{p.invoice_id ? '✓ linked' : '—'}</td>
                    <td>
                      <Badge kind={modeColor[p.mode] || 'idle'}>{p.mode}</Badge>
                      {p.ref && <div className="tiny muted mono" style={{ marginTop: 3 }}>{p.ref}</div>}
                    </td>
                    <td className="tiny muted">{p.payment_date}</td>
                    <td className="mono" style={{ fontWeight: 800, color: 'var(--ok)' }}>+{PKR(p.amount)}</td>
                  </tr>
                ))}
                {!filtered.length && <tr><td colSpan={6} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No payments found.</td></tr>}
              </tbody>
            </table>
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ fontWeight: 800, fontSize: 16, marginBottom: 4 }}>Collection by Mode</div>
          <div className="tiny muted" style={{ marginBottom: 18 }}>All time · PKR</div>
          <BarChart data={byMode} keys={['value']} colors={['var(--lime)']} height={150} maxTicks={4}
            fmt={(v)=>v>=1e6?(v/1e6).toFixed(1)+'M':Math.round(v/1000)+'k'} />
          <div style={{ display: 'grid', gap: 10, marginTop: 18 }}>
            {byMode.map(m => (
              <div key={m.label} className="row" style={{ justifyContent: 'space-between' }}>
                <span className="row tiny" style={{ gap: 8, fontWeight: 700 }}>
                  <span className="dot" style={{ background: 'var(--lime-700)' }} />{m.label}
                </span>
                <span className="mono" style={{ fontWeight: 700 }}>{PKR(m.value)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Outstanding dues ledger */}
      <div className="card">
        <div className="card-pad" style={{ paddingBottom: 8 }}>
          <div style={{ fontWeight: 800, fontSize: 17 }}>Outstanding Dues Ledger</div>
          <div className="tiny muted" style={{ marginTop: 3 }}>Customers with pending balances — ranked by amount.</div>
        </div>
        <table className="tbl">
          <thead><tr><th>Customer</th><th>Type</th><th>City</th><th>Outstanding</th><th>Ageing</th><th></th></tr></thead>
          <tbody>
            {dues.map((c, ix) => (
              <tr key={c.id}>
                <td style={{ fontWeight: 700 }}>{c.name}</td>
                <td><Badge kind={c.type==='Hospital'?'info':c.type==='Sub-Distributor'?'warn':'idle'}>{c.tag || c.type}</Badge></td>
                <td className="muted">{c.city}</td>
                <td className="mono" style={{ fontWeight: 800, color: 'var(--bad)' }}>{PKR(c.outstanding)}</td>
                <td><Badge kind={ix===0?'bad':ix<2?'warn':'idle'}>{ix===0?'60+ days':ix<2?'30–60 days':'0–30 days'}</Badge></td>
                <td><Btn variant="ghost" sm icon={<Icons.pay size={14}/>} onClick={() => setRec(true)}>Pay</Btn></td>
              </tr>
            ))}
            {!dues.length && <tr><td colSpan={6} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No outstanding dues.</td></tr>}
          </tbody>
        </table>
      </div>

      {rec && <RecordPayment customers={customers} onClose={() => setRec(false)} onSaved={handleSaved} />}
      {receiptData && <PaymentReceipt receipt={receiptData} onClose={() => setReceiptData(null)} />}
    </div>
  );
}

/* ── _calcRentalPeriods ──────────────────────────────────────────── */
function _calcRentalPeriods(rental) {
  const start = new Date(rental.from_date || rental.from);
  if (isNaN(start)) return [];
  const today = new Date();
  const cycle = rental.plan || 'Monthly';
  const rate  = parseFloat(rental.rate) || 0;
  const cLbl  = { Daily: 'Day', Weekly: 'Week', Monthly: 'Month' }[cycle] || cycle;
  const fmt   = d => d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: '2-digit' });
  const result = [];
  let ps = new Date(start); let n = 1;
  while (ps <= today && n <= 120) {
    const pe = new Date(ps);
    if      (cycle === 'Daily')  pe.setDate(pe.getDate() + 1);
    else if (cycle === 'Weekly') pe.setDate(pe.getDate() + 7);
    else                         pe.setMonth(pe.getMonth() + 1);
    result.push({ num: n, label: `${cLbl} ${n} · ${fmt(ps)} – ${fmt(pe)}`, start: ps.toISOString().slice(0,10), end: pe.toISOString().slice(0,10), amount: rate });
    ps = new Date(pe); n++;
  }
  return result;
}

/* ── RecordPayment ─────────────────────────────────────────────── */
function RecordPayment({ customers, onClose, onSaved }) {
  const { PKR } = window.DATA;

  // ── State ──────────────────────────────────────────────────────
  const [step, setStep]               = useState('form');
  const [payType, setPayType]         = useState('invoice');

  // Invoice
  const [custId, setCustId]           = useState('');
  const [invoices, setInvoices]       = useState([]);
  const [invLoading, setInvLoading]   = useState(false);
  const [invoiceId, setInvoiceId]     = useState('');

  // Rental
  const { data: allRentals }          = useRentals({});
  const [rentalId, setRentalId]       = useState('');
  const [rentSubType, setRentSubType] = useState('Rent');
  const [periodNum, setPeriodNum]     = useState('');
  const { data: existingRentPmts }    = useRentalPayments(rentalId || 0);

  // Shared
  const [amount, setAmount]           = useState('');
  const [mode, setMode]               = useState('Bank Transfer');
  const [payRef, setPayRef]           = useState('');
  const [notes, setNotes]             = useState('');
  const [busy, setBusy]               = useState(false);
  const [savedReceipt, setSavedReceipt] = useState(null);

  // ── Effects ────────────────────────────────────────────────────
  React.useEffect(() => {
    setInvoiceId(''); setInvoices([]); setAmount('');
    if (!custId || payType !== 'invoice') return;
    setInvLoading(true);
    api.getOutstandingInvoices(custId)
      .then(r => setInvoices(r.invoices || []))
      .catch(() => setInvoices([]))
      .finally(() => setInvLoading(false));
  }, [custId, payType]);

  React.useEffect(() => {
    if (payType !== 'rental' || !rentalId) { setAmount(''); return; }
    const rnt = (allRentals || []).find(r => String(r.id) === String(rentalId));
    if (!rnt) return;
    if (rentSubType === 'Deposit') { setAmount(String(parseFloat(rnt.deposit) || 0)); return; }
    if (periodNum) setAmount(String(parseFloat(rnt.rate) || 0));
    else setAmount('');
  }, [payType, rentalId, rentSubType, periodNum, allRentals]);

  // ── Derived ────────────────────────────────────────────────────
  const activeRentals = (allRentals || []).filter(r => ['Active','Due Soon','Overdue'].includes(r.status));
  const selRental     = activeRentals.find(r => String(r.id) === String(rentalId)) || null;
  const allPeriods    = selRental ? _calcRentalPeriods(selRental) : [];
  const paidNums      = new Set((existingRentPmts || []).filter(p => p.type === 'Rent' && p.status === 'Paid').map(p => p.period_num));
  const pendingPers   = allPeriods.filter(p => !paidNums.has(p.num));
  const selPeriod     = pendingPers.find(p => String(p.num) === String(periodNum)) || null;
  const depositDone   = (existingRentPmts || []).some(p => p.type === 'Deposit' && p.status === 'Paid');

  const selInv  = invoices.find(i => i.id === invoiceId) || null;
  const amtNum  = parseFloat((amount||'').replace(/[^0-9.]/g, '')) || 0;
  const balance = selInv ? selInv.balance : 0;
  const overPay = amtNum > balance + 0.001;

  const canSaveInv    = !!(custId && invoiceId && amtNum > 0 && !overPay);
  const canSaveRental = !!(rentalId && amtNum > 0 && (rentSubType === 'Deposit' || periodNum));
  const canSave       = payType === 'invoice' ? canSaveInv : canSaveRental;
  const fillFull      = () => selInv && setAmount(String(selInv.balance));

  // ── Save ───────────────────────────────────────────────────────
  const save = async () => {
    setBusy(true);
    try {
      const today = new Date().toISOString().slice(0, 10);
      if (payType === 'invoice') {
        const cust = customers.find(c => c.id === custId) || {};
        const res  = await api.createPayment({
          invoice_id: invoiceId, customer_id: custId, customer_name: cust.name || '',
          amount: amtNum, mode, ref: payRef || '', type: 'Sale Invoice',
          payment_date: today, notes: notes || '', created_by: api.user ? api.user.id : null,
        });
        let receipt = null;
        try { receipt = (await api.getPaymentReceipt(res.payment.id)).receipt; } catch {}
        setSavedReceipt(receipt);
        setStep('done');
        window.toast('Payment recorded — ' + (res.payment_ref || res.payment.payment_ref), 'ok');
      } else {
        await api.createRentalPayment({
          rental_id:    rentalId,
          type:         rentSubType,
          period_num:   selPeriod ? selPeriod.num   : null,
          period_label: selPeriod ? selPeriod.label : (rentSubType === 'Deposit' ? 'Security Deposit' : ''),
          period_start: selPeriod ? selPeriod.start : null,
          period_end:   selPeriod ? selPeriod.end   : null,
          amount_due:   rentSubType === 'Rent'
            ? (selPeriod ? selPeriod.amount : amtNum)
            : (parseFloat(selRental ? selRental.deposit : 0) || amtNum),
          amount_paid:  amtNum,
          payment_date: today,
          mode, ref: payRef || '', notes: notes || '',
        });
        window.toast(`Rental payment recorded · ${selRental ? selRental.rental_number : ''}`, 'ok');
        setStep('done');
      }
    } catch (err) {
      window.toast(err.message || 'Failed to record payment', 'error');
      setStep('form');
    } finally { setBusy(false); }
  };

  // ── Done ───────────────────────────────────────────────────────
  if (step === 'done') {
    if (payType === 'invoice' && savedReceipt) {
      return (
        <Modal title="Payment Recorded" sub="Receipt generated — ready to print or share" onClose={() => onSaved(savedReceipt)}
          foot={<><Btn variant="ghost" icon={<Icons.print size={16}/>} onClick={() => window.print()}>Print</Btn><Btn variant="primary" onClick={() => onSaved(savedReceipt)}>Close</Btn></>}>
          <ReceiptContent receipt={savedReceipt} />
        </Modal>
      );
    }
    return (
      <Modal title="Rental Payment Recorded" sub={selRental ? selRental.rental_number : ''} onClose={() => onSaved(null)}
        foot={<Btn variant="primary" onClick={() => onSaved(null)}>Close</Btn>}>
        <div style={{ display: 'grid', gap: 16, padding: '8px 0' }}>
          <div style={{ textAlign: 'center', padding: '10px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--grad-green)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
              <Icons.check size={28} style={{ color: '#fff' }} stroke={3} />
            </div>
            <div style={{ fontWeight: 800, fontSize: 17 }}>Payment Recorded</div>
            <div className="tiny muted" style={{ marginTop: 4 }}>{selRental ? selRental.customer_name : ''} · {selRental ? (selRental.device || 'Machine') : ''}</div>
          </div>
          <div style={{ background: 'var(--grad-green)', borderRadius: 14, padding: '16px 20px', color: '#fff', textAlign: 'center' }}>
            <div className="tiny" style={{ color: 'rgba(255,255,255,.7)' }}>Amount Received</div>
            <div style={{ fontWeight: 900, fontSize: 30, fontFamily: 'monospace', marginTop: 4 }}>{PKR(amtNum)}</div>
            <div className="tiny" style={{ color: 'rgba(255,255,255,.8)', marginTop: 6 }}>
              {rentSubType} · {mode}{selPeriod ? ` · ${selPeriod.label}` : ''}
            </div>
          </div>
        </div>
      </Modal>
    );
  }

  // ── Confirm ────────────────────────────────────────────────────
  if (step === 'confirm') {
    if (payType === 'invoice') {
      const cust = customers.find(c => c.id === custId) || {};
      const remaining = balance - amtNum;
      return (
        <Modal title="Confirm Payment" sub="Review before posting — this cannot be reversed" onClose={() => setStep('form')}
          foot={<>
            <Btn variant="ghost" onClick={() => setStep('form')}>Back</Btn>
            <Btn variant="primary" icon={<Icons.check size={16}/>} onClick={save} disabled={busy}>
              {busy ? 'Posting…' : 'Confirm & Post'}
            </Btn>
          </>}>
          <div style={{ display: 'grid', gap: 14 }}>
            <ConfirmRow label="Customer"      value={cust.name} />
            <ConfirmRow label="Invoice"       value={selInv ? selInv.invoice_number : '—'} mono />
            <ConfirmRow label="Invoice Total" value={PKR(selInv ? selInv.total : 0)} mono />
            <ConfirmRow label="Already Paid"  value={PKR(selInv ? selInv.paid : 0)} mono />
            <ConfirmRow label="Outstanding"   value={PKR(balance)} mono highlight="bad" />
            <div style={{ height: 1, background: 'var(--line-2)' }} />
            <ConfirmRow label="Payment Amount"  value={PKR(amtNum)} mono highlight="ok" big />
            <ConfirmRow label="Remaining After" value={PKR(Math.max(0, remaining))} mono highlight={remaining <= 0.001 ? 'ok' : 'warn'} />
            <ConfirmRow label="Mode" value={mode} />
            {payRef && <ConfirmRow label="Reference" value={payRef} mono />}
            <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}>
              <Icons.bell size={18} style={{ color: 'var(--lime-700)' }} />
              <span className="tiny" style={{ fontWeight: 600 }}>An SMS + WhatsApp alert will be sent to {cust.name || 'customer'} on confirmation.</span>
            </div>
          </div>
        </Modal>
      );
    }
    return (
      <Modal title="Confirm Rental Payment" sub="Review before posting" onClose={() => setStep('form')}
        foot={<>
          <Btn variant="ghost" onClick={() => setStep('form')}>Back</Btn>
          <Btn variant="primary" icon={<Icons.check size={16}/>} onClick={save} disabled={busy}>
            {busy ? 'Posting…' : 'Confirm & Post'}
          </Btn>
        </>}>
        <div style={{ display: 'grid', gap: 14 }}>
          <ConfirmRow label="Customer" value={selRental ? selRental.customer_name : '—'} />
          <ConfirmRow label="Contract" value={selRental ? selRental.rental_number : '—'} mono />
          <ConfirmRow label="Device"   value={selRental ? (selRental.device || '—') : '—'} />
          <ConfirmRow label="Type"     value={rentSubType} />
          {rentSubType === 'Rent' && selPeriod && <ConfirmRow label="Period" value={selPeriod.label} mono />}
          <div style={{ height: 1, background: 'var(--line-2)' }} />
          <ConfirmRow label="Payment Amount" value={PKR(amtNum)} mono highlight="ok" big />
          <ConfirmRow label="Mode" value={mode} />
          {payRef && <ConfirmRow label="Reference" value={payRef} mono />}
        </div>
      </Modal>
    );
  }

  // ── Form ───────────────────────────────────────────────────────
  return (
    <Modal title="Record Payment" sub="Log a received payment" onClose={onClose}
      foot={<>
        <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
        <Btn variant="primary" icon={<Icons.chevR size={16}/>} onClick={() => setStep('confirm')} disabled={!canSave}>
          Review & Confirm
        </Btn>
      </>}>
      <div style={{ display: 'grid', gap: 14 }}>

        {/* Payment Type Toggle */}
        <div style={{ display: 'flex', borderRadius: 10, overflow: 'hidden', border: '1px solid var(--line-2)' }}>
          {[['invoice','Invoice Payment'],['rental','Rental Payment']].map(([v, lbl]) => (
            <button key={v} onClick={() => { setPayType(v); setAmount(''); setRentalId(''); setCustId(''); setPeriodNum(''); }}
              style={{ flex: 1, padding: '9px 0', fontSize: 13.5, fontWeight: 700, cursor: 'pointer', border: 'none',
                background: payType === v ? 'var(--lime-700)' : 'var(--surface-2)',
                color: payType === v ? '#fff' : 'var(--ink-2)' }}>{lbl}</button>
          ))}
        </div>

        {/* ─── INVOICE FLOW ─── */}
        {payType === 'invoice' && (<>

          <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>

          {custId && (
            <label className="fld"><span>Invoice {invLoading && <span className="tiny muted"> Loading…</span>}</span>
              {!invLoading && invoices.length === 0
                ? <div style={{ padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 10, fontSize: 13, color: 'var(--ink-3)' }}>
                    No outstanding invoices for this customer.
                  </div>
                : <select className="input-block" value={invoiceId} onChange={e => { setInvoiceId(e.target.value); setAmount(''); }}>
                    <option value="">— Select invoice —</option>
                    {invoices.map(inv => (
                      <option key={inv.id} value={inv.id}>
                        {inv.invoice_number} · {inv.date} · Balance: Rs {Number(inv.balance).toLocaleString('en-PK')}
                      </option>
                    ))}
                  </select>
              }
            </label>
          )}

          {selInv && (
            <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '14px 16px', display: 'grid', gap: 8 }}>
              <div className="row" style={{ justifyContent: 'space-between', marginBottom: 2 }}>
                <span style={{ fontWeight: 800, fontSize: 14 }}>{selInv.invoice_number}</span>
                <Badge kind={selInv.status === 'Partial' ? 'warn' : 'bad'}>{selInv.status}</Badge>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <InvStat label="Invoice Total" value={PKR(selInv.total)} />
                <InvStat label="Paid So Far"   value={PKR(selInv.paid)}    color="var(--ok)" />
                <InvStat label="Balance Due"   value={PKR(selInv.balance)} color="var(--bad)" bold />
              </div>
              {selInv.device && <div className="tiny muted" style={{ marginTop: 2 }}>Device: {selInv.device}</div>}
            </div>
          )}

          {invoiceId && (
            <div>
              <label className="fld"><span>Payment Amount</span>
                <div className="row" style={{ gap: 8 }}>
                  <input className="input-block mono" style={{ flex: 1 }} value={amount}
                    onChange={e => setAmount(e.target.value.replace(/[^0-9.]/g,''))} placeholder="Rs 0" />
                  {selInv && <Btn variant="ghost" sm onClick={fillFull}>Full</Btn>}
                </div>
              </label>
              {overPay && (
                <div style={{ color: 'var(--bad)', fontSize: 12.5, marginTop: 4, display: 'flex', gap: 6, alignItems: 'center' }}>
                  <Icons.x size={14} stroke={2.5} /> Amount exceeds outstanding balance (Rs {Number(balance).toLocaleString('en-PK')})
                </div>
              )}
              {amtNum > 0 && !overPay && selInv && (
                <div style={{ color: 'var(--ok)', fontSize: 12.5, marginTop: 4, display: 'flex', gap: 6, alignItems: 'center' }}>
                  <Icons.check size={14} stroke={2.5} /> Remaining after payment: Rs {Math.max(0, selInv.balance - amtNum).toLocaleString('en-PK')}
                </div>
              )}
            </div>
          )}

          {invoiceId && (
            <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>
          )}

          {invoiceId && mode !== 'Cash' && (
            <label className="fld"><span>Reference #</span>
              <input className="input-block mono" value={payRef} onChange={e => setPayRef(e.target.value)}
                placeholder={mode==='Cheque'?'Cheque number':'Transaction ID / UTR'} />
            </label>
          )}

          {invoiceId && (
            <label className="fld"><span>Notes <span className="muted">(optional)</span></span>
              <input className="input-block" value={notes} onChange={e => setNotes(e.target.value)} placeholder="Advance, partial, etc." />
            </label>
          )}

        </>)}

        {/* ─── RENTAL FLOW ─── */}
        {payType === 'rental' && (<>

          <label className="fld"><span>Rental Contract</span>
            <select className="input-block" value={rentalId}
              onChange={e => { setRentalId(e.target.value); setPeriodNum(''); setAmount(''); }}>
              <option value="">— Select active rental —</option>
              {activeRentals.map(r => (
                <option key={r.id} value={r.id}>
                  {r.rental_number} · {r.customer_name} · {r.device || 'Machine'} ({r.status})
                </option>
              ))}
            </select>
          </label>

          {selRental && (
            <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '14px 16px', display: 'grid', gap: 8 }}>
              <div className="row" style={{ justifyContent: 'space-between', marginBottom: 2 }}>
                <span style={{ fontWeight: 800, fontSize: 14 }}>{selRental.rental_number}</span>
                <Badge kind={selRental.status==='Overdue'?'bad':selRental.status==='Due Soon'?'warn':'ok'}>{selRental.status}</Badge>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <InvStat label="Customer" value={selRental.customer_name} />
                <InvStat label="Plan"     value={selRental.plan || 'Monthly'} />
                <InvStat label="Rate"     value={PKR(selRental.rate)} color="var(--lime-700)" bold />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 4 }}>
                <InvStat label="Security Deposit" value={PKR(selRental.deposit || 0)} />
                <InvStat label="Deposit Status"   value={depositDone ? '✓ Collected' : 'Pending'} color={depositDone ? 'var(--ok)' : 'var(--bad)'} />
              </div>
            </div>
          )}

          {rentalId && (
            <label className="fld"><span>Payment Type</span>
              <div className="tabs" style={{ width: '100%', display: 'flex' }}>
                {[['Rent','Rent Period'],['Deposit','Security Deposit']].map(([v, lbl]) => (
                  <button key={v} className={cls('tab', rentSubType===v&&'active')} style={{flex:1}}
                    onClick={() => { setRentSubType(v); setPeriodNum(''); setAmount(''); }}>{lbl}</button>
                ))}
              </div>
            </label>
          )}

          {rentalId && rentSubType === 'Rent' && (
            <label className="fld">
              <span>Billing Period
                {pendingPers.length > 0
                  ? <span style={{ marginLeft: 8, fontSize: 12, color: 'var(--bad)', fontWeight: 600 }}>{pendingPers.length} pending</span>
                  : <span style={{ marginLeft: 8, fontSize: 12, color: 'var(--ok)', fontWeight: 600 }}>All up to date</span>
                }
              </span>
              {pendingPers.length === 0
                ? <div style={{ padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 10, fontSize: 13, color: 'var(--ink-3)' }}>
                    No pending periods — all payments up to date.
                  </div>
                : <select className="input-block" value={periodNum} onChange={e => setPeriodNum(e.target.value)}>
                    <option value="">— Select period —</option>
                    {pendingPers.map(p => (
                      <option key={p.num} value={p.num}>{p.label} · Rs {Number(p.amount).toLocaleString('en-PK')}</option>
                    ))}
                  </select>
              }
            </label>
          )}

          {rentalId && rentSubType === 'Deposit' && depositDone && (
            <div style={{ padding: '10px 14px', background: 'var(--lime-soft)', borderRadius: 10, fontSize: 13, color: 'var(--ok)', fontWeight: 600 }}>
              ✓ Security deposit already recorded for this contract.
            </div>
          )}

          {rentalId && (rentSubType === 'Deposit' || periodNum) && (
            <label className="fld"><span>Amount</span>
              <input className="input-block mono" value={amount}
                onChange={e => setAmount(e.target.value.replace(/[^0-9.]/g,''))} placeholder="Rs 0" />
            </label>
          )}

          {rentalId && (rentSubType === 'Deposit' || periodNum) && (
            <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>
          )}

          {rentalId && (rentSubType === 'Deposit' || periodNum) && mode !== 'Cash' && (
            <label className="fld"><span>Reference #</span>
              <input className="input-block mono" value={payRef} onChange={e => setPayRef(e.target.value)}
                placeholder={mode==='Cheque'?'Cheque number':'Transaction ID / UTR'} />
            </label>
          )}

          {rentalId && (rentSubType === 'Deposit' || periodNum) && (
            <label className="fld"><span>Notes <span className="muted">(optional)</span></span>
              <input className="input-block" value={notes} onChange={e => setNotes(e.target.value)} placeholder="Any notes…" />
            </label>
          )}

        </>)}

        {canSave && (
          <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}>
            <Icons.bell size={18} style={{ color: 'var(--lime-700)' }} />
            <span className="tiny" style={{ fontWeight: 600 }}>An instant SMS + WhatsApp alert is sent on save.</span>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* ── PaymentReceipt (standalone modal) ────────────────────────── */
function PaymentReceipt({ receipt, onClose }) {
  return (
    <Modal title="Payment Receipt" sub={receipt.payment_ref} onClose={onClose} wide
      foot={<><Btn variant="ghost" icon={<Icons.print size={16}/>} onClick={() => window.print()}>Print</Btn><Btn variant="primary" onClick={onClose}>Close</Btn></>}>
      <ReceiptContent receipt={receipt} />
    </Modal>
  );
}

/* ── ReceiptContent (shared between inline done + modal) ─────── */
function ReceiptContent({ receipt }) {
  const { PKR } = window.DATA;
  const inv = receipt.invoice;
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {/* Header */}
      <div style={{ textAlign: 'center', padding: '14px 0', borderBottom: '1px solid var(--line-2)' }}>
        <div style={{ fontWeight: 800, fontSize: 18 }}>Electromed Corporation</div>
        <div className="tiny muted">Respiratory & Sleep Care</div>
        <div style={{ marginTop: 10, fontWeight: 700, fontSize: 14, letterSpacing: .5 }}>PAYMENT RECEIPT</div>
        <div className="mono tiny" style={{ color: 'var(--lime-700)', marginTop: 2 }}>{receipt.payment_ref}</div>
      </div>

      {/* Details grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <ReceiptField label="Customer"     value={receipt.customer_name} />
        <ReceiptField label="Payment Date" value={receipt.payment_date} />
        <ReceiptField label="Payment Mode" value={receipt.mode} />
        {receipt.ref && <ReceiptField label="Reference" value={receipt.ref} mono />}
      </div>

      {/* Invoice linkage */}
      {inv && (
        <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 16px', display: 'grid', gap: 8 }}>
          <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 4 }}>Invoice Details</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <ReceiptField label="Invoice #"    value={inv.invoice_number} mono />
            <ReceiptField label="Invoice Date" value={inv.date} />
            <ReceiptField label="Invoice Total"  value={PKR(inv.total)} mono />
            <ReceiptField label="Prev. Paid"     value={PKR(inv.paid - parseFloat(receipt.amount || 0))} mono />
          </div>
        </div>
      )}

      {/* Amount highlight */}
      <div style={{ background: 'var(--grad-green)', borderRadius: 14, padding: '16px 20px', color: '#fff', display: 'grid', gap: 6 }}>
        <div className="tiny" style={{ color: 'rgba(255,255,255,.7)' }}>Amount Received</div>
        <div style={{ fontWeight: 900, fontSize: 28, fontFamily: 'monospace' }}>
          {PKR(receipt.amount)}
        </div>
        {inv && (
          <div className="tiny" style={{ color: 'rgba(255,255,255,.8)', marginTop: 4 }}>
            Remaining balance on {inv.invoice_number}: <b style={{ color: 'var(--lime)' }}>{PKR(inv.balance)}</b>
          </div>
        )}
      </div>

      {/* SMS preview */}
      {inv && (
        <div style={{ border: '1px solid var(--line-2)', borderRadius: 12, padding: '12px 16px' }}>
          <div className="tiny muted" style={{ marginBottom: 6 }}>SMS / WhatsApp notification sent:</div>
          <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)' }}>
            "Dear <b>{receipt.customer_name}</b>, we have received <b>{PKR(receipt.amount)}</b> against Invoice #{inv.invoice_number}. Remaining balance: <b>{PKR(inv.balance)}</b>. Thank you. — Electromed"
          </div>
        </div>
      )}
    </div>
  );
}

/* ── Small helper components ──────────────────────────────────── */
function InvStat({ label, value, color, bold }) {
  return (
    <div>
      <div className="tiny muted" style={{ marginBottom: 2 }}>{label}</div>
      <div className="mono" style={{ fontWeight: bold ? 800 : 600, fontSize: 13.5, color: color || 'var(--ink)' }}>{value}</div>
    </div>
  );
}

function ConfirmRow({ label, value, mono, highlight, big }) {
  const color = highlight === 'ok' ? 'var(--ok)' : highlight === 'bad' ? 'var(--bad)' : highlight === 'warn' ? 'var(--warn)' : 'var(--ink)';
  return (
    <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line-2)' }}>
      <span className="tiny muted" style={{ fontWeight: 600 }}>{label}</span>
      <span style={{ fontFamily: mono ? 'monospace' : 'inherit', fontWeight: big ? 800 : 600, fontSize: big ? 16 : 13.5, color }}>{value}</span>
    </div>
  );
}

function ReceiptField({ label, value, mono }) {
  return (
    <div>
      <div className="tiny muted" style={{ marginBottom: 1 }}>{label}</div>
      <div style={{ fontWeight: 600, fontSize: 13.5, fontFamily: mono ? 'monospace' : 'inherit' }}>{value || '—'}</div>
    </div>
  );
}

window.Payments = Payments;
