(function () {
  let postsData = [];
  let currentLang = 'it';
  let activeTag = 'all';
  let langStrings = {};

  function init() {
    currentLang = document.documentElement.lang || 'it';
    if (currentLang === 'br') currentLang = 'pt';

    ensureLangLoaded(function () {
      const isSubdir =
        window.location.pathname.split('/').filter(Boolean).length > 1 &&
        !window.location.pathname.endsWith('/');
      const dataPath = isSubdir ? '../data/blog-posts.json' : 'data/blog-posts.json';

      fetch(dataPath + '?v=' + Date.now())
        .then(function (r) {
          if (!r.ok) throw new Error('Blog data not available');
          return r.json();
        })
        .then(function (data) {
          postsData = data.posts || [];
          onHashChange();
          window.addEventListener('hashchange', onHashChange);
        })
        .catch(function (err) {
          console.warn('Blog: could not load posts', err);
          var grid = document.getElementById('blog-posts-grid');
          if (grid) grid.innerHTML = '<p class="blog-empty">' + getUiString('noPosts') + '</p>';
        });
    });
  }

  function ensureLangLoaded(cb) {
    var cacheKey = 'lang_' + currentLang + '_v4';
    var cached = sessionStorage.getItem(cacheKey);
    if (cached) {
      try {
        var d = JSON.parse(cached);
        if (d.blog) {
          langStrings = d.blog;
          cb();
          return;
        }
      } catch (e) {}
    }

    var isSubdir =
      window.location.pathname.split('/').filter(Boolean).length > 1 &&
      !window.location.pathname.endsWith('/');
    var langPath = isSubdir ? '../lang/' : 'lang/';

    fetch(langPath + currentLang + '.json?v=' + Date.now())
      .then(function (r) { return r.json(); })
      .then(function (data) {
        try { sessionStorage.setItem(cacheKey, JSON.stringify(data)); } catch (e) {}
        if (data.blog) langStrings = data.blog;
        cb();
      })
      .catch(function () {
        cb();
      });
  }

  function onHashChange() {
    var hash = window.location.hash.replace('#', '');
    if (hash && postsData.length) {
      var post = findPost(hash);
      if (post) return renderDetail(post);
    }
    renderListing();
  }

  function findPost(slug) {
    for (var i = 0; i < postsData.length; i++) {
      if (postsData[i].id === slug) return postsData[i];
    }
    return null;
  }

  function getUiString(key) {
    return langStrings[key] || key;
  }

  function formatDate(dateStr) {
    var d = new Date(dateStr);
    var months = {
      it: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'],
      en: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      pt: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
      de: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
      fr: ['janv', 'févr', 'mars', 'avr', 'mai', 'juin', 'juil', 'août', 'sept', 'oct', 'nov', 'déc'],
      es: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'],
    };
    var m = months[currentLang] || months.it;
    var day = d.getDate();
    var mon = m[d.getMonth()];
    var year = d.getFullYear();
    if (currentLang === 'it' || currentLang === 'pt' || currentLang === 'de' || currentLang === 'fr' || currentLang === 'es') return day + ' ' + mon + ' ' + year;
    return mon + ' ' + day + ', ' + year;
  }

  function imgPath(post) {
    var isSubdir =
      window.location.pathname.split('/').filter(Boolean).length > 1 &&
      !window.location.pathname.endsWith('/');
    return isSubdir ? '../' + post.image : post.image;
  }

  function listingPageUrl() {
    var isSubdir =
      window.location.pathname.split('/').filter(Boolean).length > 1 &&
      !window.location.pathname.endsWith('/');
    return isSubdir ? 'blog.html' : 'blog.html';
  }

  function renderListing() {
    var listing = document.getElementById('blog-listing');
    var detail = document.getElementById('blog-detail');
    if (listing) listing.style.display = 'block';
    if (detail) detail.style.display = 'none';

    updateListingSEO();

    var grid = document.getElementById('blog-posts-grid');
    if (!grid) return;

    var filtered = postsData;
    if (activeTag !== 'all') {
      filtered = postsData.filter(function (p) {
        return p.tags.indexOf(activeTag) !== -1;
      });
    }

    if (!filtered.length) {
      grid.innerHTML = '<p class="blog-empty">' + getUiString('noPosts') + '</p>';
      renderTagFilters(postsData);
      return;
    }

    var html = '';
    for (var i = 0; i < filtered.length; i++) {
      var p = filtered[i];
      var tr = p.translations[currentLang] || p.translations.it;
      var alt =
        (p.imageAlt && p.imageAlt[currentLang]) ||
        (p.imageAlt && p.imageAlt.it) ||
        tr.title;

      var tagsHtml = '';
      if (p.tags && p.tags.length) {
        tagsHtml = '<div class="blog-card-tags">' +
          p.tags.slice(0, 3).map(function (t) { return '<span class="card-tag">' + escapeHtml(t) + '</span>'; }).join('') +
          '</div>';
      }

      html +=
        '<article class="blog-card reveal-on-scroll">' +
        '<a href="blog.html#' +
        p.id +
        '" class="blog-card-link">' +
        '<div class="blog-card-image">' +
        tagsHtml +
        '<img src="' +
        imgPath(p) +
        '" alt="' +
        escapeHtml(alt) +
        '" loading="lazy" width="400" height="225" onerror="this.style.display=\'none\';this.parentElement.classList.add(\'no-image\');">' +
        '</div>' +
        '<div class="blog-card-body">' +
        '<time datetime="' +
        p.date +
        '">' +
        formatDate(p.date) +
        '</time>' +
        '<h2>' +
        escapeHtml(tr.title) +
        '</h2>' +
        '<p>' +
        escapeHtml(tr.excerpt) +
        '</p>' +
        '<span class="read-more">' +
        getUiString('readMore') +
        '</span>' +
        '</div>' +
        '</a>' +
        '</article>';
    }
    grid.innerHTML = html;
    if (typeof window.initScrollReveal === 'function') window.initScrollReveal();
    renderTagFilters(postsData);
  }

  function renderTagFilters(allPosts) {
    var container = document.getElementById('blog-tags-filter');
    if (!container) return;
    var tags = [];
    for (var i = 0; i < allPosts.length; i++) {
      var ptags = allPosts[i].tags;
      for (var j = 0; j < ptags.length; j++) {
        if (tags.indexOf(ptags[j]) === -1) tags.push(ptags[j]);
      }
    }
    var headerLabels = { it: 'Filtra per Tema', en: 'Filter by Theme', pt: 'Filtrar por Tema', de: 'Nach Thema filtern', fr: 'Filtrer par thème', es: 'Filtrar por tema' };
    var headerText = headerLabels[currentLang] || 'Filtra per Tema';
    var html = '<div class="accordion-item">';
    html += '<div class="accordion-header" id="blog-tags-header">';
    html += '<h3>' + escapeHtml(headerText) + '</h3>';
    html += '<i class="fa-solid fa-tags"></i>';
    html += '</div>';
    html += '<div class="accordion-content">';
    html += '<button class="tag-btn' + (activeTag === 'all' ? ' active' : '') + '" data-tag="all">' + escapeHtml(getUiString('allTags')) + '</button>';
    for (var k = 0; k < tags.length; k++) {
      html += '<button class="tag-btn' + (activeTag === tags[k] ? ' active' : '') + '" data-tag="' + escapeHtml(tags[k]) + '">' + escapeHtml(tags[k]) + '</button>';
    }
    html += '</div></div>';
    container.innerHTML = html;

    var header = document.getElementById('blog-tags-header');
    if (header) {
      header.onclick = function () {
        this.parentElement.classList.toggle('active');
      };
    }

    var buttons = container.querySelectorAll('.tag-btn');
    for (var b = 0; b < buttons.length; b++) {
      buttons[b].addEventListener('click', function () {
        activeTag = this.getAttribute('data-tag');
        renderListing();
      });
    }
  }

  function renderDetail(post) {
    var listing = document.getElementById('blog-listing');
    var detail = document.getElementById('blog-detail');
    if (listing) listing.style.display = 'none';
    if (detail) detail.style.display = 'block';

    var tr = post.translations[currentLang] || post.translations.it;
    var alt =
      (post.imageAlt && post.imageAlt[currentLang]) ||
      (post.imageAlt && post.imageAlt.it) ||
      tr.title;

    document.title = tr.title + ' | Studio Karishma';

    var container = document.getElementById('blog-detail-content');
    var html =
      '<a href="' + listingPageUrl() + '" class="blog-back-link">&larr; ' +
      getUiString('back') +
      '</a>' +
      '<article class="blog-detail-article">' +
      '<h1>' +
      escapeHtml(tr.title) +
      '</h1>' +
      '<div class="blog-detail-meta">' +
      '<span>' +
      getUiString('publishedOn') +
      ' </span>' +
      '<time datetime="' +
      post.date +
      '">' +
      formatDate(post.date) +
      '</time>' +
      '<span> &mdash; Carlotta Crescini</span>' +
      '</div>' +
      '<div class="blog-detail-image">' +
      '<img src="' +
      imgPath(post) +
      '" alt="' +
      escapeHtml(alt) +
      '" width="800" height="450" onerror="this.style.display=\'none\';this.parentElement.classList.add(\'no-image\');">' +
      '</div>' +
      '<div class="blog-detail-body">' +
      tr.content +
      '</div>' +
      '</article>';

    container.innerHTML = html;
    window.scrollTo(0, 0);

    updateDetailSEO(post, tr);
  }

  function updateListingSEO() {
    var canonical = document.querySelector('link[rel="canonical"]');
    if (canonical) {
      var isSubdir =
        window.location.pathname.split('/').filter(Boolean).length > 1 &&
        !window.location.pathname.endsWith('/');
      canonical.href = isSubdir
        ? 'https://studiokarishma.it/' + currentLang + '/blog.html'
        : currentLang === 'it'
          ? 'https://studiokarishma.it/blog.html'
          : 'https://studiokarishma.it/' + currentLang + '/blog.html';
    }

    if (langStrings && langStrings.title) {
      document.title = langStrings.title;
    }
    var metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc && langStrings && langStrings.intro) {
      metaDesc.setAttribute('content', langStrings.intro);
    }
    var ogTitle = document.querySelector('meta[property="og:title"]');
    if (ogTitle && langStrings && langStrings.title) {
      ogTitle.setAttribute('content', langStrings.title);
    }
    var ogDesc = document.querySelector('meta[property="og:description"]');
    if (ogDesc && langStrings && langStrings.intro) {
      ogDesc.setAttribute('content', langStrings.intro);
    }

    injectBlogJSONLD();
  }

  function updateDetailSEO(post, tr) {
    var ld = {
      '@context': 'https://schema.org',
      '@type': 'BlogPosting',
      '@id': window.location.href,
      headline: tr.title,
      description: tr.excerpt,
      datePublished: post.date,
      author: { '@type': 'Person', name: 'Carlotta Crescini', '@id': 'https://studiokarishma.it/chi-sono.html#person' },
      image: 'https://studiokarishma.it/' + post.image,
      url: window.location.href,
      publisher: {
        '@type': 'Organization',
        name: 'Studio Karishma',
        '@id': 'https://studiokarishma.it/#business',
      },
    };
    var script = document.getElementById('blog-jsonld');
    if (script) script.textContent = JSON.stringify(ld);
  }

  function injectBlogJSONLD() {
    var blogPosts = [];
    for (var i = 0; i < postsData.length; i++) {
      var p = postsData[i];
      var tr = p.translations[currentLang] || p.translations.it;
      var isSubdir =
        window.location.pathname.split('/').filter(Boolean).length > 1 &&
        !window.location.pathname.endsWith('/');
      var langPath = currentLang === 'it' ? '' : currentLang + '/';
      blogPosts.push({
        '@type': 'BlogPosting',
        '@id': 'https://studiokarishma.it/' + langPath + 'blog.html#' + p.id,
        headline: tr.title,
        description: tr.excerpt,
        datePublished: p.date,
        author: { '@type': 'Person', name: 'Carlotta Crescini' },
        image: 'https://studiokarishma.it/' + p.image,
        url: 'https://studiokarishma.it/' + langPath + 'blog.html#' + p.id,
      });
    }

    var ld = {
      '@context': 'https://schema.org',
      '@graph': [
        {
          '@type': 'Blog',
          '@id': 'https://studiokarishma.it/blog.html#blog',
          name: 'Studio Karishma Blog',
          description: 'Riflessioni e approfondimenti sul benessere olistico.',
          url: 'https://studiokarishma.it/blog.html',
          author: {
            '@type': 'Person',
            name: 'Carlotta Crescini',
            '@id': 'https://studiokarishma.it/chi-sono.html#person',
          },
        },
      ].concat(blogPosts),
    };

    var script = document.getElementById('blog-jsonld');
    if (script) script.textContent = JSON.stringify(ld);
  }

  function escapeHtml(str) {
    if (!str) return '';
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

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