// @bun
var{defineProperty:P,getOwnPropertyNames:T,getOwnPropertyDescriptor:k}=Object,M=Object.prototype.hasOwnProperty;function R(O){return this[O]}var r=(O)=>{var j=(H??=new WeakMap).get(O),z;if(j)return j;if(j=P({},"__esModule",{value:!0}),O&&typeof O==="object"||typeof O==="function"){for(var J of T(O))if(!M.call(j,J))P(j,J,{get:R.bind(O,J),enumerable:!(z=k(O,J))||z.enumerable})}return H.set(O,j),j},H;var I=(O)=>O;function C(O,j){this[O]=I.bind(null,j)}var c=(O,j)=>{for(var z in j)P(O,z,{get:j[z],enumerable:!0,configurable:!0,set:C.bind(j,z)})};var a=(O,j)=>()=>(O&&(j=O(O=0)),j);var s=import.meta.require;function w(O,j=""){let z=`${O}${j}`,J=0;for(let L=0;L<z.length;L++){let U=z.charCodeAt(L);J=(J<<5)-J+U,J=J&J}return`stx-${Math.abs(J).toString(36)}`}function f(O,j,z={}){let{prefix:J="",preserveHost:L=!0,scopeKeyframes:U=!0,scopeCustomProperties:W=!1}=z;if(!O.trim())return"";let Q=D(O),E=[],Z=new Map;if(U)for(let X of Q){let _=X.selector.match(/@keyframes\s+([a-z_-][a-z0-9_-]*)/i);if(_){let $=_[1],F=`${j}_${$}`;Z.set($,F)}}for(let X of Q){let _=x(X,j,J,L,Z,W);E.push(_)}return E.join(`

`)}function D(O){let j=[],z=O.replace(/\/\*[\s\S]*?\*\//g,""),J=0,L="",U=!1,W="";for(let Q=0;Q<z.length;Q++){let E=z[Q];if(E==="@"&&J===0)U=!0;if(E==="{")J++;else if(E==="}"){if(J--,J===0){if(U){W+=E;let Z=W.match(/@([a-z-]+)\s*([^{]*)\{([\s\S]*)\}/i);if(Z){let[,X,_,$]=Z;if(X==="keyframes")j.push({selector:`@keyframes ${_.trim()}`,declarations:$.trim()});else if(X==="media"||X==="supports"||X==="container"){let F=D($);j.push({selector:`@${X} ${_.trim()}`,declarations:F.map((G)=>`${G.selector} { ${G.declarations} }`).join(`
`)})}else j.push({selector:`@${X} ${_.trim()}`,declarations:$.trim()})}W="",U=!1}else if(L.trim()){L+=E;let Z=L.match(/([^{]+)\{([^}]*)\}/);if(Z)j.push({selector:Z[1].trim(),declarations:Z[2].trim()});L=""}continue}}if(U)W+=E;else L+=E}return j}function x(O,j,z,J,L,U){let{selector:W,declarations:Q}=O;if(W.startsWith("@")){if(W.startsWith("@keyframes")){let X=W.replace("@keyframes ","").trim();return`@keyframes ${L.get(X)||X} { ${Q} }`}if(W.startsWith("@media")||W.startsWith("@supports")||W.startsWith("@container")){let _=D(`x { ${Q} }`.replace(/x \{ /,"").replace(/ \}$/,"")).map(($)=>x($,j,z,J,L,U)).join(`
  `);return`${W} {
  ${_}
}`}return`${W} { ${Q} }`}let E=y(W,j,z,J),Z=Q;for(let[X,_]of L)Z=Z.replace(new RegExp(`\\b${X}\\b`,"g"),_);if(U)Z=Z.replace(/--([a-z-]+)/gi,`--${j}-$1`);return`${E} { ${Z} }`}function y(O,j,z,J){let L=O.split(",").map((W)=>W.trim()),U=[];for(let W of L){if(W.startsWith(":host")){if(J)U.push(W);else{let E=W.replace(/:host(\([^)]*\))?/,`.${j}$1`);U.push(E)}continue}if(W.includes("::slotted")){U.push(W);continue}if(W===":root"){U.push(`:root .${j}`);continue}let Q=z?`${z} .${j}`:`.${j}`;U.push(`${Q} ${W}`)}return U.join(", ")}function h(O){let j=O.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i),z=j?j[1]:"",J=j?O.replace(/<style\b[^>]*>[\s\S]*?<\/style>/i,""):O;return{css:z,templateWithoutStyle:J}}function i(O,j,z="head"){if(!j.trim())return O;let J=`<style data-stx-scoped>
${j}
</style>`;switch(z){case"head":if(O.includes("</head>"))return O.replace("</head>",`${J}
</head>`);return J+O;case"body-start":if(O.includes("<body"))return O.replace(/(<body[^>]*>)/,`$1
${J}`);return J+O;case"body-end":{let L=O.lastIndexOf("</body>");if(L!==-1)return O.slice(0,L)+J+`
`+O.slice(L);return O+J}default:return O}}function u(O){return O.trim()}function K(){return`
/**
 * Reactive mixin for stx web components
 * Adds reactive state management to custom elements
 */
function StxReactive(Base) {
  return class extends Base {
    #state = {};
    #watchers = new Map();
    #computed = new Map();
    #dirty = new Set();
    #updateScheduled = false;

    constructor() {
      super();
      this.#initializeState();
    }

    #initializeState() {
      // Initialize reactive properties from static definition
      const props = this.constructor.reactiveProperties || {};
      for (const [name, config] of Object.entries(props)) {
        this.#state[name] = config.default;
        this.#defineProperty(name, config);
      }
    }

    #defineProperty(name, config) {
      Object.defineProperty(this, name, {
        get: () => this.#state[name],
        set: (value) => {
          const oldValue = this.#state[name];
          if (oldValue !== value) {
            this.#state[name] = value;
            this.#markDirty(name);
            this.#notifyWatchers(name, value, oldValue);
            if (config.reflect) {
              this.#reflectAttribute(name, value);
            }
          }
        },
        enumerable: true,
        configurable: true
      });
    }

    #reflectAttribute(name, value) {
      const attrName = name.replace(/([A-Z])/g, '-$1').toLowerCase();
      if (value === null || value === undefined || value === false) {
        this.removeAttribute(attrName);
      }
else if (value === true) {
        this.setAttribute(attrName, '');
      }
else {
        this.setAttribute(attrName, String(value));
      }
    }

    #markDirty(name) {
      this.#dirty.add(name);
      this.#scheduleUpdate();
    }

    #scheduleUpdate() {
      if (!this.#updateScheduled) {
        this.#updateScheduled = true;
        queueMicrotask(() => {
          this.#updateScheduled = false;
          this.#performUpdate();
        });
      }
    }

    #performUpdate() {
      // Recompute computed properties that depend on dirty state
      for (const [name, { deps, getter }] of this.#computed) {
        if (deps.some(dep => this.#dirty.has(dep))) {
          this.#state[name] = getter.call(this);
        }
      }

      // Clear dirty set and trigger re-render
      this.#dirty.clear();
      if (typeof this.render === 'function') {
        this.render();
      }
    }

    #notifyWatchers(name, newValue, oldValue) {
      const handlers = this.#watchers.get(name) || [];
      for (const handler of handlers) {
        try {
          handler.call(this, newValue, oldValue);
        }
catch (e) {
          console.error(\`Watcher error for "\${name}":\`, e);
        }
      }
    }

    $watch(property, handler, options = {}) {
      if (!this.#watchers.has(property)) {
        this.#watchers.set(property, []);
      }
      this.#watchers.get(property).push(handler);

      if (options.immediate) {
        handler.call(this, this.#state[property], undefined);
      }

      // Return unwatch function
      return () => {
        const handlers = this.#watchers.get(property);
        const index = handlers.indexOf(handler);
        if (index > -1) {
          handlers.splice(index, 1);
        }
      };
    }

    $computed(name, deps, getter) {
      this.#computed.set(name, { deps, getter });
      Object.defineProperty(this, name, {
        get: () => {
          if (!(name in this.#state)) {
            this.#state[name] = getter.call(this);
          }
          return this.#state[name];
        },
        enumerable: true,
        configurable: true
      });
    }

    $set(property, value) {
      this[property] = value;
    }

    $batch(fn) {
      // Temporarily disable updates during batch
      const prevScheduled = this.#updateScheduled;
      this.#updateScheduled = true;
      try {
        fn();
      }
finally {
        this.#updateScheduled = prevScheduled;
        if (!prevScheduled) {
          this.#scheduleUpdate();
        }
      }
    }
  };
}
`}function d(O,j,z={}){let{properties:J=[],computed:L=[],watchers:U=[],methods:W={},lifecycle:Q={}}=z,E=O.name,Z=O.tag,X=O.shadowDOM!==!1,_=J.map((Y)=>{let q=Y.default!==void 0?JSON.stringify(Y.default):S(Y.type);return`    ${Y.name}: { type: '${Y.type}', default: ${q}, reflect: ${!!Y.reflect} }`}).join(`,
`),$=L.map((Y)=>{let q=JSON.stringify(Y.dependencies);return`    this.$computed('${Y.name}', ${q}, ${Y.getter});`}).join(`
`),F=U.map((Y)=>{let q=Y.immediate||Y.deep?`, { immediate: ${!!Y.immediate}, deep: ${!!Y.deep} }`:"";return`    this.$watch('${Y.property}', ${Y.handler}${q});`}).join(`
`),G=Object.entries(W).map(([Y,q])=>`  ${Y}${q}`).join(`

`),V=Q.connected||"",b=Q.disconnected||"",B=Q.adopted||"",g=Q.attributeChanged||"",A=j.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$");return`
${K()}

class ${E} extends StxReactive(HTMLElement) {
  static reactiveProperties = {
${_}
  };

  static get observedAttributes() {
    return ${JSON.stringify(O.attributes||[])};
  }

  #shadowRoot;

  constructor() {
    super();
    ${X?"this.#shadowRoot = this.attachShadow({ mode: 'open' });":""}
    this.#setupComputed();
    this.#setupWatchers();
  }

  #setupComputed() {
${$}
  }

  #setupWatchers() {
${F}
  }

  connectedCallback() {
    this.render();
    ${V}
  }

  disconnectedCallback() {
    ${b}
  }

  adoptedCallback() {
    ${B}
  }

  attributeChangedCallback(name, oldValue, newValue) {
    // Convert attribute name to property name (kebab-case to camelCase)
    const propName = name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());

    // Get the property type
    const propConfig = ${E}.reactiveProperties[propName];
    if (propConfig) {
      let value = newValue;

      // Convert based on type
      switch (propConfig.type) {
        case 'number':
          value = newValue !== null ? Number(newValue) : propConfig.default;
          break;
        case 'boolean':
          value = newValue !== null;
          break;
        case 'object':
        case 'array':
          try {
            value = newValue !== null ? JSON.parse(newValue) : propConfig.default;
          }
catch (e) {
            value = propConfig.default;
          }
          break;
      }

      this[propName] = value;
    }

    ${g}
  }

  render() {
    const root = ${X?"this.#shadowRoot":"this"};
    root.innerHTML = this.#template();
  }

  #template() {
    return \`${A}\`;
  }

${G}
}

customElements.define('${Z}', ${E});

export { ${E} };
`}function m(O,j,z={}){let{properties:J=[],computed:L=[],watchers:U=[],methods:W={},lifecycle:Q={}}=z,E=O.name,Z=O.tag,X=O.shadowDOM!==!1,_=J.map((q)=>{let v=n(q.type);return`  ${q.name}: ${v};`}).join(`
`),$=J.map((q)=>{let v=q.default!==void 0?JSON.stringify(q.default):S(q.type);return`    ${q.name}: { type: '${q.type}' as const, default: ${v}, reflect: ${!!q.reflect} }`}).join(`,
`),F=L.map((q)=>{let v=JSON.stringify(q.dependencies);return`    this.$computed('${q.name}', ${v}, ${q.getter});`}).join(`
`),G=U.map((q)=>{let v=q.immediate||q.deep?`, { immediate: ${!!q.immediate}, deep: ${!!q.deep} }`:"";return`    this.$watch('${q.property}', ${q.handler}${v});`}).join(`
`),V=Object.entries(W).map(([q,v])=>`  ${q}${v}`).join(`

`),b=Q.connected||"",B=Q.disconnected||"",g=Q.adopted||"",A=Q.attributeChanged||"",Y=j.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$");return`
interface ${E}Props {
${_}
}

interface ReactivePropertyConfig {
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  default: unknown;
  reflect: boolean;
}

interface ReactiveElement extends HTMLElement {
  $watch(property: string, handler: (newVal: unknown, oldVal: unknown) => void, options?: { immediate?: boolean; deep?: boolean }): () => void;
  $computed(name: string, deps: string[], getter: () => unknown): void;
  $set(property: string, value: unknown): void;
  $batch(fn: () => void): void;
}

${K()}

class ${E} extends StxReactive(HTMLElement) implements ReactiveElement {
  static reactiveProperties: Record<string, ReactivePropertyConfig> = {
${$}
  };

  static get observedAttributes(): string[] {
    return ${JSON.stringify(O.attributes||[])};
  }

  #shadowRoot: ShadowRoot | null = null;

  constructor() {
    super();
    ${X?"this.#shadowRoot = this.attachShadow({ mode: 'open' });":""}
    this.#setupComputed();
    this.#setupWatchers();
  }

  #setupComputed(): void {
${F}
  }

  #setupWatchers(): void {
${G}
  }

  connectedCallback(): void {
    this.render();
    ${b}
  }

  disconnectedCallback(): void {
    ${B}
  }

  adoptedCallback(): void {
    ${g}
  }

  attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {
    const propName = name.replace(/-([a-z])/g, (_: string, c: string) => c.toUpperCase());

    const propConfig = ${E}.reactiveProperties[propName];
    if (propConfig) {
      let value: unknown = newValue;

      switch (propConfig.type) {
        case 'number':
          value = newValue !== null ? Number(newValue) : propConfig.default;
          break;
        case 'boolean':
          value = newValue !== null;
          break;
        case 'object':
        case 'array':
          try {
            value = newValue !== null ? JSON.parse(newValue) : propConfig.default;
          }
catch {
            value = propConfig.default;
          }
          break;
      }

      (this as Record<string, unknown>)[propName] = value;
    }

    ${A}
  }

  render(): void {
    const root = ${X?"this.#shadowRoot":"this"};
    if (root) {
      root.innerHTML = this.#template();
    }
  }

  #template(): string {
    return \`${Y}\`;
  }

${V}
}

customElements.define('${Z}', ${E});

export { ${E} };
export type { ${E}Props };
`}function S(O){switch(O){case"string":return"''";case"number":return"0";case"boolean":return"false";case"array":return"[]";case"object":return"{}";default:return"undefined"}}function n(O){switch(O){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"unknown"}}function l(){return`
(function() {
  'use strict';

  // StxReactive mixin for dynamic component creation
  window.StxReactive = ${K().replace(/\n/g," ").replace(/\s+/g," ")};

  // Helper to create reactive components dynamically
  window.createReactiveComponent = function(tag, config) {
    const { properties = {}, template, methods = {}, lifecycle = {} } = config;

    class DynamicComponent extends StxReactive(HTMLElement) {
      static reactiveProperties = properties;
      static get observedAttributes() {
        return Object.keys(properties).map(p =>
          p.replace(/([A-Z])/g, '-$1').toLowerCase()
        );
      }

      constructor() {
        super();
        if (config.shadow !== false) {
          this.attachShadow({ mode: 'open' });
        }
      }

      connectedCallback() {
        this.render();
        if (lifecycle.connected) lifecycle.connected.call(this);
      }

      disconnectedCallback() {
        if (lifecycle.disconnected) lifecycle.disconnected.call(this);
      }

      render() {
        const root = this.shadowRoot || this;
        root.innerHTML = typeof template === 'function'
          ? template.call(this)
          : template;
      }
    }

    // Add methods
    Object.entries(methods).forEach(([name, fn]) => {
      DynamicComponent.prototype[name] = fn;
    });

    customElements.define(tag, DynamicComponent);
    return DynamicComponent;
  };
})();
`}export{f as scopeCss,i as injectScopedCss,u as generateShadowDomCss,l as generateReactiveRuntime,K as generateReactiveMixin,m as generateReactiveComponentTS,d as generateReactiveComponentJS,w as generateComponentId,h as extractStyleFromTemplate};
