// ─── Billing Module ─────────────────────────────────────────────────

const Billing = {
  async render(app) {
    const res = await app.api('invoices');
    const invs = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>My Invoices</h1>
      </div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead>
              <tr><th>Invoice #</th><th>Date</th><th>Due Date</th><th>Amount</th><th>Status</th><th></th></tr>
            </thead>
            <tbody>
              ${invs.length ? invs.map(i => `
                <tr>
                  <td>#${i.id}</td>
                  <td>${i.date ? i.date.slice(0,10) : '-'}</td>
                  <td>${i.exdate ? i.exdate.slice(0,10) : '-'}</td>
                  <td>$${i.price}</td>
                  <td><span class="${app.invClass(i.status)}">${app.invLabel(i.status)}</span></td>
                  <td><a href="#invoice-${i.iid_enc}" class="btn btn-sm btn-primary" onclick="Billing.detail('${i.iid_enc}')">View</a></td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No invoices found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async detail(iidEnc) {
    const app = App;
    window.location.hash = `invoice-${iidEnc}`;
    app.showLoading();

    const res = await app.api(`invoices/detail&iid=${encodeURIComponent(iidEnc)}`);
    if (!res.success) { app.$content.innerHTML = '<div class="empty"><i class="fas fa-file-invoice"></i><p>Invoice not found</p></div>'; return; }
    const i = res.data;
    const unpaid = i.status === 0;

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>Invoice #${i.id}</h1>
        <a href="#billing" data-nav="billing" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
      </div>
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header"><h3>Invoice Details</h3></div>
            <div class="card-body">
              <p><strong>Item:</strong> ${app.escape(i.item || '')}</p>
              ${i.domain ? `<p><strong>Domain:</strong> ${app.escape(i.domain)}</p>` : ''}
              <p><strong>Amount:</strong> $${i.price}</p>
              <p><strong>Date:</strong> ${i.date ? i.date.slice(0,10) : '-'}</p>
              <p><strong>Due:</strong> ${i.exdate ? i.exdate.slice(0,10) : '-'}</p>
              <p><strong>Status:</strong> <span class="${app.invClass(i.status)}">${app.invLabel(i.status)}</span></p>
            </div>
          </div>
        </div>
        <div class="col-6" id="payment-panel">
          ${unpaid ? `
          <div class="card card-flat">
            <div class="card-header"><h3>Pay This Invoice</h3></div>
            <div class="card-body" style="display:flex;flex-direction:column;gap:1rem">
              <div id="paypal-button-container"></div>
              <div style="border-top:1px solid var(--gray-200);padding-top:1rem">
                <p style="margin-bottom:.5rem"><strong>Or pay with BTC</strong></p>
                <p style="color:var(--gray-500);font-size:.875rem">Send the exact amount to the address below, then click "I've Paid" — an admin will confirm and mark this invoice paid once the transaction is verified on-chain.</p>
                <p id="btc-address" style="font-family:monospace;background:var(--gray-50);padding:.5rem;border-radius:var(--radius);word-break:break-all"></p>
                <button class="btn btn-secondary btn-block" onclick="Billing.markBtcPaid('${i.iid_enc}')">I've Paid via BTC</button>
              </div>
            </div>
          </div>` : `
          <div class="card card-flat"><div class="card-body"><p style="color:var(--success)"><i class="fas fa-check-circle"></i> This invoice is ${app.invLabel(i.status).toLowerCase()}.</p></div></div>
          `}
        </div>
      </div>
    `;

    if (unpaid) Billing.initPayment(i);
  },

  async initPayment(invoice) {
    const app = App;
    const cfg = await app.api('payments/config');
    if (cfg.success && cfg.data.btcAddress) {
      document.getElementById('btc-address').textContent = cfg.data.btcAddress;
    }
    if (!cfg.success || !cfg.data.paypalClientId) return;

    const script = document.createElement('script');
    script.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(cfg.data.paypalClientId)}&currency=USD`;
    script.onload = () => {
      if (!window.paypal) return;
      window.paypal.Buttons({
        createOrder: async () => {
          const r = await app.api('payments/create-order', 'POST', { iid: invoice.iid_enc });
          return r.data.orderId;
        },
        onApprove: async (data) => {
          const r = await app.api('payments/capture-order', 'POST', { orderId: data.orderID, iid: invoice.iid_enc });
          if (r.success) { app.showMessage('Payment received — service activating.', 'success'); Billing.detail(invoice.iid_enc); }
          else app.showMessage(r.message || 'Payment could not be captured.', 'danger');
        }
      }).render('#paypal-button-container');
    };
    document.body.appendChild(script);
  },

  async markBtcPaid(iidEnc) {
    const app = App;
    const r = await app.api('payments/btc-claim', 'POST', { iid: iidEnc });
    app.showMessage(r.message || 'Submitted for review.', r.success ? 'success' : 'danger');
  }
};