/**
 * Initializes standard UI components inside a dynamically-loaded HTML fragment
 * (e.g. detail drawer body). Mirrors the subset of app-init.js components that
 * make sense inside content fragments — layout/topbar/global components are
 * intentionally excluded since those live in the shell, not the fragment.
 *
 * Consumers:
 *   import { initFragmentContent } from '/js/core/app-fragment-init.js';
 *   initFragmentContent(contentEl);
 *
 * Each initializer is best-effort: failures are logged but do not abort the
 * remaining initializers so one broken component cannot silently break all
 * interactive elements in the fragment.
 */

import { initTabs } from '../components/app-tabs.js';
import { initConfirmActions } from '../components/app-confirm-actions.js';
import { initLookupFields } from '../components/app-lookup-field.js';
import { initAutoSubmit } from '../components/app-auto-submit.js';
import { initFileUpload } from '../components/app-file-upload.js';

const INITIALIZERS = [
  {
    name: 'tabs',
    selector: '[data-app-component="tabs"]',
    run: (root) => initTabs(root),
  },
  {
    name: 'confirm-actions',
    selector: '[data-confirm]',
    run: (root) => initConfirmActions(root),
  },
  {
    name: 'lookup-field',
    selector: '[data-lookup-field]',
    run: (root) => initLookupFields(root),
  },
  {
    name: 'auto-submit',
    selector: '[data-auto-submit]',
    run: (root) => initAutoSubmit(root),
  },
  {
    name: 'file-upload',
    selector: '[data-app-component="file-upload"]',
    run: (root) => initFileUpload(root),
  },
];

const refreshFsLightboxSafe = () => {
  if (typeof window !== 'undefined' && typeof window.refreshFsLightbox === 'function') {
    try {
      window.refreshFsLightbox();
    } catch (err) {
      console.warn('[fragment-init] refreshFsLightbox failed', err);
    }
  }
};

/**
 * Initialize all known components within the given fragment root.
 *
 * @param {HTMLElement} contentEl — the container holding freshly-injected HTML
 */
export function initFragmentContent(contentEl) {
  if (!(contentEl instanceof HTMLElement)) {
    return;
  }

  for (const { name, selector, run } of INITIALIZERS) {
    if (!contentEl.querySelector(selector)) {
      continue;
    }
    try {
      run(contentEl);
    } catch (err) {
      console.warn(`[fragment-init] ${name} failed`, err);
    }
  }

  refreshFsLightboxSafe();
}
