import { writable } from 'svelte/store'; import { get, set } from 'idb-keyval'; import type { VideoThumbnail } from '$lib/api/youtube'; export interface Subscription { channelId: string; channelName: string; thumbnail: string; } const STORAGE_KEY = 'actualyt-subscriptions'; function createSubscriptionStore() { const { subscribe, set: setStore, update } = writable([]); let initialized = false; async function init() { if (initialized) return; try { const stored = await get(STORAGE_KEY); if (stored) { setStore(stored); } initialized = true; } catch (e) { console.error('Failed to load subscriptions:', e); } } async function persist(subs: Subscription[]) { try { await set(STORAGE_KEY, subs); } catch (e) { console.error('Failed to save subscriptions:', e); } } return { subscribe, init, add: async (channelId: string, channelName: string, thumbnails: VideoThumbnail[]) => { update(subs => { if (subs.some(s => s.channelId === channelId)) { return subs; } const thumbnail = thumbnails[0]?.url || ''; const newSubs = [...subs, { channelId, channelName, thumbnail }]; persist(newSubs); return newSubs; }); }, remove: async (channelId: string) => { update(subs => { const newSubs = subs.filter(s => s.channelId !== channelId); persist(newSubs); return newSubs; }); }, isSubscribed: (subs: Subscription[], channelId: string): boolean => { return subs.some(s => s.channelId === channelId); } }; } export const subscriptions = createSubscriptionStore();