import * as i0 from '@angular/core';
import { inject, PLATFORM_ID, DOCUMENT, DestroyRef, effect, TemplateRef, Directive, ViewContainerRef, contentChild, computed, output, ChangeDetectionStrategy, Component } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { signalStore, withState, withMethods, patchState, withHooks } from '@ngrx/signals';
import { TemplatePortal, CdkPortalOutlet } from '@angular/cdk/portal';
import { Button } from '@ngstarter-ui/components/button';

const COLOR_SCHEME_LOCAL_KEY = 'ngstarter-color-scheme';

const initialState = {
    theme: 'auto',
    resolvedTheme: 'light',
};
const ColorSchemeStore = signalStore(withState(initialState), withMethods((store) => {
    const platformId = inject(PLATFORM_ID);
    const document = inject(DOCUMENT);
    const resolveScheme = (scheme) => {
        if (scheme !== 'auto') {
            return scheme;
        }
        const media = document.defaultView?.matchMedia?.('(prefers-color-scheme: dark)');
        return media?.matches ? 'dark' : 'light';
    };
    return {
        setScheme(scheme) {
            patchState(store, {
                theme: scheme,
                resolvedTheme: resolveScheme(scheme),
            });
            if (isPlatformBrowser(platformId)) {
                localStorage.setItem(COLOR_SCHEME_LOCAL_KEY, scheme);
            }
        },
    };
}), withHooks({
    onInit(store) {
        const document = inject(DOCUMENT);
        const platformId = inject(PLATFORM_ID);
        const destroyRef = inject(DestroyRef);
        const media = document.defaultView?.matchMedia?.('(prefers-color-scheme: dark)');
        if (isPlatformBrowser(platformId) && media) {
            const updateResolvedScheme = () => {
                if (store.theme() === 'auto') {
                    patchState(store, { resolvedTheme: media.matches ? 'dark' : 'light' });
                }
            };
            updateResolvedScheme();
            media.addEventListener('change', updateResolvedScheme);
            destroyRef.onDestroy(() => media.removeEventListener('change', updateResolvedScheme));
        }
        effect(() => {
            const scheme = store.theme();
            const resolvedScheme = scheme === 'auto' ? store.resolvedTheme() : scheme;
            if (resolvedScheme === 'dark') {
                document.documentElement.classList.add('dark');
            }
            else if (resolvedScheme === 'light') {
                document.documentElement.classList.remove('dark');
            }
            document.documentElement.setAttribute('data-ngs-color-scheme', scheme);
            document.documentElement.setAttribute('data-ngs-resolved-color-scheme', resolvedScheme);
        });
    },
}));

class ColorSchemeLightDirective {
    templateRef = inject(TemplateRef);
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeLightDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: ColorSchemeLightDirective, isStandalone: true, selector: "[ngsColorSchemeLight]", ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeLightDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsColorSchemeLight]'
                }]
        }] });

class ColorSchemeDarkDirective {
    templateRef = inject(TemplateRef);
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeDarkDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: ColorSchemeDarkDirective, isStandalone: true, selector: "[ngsColorSchemeDark]", ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeDarkDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsColorSchemeDark]'
                }]
        }] });

class ColorSchemeAutoDirective {
    templateRef = inject(TemplateRef);
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeAutoDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: ColorSchemeAutoDirective, isStandalone: true, selector: "[ngsColorSchemeAuto]", ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeAutoDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsColorSchemeAuto]'
                }]
        }] });

