/**
 * Generic export trigger for Grid.js list pages.
 *
 * Binds click handlers to `[data-list-export]` elements. Each click builds
 * an export URL that mirrors the grid's current filter/search/sort state,
 * appends `format=<flavor>`, and navigates the browser there so the
 * Content-Disposition download fires with the user's session cookie intact.
 *
 * Usage:
 *   initListExport({
 *     gridConfig,                 // returned by initListPage()
 *     exportUrl: '/helpdesk/domains/export',
 *     scope: document,            // optional, defaults to document
 *   });
 */

const DEFAULT_TRIGGER_SELECTOR = '[data-list-export]';

export function initListExport({ gridConfig, exportUrl, scope = document, triggers = DEFAULT_TRIGGER_SELECTOR } = {}) {
  if (!gridConfig || typeof gridConfig.baseUrl !== 'function') {
    return;
  }
  const target = typeof exportUrl === 'string' ? exportUrl.trim() : '';
  if (target === '') {
    return;
  }
  const root = scope || document;
  const nodes = root.querySelectorAll(triggers);
  if (!nodes.length) {
    return;
  }

  const onClick = (event) => {
    const button = event.currentTarget;
    if (!(button instanceof HTMLElement)) {
      return;
    }
    const flavor = (button.dataset.listExport || 'csv').toLowerCase();

    let url;
    try {
      url = new URL(target, window.location.href);
    } catch {
      return;
    }

    // Mirror grid filters + search onto the export URL
    try {
      const dataUrl = new URL(gridConfig.baseUrl(), window.location.href);
      dataUrl.searchParams.forEach((value, key) => {
        if (key === 'limit' || key === 'offset') {
          return;
        }
        url.searchParams.set(key, value);
      });
    } catch {
      // ignore malformed grid base URLs — fall through without filters
    }

    // Current sort
    const sort = typeof gridConfig.getSortParams === 'function' ? gridConfig.getSortParams() : null;
    if (sort && sort.order) {
      url.searchParams.set('order', sort.order);
      url.searchParams.set('dir', sort.dir || 'asc');
    }

    url.searchParams.set('format', flavor === 'excel' ? 'excel' : 'csv');

    // Close parent <details> dropdown if present
    const details = button.closest('details');
    if (details) {
      details.open = false;
    }

    window.location.href = url.toString();
  };

  nodes.forEach((node) => node.addEventListener('click', onClick));
}
