import { escapeHtml } from '../utils.js';

const RECENTS_KEY = 'pena_recents';
const RECENTS_MAX = 8;

export function loadRecents() {
  try { return JSON.parse(localStorage.getItem(RECENTS_KEY) ?? '[]'); }
  catch { return []; }
}

export function saveRecent(path, mode) {
  const name = path.replace(/\\/g, '/').split('/').pop().replace(/\.md$/i, '');
  const parent = path.replace(/\\/g, '/').split('/').slice(0, -1).join('/');
  const recents = loadRecents().filter(r => r.path !== path);
  recents.unshift({ path, mode, name, parent });
  localStorage.setItem(RECENTS_KEY, JSON.stringify(recents.slice(0, RECENTS_MAX)));
}

export function renderRecents(onOpen) {
  const recents = loadRecents();
  const container = document.getElementById('home-recents');
  const list = document.getElementById('home-recents-list');
  if (recents.length === 0) {
    container.classList.add('hidden');
    return;
  }
  container.classList.remove('hidden');
  list.innerHTML = recents.map(r => {
    const icon = r.mode === 'dir' ? '📁' : '📄';
    const escaped = escapeHtml(r.path);
    return `<li>
      <button class="home-recents__item" data-path="${escaped}" data-mode="${r.mode}">
        <span class="home-recents__item__icon">${icon}</span>
        <span class="home-recents__item__info">
          <span class="home-recents__item__name">${escapeHtml(r.name)}</span>
          <span class="home-recents__item__path">${escapeHtml(r.parent)}</span>
        </span>
      </button>
    </li>`;
  }).join('');
  list.querySelectorAll('.home-recents__item').forEach(btn => {
    btn.addEventListener('click', () => onOpen(btn.dataset.path, btn.dataset.mode));
  });
}
