// Entry point. Picks the InvoiceManager (no ?id) or the InvoiceEditor
// (?id=<uuid> with a matching, non-trashed metadata row) and mounts.
//
// Runs once-per-load housekeeping first:
//   - migrateLegacyInvoiceIfNeeded() rolls the old pp-invoice-v1 single
//     invoice into the new index as the first entry.
//   - purgeExpiredInvoices() drops anything that's been in trash for
//     longer than INVOICE_TRASH_TTL_MS (30 days).

(function mount() {
  migrateLegacyInvoiceIfNeeded();
  purgeExpiredInvoices();

  const params = new URLSearchParams(location.search);
  const id = params.get('id');

  let view;
  if (id) {
    const meta = (loadInvoiceIndex() || []).find(m => m.id === id && !m.deletedAt);
    if (meta) {
      view = <window.InvoiceEditor meta={meta} />;
    } else {
      // Bad / stale / trashed id → silently drop back to the manager
      history.replaceState(null, '', location.pathname);
      view = <window.InvoiceManager />;
    }
  } else {
    view = <window.InvoiceManager />;
  }

  ReactDOM.createRoot(document.getElementById('root')).render(view);
})();
