class DayNightSystem {
    constructor(scene, timeSystem) {
        this.scene = scene;
        this.timeSystem = timeSystem;

        // Visual overlay
        this.overlay = null;
        this.currentPhase = 'day'; // dawn, day, dusk, night

        this.init();
    }

    init() {
        // No local overlay - using UIScene.overlayGraphics
    }

    update() {
        if (!this.timeSystem) return;

        const hour = this.timeSystem.getCurrentHour();
        const phase = this.getPhase(hour);

        if (phase !== this.currentPhase) {
            this.currentPhase = phase;
            console.log(`🌅 Time of Day: ${phase} (${hour}:00)`);
        }

        this.updateLighting(hour);
    }

    getPhase(hour) {
        if (hour >= 5 && hour < 7) return 'dawn';
        if (hour >= 7 && hour < 18) return 'day';
        if (hour >= 18 && hour < 20) return 'dusk';
        return 'night';
    }

    updateLighting(hour) {
        // Get Shared Overlay from UI Scene
        const uiScene = this.scene.scene.get('UIScene');
        if (!uiScene || !uiScene.overlayGraphics) return;

        const graphics = uiScene.overlayGraphics;

        // IMPORTANT: DayNight is the FIRST system to render to overlay, so it MUST CLEAR it.
        graphics.clear();

        const width = uiScene.scale.width;
        const height = uiScene.scale.height;

        let color = 0x000033; // Default night blue
        let alpha = 0;

        if (hour >= 0 && hour < 5) {
            // Deep Night (0-5h) - Dark blue
            color = 0x000033;
            alpha = 0.6;
        } else if (hour >= 5 && hour < 7) {
            // Dawn (5-7h) - Orange/Pink gradient
            color = 0xFF6B35;
            const progress = (hour - 5) / 2; // 0-1
            alpha = 0.6 - (progress * 0.6); // 0.6 -> 0
        } else if (hour >= 7 && hour < 18) {
            // Day (7-18h) - No overlay (bright)
            alpha = 0;
        } else if (hour >= 18 && hour < 20) {
            // Dusk (18-20h) - Orange/Purple
            color = 0x8B4789;
            const progress = (hour - 18) / 2; // 0-1
            alpha = progress * 0.5; // 0 -> 0.5
        } else if (hour >= 20 && hour < 24) {
            // Night (20-24h) - Dark blue
            color = 0x000033;
            const progress = (hour - 20) / 4; // 0-1
            alpha = 0.5 + (progress * 0.1); // 0.5 -> 0.6
        }

        if (alpha > 0) {
            graphics.fillStyle(color, alpha);
            graphics.fillRect(0, 0, width, height);
        }
    }

    getCurrentPhase() {
        return this.currentPhase;
    }

    isNight() {
        return this.currentPhase === 'night';
    }

    isDay() {
        return this.currentPhase === 'day';
    }
}
