import { localStorageAPI } from "./localStorage";

// Load settings from localStorage or fallback to defaults
function getAPISettings() {
  const stored = localStorage.getItem("api_settings");
  if (stored) {
    try {
      return JSON.parse(stored);
    } catch (e) {
      console.error("Failed to parse API settings, resetting to defaults:", e);
      localStorage.removeItem("api_settings");
    }
  }

  // Auto-detect hostname from current URL
  const currentHost = window.location.hostname;
  const isLocal = currentHost === "localhost" || currentHost === "127.0.0.1";

  return {
    protocol: window.location.protocol.replace(":", ""), // Use same protocol as page (http/https)
    hostname: isLocal ? "localhost" : currentHost,
    port: isLocal ? "8080" : "", // No port when using DNS (Nginx handles routing)
    useLocalStorage: false,
  };
}

function getAPIBase() {
  const settings = getAPISettings();
  if (settings.useLocalStorage) return null;

  // Build API URL - only include port if specified
  const portPart = settings.port ? `:${settings.port}` : "";
  return `${settings.protocol}://${settings.hostname}${portPart}/api`;
}

// Auto-switch to Backend Mode when API is reachable to avoid stuck Offline
async function ensureBackendMode() {
  try {
    const settings = getAPISettings();
    const portPart = settings.port ? `:${settings.port}` : "";
    const apiHost = `${settings.protocol}://${settings.hostname}${portPart}`;
    const res = await fetch(`${apiHost}/api/health`, { method: "GET" });
    if (res.ok && settings.useLocalStorage) {
      const fixed = { ...settings, useLocalStorage: false };
      localStorage.setItem("api_settings", JSON.stringify(fixed));
      // Notify app to refresh data sources
      window.dispatchEvent(new CustomEvent("settingsFixed", { detail: fixed }));
    }
  } catch (_) {
    // ignore if unreachable; app can still operate in local mode
  }
}

// Run on module load
ensureBackendMode();

// Real-time sync via polling (WebSocket removed - Flask doesn't support WebSockets by default)
// Components will use polling intervals to check for updates

// Quick backend reachability check
export async function pingBackend(timeoutMs = 3000) {
  const settings = getAPISettings();
  if (settings.useLocalStorage) return { online: false };
  const API_BASE = getAPIBase();
  const controller = new AbortController();
  const t = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch(`${API_BASE}/health`, {
      signal: controller.signal,
    });
    clearTimeout(t);
    return { online: res.ok };
  } catch (e) {
    clearTimeout(t);
    return { online: false, error: e.message };
  }
}

// Manual sync trigger: emit event so views can refresh
export async function syncNow() {
  try {
    window.dispatchEvent(new CustomEvent("syncNow"));
    return { ok: true };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

export async function fetchProfiles() {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  // Always include local profiles; merge with backend when online
  const localProfiles = await localStorageAPI.getProfiles();
  if (settings.useLocalStorage) {
    return localProfiles;
  }
  try {
    // Use ETag for conditional requests to reduce bandwidth
    const lastETag = sessionStorage.getItem("profiles_etag");
    const headers = {
      credentials: "include",
    };
    if (lastETag) {
      headers["If-None-Match"] = lastETag;
    }

    const res = await fetch(`${API_BASE}/profiles`, headers);

    // If 304 Not Modified, return cached data
    if (res.status === 304) {
      const cached = sessionStorage.getItem("profiles_cached");
      if (cached) {
        try {
          return JSON.parse(cached);
        } catch (e) {
          // Fall through to refetch
        }
      }
    }

    // Store ETag for next request
    const etag = res.headers.get("ETag");
    if (etag) {
      sessionStorage.setItem("profiles_etag", etag);
    }

    // Check for authentication error
    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return localProfiles;
    }

    const backendProfiles = res.ok ? await res.json() : [];

    // Cache response
    if (backendProfiles.length > 0) {
      sessionStorage.setItem(
        "profiles_cached",
        JSON.stringify(backendProfiles)
      );
    }

    // ID-based deduplication (more reliable than name-based)
    const backendIds = new Set(backendProfiles.map((p) => p.id));
    const extra = localProfiles.filter((lp) => !backendIds.has(lp.id));

    // Sync backend profiles to localStorage in parallel (faster & error-resilient)
    await Promise.allSettled(
      backendProfiles.map((profile) =>
        localStorageAPI.updateProfile(profile.id, profile).catch(() => null)
      )
    );

    return [...backendProfiles, ...extra];
  } catch (err) {
    return localProfiles;
  }
}

export async function createProfile(payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.createProfile(payload);
  }
  try {
    const res = await fetch(`${API_BASE}/profiles`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.createProfile(payload);
    }

    const created = res.ok ? await res.json() : null;
    if (!created) {
      return await localStorageAPI.createProfile(payload);
    }

    // Sync to localStorage with backend ID
    await localStorageAPI.createProfile(created);

    // Invalidate cache
    sessionStorage.removeItem("profiles_etag");
    sessionStorage.removeItem("profiles_cached");

    // Dispatch event to update all components
    window.dispatchEvent(new Event("profileChanged"));

    return created;
  } catch (err) {
    return await localStorageAPI.createProfile(payload);
  }
}

