const ALGOLIA_ID = '0X4IAR77M1'; // Algolia ID
const ALGOLIA_KEY = '591d39ef5124b1813557f8e7f123cbd1'; // Algolia API Key

// algolia analytics
aa('init', {
  appId: ALGOLIA_ID,
  apiKey: ALGOLIA_KEY,
  useCookie: true,
});

// init algolia search client with credentials
const searchClient = algoliasearch(ALGOLIA_ID, ALGOLIA_KEY);

const pagehitsContainer = document.querySelector('#pagehitcontainer');
const bloghitsContainer = document.querySelector('#bloghitcontainer');
const resourcehitsContainer = document.querySelector('#resourcehitcontainer');
const docshitContainer = document.querySelector('#docshitcontainer');
const statsContainer = document.querySelector('#stats');
const refinementContainer = document.querySelector('.filter-options');
const noResultsContainer = document.querySelector('#noResults');
const toggleRefinement = document.querySelector('#toggle-refinement');

const search = instantsearch({
  indexName: 'Marketing',
  searchClient,
  searchFunction: function (helper) {
    if (helper.state.query.length < 1) {
      pagehitsContainer.style.display = 'none';
      bloghitsContainer.style.display = 'none';
      resourcehitsContainer.style.display = 'none';
      docshitContainer.style.display = 'none';
      statsContainer.style.display = 'none';
      refinementContainer.style.display = 'none';
    } else {
      pagehitsContainer.style.display = 'block';
      bloghitsContainer.style.display = 'block';
      resourcehitsContainer.style.display = 'block';
      docshitContainer.style.display = 'block';
      statsContainer.style.display = 'flex';
      refinementContainer.style.display = 'flex';
      helper.search();
    }
  },
});

const renderStats = (renderOptions) => {
  const { nbHits, query } = renderOptions;
  if (nbHits > 4) {
    statsContainer.innerHTML = `
      <a href='/searchresults?q=${query}'>View more results</a>
    `;
  } else {
    statsContainer.innerHTML = ``;
  }
};

const customStats = instantsearch.connectors.connectStats(renderStats);

