// views/receipt-doc.jsx — payment receipt. Same rules as invoice-doc.jsx: no
// Store, no app helpers, because the public /i/<token>?r page renders it too.

const RCPT_MODE = { transfer: 'Bank transfer', upi: 'UPI', cheque: 'Cheque', card: 'Card', cash: 'Cash' };
function rcptMode(m) { return RCPT_MODE[m] || m || 'Bank transfer'; }

// One receipt per payment (RCPT-<inv>-1, -2…) or one settlement receipt for
// the whole invoice (RCPT-<inv>) once it is paid in full.
function rcptNumber(inv, idx) {
  const base = 'RCPT-' + (inv.number || inv.id || '');
  return idx == null ? base : base + '-' + (idx + 1);
}

function ReceiptDoc({ inv, firm, payments, paid, only }) {
  const f = firm || {};
  const t = invTotals(inv);
  const all = (payments || []).slice().sort((a, b) => String(a.date || '').localeCompare(String(b.date || '')));
  const idx = only != null ? all.findIndex(p => p.id === only) : -1;
  const rows = idx >= 0 ? [all[idx]] : all;
  const amount = rows.reduce((a, p) => a + (Number(p.amount) || 0), 0);
  const upto = idx >= 0 ? all.slice(0, idx + 1).reduce((a, p) => a + (Number(p.amount) || 0), 0) : (Number(paid) || amount);
  const balance = Math.max(0, Math.round((t.total - upto) * 100) / 100);
  const date = rows.length ? rows[rows.length - 1].date : null;
  const full = balance <= 1;

  return (
    <div className="inv-fit">
    <div className="inv-doc rc-doc">
      <div className="inv-head">
        <div className="inv-firm">
          <img className="inv-logo" src={f.logo || ((typeof window !== 'undefined' && window.__INV_ASSET_BASE__) || 'assets/') + 'luxury-unlocked-logo.png'} alt="" />
          {f.address && <div className="inv-firm-meta">{f.address}</div>}
          <div className="inv-firm-meta">
            {f.gstin && <div>GSTIN {f.gstin}</div>}
            {f.pan && <div>PAN {f.pan}</div>}
            {f.email && <div>{f.email}</div>}
            {f.phone && <div>{f.phone}</div>}
          </div>
        </div>
        <div className="inv-title-block">
          <div className="inv-doctype">Payment Receipt</div>
          <table className="inv-meta">
            <tbody>
              <tr><td>Receipt</td><td className="mono">{rcptNumber(inv, idx >= 0 ? idx : null)}</td></tr>
              <tr><td>Date</td><td>{invDate(date)}</td></tr>
              <tr><td>Invoice</td><td className="mono">{inv.number || '—'}</td></tr>
              <tr><td>Invoice date</td><td>{invDate(inv.date)}</td></tr>
            </tbody>
          </table>
          <div className={'inv-stamp ' + (full ? 'paid' : 'part')}>{full ? 'Paid in full' : 'Part payment'}</div>
        </div>
      </div>

      <div className="inv-party">
        <div className="inv-label">Received from</div>
        <div className="inv-party-name">{inv.customer_name || '—'}</div>
        {inv.customer_address && <div className="inv-party-meta">{inv.customer_address}</div>}
        {inv.customer_gstin && <div className="inv-party-meta mono">GSTIN {inv.customer_gstin}</div>}
        {inv.title && <div className="inv-journey">{inv.title}</div>}
      </div>

      <div className="rc-amount">
        <div className="inv-label">Amount received</div>
        <div className="rc-amount-val">{invINR(amount)}</div>
        <div className="inv-words">{invAmountWords(amount)}</div>
      </div>

      <table className="inv-items">
        <thead>
          <tr><th className="w-qty" style={{ textAlign: 'left' }}>Date</th><th>Mode</th><th className="w-amt">Amount</th></tr>
        </thead>
        <tbody>
          {rows.map((p, i) => (
            <tr key={p.id || i}>
              <td>{invDate(p.date)}</td>
              <td>{rcptMode(p.mode)}{p.ref ? <span className="inv-item-detail"> · {p.ref}</span> : null}</td>
              <td className="num">{invINR(p.amount, { noSymbol: true })}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="inv-foot">
        <div className="inv-foot-left">
          <div className="inv-text" style={{ color: '#8A8378', fontSize: 11 }}>
            Received with thanks against invoice {inv.number || ''}{inv.date ? ' dated ' + invDate(inv.date) : ''}.
          </div>
        </div>
        <div className="inv-foot-right">
          <table className="inv-sum">
            <tbody>
              <tr><td>Invoice total</td><td className="num">{invINR(t.total)}</td></tr>
              <tr><td>Received to date</td><td className="num">{invINR(upto)}</td></tr>
              <tr className="inv-sum-due"><td>Balance due</td><td className="num">{invINR(balance)}</td></tr>
            </tbody>
          </table>
        </div>
      </div>

      <div className="inv-sign">
        <div className="inv-thanks">This is a computer-generated receipt.</div>
        <InvSignBlock doc={inv} firm={f} />
      </div>
    </div>
    </div>
  );
}

function rcptPrint(inv, idx) {
  const safe = s => String(s || '').replace(/[\\/:*?"<>|]+/g, '-').replace(/\s+/g, ' ').trim();
  const name = ['Receipt', safe(rcptNumber(inv, idx)), safe(inv && inv.customer_name)].filter(Boolean).join(' - ');
  const prev = document.title;
  document.title = name || prev;
  const restore = () => { document.title = prev; window.removeEventListener('afterprint', restore); };
  window.addEventListener('afterprint', restore);
  window.print();
  setTimeout(restore, 3000);
}

if (typeof window !== 'undefined') Object.assign(window, { ReceiptDoc, rcptPrint, rcptNumber, rcptMode });