export async function updateProfile(id, payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.updateProfile(id, payload);
  }
  try {
    const res = await fetch(`${API_BASE}/profiles/${id}`, {
      method: "PUT",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.updateProfile(id, payload);
    }

    const updated = res.ok ? await res.json() : null;
    if (!updated) {
      return await localStorageAPI.updateProfile(id, payload);
    }

    console.log("[updateProfile] Updated in backend:", id);
    await localStorageAPI.updateProfile(id, updated);
    console.log("[updateProfile] Synced to localStorage");

    // Invalidate cache
    sessionStorage.removeItem("profiles_etag");
    sessionStorage.removeItem("profiles_cached");

    // Dispatch event to update all components
    window.dispatchEvent(new Event("profileChanged"));

    return updated;
  } catch (err) {
    console.error("[updateProfile] Error:", err);
    return await localStorageAPI.updateProfile(id, payload);
  }
}

export async function deleteProfile(id) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.deleteProfile(id);
  }
  try {
    const res = await fetch(`${API_BASE}/profiles/${id}`, {
      method: "DELETE",
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.deleteProfile(id);
    }

    // Always sync to localStorage regardless of backend response
    await localStorageAPI.deleteProfile(id);

    // Invalidate cache
    sessionStorage.removeItem("profiles_etag");
    sessionStorage.removeItem("profiles_cached");

    // Dispatch event to update all components
    window.dispatchEvent(new Event("profileChanged"));

    return res.ok ? await res.json() : { ok: true };
  } catch (err) {
    return await localStorageAPI.deleteProfile(id);
  }
}

export async function searchLocalSongs(q = "") {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  const localSongs = await localStorageAPI.getSongs(q);
  if (settings.useLocalStorage) {
    return localSongs;
  }
  try {
    const res = await fetch(`${API_BASE}/songs?q=${encodeURIComponent(q)}`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return localSongs;
    }

    const backendSongs = res.ok ? await res.json() : [];
    // Dedupe by title+artist
    const key = (s) =>
      `${(s.title || "").trim().toLowerCase()}|${(s.artist || "")
        .trim()
        .toLowerCase()}`;
    const seen = new Set(backendSongs.map(key));
    const extra = localSongs.filter((s) => !seen.has(key(s)));
    return [...backendSongs, ...extra];
  } catch (err) {
    return localSongs;
  }
}

export async function getSong(id) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.getSong(id);
  }
  try {
    const res = await fetch(`${API_BASE}/songs/${id}`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.getSong(id);
    }

    if (!res.ok) throw new Error("API Error");
    return res.json();
  } catch (err) {
    return await localStorageAPI.getSong(id);
  }
}

