// Cloudflare Pages Functions backed private sync.

function createScheduleSync() {
  const listeners = new Set();
  let currentSession = null;
  const configured = window.location.protocol !== 'file:';

  async function api(path, options = {}) {
    const headers = { ...(options.headers || {}) };
    const request = { credentials: 'include', ...options, headers };
    if (request.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';

    const response = await fetch(path, request);
    let data = {};
    try { data = await response.json(); } catch (_) {}
    if (!response.ok) throw new Error(data.error || `Request failed (${response.status})`);
    return data;
  }

  function emit(session) {
    currentSession = session || null;
    listeners.forEach(listener => listener(currentSession));
  }

  return {
    configured,

    async getSession() {
      if (!configured) return null;
      const data = await api('/api/me', { method: 'GET' });
      const session = data.user ? { user: data.user } : null;
      currentSession = session;
      return session;
    },

    onAuthChange(callback) {
      listeners.add(callback);
      return () => listeners.delete(callback);
    },

    async signInWithEmail(email, password) {
      const data = await api('/api/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });
      emit({ user: data.user });
    },

    async signOut() {
      try {
        await api('/api/logout', { method: 'POST', body: JSON.stringify({}) });
      } finally {
        emit(null);
      }
    },

    async loadState() {
      const data = await api('/api/state', { method: 'GET' });
      return data.payload ? { payload: data.payload, updatedAt: data.updatedAt } : null;
    },

    async saveState(state) {
      await api('/api/state', {
        method: 'POST',
        body: JSON.stringify({ payload: state }),
      });
    },

    clearLocalSession() {
      emit(null);
    },
  };
}

window.ScheduleSync = createScheduleSync();
