// Vault-tab list column: renders the middle list pane (row markup, empty
// state, and the row-click → drawer selection). Receives the VaultController
// (`ctx`) and reaches sibling concerns through it; pure helpers come from
// vault-context. Imports only from shared/ and vault-context.

import type { ItemId, ManifestEntry, ItemType } from '../shared/types';
import { relativeTime } from '../shared/relative-time';
import {
  type VaultController, escapeHtml, typeIcon, getFilteredEntries,
} from './vault-context';

export function renderListPane(ctx: VaultController): void {
  const pane = document.getElementById('vault-list-pane');
  if (!pane) return;

  const group = ctx.state.activeGroup as ItemType | null;
  let items = getFilteredEntries(ctx.state);
  if (group) items = items.filter(([, e]) => e.type === group);

  if (items.length === 0) {
    pane.innerHTML = `
      <div class="empty-state">
        <span class="empty-state__icon" aria-hidden="true">${ctx.state.searchQuery ? '⊘' : '◈'}</span>
        <div class="empty-state__title">${ctx.state.searchQuery ? `No results for "${escapeHtml(ctx.state.searchQuery)}"` : 'No items yet'}</div>
        <div class="empty-state__hint">${ctx.state.searchQuery ? 'Try a shorter search term.' : 'Click + new item to get started.'}</div>
      </div>
    `;
    return;
  }

  pane.innerHTML = items.map(([id, e]: [ItemId, ManifestEntry]) => {
    const sel = id === ctx.state.selectedId ? ' vault-list-row--selected' : '';
    const subtitle = (e as any).icon_hint ?? (e.tags?.length > 0 ? e.tags.join(', ') : '');
    const modifiedAgo = e.modified ? relativeTime(e.modified) : '';
    return `
      <div class="vault-list-row${sel}" data-id="${escapeHtml(id)}">
        <div class="vault-list-row__icon" aria-hidden="true">${typeIcon(e.type)}</div>
        <div class="vault-list-row__text">
          <div class="vault-list-row__title">${escapeHtml(e.title)}</div>
          ${subtitle ? `<div class="vault-list-row__subtitle">${escapeHtml(subtitle)}</div>` : ''}
        </div>
        ${modifiedAgo ? `<div class="vault-list-row__age">${escapeHtml(modifiedAgo)}</div>` : ''}
      </div>
    `;
  }).join('');

  pane.querySelectorAll<HTMLElement>('.vault-list-row').forEach((row) => {
    row.addEventListener('click', async () => {
      await ctx.selectItemForDrawer(row.dataset.id!);
    });
  });
}
