{% comment %}
Help Side Nav (with padding + full-content search)
- Place as the FIRST section on each help template (page.contact.json, page.faq.json, etc.)
- Left column shows a search input; typing fetches & searches ALL linked help pages (incl. FAQ accordions)
- Below that: either search results (when typing) or the normal page list (when empty)
- Keeps "Common settings" (width, color scheme, spacing)
{% endcomment %}

<nav class="help-sidenav" aria-label="Help topics">
  <div class="help-sidenav__inner">
    <!-- Search -->
    <div class="help-sidenav__search">
      <input
        type="text"
        id="helpSearch-{{ section.id }}"
        class="help-sidenav__input"
        placeholder="Search keywords"
        aria-label="Search help content"
        autocomplete="off"
      >
    </div>

    <!-- Results appear here when typing -->
    <div class="help-sidenav__results" id="helpResults-{{ section.id }}" hidden></div>

    {% if section.settings.menu != blank and linklists[section.settings.menu] %}
      <!-- Default page list (hidden while searching) -->
      <ul class="help-sidenav__list" id="helpList-{{ section.id }}">
        {% for link in linklists[section.settings.menu].links %}
          {% assign active_class = '' %}
          {% if link.url == request.path or link.url == request.fullpath %}
            {% assign active_class = ' is-active' %}
          {% endif %}
          <li class="help-sidenav__item" data-title="{{ link.title | downcase }}">
            <a class="help-sidenav__link{{ active_class }}" href="{{ link.url }}" data-help-url="{{ link.url }}">{{ link.title }}</a>
          </li>
        {% endfor %}
      </ul>
      <div class="help-sidenav__empty" id="helpEmpty-{{ section.id }}" hidden>No matches.</div>
    {% else %}
      <p>Add a menu in section settings.</p>
    {% endif %}
  </div>
</nav>

<style>
/* --- Common settings (spacing) --- */
#shopify-section-{{ section.id }}.shopify-section {
  float: left;
  width: 260px; /* column width; content gets inner padding */
  --padding-block-start: calc(var(--section-spacing-unit-size) * {{ section.settings.spacing_top }});   /* top spacing */
  --padding-block-end:   calc(var(--section-spacing-unit-size) * {{ section.settings.spacing_bottom }}); /* bottom spacing */
  padding-block-start: var(--padding-block-start);
  padding-block-end:   var(--padding-block-end);
}

/* Push subsequent sections (main page content) to the right */
#shopify-section-{{ section.id }}.shopify-section ~ .shopify-section {
  margin-left: 292px; /* 260 + 32 gap */
}

/* Left/right breathing room INSIDE the nav (desktop + mobile) */
#shopify-section-{{ section.id }} .help-sidenav__inner {
  padding: 0 14px;        /* <-- adds space on both sides */
}
@media (min-width: 992px) {
  #shopify-section-{{ section.id }} .help-sidenav__inner {
    padding: 0 0 0 var(--page-gutter);
  }
}

/* Sidenav layout */
#shopify-section-{{ section.id }} .help-sidenav {
  position: sticky;
  top: calc(var(--header-height, 64px) + 16px);
}
#shopify-section-{{ section.id }} .help-sidenav__search { margin-bottom: 10px; }
#shopify-section-{{ section.id }} .help-sidenav__input {
  width: 100%;
  height: 3.6rem;
  padding: 0 .9rem;
  border: 1px solid #a9a7a7;
  border-radius: var(--input-border-radius);
  background: transparent;
  color: rgb(var(--color-heading-text));
  font: inherit;
  line-height: 1;
  transition: border-color var(--duration-default);
}
#shopify-section-{{ section.id }} .help-sidenav__input:focus {
  outline: none; border-color: rgb(var(--color-heading-text));
}

#shopify-section-{{ section.id }} .help-sidenav__list {
  list-style: none; margin: 0; padding: 0;
  display: flex; flex-direction: column; gap: 6px;
}
#shopify-section-{{ section.id }} .help-sidenav__link {
  display: block; padding: 10px 12px; border-radius: 8px;
  text-decoration: none; color: var(--color-foreground, inherit);
}
#shopify-section-{{ section.id }} .help-sidenav__link:hover {
  text-decoration: underline;
  font-weight: 500;
}
#shopify-section-{{ section.id }} .help-sidenav__link.is-active {
  font-weight: 600; 
  text-decoration: underline;
}
#shopify-section-{{ section.id }} .help-sidenav__empty {
  margin-top: 8px; font-size: 13px; color: #777;
}

/* Result items */
#shopify-section-{{ section.id }} .help-result {
  padding: 10px 12px; border-radius: 8px; background: var(--color-base-background-2, #f5f5f5);
  margin-bottom: 6px;
}
#shopify-section-{{ section.id }} .help-result__meta {
  display:block; font-size: 12.5px; color:#666; margin-bottom: 4px;
}
#shopify-section-{{ section.id }} .help-result__title {
  font-weight: 600; margin-bottom: 4px;
}
#shopify-section-{{ section.id }} .help-result a { text-decoration: none; }

/* Mobile: stack (no two-column offset) */
@media (max-width: 992px) {
  #shopify-section-{{ section.id }}.shopify-section { float: none; width: auto; }
  #shopify-section-{{ section.id }}.shopify-section ~ .shopify-section { margin-left: 0; }
}

/* Mobile: show ONLY the search bar */
@media (max-width: 992px) {
  #shopify-section-{{ section.id }} .help-sidenav__list,
  #shopify-section-{{ section.id }} .help-sidenav__empty {
    display: none !important;   /* hide page list + "no matches" note */
  }

  /* keep the section stacked (already present in your file) */
  #shopify-section-{{ section.id }}.shopify-section { float: none; width: auto; }
  #shopify-section-{{ section.id }}.shopify-section ~ .shopify-section { margin-left: 0; }
}

