/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-1fc5ad1 | Cube Dev Team */
import { createStyle } from "../styles/createStyle.js";
import { STYLE_HANDLER_MAP } from "../styles/index.js";

//#region src/tasty/injector/sheet-manager.ts
var SheetManager = class {
	rootRegistries = /* @__PURE__ */ new WeakMap();
	config;
	/** Dedicated style elements for raw CSS per root */
	rawStyleElements = /* @__PURE__ */ new WeakMap();
	/** Tracking for raw CSS blocks per root */
	rawCSSBlocks = /* @__PURE__ */ new WeakMap();
	/** Counter for generating unique raw CSS IDs */
	rawCSSCounter = 0;
	constructor(config) {
		this.config = config;
	}
	/**
	* Get or create registry for a root (Document or ShadowRoot)
	*/
	getRegistry(root) {
		let registry = this.rootRegistries.get(root);
		if (!registry) {
			const metrics = this.config.devMode ? {
				hits: 0,
				misses: 0,
				bulkCleanups: 0,
				totalInsertions: 0,
				totalUnused: 0,
				stylesCleanedUp: 0,
				cleanupHistory: [],
				startTime: Date.now()
			} : void 0;
			registry = {
				sheets: [],
				refCounts: /* @__PURE__ */ new Map(),
				rules: /* @__PURE__ */ new Map(),
				cacheKeyToClassName: /* @__PURE__ */ new Map(),
				ruleTextSet: /* @__PURE__ */ new Set(),
				bulkCleanupTimeout: null,
				cleanupCheckTimeout: null,
				metrics,
				classCounter: 0,
				keyframesCache: /* @__PURE__ */ new Map(),
				keyframesNameToContent: /* @__PURE__ */ new Map(),
				keyframesCounter: 0,
				injectedProperties: /* @__PURE__ */ new Map(),
				globalRules: /* @__PURE__ */ new Map()
			};
			this.rootRegistries.set(root, registry);
		}
		return registry;
	}
	/**
	* Create a new stylesheet for the registry
	*/
	createSheet(registry, root) {
		const sheetInfo = {
			sheet: this.createStyleElement(root),
			ruleCount: 0,
			holes: []
		};
		registry.sheets.push(sheetInfo);
		return sheetInfo;
	}
	/**
	* Create a style element and append to document
	*/
	createStyleElement(root) {
		const style = root.createElement?.("style") || document.createElement("style");
		if (this.config.nonce) style.nonce = this.config.nonce;
		style.setAttribute("data-tasty", "");
		if ("head" in root && root.head) root.head.appendChild(style);
		else if ("appendChild" in root) root.appendChild(style);
		else document.head.appendChild(style);
		if (!style.isConnected && !this.config.forceTextInjection) console.error("SheetManager: Style element failed to connect to DOM!", {
			parentNode: style.parentNode?.nodeName,
			isConnected: style.isConnected
		});
		return style;
	}
	/**
	* Insert CSS rules as a single block
	*/
	insertRule(registry, flattenedRules, className, root) {
		let targetSheet = this.findAvailableSheet(registry, root);
		if (!targetSheet) targetSheet = this.createSheet(registry, root);
		const sheetIndex = registry.sheets.indexOf(targetSheet);
		try {
			const groupedRules = [];
			const groupMap = /* @__PURE__ */ new Map();
			const atKey = (at) => at && at.length ? at.join("|") : "";
			flattenedRules.forEach((r) => {
				const key = `${atKey(r.atRules)}||${r.selector}`;
				const existing = groupMap.get(key);
				if (existing) existing.declarations = existing.declarations ? `${existing.declarations} ${r.declarations}` : r.declarations;
				else {
					groupMap.set(key, {
						idx: groupedRules.length,
						selector: r.selector,
						atRules: r.atRules,
						declarations: r.declarations
					});
					groupedRules.push({ ...r });
				}
			});
			groupMap.forEach((val) => {
				groupedRules[val.idx] = {
					selector: val.selector,
					atRules: val.atRules,
					declarations: val.declarations
				};
			});
			const insertedRuleTexts = [];
			const insertedIndices = [];
			let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);
			let firstInsertedIndex = null;
			let lastInsertedIndex = null;
			for (const rule of groupedRules) {
				const declarations = rule.declarations;
				const baseRule = `${rule.selector} { ${declarations} }`;
				let fullRule = baseRule;
				if (rule.atRules && rule.atRules.length > 0) fullRule = rule.atRules.reduce((css, atRule) => `${atRule} { ${css} }`, baseRule);
				const styleElement = targetSheet.sheet;
				const styleSheet = styleElement.sheet;
				if (styleSheet && !this.config.forceTextInjection) {
					const maxIndex = styleSheet.cssRules.length;
					const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);
					const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);
					const splitSelectorsSafely = (selectorList) => {
						const parts = [];
						let buf = "";
						let depthSq = 0;
						let depthPar = 0;
						let inStr = "";
						for (let i = 0; i < selectorList.length; i++) {
							const ch = selectorList[i];
							if (inStr) {
								if (ch === inStr && selectorList[i - 1] !== "\\") inStr = "";
								buf += ch;
								continue;
							}
							if (ch === "\"" || ch === "'") {
								inStr = ch;
								buf += ch;
								continue;
							}
							if (ch === "[") depthSq++;
							else if (ch === "]") depthSq = Math.max(0, depthSq - 1);
							else if (ch === "(") depthPar++;
							else if (ch === ")") depthPar = Math.max(0, depthPar - 1);
							if (ch === "," && depthSq === 0 && depthPar === 0) {
								const part = buf.trim();
								if (part) parts.push(part);
								buf = "";
							} else buf += ch;
						}
						const tail = buf.trim();
						if (tail) parts.push(tail);
						return parts;
					};
					try {
						styleSheet.insertRule(fullRule, safeIndex);
						targetSheet.ruleCount++;
						insertedIndices.push(safeIndex);
						if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;
						lastInsertedIndex = safeIndex;
						currentRuleIndex = safeIndex + 1;
					} catch (e) {
						const selectors = splitSelectorsSafely(rule.selector);
						if (selectors.length > 1) {
							let anyInserted = false;
							for (const sel of selectors) {
								const singleBase = `${sel} { ${declarations} }`;
								let singleRule = singleBase;
								if (rule.atRules && rule.atRules.length > 0) singleRule = rule.atRules.reduce((css, atRule) => `${atRule} { ${css} }`, singleBase);
								try {
									const maxIdx = styleSheet.cssRules.length;
									const atomicIdx = this.findAvailableRuleIndex(targetSheet);
									const idx = Math.min(Math.max(0, atomicIdx), maxIdx);
									styleSheet.insertRule(singleRule, idx);
									targetSheet.ruleCount++;
									insertedIndices.push(idx);
									if (firstInsertedIndex == null) firstInsertedIndex = idx;
									lastInsertedIndex = idx;
									currentRuleIndex = idx + 1;
									anyInserted = true;
								} catch (singleErr) {
									if (process.env.NODE_ENV !== "production") console.warn("[tasty] Browser rejected CSS rule:", singleRule, singleErr);
								}
							}
							if (!anyInserted) {}
						} else if (process.env.NODE_ENV !== "production") console.warn("[tasty] Browser rejected CSS rule:", fullRule, e);
					}
				} else {
					const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);
					styleElement.textContent = (styleElement.textContent || "") + "\n" + fullRule;
					targetSheet.ruleCount++;
					insertedIndices.push(atomicRuleIndex);
					if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;
					lastInsertedIndex = atomicRuleIndex;
					currentRuleIndex = atomicRuleIndex + 1;
				}
				if (!styleElement.parentNode && !this.config.forceTextInjection) console.error("SheetManager: Style element is NOT in DOM! This is the problem!", {
					className,
					ruleIndex: currentRuleIndex
				});
				if (this.config.devMode) {
					insertedRuleTexts.push(fullRule);
					try {
						registry.ruleTextSet.add(fullRule);
					} catch (_) {}
				}
			}
			if (insertedIndices.length === 0) return null;
			return {
				className,
				ruleIndex: firstInsertedIndex ?? 0,
				sheetIndex,
				cssText: this.config.devMode ? insertedRuleTexts : void 0,
				endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,
				indices: insertedIndices
			};
		} catch (error) {
			console.warn("Failed to insert CSS rules:", error, {
				flattenedRules,
				className
			});
			return null;
		}
	}
	/**
	* Insert global CSS rules
	*/
	insertGlobalRule(registry, flattenedRules, globalKey, root) {
		const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);
		if (ruleInfo) registry.globalRules.set(globalKey, ruleInfo);
		return ruleInfo;
	}
	/**
	* Delete a global CSS rule by key
	*/
	deleteGlobalRule(registry, globalKey) {
		const ruleInfo = registry.globalRules.get(globalKey);
		if (!ruleInfo) return;
		this.deleteRule(registry, ruleInfo);
		registry.globalRules.delete(globalKey);
	}
	/**
	* Adjust rule indices after deletion to account for shifting
	*/
	adjustIndicesAfterDeletion(registry, sheetIndex, startIdx, endIdx, deleteCount, deletedRuleInfo, deletedIndices) {
		try {
			const sortedDeleted = deletedIndices && deletedIndices.length > 0 ? [...deletedIndices].sort((a, b) => a - b) : null;
			const countDeletedBefore = (sorted, idx) => {
				let shift = 0;
				for (const delIdx of sorted) if (delIdx < idx) shift++;
				else break;
				return shift;
			};
			const adjustRuleInfo = (info) => {
				if (info === deletedRuleInfo) return;
				if (info.sheetIndex !== sheetIndex) return;
				if (!info.indices || info.indices.length === 0) return;
				if (sortedDeleted) info.indices = info.indices.map((idx) => {
					return idx - countDeletedBefore(sortedDeleted, idx);
				});
				else info.indices = info.indices.map((idx) => idx > endIdx ? Math.max(0, idx - deleteCount) : idx);
				if (info.indices.length > 0) {
					info.ruleIndex = Math.min(...info.indices);
					info.endRuleIndex = Math.max(...info.indices);
				}
			};
			for (const info of registry.rules.values()) adjustRuleInfo(info);
			for (const info of registry.globalRules.values()) adjustRuleInfo(info);
			for (const entry of registry.keyframesCache.values()) {
				const ki = entry.info;
				if (ki.sheetIndex !== sheetIndex) continue;
				if (sortedDeleted) {
					const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);
					if (shift > 0) ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);
				} else if (ki.ruleIndex > endIdx) ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);
			}
		} catch (_) {}
	}
	/**
	* Delete a CSS rule from the sheet
	*/
	deleteRule(registry, ruleInfo) {
		const sheet = registry.sheets[ruleInfo.sheetIndex];
		if (!sheet) return;
		try {
			const texts = this.config.devMode && Array.isArray(ruleInfo.cssText) ? ruleInfo.cssText.slice() : [];
			const styleSheet = sheet.sheet.sheet;
			if (styleSheet) {
				const rules = styleSheet.cssRules;
				if (ruleInfo.indices && ruleInfo.indices.length > 0) {
					const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a);
					const deletedIndices = [];
					for (const idx of sortedIndices) if (idx >= 0 && idx < styleSheet.cssRules.length) try {
						styleSheet.deleteRule(idx);
						deletedIndices.push(idx);
					} catch (e) {
						console.warn(`Failed to delete rule at index ${idx}:`, e);
					}
					sheet.ruleCount = Math.max(0, sheet.ruleCount - deletedIndices.length);
					if (deletedIndices.length > 0) this.adjustIndicesAfterDeletion(registry, ruleInfo.sheetIndex, Math.min(...deletedIndices), Math.max(...deletedIndices), deletedIndices.length, ruleInfo, deletedIndices);
				} else {
					const startIdx = Math.max(0, ruleInfo.ruleIndex);
					const endIdx = Math.min(rules.length - 1, Number.isFinite(ruleInfo.endRuleIndex) ? ruleInfo.endRuleIndex : startIdx);
					if (Number.isFinite(startIdx) && endIdx >= startIdx) {
						const deleteCount = endIdx - startIdx + 1;
						for (let idx = endIdx; idx >= startIdx; idx--) {
							if (idx < 0 || idx >= styleSheet.cssRules.length) continue;
							styleSheet.deleteRule(idx);
						}
						sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);
						this.adjustIndicesAfterDeletion(registry, ruleInfo.sheetIndex, startIdx, endIdx, deleteCount, ruleInfo);
					}
				}
			}
			if (this.config.devMode && texts.length) try {
				for (const text of texts) registry.ruleTextSet.delete(text);
			} catch (_) {}
		} catch (error) {
			console.warn("Failed to delete CSS rule:", error);
		}
	}
	/**
	* Find a sheet with available space or return null
	*/
	findAvailableSheet(registry, root) {
		const maxRules = this.config.maxRulesPerSheet;
		if (!maxRules) return registry.sheets[registry.sheets.length - 1] || null;
		for (const sheet of registry.sheets) if (sheet.ruleCount < maxRules) return sheet;
		return null;
	}
	/**
	* Find an available rule index in the sheet
	*/
	findAvailableRuleIndex(sheet) {
		return sheet.ruleCount;
	}
	/**
	* Schedule bulk cleanup of all unused styles (non-stacking)
	*/
	scheduleBulkCleanup(registry) {
		if (registry.bulkCleanupTimeout) {
			if (this.config.idleCleanup && typeof cancelIdleCallback !== "undefined") cancelIdleCallback(registry.bulkCleanupTimeout);
			else clearTimeout(registry.bulkCleanupTimeout);
			registry.bulkCleanupTimeout = null;
		}
		const performCleanup = () => {
			this.performBulkCleanup(registry);
			registry.bulkCleanupTimeout = null;
		};
		if (this.config.idleCleanup && typeof requestIdleCallback !== "undefined") registry.bulkCleanupTimeout = requestIdleCallback(performCleanup);
		else {
			const delay = this.config.bulkCleanupDelay || 5e3;
			registry.bulkCleanupTimeout = setTimeout(performCleanup, delay);
		}
	}
	/**
	* Force cleanup of unused styles
	*/
	forceCleanup(registry) {
		this.performBulkCleanup(registry, true);
	}
	/**
	* Perform bulk cleanup of all unused styles
	*/
	performBulkCleanup(registry, cleanupAll = false) {
		const cleanupStartTime = Date.now();
		const unusedClassNames = Array.from(registry.refCounts.entries()).filter(([, refCount]) => refCount === 0).map(([className]) => className);
		if (unusedClassNames.length === 0) return;
		const candidates = unusedClassNames.map((className) => {
			return {
				className,
				ruleInfo: registry.rules.get(className)
			};
		});
		if (candidates.length === 0) return;
		let selected = candidates;
		if (!cleanupAll) {
			const ratio = this.config.bulkCleanupBatchRatio ?? .5;
			const limit = Math.max(1, Math.floor(candidates.length * Math.min(1, Math.max(0, ratio))));
			selected = candidates.slice(0, limit);
		}
		let cleanedUpCount = 0;
		let totalCssSize = 0;
		let totalRulesDeleted = 0;
		const rulesBySheet = /* @__PURE__ */ new Map();
		for (const { className, ruleInfo } of selected) {
			const sheetIndex = ruleInfo.sheetIndex;
			if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {
				const cssSize = ruleInfo.cssText.reduce((total, css) => total + css.length, 0);
				totalCssSize += cssSize;
				totalRulesDeleted += ruleInfo.cssText.length;
			}
			if (!rulesBySheet.has(sheetIndex)) rulesBySheet.set(sheetIndex, []);
			rulesBySheet.get(sheetIndex).push({
				className,
				ruleInfo
			});
		}
		for (const [sheetIndex, rulesInSheet] of rulesBySheet) {
			rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);
			for (const { className, ruleInfo } of rulesInSheet) {
				if ((registry.refCounts.get(className) || 0) > 0) continue;
				if (registry.rules.get(className) !== ruleInfo) continue;
				const sheetInfo = registry.sheets[ruleInfo.sheetIndex];
				if (!sheetInfo || !sheetInfo.sheet) continue;
				const styleSheet = sheetInfo.sheet.sheet;
				if (!styleSheet) continue;
				const maxRuleIndex = styleSheet.cssRules.length - 1;
				const startIdx = ruleInfo.ruleIndex;
				const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;
				if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) continue;
				this.deleteRule(registry, ruleInfo);
				registry.rules.delete(className);
				registry.refCounts.delete(className);
				const keysToDelete = [];
				for (const [key, mappedClassName] of registry.cacheKeyToClassName.entries()) if (mappedClassName === className) keysToDelete.push(key);
				for (const key of keysToDelete) registry.cacheKeyToClassName.delete(key);
				cleanedUpCount++;
			}
		}
		if (registry.metrics) {
			registry.metrics.bulkCleanups++;
			registry.metrics.stylesCleanedUp += cleanedUpCount;
			registry.metrics.cleanupHistory.push({
				timestamp: cleanupStartTime,
				classesDeleted: cleanedUpCount,
				cssSize: totalCssSize,
				rulesDeleted: totalRulesDeleted
			});
		}
	}
	/**
	* Get total number of rules across all sheets
	*/
	getTotalRuleCount(registry) {
		return registry.sheets.reduce((total, sheet) => total + sheet.ruleCount - sheet.holes.length, 0);
	}
	/**
	* Get CSS text from all sheets (for SSR)
	*/
	getCssText(registry) {
		const cssChunks = [];
		for (const sheet of registry.sheets) try {
			const styleElement = sheet.sheet;
			if (styleElement.textContent) cssChunks.push(styleElement.textContent);
			else if (styleElement.sheet) {
				const rules = Array.from(styleElement.sheet.cssRules);
				cssChunks.push(rules.map((rule) => rule.cssText).join("\n"));
			}
		} catch (error) {
			console.warn("Failed to read CSS from sheet:", error);
		}
		return cssChunks.join("\n");
	}
	/**
	* Get cache performance metrics
	*/
	getMetrics(registry) {
		if (!registry.metrics) return null;
		const unusedRulesCount = Array.from(registry.refCounts.values()).filter((count) => count === 0).length;
		return {
			...registry.metrics,
			unusedHits: unusedRulesCount
		};
	}
	/**
	* Reset cache performance metrics
	*/
	resetMetrics(registry) {
		if (registry.metrics) registry.metrics = {
			hits: 0,
			misses: 0,
			bulkCleanups: 0,
			totalInsertions: 0,
			totalUnused: 0,
			stylesCleanedUp: 0,
			cleanupHistory: [],
			startTime: Date.now()
		};
	}
	/**
	* Convert keyframes steps to CSS string
	*/
	stepsToCSS(steps) {
		const rules = [];
		for (const [key, value] of Object.entries(steps)) {
			if (typeof value === "string") {
				rules.push(`${key} { ${value.trim()} }`);
				continue;
			}
			const styleMap = value || {};
			const styleNames = Object.keys(styleMap).sort();
			const handlerQueue = [];
			const seenHandlers = /* @__PURE__ */ new Set();
			styleNames.forEach((styleName) => {
				let handlers = STYLE_HANDLER_MAP[styleName];
				if (!handlers) handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];
				handlers.forEach((handler) => {
					if (!seenHandlers.has(handler)) {
						seenHandlers.add(handler);
						handlerQueue.push(handler);
					}
				});
			});
			const declarationPairs = [];
			handlerQueue.forEach((handler) => {
				const result = handler(handler.__lookupStyles.reduce((acc, name) => {
					const v = styleMap[name];
					if (v !== void 0) acc[name] = v;
					return acc;
				}, {}));
				if (!result) return;
				(Array.isArray(result) ? result : [result]).forEach((cssMap) => {
					if (!cssMap || typeof cssMap !== "object") return;
					const { $, ...props } = cssMap;
					Object.entries(props).forEach(([prop, val]) => {
						if (val == null || val === "") return;
						if (Array.isArray(val)) val.forEach((v) => {
							if (v != null && v !== "") declarationPairs.push({
								prop,
								value: String(v)
							});
						});
						else declarationPairs.push({
							prop,
							value: String(val)
						});
					});
				});
			});
			const declarations = declarationPairs.map((d) => `${d.prop}: ${d.value}`).join("; ");
			rules.push(`${key} { ${declarations.trim()} }`);
		}
		return rules.join(" ");
	}
	/**
	* Insert keyframes rule
	*/
	insertKeyframes(registry, steps, name, root) {
		let targetSheet = this.findAvailableSheet(registry, root);
		if (!targetSheet) targetSheet = this.createSheet(registry, root);
		const ruleIndex = this.findAvailableRuleIndex(targetSheet);
		const sheetIndex = registry.sheets.indexOf(targetSheet);
		try {
			const fullRule = `@keyframes ${name} { ${this.stepsToCSS(steps)} }`;
			const styleElement = targetSheet.sheet;
			const styleSheet = styleElement.sheet;
			if (styleSheet && !this.config.forceTextInjection) {
				const safeIndex = Math.min(Math.max(0, ruleIndex), styleSheet.cssRules.length);
				styleSheet.insertRule(fullRule, safeIndex);
			} else styleElement.textContent = (styleElement.textContent || "") + "\n" + fullRule;
			targetSheet.ruleCount++;
			return {
				name,
				ruleIndex,
				sheetIndex,
				cssText: this.config.devMode ? fullRule : void 0
			};
		} catch (error) {
			console.warn("Failed to insert keyframes:", error);
			return null;
		}
	}
	/**
	* Delete keyframes rule
	*/
	deleteKeyframes(registry, info) {
		const sheet = registry.sheets[info.sheetIndex];
		if (!sheet) return;
		try {
			const styleSheet = sheet.sheet.sheet;
			if (styleSheet) {
				if (info.ruleIndex >= 0 && info.ruleIndex < styleSheet.cssRules.length) {
					styleSheet.deleteRule(info.ruleIndex);
					sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);
					this.adjustIndicesAfterDeletion(registry, info.sheetIndex, info.ruleIndex, info.ruleIndex, 1, {
						className: "",
						ruleIndex: info.ruleIndex,
						sheetIndex: info.sheetIndex
					}, [info.ruleIndex]);
				}
			}
		} catch (error) {
			console.warn("Failed to delete keyframes:", error);
		}
	}
	/**
	* Schedule async cleanup check (non-stacking)
	*/
	checkCleanupNeeded(registry) {
		if (registry.cleanupCheckTimeout) {
			clearTimeout(registry.cleanupCheckTimeout);
			registry.cleanupCheckTimeout = null;
		}
		registry.cleanupCheckTimeout = setTimeout(() => {
			this.performCleanupCheck(registry);
			registry.cleanupCheckTimeout = null;
		}, 0);
	}
	/**
	* Perform the actual cleanup check (called asynchronously)
	*/
	performCleanupCheck(registry) {
		if (Array.from(registry.refCounts.values()).filter((count) => count === 0).length >= (this.config.unusedStylesThreshold || 500)) this.scheduleBulkCleanup(registry);
	}
	/**
	* Clean up resources for a root
	*/
	cleanup(root) {
		const registry = this.rootRegistries.get(root);
		if (!registry) return;
		if (registry.bulkCleanupTimeout) {
			if (this.config.idleCleanup && typeof cancelIdleCallback !== "undefined") cancelIdleCallback(registry.bulkCleanupTimeout);
			else clearTimeout(registry.bulkCleanupTimeout);
			registry.bulkCleanupTimeout = null;
		}
		if (registry.cleanupCheckTimeout) {
			clearTimeout(registry.cleanupCheckTimeout);
			registry.cleanupCheckTimeout = null;
		}
		for (const sheet of registry.sheets) try {
			const styleElement = sheet.sheet;
			if (styleElement.parentNode) styleElement.parentNode.removeChild(styleElement);
		} catch (error) {
			console.warn("Failed to cleanup sheet:", error);
		}
		this.rootRegistries.delete(root);
		const rawStyleElement = this.rawStyleElements.get(root);
		if (rawStyleElement?.parentNode) rawStyleElement.parentNode.removeChild(rawStyleElement);
		this.rawStyleElements.delete(root);
		this.rawCSSBlocks.delete(root);
	}
	/**
	* Get or create a dedicated style element for raw CSS
	* Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts
	*/
	getOrCreateRawStyleElement(root) {
		let styleElement = this.rawStyleElements.get(root);
		if (!styleElement) {
			styleElement = root.createElement?.("style") || document.createElement("style");
			if (this.config.nonce) styleElement.nonce = this.config.nonce;
			styleElement.setAttribute("data-tasty-raw", "");
			if ("head" in root && root.head) root.head.appendChild(styleElement);
			else if ("appendChild" in root) root.appendChild(styleElement);
			else document.head.appendChild(styleElement);
			this.rawStyleElements.set(root, styleElement);
			this.rawCSSBlocks.set(root, /* @__PURE__ */ new Map());
		}
		return styleElement;
	}
	/**
	* Inject raw CSS text directly without parsing
	* Returns a dispose function to remove the injected CSS
	*/
	injectRawCSS(css, root) {
		if (!css.trim()) return { dispose: () => {} };
		const styleElement = this.getOrCreateRawStyleElement(root);
		const blocksMap = this.rawCSSBlocks.get(root);
		const id = `raw_${this.rawCSSCounter++}`;
		const currentContent = styleElement.textContent || "";
		const startOffset = currentContent.length;
		const cssWithNewline = (currentContent ? "\n" : "") + css;
		const endOffset = startOffset + cssWithNewline.length;
		styleElement.textContent = currentContent + cssWithNewline;
		const info = {
			id,
			css,
			startOffset,
			endOffset
		};
		blocksMap.set(id, info);
		return { dispose: () => {
			this.disposeRawCSS(id, root);
		} };
	}
	/**
	* Remove a raw CSS block by ID
	*/
	disposeRawCSS(id, root) {
		const styleElement = this.rawStyleElements.get(root);
		const blocksMap = this.rawCSSBlocks.get(root);
		if (!styleElement || !blocksMap) return;
		if (!blocksMap.get(id)) return;
		blocksMap.delete(id);
		const remainingBlocks = Array.from(blocksMap.values());
		if (remainingBlocks.length === 0) styleElement.textContent = "";
		else {
			remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);
			styleElement.textContent = remainingBlocks.map((block) => block.css).join("\n");
			let offset = 0;
			for (const block of remainingBlocks) {
				block.startOffset = offset;
				block.endOffset = offset + block.css.length;
				offset = block.endOffset + 1;
			}
		}
	}
	/**
	* Get the raw CSS content for SSR
	*/
	getRawCSSText(root) {
		return this.rawStyleElements.get(root)?.textContent || "";
	}
};

//#endregion
export { SheetManager };
//# sourceMappingURL=sheet-manager.js.map