(function(){
  const $_ = (q, el=document) => el.querySelector(q);
  const $_all = (q, el=document) => Array.from(el.querySelectorAll(q));

  const state = {
    pages: [],
    index: {},
    current: null,
  };

  async function loadJSON(path){
    const res = await fetch(path, {cache:'no-store'});
    if(!res.ok) throw new Error('Failed to load ' + path);
    return await res.json();
  }

  async function loadPageContent(file){
    const res = await fetch('pages/' + file, {cache:'no-store'});
    if(!res.ok) return '<div class="article"><h2>Missing page</h2><p>Could not load: '+file+'</p></div>';
    return await res.text();
  }

  function setActiveNav(id){
    $_all('.nav a').forEach(a => a.classList.toggle('active', a.dataset.id === id));
  }

  function setBreadcrumb(title, sub){
    $('#pageTitle').textContent = title || 'SKIDATA Cashier Manual';
    $('#pageSub').textContent = sub || '';
    document.title = (title ? title + ' — ' : '') + 'SKIDATA Cashier Manual';
  }

  function scrollTop(){
    $('#mainScroll').scrollTo({top:0, behavior:'smooth'});
  }

  function toggleTheme(){
    // Placeholder if you want to add a light theme later
    alert('Theme toggle is ready for future expansion 🙂');
  }

  function buildNav(pages){
    const nav = $('#nav');
    nav.innerHTML = '';
    let lastGroup = null;

    pages.forEach(p => {
      if(p.group && p.group !== lastGroup){
        const gt = document.createElement('div');
        gt.className = 'groupTitle';
        gt.textContent = p.group;
        nav.appendChild(gt);
        lastGroup = p.group;
      }

      const a = document.createElement('a');
      a.href = '#/' + encodeURIComponent(p.id);
      a.dataset.id = p.id;

      const wrap = document.createElement('div');
      wrap.style.display = 'grid';
      wrap.style.gap = '2px';

      const t = document.createElement('div');
      t.textContent = p.title;
      t.style.fontWeight = '800';
      t.style.fontSize = '13px';

      const d = document.createElement('div');
      d.textContent = p.desc || '';
      d.style.fontSize = '12px';
      d.style.color = 'rgba(159,176,197,.92)';

      wrap.appendChild(t);
      if(p.desc) wrap.appendChild(d);

      const pill = document.createElement('div');
      pill.className = 'pill';
      pill.textContent = p.pill || '';

      a.appendChild(wrap);
      if(p.pill) a.appendChild(pill);

      nav.appendChild(a);
    });
  }

  function buildSearchIndex(pages){
    const idx = {};
    pages.forEach(p => {
      idx[p.id] = (p.title + ' ' + (p.desc||'') + ' ' + (p.keywords||[]).join(' ')).toLowerCase();
    });
    state.index = idx;
  }

  function applyFilter(text){
    const q = (text || '').trim().toLowerCase();
    $_all('.nav a').forEach(a => {
      const id = a.dataset.id;
      const hay = state.index[id] || '';
      a.style.display = (!q || hay.includes(q)) ? '' : 'none';
    });
    // Keep group titles visible if any of their items visible
    const nav = $('#nav');
    const children = Array.from(nav.children);
    for(let i=0;i<children.length;i++){
      const el = children[i];
      if(!el.classList.contains('groupTitle')) continue;
      // groupTitle applies to following items until next groupTitle
      let visible = false;
      for(let j=i+1;j<children.length;j++){
        if(children[j].classList.contains('groupTitle')) break;
        if(children[j].tagName === 'A' && children[j].style.display !== 'none') { visible = true; break; }
      }
      el.style.display = visible ? '' : 'none';
    }
  }

  async function route(){
    const raw = location.hash || '#/home';
    const id = decodeURIComponent(raw.replace(/^#\//,'').trim()) || 'home';
    const page = state.pages.find(p => p.id === id) || state.pages[0];

    state.current = page.id;
    setActiveNav(page.id);
    setBreadcrumb(page.title, page.sub || page.group || '');
    const html = await loadPageContent(page.file);
    $('#content').innerHTML = html;
    scrollTop();
    highlightCallouts();
  }

  function highlightCallouts(){
    // Enhances standard "Hint/Notice/Danger/Task" blocks if present
    $_all('[data-callout]').forEach(el => {
      const type = el.getAttribute('data-callout') || 'hint';
      el.classList.add('callout', type);
      // auto-build tag if not present
      if(!el.querySelector('.tag')){
        const tag = document.createElement('div');
        tag.className = 'tag';
        tag.textContent = type;
        el.prepend(tag);
      }
    });
  }

  async function init(){
    const pages = await loadJSON('assets/data/pages.json');
    state.pages = pages;
    buildNav(pages);
    buildSearchIndex(pages);

    window.addEventListener('hashchange', route);

    $('#search').addEventListener('input', (e) => applyFilter(e.target.value));
    $('#btnTop').addEventListener('click', scrollTop);
    $('#btnTheme').addEventListener('click', toggleTheme);

    // first route
    await route();
  }

  init().catch(err => {
    console.error(err);
    document.body.innerHTML = '<pre style="color:#fff;background:#000;padding:16px;">App failed to start:\n'+(err && err.stack ? err.stack : err)+'</pre>';
  });
})();