// Configuration module for VAPORA frontend
// Handles API URL detection and environment configuration

/// Application configuration
#[derive(Debug, Clone)]
pub struct AppConfig {
    pub api_url: String,
}

impl AppConfig {
    /// Load configuration from environment or auto-detect
    pub fn load() -> Self {
        let api_url = Self::detect_api_url();
        Self { api_url }
    }

    /// Detect API URL based on current location
    fn detect_api_url() -> String {
        // Try to get current window location
        if let Some(window) = web_sys::window() {
            if let Ok(location) = window.location().href() {
                // If running on localhost:3000, point to backend on :8080
                if location.contains("localhost:3000") || location.contains("127.0.0.1:3000") {
                    return "http://localhost:8080".to_string();
                }

                // For production, use same host with /api prefix
                if let Some(origin) = location.split('/').take(3).collect::<Vec<_>>().get(..3) {
                    let base = origin.join("/");
                    return format!("{}/api", base);
                }
            }
        }

        // Fallback to localhost
        "http://localhost:8080".to_string()
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        Self::load()
    }
}
