import { warnOnce } from './app-dom.js';

export function readPageConfig(configId, root = document) {
  const id = `page-config-${String(configId || '').trim()}`;
  if (!id || id === 'page-config-') {
    warnOnce('UI_CONFIG_INVALID', 'Invalid page config id', { module: 'page-config', configId });
    return null;
  }

  const node = root.getElementById(id);
  if (!node) {
    warnOnce('UI_CONFIG_MISSING', `Missing page config element: #${id}`, { module: 'page-config', configId });
    return null;
  }

  const raw = String(node.textContent || '').trim();
  if (raw === '') {
    warnOnce('UI_CONFIG_EMPTY', `Empty page config payload: #${id}`, { module: 'page-config', configId });
    return null;
  }

  try {
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object') {
      warnOnce('UI_CONFIG_INVALID', `Page config is not an object: #${id}`, { module: 'page-config', configId });
      return null;
    }
    return parsed;
  } catch (error) {
    warnOnce('UI_CONFIG_PARSE_FAIL', `Failed to parse page config: #${id}`, {
      module: 'page-config',
      configId,
      error,
    });
    return null;
  }
}
