// DSS Team Portal - State Bridge & Token Synchronizer
import { subscribe } from './store.js';
import { camera } from './scene.js';
import { updateCrystalColor } from './scene.js';
import gsap from 'gsap';

const uiContainer = document.getElementById('ui-container');

function initializeBridge() {
    // 1. StateBridge: Subscribe to store changes and trigger animations
    subscribe((state) => {
        const { viewState } = state;

        if (viewState === 'TRANSITION_TO_2D') {
            gsap.to(camera.position, {
                duration: 1.5,
                z: 10, // Dolly out
                ease: 'power2.inOut',
            });
            gsap.to(uiContainer, {
                duration: 1.5,
                opacity: 1,
                y: 0,
                ease: 'power2.inOut',
                onComplete: () => store.getState().actions.setViewState('2D_WORKBENCH')
            });
        }

        if (viewState === 'TRANSITION_TO_3D') {
            gsap.to(camera.position, {
                duration: 1.5,
                z: 5, // Dolly in
                ease: 'power2.inOut',
            });
            gsap.to(uiContainer, {
                duration: 1.5,
                opacity: 0,
                y: 20,
                ease: 'power2.inOut',
                onComplete: () => store.getState().actions.setViewState('3D_HOME')
            });
        }
    });

    // Set initial UI state
    gsap.set(uiContainer, { opacity: 0, y: 20 });
}

function initializeTokenSynchronizer() {
    // 2. TokenSynchronizer: Sync theme colors to the 3D scene
    const sync = () => {
        const style = getComputedStyle(document.body);
        const primaryColor = style.getPropertyValue('--color-primary').trim();
        if (primaryColor) {
            updateCrystalColor(primaryColor);
        }
    };

    // Sync on init
    sync();

    // Sync when theme changes
    subscribe((state, prevState) => {
        if (state.theme !== prevState.theme) {
            document.body.dataset.theme = state.theme;
            // Allow time for CSS to apply
            setTimeout(sync, 50); 
        }
    });
    
    // Set initial theme
    document.body.dataset.theme = store.getState().theme;
}

export { initializeBridge, initializeTokenSynchronizer };
