if (!LFP) { error("LFP not loaded: author_block_polopoly"); }
if (!LFP.MODULES.POLOPOLY_AUTHOR) {
  LFP.MODULES.POLOPOLY_AUTHOR = new Object();

  LFP.MODULES.POLOPOLY_AUTHOR.loadAuthors = function() {
    const authorBlocks = document.querySelectorAll('.author_block_polopoly');
    const graphQlEndpoint = 'https://www.cbc.ca/graphql'

    authorBlocks.forEach(function(authorBlock) {
      const authorId = authorBlock.dataset['author'];
      const query = {
        query: `{
          author(sourceId: "${authorId}") {
            title
            name
            biography
            sourceId
            url
            authorLinks {
              type
              title
              url
            }
            photoDerivatives {
              square_140 {
                w
                h
                fileurl
              }
              square_300 {
                w
                h
                fileurl
              }
              square_620 {
                w
                h
                fileurl
              }
            }
          }
        }`
      };

      const xhr = new XMLHttpRequest();
      xhr.responseType = 'json';
      xhr.open('POST', graphQlEndpoint);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.addEventListener('load', function() {
        LFP.MODULES.POLOPOLY_AUTHOR.renderAuthorBlock(this.response, authorBlock);
      });
      xhr.send(JSON.stringify(query));
    });
  }
  
  LFP.MODULES.POLOPOLY_AUTHOR.renderAuthorBlock = function(data, authorBlock) {
    let markup = `<p style="color: red;">There was an error displaying this author block</p>`;
    if (data.errors && data.errors[0].message) {
      markup = `<p style="color: red;">Author Block — ${data.errors[0].message}</p>`;
    } else if (data.data && data.data.author) {
      const author = data.data.author;
      markup = `<div class="entry-author">
            <a href="${author.url}"><img class="author-image" src="${author.photoDerivatives.square_140.fileurl}" alt="${author.name}"></a>
            <div class="author-info">
              <span class="author-name">${author.name}</span>
              <span class="author-bio"><p>${author.biography}</p></span>
            </div>
          </div>`
    }
    authorBlock.innerHTML = markup;
  }
  
  LFP.MODULES.POLOPOLY_AUTHOR.loadAuthors();
}
