type Interval = '5s' | '30s' | '1m' | '5m' | '30m' | 'off';

const INTERVAL_MS: Record<Interval, number> = {
	'5s': 5000,
	'30s': 30000,
	'1m': 60000,
	'5m': 300000,
	'30m': 1800000,
	'off': 0,
};

export const INTERVAL_LABELS: { value: Interval; label: string }[] = [
	{ value: '5s', label: '5s' },
	{ value: '30s', label: '30s' },
	{ value: '1m', label: '1m' },
	{ value: '5m', label: '5m' },
	{ value: '30m', label: '30m' },
	{ value: 'off', label: 'Off' },
];

function createRefreshStore() {
	let interval = $state<Interval>((typeof localStorage !== 'undefined' ? localStorage.getItem('mc_refresh') as Interval : null) || '30s');
	let lastUpdated = $state<Date | null>(null);
	let refreshing = $state(false);
	let tick = $state(0);
	let timerId: ReturnType<typeof setInterval> | null = null;

	function schedule() {
		if (typeof window === 'undefined') return;
		if (timerId) clearInterval(timerId);
		timerId = null;
		const ms = INTERVAL_MS[interval];
		if (ms > 0) {
			timerId = setInterval(() => {
				tick++;
			}, ms);
		}
	}

	function setInterval_(v: Interval) {
		interval = v;
		if (typeof localStorage !== 'undefined') localStorage.setItem('mc_refresh', v);
		schedule();
	}

	function markUpdated() {
		lastUpdated = new Date();
		refreshing = false;
	}

	function markRefreshing() {
		refreshing = true;
	}

	function triggerNow() {
		tick++;
	}

	function stop() {
		if (timerId) clearInterval(timerId);
		timerId = null;
	}

	// Start the schedule
	schedule();

	return {
		get interval() { return interval; },
		get lastUpdated() { return lastUpdated; },
		get refreshing() { return refreshing; },
		get tick() { return tick; },
		setInterval: setInterval_,
		markUpdated,
		markRefreshing,
		triggerNow,
		stop,
	};
}

export const refresh = createRefreshStore();
