import { initStandardListPage } from './app-grid-factory.js';
import { warnOnce } from './app-dom.js';
import { readPageConfig } from './app-page-config.js';
import { getAppBase } from '../pages/app-list-utils.js';

const noop = () => {};

const defaultErrorMessage = (moduleId) => `${moduleId} grid init failed`;

export function initListSection(options = {}) {
  const {
    moduleId = 'list-section',
    initOptions = null,
    initErrorMessage = '',
  } = options;

  const safeModuleId = String(moduleId || '').trim() || 'list-section';
  if (!initOptions || typeof initOptions !== 'object') {
    warnOnce('UI_CONFIG_INVALID', 'initListSection requires initOptions', {
      module: safeModuleId,
      component: 'grid',
    });
    return null;
  }

  const failInit = (error = null) => {
    const message = initErrorMessage || defaultErrorMessage(safeModuleId);
    warnOnce('UI_INIT_FAIL', message, {
      module: safeModuleId,
      component: 'grid',
      error,
    });
  };

  try {
    const result = initStandardListPage(initOptions);
    const gridConfig = result?.gridConfig || null;
    if (!gridConfig || !gridConfig.grid) {
      failInit();
      return null;
    }
    return result;
  } catch (error) {
    failInit(error);
    return null;
  }
}

export function createListPageModule(options = {}) {
  const {
    configId,
    moduleId,
    setup,
    missingGridMessage = '',
    initErrorMessage = '',
  } = options;

  const safeModuleId = String(moduleId || '').trim() || 'list-page';
  const safeConfigId = String(configId || '').trim();
  if (safeConfigId === '' || typeof setup !== 'function') {
    warnOnce('UI_CONFIG_INVALID', 'createListPageModule requires configId and setup()', {
      module: safeModuleId,
      component: 'list-page-module',
    });
    return null;
  }

  const config = readPageConfig(safeConfigId);
  if (!config) {
    return null;
  }

  const gridjs = window.gridjs || null;
  if (!gridjs) {
    const fallbackMessage = missingGridMessage || `${safeModuleId} grid init failed: Grid.js missing`;
    warnOnce('UI_INIT_FAIL', fallbackMessage, { module: safeModuleId, component: 'grid' });
    return null;
  }

  const failInit = (error = null) => {
    const message = initErrorMessage || defaultErrorMessage(safeModuleId);
    warnOnce('UI_INIT_FAIL', message, {
      module: safeModuleId,
      component: 'grid',
      error,
    });
  };

  const initListPage = (pageOptions = {}) => {
    const result = initStandardListPage(pageOptions);
    const gridConfig = result?.gridConfig || null;
    if (!gridConfig || !gridConfig.grid) {
      failInit();
      return null;
    }
    return {
      gridConfig,
      filterPanel: result?.filterPanel || null,
    };
  };

  try {
    return setup({
      config,
      gridjs,
      appBase: getAppBase(),
      initListPage,
      failInit,
      noop,
    });
  } catch (error) {
    failInit(error);
    return null;
  }
}
