import { Dashboard } from './modules/dashboard.js';
import { WaterView } from './modules/views/WaterView.js';
import { FitnessView } from './modules/views/FitnessView.js';
import { SleepView } from './modules/views/SleepView.js';
import { GoalsView } from './modules/views/GoalsView.js';
import { NotesView } from './modules/views/NotesView.js';

class App {
    constructor() {
        this.appContainer = document.getElementById('app');
        this.currentView = null;
        this.routes = {
            'dashboard': Dashboard,
            'water-detail': WaterView,
            'fitness-detail': FitnessView,
            'sleep-detail': SleepView,
            'goals-detail': GoalsView,
            'notes-detail': NotesView
        };

        // Handle browser back button
        window.addEventListener('popstate', (e) => {
            if (e.state && e.state.view) {
                this.render(e.state.view, e.state.params);
            } else {
                this.render('dashboard');
            }
        });

        this.init();
    }

    init() {
        console.log('HydroFlux Router Initialized');
        this.navigateTo('dashboard');
    }

    navigateTo(viewName, params = {}) {
        history.pushState({ view: viewName, params }, '', `#${viewName}`);
        this.render(viewName, params);
    }

    back() {
        // history.back() can be tricky if state isn't perfect, safer to just go dashboard for now
        this.navigateTo('dashboard');
    }

    async render(viewName, params) {
        // Cleanup current view if needed (optional destroy method)
        if (this.currentView && typeof this.currentView.destroy === 'function') {
            this.currentView.destroy();
        }

        this.appContainer.innerHTML = ''; // Clear container

        const ViewClass = this.routes[viewName] || this.routes['dashboard'];

        // Dynamic Import for Views (if we wanted lazy loading, but consistent imports are easier for now)
        // For now, we instantiate directly.

        this.currentView = new ViewClass('app', this, params);
        // Note: Dashboard expects (containerId, app). We'll keep that signature.
    }
}

// Start App
const app = new App();

// Global health bridge listener
window.addEventListener('health-update', (e) => {
    console.log('Health Update Received:', e.detail);
});
