/**
 * Footer: show bookmark & subfolder counts for the currently displayed folder.
 */
(function () {
  function getFolderStatsElement() {
    return document.getElementById('folder-stats-text');
  }

  function formatFolderStats(bookmarkCount, folderCount) {
    const args = [String(bookmarkCount), String(folderCount)];
    const localized = chrome.i18n.getMessage('folderStats', args);
    // Chrome substitutes $1/$2; reject unresolved placeholder strings
    if (localized && !/\$\d|\$[A-Z_]+\$/i.test(localized)) {
      return localized;
    }
    return `${bookmarkCount} bookmarks · ${folderCount} folders`;
  }

  /** Count all bookmarks and folders under a node (including nested folders). */
  function countTreeStats(node) {
    let bookmarkCount = 0;
    let folderCount = 0;
    for (const child of node.children || []) {
      if (child.url) {
        bookmarkCount += 1;
      } else {
        folderCount += 1;
        const nested = countTreeStats(child);
        bookmarkCount += nested.bookmarkCount;
        folderCount += nested.folderCount;
      }
    }
    return { bookmarkCount, folderCount };
  }

  function updateFolderStats(folderNode) {
    const el = getFolderStatsElement();
    if (!el) {
      return;
    }

    if (!folderNode) {
      el.textContent = '';
      return;
    }

    const { bookmarkCount, folderCount } = countTreeStats(folderNode);
    el.textContent = formatFolderStats(bookmarkCount, folderCount);
  }

  window.updateFolderStats = updateFolderStats;

  document.addEventListener('DOMContentLoaded', function () {
    const el = getFolderStatsElement();
    if (el && !el.textContent) {
      el.textContent = formatFolderStats(0, 0);
    }
  });
})();
