// #region Imports
import { noChange } from 'lit';
import { directive, PartType } from 'lit/directive.js';
import { ControllerBase } from '../../Controllers/Abstracts/ControllerBase';
import { DirectiveBase } from '../Abstracts/DirectiveBase';
import { waitForEvent } from '@breadstone/mosaik-elements';
import { isReactiveControllerHost } from '../../Controllers/Utils';
// #endregion
class AdoptStyleController extends ControllerBase {
    // #region Ctor
    /**
     * Constructs a new instance of the `AdoptStyleController` class.
     *
     * @public
     */
    constructor(host) {
        super(host);
    }
    // #endregion
    // #region Methods
    /**
     * Adopts the provided styles to the specified element.
     *
     * @param element - The element to adopt the styles to.
     * @public
     */
    adoptStyles(styles) {
        if (this.isConnected) {
            if (Array.isArray(styles)) {
                const styleSheets = Array.from(styles).map((style) => style.styleSheet);
                if (this.host.shadowRoot) {
                    this.host.shadowRoot.adoptedStyleSheets = styleSheets;
                }
            }
            else {
                const styleSheet = styles.styleSheet;
                if (styleSheet && this.host.shadowRoot) {
                    const current = this.host.shadowRoot.adoptedStyleSheets;
                    current.push(styleSheet);
                    this.host.shadowRoot.adoptedStyleSheets = current;
                }
            }
        }
        else {
            void waitForEvent(this.host, 'connected').then(() => this.adoptStyles(styles));
        }
    }
}
class AdoptStyleDirective extends DirectiveBase {
    // #region Fields
    _adoptStyleController;
    // #endregion
    // #region Ctor
    constructor(args) {
        super(args);
        if (args.type !== PartType.ELEMENT) {
            throw new Error('The `adoptStyle` directive can only be used on elements.');
        }
        if (!isReactiveControllerHost(args.element)) {
            throw new Error('The `adoptStyle` directive can only be used on reactive controller host elements.');
        }
        this._adoptStyleController = new AdoptStyleController(args.element);
    }
    // #endregion
    // #region Methods
    render(_styles) {
        return noChange; // Directive does not manipulate the part directly
    }
    update(_part, [styles]) {
        if (styles === undefined) {
            return noChange;
        }
        this._adoptStyleController.adoptStyles(styles);
        return this.render(styles);
    }
}
/**
 * @public
 */
export const adoptStyle = directive(AdoptStyleDirective);
//# sourceMappingURL=AdoptStyleDirective.js.map