//! WASM-specific async loading functionality
//!
//! Handles asynchronous loading of meta configurations in the browser

#[cfg(all(target_arch = "wasm32", not(feature = "ssr")))]
use crate::categories::cache::{MetaConfig, META_CACHE};

/// DEPRECATED: Legacy meta config loading - replaced by filter component direct
/// loading This function is now a no-op to prevent conflicts with the new
/// filter system
#[cfg(all(target_arch = "wasm32", not(feature = "ssr")))]
pub fn initiate_meta_config_loading(_content_type: &str, _language: &str, _cache_key: String) {
    // No-op: Filter component now handles data loading directly from
    // /r/{content_type}/{language}/filter-index.json This prevents 400 errors
    // from trying to load /api/content/meta/{content_type}/{language}
    tracing::debug!("Meta config loading skipped - filter component handles data loading directly");
}

/// Async fetch for meta config (WASM only)
#[cfg(target_arch = "wasm32")]
async fn fetch_meta_config_async(url: &str) -> Result<MetaConfig, String> {
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;
    use web_sys::{Request, RequestInit, RequestMode, Response};

    let opts = RequestInit::new();
    opts.set_method("GET");
    opts.set_mode(RequestMode::SameOrigin);

    let request = Request::new_with_str_and_init(url, &opts)
        .map_err(|e| format!("Failed to create request: {:?}", e))?;

    let window = web_sys::window().ok_or("No window available")?;
    let resp_value = JsFuture::from(window.fetch_with_request(&request))
        .await
        .map_err(|e| format!("Fetch failed: {:?}", e))?;

    let resp: Response = resp_value
        .dyn_into()
        .map_err(|_| "Failed to cast to Response")?;

    if !resp.ok() {
        return Err(format!("HTTP error: {}", resp.status()));
    }

    let json = JsFuture::from(
        resp.json()
            .map_err(|e| format!("Failed to get JSON: {:?}", e))?,
    )
    .await
    .map_err(|e| format!("JSON parsing failed: {:?}", e))?;

    let config: MetaConfig = serde_wasm_bindgen::from_value(json)
        .map_err(|e| format!("Failed to deserialize MetaConfig: {:?}", e))?;

    Ok(config)
}

// Stub functions for non-WASM builds or SSR to satisfy imports
#[cfg(any(not(target_arch = "wasm32"), feature = "ssr"))]
pub fn initiate_meta_config_loading(_content_type: &str, _language: &str, _cache_key: String) {
    // No-op on server or during SSR
}
