(() => {
  'use strict';
  const cfg = window.SHCDSiteSPA || {};
  if (!cfg.enabled || !window.fetch || !window.DOMParser) return;

  const cache = new Map();
  const pending = new Map();
  let controller = null;

  const sameOrigin = (url) => {
    try { return new URL(url, window.location.href).origin === window.location.origin; } catch (_) { return false; }
  };

  const normalize = (url) => {
    try { return new URL(url, window.location.href); } catch (_) { return null; }
  };

  const contentRoot = () => document.getElementById('shabnam-spa-content');

  const isExcluded = (url, link) => {
    if (!url || url.origin !== window.location.origin) return true;
    if (link && (link.target === '_blank' || link.hasAttribute('download') || link.dataset.noSpa === 'true')) return true;
    if (url.hash && url.pathname === window.location.pathname && url.search === window.location.search) return true;
    if (/\.(?:zip|pdf|jpe?g|png|gif|webp|svg|mp4|mp3|woff2?|ttf)$/i.test(url.pathname)) return true;
    if (url.pathname.indexOf('/wp-admin/') !== -1 || url.pathname.indexOf('/wp-login.php') !== -1) return true;
    if (url.searchParams.has('action') && ['logout', 'lostpassword', 'postpass'].includes(url.searchParams.get('action'))) return true;
    if (url.searchParams.has('_wpnonce') || url.searchParams.has('download_file')) return true;
    if (link && (link.closest('[data-uc-toggle]') || link.closest('.remove_from_cart_button') || link.classList.contains('add_to_cart_button'))) return true;
    return false;
  };

  const parsePage = (html, url) => {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    const root = doc.getElementById('shabnam-spa-content');
    if (!root) throw new Error('spa-root-missing');
    const description = doc.querySelector('meta[name="description"]');
    const robots = doc.querySelector('meta[name="robots"]');
    const canonical = doc.querySelector('link[rel="canonical"]');
    const adminEdit = doc.querySelector('#wp-admin-bar-edit a');
    const adminElementor = doc.querySelector('#wp-admin-bar-elementor_edit_page a');
    return {
      url,
      title: doc.title || document.title,
      html: root.innerHTML,
      bodyClass: doc.body ? doc.body.className : '',
      head: {
        description: description ? description.getAttribute('content') || '' : '',
        robots: robots ? robots.getAttribute('content') || '' : '',
        canonical: canonical ? canonical.href || '' : '',
        adminEdit: adminEdit ? { href: adminEdit.href || '', text: adminEdit.textContent || '' } : null,
        adminElementor: adminElementor ? { href: adminElementor.href || '', text: adminElementor.textContent || '' } : null
      },
      styles: Array.from(doc.querySelectorAll('link[rel="stylesheet"][href]')).map((node) => node.href),
      scripts: Array.from(doc.querySelectorAll('script')).map((node) => ({
        src: node.src || '',
        id: node.id || '',
        type: node.type || 'text/javascript',
        text: node.src ? '' : (node.textContent || '')
      }))
    };
  };

  const fetchPage = (url, prefetch = false) => {
    const key = url.href;
    if (cache.has(key)) return Promise.resolve(cache.get(key));
    if (pending.has(key)) return pending.get(key);
    const localController = typeof AbortController !== 'undefined' ? new AbortController() : null;
    if (!prefetch && controller && controller.abort) controller.abort();
    if (!prefetch) controller = localController;
    const promise = fetch(url.href, {
      credentials: 'same-origin',
      headers: { 'X-SHCD-SPA': '1', 'X-Requested-With': 'fetch' },
      signal: localController ? localController.signal : undefined
    }).then((response) => {
      if (!response.ok) throw new Error(`http-${response.status}`);
      return response.text();
    }).then((html) => parsePage(html, url.href)).then((page) => {
      cache.set(key, page);
      return page;
    }).finally(() => {
      pending.delete(key);
      if (!prefetch && controller === localController) controller = null;
    });
    pending.set(key, promise);
    return promise;
  };

  const ensureStyles = async (urls) => {
    const existing = new Set(Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).map((n) => n.href));
    const missing = urls.filter((url) => sameOrigin(url) && !existing.has(url));
    await Promise.all(missing.map((url) => new Promise((resolve) => {
      const link = document.createElement('link');
      link.rel = 'stylesheet'; link.href = url; link.onload = resolve; link.onerror = resolve;
      document.head.appendChild(link);
    })));
  };

  const syncScripts = async (descriptors) => {
    const existingSrc = new Set(Array.from(document.querySelectorAll('script[src]')).map((n) => n.src));
    for (const item of descriptors || []) {
      const type = String(item.type || 'text/javascript').toLowerCase();
      if (type && !['text/javascript', 'application/javascript', 'module'].includes(type)) continue;

      if (item.src) {
        if (!sameOrigin(item.src) || existingSrc.has(item.src)) continue;
        await new Promise((resolve) => {
          const script = document.createElement('script');
          script.src = item.src;
          if (type === 'module') script.type = 'module';
          script.async = false;
          script.onload = resolve;
          script.onerror = resolve;
          document.body.appendChild(script);
        });
        existingSrc.add(item.src);
        continue;
      }

      // WordPress uses these inline blocks for localized variables and code
      // that must precede/follow a registered script. Re-run only those
      // explicit blocks; arbitrary editor content scripts are not executed.
      if (item.text && item.id && /-(?:js-extra|js-before|js-after)$/.test(item.id)) {
        try {
          const script = document.createElement('script');
          script.text = item.text;
          document.body.appendChild(script);
          script.remove();
        } catch (_) {
          // A failed enhancement must never strand navigation.
        }
      }
    }
  };

  const syncHead = (page) => {
    const head = page.head || {};
    const setMeta = (name, content) => {
      let node = document.querySelector(`meta[name="${name}"]`);
      if (!content) return;
      if (!node) {
        node = document.createElement('meta');
        node.name = name;
        document.head.appendChild(node);
      }
      node.setAttribute('content', content);
    };
    setMeta('description', head.description);
    setMeta('robots', head.robots);
    if (head.canonical) {
      let canonical = document.querySelector('link[rel="canonical"]');
      if (!canonical) {
        canonical = document.createElement('link');
        canonical.rel = 'canonical';
        document.head.appendChild(canonical);
      }
      canonical.href = head.canonical;
    }
    const syncAdminLink = (selector, info) => {
      const link = document.querySelector(selector);
      if (!link || !info) return;
      if (info.href) link.href = info.href;
      if (info.text) link.textContent = info.text;
    };
    syncAdminLink('#wp-admin-bar-edit a', head.adminEdit);
    syncAdminLink('#wp-admin-bar-elementor_edit_page a', head.adminElementor);
  };

  const syncHeaderActiveLink = (url) => {
    const target = normalize(url);
    if (!target) return;
    document.querySelectorAll('.uc-header .uc-navbar-nav a[href], #uc-menu-panel a[href]').forEach((link) => {
      const item = link.closest('li');
      if (!item) return;
      const linkUrl = normalize(link.href);
      const active = Boolean(linkUrl && linkUrl.origin === target.origin && linkUrl.pathname.replace(/\/+$/, '') === target.pathname.replace(/\/+$/, ''));
      item.classList.toggle('current-menu-item', active);
      item.classList.toggle('current_page_item', active);
      if (active) link.setAttribute('aria-current', 'page');
      else link.removeAttribute('aria-current');
    });
  };

  const updateBodyClass = (className) => {
    const preserve = ['admin-bar', 'logged-in', 'shabnam-site-spa-enabled'];
    const next = new Set(String(className || '').split(/\s+/).filter(Boolean));
    preserve.forEach((name) => { if (document.body.classList.contains(name)) next.add(name); });
    document.body.className = Array.from(next).join(' ');
  };

  const afterSwap = (url) => {
    document.dispatchEvent(new CustomEvent('shcd:spa:navigated', { detail: { url } }));
    if (window.jQuery) {
      window.jQuery(document.body).trigger('shcd_spa_navigated', [url]);
      window.jQuery(document.body).trigger('wc_fragment_refresh');
    }
    if (window.elementorFrontend && window.elementorFrontend.elementsHandler && typeof window.elementorFrontend.elementsHandler.runReadyTrigger === 'function') {
      document.querySelectorAll('#shabnam-spa-content .elementor-element').forEach((element) => {
        try { window.elementorFrontend.elementsHandler.runReadyTrigger(element); } catch (_) {}
      });
    }
    if (window.UIkit && typeof window.UIkit.update === 'function') {
      try { window.UIkit.update(document.getElementById('shabnam-spa-content')); } catch (_) {}
    }
    // Re-run lightweight browser-native lazy behavior and reading progress.
    if (typeof window.SHCDReadingProgressInit === 'function') window.SHCDReadingProgressInit();
  };

  const swap = async (page, push = true) => {
    const root = contentRoot();
    if (!root) { window.location.href = page.url; return; }
    await ensureStyles(page.styles);
    const perform = () => {
      root.innerHTML = page.html;
      document.title = page.title;
      syncHead(page);
      syncHeaderActiveLink(page.url);
      updateBodyClass(page.bodyClass);
      if (push) window.history.pushState({ shcdSpa: true }, '', page.url);
      root.classList.remove('shabnam-spa-enter');
      void root.offsetWidth;
      root.classList.add('shabnam-spa-enter');
      const targetUrl = normalize(page.url);
      const hash = targetUrl ? targetUrl.hash : '';
      if (hash) {
        const anchor = document.getElementById(decodeURIComponent(hash.slice(1)));
        if (anchor) anchor.scrollIntoView({ block: 'start', behavior: 'auto' });
        else window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
      } else {
        window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
      }
    };
    if (document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      const transition = document.startViewTransition(perform);
      try { await transition.updateCallbackDone; } catch (_) {}
    } else {
      perform();
    }
    await syncScripts(page.scripts);
    afterSwap(page.url);
  };

  const navigate = (url, push = true) => {
    const target = normalize(url);
    if (!target || isExcluded(target)) { window.location.href = url; return; }
    const root = contentRoot();
    if (root) root.setAttribute('aria-busy', 'true');
    // No loader/blank state: old content remains visible until the next page is ready.
    fetchPage(target, false).then((page) => swap(page, push)).catch((error) => {
      if (error && error.name === 'AbortError') return;
      window.location.href = target.href;
    }).finally(() => { if (root) root.removeAttribute('aria-busy'); });
  };

  document.addEventListener('click', (event) => {
    if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
    const link = event.target.closest('a[href]');
    if (!link) return;
    const url = normalize(link.href);
    if (isExcluded(url, link)) return;
    event.preventDefault();
    navigate(url.href, true);
  });

  const prefetch = (link) => {
    if (!link || link.dataset.shcdSitePrefetched === '1') return;
    const url = normalize(link.href);
    if (isExcluded(url, link)) return;
    fetchPage(url, true).then(() => { link.dataset.shcdSitePrefetched = '1'; }).catch(() => {});
  };
  document.addEventListener('pointerenter', (event) => { const link = event.target.closest && event.target.closest('a[href]'); if (link) prefetch(link); }, true);
  document.addEventListener('focusin', (event) => { const link = event.target.closest && event.target.closest('a[href]'); if (link) prefetch(link); });

  document.addEventListener('submit', (event) => {
    const form = event.target;
    if (!(form instanceof HTMLFormElement)) return;
    const method = String(form.method || 'get').toLowerCase();
    if (method !== 'get' || form.dataset.noSpa === 'true') return;
    const action = normalize(form.action || window.location.href);
    if (!action || isExcluded(action)) return;
    event.preventDefault();
    const params = new URLSearchParams(new FormData(form));
    action.search = params.toString();
    navigate(action.href, true);
  });

  window.addEventListener('popstate', () => navigate(window.location.href, false));

  // Cache current page immediately.
  const currentRoot = contentRoot();
  if (currentRoot) {
    cache.set(window.location.href, {
      url: window.location.href,
      title: document.title,
      html: currentRoot.innerHTML,
      bodyClass: document.body.className,
      head: {
        description: document.querySelector('meta[name="description"]')?.getAttribute('content') || '',
        robots: document.querySelector('meta[name="robots"]')?.getAttribute('content') || '',
        canonical: document.querySelector('link[rel="canonical"]')?.href || '',
        adminEdit: null,
        adminElementor: null
      },
      styles: [], scripts: []
    });
  }
})();

(() => {
  'use strict';
  const init = () => {
    const bar = document.querySelector('[data-shcd-reading-progress]');
    if (!bar) return;
    const update = () => {
      const article = document.querySelector('.shabnam-single-post article');
      if (!article) { bar.style.setProperty('--shcd-reading-progress', '0%'); return; }
      const rect = article.getBoundingClientRect();
      const top = window.scrollY + rect.top;
      const height = Math.max(1, article.offsetHeight - window.innerHeight);
      const current = Math.max(0, Math.min(height, window.scrollY - top + 100));
      bar.style.setProperty('--shcd-reading-progress', `${Math.min(100, (current / height) * 100)}%`);
    };
    if (window.SHCDReadingProgressCleanup) window.SHCDReadingProgressCleanup();
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => { update(); ticking = false; });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    window.SHCDReadingProgressCleanup = () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
    update();
  };
  window.SHCDReadingProgressInit = init;
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, { once: true });
  else init();
  document.addEventListener('shcd:spa:navigated', init);
})();
