(function () {
  'use strict';

  var refreshTimer = null;

  function slugify(text) {
    return String(text || '')
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }

  function escapeHtml(text) {
    return String(text || '').replace(/[&<>"']/g, function (match) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      }[match];
    });
  }

  function getViewportType() {
    var viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;

    if (viewportWidth >= 1025) {
      return 'desktop';
    }

    if (viewportWidth >= 768) {
      return 'tablet';
    }

    return 'mobile';
  }

  function getResponsiveExcerptLength(dataset) {
    var viewportType = getViewportType();
    var fallback = 40;
    var length = 0;

    if (viewportType === 'mobile') {
      length = parseInt(dataset.sitselExcerptLengthMobile, 10) || 0;
    } else if (viewportType === 'tablet') {
      length = parseInt(dataset.sitselExcerptLengthTablet, 10) || 0;
    } else {
      length = parseInt(dataset.sitselExcerptLengthDesktop, 10) || 0;
    }

    if (!length) {
      length = parseInt(dataset.sitselExcerptLengthDesktop, 10)
        || parseInt(dataset.sitselExcerptLengthTablet, 10)
        || parseInt(dataset.sitselExcerptLengthMobile, 10)
        || fallback;
    }

    return Math.max(5, length);
  }

  function trimWords(text, limit) {
    var words = String(text || '')
      .replace(/\s+/g, ' ')
      .trim()
      .split(' ')
      .filter(Boolean);
    var maxWords = Math.max(5, parseInt(limit, 10) || 0);

    if (!words.length) {
      return '';
    }

    if (words.length <= maxWords) {
      return words.join(' ');
    }

    return words.slice(0, maxWords).join(' ');
  }

  function renderExcerptBody(body) {
    if (!body || body.dataset.sitselPostContentMode !== 'excerpt') {
      return;
    }

    var source = String(body.dataset.sitselExcerptSource || '').trim();
    if (!source) {
      return;
    }

    var targetLength = getResponsiveExcerptLength(body.dataset);
    var renderedLength = parseInt(body.dataset.sitselRenderedExcerptLength, 10) || 0;
    var renderedSource = String(body.dataset.sitselRenderedExcerptSource || '');

    if (renderedLength === targetLength && renderedSource === source) {
      return;
    }

    var trimmed = trimWords(source, targetLength);
    var html = '';

    if (trimmed) {
      html = '<p>' + escapeHtml(trimmed)
        .replace(/\r\n|\r|\n{2,}/g, '</p><p>')
        .replace(/\n/g, '<br>') + '</p>';
    }

    body.innerHTML = html;
    body.dataset.sitselRenderedExcerptLength = String(targetLength);
    body.dataset.sitselRenderedExcerptSource = source;
  }

  function buildToc(root) {
    if (!root || root.dataset.enableToc !== 'yes') {
      return;
    }

    var headings = root.querySelectorAll('h1, h2, h3, h4, h5, h6');
    if (!headings.length) {
      return;
    }

    var box = root.closest('.sitsel-post-content-box');
    var toc = box ? box.querySelector('.sitsel-post-content-toc-list') : null;
    if (!toc) {
      return;
    }

    toc.innerHTML = '';
    headings.forEach(function (heading, index) {
      if (!heading.id) {
        var base = slugify(heading.textContent) || 'heading';
        heading.id = base + '-' + index;
      }

      var link = document.createElement('a');
      link.href = '#' + heading.id;
      link.textContent = heading.textContent || heading.tagName.toLowerCase();
      link.className = 'sitsel-post-content-toc-link';
      link.addEventListener('click', function (event) {
        event.preventDefault();
        var target = document.getElementById(heading.id);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      });

      toc.appendChild(link);
    });
  }

  function init() {
    document.querySelectorAll('.sitsel-post-content-body').forEach(function (body) {
      renderExcerptBody(body);
      buildToc(body);
    });
  }

  function scheduleRefresh() {
    window.clearTimeout(refreshTimer);
    refreshTimer = window.setTimeout(init, 80);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  window.addEventListener('resize', scheduleRefresh);
  window.addEventListener('orientationchange', scheduleRefresh);

  if (window.elementorFrontend && window.elementorFrontend.hooks) {
    window.elementorFrontend.hooks.addAction('frontend/element_ready/sitsel_post_content.default', init);
  }
})();
