const relatedPostsJsVars = window['generatify_related_posts_js_vars'] || {};

class GeneratifyRelatedPosts extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.styles = new Set();
    this.title = relatedPostsJsVars.aiRelatedPostsSettings.title || '';
    this.description = relatedPostsJsVars.aiRelatedPostsSettings.description || '';
    this.quantity = relatedPostsJsVars.aiRelatedPostsSettings.quantity || 3;
    this.relatedPosts = relatedPostsJsVars.relatedPosts || [];
  }

  async connectedCallback() {
    this.render();
  }

  renderRelatedPost(id = '', title = '', excerpt = '', permalink = '', thumbnail = '') {
    // Use placeholder if thumbnail is empty
    const imageSrc = thumbnail || relatedPostsJsVars.pluginDirUrl + 'assets/media/images/placeholder.png';

    this.styles.add(`
      .related-post {
        width: 100%;
        height: auto;
        max-width: 350px;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        overflow: hidden;
        background-color: #ffffff;
        transition: box-shadow 0.2s ease;
      }

      .related-post:hover {
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }

      .related-post_link {
        display: block;
        padding: 16px;
        text-decoration: none;
        color: inherit;
      }

      .related-post_thumbnail {
        width: 100%;
        height: 180px;
        display: block;
        border-radius: 8px;
        object-fit: cover;
      }

      .related-post_title {
        margin-top: 16px;
        font-size: 20px;
        line-height: 28px;
        font-weight: 600;
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }

      .related-post_excerpt {
        margin-top: 14px;
        font-size: 14px;
        line-height: 20px;
        color: #4b5563;
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
    `);

    return `
      <article class="related-post" data-post-id="${id}">
        <a class="related-post_link text-xl font-semibold text-gray-800" href="${permalink}" target="_parent">
          <img class="related-post_thumbnail" src="${imageSrc}" alt="${title}" />
          <div class="related-post_title">${title}</div>
          <div class="related-post_excerpt">${excerpt}</div>
        </a>
      </article>
    `;
  }

  async renderRelatedPosts() {
    const renderedPosts = await Promise.all(
      this.relatedPosts.map(async (post) => {
        const { id, title, excerpt, permalink, thumbnail } = post;
        return this.renderRelatedPost(id, title, excerpt, permalink, thumbnail);
      })
    );

    return renderedPosts.join('');
  }

  async render() {
    this.styles.add(`
     .related-posts-section {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
            -ms-flex-direction: column;
                flex-direction: column;
        gap: 30px;
        margin: 60px auto;
      }

      .related-posts-header {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
            -ms-flex-direction: column;
                flex-direction: column;
        -webkit-box-align: center;
            -ms-flex-align: center;
                align-items: center;
        gap: 5px;
      }

      .related-posts-title {
        font-size: 30px;
        line-height: 36px;
        font-weight: 700;
        color: #111827;
        text-align: center;
      }

      .related-posts-description {
        font-size: 16px;
        line-height: 24px;
        text-align: center;
        text-wrap: balance;
        color: #4b5563;
      }

      .related-posts-container {
        display:-ms-grid;
        display:grid;
        grid-template-columns: repeat(auto-fit, minmax(0, 350px));
        -webkit-box-pack: center;
            -ms-flex-pack: center;
                justify-content: center;
        gap: 30px;
      }
    `);

    const relatedPostsHtml = await this.renderRelatedPosts();
    const combinedStyles = Array.from(this.styles).join('\n');
    const headerHtml =
      this.title || this.description
        ? `
      <div class="related-posts-header">
        <div class="related-posts-title">${this.title}</div>
        <div class="related-posts-description">${this.description}</div>
      </div>
    `
        : '';

    this.shadowRoot.innerHTML = `
      <style>${combinedStyles}</style>
      <div class="related-posts-section">
        ${headerHtml}
        <div class="related-posts-container">
          ${relatedPostsHtml}
        </div>
      </div>
    `;
  }
}

function initRelatedPosts() {
  if (!customElements.get('generatify-related-posts')) {
    customElements.define('generatify-related-posts', GeneratifyRelatedPosts);
  }
}

document.addEventListener('DOMContentLoaded', () => {
  if (document.querySelector('generatify-related-posts')) {
    initRelatedPosts();
  }
});
