// @bun
var{defineProperty:D,getOwnPropertyNames:L,getOwnPropertyDescriptor:M}=Object,N=Object.prototype.hasOwnProperty;function Q(j){return this[j]}var R=(j)=>{var q=(E??=new WeakMap).get(j),w;if(q)return q;if(q=D({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var v of L(j))if(!N.call(q,v))D(q,v,{get:Q.bind(j,v),enumerable:!(w=M(j,v))||w.enumerable})}return E.set(j,q),q},E;var T=(j)=>j;function U(j,q){this[j]=T.bind(null,q)}var W=(j,q)=>{for(var w in q)D(j,w,{get:q[w],enumerable:!0,configurable:!0,set:U.bind(q,w)})};var g=(j,q)=>()=>(j&&(q=j(j=0)),q);var V=import.meta.require;var P={};W(P,{renderSSRSuspense:()=>O,processSuspenseDirectives:()=>_,generateSuspenseRuntime:()=>C,generateSuspenseCSS:()=>x,createSSRSuspense:()=>H});function Z(){return`suspense-${++Y}-${Date.now().toString(36)}`}function _(j,q={},w){let v=/@suspense(?:\s*\(([^)]*)\))?\s*([\s\S]*?)@fallback\s*([\s\S]*?)@endsuspense/gi;return j.replace(v,(z,A,B,F)=>{let J=Z(),K=$(A||"");return G(J,B.trim(),F.trim(),K)})}function $(j){let q={},w=/(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|(\d+)|(\w+))/g,v;while((v=w.exec(j))!==null){let z=v[1],A=v[2]||v[3],B=v[4];switch(z){case"id":q.id=A;break;case"timeout":q.timeout=B?parseInt(B,10):void 0;break}}return q}function G(j,q,w,v){let z=v.timeout||30000,A=v.id||j;return`
<div class="stx-suspense" data-suspense-id="${j}" data-custom-id="${A}" data-status="pending">
  <div class="stx-suspense-fallback" data-suspense-fallback="${j}">
    ${w}
  </div>
  <div class="stx-suspense-content" data-suspense-content="${j}" style="display: none;">
    ${q}
  </div>
</div>
<script>
(function() {
  const suspenseId = '${j}';
  const customId = '${A}';
  const timeout = ${z};

  const container = document.querySelector('[data-suspense-id="' + suspenseId + '"]');
  const fallbackEl = document.querySelector('[data-suspense-fallback="' + suspenseId + '"]');
  const contentEl = document.querySelector('[data-suspense-content="' + suspenseId + '"]');

  if (!container || !fallbackEl || !contentEl) return;

  // State
  const pending = new Set();
  const resolved = new Set();
  let status = 'pending';
  let error = null;
  let timeoutTimer = null;

  // Update UI based on state
  function updateUI() {
    container.setAttribute('data-status', status);

    if (status === 'resolved') {
      fallbackEl.style.display = 'none';
      contentEl.style.display = '';
    }
else if (status === 'rejected') {
      fallbackEl.style.display = 'none';
      contentEl.style.display = '';
      // Show error in content area if needed
    }
else {
      fallbackEl.style.display = '';
      contentEl.style.display = 'none';
    }
  }

  // Check if all children are resolved
  function checkResolved() {
    if (pending.size === 0 && resolved.size > 0) {
      clearTimeout(timeoutTimer);
      status = 'resolved';
      updateUI();

      container.dispatchEvent(new CustomEvent('stx:suspense:resolved', {
        detail: { suspenseId: suspenseId, customId: customId },
        bubbles: true
      }));
    }
  }

  // Register an async child
  function register(childId) {
    if (status === 'resolved') {
      // Reset if we get a new child after resolution
      status = 'pending';
      updateUI();
    }
    pending.add(childId);

    // Start timeout on first registration
    if (pending.size === 1 && !timeoutTimer) {
      timeoutTimer = setTimeout(function() {
        if (status === 'pending') {
          error = new Error('Suspense timeout after ' + timeout + 'ms');
          status = 'rejected';
          updateUI();

          container.dispatchEvent(new CustomEvent('stx:suspense:timeout', {
            detail: { suspenseId: suspenseId, customId: customId, pending: Array.from(pending) },
            bubbles: true
          }));
        }
      }, timeout);
    }
  }

  // Resolve a child
  function resolve(childId) {
    pending.delete(childId);
    resolved.add(childId);
    checkResolved();
  }

  // Reject a child
  function reject(childId, err) {
    pending.delete(childId);
    error = err;
    status = 'rejected';
    clearTimeout(timeoutTimer);
    updateUI();

    container.dispatchEvent(new CustomEvent('stx:suspense:error', {
      detail: { suspenseId: suspenseId, customId: customId, error: err, childId: childId },
      bubbles: true
    }));
  }

  // Reset the boundary
  function reset() {
    pending.clear();
    resolved.clear();
    status = 'pending';
    error = null;
    clearTimeout(timeoutTimer);
    timeoutTimer = null;
    updateUI();
  }

  // Expose API globally for async components to use
  window.STX = window.STX || {};
  window.STX.suspense = window.STX.suspense || {
    boundaries: {},
    // Find the nearest suspense boundary for a child
    findBoundary: function(element) {
      const boundary = element.closest('[data-suspense-id]');
      if (boundary) {
        return boundary.getAttribute('data-suspense-id');
      }
      return null;
    },
    register: function(childId, boundaryId) {
      if (!boundaryId) {
        // Find nearest boundary
        const asyncEl = document.querySelector('[data-async-id="' + childId + '"]');
        if (asyncEl) {
          boundaryId = this.findBoundary(asyncEl);
        }
      }
      if (boundaryId && this.boundaries[boundaryId]) {
        this.boundaries[boundaryId].register(childId);
      }
    },
    resolve: function(childId, boundaryId) {
      if (!boundaryId) {
        const asyncEl = document.querySelector('[data-async-id="' + childId + '"]');
        if (asyncEl) {
          boundaryId = this.findBoundary(asyncEl);
        }
      }
      if (boundaryId && this.boundaries[boundaryId]) {
        this.boundaries[boundaryId].resolve(childId);
      }
    },
    reject: function(childId, error, boundaryId) {
      if (!boundaryId) {
        const asyncEl = document.querySelector('[data-async-id="' + childId + '"]');
        if (asyncEl) {
          boundaryId = this.findBoundary(asyncEl);
        }
      }
      if (boundaryId && this.boundaries[boundaryId]) {
        this.boundaries[boundaryId].reject(childId, error);
      }
    }
  };

  // Register this boundary
  window.STX.suspense.boundaries[suspenseId] = {
    id: suspenseId,
    customId: customId,
    getStatus: function() { return status; },
    getPending: function() { return Array.from(pending); },
    getResolved: function() { return Array.from(resolved); },
    getError: function() { return error; },
    register: register,
    resolve: resolve,
    reject: reject,
    reset: reset
  };

  // Initial state - if no async children register within a tick, show content
  setTimeout(function() {
    if (pending.size === 0 && resolved.size === 0) {
      status = 'resolved';
      updateUI();
    }
  }, 0);
})();
</script>
`}function H(j,q,w){return{id:j,fallback:w,content:q}}async function O(j){let q=j.map((v)=>`
<div id="stx-ssr-suspense-${v.id}" class="stx-ssr-suspense">
  ${v.fallback}
</div>
`).join(`
`);async function*w(){for(let v of j)try{let z=await v.content;yield`
<script>
(function() {
  const el = document.getElementById('stx-ssr-suspense-${v.id}');
  if (el) {
    el.innerHTML = ${JSON.stringify(z)};
    el.classList.add('stx-ssr-suspense-resolved');
  }
})();
</script>
`}catch(z){yield`
<script>
(function() {
  const el = document.getElementById('stx-ssr-suspense-${v.id}');
  if (el) {
    el.classList.add('stx-ssr-suspense-error');
    console.error('SSR Suspense error for ${v.id}:', ${JSON.stringify(String(z))});
  }
})();
</script>
`}}return{initial:q,streaming:w()}}function x(){return`
/* STX Suspense Styles */
.stx-suspense {
  position: relative;
}

.stx-suspense[data-status="pending"] .stx-suspense-fallback {
  display: block;
}

.stx-suspense[data-status="pending"] .stx-suspense-content {
  display: none;
}

.stx-suspense[data-status="resolved"] .stx-suspense-fallback {
  display: none;
}

.stx-suspense[data-status="resolved"] .stx-suspense-content {
  display: block;
}

/* SSR Suspense */
.stx-ssr-suspense {
  transition: opacity 0.3s ease;
}

.stx-ssr-suspense-resolved {
  animation: stx-suspense-fade-in 0.3s ease;
}

@keyframes stx-suspense-fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* Skeleton fallback helper */
.stx-suspense-skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: stx-suspense-shimmer 1.5s infinite;
  border-radius: 0.25rem;
}

@keyframes stx-suspense-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* Dark mode */
@media (prefers-color-scheme: dark) {
  .stx-suspense-skeleton {
    background: linear-gradient(90deg, #374151 25%, #4b5563 50%, #374151 75%);
    background-size: 200% 100%;
  }
}
`}function C(){return`
// STX Suspense Runtime
(function() {
  if (typeof window === 'undefined') return;

  window.STX = window.STX || {};

  // Suspense boundary management is set up per-boundary in the HTML
  // This just provides additional utilities

  window.STX.suspense = window.STX.suspense || {
    boundaries: {},
    findBoundary: function(element) {
      const boundary = element.closest('[data-suspense-id]');
      return boundary ? boundary.getAttribute('data-suspense-id') : null;
    },
    register: function(childId, boundaryId) {},
    resolve: function(childId, boundaryId) {},
    reject: function(childId, error, boundaryId) {}
  };

  // Wait for all suspense boundaries to resolve
  window.STX.suspense.waitForAll = function() {
    return new Promise(function(resolve, reject) {
      const boundaries = Object.values(window.STX.suspense.boundaries);
      if (boundaries.length === 0) {
        resolve();
        return;
      }

      let resolved = 0;
      let rejected = false;

      boundaries.forEach(function(boundary) {
        if (boundary.getStatus() === 'resolved') {
          resolved++;
          if (resolved === boundaries.length) resolve();
        }
else if (boundary.getStatus() === 'rejected') {
          if (!rejected) {
            rejected = true;
            reject(boundary.getError());
          }
        }
else {
          // Listen for resolution
          const container = document.querySelector('[data-suspense-id="' + boundary.id + '"]');
          if (container) {
            container.addEventListener('stx:suspense:resolved', function() {
              resolved++;
              if (resolved === boundaries.length && !rejected) resolve();
            }, { once: true });

            container.addEventListener('stx:suspense:error', function(e) {
              if (!rejected) {
                rejected = true;
                reject(e.detail.error);
              }
            }, { once: true });
          }
        }
      });
    });
  };

  console.log('[stx] Suspense runtime initialized');
})();
`}var Y=0;export{O as renderSSRSuspense,_ as processSuspenseDirectives,C as generateSuspenseRuntime,x as generateSuspenseCSS,H as createSSRSuspense};