class ColorSchemeSwitcher {
    store = inject(ColorSchemeStore);
    viewContainerRef = inject(ViewContainerRef);
    lightRef = contentChild(ColorSchemeLightDirective, ...(ngDevMode ? [{ debugName: "lightRef" }] : /* istanbul ignore next */ []));
    darkRef = contentChild(ColorSchemeDarkDirective, ...(ngDevMode ? [{ debugName: "darkRef" }] : /* istanbul ignore next */ []));
    autoRef = contentChild(ColorSchemeAutoDirective, ...(ngDevMode ? [{ debugName: "autoRef" }] : /* istanbul ignore next */ []));
    colorScheme = computed(() => this.store.theme(), ...(ngDevMode ? [{ debugName: "colorScheme" }] : /* istanbul ignore next */ []));
    resolvedColorScheme = computed(() => this.store.resolvedTheme(), ...(ngDevMode ? [{ debugName: "resolvedColorScheme" }] : /* istanbul ignore next */ []));
    colorSchemeChanged = output();
    portal = null;
    constructor() {
        effect(() => {
            this.colorScheme();
            this.resolvedColorScheme();
            this.lightRef();
            this.darkRef();
            this.autoRef();
            this.setPortal();
        });
    }
    toggleScheme() {
        const order = ['light', 'dark', 'auto'];
        const currentIndex = order.indexOf(this.store.theme());
        const newScheme = order[(currentIndex + 1) % order.length];
        this.store.setScheme(newScheme);
        this.setPortal();
        this.colorSchemeChanged.emit(this.store.theme());
    }
    setPortal() {
        const lightRef = this.lightRef();
        const darkRef = this.darkRef();
        const autoRef = this.autoRef();
        if (this.colorScheme() === 'auto' && autoRef) {
            this.portal = new TemplatePortal(autoRef.templateRef, this.viewContainerRef);
        }
        else if (this.resolvedColorScheme() === 'light' && lightRef) {
            this.portal = new TemplatePortal(lightRef.templateRef, this.viewContainerRef);
        }
        else if (this.resolvedColorScheme() === 'dark' && darkRef) {
            this.portal = new TemplatePortal(darkRef.templateRef, this.viewContainerRef);
        }
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeSwitcher, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: ColorSchemeSwitcher, isStandalone: true, selector: "ngs-color-scheme-switcher", outputs: { colorSchemeChanged: "colorSchemeChanged" }, host: { attributes: { "ngSkipHydration": "true" }, classAttribute: "ngs-color-scheme-switcher" }, queries: [{ propertyName: "lightRef", first: true, predicate: ColorSchemeLightDirective, descendants: true, isSignal: true }, { propertyName: "darkRef", first: true, predicate: ColorSchemeDarkDirective, descendants: true, isSignal: true }, { propertyName: "autoRef", first: true, predicate: ColorSchemeAutoDirective, descendants: true, isSignal: true }], exportAs: ["ngsColorSchemeSwitcher"], ngImport: i0, template: "<button ngsIconButton (click)=\"toggleScheme()\">\n  @if (portal) {\n    <ng-container [cdkPortalOutlet]=\"portal\"/>\n  }\n</button>\n", styles: [":host{display:block;width:max-content}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "directive", type: CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { kind: "component", type: Button, selector: "    button[ngsButton], button[ngsIconButton],    a[ngsButton], a[ngsIconButton]  ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ColorSchemeSwitcher, decorators: [{
            type: Component,
            args: [{ selector: 'ngs-color-scheme-switcher', exportAs: 'ngsColorSchemeSwitcher', imports: [
                        CdkPortalOutlet,
                        Button,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        'class': 'ngs-color-scheme-switcher',
                        ngSkipHydration: 'true' // important! to prevent double render for icons
                    }, template: "<button ngsIconButton (click)=\"toggleScheme()\">\n  @if (portal) {\n    <ng-container [cdkPortalOutlet]=\"portal\"/>\n  }\n</button>\n", styles: [":host{display:block;width:max-content}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"] }]
        }], ctorParameters: () => [], propDecorators: { lightRef: [{ type: i0.ContentChild, args: [i0.forwardRef(() => ColorSchemeLightDirective), { isSignal: true }] }], darkRef: [{ type: i0.ContentChild, args: [i0.forwardRef(() => ColorSchemeDarkDirective), { isSignal: true }] }], autoRef: [{ type: i0.ContentChild, args: [i0.forwardRef(() => ColorSchemeAutoDirective), { isSignal: true }] }], colorSchemeChanged: [{ type: i0.Output, args: ["colorSchemeChanged"] }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { COLOR_SCHEME_LOCAL_KEY, ColorSchemeAutoDirective, ColorSchemeDarkDirective, ColorSchemeLightDirective, ColorSchemeStore, ColorSchemeSwitcher };
//# sourceMappingURL=ngstarter-ui-components-color-scheme.mjs.map
