import { writable, type Writable } from 'svelte/store';
import { browser } from '$app/environment';

export const ql = writable(fromLocalStorage('ql', []));
toLocalStorage(ql, 'ql');

function fromLocalStorage(storageKey: string, fallback: string[]): string[] {
  if (browser) {
    const storedValue = localStorage.getItem(storageKey);
    if (storedValue !== 'undefined' && storedValue !== null) {
      return typeof fallback === 'object' ? JSON.parse(storedValue) : storedValue;
    }
  }
  return fallback;
}

function toLocalStorage(store: Writable<string[]>, storageKey: string) {
  if (browser) {
    store.subscribe((value) => {
      let storageValue = typeof value === 'object' ? JSON.stringify(value.sort()) : value;

      localStorage.setItem(storageKey, storageValue);
    });
  }
}
