// Redmine History Timeline Navigator — Bracke Forest (v1.8.1)
// - No visual highlight on first init (only internal mark)
// - Preview de-dup (no heading if missing/duplicated)
// - bf-pills: overflow-x:hidden + ellipsis
// - Removed "bounce"; pills now scroll into view without animation

(function () {
  const CONFIG = {
    PANEL_WIDTH: 280,
    LEFT_OFFSET: 6,
    BOTTOM_OFFSET: 60,
    NOTE_TARGET_PAD: 80,
    LONG_THRESHOLD: 500,
    PREVIEW_MAX_CHARS: 220,
    PREVIEW_IMG_MAX_W: 160,
    PREVIEW_IMG_MAX_H: 100,
    HIGHLIGHT_RING: '0 0 0 2px rgba(37,99,235,.85)',
    HIGHLIGHT_FADE_MS: 700
  };

  // Matches #tab-content-history in your HTML
  const HISTORY_SEL = '#tab-content-history';
  // const NOTE_SEL = '.note[id^="note-"]';	// work with Redmine 6.0
  const NOTE_SEL = 'div[id^="note-"]';		// work with older Redmine installations
  const JOURNAL_SEL = '.journal';

  const PANEL_ID = 'bf-history-timeline-panel';
  const STYLE_ID = PANEL_ID + '-style';
  const LAUNCH_ID = 'bf-history-launcher';
  const HOVERZONE_ID = 'bf-history-hoverzone';
  const PREVIEW_ID = 'bf-history-preview';
  const HINT_ID = 'bf-history-hint';
  const NOTE_HL_CLASS = 'bf-note-highlight';

  if (window.__BF_HistoryTimeline?.destroy) {
    try { window.__BF_HistoryTimeline.destroy(); } catch(e){}
  }

  function ready(fn){
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
      setTimeout(fn, 0);
    } else {
      document.addEventListener('DOMContentLoaded', fn, { once: true });
    }
  }

  ready(bootstrap);

  let retryTimer = null;
  function bootstrap() {
    const tryInit = () => {
      const historyRoot = document.querySelector(HISTORY_SEL);
      if (!historyRoot) return false;
      init(historyRoot);
      return true;
    };
    if (!tryInit()) {
      let tries = 0;
      retryTimer = setInterval(() => {
        tries++;
        if (tryInit() || tries > 50) { clearInterval(retryTimer); retryTimer = null; }
      }, 200);
    }
  }

  function init(historyRoot){
    [PANEL_ID, STYLE_ID, LAUNCH_ID, HOVERZONE_ID, PREVIEW_ID, HINT_ID].forEach(id => document.getElementById(id)?.remove());
    document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(el => el.classList.remove(NOTE_HL_CLASS));

    const esc = (s) => (s || '').replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m]));
    const by = (sel, root=document) => root.querySelector(sel);

    function jumpTo(el) {
      if (!el) return;
      const journal = el.closest(JOURNAL_SEL);
      if (journal && journal.style && journal.style.display === 'none') journal.style.display = '';
      const rect = el.getBoundingClientRect();
      const y = window.scrollY + rect.top - CONFIG.NOTE_TARGET_PAD;
      window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
      highlight(el);
      setActiveIndex(indexOf(el));
    }

    function highlight(el, silent=false) {
      document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(e => e.classList.remove(NOTE_HL_CLASS));
      if (silent) return;
      el.classList.add(NOTE_HL_CLASS);
      el.style.transition = 'box-shadow 0.6s ease';
      el.style.boxShadow = CONFIG.HIGHLIGHT_RING;
      setTimeout(() => { el.style.boxShadow = '0 0 0 0 rgba(37,99,235,0)'; }, CONFIG.HIGHLIGHT_FADE_MS);
    }

    function extractWhenFromHeader(header) {
      if (!header) return '';
      const links = Array.from(header.querySelectorAll('a[title]'));
      const dateLike = links.find(a => /\d{4}-\d{2}-\d{2}/.test(a.getAttribute('title') || ''));
      if (dateLike) return dateLike.getAttribute('title') || dateLike.textContent.trim();
      const act = links.find(a => /activity\?from=/.test(a.getAttribute('href') || ''));
      if (act) return act.getAttribute('title') || act.textContent.trim();
      const last = links[links.length - 1];
      return last ? (last.getAttribute('title') || last.textContent.trim()) : '';
    }

    function getSummaryAndBody(wikiEl) {
      const firstHeading = wikiEl.querySelector('h1,h2,h3,h4,h5,h6');
      const headingText = firstHeading?.innerText?.trim() || '';
      let bodyText = (wikiEl.innerText || '').replace(/\s+/g,' ').trim();
      const norm = s => (s||'').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu,' ').trim();
      if (headingText && norm(bodyText).startsWith(norm(headingText))) {
        const idx = bodyText.toLowerCase().indexOf(headingText.toLowerCase());
        if (idx === 0) bodyText = bodyText.slice(headingText.length).trim();
      }
      const showTitle = !!headingText && !norm(bodyText.slice(0,100)).includes(norm(headingText));
      const summary = showTitle ? headingText : '';
      return { summary, bodyText };
    }

    const collectNotes = (excludeHiddenJournals) => {
      const notes = Array.from(historyRoot.querySelectorAll(NOTE_SEL))
        .filter(n => {
          if (!excludeHiddenJournals) return true;
          const j = n.closest(JOURNAL_SEL);
          return !(j && j.style && j.style.display === 'none');
        })
        .sort((a,b) => {
          const an = parseInt(a.id.replace('note-',''),10);
          const bn = parseInt(b.id.replace('note-',''),10);
          if (!isNaN(an) && !isNaN(bn)) return an - bn;
          return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
        });

      return notes.map((note, i) => {
        const num = parseInt(note.id.replace('note-',''),10);
        const journal = note.closest(JOURNAL_SEL);
        const header = note.querySelector('.note-header') || journal?.querySelector('.note-header');
        const author = header?.querySelector('a.user')?.textContent?.trim() || 'Unknown';
        const linkTxt = journal?.querySelector('.journal-link')?.textContent?.trim() || ('#' + (isNaN(num) ? (i+1) : num));
        const when = extractWhenFromHeader(header);
        const wiki = note.querySelector('.wiki') || note;
        const { summary, bodyText } = getSummaryAndBody(wiki);
        const imgSrc = (wiki.querySelector('img')?.getAttribute('src')) || null;
        return { el: note, num, author, linkTxt, when, textLen: bodyText.length, imgSrc, summary, fullText: bodyText };
      });
    };

    let excludeHidden = true;
    let notes = collectNotes(excludeHidden);
    if (!notes.length) { console.warn('Timeline: No notes found.'); return; }
    const indexOf = (el) => notes.findIndex(n => n.el === el);
    let activeIndex = 0;

    const css = document.createElement('style');
    css.id = STYLE_ID;
    css.textContent = `
      :root { --bf-width: ${CONFIG.PANEL_WIDTH}px; --bf-left: ${CONFIG.LEFT_OFFSET}px; --bf-bottom: ${CONFIG.BOTTOM_OFFSET}px; }

      #${HOVERZONE_ID} { position: fixed; left: 50%; transform: translateX(-50%); bottom: var(--bf-bottom); width: 360px; height: 42px; z-index: 9997; }
      #${LAUNCH_ID} {
        position: fixed; left: 50%; transform: translateX(-50%);
        bottom: calc(var(--bf-bottom) - 10px); z-index: 9998; opacity: 0; transition: opacity .2s ease, transform .2s ease;
        background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; border-radius: 999px;
        padding: 6px 12px; font-weight: 600; font-size: 12px; box-shadow: 0 6px 18px rgba(0,0,0,.12); cursor: pointer;
      }
      #${HOVERZONE_ID}:hover + #${LAUNCH_ID}, #${LAUNCH_ID}:hover { opacity: 1; transform: translateX(-50%) translateY(-2px); }

      #${PANEL_ID} {
        position: fixed; width: var(--bf-width); left: var(--bf-left);
        bottom: calc(var(--bf-bottom) + 14px); max-width: calc(100vw - 24px); background: #f9fafb; color: #111827;
        border: 1px solid #e5e7eb; border-radius: 14px; box-shadow: 0 16px 40px rgba(0,0,0,.18);
        font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, 'Helvetica Neue', Arial, 'Noto Sans';
        overflow: hidden; user-select: none; z-index: 9999; transform: translate(-120%, 0); opacity: 0; pointer-events: none;
        transition: transform .28s ease, opacity .28s ease;
      }
      #${PANEL_ID}.open { transform: translate(0, 0); opacity: 1; pointer-events: auto; }

      #${PANEL_ID} .bf-hdr { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; background:#f3f4f6; border-bottom:1px solid #e5e7eb; }
      #${PANEL_ID} .bf-title { font-weight:700; letter-spacing:.2px; color:#111827; }
      #${PANEL_ID} .bf-counter { opacity:.85; font-variant-numeric: tabular-nums; color:#374151; }
      #${PANEL_ID} .bf-close { background:#e5e7eb; color:#374151; border:1px solid #d1d5db; font-size:12px; padding:4px 8px; border-radius:8px; cursor:pointer; }
      #${PANEL_ID} .bf-close:hover { background:#d1d5db; }

      #${PANEL_ID} .bf-controls { display:grid; grid-template-columns: auto 1fr auto; gap:8px; align-items:center; padding:10px 12px; }
      #${PANEL_ID} .bf-btn { border:1px solid #d1d5db; padding:4px 8px; border-radius:8px; background:#ffffff; color:#374151; cursor:pointer; font-size:12px; line-height:1; }
      #${PANEL_ID} .bf-btn:hover { background:#f3f4f6; }
      #${PANEL_ID} .bf-slider-wrap { display:flex; align-items:center; gap:10px; }
      #${PANEL_ID} .bf-edge { font-size:11px; color:#6b7280; user-select:none; }

      #${PANEL_ID} .bf-slider { -webkit-appearance: none; appearance: none; width: 100%; height: 18px; background: transparent; }
      #${PANEL_ID} .bf-slider::-webkit-slider-runnable-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
      #${PANEL_ID} .bf-slider::-moz-range-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
      #${PANEL_ID} .bf-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; background: #ffffff; border: 1px solid #9ca3af; margin-top: -6px; box-shadow: 0 1px 2px rgba(0,0,0,.12); }
      #${PANEL_ID} .bf-slider::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: #ffffff; border: 1px solid #9ca3af; box-shadow: 0 1px 2px rgba(0,0,0,.12); }

      #${PANEL_ID} .bf-toggles { display:flex; gap:10px; align-items:center; padding:0 12px 10px 12px; flex-wrap:wrap; }
      #${PANEL_ID} .bf-toggles label { font-size:12px; color:#374151; display:flex; gap:6px; align-items:center; }
      #${PANEL_ID} .bf-filter { flex:1; min-width:120px; padding:6px 8px; border-radius:8px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:12px; }

      #${PANEL_ID} .bf-pills {
        display:flex;
        flex-wrap:wrap;
        gap:6px;
        padding:0 12px 12px 12px;
        max-height:160px;
        overflow-y:auto;
        overflow-x:hidden;
      }
      #${PANEL_ID} .bf-pill {
        font-size:12px;
        border:1px solid #d1d5db;
        background:#ffffff;
        color:#374151;
        border-radius:999px;
        padding:4px 8px;
        cursor:pointer;
        max-width:100%;
        overflow:hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
      }
      #${PANEL_ID} .bf-pill:hover { background:#f3f4f6; }
      #${PANEL_ID} .bf-pill.active { border-color:#2563eb; box-shadow:0 0 0 2px rgba(37,99,235,.20) inset; }

      #${PANEL_ID} .bf-help { font-size:11px; color:#6b7280; padding:0 12px 12px 12px; }

      .${NOTE_HL_CLASS} { border-radius: inherit !important; }
      .${NOTE_HL_CLASS}::before { border-color: rgba(37,99,235,.85) !important; }

      #${PREVIEW_ID} {
        position: fixed; z-index: 10000; pointer-events: none;
        max-width: 340px; background: #ffffff; color:#111827; border:1px solid #e5e7eb; border-radius: 10px;
        box-shadow: 0 12px 30px rgba(0,0,0,.18); padding: 8px; font-size: 12px; display: none;
      }
      #${PREVIEW_ID} .ttl { font-weight: 700; margin-bottom: 4px; }
      #${PREVIEW_ID} .txt { color:#374151; line-height: 1.3; }
      #${PREVIEW_ID} .row { display:flex; gap:8px; align-items:flex-start; }
      #${PREVIEW_ID} img { display:block; max-width:${CONFIG.PREVIEW_IMG_MAX_W}px; max-height:${CONFIG.PREVIEW_IMG_MAX_H}px; border-radius:6px; border:1px solid #e5e7eb; }

      #${HINT_ID}{
        position: fixed; z-index: 10001; pointer-events: none;
        background:#111827; color:#ffffff; border-radius:6px; padding:4px 8px; font-size:11px;
        box-shadow: 0 6px 18px rgba(0,0,0,.18); display:none; white-space:nowrap;
      }
    `;
    document.head.appendChild(css);

    const hoverZone = document.createElement('div'); hoverZone.id = HOVERZONE_ID;
    const launcher = document.createElement('button'); launcher.id = LAUNCH_ID; launcher.textContent = 'Quick jump';
    document.body.appendChild(hoverZone); document.body.appendChild(launcher);

    const panel = document.createElement('div');
    panel.id = PANEL_ID;
    panel.innerHTML = `
      <div class="bf-hdr">
        <span class="bf-title">History timeline</span>
        <span class="bf-counter"></span>
        <button class="bf-close" title="Close">Close</button>
      </div>
      <div class="bf-controls">
        <button class="bf-btn bf-prev" title="Previous (p/k)">⟨</button>
        <div class="bf-slider-wrap">
          <span class="bf-edge">Oldest</span>
          <input type="range" class="bf-slider" min="0" value="0" step="1">
          <span class="bf-edge">Newest</span>
        </div>
        <button class="bf-btn bf-next" title="Next (n/j)">⟩</button>
      </div>
      <div class="bf-toggles">
        <label title="Checked = show only visible notes (ignores hidden journals). Unchecked = include hidden.">
          <input type="checkbox" class="bf-toggle-onlynotes" checked> Only notes
        </label>
        <label><input type="checkbox" class="bf-toggle-long"> Only jump to long notes</label>
        <input type="text" class="bf-filter" placeholder="Filter: author, date or #">
      </div>
      <div class="bf-pills" role="listbox" aria-label="Quick jump"></div>
      <div class="bf-help">Keyboard shortcuts:<br><b>n/j</b> next, <b>p/k</b> previous, <b>g</b> go to #</div>
    `;
    document.body.appendChild(panel);

    const preview = document.createElement('div'); preview.id = PREVIEW_ID; document.body.appendChild(preview);
    const hint = document.createElement('div'); hint.id = HINT_ID; document.body.appendChild(hint);

    const slider = by('.bf-slider', panel);
    const btnPrev = by('.bf-prev', panel);
    const btnNext = by('.bf-next', panel);
    const counter = by('.bf-counter', panel);
    const pills = by('.bf-pills', panel);
    const closeBtn = by('.bf-close', panel);
    const toggleOnlyNotes = by('.bf-toggle-onlynotes', panel);
    const toggleLong = by('.bf-toggle-long', panel);
    const filterInput = by('.bf-filter', panel);

    let filteredIdxList = null;
    let pillEls = [];

    function formatLabel(n) {
      const when = n.when ? n.when.replace(/\s+/g,' ').trim() : '—';
      const numTxt = isNaN(n.num) ? n.linkTxt : `#${n.num}`;
      return `${numTxt} · ${when} · ${n.author}`;
    }

    function buildPreviewHTML(n) {
      const useTitle = !!n.summary;
      const ttl = useTitle ? esc(n.summary) : '';
      const text = esc(n.fullText.slice(0, CONFIG.PREVIEW_MAX_CHARS));
      const textHTML = `<div class="txt">${text}${n.fullText.length > CONFIG.PREVIEW_MAX_CHARS ? '…' : ''}</div>`;
      return n.imgSrc
        ? `<div class="row"><img src="${n.imgSrc}"><div style="flex:1 1 auto;">${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}</div></div>`
        : `${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}`;
    }

    function showHint(e, text){
      hint.textContent = text;
      hint.style.display = 'block';
      const rectW = hint.offsetWidth || 120;
      const x = Math.min(window.innerWidth - rectW - 8, Math.max(8, e.clientX - rectW/2));
      const y = Math.max(8, e.clientY - 26);
      hint.style.left = `${x}px`;
      hint.style.top = `${y}px`;
    }
    function hideHint(){ hint.style.display = 'none'; }

    function attachPillPreview(pill, n) {
      pill.removeAttribute('title');
      pill.addEventListener('mouseenter', (e) => {
        preview.innerHTML = buildPreviewHTML(n);
        preview.style.display = 'block';
        movePreview(e);
        showHint(e, `Jump to ${isNaN(n.num) ? n.linkTxt : ('#' + n.num)}`);
      });
      pill.addEventListener('mousemove', (e) => { movePreview(e); showHint(e, hint.textContent); });
      pill.addEventListener('mouseleave', () => { preview.style.display = 'none'; hideHint(); });

      function movePreview(e) {
        const pad = 12;
        const vw = window.innerWidth, vh = window.innerHeight;
        let x = e.clientX + pad, y = e.clientY + pad;
        const rectW = preview.offsetWidth || 320, rectH = preview.offsetHeight || 140;
        if (x + rectW + 8 > vw) x = vw - rectW - 8;
        if (y + rectH + 8 > vh) y = vh - rectH - 8;
        preview.style.left = `${x}px`;
        preview.style.top = `${y}px`;
      }
    }

    function rebuildPills() {
      pills.innerHTML = '';
      pillEls = [];
      const term = filterInput.value.trim().toLowerCase();
      const useFilter = !!term;
      filteredIdxList = [];

      notes.forEach((n, idx) => {
        if (toggleLong.checked && n.textLen < CONFIG.LONG_THRESHOLD) return;
        if (useFilter) {
          const hay = `${n.author} ${n.num} ${n.linkTxt} ${n.when}`.toLowerCase();
          if (!hay.includes(term)) return;
        }
        filteredIdxList.push(idx);

        const pill = document.createElement('button');
        pill.className = 'bf-pill';
        pill.setAttribute('role', 'option');
        pill.textContent = formatLabel(n);
        pill.addEventListener('click', () => { setActiveIndex(idx); jumpTo(n.el); });
        attachPillPreview(pill, n);
        pills.appendChild(pill);
        pillEls[idx] = pill;
      });

      if (!filteredIdxList.length) {
        const none = document.createElement('div');
        none.style.color = '#6b7280'; none.style.fontSize = '12px';
        none.textContent = 'No results match the filter.';
        pills.appendChild(none);
      }

      setActiveIndex(Math.min(activeIndex, notes.length - 1));
    }

    // Scroll active pill into view without animation; handle when active is missing in filtered view
    function ensureActivePillVisible() {
      let pill = pillEls[activeIndex];

      if (!pill && filteredIdxList && filteredIdxList.length) {
        let nearest = filteredIdxList[0], best = Math.abs(nearest - activeIndex);
        for (const i of filteredIdxList) {
          const d = Math.abs(i - activeIndex);
          if (d < best) { best = d; nearest = i; }
        }
        activeIndex = nearest;
        pill = pillEls[activeIndex];
      }
      if (!pill) return;

      pill.classList.add('active');
      pillEls.forEach((p, i) => { if (p && i !== activeIndex) p.classList.remove('active'); });
      pillEls.forEach((p, i) => p && p.setAttribute('aria-selected', i === activeIndex ? 'true' : 'false'));

      // scrollIntoView without smooth → no bounce
      if (pill.scrollIntoView) {
        pill.scrollIntoView({ block: 'nearest', inline: 'nearest' });
      } else {
        // manual fallback
        const c = pills, pTop = pill.offsetTop, pBottom = pTop + pill.offsetHeight + 6;
        if (pTop < c.scrollTop) c.scrollTop = pTop - 6;
        else if (pBottom > c.scrollTop + c.clientHeight) c.scrollTop = pBottom - c.clientHeight;
      }
    }

    function setActiveIndex(i) {
      activeIndex = Math.max(0, Math.min(notes.length - 1, i));
      slider.max = String(Math.max(0, notes.length - 1));
      slider.value = String(activeIndex);
      counter.textContent = `${activeIndex + 1}/${notes.length}`;
      ensureActivePillVisible();
    }

    function rebuildAll() {
      notes = collectNotes(excludeHidden);
      rebuildPills();
    }

    function move(delta) {
      const insideFilter = (toggleLong.checked || (filterInput.value.trim().length > 0));
      if (insideFilter && filteredIdxList && filteredIdxList.length) {
        const currPos = filteredIdxList.indexOf(activeIndex);
        const nextPos = currPos === -1 ? 0 : Math.max(0, Math.min(filteredIdxList.length - 1, currPos + delta));
        const nextIdx = filteredIdxList[nextPos];
        setActiveIndex(nextIdx);
      } else {
        setActiveIndex(activeIndex + delta);
      }
      const n = notes[activeIndex];
      if (n) jumpTo(n.el);
    }

    const sliderInput = () => setActiveIndex(parseInt(slider.value,10) || 0);
    slider.addEventListener('input', sliderInput);
    slider.addEventListener('change', () => { const n = notes[activeIndex]; if (n) jumpTo(n.el); });
    btnPrev.addEventListener('click', () => move(-1));
    btnNext.addEventListener('click', () => move(1));
    toggleOnlyNotes.addEventListener('change', () => { excludeHidden = toggleOnlyNotes.checked; rebuildAll(); });
    toggleLong.addEventListener('change', rebuildPills);
    filterInput.addEventListener('input', rebuildPills);
    closeBtn.addEventListener('click', () => panel.classList.remove('open'));

    const launcherClick = () => {
      panel.classList.toggle('open');
      if (panel.classList.contains('open')) selectClosest(false);
    };
    launcher.addEventListener('click', launcherClick);

    const onKey = (e) => {
      if (!panel.classList.contains('open')) return;
      const tag = (e.target.tagName || '').toLowerCase();
      const isTyping = (tag === 'input' || tag === 'textarea' || tag === 'select');
      if (isTyping && e.target !== filterInput) return;
      if (e.key === 'j' || e.key === 'n') { e.preventDefault(); move(1); }
      else if (e.key === 'k' || e.key === 'p') { e.preventDefault(); move(-1); }
      else if (e.key.toLowerCase() === 'g') {
        e.preventDefault();
        const s = prompt('Go to comment # (e.g. 10):'); if (!s) return;
        const targetNum = parseInt(s, 10); if (isNaN(targetNum)) return;
        const idx = notes.findIndex(n => n.num === targetNum);
        if (idx >= 0) { setActiveIndex(idx); jumpTo(notes[idx].el); }
        else alert(`Could not find #${targetNum}`);
      }
    };
    window.addEventListener('keydown', onKey);

    function selectClosest(suppressHighlight=false) {
      const viewportMid = window.scrollY + window.innerHeight / 2;
      let bestIdx = 0, bestDist = Infinity;
      notes.forEach((n, i) => {
        const rect = n.el.getBoundingClientRect();
        const y = window.scrollY + rect.top;
        const d = Math.abs(y - viewportMid);
        if (d < bestDist) { bestDist = d; bestIdx = i; }
      });
      setActiveIndex(bestIdx);
      highlight(notes[bestIdx].el, suppressHighlight);
    }

    rebuildAll();
    selectClosest(true);

    const mo = new MutationObserver(() => {
      clearTimeout(mo._t);
      mo._t = setTimeout(() => {
        const now = collectNotes(excludeHidden);
        const beforeIds = notes.map(n => n.el.id).join(',');
        const afterIds  = now.map(n => n.el.id).join(',');
        if (beforeIds !== afterIds) { notes = now; rebuildPills(); }
      }, 200);
    });
    mo.observe(historyRoot, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] });

    window.__BF_HistoryTimeline = {
      refresh: rebuildAll,
      open: () => panel.classList.add('open'),
      close: () => panel.classList.remove('open'),
      setWidth: (px) => { document.documentElement.style.setProperty('--bf-width', px + 'px'); },
      setLeft: (px) => { document.documentElement.style.setProperty('--bf-left', px + 'px'); },
      setBottom: (px) => { document.documentElement.style.setProperty('--bf-bottom', px + 'px'); },
      destroy: () => {
        mo.disconnect();
        [panel, launcher, hoverZone, css, preview, hint].forEach(el=>el?.remove());
        window.removeEventListener('keydown', onKey);
      }
    };
  }
})();
