// Hero video store — backed by the Cloudflare Workers API.
//
// Public consumers (landing.jsx, mobile.jsx) read `hero.src` to set the
// background video. We resolve src at fetch time:
//   - if the server has a hero video set:  API /api/hero-video/raw
//   - otherwise:                            HERO_VIDEO_DEFAULT_SRC (bundled mp4)
//
// Admin gets `upload(file)` and `clear()` mutators that hit the matching
// PUT/DELETE admin endpoints.

const HERO_VIDEO_DEFAULT_SRC = 'media/hero.mp4';
const _heroCache = { hero: null, loading: false };

function _publish(hero) {
  _heroCache.hero = hero;
  window.dispatchEvent(new CustomEvent('herovideochange', { detail: hero }));
}

function _normalize(serverHero) {
  // Backend shape: { filename, size, contentType, url, addedAt }
  // url is null when no file is set; otherwise it's the API path.
  const apiUrl = serverHero?.url ? window.api.API_BASE_URL + serverHero.url : null;
  return {
    meta: serverHero?.filename ? {
      filename: serverHero.filename,
      size: serverHero.size,
      type: serverHero.contentType,
      addedAt: serverHero.addedAt,
    } : null,
    blobUrl: null,                                    // legacy field, unused with API
    src: apiUrl || HERO_VIDEO_DEFAULT_SRC,
  };
}

function useHeroVideo() {
  const [hero, setHero] = React.useState(() => _heroCache.hero || _normalize(null));
  const [loading, setLoading] = React.useState(_heroCache.hero === null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const onChange = (e) => setHero(e.detail);
    window.addEventListener('herovideochange', onChange);

    if (_heroCache.hero === null && !_heroCache.loading) {
      _heroCache.loading = true;
      window.api.apiGet('/api/hero-video')
        .then(r => _publish(_normalize(r?.heroVideo)))
        .catch(err => { setError(err); _publish(_normalize(null)); })
        .finally(() => { _heroCache.loading = false; setLoading(false); });
    } else {
      setLoading(false);
    }

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

  const upload = React.useCallback(async (file) => {
    const r = await window.api.apiUploadPut('/api/admin/hero-video', file);
    if (r?.heroVideo) _publish(_normalize(r.heroVideo));
  }, []);

  const clear = React.useCallback(async () => {
    await window.api.apiDelete('/api/admin/hero-video');
    _publish(_normalize(null));
  }, []);

  return [hero, { upload, clear }];
}

Object.assign(window, { useHeroVideo, HERO_VIDEO_DEFAULT_SRC });
