/**
 * Shows/hides bulk action buttons based on Grid.js row selection state.
 */
import { warnOnce } from '../core/app-dom.js';

export function bindBulkVisibility({
  containerSelector,
  buttonSelector,
  selectedRowSelector = '.gridjs-tr-selected'
} = {}) {
  const container = document.querySelector(containerSelector);
  const buttons = Array.from(document.querySelectorAll(buttonSelector));
  if (!container || !buttons.length) {
    if (!container) {
      warnOnce('UI_EL_MISSING', `Missing bulk container: ${containerSelector}`, { module: 'bulk-selection' });
    }
    if (!buttons.length) {
      warnOnce('UI_EL_MISSING', `Missing bulk buttons: ${buttonSelector}`, { module: 'bulk-selection' });
    }
    return { update: () => {} };
  }

  const update = () => {
    const selected = container.querySelectorAll(selectedRowSelector).length > 0;
    buttons.forEach((button) => {
      button.hidden = !selected;
    });
  };

  const observer = new MutationObserver(() => update());
  observer.observe(container, {
    subtree: true,
    attributes: true,
    attributeFilter: ['class']
  });

  update();
  return { update, destroy: () => observer.disconnect() };
}
