const AUTH_KEY = 'aetherforge_auth';

export function getStoredAuth(): string | null {
  try {
    return sessionStorage.getItem(AUTH_KEY);
  } catch {
    return null;
  }
}

export function setStoredAuth(username: string, password: string, opts?: { silent?: boolean }) {
  const token = btoa(`${username}:${password}`);
  sessionStorage.setItem(AUTH_KEY, token);
  if (!opts?.silent) {
    window.dispatchEvent(new Event('aetherforge-auth'));
  }
}

export function clearStoredAuth(opts?: { silent?: boolean }) {
  sessionStorage.removeItem(AUTH_KEY);
  if (!opts?.silent) {
    window.dispatchEvent(new Event('aetherforge-auth'));
  }
}

export function authHeaders(): Record<string, string> {
  const token = getStoredAuth();
  if (!token) return {};
  return { Authorization: `Basic ${token}` };
}
