import { Injectable, signal, computed } from '@angular/core';
import { DrawerMode } from '@progress/kendo-angular-layout';

@Injectable({
    providedIn: 'root'
})
export class LayoutService {
    // Signals for reactive state management
    private readonly windowWidth = signal<number>(typeof window !== 'undefined' ? window.innerWidth : 1024);

    // Computed signals for responsive breakpoints
    public readonly isMobile = computed(() => this.windowWidth() < 768);
    public readonly isTablet = computed(() => this.windowWidth() >= 768 && this.windowWidth() < 1024);
    public readonly isDesktop = computed(() => this.windowWidth() >= 1024);

    // Drawer state
    public readonly drawerExpanded = signal<boolean>(true);
    public readonly drawerMode = computed<DrawerMode>(() =>
        this.isMobile() ? 'overlay' : 'push'
    );
    public readonly drawerAutoCollapse = computed<boolean>(() => this.isMobile());

    constructor() {
        this.initializeResizeListener();
        this.updateDrawerState();
    }

    /**
     * Initialize window resize listener
     */
    private initializeResizeListener(): void {
        if (typeof window !== 'undefined') {
            window.addEventListener('resize', () => this.handleResize());
        }
    }

    /**
     * Handle window resize events
     */
    private handleResize(): void {
        this.windowWidth.set(window.innerWidth);
        this.updateDrawerState();
    }

    /**
     * Update drawer state based on screen size
     */
    private updateDrawerState(): void {
        if (this.isMobile()) {
            this.drawerExpanded.set(false);
        } else {
            this.drawerExpanded.set(true);
        }
    }

    /**
     * Toggle drawer open/closed state
     */
    public toggleDrawer(): void {
        this.drawerExpanded.update(expanded => !expanded);
    }

    /**
     * Close drawer (useful for mobile after navigation)
     */
    public closeDrawer(): void {
        this.drawerExpanded.set(false);
    }

    /**
     * Open drawer
     */
    public openDrawer(): void {
        this.drawerExpanded.set(true);
    }

    /**
     * Get current window width
     */
    public getWindowWidth(): number {
        return this.windowWidth();
    }
}