search.addWidgets([
  instantsearch.widgets.configure({
    attributesToSnippet: ['post_content'],
    clickAnalytics: true,
    hitsPerPage: 4,
    distinct: 4,
    snippetEllipsisText: '...',
  }),

  instantsearch.widgets.searchBox({
    container: '#searchbox',
    placeholder: 'Search for...',
    autofocus: true,
  }),

  instantsearch.widgets.refinementList({
    container: '#refinement-list',
    attribute: 'post_type',
    showMore: true,
  }),

  // instantsearch.widgets.hits({
  //   container: '#pageHits',
  //   templates: {
  //     item: (hit, bindEvent) => {
  //         return (
  //           `
  //       <a ${bindEvent('click', hit, 'hit clicked')} href="` +
  //           hit.url +
  //           `">
  //         <h6 style="color: #b835a1;font-size:0.825rem;margin:0;text-transform: capitalize;">${
  //           hit.post_type
  //         }</h6>
  //         <h2>
  //           ${instantsearch.highlight({ attribute: 'post_title', hit: hit })}
  //         </h2>
  //         <p>
  //           ${instantsearch.snippet({ attribute: 'post_content', hit: hit })}
  //         </p>
  //       </a>
  //       `
  //         );
  //       }
  //     },
  //     empty: (results) => {
  //       refinementContainer.style.display = 'none';
  //       return `<div id="noResults">
  //             <h2>We're sorry!</h2>
  //             <p>We couldn't find any results for: "${
  //               results && results.query
  //             }"</p>
  //           </div>`;
  //     },
  // }),

  customStats({
    container: document.querySelector('#stats'),
  }),

  instantsearch.widgets.index({ indexName: 'Marketing' }).addWidgets([
    instantsearch.widgets.configure({
      attributesToSnippet: ['post_content:15'],
      filters: 'post_type: "blog" AND post_status: "publish"',
    }),
    instantsearch.widgets.hits({
      container: '#blogHits',
      templates: {
        item: (hit, bindEvent) => {
          return (
            `
                <a ${bindEvent('click', hit, 'hit clicked')} href="` +
            hit.url +
            `">
                  <h2>
                  ${
                    hit.headline
                      ? instantsearch.highlight({
                          attribute: 'headline',
                          hit: hit,
                        })
                      : instantsearch.highlight({
                          attribute: 'post_title',
                          hit: hit,
                        })
                  }
                  </h2>
                  <p>
                    ${instantsearch.snippet({ attribute: 'post_content', hit })}
                  </p>
                </a>
                `
          );
        },
        empty: (results) => {
          bloghitsContainer.style.display = 'none';
          return ``;
        },
      },
    }),
  ]),

  instantsearch.widgets.index({ indexName: 'Marketing' }).addWidgets([
    instantsearch.widgets.configure({
      attributesToSnippet: ['post_content:15'],
      filters: 'post_type: "page" AND post_status: "publish"',
    }),
    instantsearch.widgets.hits({
      container: '#pageHits',
      templates: {
        item: (hit, bindEvent) => {
          return (
            `
                <a ${bindEvent('click', hit, 'hit clicked')} href="` +
            hit.url +
            `">
                <h6 style="font-size: 0.8rem;color: #b835a1;font-weight: 600;margin: 0;">${
                  hit.resource_type ? hit.resource_type : ''
                }</h6>
                <h2>
                ${instantsearch.highlight({
                  attribute: 'post_title',
                  hit: hit,
                })}
                </h2>
                <p>
                  ${instantsearch.snippet({ attribute: 'post_content', hit })}
                </p>
                </a>
                `
          );
        },
        empty: (results) => {
          pagehitsContainer.style.display = 'none';
          return ``;
        },
      },
    }),
  ]),

  instantsearch.widgets.index({ indexName: 'Marketing' }).addWidgets([
    instantsearch.widgets.configure({
      attributesToSnippet: ['post_content:15'],
      filters: 'post_type: "resources" AND post_status: "publish"',
    }),
    instantsearch.widgets.hits({
      container: '#resourceHits',
      templates: {
        item: (hit, bindEvent) => {
          return (
            `
                <a ${bindEvent('click', hit, 'hit clicked')} href="` +
            hit.url +
            `">
                  <h6 style="font-size: 0.8rem;color: #b835a1;font-weight: 600;margin: 0;">${
                    hit.resource_type ? hit.resource_type : ''
                  }</h6>
                  <h2>
                  ${instantsearch.highlight({
                    attribute: 'post_title',
                    hit: hit,
                  })}
                  </h2>
                  <p>
                    ${instantsearch.snippet({ attribute: 'post_content', hit })}
                  </p>
                </a>
                `
          );
        },
        empty: (results) => {
          resourcehitsContainer.style.display = 'none';
          return ``;
        },
      },
    }),
  ]),

  instantsearch.widgets.index({ indexName: 'AllDocs' }).addWidgets([
    instantsearch.widgets.configure({
      attributesToSnippet: ['content'],
      clickAnalytics: true,
      hitsPerPage: 4,
      filters: 'version: "latest" OR type: "guides"',
    }),
    instantsearch.widgets.hits({
      container: '#docsHits',
      templates: {
        item: (hit, bindEvent) => {
          return (
            `
                <a ${bindEvent('click', hit, 'hit clicked')} href="` +
            hit.url +
            `">
                  <h2>
                    ${instantsearch.highlight({ attribute: 'title', hit: hit })}
                  </h2>
                  <p>
                    ${instantsearch.snippet({ attribute: 'content', hit: hit })}
                  </p>
                </a>
                `
          );
        },
        empty: (results) => {
          docshitContainer.style.display = 'none';
          return ``;
        },
      },
    }),

    instantsearch.widgets.toggleRefinement({
      container: '#toggle-refinement',
      attribute: 'type',
      on: true,
      templates: {
        labelText: 'Hide documentation',
      },
    }),
  ]),
]);

search.use(
  instantsearch.middlewares.createInsightsMiddleware({
    insightsClient: window.aa,
  })
);

search.start();
