const PROGRESS_KEY = "codetutor-progress";
const SOLUTIONS_KEY = "codetutor-solutions";

export function getCompletedQuestions(): Set<string> {
  if (typeof window === "undefined") return new Set();
  const stored = localStorage.getItem(PROGRESS_KEY);
  return stored ? new Set(JSON.parse(stored)) : new Set();
}

export function markQuestionCompleted(slug: string, code?: string): void {
  const completed = getCompletedQuestions();
  completed.add(slug);
  localStorage.setItem(PROGRESS_KEY, JSON.stringify([...completed]));

  if (code) {
    saveSolution(slug, code);
  }
}

export function isQuestionCompleted(slug: string): boolean {
  return getCompletedQuestions().has(slug);
}

export function saveSolution(slug: string, code: string): void {
  if (typeof window === "undefined") return;
  const solutions = getSavedSolutions();
  solutions[slug] = code;
  localStorage.setItem(SOLUTIONS_KEY, JSON.stringify(solutions));
}

export function getSavedSolution(slug: string): string | null {
  if (typeof window === "undefined") return null;
  const solutions = getSavedSolutions();
  return solutions[slug] || null;
}

function getSavedSolutions(): Record<string, string> {
  const stored = localStorage.getItem(SOLUTIONS_KEY);
  return stored ? JSON.parse(stored) : {};
}
