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32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// Audio player store for managing playback state
import { writable, derived, get } from 'svelte/store';
import { browser } from '$app/environment';
import type { Track, AudioQuality, PlayableTrack } from '$lib/types';
import { deriveTrackQuality } from '$lib/utils/audioQuality';
import { userPreferencesStore } from '$lib/stores/userPreferences';

interface PlayerState {
	currentTrack: PlayableTrack | null;
	isPlaying: boolean;
	currentTime: number;
	duration: number;
	volume: number;
	quality: AudioQuality;
	qualitySource: 'auto' | 'manual';
	isLoading: boolean;
	queue: PlayableTrack[];
	queueIndex: number;
	sampleRate: number | null;
	bitDepth: number | null;
	replayGain: number | null;
}

const initialPreferences = get(userPreferencesStore);

const initialState: PlayerState = {
	currentTrack: null,
	isPlaying: false,
	currentTime: 0,
	duration: 0,
	volume: 0.8,
	quality: initialPreferences.playbackQuality,
	qualitySource: 'manual',
	isLoading: false,
	queue: [],
	queueIndex: -1,
	sampleRate: null,
	bitDepth: null,
	replayGain: null
};

function createPlayerStore() {
	let startState = initialState;
	if (browser) {
		try {
			const stored = sessionStorage.getItem('tidal-player-store');
			if (stored) {
				const parsed = JSON.parse(stored);
				startState = {
					...initialState,
					...parsed,
					isPlaying: false,
					isLoading: false
				};
			}
		} catch (e) {
			console.warn('Failed to restore player state', e);
		}
	}

	const { subscribe, set, update } = writable<PlayerState>(startState);

	if (browser) {
		subscribe((state) => {
			try {
				const toSave = {
					currentTrack: state.currentTrack,
					queue: state.queue,
					queueIndex: state.queueIndex,
					volume: state.volume,
					quality: state.quality,
					qualitySource: state.qualitySource,
					currentTime: state.currentTime,
					duration: state.duration,
					sampleRate: state.sampleRate,
					bitDepth: state.bitDepth,
					replayGain: state.replayGain
				};
				sessionStorage.setItem('tidal-player-store', JSON.stringify(toSave));
			} catch (e) {
				console.warn('Failed to save player state', e);
			}
		});
	}

	const applyAutoQuality = (state: PlayerState, track: PlayableTrack | null): PlayerState => {
		if (state.qualitySource === 'manual') {
			return state;
		}
		// SonglinkTrack will be converted to Track before playing, so use LOSSLESS for now
		if (track && 'isSonglinkTrack' in track && track.isSonglinkTrack) {
			const nextQuality: AudioQuality = 'LOSSLESS';
			if (state.quality === nextQuality) {
				return state;
			}
			return { ...state, quality: nextQuality };
		}
		const derived = deriveTrackQuality(track as Track | null);
		const nextQuality: AudioQuality = derived ?? 'LOSSLESS';
		if (state.quality === nextQuality) {
			return state;
		}
		return { ...state, quality: nextQuality };
	};

	const resolveSampleRate = (state: PlayerState, track: PlayableTrack | null): number | null => {
		// SonglinkTrack doesn't have sampleRate, return null
		if (track && 'isSonglinkTrack' in track && track.isSonglinkTrack) {
			return null;
		}
		if (state.currentTrack && track && 'id' in state.currentTrack && 'id' in track && state.currentTrack.id === track.id) {
			return state.sampleRate;
		}
		return null;
	};

	return {
		subscribe,
		setTrack: (track: PlayableTrack) =>
			update((state) => {
				const next: PlayerState = {
					...state,
					currentTrack: track,
					duration: track.duration,
					currentTime: 0,
					isLoading: true,
					sampleRate: resolveSampleRate(state, track),
					bitDepth: null,
					replayGain: null
				};
				return applyAutoQuality(next, track);
			}),
		play: () => update((state) => ({ ...state, isPlaying: true })),
		pause: () => update((state) => ({ ...state, isPlaying: false })),
		togglePlay: () => update((state) => ({ ...state, isPlaying: !state.isPlaying })),
		setCurrentTime: (time: number) => update((state) => ({ ...state, currentTime: time })),
		setDuration: (duration: number) => update((state) => ({ ...state, duration })),
		setSampleRate: (sampleRate: number | null) => update((state) => ({ ...state, sampleRate })),
		setBitDepth: (bitDepth: number | null) => update((state) => ({ ...state, bitDepth })),
		setReplayGain: (replayGain: number | null) => update((state) => ({ ...state, replayGain })),
		setVolume: (volume: number) => update((state) => ({ ...state, volume })),
		setQuality: (quality: AudioQuality) =>
			update((state) => {
				userPreferencesStore.setPlaybackQuality(quality);
				return { ...state, quality, qualitySource: 'manual' };
			}),
		setLoading: (isLoading: boolean) => update((state) => ({ ...state, isLoading })),
		setQueue: (queue: PlayableTrack[], startIndex: number = 0) =>
			update((state) => {
				const hasTracks = queue.length > 0;
				const clampedIndex = hasTracks
					? Math.min(Math.max(startIndex, 0), queue.length - 1)
					: -1;
				const nextTrack = hasTracks ? queue[clampedIndex]! : null;

				// Check if we are staying on the same track (prevent reload if so)
				const isSameTrack = state.currentTrack && nextTrack && state.currentTrack.id === nextTrack.id;

				let next: PlayerState = {
					...state,
					queue,
					queueIndex: clampedIndex,
					currentTrack: nextTrack,
					isPlaying: hasTracks ? state.isPlaying : false,
					isLoading: isSameTrack ? state.isLoading : hasTracks,
					currentTime: isSameTrack ? state.currentTime : 0,
					duration: isSameTrack ? state.duration : (nextTrack?.duration ?? 0),
					sampleRate: isSameTrack ? state.sampleRate : resolveSampleRate(state, nextTrack),
					bitDepth: isSameTrack ? state.bitDepth : null,
					replayGain: isSameTrack ? state.replayGain : null
				};

				if (!hasTracks) {
					next = {
						...next,
						queueIndex: -1,
						currentTrack: null,
						isPlaying: false,
						isLoading: false,
						currentTime: 0,
						duration: 0,
						sampleRate: null,
						bitDepth: null,
						replayGain: null
					};
				}

				return applyAutoQuality(next, next.currentTrack);
			}),
		enqueue: (track: PlayableTrack) =>
			update((state) => {
				const queue = state.queue.slice();
				if (queue.length === 0) {
					const next: PlayerState = {
						...state,
						queue: [track],
						queueIndex: 0,
						currentTrack: track,
						isPlaying: true,
						isLoading: true,
						currentTime: 0,
						duration: track.duration,
						sampleRate: resolveSampleRate(state, track),
						bitDepth: null,
						replayGain: null
					};
					return applyAutoQuality(next, track);
				}

				queue.push(track);
				return {
					...state,
					queue
				};
			}),
		enqueueNext: (track: PlayableTrack) =>
			update((state) => {
				const queue = state.queue.slice();
				let queueIndex = state.queueIndex;
				if (queue.length === 0 || queueIndex === -1) {
					const next: PlayerState = {
						...state,
						queue: [track],
						queueIndex: 0,
						currentTrack: track,
						isPlaying: true,
						isLoading: true,
						currentTime: 0,
						duration: track.duration,
						sampleRate: resolveSampleRate(state, track),
						bitDepth: null,
						replayGain: null
					};
					return applyAutoQuality(next, track);
				}

				const insertIndex = Math.min(queueIndex + 1, queue.length);
				queue.splice(insertIndex, 0, track);
				if (insertIndex <= queueIndex) {
					queueIndex += 1;
				}
				return {
					...state,
					queue,
					queueIndex
				};
			}),
		next: () =>
			update((state) => {
				if (state.queueIndex < state.queue.length - 1) {
					const newIndex = state.queueIndex + 1;
					const nextTrack = state.queue[newIndex] ?? null;
					const nextState: PlayerState = {
						...state,
						queueIndex: newIndex,
						currentTrack: nextTrack,
						currentTime: 0,
						duration: nextTrack?.duration ?? 0,
						sampleRate: resolveSampleRate(state, nextTrack),
						bitDepth: null,
						replayGain: null
					};
					return applyAutoQuality(nextState, nextTrack);
				}
				return state;
			}),
		previous: () =>
			update((state) => {
				if (state.queueIndex > 0) {
					const newIndex = state.queueIndex - 1;
					const nextTrack = state.queue[newIndex] ?? null;
					const nextState: PlayerState = {
						...state,
						queueIndex: newIndex,
						currentTrack: nextTrack,
						currentTime: 0,
						duration: nextTrack?.duration ?? 0,
						sampleRate: resolveSampleRate(state, nextTrack),
						bitDepth: null,
						replayGain: null
					};
					return applyAutoQuality(nextState, nextTrack);
				}
				return state;
			}),
		shuffleQueue: () =>
			update((state) => {
				const {
					queue: originalQueue,
					queueIndex: originalIndex,
					currentTrack: originalCurrent
				} = state;

				if (originalQueue.length <= 1) {
					return state;
				}

				const queue = originalQueue.slice();
				let pinnedTrack: PlayableTrack | null = null;

				if (originalCurrent) {
					const locatedIndex = queue.findIndex((track) => track.id === originalCurrent.id);
					if (locatedIndex >= 0) {
						pinnedTrack = queue.splice(locatedIndex, 1)[0] ?? null;
					}
				}

				if (!pinnedTrack && originalIndex >= 0 && originalIndex < queue.length) {
					pinnedTrack = queue.splice(originalIndex, 1)[0] ?? null;
				}

				if (!pinnedTrack && originalCurrent) {
					pinnedTrack = originalCurrent;
				}

				for (let i = queue.length - 1; i > 0; i -= 1) {
					const j = Math.floor(Math.random() * (i + 1));
					[queue[i], queue[j]] = [queue[j]!, queue[i]!];
				}

				if (pinnedTrack) {
					queue.unshift(pinnedTrack);
				}

				const nextQueueIndex = queue.length > 0 ? 0 : -1;
				const nextCurrentTrack = queue.length > 0 ? (queue[0] ?? null) : null;

				let nextState: PlayerState = {
					...state,
					queue,
					queueIndex: nextQueueIndex,
					currentTrack: nextCurrentTrack,
					currentTime: 0,
					duration: nextCurrentTrack?.duration ?? 0,
					sampleRate: resolveSampleRate(state, nextCurrentTrack),
					bitDepth: null,
					replayGain: null
				};

				if (nextQueueIndex === -1) {
					nextState = {
						...nextState,
						currentTrack: null,
						currentTime: 0,
						duration: 0,
						sampleRate: null,
						bitDepth: null,
						replayGain: null
					};
				}

				return applyAutoQuality(nextState, nextState.currentTrack);
			}),
		playAtIndex: (index: number) =>
			update((state) => {
				if (index < 0 || index >= state.queue.length) {
					return state;
				}

				const nextTrack = state.queue[index] ?? null;
				const nextState: PlayerState = {
					...state,
					queueIndex: index,
					currentTrack: nextTrack,
					currentTime: 0,
					isPlaying: true,
					isLoading: true,
					duration: nextTrack?.duration ?? 0,
					sampleRate: resolveSampleRate(state, nextTrack),
					bitDepth: null,
					replayGain: null
				};
				return applyAutoQuality(nextState, nextTrack);
			}),
		removeFromQueue: (index: number) =>
			update((state) => {
				if (index < 0 || index >= state.queue.length) {
					return state;
				}

				const queue = state.queue.slice();
				queue.splice(index, 1);
				let queueIndex = state.queueIndex;
				let currentTrack = state.currentTrack;
				let isPlaying = state.isPlaying;
				let currentTime = state.currentTime;
				let duration = state.duration;
				let isLoading = state.isLoading;

				if (queue.length === 0) {
					const nextState: PlayerState = {
						...state,
						queue,
						queueIndex: -1,
						currentTrack: null,
						isPlaying: false,
						isLoading: false,
						currentTime: 0,
						duration: 0,
						sampleRate: null,
						bitDepth: null,
						replayGain: null
					};
					return applyAutoQuality(nextState, null);
				}

				if (index < queueIndex) {
					queueIndex -= 1;
				} else if (index === queueIndex) {
					if (queueIndex >= queue.length) {
						queueIndex = queue.length - 1;
					}
					currentTrack = queue[queueIndex] ?? null;
					currentTime = 0;
					duration = currentTrack?.duration ?? 0;
					if (!currentTrack) {
						isPlaying = false;
						isLoading = false;
					} else {
						isLoading = true;
					}
				}
				const nextSampleRate =
					state.currentTrack && currentTrack && state.currentTrack.id === currentTrack.id
						? state.sampleRate
						: null;

				const nextState: PlayerState = {
					...state,
					queue,
					queueIndex,
					currentTrack,
					isPlaying,
					isLoading,
					currentTime,
					duration,
					sampleRate: nextSampleRate,
					replayGain: state.replayGain
				};
				return applyAutoQuality(nextState, currentTrack);
			}),
		clearQueue: () =>
			update((state) => {
				const nextState: PlayerState = {
					...state,
					queue: [],
					queueIndex: -1,
					currentTrack: null,
					isPlaying: false,
					isLoading: false,
					currentTime: 0,
					duration: 0,
					sampleRate: null,
					bitDepth: null,
					replayGain: null
				};
				return applyAutoQuality(nextState, null);
			}),
		reset: () => set(initialState)
	};
}

export const playerStore = createPlayerStore();

// Derived stores for convenience
export const currentTrack = derived(playerStore, ($store) => $store.currentTrack);
export const isPlaying = derived(playerStore, ($store) => $store.isPlaying);
export const currentTime = derived(playerStore, ($store) => $store.currentTime);
export const duration = derived(playerStore, ($store) => $store.duration);
export const volume = derived(playerStore, ($store) => $store.volume);
export const progress = derived(playerStore, ($store) =>
	$store.duration > 0 ? ($store.currentTime / $store.duration) * 100 : 0
);