// Fetch song from both sources and merge fields
export async function getSongMerged(id) {
  const settings = getAPISettings();
  if (settings.useLocalStorage) {
    return await localStorageAPI.getSong(id);
  }
  const API_BASE = getAPIBase();
  let backend = null;
  try {
    const res = await fetch(`${API_BASE}/songs/${id}`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.getSong(id);
    }

    backend = res.ok ? await res.json() : null;
  } catch (e) {}
  const local = await localStorageAPI.getSong(id);
  if (!backend) return local;
  if (!local) return backend;
  // Merge with preference for non-empty fields
  return {
    id: backend.id || local.id,
    title: backend.title || local.title || "",
    artist: backend.artist || local.artist || "",
    band: backend.band || local.band || "",
    lyrics: backend.lyrics || local.lyrics || "",
    chords: backend.chords || local.chords || "",
    singer: backend.singer || local.singer || "",
    created_at: backend.created_at || local.created_at,
    updated_at: backend.updated_at || local.updated_at,
  };
}

export async function saveSong(id, payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.updateSong(id, payload);
  }
  try {
    const res = await fetch(`${API_BASE}/songs/${id}`, {
      method: "PUT",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.updateSong(id, payload);
    }

    const updated = res.ok ? await res.json() : null;
    await localStorageAPI.updateSong(id, updated ?? payload);
    return updated ?? payload;
  } catch (err) {
    return await localStorageAPI.updateSong(id, payload);
  }
}

export async function deleteSong(id) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.deleteSong(id);
  }
  try {
    const res = await fetch(`${API_BASE}/songs/${id}`, {
      method: "DELETE",
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.deleteSong(id);
    }

    await localStorageAPI.deleteSong(id);
    return res.ok ? await res.json() : { ok: true };
  } catch (err) {
    return await localStorageAPI.deleteSong(id);
  }
}

export async function createSong(payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.createSong(payload);
  }
  try {
    const res = await fetch(`${API_BASE}/songs`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.createSong(payload);
    }

    const created = res.ok ? await res.json() : null;
    await localStorageAPI.createSong(created ?? payload);
    return created ?? payload;
  } catch (err) {
    return await localStorageAPI.createSong(payload);
  }
}

export async function searchExternal(q = "", filterType = "all") {
  const API_BASE = getAPIBase();
  const res = await fetch(
    `${API_BASE}/external/search?q=${encodeURIComponent(
      q
    )}&filter=${filterType}`,
    { credentials: "include" }
  );
  return res.json();
}

export async function searchEssentialWorship(q = "") {
  const API_BASE = getAPIBase();
  const res = await fetch(
    `${API_BASE}/essentialworship/search?q=${encodeURIComponent(q)}`
  );
  return res.json();
}

export async function fetchEssentialWorshipLyrics(url = "") {
  const API_BASE = getAPIBase();
  const res = await fetch(
    `${API_BASE}/essentialworship/lyrics?url=${encodeURIComponent(url)}`
  );
  return res.json();
}

export async function fetchPlans() {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  const localPlans = await localStorageAPI.getPlans();
  if (settings.useLocalStorage) {
    return localPlans;
  }
  try {
    // Add cache busting to ensure fresh data
    const res = await fetch(`${API_BASE}/plans?_t=${Date.now()}`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return localPlans;
    }

    const backendPlans = res.ok ? await res.json() : [];

    // Use ID-based deduplication instead of date+notes to prevent duplicates
    const planMap = new Map();

    // Backend plans take priority
    backendPlans.forEach((p) => {
      if (p.id) planMap.set(p.id, p);
    });

    // Only add local plans that don't exist in backend
    localPlans.forEach((p) => {
      if (p.id && !planMap.has(p.id)) {
        planMap.set(p.id, p);
      }
    });

    return Array.from(planMap.values());
  } catch (err) {
    return localPlans;
  }
}

export async function createPlan(payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.createPlan(payload);
  }
  try {
    const res = await fetch(`${API_BASE}/plans`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.createPlan(payload);
    }

    const created = res.ok ? await res.json() : null;
    await localStorageAPI.createPlan(created ?? payload);
    return created ?? payload;
  } catch (err) {
    return await localStorageAPI.createPlan(payload);
  }
}