</style>

<script>
(function() {
  const root = document.getElementById('shopify-section-{{ section.id }}');
  if (!root) return;

  const input   = root.querySelector('#helpSearch-{{ section.id }}');
  const list    = root.querySelector('#helpList-{{ section.id }}');
  const empty   = root.querySelector('#helpEmpty-{{ section.id }}');
  const results = root.querySelector('#helpResults-{{ section.id }}');
  const menuLinks = root.querySelectorAll('.help-sidenav__link[data-help-url]');

  // Build an index by fetching each linked page so we can search FAQs/answers/content
  let index = [];
  let ready = false;
  let building = false;

  async function buildIndex() {
    if (ready || building) return;
    building = true;
    const parser = new DOMParser();

    for (const a of menuLinks) {
      const url = a.getAttribute('data-help-url');
      const pageTitle = a.textContent.trim();

      try {
        const res = await fetch(url, { credentials: 'same-origin' });
        if (!res.ok) continue;
        const html = await res.text();
        const doc = parser.parseFromString(html, 'text/html');

        // Prefer extracting structured accordion Q&As
        const acc = doc.querySelectorAll('.accordion__section');
        if (acc.length) {
          const category = doc.querySelector('.section__heading')?.textContent?.trim() || pageTitle;
          acc.forEach(sec => {
            const q = sec.querySelector('.accordion__button-text')?.textContent?.trim() || '';
            const aHTML = sec.querySelector('.accordion__body-inner')?.innerHTML || '';
            const aText = sec.querySelector('.accordion__body-inner')?.textContent?.trim() || '';
            if (q || aHTML) {
              index.push({ pageTitle, category, question: q, answerHTML: aHTML, answerText: aText, url });
            }
          });
        } else {
          // Fallback: index main content text
          const main = doc.querySelector('main') || doc.body;
          const text = (main.textContent || '').trim();
          if (text) {
            // Break into short snippets around headings/paragraphs
            const firstH = main.querySelector('h1,h2,h3,h4,h5,h6')?.textContent?.trim() || pageTitle;
            index.push({ pageTitle, category: firstH, question: firstH, answerHTML: main.innerHTML, answerText: text, url });
          }
        }
      } catch (e) {
        /* ignore fetch errors to avoid blocking */
      }
    }

    ready = true;
    building = false;
  }

  function renderResults(items) {
    results.innerHTML = '';
    if (!items.length) {
      results.hidden = false;
      results.innerHTML = '<div class="help-sidenav__empty">No matches.</div>';
      return;
    }
    const frag = document.createDocumentFragment();
    items.slice(0, 50).forEach(it => {
      const el = document.createElement('div');
      el.className = 'help-result';
      el.innerHTML = `
        <a class="help-result__meta" href="${it.url}">${it.pageTitle}</a>
        ${it.question ? `<div class="help-result__title">${it.question}</div>` : ''}
        <div class="help-result__snippet">${it.answerHTML}</div>
      `;
      frag.appendChild(el);
    });
    results.appendChild(frag);
    results.hidden = false;
  }

  function doSearch() {
    const q = input.value.toLowerCase().trim();
    if (!q) {
      results.hidden = true;
      results.innerHTML = '';
      if (list) list.hidden = false;
      if (empty) empty.hidden = true;
      return;
    }
    if (list) list.hidden = true;

    const hits = index.filter(it =>
      (it.question && it.question.toLowerCase().includes(q)) ||
      (it.answerText && it.answerText.toLowerCase().includes(q)) ||
      (it.pageTitle && it.pageTitle.toLowerCase().includes(q)) ||
      (it.category && it.category.toLowerCase().includes(q))
    );
    renderResults(hits);
  }

  function ensureIndexThenSearch() {
    if (!ready && !building) {
      buildIndex().then(doSearch);
    } else {
      doSearch();
    }
  }

  input?.addEventListener('focus', ensureIndexThenSearch);
  input?.addEventListener('input', ensureIndexThenSearch);
})();
</script>

{% schema %}
{
  "name": "Help side nav",
  "settings": [
    { "type": "link_list", "id": "menu", "label": "Help menu (Pages)", "info": "Choose a menu that lists your help pages." },

    { "type": "header", "content": "Common settings", "info": "These settings are common for all sections." },
    { "type": "select", "id": "section_width", "label": "Section width",
      "options": [
        { "value": "max-w-page", "label": "Page" },
        { "value": "max-w-narrow", "label": "Narrow" },
        { "value": "max-w-narrower", "label": "Narrower" },
        { "value": "max-w-fluid", "label": "Fluid" }
      ],
      "default": "max-w-narrow"
    },
    { "type": "color_scheme", "id": "color_scheme", "label": "Color scheme", "default": "scheme-3" },
    { "type": "color_scheme", "id": "color_scheme_for_media", "label": "Color scheme for media", "default": "scheme-1" },
    { "type": "select", "id": "spacing_top", "label": "Top spacing",
      "options": [
        { "value": "0", "label": "No" },
        { "value": "1", "label": "S" },
        { "value": "2", "label": "M" },
        { "value": "4", "label": "L" },
        { "value": "6", "label": "XL" }
      ],
      "default": "2"
    },
    { "type": "select", "id": "spacing_bottom", "label": "Bottom spacing",
      "options": [
        { "value": "0", "label": "No" },
        { "value": "1", "label": "S" },
        { "value": "2", "label": "M" },
        { "value": "4", "label": "L" },
        { "value": "6", "label": "XL" }
      ],
      "default": "6"
    }
  ],
  "presets": [{ "name": "Help side nav" }]
}
{% endschema %}
