import { fetchProfile, updateProfile as updateProfileApi, type ProfileSettings } from "@/lib/api/settings";

const CACHE_KEY = "nexus-profile";

export type UserProfile = {
  name: string;
  avatar: string; // base64 data URI or empty
  platformName: string;
  platformSubtitle: string;
  botName: string;
  botAvatar: string; // base64 data URI or empty
};

const defaults: UserProfile = {
  name: "",
  avatar: "",
  platformName: "Track Platform",
  platformSubtitle: "Nexus System",
  botName: "Nexus Platform Core",
  botAvatar: "",
};

/** Convert backend snake_case → frontend camelCase */
function fromApi(s: ProfileSettings): UserProfile {
  return {
    name: s.name,
    avatar: s.avatar,
    platformName: s.platform_name,
    platformSubtitle: s.platform_subtitle,
    botName: s.bot_name,
    botAvatar: s.bot_avatar,
  };
}

/** Convert frontend camelCase → backend snake_case */
function toApi(p: UserProfile): ProfileSettings {
  return {
    name: p.name,
    avatar: p.avatar,
    platform_name: p.platformName,
    platform_subtitle: p.platformSubtitle,
    bot_name: p.botName,
    bot_avatar: p.botAvatar,
  };
}

/** Load profile from localStorage cache (sync, for initial render) */
export function loadProfile(): UserProfile {
  if (typeof window === "undefined") return defaults;
  try {
    const raw = localStorage.getItem(CACHE_KEY);
    return raw ? { ...defaults, ...JSON.parse(raw) } : defaults;
  } catch {
    return defaults;
  }
}

/** Fetch profile from backend and update cache */
export async function loadProfileFromServer(): Promise<UserProfile> {
  try {
    const data = await fetchProfile();
    const profile = fromApi(data);
    localStorage.setItem(CACHE_KEY, JSON.stringify(profile));
    return profile;
  } catch {
    return loadProfile();
  }
}

/** Save profile to backend and update cache */
export async function saveProfile(profile: UserProfile): Promise<void> {
  localStorage.setItem(CACHE_KEY, JSON.stringify(profile));
  await updateProfileApi(toApi(profile));
}
