import { browser } from '$app/environment';
import { getContext, setContext } from 'svelte';

import type { ReaderSettings } from '$lib/schema/reader';
import {
	DEFAULT_READER_SETTINGS,
	loadReaderSettings,
	saveReaderSettings,
	toRendererAttributes
} from '$lib/reader/settings';

export class ReaderSettingsState {
	settings = $state<ReaderSettings>(DEFAULT_READER_SETTINGS);

	/** The half foliate takes as renderer attributes. */
	readonly attributes = $derived(toRendererAttributes(this.settings));

	constructor() {
		// Defaults during SSR, real values once the browser has localStorage. The
		// reader only applies these after mount, so there is nothing to flash.
		if (browser) this.settings = loadReaderSettings();
	}

	set<K extends keyof ReaderSettings>(key: K, value: ReaderSettings[K]) {
		this.settings = { ...this.settings, [key]: value };
		saveReaderSettings(this.settings);
	}

	reset() {
		this.settings = DEFAULT_READER_SETTINGS;
		saveReaderSettings(this.settings);
	}
}

const READER_SETTINGS_KEY = Symbol('READER_SETTINGS');

export function setReaderSettingsState() {
	return setContext(READER_SETTINGS_KEY, new ReaderSettingsState());
}

export function getReaderSettingsState() {
	return getContext<ReturnType<typeof setReaderSettingsState>>(READER_SETTINGS_KEY);
}
