// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { CssLength, ITheme, ThemePalette } from '@breadstone/mosaik-themes';
import { Component } from '../Controls/Decorators/ComponentDecorator';
import { CustomElement } from '../Controls/Components/Abstracts/CustomElement';
import { theme2ElementTemplate } from './Theme2ElementTemplate';
import { theme2ElementStyle } from './Theme2ElementStyle';
import { Property } from '../Controls/Decorators/PropertyDecorator';
import { Watch } from '../Controls/Decorators/WatchDecorator';
import { RendererServiceLocator } from '../Dom/Renderer';
import { Equals } from '../Equality/Equals';
import { Theme } from './Theme';
import { GlobalStyleSheet } from '../Dom/StyleSheet';
// #endregion
/**
 * The `{@link Theme2Element}` element.
 *
 * @public
 */
let Theme2Element = class Theme2Element extends CustomElement {
    // #region Fields
    _theme;
    _isInline;
    _globalStyleSheet;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        Theme.register(this);
        this._theme = null;
        this._isInline = false;
        this._globalStyleSheet = new GlobalStyleSheet();
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-theme2';
    }
    /**
     * Gets or sets the `theme` property.
     *
     * @public
     */
    get theme() {
        return this._theme;
    }
    set theme(value) {
        if (!Equals.areObjectsEqual(this._theme, value)) {
            this._theme = value;
            this.requestUpdate('theme');
        }
    }
    /**
     * Gets or sets the `isInline` property.
     *
     * @public
     */
    get isInline() {
        return this._isInline;
    }
    set isInline(value) {
        if (this._isInline !== value) {
            this._isInline = value;
            this.requestUpdate('isInline');
        }
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this._globalStyleSheet.initialize();
        this.applyTheme(this._theme);
    }
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        Theme.unregister(this);
        this._globalStyleSheet.dispose();
    }
    /**
     * @internal
     */
    applyTheme(theme) {
        if (!theme) {
            return;
        }
        this.applyScheme(theme.scheme);
        this.applyPalette(theme.palette);
        this.applyFontFamily(theme.fontFamily);
        this.applyTypography(theme.typography);
        this.applyLayout(theme.layout);
        this.applyElevation(theme.elevation);
    }
    /**
     * @internal
     */
    applyScheme(scheme) {
        const themeName = this.getThemeName();
        Object.entries(scheme).forEach(([key, value]) => {
            Object.entries(value).forEach(([property, cssValue]) => {
                const kebabProperty = this.toKebabCase(property);
                // legacy variable style
                this.setCssVariable(`--${themeName}-scheme-${key}-${kebabProperty}`, cssValue);
                // new variable style
                this.setCssVariable(`--mosaik-scheme-${kebabProperty}`, `var(--${themeName}-scheme-${key}-${kebabProperty}, ${cssValue})`);
            });
        });
    }
    /**
     * @internal
     */
    applyPalette(palette) {
        const themeName = this.getThemeName();
        Object.entries(palette).forEach(([mode, modeValues]) => {
            Object.entries(modeValues).forEach(([paletteName, paletteValues]) => {
                if (!ThemePalette.isThemePalette(paletteValues)) {
                    // legacy variable style
                    this.setCssVariable(`--${themeName}-color-${mode}-${paletteName}`, paletteValues);
                    // new variable style
                    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                    this.setCssVariable(`--mosaik-color-${paletteName}`, `var(--${themeName}-color-${mode}-${paletteName}, ${paletteValues})`);
                    return;
                }
                Object.entries(paletteValues).forEach(([shade, colorValue]) => {
                    const kebabShade = this.toKebabCase(shade);
                    // legacy variable style
                    this.setCssVariable(`--${themeName}-color-${mode}-${paletteName}-${kebabShade}`, colorValue);
                    // new variable style
                    this.setCssVariable(`--mosaik-color-${paletteName}-${kebabShade}`, `var(--${themeName}-color-${mode}-${paletteName}-${kebabShade}, ${colorValue})`);
                });
            });
        });
    }
    /**
     * @internal
     */
    applyFontFamily(fontFamily) {
        const themeName = this.getThemeName();
        const typographyKeys = Object.keys(this._theme?.typography ?? {});
        // legacy variable style
        this.setCssVariable(`--${themeName}-font-family`, fontFamily);
        // new variable style
        this.setCssVariable('--mosaik-font-family', `var(--${themeName}-font-family, ${fontFamily})`);
        typographyKeys.forEach((typographyName) => {
            // legacy variable style
            this.setCssVariable(`--${themeName}-typography-${typographyName}-font-family`, fontFamily);
            // new variable style
            this.setCssVariable(`--mosaik-typography-${typographyName}-font-family`, fontFamily);
        });
    }
    /**
     * @internal
     */
    applyTypography(typography) {
        const themeName = this.getThemeName();
        const fontFamily = this._theme?.fontFamily ?? '';
        Object.entries(typography).forEach(([name, value]) => {
            Object.entries(value).forEach(([property, cssValue]) => {
                const kebabProperty = this.toKebabCase(property);
                // legacy variable style
                this.setCssVariable(`--${themeName}-typography-${name}-${kebabProperty}`, cssValue);
                // new variable style
                this.setCssVariable(`--mosaik-typography-${name}-${kebabProperty}`, `var(--${themeName}-typography-${name}-${kebabProperty}, ${cssValue})`);
            });
            const shorthand = `${value.fontWeight} ${value.fontSize}/${value.lineHeight} ${fontFamily}`;
            // legacy variable style
            this.setCssVariable(`--${themeName}-typography-${name}`, shorthand);
            // new variable style
            this.setCssVariable(`--mosaik-typography-${name}`, `var(--${themeName}-typography-${name}, ${shorthand})`);
        });
    }
    /**
     * @internal
     */
    applyLayout(layout) {
        const themeName = this.getThemeName();
        Object.entries(layout).forEach(([key, value]) => {
            const normalizedValue = this.normalizeCssLength(value);
            const kebabKey = this.toKebabCase(key);
            // legacy variable style
            this.setCssVariable(`--${themeName}-layout-${kebabKey}`, normalizedValue);
            // new variable style
            this.setCssVariable(`--mosaik-layout-${kebabKey}`, `var(--${themeName}-layout-${kebabKey}, ${normalizedValue})`);
        });
    }
    /**
     * @internal
     */
    applyElevation(elevation) {
        const themeName = this.getThemeName();
        Object.entries(elevation).forEach(([level, value]) => {
            Object.entries(value).forEach(([property, cssValue]) => {
                const kebabProperty = this.toKebabCase(property);
                // legacy variable style
                this.setCssVariable(`--${themeName}-elevation-${level}-${kebabProperty}`, cssValue);
                // new variable style
                this.setCssVariable(`--mosaik-elevation-${level}-${kebabProperty}`, `var(--${themeName}-elevation-${level}-${kebabProperty}, ${cssValue})`);
            });
        });
    }
    /**
     * @protected
     */
    onThemePropertyChanged(prev, next) {
        if (prev !== next && next) {
            this.applyTheme(next);
        }
    }
    /**
     * Converts a camelCase string to kebab-case.
     *
     * @private
     */
    toKebabCase(value) {
        return value
            .replace(/([a-z])([A-Z])/g, '$1-$2')
            .replace(/\s+/g, '-')
            .toLowerCase();
    }
    /**
     * Gets the current theme name or empty string.
     *
     * @private
     */
    getThemeName() {
        return this._theme?.name ?? '';
    }
    /**
     * Sets a CSS variable both locally on this element and globally.
     *
     * @private
     */
    setCssVariable(property, value) {
        RendererServiceLocator.current.setStyle(this, property, value);
        this._globalStyleSheet.setVariable(property, value);
        document.documentElement.style.setProperty(property, value);
    }
    /**
     * Normalizes a CssLength value to a px string.
     *
     * @private
     */
    normalizeCssLength(value) {
        if (typeof value === 'number') {
            return `${value}px`;
        }
        if (value === 'auto') {
            throw new Error(`[Theme2Element] The layout property '${value}' must be a px value.`);
        }
        if (CssLength.extractUnit(value) !== 'px') {
            throw new Error(`[Theme2Element] The layout property '${value}' must be a px value.`);
        }
        return value;
    }
};
__decorate([
    Property({ type: Object }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], Theme2Element.prototype, "theme", null);
__decorate([
    Property({ type: Boolean }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], Theme2Element.prototype, "isInline", null);
__decorate([
    Watch('theme'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], Theme2Element.prototype, "onThemePropertyChanged", null);
Theme2Element = __decorate([
    Component({
        selector: 'mosaik-theme2',
        template: theme2ElementTemplate,
        styles: theme2ElementStyle,
        imports: []
    }),
    __metadata("design:paramtypes", [])
], Theme2Element);
export { Theme2Element };
//# sourceMappingURL=Theme2Element.js.map