// Re-export all navigation utilities from shared
pub use rustelo_core_lib::utils::nav::*;
// Re-export console logging macros from shared for backward compatibility
pub use rustelo_core_lib::{safe_console_error, safe_console_log, safe_console_warn};
use serde::{Deserialize, Serialize};

// Hydration debugging module
pub mod hydration_debug;

// Re-export highlight utilities for easy access
pub use crate::highlight::*;

/// Generic API request function for making HTTP requests to the server
pub async fn api_request<T, R>(
    url: &str,
    method: &str,
    body: Option<T>,
) -> Result<R, Box<dyn std::error::Error>>
where
    T: Serialize,
    R: for<'de> Deserialize<'de>,
{
    let mut request = reqwasm::http::Request::new(url);
    request = match method {
        "GET" => request.method(reqwasm::http::Method::GET),
        "POST" => request.method(reqwasm::http::Method::POST),
        "PUT" => request.method(reqwasm::http::Method::PUT),
        "DELETE" => request.method(reqwasm::http::Method::DELETE),
        "PATCH" => request.method(reqwasm::http::Method::PATCH),
        _ => request.method(reqwasm::http::Method::GET),
    };
    request = request.header("Content-Type", "application/json");

    // Add auth token if available
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            if let Ok(Some(token)) = storage.get_item("auth_token") {
                request = request.header("Authorization", &format!("Bearer {token}"));
            }
        }
    }

    // Add body if provided
    if let Some(body) = body {
        let body_str = serde_json::to_string(&body)?;
        request = request.body(body_str);
    }

    let response = request.send().await?;

    if response.ok() {
        let json_response = response.json::<R>().await?;
        Ok(json_response)
    } else {
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        Err(format!("API request failed: {error_text}").into())
    }
}
