patx/youtube-clone

/** Session state shared across views, with a tiny subscribe/notify. */
import { api } from './api.js';

const listeners = new Set();

export const state = {
  user: null,
  subscriptions: [],
  categories: ['All'],
  ready: false,
};

export function onChange(fn) {
  listeners.add(fn);
  return () => listeners.delete(fn);
}

export function notify() {
  for (const fn of listeners) fn(state);
}

export function setUser(user) {
  state.user = user;
  if (!user) state.subscriptions = [];
  notify();
}

export async function refreshSubscriptions() {
  if (!state.user) {
    state.subscriptions = [];
    notify();
    return;
  }
  try {
    const { channels } = await api.subscriptions();
    state.subscriptions = channels;
  } catch {
    state.subscriptions = [];
  }
  notify();
}

export async function bootstrap() {
  const [me, cats] = await Promise.allSettled([api.me(), api.categories()]);
  state.user = me.status === 'fulfilled' ? me.value.user : null;
  state.categories = cats.status === 'fulfilled' ? cats.value.categories : ['All'];
  state.ready = true;
  if (state.user) await refreshSubscriptions();
  else notify();
}