var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var elementDefine_exports = {};
__export(elementDefine_exports, {
  ELEMENT_CONFIG_KEY: () => ELEMENT_CONFIG_KEY,
  STATE_CHANGE_EVENT: () => STATE_CHANGE_EVENT,
  elementDefine: () => elementDefine,
  getElementConfig: () => getElementConfig
});
module.exports = __toCommonJS(elementDefine_exports);
var import_ReflectUtils = require("@dooboostore/core/reflect/ReflectUtils");
var import_innerHtml = require("./innerHtml");
var import_query = require("./query");
var import_queryAll = require("./queryAll");
var import_addEventListener = require("./addEventListener");
var import_lifecycles = require("./lifecycles");
var import_attribute = require("./attribute");
var import_state = require("./state");
var import_emitCustomEvent = require("./emitCustomEvent");
var import_Utils = require("../utils/Utils");
var import_config = require("../config/config");
const ELEMENT_CONFIG_KEY = Symbol("simple-web-component:element-config");
const STATE_CHANGE_EVENT = "swc:state-change";
function buildEnv(configWindow) {
  const win = configWindow || (typeof window !== "undefined" ? window : void 0);
  const doc = win?.document;
  const builtInTagMap = /* @__PURE__ */ new Map();
  for (const [cls, tag] of import_config.HTML_TAG_ENTRIES) {
    if (win?.[cls]) builtInTagMap.set(win[cls], tag);
  }
  const domHelpers = {
    $d: doc,
    $w: win,
    $q: (sel, root) => (root ?? doc).querySelector(sel),
    $qa: (sel, root) => Array.from((root ?? doc).querySelectorAll(sel)),
    $qi: (id, root) => (root ?? doc).getElementById(id)
  };
  return { win, doc, builtInTagMap, domHelpers };
}
const elementDefine = (inConfig) => (constructor) => {
  const config = typeof inConfig === "string" ? { name: inConfig } : inConfig;
  const { win, doc, builtInTagMap: BUILT_IN_TAG_MAP, domHelpers: SWC_DOM_HELPERS } = buildEnv(config.window);
  config.window = win;
  const SWC_DOM_HELPER_KEYS = Object.keys(SWC_DOM_HELPERS);
  const SWC_DOM_HELPER_VALS = () => SWC_DOM_HELPER_KEYS.map((k) => SWC_DOM_HELPERS[k]);
  let extendsTagName = config.extends;
  if (!extendsTagName) {
    let proto = constructor;
    while (proto && proto !== HTMLElement && proto !== Function.prototype) {
      extendsTagName = BUILT_IN_TAG_MAP.get(proto);
      if (extendsTagName) break;
      proto = Object.getPrototypeOf(proto);
    }
    config.extends = extendsTagName;
  }
  const attributePropsList = (0, import_attribute.getAttributeMetadataList)(constructor);
  const emitCustomEventList = (0, import_emitCustomEvent.getEmitCustomEventMetadataList)(constructor);
  const stateList = (0, import_state.getStateMetadataList)(constructor);
  const observedFromProps = attributePropsList ? attributePropsList.map((it) => it.options.name) : [];
  const observedFromEmits = emitCustomEventList ? emitCustomEventList.map((it) => it.options.attributeName) : [];
  const swcLifecycleAttributes = ["swc-on-constructor", "swc-on-before-connected", "swc-on-after-connected", "swc-on-before-disconnected", "swc-on-after-disconnected", "swc-on-before-adopted", "swc-on-after-adopted", "swc-on-attribute-changed"];
  const mergedObservedAttributes = [.../* @__PURE__ */ new Set([...config.observedAttributes ?? [], ...observedFromProps, ...observedFromEmits, ...swcLifecycleAttributes])];
  const NewClass = class extends constructor {
    constructor(...args) {
      super(...args);
      this._swcId = Math.random().toString(36).substring(2, 11);
      this._observer = null;
      this._shadowObserver = null;
      this._boundElements = /* @__PURE__ */ new WeakMap();
      this._activeListeners = [];
      this._emitHandlers = /* @__PURE__ */ new Map();
      this._stateBindings = /* @__PURE__ */ new Map();
      this._internalStates = /* @__PURE__ */ new Map();
      this._externalSources = /* @__PURE__ */ new Map();
      this._isSyncing = false;
      this._isUpdatingState = false;
      this._executeSwcScript("swc-on-constructor");
      if (stateList) {
        stateList.forEach((meta) => {
          const key = meta.propertyKey;
          const stateName = meta.options.name;
          const initialVal = this[key];
          this._internalStates.set(
            key,
            import_Utils.SwcUtils.createReactiveProxy(initialVal, () => this._updateState(stateName))
          );
          Object.defineProperty(this, key, {
            get: () => this._internalStates.get(key),
            set: (newVal) => {
              if (this._internalStates.get(key) === newVal) return;
              this._internalStates.set(
                key,
                import_Utils.SwcUtils.createReactiveProxy(newVal, () => this._updateState(stateName))
              );
              this._updateState(stateName);
            },
            enumerable: true,
            configurable: true
          });
        });
      }
      if (attributePropsList) {
        attributePropsList.forEach((meta) => {
          const key = meta.propertyKey;
          const attrName = meta.options.name;
          const attrValue = this.getAttribute(attrName);
          let initialVal = attrValue !== null ? attrValue : this[key];
          if (initialVal === void 0) initialVal = null;
          if (attrValue !== null) {
            if (meta.options.type === Number) initialVal = Number(attrValue);
            else if (meta.options.type === Boolean) initialVal = true;
            else if (meta.options.type === Object) {
              try {
                initialVal = JSON.parse(attrValue);
              } catch (e) {
              }
            }
          }
          this._internalStates.set(key, initialVal);
          Object.defineProperty(this, key, {
            get: () => this._internalStates.get(key),
            set: (newVal) => {
              if (this._internalStates.get(key) === newVal) return;
              this._internalStates.set(key, newVal);
              if (typeof this._updateState === "function") this._updateState(attrName);
              if (!meta.options.disableReflect && this.setAttribute && typeof newVal !== "object") {
                if (newVal === null || newVal === void 0 || newVal === false) this.removeAttribute(attrName);
                else this.setAttribute(attrName, String(newVal));
              }
            },
            enumerable: true,
            configurable: true
          });
        });
      }
      const innerHtmlList = (0, import_innerHtml.getInnerHtmlMetadataList)(this);
      if (innerHtmlList?.some((it) => it.options.useShadow === true) && !this.shadowRoot) {
        this.attachShadow({ mode: "open" });
      }
    }
    // name→value 컨텍스트 반환 (applyData의 hostContext용)
    _getHostContext() {
      const ctx = {};
      if (stateList) {
        stateList.forEach((meta) => {
          const name = meta.options.name;
          const val = this._internalStates.get(meta.propertyKey);
          ctx[name] = val;
        });
      }
      if (attributePropsList) {
        attributePropsList.forEach((meta) => {
          const name = meta.options.name;
          const val = this._internalStates.get(meta.propertyKey);
          ctx[name] = val;
        });
      }
      return ctx;
    }
    static get observedAttributes() {
      return mergedObservedAttributes;
    }
    _executeSwcScript(attrName, extraArgs = {}) {
      const script = this.getAttribute(attrName);
      if (script) {
        try {
          const $hosts = import_Utils.SwcUtils.findAllSwcHosts(this);
          const $firstHost = $hosts[0] || null;
          const $lastHost = $hosts[$hosts.length - 1] || null;
          const $host = $lastHost;
          const args = { $host, $hosts, $firstHost, $lastHost, ...SWC_DOM_HELPERS, ...extraArgs };
          const argNames = Object.keys(args);
          const argValues = Object.values(args);
          new Function(...argNames, script).apply(this, argValues);
        } catch (e) {
          console.error(`[SWC] Failed to execute ${attrName} script:`, e);
        }
      }
    }
    _syncDecorators() {
      if (this._isSyncing) return;
      this._isSyncing = true;
      try {
        this._buildStateMap();
        this._syncEventListenersAndQueries();
      } finally {
        this._isSyncing = false;
      }
    }
    _syncEventListenersAndQueries() {
      const getSearchRoots = (rootOption) => {
        const roots = [];
        if (rootOption === "shadow") {
          if (this.shadowRoot) roots.push(this.shadowRoot);
        } else if (rootOption === "light") {
          roots.push(this);
        } else if (rootOption === "all") {
          if (this.shadowRoot) roots.push(this.shadowRoot);
          roots.push(this);
        } else {
          roots.push(this.shadowRoot || this);
        }
        return roots;
      };
      const queryMetadata = (0, import_query.getQueryMetadata)(this);
      if (queryMetadata) {
        queryMetadata.filter((it) => it.isMethod).forEach((it) => {
          const searchRoots = getSearchRoots(it.options.root);
          let foundEl = null;
          for (const root of searchRoots) {
            foundEl = it.selector ? root.querySelector(it.selector) : this;
            if (foundEl) break;
          }
          if (foundEl) {
            let bound = this._boundElements.get(foundEl);
            if (!bound) {
              bound = /* @__PURE__ */ new Set();
              this._boundElements.set(foundEl, bound);
            }
            if (!bound.has(it.propertyKey)) {
              this[it.propertyKey](foundEl);
              bound.add(it.propertyKey);
            }
          }
        });
      }
      const queryAllMetadata = (0, import_queryAll.getQueryAllMetadata)(this);
      if (queryAllMetadata) {
        queryAllMetadata.filter((it) => it.isMethod).forEach((it) => {
          const searchRoots = getSearchRoots(it.options.root);
          const allElements = [];
          searchRoots.forEach((root) => {
            const found = it.selector ? root.querySelectorAll(it.selector) : [this];
            allElements.push(...Array.from(found));
          });
          this[it.propertyKey](allElements);
        });
      }
      const eventListeners = (0, import_addEventListener.getAddEventListenerMetadata)(this);
      if (eventListeners) {
        eventListeners.forEach((it) => {
          const { query, type, root: rootOption, ...options } = it.options;
          const searchRoots = getSearchRoots(rootOption);
          searchRoots.forEach((root) => {
            const targetElements = query ? root.querySelectorAll(query) : [this];
            targetElements.forEach((targetElement) => {
              if (targetElement) {
                let bound = this._boundElements.get(targetElement);
                if (!bound) {
                  bound = /* @__PURE__ */ new Set();
                  this._boundElements.set(targetElement, bound);
                }
                const eventKey = `event:${String(it.propertyKey)}:${type}`;
                if (!bound.has(eventKey)) {
                  const handler = (event) => {
                    if (it.options.stopImmediatePropagation) event.stopImmediatePropagation();
                    if (it.options.stopPropagation) event.stopPropagation();
                    if (it.options.preventDefault) event.preventDefault();
                    this[it.propertyKey](event, targetElement);
                  };
                  targetElement.addEventListener(type, handler, options);
                  bound.add(eventKey);
                  if (config.autoRemoveEventListeners) this._activeListeners.push({ el: targetElement, type, handler, options });
                  const addEventMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_ADD_EVENT_LISTENER_METADATA_KEY);
                  addEventMethods?.forEach((m) => {
                    if (typeof this[m] === "function") this[m](targetElement, type, handler);
                  });
                }
              }
            });
          });
        });
      }
    }
    _buildStateMap() {
      const scan = (root) => {
        const walker = doc.createTreeWalker(root, win.NodeFilter.SHOW_ELEMENT | win.NodeFilter.SHOW_TEXT);
        let node = null;
        while (node = walker.nextNode()) {
          if (node.nodeType === Node.TEXT_NODE) this._parseAndBind(node, "text");
          else if (node.nodeType === Node.ELEMENT_NODE) {
            const el = node;
            const alias = el.getAttribute("as");
            if (alias && !this._externalSources.has(alias)) {
              this._externalSources.set(alias, el);
              const aliasKey = `alias-event:${alias}`;
              let bound = this._boundElements.get(el);
              if (!bound) {
                bound = /* @__PURE__ */ new Set();
                this._boundElements.set(el, bound);
              }
              if (!bound.has(aliasKey)) {
                el.addEventListener(STATE_CHANGE_EVENT, () => this._updateState(alias));
                bound.add(aliasKey);
              }
            }
            Array.from(el.attributes).forEach((attr) => {
              if (attr.name.startsWith("swc-on-") && !swcLifecycleAttributes.includes(attr.name)) {
                const eventName = attr.name.substring(7);
                if (eventName === "connected") {
                  const eventKey2 = `attr-once:${attr.name}`;
                  let bound2 = this._boundElements.get(el);
                  if (!bound2) {
                    bound2 = /* @__PURE__ */ new Set();
                    this._boundElements.set(el, bound2);
                  }
                  if (!bound2.has(eventKey2)) {
                    const script = el.getAttribute(attr.name);
                    if (script) {
                      try {
                        const $hosts = import_Utils.SwcUtils.findAllSwcHosts(el);
                        const $firstHost = $hosts[0] || null;
                        const $lastHost = $hosts[$hosts.length - 1] || null;
                        const $host = $lastHost;
                        new Function("event", "$data", "$host", "$hosts", "$firstHost", "$lastHost", ...SWC_DOM_HELPER_KEYS, script).call(el, null, null, $host, $hosts, $firstHost, $lastHost, ...SWC_DOM_HELPER_VALS());
                      } catch (e) {
                        console.error(`[SWC] Failed to execute ${attr.name} script:`, e);
                      }
                    }
                    bound2.add(eventKey2);
                  }
                  return;
                }
                const eventKey = `attr-event:${attr.name}`;
                let bound = this._boundElements.get(el);
                if (!bound) {
                  bound = /* @__PURE__ */ new Set();
                  this._boundElements.set(el, bound);
                }
                if (!bound.has(eventKey)) {
                  const handler = (event) => {
                    const rawScript = el.getAttribute(attr.name);
                    if (rawScript) {
                      try {
                        const $hosts = import_Utils.SwcUtils.findAllSwcHosts(el);
                        const $firstHost = $hosts[0] || null;
                        const $lastHost = $hosts[$hosts.length - 1] || null;
                        const $host = $lastHost;
                        new Function("event", "$data", "$host", "$hosts", "$firstHost", "$lastHost", ...SWC_DOM_HELPER_KEYS, rawScript).call(el, event, event.detail, $host, $hosts, $firstHost, $lastHost, ...SWC_DOM_HELPER_VALS());
                      } catch (e) {
                        console.error(`[SWC] Failed to execute ${attr.name} script:`, e);
                      }
                    }
                  };
                  el.addEventListener(eventName, handler);
                  bound.add(eventKey);
                  if (config.autoRemoveEventListeners) this._activeListeners.push({ el, type: eventName, handler });
                }
              }
              this._parseAndBind(attr, "attribute", el);
            });
            const isSwcChild = el._swcId || getElementConfig(el.constructor) || (el.getAttribute("is")?.startsWith("swc-") ?? false);
            if (isSwcChild) {
              const next = walker.nextSibling();
              if (!next) break;
              node = next;
              if (node.nodeType === Node.TEXT_NODE) this._parseAndBind(node, "text");
            }
          }
        }
      };
      if (this.shadowRoot) scan(this.shadowRoot);
      scan(this);
    }
    _parseAndBind(node, type, owner) {
      const tplKey = `__swc_original_${this._swcId}`;
      const isAlreadyBound = node.__swc_bound_ids?.has(this._swcId);
      const content = node[tplKey] || node.textContent || "";
      const matches = Array.from(content.matchAll(/{{(.*?)}}/g));
      if (matches.length === 0 || isAlreadyBound) return;
      matches.forEach((match) => {
        const fullPath = match[1].trim();
        const rootName = fullPath.split(".")[0];
        const isState = stateList?.some((s) => s.options.name === rootName);
        const isAttr = attributePropsList?.some((a) => a.options.name === rootName);
        const isLogicKey = this._asKey === rootName || this._asIndexKey === rootName;
        const isExternal = this._externalSources.has(rootName);
        const isSelfAlias = this.getAttribute("as") === rootName;
        const isInstanceProp = rootName in this;
        if (!isState && !isAttr && !isLogicKey && !isExternal && !isSelfAlias && !isInstanceProp) return;
        if (!this._stateBindings.has(rootName)) this._stateBindings.set(rootName, []);
        if (!node[tplKey]) node[tplKey] = content;
        if (!node.__swc_bound_ids) node.__swc_bound_ids = /* @__PURE__ */ new Set();
        node.__swc_bound_ids.add(this._swcId);
        this._stateBindings.get(rootName).push({ node, type, owner, path: fullPath });
        this._updateState(rootName);
      });
    }
    _updateState(stateName) {
      if (!this._stateBindings) return;
      if (this._isUpdatingState) return;
      this._isUpdatingState = true;
      try {
        this._executeBindingUpdate(stateName);
        const selfAlias = this.getAttribute("as");
        if (selfAlias && selfAlias !== stateName) this._executeBindingUpdate(selfAlias);
        this.dispatchEvent(new CustomEvent(STATE_CHANGE_EVENT, { bubbles: true, composed: true }));
      } finally {
        this._isUpdatingState = false;
      }
    }
    _executeBindingUpdate(stateName) {
      const bindings = this._stateBindings.get(stateName);
      if (!bindings) return;
      const tplKey = `__swc_original_${this._swcId}`;
      bindings.forEach((bin) => {
        let text = bin.node[tplKey];
        if (!text) return;
        const matches = Array.from(text.matchAll(/{{(.*?)}}/g));
        let updatedText = text;
        for (const match of matches) {
          const path = match[1].trim();
          const root = path.split(".")[0];
          let val = void 0;
          let current = this;
          while (current) {
            const currentNewClass = current;
            if (current.getAttribute("as") === root) {
              val = import_Utils.SwcUtils.getValueByPath(current, path.split(".").slice(1).join(".") || "value", "value");
              if (val !== import_Utils.SWC_NOT_FOUND) break;
            }
            const externalSource = currentNewClass._externalSources?.get(root);
            if (externalSource) {
              val = import_Utils.SwcUtils.getValueByPath(externalSource, path.split(".").slice(1).join(".") || "value", "value");
              if (val !== import_Utils.SWC_NOT_FOUND) break;
            }
            const cStates = (0, import_state.getStateMetadataList)(current.constructor);
            const cAttrs = (0, import_attribute.getAttributeMetadataList)(current.constructor);
            const sMeta = cStates?.find((s) => s.options.name === root);
            const aMeta = cAttrs?.find((a) => a.options.name === root);
            if (sMeta || aMeta) {
              const propKey = sMeta ? String(sMeta.propertyKey) : String(aMeta.propertyKey);
              const rootVal = current[propKey];
              const subPath = path.split(".").slice(1).join(".");
              if (subPath) {
                val = import_Utils.SwcUtils.getValueByPath(rootVal, subPath, subPath.split(".")[0]);
                if (val === import_Utils.SWC_NOT_FOUND) {
                  const parts = subPath.split(".");
                  let cur = rootVal;
                  for (const p of parts) {
                    if (cur === null || cur === void 0) {
                      cur = import_Utils.SWC_NOT_FOUND;
                      break;
                    }
                    cur = cur[p];
                  }
                  if (cur !== void 0 && cur !== import_Utils.SWC_NOT_FOUND) val = cur;
                }
              } else {
                val = rootVal;
              }
              if (val !== import_Utils.SWC_NOT_FOUND && val !== void 0) break;
            }
            if (root in current) {
              val = import_Utils.SwcUtils.getValueByPath(current, path, root);
              if (val !== import_Utils.SWC_NOT_FOUND) break;
            }
            current = current.parentElement || current.getRootNode().host;
          }
          if (val !== import_Utils.SWC_NOT_FOUND && val !== void 0) {
            const strVal = val === null ? "" : typeof val === "object" ? JSON.stringify(val) : String(val);
            updatedText = updatedText.replace(match[0], strVal);
            if (bin.type === "attribute" && bin.owner) {
              const attrName = bin.node.name;
              const ownerAttrs = (0, import_attribute.getAttributeMetadataList)(bin.owner.constructor);
              const attrMeta = ownerAttrs?.find((a) => a.options.name === attrName);
              const propName = attrMeta ? String(attrMeta.propertyKey) : attrName.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
              if (val === null || val === void 0) {
                bin.owner.removeAttribute(attrName);
                if (propName in bin.owner) bin.owner[propName] = val;
              } else {
                if (propName in bin.owner) bin.owner[propName] = val;
                bin.owner.setAttribute(attrName, updatedText);
                if ((attrName === "value" || attrName === "checked") && bin.owner.tagName.match(/INPUT|TEXTAREA|SELECT/)) {
                  bin.owner[attrName] = updatedText;
                }
              }
            }
          }
        }
        if (bin.type === "text") bin.node.textContent = updatedText;
      });
    }
    disconnectedCallback() {
      this._executeSwcScript("swc-on-before-disconnected");
      const bMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_BEFORE_DISCONNECTED_METADATA_KEY);
      bMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      if (this._observer) this._observer.disconnect();
      if (this._shadowObserver) this._shadowObserver.disconnect();
      if (config.autoRemoveEventListeners) {
        this._activeListeners.forEach(({ el, type, handler, options }) => el.removeEventListener(type, handler, options));
        this._activeListeners = [];
      }
      if (super.disconnectedCallback) super.disconnectedCallback();
      const aMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_AFTER_DISCONNECTED_METADATA_KEY);
      aMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      this._executeSwcScript("swc-on-after-disconnected");
    }
    adoptedCallback() {
      this._executeSwcScript("swc-on-before-adopted");
      const bMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_BEFORE_ADOPTED_METADATA_KEY);
      bMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      if (super.adoptedCallback) super.adoptedCallback();
      const aMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_AFTER_ADOPTED_METADATA_KEY);
      aMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      this._executeSwcScript("swc-on-after-adopted");
    }
    async connectedCallback() {
      this._executeSwcScript("swc-on-before-connected");
      const bMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_BEFORE_CONNECTED_METADATA_KEY);
      bMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      if (typeof this.initCore === "function") this.initCore();
      const iHtmlList = (0, import_innerHtml.getInnerHtmlMetadataList)(this);
      let sContent = "";
      let lContent = "";
      if (iHtmlList) {
        for (const meta of iHtmlList) {
          const result = await this[meta.propertyKey]();
          if (result !== void 0) {
            if (meta.options.useShadow === true) sContent += result;
            else lContent += result;
          }
        }
      }
      if (this.shadowRoot) this.shadowRoot.innerHTML = sContent;
      if (lContent) this.innerHTML = lContent;
      this._syncDecorators();
      const isManagedByParent = !!import_Utils.SwcUtils.findNearestSwcHost(this);
      if (!isManagedByParent) {
        Array.from(this.attributes).forEach((attr) => {
          if (attr.name.startsWith("swc-on-") && swcLifecycleAttributes.indexOf(attr.name) === -1) {
            const eventName = attr.name.substring(7);
            if (eventName === "connected") {
              const eventKey2 = `host-attr-once:${attr.name}`;
              let bound2 = this._boundElements.get(this);
              if (!bound2) {
                bound2 = /* @__PURE__ */ new Set();
                this._boundElements.set(this, bound2);
              }
              if (!bound2.has(eventKey2)) {
                const script = this.getAttribute(attr.name);
                if (script) {
                  try {
                    const $hosts = import_Utils.SwcUtils.findAllSwcHosts(this);
                    const $firstHost = $hosts[0] || null;
                    const $lastHost = $hosts[$hosts.length - 1] || null;
                    const $host = $lastHost;
                    new Function("event", "$data", "$host", "$hosts", "$firstHost", "$lastHost", ...SWC_DOM_HELPER_KEYS, script).call(this, null, null, $host, $hosts, $firstHost, $lastHost, ...SWC_DOM_HELPER_VALS());
                  } catch (e) {
                    console.error(`[SWC] Failed to execute ${attr.name} script:`, e);
                  }
                }
                bound2.add(eventKey2);
              }
              return;
            }
            const eventKey = `host-attr-event:${attr.name}`;
            let bound = this._boundElements.get(this);
            if (!bound) {
              bound = /* @__PURE__ */ new Set();
              this._boundElements.set(this, bound);
            }
            if (!bound.has(eventKey)) {
              const handler = (event) => {
                const script = this.getAttribute(attr.name);
                if (script) {
                  try {
                    const $hosts = import_Utils.SwcUtils.findAllSwcHosts(this);
                    const $firstHost = $hosts[0] || null;
                    const $lastHost = $hosts[$hosts.length - 1] || null;
                    const $host = $lastHost;
                    new Function("event", "$data", "$host", "$hosts", "$firstHost", "$lastHost", ...SWC_DOM_HELPER_KEYS, script).call(this, event, event.detail, $host, $hosts, $firstHost, $lastHost, ...SWC_DOM_HELPER_VALS());
                  } catch (e) {
                    console.error(`[SWC] Failed to execute ${attr.name} script:`, e);
                  }
                }
              };
              this.addEventListener(eventName, handler);
              bound.add(eventKey);
              if (config.autoRemoveEventListeners) this._activeListeners.push({ el: this, type: eventName, handler });
            }
          }
        });
      }
      const mutationMetaList = (0, import_lifecycles.getMutationSubscribeMetadataList)(this);
      const fireMutationCallbacks = (mutationList, observer, root) => {
        mutationMetaList?.forEach((meta) => {
          const r = meta.options.root ?? "auto";
          const matches = r === "all" || r === root || r === "auto" && (this.shadowRoot ? root === "shadow" : root === "light");
          if (matches && typeof this[meta.propertyKey] === "function") {
            this[meta.propertyKey](mutationList, observer, root);
          }
        });
      };
      this._observer = new win.MutationObserver((mutationList, observer) => {
        this._syncDecorators();
        fireMutationCallbacks(mutationList, observer, "light");
      });
      this._observer.observe(this, { childList: true, subtree: true });
      if (this.shadowRoot) {
        this._shadowObserver = new win.MutationObserver((mutationList, observer) => {
          this._syncDecorators();
          fireMutationCallbacks(mutationList, observer, "shadow");
        });
        this._shadowObserver.observe(this.shadowRoot, { childList: true, subtree: true });
      }
      if (super.connectedCallback) await super.connectedCallback();
      const aMethods = (0, import_lifecycles.getLifecycleMetadata)(this, import_lifecycles.ON_AFTER_CONNECTED_METADATA_KEY);
      aMethods?.forEach((m) => {
        if (typeof this[m] === "function") this[m]();
      });
      this._executeSwcScript("swc-on-after-connected");
    }
    attributeChangedCallback(name, oldValue, newValue) {
      if (super.attributeChangedCallback) super.attributeChangedCallback(name, oldValue, newValue);
      if (attributePropsList) {
        attributePropsList.forEach((meta) => {
          if (meta.options.name === name) {
            const current = this[meta.propertyKey];
            if (typeof current === "object" && current !== null) return;
            if (String(current) !== String(newValue)) this[meta.propertyKey] = newValue;
          }
        });
      }
      if (typeof this._updateState === "function") this._updateState(name);
      const aMethodsMap = (0, import_lifecycles.getLifecycleMetadata)(constructor, import_lifecycles.ON_ATTRIBUTE_CHANGED_METADATA_KEY);
      const mKeys = aMethodsMap?.get(name);
      if (mKeys && Array.isArray(mKeys))
        mKeys.forEach((key) => {
          if (typeof this[key] === "function") this[key](newValue, oldValue, name);
        });
      if (emitCustomEventList) {
        const eMeta = emitCustomEventList.find((it) => it.options.attributeName === name);
        if (eMeta) {
          const eType = eMeta.options.type;
          const oHandler = this._emitHandlers.get(eType);
          if (oHandler) this.removeEventListener(eType, oHandler);
          if (newValue) {
            const nHandler = (e) => {
              new Function("event", "$data", newValue).call(this, e, e.detail);
            };
            this.addEventListener(eType, nHandler);
            this._emitHandlers.set(eType, nHandler);
          }
        }
      }
      const wMethodsKeys = aMethodsMap?.get(import_lifecycles.ATTRIBUTE_CHANGED_WILDCARD);
      if (wMethodsKeys && Array.isArray(wMethodsKeys))
        wMethodsKeys.forEach((key) => {
          if (typeof this[key] === "function") this[key](newValue, oldValue, name);
        });
      this._executeSwcScript("swc-on-attribute-changed", { $new: newValue, $old: oldValue, $name: name });
    }
  };
  import_ReflectUtils.ReflectUtils.defineMetadata(ELEMENT_CONFIG_KEY, config, NewClass);
  import_ReflectUtils.ReflectUtils.defineMetadata(ELEMENT_CONFIG_KEY, config, constructor);
  const registry = config.customElementRegistry || (typeof win !== "undefined" ? win.customElements : void 0);
  if (registry && !registry.get(config.name)) {
    const options = config.extends ? { extends: config.extends } : void 0;
    registry.define(config.name, NewClass, options);
  }
  return NewClass;
};
const getElementConfig = (target) => {
  const constructor = target instanceof Function ? target : target.constructor;
  return import_ReflectUtils.ReflectUtils.getMetadata(ELEMENT_CONFIG_KEY, constructor);
};
//# sourceMappingURL=elementDefine.js.map
