// @bun
var{defineProperty:W,getOwnPropertyNames:y,getOwnPropertyDescriptor:B}=Object,v=Object.prototype.hasOwnProperty;function E(j){return this[j]}var h=(j)=>{var k=(T??=new WeakMap).get(j),w;if(k)return k;if(k=W({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var q of y(j))if(!v.call(k,q))W(k,q,{get:E.bind(j,q),enumerable:!(w=B(j,q))||w.enumerable})}return T.set(j,k),k},T;var f=(j)=>j;function M(j,k){this[j]=f.bind(null,k)}var p=(j,k)=>{for(var w in k)W(j,w,{get:k[w],enumerable:!0,configurable:!0,set:M.bind(k,w)})};var I=(j,k)=>()=>(j&&(k=j(j=0)),k);var l=import.meta.require;import*as P from"crypto";function V(j){let k=/\$(\w+)\./g,w=[],q;while((q=k.exec(j))!==null)if(!w.includes(q[1]))w.push(q[1]);return w}function A(){return`stx-${P.randomBytes(4).toString("hex")}`}function x(j){return/\$\w+\./.test(j)}function N(j){let k=[],w=new Set,q=/<(\w+)([^>]*?)(\s*\/?>)/g,z=j;return z=z.replace(q,(C,F,Q,G)=>{if(["script","style","template"].includes(F.toLowerCase()))return C;let X=[],Y=!1,D=Q,H=/(\w+(?:-\w+)*)\s*=\s*"([^"]*\{\{[^}]*\$\w+[^}]*\}\}[^"]*)"/g,S=[...Q.matchAll(H)];for(let J of S){let O=J[0],K=J[1],_=J[2];if(x(_)){Y=!0;let $=_.match(/\{\{\s*([\s\S]+?)\s*\}\}/);if($){let L=$[1];if(X.push({attr:K,expr:L,fullMatch:O,originalAttr:K}),V(L).forEach((R)=>w.add(R)),K==="text")D=D.replace(O,"");else if(K==="class")D=D.replace(O,'class=""');else if(K==="disabled"||K==="hidden")D=D.replace(O,"");else D=D.replace(O,`${K}=""`)}}}if(!Y)return C;let Z=D.match(/\bid\s*=\s*"([^"]+)"/),U;if(Z)U=Z[1];else U=A(),D=` id="${U}"${D}`;for(let J of X)k.push({elementId:U,attribute:J.attr,expression:J.expr,stores:V(J.expr)});return`<${F}${D}${G}`}),{html:z,bindings:k,stores:w}}function u(j,k){if(j.length===0)return"";let w=Array.from(k),q=`
<script>
(function() {
  'use strict';

  // Wait for stores to be available
  function initBindings() {
    var stores = window.VoideStores;
    if (!stores) {
      setTimeout(initBindings, 10);
      return;
    }

    // Store references for expressions
    // eslint-disable-next-line pickier/no-unused-vars
    var $state = {};
`;for(let z of w)q+=`    $state.${z} = stores.${z} ? stores.${z}.get() : {};
`;q+=`
    // Binding update functions
    function updateBindings() {
`;for(let z of j){let{elementId:C,attribute:F,expression:Q}=z,G=Q.replace(/\$(\w+)\./g,"$state.$1.");if(F==="text")q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            el.textContent = ${G};
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`;else if(F==="html")q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            el.innerHTML = ${G};
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`;else if(F==="class")q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            var value = ${G};
            if (typeof value === 'string') {
              // Dynamic class string - merge with existing static classes
              // eslint-disable-next-line pickier/no-unused-vars
              var staticClasses = el.getAttribute('data-static-class') || el.className;
              if (!el.hasAttribute('data-static-class')) {
                el.setAttribute('data-static-class', el.className);
              }
              el.className = (el.getAttribute('data-static-class') + ' ' + value).trim();
            }
else if (typeof value === 'object') {
              // Object syntax: { 'class-name': condition }
              for (var cls in value) {
                if (value[cls]) {
                  el.classList.add(cls);
                }
else {
                  el.classList.remove(cls);
                }
              }
            }
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`;else if(F==="show")q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            el.style.display = (${G}) ? '' : 'none';
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`;else if(F==="if")q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            el.style.visibility = (${G}) ? 'visible' : 'hidden';
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`;else q+=`      (function() {
        var el = document.getElementById('${C}');
        if (el) {
          try {
            var value = ${G};
            if (value === false || value === null || value === undefined) {
              el.removeAttribute('${F}');
            }
else if (value === true) {
              el.setAttribute('${F}', '');
            }
else {
              el.setAttribute('${F}', value);
            }
          }
catch (e) { console.error('Binding error:', e); }
        }
      })();
`}q+=`    }

    // Subscribe to stores and update on changes. Capture the disposers so
    // SPA fragment swaps can tear down old bindings before the next page's
    // runtime takes over \u2014 without this, every navigation between pages
    // using reactive-bindings stacked another subscription on every store,
    // walking detached DOM forever. See stacksjs/stx#1709.
    var _disposers = [];
`;for(let z of w)q+=`    if (stores.${z}) {
      var _unsub_${z} = stores.${z}.subscribe(function(state) {
        $state.${z} = state;
        updateBindings();
      });
      // store.subscribe() may return the disposer (preferred) or void; both
      // are tolerated here.
      if (typeof _unsub_${z} === 'function') _disposers.push(_unsub_${z});
    }
`;return q+=`
    // Initial update
    updateBindings();

    // Register this runtime's cleanup so SPA navigation can run it before
    // swapping pages. The router (and any code) can call
    // window.__stxCleanupBindings() to dispose subscriptions; we also wire
    // 'popstate' and 'beforeunload' as a safety net for browser-driven nav.
    function _cleanup() {
      for (var i = 0; i < _disposers.length; i++) {
        try { _disposers[i](); } catch (e) { /* swallow */ }
      }
      _disposers.length = 0;
    }
    if (!window.__stxBindingsCleanups) window.__stxBindingsCleanups = [];
    window.__stxBindingsCleanups.push(_cleanup);
    if (!window.__stxCleanupBindings) {
      window.__stxCleanupBindings = function() {
        var fns = window.__stxBindingsCleanups || [];
        for (var i = 0; i < fns.length; i++) {
          try { fns[i](); } catch (e) { /* swallow */ }
        }
        window.__stxBindingsCleanups = [];
      };
      window.addEventListener('popstate', window.__stxCleanupBindings);
      window.addEventListener('beforeunload', window.__stxCleanupBindings);
    }
  }

  // Start when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initBindings);
  }
else {
    initBindings();
  }
})();
</script>
`,q}function m(j){let{html:k,bindings:w,stores:q}=N(j);if(w.length===0)return j;let z=u(w,q),C=k.lastIndexOf("</body>");if(C!==-1)return k.slice(0,C)+z+k.slice(C);return k+z}var g=()=>{};g();export{m as processTemplateBindings,N as processReactiveBindings,u as generateBindingsRuntime};
