<?php
use MintyPHP\Buffer;
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('Search')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('Search results')); ?></h1>
</div>
<div class="app-list-toolbar">
  <label class="app-field">
    <span><?php e(t('Search')); ?></span>
    <input type="search" id="search-results-input" placeholder="<?php e(t('Search...')); ?>">
  </label>
</div>
<div class="app-list-table">
  <div id="search-results-grid"></div>
</div>

<script src="<?php e(asset('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="module">
  import { createServerGrid } from "<?php e(assetVersion('js/core/app-grid-factory.js')); ?>";
  import { getAppBase, escapeHtml } from "<?php e(asset('js/pages/app-list-utils.js')); ?>";

  const appBase = getAppBase();
  const renderResult = (cell) => {
    const title = escapeHtml(cell?.title ?? '');
    const description = escapeHtml(cell?.description ?? '');
    const url = cell?.url ?? '#';
    const typeLabel = escapeHtml(cell?.type ?? '');
    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>`);

  createServerGrid({
    gridjs: window.gridjs,
    container: '#search-results-grid',
    dataUrl: 'search/data',
    appBase,
    columns: [
      {
        name: "<?php e(t('Result')); ?>",
        sort: false,
        formatter: (cell) => renderResult(cell)
      },
      {
        name: "<?php e(t('Type')); ?>",
        sort: false,
        formatter: (cell) => renderType(cell)
      }
    ],
    sortColumns: [null, null],
    paginationLimit: 10,
    language: <?php MintyPHP\Buffer::get('grid_lang'); ?>,
    mapData: (data) => data.data.map((row) => [row, row.type]),
    search: {
      input: '#search-results-input',
      param: 'search',
      debounce: 250
    },
    urlSync: true
  });
</script>
