// modules/example-module/index.js
import { registerFrameTask, unregisterFrameTask } from '../../core/frameloop.js';
import { Logger } from '../../core/logger.js';

let frameId = 'example-module';
let resizeHandler = null;
let state = null;

/**
 * Initialize example module with state management
 * @param {Object} config - Module configuration
 * @param {Object} stateManager - Scoped state manager
 */
export function init(config = {}, stateManager = null) {
    Logger.info('[example-module] init');
    state = stateManager;

    // Register module state
    if (state) {
        state.register('windowSize', { width: window.innerWidth, height: window.innerHeight });
        state.register('scrollPosition', { x: 0, y: 0 });
        state.register('isVisible', true);
        
        // Example: Subscribe to global app state (if exists)
        // state.subscribe('app.theme', (theme) => {
        //     Logger.info(`[example-module] Theme changed to: ${theme}`);
        // });
    }

    // Event-Listener mit State-Updates
    resizeHandler = () => {
        const newSize = { width: window.innerWidth, height: window.innerHeight };
        Logger.info('Fenstergröße geändert:', newSize);
        
        if (state) {
            state.set('windowSize', newSize);
        }
    };
    window.addEventListener('resize', resizeHandler);

    // Frame-Logik mit State-Updates
    registerFrameTask(frameId, () => {
        const scrollY = window.scrollY;
        const scrollX = window.scrollX;
        
        if (state) {
            const currentScroll = state.get('scrollPosition');
            if (currentScroll.x !== scrollX || currentScroll.y !== scrollY) {
                state.set('scrollPosition', { x: scrollX, y: scrollY });
            }
        }
    }, { autoStart: true });
}

export function destroy() {
    Logger.info('[example-module] destroy');

    // EventListener entfernen
    if (resizeHandler) {
        window.removeEventListener('resize', resizeHandler);
        resizeHandler = null;
    }

    // FrameTask entfernen
    unregisterFrameTask(frameId);

    // State cleanup
    if (state && typeof state.cleanup === 'function') {
        state.cleanup();
    }
    state = null;
}