import { writable } from 'svelte/store';

const EXPERT_MODE_KEY = 'headroom.capacity.expertMode';

function getInitialExpertMode(): boolean {
  if (typeof localStorage === 'undefined') return false;

  const stored = localStorage.getItem(EXPERT_MODE_KEY);
  if (stored === 'true') return true;
  if (stored === 'false') return false;
  return false;
}

const expertModeWritable = writable<boolean>(getInitialExpertMode());

if (typeof localStorage !== 'undefined') {
  expertModeWritable.subscribe((value) => {
    localStorage.setItem(EXPERT_MODE_KEY, String(value));
  });
}

export const expertMode = {
  subscribe: expertModeWritable.subscribe,
};

export function setExpertMode(value: boolean): void {
  expertModeWritable.set(value);
}

export function toggleExpertMode(): void {
  expertModeWritable.update((current) => !current);
}
