import { createListPageModule } from '../core/app-list-page-module.js';
import { escapeHtml } from './app-list-utils.js';

createListPageModule({
  configId: 'search-index',
  moduleId: 'search-index',
  missingGridMessage: 'Search results grid init failed: Grid.js missing',
  initErrorMessage: 'Search results grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const gridSearch = config.gridSearch ?? null;
    const filterSchema = config.filterSchema ?? [];
    const labels = config.labels ?? {};

    const renderResult = (cell) => {
      const title = escapeHtml(cell?.title ?? '');
      const description = escapeHtml(cell?.description ?? '');
      const url = cell?.url ?? '#';
      const image = cell?.image ?? '';
      const icon = escapeHtml(cell?.icon ?? 'bi-search');
      const avatar = image
        ? `<img class="search-result-avatar" src="${image}" alt="" loading="lazy">`
        : `<span class="search-result-avatar-placeholder"><i class="bi ${icon}"></i></span>`;

      return gridjs.html(`
      <div class="search-result-row">
        ${avatar}
        <div class="search-result-content">
          <a class="search-result-title" href="${url}">${title}</a>
          ${description ? `<p class="search-result-desc">${description}</p>` : ''}
        </div>
      </div>
    `);
    };

    const renderType = (cell) => gridjs.html(`<span class="search-result-type">${escapeHtml(cell ?? '')}</span>`);

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#search-results-grid',
        dataUrl: 'search/data',
        appBase,
        columns: [
          {
            name: labels.result || 'Result',
            sort: false,
            formatter: (cell) => renderResult(cell),
          },
          {
            name: labels.type || 'Type',
            sort: false,
            formatter: (cell) => renderType(cell),
          },
        ],
        sortColumns: [null, null],
        paginationLimit: 10,
        language: config.gridLang ?? {},
        mapData: (data) => data.data.map((row) => [row, row.type]),
        search: gridSearch,
        filterSchema,
        urlSync: true,
      },
      filters: {
        mode: 'search-only',
      },
    }) || {};

    return gridConfig;
  },
});
