(() => {
  const numberPattern = /^(\d{3})\s*[—–-]\s*(.+)$/;

  function applyLatestDocument(documentData) {
    const { number, title, subtitle, description, url, hero, cover, pdf, docx, nextNumber, nextTitle, nextDescription } = documentData;
    const total = Number.parseInt(number, 10);

    document.querySelectorAll('[data-document-total]').forEach((element) => {
      element.textContent = String(total);
    });
    document.querySelectorAll('[data-document-count]').forEach((element) => {
      element.textContent = `Explore all ${total} releases in the Developer Library`;
    });
    document.querySelectorAll('[data-latest-ticker]').forEach((element) => {
      element.href = url;
      element.innerHTML = `<strong>Document ${number}</strong> — ${title} is now available`;
    });
    document.querySelectorAll('[data-latest-hero-link]').forEach((element) => {
      element.href = url;
      element.querySelector('strong').textContent = `Document ${number} — ${title}`;
    });
    document.querySelectorAll('[data-latest-hero-background]').forEach((element) => {
      if (hero) element.style.backgroundImage = `url('${hero}')`;
    });
    document.querySelectorAll('[data-latest-cover]').forEach((element) => {
      if (cover || hero) element.src = cover || hero;
      element.alt = `${title} cover`;
    });
    document.querySelectorAll('[data-latest-number]').forEach((element) => { element.textContent = `Document ${number}`; });
    document.querySelectorAll('[data-latest-title]').forEach((element) => { element.textContent = title; });
    document.querySelectorAll('[data-latest-description]').forEach((element) => { element.textContent = subtitle; });
    document.querySelectorAll('[data-latest-read]').forEach((element) => { element.href = url; });
    document.querySelectorAll('[data-latest-pdf]').forEach((element) => { if (pdf) element.href = pdf; });
    document.querySelectorAll('[data-latest-docx]').forEach((element) => { if (docx) element.href = docx; });
    document.querySelectorAll('[data-latest-start]').forEach((element) => {
      element.href = url;
      const descriptionElement = element.querySelector('.ev-start-desc');
      if (descriptionElement) descriptionElement.textContent = `${number} — ${title}.`;
    });
    document.querySelectorAll('[data-latest-share]').forEach((element) => {
      element.dataset.shareTitle = `Document ${number} — ${title}`;
      element.dataset.shareText = subtitle;
      element.dataset.shareUrl = url;
    });
    document.querySelectorAll('[data-library-share]').forEach((element) => {
      element.dataset.shareText = `Explore all ${total} official documents in the Arena Z Studios Developer Library.`;
    });
    document.querySelectorAll('[data-world-share]').forEach((element) => {
      element.dataset.shareText = `Explore the world of Valekor — kingdoms, dragons, characters and ${total} official documents.`;
    });

    const feature = document.querySelector('[data-latest-feature]');
    if (feature) {
      feature.href = url;
      const image = feature.querySelector('img');
      if (hero) image.src = hero;
      image.alt = title;
      feature.querySelector('.gp-story-copy').innerHTML = `<p>Featured Today · Latest Document</p><h3>${number} — ${title}</h3><span>${description || subtitle}</span>`;
    }

    const preview = document.querySelector('[data-latest-library-preview]');
    if (preview) {
      preview.href = url;
      const image = preview.querySelector('img');
      if (cover || hero) image.src = cover || hero;
      image.alt = `${title} cover`;
      preview.querySelector('small').textContent = `Document ${number}`;
      preview.querySelector('h3').textContent = title;
      preview.querySelector('p').textContent = subtitle;
    }

    const studioNews = document.querySelector('[data-latest-studio-news]');
    if (studioNews) {
      studioNews.href = url;
      studioNews.querySelector('h3').textContent = `${number} — ${title}`;
      studioNews.querySelector('p').textContent = `Now Available · ${subtitle}`;
    }

    const nextChapter = document.querySelector('[data-next-chapter]');
    if (nextChapter && nextNumber && nextTitle) {
      nextChapter.setAttribute('aria-label', `Coming next: Developer Library Document ${nextNumber}, ${nextTitle}`);
      nextChapter.querySelector('.gp-coming-art strong').textContent = nextNumber;
      nextChapter.querySelector('small').textContent = `Developer Library · Document ${nextNumber}`;
      nextChapter.querySelector('h3').textContent = nextTitle;
      nextChapter.querySelector('p').textContent = nextDescription || '';
    }
  }

  fetch('arena-z-studios.html')
    .then((response) => {
      if (!response.ok) throw new Error('Developer Library could not be loaded.');
      return response.text();
    })
    .then((html) => {
      const library = new DOMParser().parseFromString(html, 'text/html');
      const documents = [...library.querySelectorAll('.azs-library-card')].map((card) => {
        const match = card.querySelector('h3')?.textContent.trim().match(numberPattern);
        const url = card.querySelector('.azs-card-actions a[href$=".html"]')?.getAttribute('href');
        const pdf = card.querySelector('.azs-card-actions a[href$=".pdf"]')?.getAttribute('href') || '';
        const docx = card.querySelector('.azs-card-actions a[href$=".docx"]')?.getAttribute('href') || '';
        if (!match || !url) return null;
        return {
          number: match[1],
          title: match[2].trim(),
          subtitle: card.querySelector('p strong')?.textContent.trim() || card.querySelector('p')?.textContent.trim() || '',
          url,
          pdf,
          docx,
          description: card.dataset.homeDescription || '',
          hero: card.dataset.homeHero || '',
          cover: card.dataset.homeCover || '',
          nextNumber: card.dataset.nextNumber || '',
          nextTitle: card.dataset.nextTitle || '',
          nextDescription: card.dataset.nextDescription || ''
        };
      }).filter(Boolean).sort((first, second) => Number(first.number) - Number(second.number));

      if (documents.length) applyLatestDocument(documents.at(-1));
    })
    .catch(() => {
      // The server-rendered homepage already contains the current latest release.
    });
})();
