/**
 * Auto-submit: submits the parent form when a [data-auto-submit] element changes.
 * Replaces inline onchange="this.form.submit()" handlers for CSP compliance.
 */
import { resolveHost } from '../core/app-dom.js';

export function initAutoSubmit(root = document, options = {}) {
  const selector = String(options.selector || '[data-auto-submit]').trim() || '[data-auto-submit]';
  const host = resolveHost(root);
  const elements = Array.from(host.querySelectorAll(selector));
  if (!elements.length) {
    return { destroy: () => {} };
  }

  const cleanupFns = [];
  elements.forEach((element) => {
    if (!(element instanceof HTMLElement) || element.dataset.autoSubmitBound === '1') {
      return;
    }
    element.dataset.autoSubmitBound = '1';
    const onChange = () => {
      const form = element.closest('form');
      if (form instanceof HTMLFormElement) {
        form.submit();
      }
    };
    element.addEventListener('change', onChange);
    cleanupFns.push(() => {
      element.removeEventListener('change', onChange);
      delete element.dataset.autoSubmitBound;
    });
  });

  const destroy = () => {
    cleanupFns.forEach((cleanup) => cleanup());
  };

  return { destroy };
}
