// modules/scroll-dependent/index.js
import { Logger } from '../../core/logger.js';
import { DependencyManager } from '../../core/DependencyManager.js';

// Module definition with explicit dependencies
export const definition = DependencyManager.createDefinition('scroll-dependent', '1.0.0')
    .depends('example-module', '1.0.0')  // Required dependency
    .depends('scrollfx', '1.0.0', true) // Optional dependency
    .provides('scroll-coordination')
    .priority(10); // Lower priority = later initialization

let scrollSubscription = null;
let state = null;

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

    // Register own state
    if (state) {
        state.register('isScrolling', false);
        state.register('scrollDirection', 'none');
        
        // Subscribe to dependency state
        scrollSubscription = state.subscribe('example-module.scrollPosition', (newPos, oldPos) => {
            if (oldPos.y !== newPos.y) {
                const direction = newPos.y > oldPos.y ? 'down' : 'up';
                state.set('scrollDirection', direction);
                state.set('isScrolling', true);
                
                // Reset scrolling state after delay
                setTimeout(() => {
                    if (state) {
                        state.set('isScrolling', false);
                    }
                }, 150);
                
                Logger.info(`[scroll-dependent] Scroll ${direction}: ${newPos.y}`);
            }
        });
    }
}

export function destroy() {
    Logger.info('[scroll-dependent] destroy');
    
    if (scrollSubscription && state) {
        state.unsubscribe(scrollSubscription);
        scrollSubscription = null;
    }
    
    if (state && typeof state.cleanup === 'function') {
        state.cleanup();
    }
    state = null;
}