import { writable, derived } from "svelte/store";
import { generatePug } from "./lib/pug";

export const BLOCKS_KEY = "vip_letter_editor_blocks_v1";
export const SETTINGS_KEY = "vip_letter_editor_settings_v1";
export const THEME_KEY = "vip_letter_editor_theme";

const loadJson = (key, fallback) => {
  try {
    const raw = localStorage.getItem(key);
    if (!raw) return fallback;
    const parsed = JSON.parse(raw);
    return parsed ?? fallback;
  } catch (e) {
    console.warn("Failed to load from localStorage", e);
    return fallback;
  }
};

const persist = (key, value) => {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (e) {
    console.warn("Failed to save to localStorage", e);
  }
};

function createBlocksStore() {
  const initial = loadJson(BLOCKS_KEY, []);
  const { subscribe, update, set } = writable(initial);

  return {
    subscribe,
    set: (value) => {
      persist(BLOCKS_KEY, value);
      set(value);
    },
    update: (fn) =>
      update((prev) => {
        const next = fn(prev);
        persist(BLOCKS_KEY, next);
        return next;
      })
  };
}

function createSettingsStore() {
  const defaults = {
    imageBaseUrl: "",
    showPrices: true,
    projectName: "aspekter",
    templateName: "let.pug"
  };
  const saved = loadJson(SETTINGS_KEY, defaults);
  const initial = { ...defaults, ...saved };
  const { subscribe, update, set } = writable(initial);
  return {
    subscribe,
    set: (value) => {
      persist(SETTINGS_KEY, value);
      set(value);
    },
    update: (fn) =>
      update((prev) => {
        const next = fn(prev);
        persist(SETTINGS_KEY, next);
        return next;
      })
  };
}

function createThemeStore() {
  const initial = loadJson(THEME_KEY, "dark");
  const { subscribe, set } = writable(initial);
  return {
    subscribe,
    set: (value) => {
      persist(THEME_KEY, value);
      set(value);
    }
  };
}

export const blocks = createBlocksStore();
export const settings = createSettingsStore();
export const theme = createThemeStore();

export const pugCode = derived([blocks, settings], ([$blocks, $settings]) =>
  generatePug($blocks, $settings)
);
