// Condense pagination into a 5-slot compact sequence.
// Safe to run early: waits for DOM and for dynamic insertion of .pages.
// Idempotent: won't reapply if already applied.

(function () {
  'use strict';

  // Wait for DOM ready, then try to find and enhance .pages.
  function whenReady(fn) {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', fn, { once: true });
    } else {
      // already ready
      fn();
    }
  }

  // Wait for an element matching selector to appear (optionally with timeout).
  function waitForSelector(selector, timeout = 5000) {
    return new Promise((resolve) => {
      const el = document.querySelector(selector);
      if (el) return resolve(el);

      const obs = new MutationObserver((mutations, o) => {
        const found = document.querySelector(selector);
        if (found) {
          o.disconnect();
          resolve(found);
        }
      });
      obs.observe(document.documentElement, { childList: true, subtree: true });

      if (timeout > 0) {
        setTimeout(() => {
          obs.disconnect();
          resolve(null);
        }, timeout);
      }
    });
  }

  // Main apply function (runs once per container)
  function applyCondensedPagination(container) {
    if (!container) return;
    if (container.dataset.condensedApplied === '1') return; // idempotent

    // Save original HTML so we can restore later if needed
    if (!container.dataset.condensedOriginal) {
      container.dataset.condensedOriginal = container.innerHTML;
    }

    // collect numeric anchors and the selected page
    const anchors = Array.from(container.querySelectorAll('a'));
    const numAnchors = anchors.filter(a => /^\d+$/.test(a.textContent.trim()));
    if (numAnchors.length === 0) return;

    // selected element might be <a class="selected"> or <span class="selected"> etc.
    const selected = container.querySelector('.selected');
    const currentPage = selected ? parseInt(selected.textContent.trim(), 10) : NaN;
    if (!Number.isInteger(currentPage) || Number.isNaN(currentPage)) return;

    const nums = numAnchors.map(a => parseInt(a.textContent.trim(), 10)).filter(n => Number.isFinite(n));
    const totalPages = nums.length ? Math.max(...nums) : currentPage;
    if (!Number.isFinite(totalPages) || totalPages <= 5) return; // nothing to change

    // map page -> existing anchor (so we can clone href/attrs)
    const byNum = new Map();
    numAnchors.forEach(a => {
      const n = parseInt(a.textContent.trim(), 10);
      if (Number.isFinite(n)) byNum.set(n, a);
    });

    // detect special links/forms we must preserve
    const prevForm = container.querySelector('form input[type="submit"][value="Previous"]')?.closest('form') || null;
    const nextForm = container.querySelector('form input[type="submit"][value="Next"]')?.closest('form') || null;

    // detect plain text "Previous"/"Next" presence (when not forms)
    const hasPrevText = !prevForm && /\bPrevious\b/.test(container.textContent);
    const hasNextText = !nextForm && /\bNext\b/.test(container.textContent);

    // catalog link (keep as-is)
    const catalogLink = container.querySelector('a[href*="catalog.html"]');

    // helpers to fabricate hrefs if a specific page anchor is missing
    const indexHref = anchors.find(a => /\/index\.html(?:$|\?)/.test(a.getAttribute('href') || ''))?.getAttribute('href') || null;
    let hrefBase = null, hrefSuffix = null;
    {
      const sample = numAnchors.find(a => /\d+\.html(?:$|\?)/.test(a.getAttribute('href') || ''));
      if (sample) {
        const h = sample.getAttribute('href');
        const m = h.match(/^(.*?)(\d+)(\.html(?:$|\?.*)?)$/);
        if (m) { hrefBase = m[1]; hrefSuffix = m[3]; }
      }
    }
    function makeHref(n) {
      if (n === 1 && indexHref) return indexHref;
      if (hrefBase && hrefSuffix) return hrefBase + String(n) + hrefSuffix;
      const existing = byNum.get(n);
      return existing ? existing.getAttribute('href') : '#';
    }

    // build the 5-slot condensed sequence
    function condensed(total, current) {
      if (total <= 5) return [...Array(total).keys()].map(i => i + 1);
      if (current <= 3) return [1, 2, 3, '...', total];
      if (current >= total - 2) return [1, '...', total - 2, total - 1, total];
      return [1, '...', current, '...', total];
    }
    const sequence = condensed(totalPages, currentPage);

    // builder utilities
    function bracketedAnchor(n, isSelected) {
      const frag = document.createDocumentFragment();
      frag.appendChild(document.createTextNode('['));
      let a;
      if (isSelected) {
        // keep the selected element style: create an <a class="selected"> to match original look.
        a = document.createElement('a');
        a.className = 'selected';
        a.textContent = String(n);
        // if there is an existing anchor for this number, try to copy attributes (title, rel, data-*)
        const existing = byNum.get(n);
        if (existing) {
          // copy non-href attributes that might be useful
          Array.from(existing.attributes).forEach(attr => {
            if (attr.name !== 'href' && attr.name !== 'class') {
              a.setAttribute(attr.name, attr.value);
            }
          });
        }
      } else if (byNum.has(n)) {
        a = byNum.get(n).cloneNode(true);
        a.classList.remove('selected');
      } else {
        a = document.createElement('a');
        a.href = makeHref(n);
        a.textContent = String(n);
      }
      frag.appendChild(a);
      frag.appendChild(document.createTextNode(']'));
      return frag;
    }

    // rebuild content safely
    const frag = document.createDocumentFragment();

    // Previous (form or text)
    if (prevForm) {
      frag.appendChild(prevForm.cloneNode(true));
      frag.appendChild(document.createTextNode(' '));
    } else if (hasPrevText) {
      frag.appendChild(document.createTextNode('Previous '));
    }

    // condensed numeric pages
    sequence.forEach((item, idx) => {
      if (item === '...') {
        frag.appendChild(document.createTextNode('[...]'));
      } else {
        const n = item;
        frag.appendChild(bracketedAnchor(n, n === currentPage));
      }
      if (idx !== sequence.length - 1) frag.appendChild(document.createTextNode(' '));
    });

    // Next (form or text)
    if (nextForm) {
      frag.appendChild(document.createTextNode(' '));
      frag.appendChild(nextForm.cloneNode(true));
    } else if (hasNextText) {
      frag.appendChild(document.createTextNode(' Next'));
    }

    // Catalog (if present)
    if (catalogLink) {
      frag.appendChild(document.createTextNode(' | '));
      frag.appendChild(catalogLink.cloneNode(true));
    }

    // swap in one shot
    while (container.firstChild) container.removeChild(container.firstChild);
    container.appendChild(frag);

    // mark applied
    container.dataset.condensedApplied = '1';
  }

  // Entry point: wait for container, then apply. If it appears later, observer will pick it up.
  whenReady(() => {
    waitForSelector('.pages', 8000).then((container) => {
      if (container) {
        applyCondensedPagination(container);
      } else {
        // fallback: if no .pages after timeout try to attach an observer that will apply when it shows up.
        const observer = new MutationObserver((mutations, o) => {
          const found = document.querySelector('.pages');
          if (found) {
            o.disconnect();
            applyCondensedPagination(found);
          }
        });
        observer.observe(document.documentElement, { childList: true, subtree: true });
        // stop observing after 20s to avoid permanent watch
        setTimeout(() => observer.disconnect(), 20000);
      }
    });
  });

})();
