export async function apiFetch(url, token, options = {}) {
  const headers = { "Content-Type": "application/json", ...options.headers };
  if (token) headers["Authorization"] = `Bearer ${token}`;
  
  const res = await fetch(url, { 
    ...options, 
    headers,
    credentials: 'include'
  });
  
  const text = await res.text();
  
  // 401 = Token abgelaufen → automatisch refreshen
  if (res.status === 401) {
    console.log("Token expired (401) - attempting refresh...");
    
    try {
      // Versuche neuen Access-Token zu generieren
      const refreshRes = await fetch("/auth/refresh", {
        method: "POST",
        credentials: "include"
      });
      
      if (refreshRes.ok) {
        console.log("Token refreshed successfully");
        
        // Retry original request mit neuem Token
        const retryRes = await fetch(url, { 
          ...options, 
          headers,
          credentials: 'include'
        });
        
        const retryText = await retryRes.text();
        
        if (!retryRes.ok) {
          throw new Error(`HTTP ${retryRes.status}: ${retryText}`);
        }
        
        try {
          return JSON.parse(retryText);
        } catch {
          return retryText;
        }
      } else {
        // Refresh fehlgeschlagen → logout
        console.log("Refresh failed - logging out");
        window.location.href = "/pages/login";
        return;
      }
    } catch (err) {
      console.error("Refresh error:", err);
      window.location.href = "/pages/login";
      return;
    }
  }
  
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}: ${text}`);
  }
  
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}
