// Slideshow store — backed by the Cloudflare Workers API.
//
// Public consumers (currently dormant on the public site, but preserved for a
// possible re-enable) call useSlideshow() and get the list of uploaded slide
// images. Each item exposes `src` pointing at /api/slideshow/:id/raw so the
// existing img/<TerrainSlot> components don't need changes.
//
// Admin uses the same hook plus mutators for add / rename / remove.

const _slideshowCache = { list: null, loading: false };

function _publish(list) {
  _slideshowCache.list = list;
  window.dispatchEvent(new CustomEvent('slideshowchange', { detail: list }));
}

function _normalize(s) {
  return {
    id: s.id,
    name: s.name,
    src: window.api.API_BASE_URL + `/api/slideshow/${encodeURIComponent(s.id)}/raw`,
    size: s.size,
    type: s.contentType,
    addedAt: s.addedAt,
    position: s.position,
  };
}

function useSlideshow() {
  const [items, setItems] = React.useState(() => _slideshowCache.list || []);
  const [loading, setLoading] = React.useState(_slideshowCache.list === null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const onChange = (e) => setItems(e.detail || []);
    window.addEventListener('slideshowchange', onChange);

    if (_slideshowCache.list === null && !_slideshowCache.loading) {
      _slideshowCache.loading = true;
      window.api.apiGet('/api/slideshow')
        .then(r => _publish((r?.slideshow || []).map(_normalize)))
        .catch(err => setError(err))
        .finally(() => { _slideshowCache.loading = false; setLoading(false); });
    } else {
      setLoading(false);
    }

    return () => window.removeEventListener('slideshowchange', onChange);
  }, []);

  const add = React.useCallback(async (file) => {
    const r = await window.api.apiUpload('/api/admin/slideshow', file);
    if (r?.slide) {
      const list = [...(_slideshowCache.list || []), _normalize(r.slide)];
      _publish(list);
    }
  }, []);

  const rename = React.useCallback(async (id, newName) => {
    const r = await window.api.apiPatch(`/api/admin/slideshow/${encodeURIComponent(id)}`, { name: newName });
    if (r?.slide) {
      const list = (_slideshowCache.list || []).map(x => x.id === id ? _normalize(r.slide) : x);
      _publish(list);
    }
  }, []);

  const remove = React.useCallback(async (id) => {
    await window.api.apiDelete(`/api/admin/slideshow/${encodeURIComponent(id)}`);
    const list = (_slideshowCache.list || []).filter(x => x.id !== id);
    _publish(list);
  }, []);

  const reset = React.useCallback(async () => {
    if (!window.confirm('Slideshow defaults are server-side. Run `npm run db:reset:local` on the backend.')) return;
  }, []);

  return [items, { add, rename, remove, reset }];
}

Object.assign(window, { useSlideshow });