export async function fetchPlanSongs(planId) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  const local = await localStorageAPI.getPlanSongs(planId);
  if (settings.useLocalStorage) {
    return local;
  }
  try {
    const res = await fetch(`${API_BASE}/plans/${planId}/songs`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return local;
    }

    const backend = res.ok ? await res.json() : [];
    // Dedupe by song_id+order_index
    const key = (ps) => `${ps.song_id}|${ps.order_index}`;
    const seen = new Set(backend.map(key));
    const extra = local.filter((ps) => !seen.has(key(ps)));
    return [...backend, ...extra].sort(
      (a, b) => (a.order_index || 0) - (b.order_index || 0)
    );
  } catch (err) {
    return local;
  }
}

export async function addSongToPlan(planId, payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.addSongToPlan(planId, payload);
  }
  try {
    const url = `${API_BASE}/plans/${planId}/songs`;
    const res = await fetch(url, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.addSongToPlan(planId, payload);
    }

    const created = res.ok ? await res.json() : null;
    // Mirror to local
    await localStorageAPI.addSongToPlan(planId, payload);
    return created ?? payload;
  } catch (err) {
    return await localStorageAPI.addSongToPlan(planId, payload);
  }
}

export async function updatePlan(id, payload) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.updatePlan(id, payload);
  }
  try {
    const url = `${API_BASE}/plans/${id}`;
    const res = await fetch(url, {
      method: "PUT",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.updatePlan(id, payload);
    }

    const updated = res.ok ? await res.json() : null;
    await localStorageAPI.updatePlan(id, updated ?? payload);
    return updated ?? payload;
  } catch (err) {
    return await localStorageAPI.updatePlan(id, payload);
  }
}

export async function deletePlan(id) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();

  if (settings.useLocalStorage) {
    return await localStorageAPI.deletePlan(id);
  }

  try {
    const res = await fetch(`${API_BASE}/plans/${id}`, {
      method: "DELETE",
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      await localStorageAPI.deletePlan(id);
      return { ok: true };
    }

    if (!res.ok) {
      throw new Error("Backend delete failed");
    }

    await localStorageAPI.deletePlan(id);

    return await res.json();
  } catch (err) {
    // If backend fails, still try to delete from localStorage
    await localStorageAPI.deletePlan(id);
    return { ok: true };
  }
}

export async function uploadLyricFile(file, meta = {}) {
  const API_BASE = getAPIBase();
  const fd = new FormData();
  fd.append("file", file);
  if (meta.title) fd.append("title", meta.title);
  if (meta.artist) fd.append("artist", meta.artist);
  if (meta.band) fd.append("band", meta.band);
  const res = await fetch(`${API_BASE}/upload_lyric`, {
    method: "POST",
    credentials: "include",
    body: fd,
  });

  if (res.status === 401) {
    window.dispatchEvent(
      new CustomEvent("authError", { detail: "Authentication required" })
    );
    throw new Error("Authentication required");
  }

  return res.json();
}

export function exportPlanURL(planId) {
  const API_BASE = getAPIBase();
  return `${API_BASE}/export/${planId}`;
}

