import { initPersistedDetailsGroup } from '../core/app-details-open-state.js';

const controllerRegistry = new WeakMap();

const initDetailsGroup = (group) => {
  if (!group || group.dataset.detailsStorageBound === '1') {
    return;
  }

  const storageKey = (group.dataset.detailsStorage || '').trim();
  if (!storageKey) {
    return;
  }

  const controller = initPersistedDetailsGroup({
    root: group,
    storageKey,
  });
  if (!controller) {
    return;
  }

  controllerRegistry.set(group, controller);
  group.dataset.detailsStorageBound = '1';
};

const initDetailsState = () => {
  const groups = Array.from(document.querySelectorAll('[data-details-storage]'));
  groups.forEach(initDetailsGroup);
};

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initDetailsState);
} else {
  initDetailsState();
}