export async function getProfileSongs(profileId) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  const local = await localStorageAPI.getProfileSongs(profileId);
  if (settings.useLocalStorage) {
    return local;
  }
  try {
    const res = await fetch(`${API_BASE}/profiles/${profileId}/songs`, {
      credentials: "include",
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return local;
    }
    const backend = res.ok ? await res.json() : [];

    // NEW: Backend now returns full song objects directly (optimized single query)
    // No need for individual song fetches - massive performance improvement!
    if (backend.length && backend[0] && backend[0].title) {
      // Backend already returns complete song data with keys
      const key = (s) => s.id;
      const seen = new Set(backend.map(key));
      const extra = local.filter((s) => !seen.has(key(s)));
      return [...backend, ...extra];
    }

    // Fallback: Old format (associations only) - for backwards compatibility
    if (backend.length && backend[0] && backend[0].song_id) {
      const fullSongs = [];
      for (const ps of backend) {
        let song = await localStorageAPI.getSong(ps.song_id);
        if (!song) {
          try {
            const r = await fetch(`${API_BASE}/songs/${ps.song_id}`);
            if (r.ok) song = await r.json();
          } catch {}
        }
        if (song) fullSongs.push(song);
      }
      const seen = new Set(fullSongs.map((s) => s.id));
      const extra = local.filter((s) => !seen.has(s.id));
      return [...fullSongs, ...extra];
    }

    // Empty or merge with local
    const key = (s) => s.id;
    const seen = new Set(backend.map(key));
    const extra = local.filter((s) => !seen.has(key(s)));
    return [...backend, ...extra];
  } catch (err) {
    return local;
  }
}

export async function addSongToProfile(profileId, songId) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.addSongToProfile(profileId, songId);
  }
  try {
    const res = await fetch(`${API_BASE}/profiles/${profileId}/songs`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ song_id: songId }),
    });

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.addSongToProfile(profileId, songId);
    }

    const created = res.ok ? await res.json() : null;
    await localStorageAPI.addSongToProfile(profileId, songId);
    return created ?? { profile_id: profileId, song_id: songId };
  } catch (err) {
    return await localStorageAPI.addSongToProfile(profileId, songId);
  }
}

export async function removeSongFromProfile(profileId, songId) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.removeSongFromProfile(profileId, songId);
  }
  try {
    const res = await fetch(
      `${API_BASE}/profiles/${profileId}/songs/${songId}`,
      {
        method: "DELETE",
        credentials: "include",
      }
    );

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.removeSongFromProfile(profileId, songId);
    }

    await localStorageAPI.removeSongFromProfile(profileId, songId);
    return res.ok ? await res.json() : { ok: true };
  } catch (err) {
    return await localStorageAPI.removeSongFromProfile(profileId, songId);
  }
}

export async function getProfileSongKey(profileId, songId) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.getProfileSongKey(profileId, songId);
  }
  try {
    const res = await fetch(
      `${API_BASE}/profiles/${profileId}/songs/${songId}/key`,
      { credentials: "include" }
    );

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.getProfileSongKey(profileId, songId);
    }

    const data = res.ok ? await res.json() : { key: null };
    // Prefer backend key, fallback to local
    const localKey = await localStorageAPI.getProfileSongKey(profileId, songId);
    return data.key ?? localKey;
  } catch (err) {
    const localKey = await localStorageAPI.getProfileSongKey(profileId, songId);
    return localKey;
  }
}

export async function saveProfileSongKey(profileId, songId, key) {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    return await localStorageAPI.saveProfileSongKey(profileId, songId, key);
  }
  try {
    const res = await fetch(
      `${API_BASE}/profiles/${profileId}/songs/${songId}/key`,
      {
        method: "PUT",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ key }),
      }
    );

    if (res.status === 401) {
      window.dispatchEvent(
        new CustomEvent("authError", { detail: "Authentication required" })
      );
      return await localStorageAPI.saveProfileSongKey(profileId, songId, key);
    }

    const updated = res.ok ? await res.json() : { key };
    await localStorageAPI.saveProfileSongKey(profileId, songId, updated.key);
    return updated;
  } catch (err) {
    return await localStorageAPI.saveProfileSongKey(profileId, songId, key);
  }
}

export async function clearProfileSelection() {
  const settings = getAPISettings();
  const API_BASE = getAPIBase();
  if (settings.useLocalStorage) {
    // In offline mode, just dispatch local event
    window.dispatchEvent(new CustomEvent("profileSelectionCleared"));
    return;
  }
  try {
    await fetch(`${API_BASE}/profile-selection/clear`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
    });
  } catch (err) {
    // Still dispatch locally even if server call fails
    window.dispatchEvent(new CustomEvent("profileSelectionCleared"));
  }
}
