/* global React */
const _CS = React;

const MOBIUS_API = 'https://api.beimingguanyu.top/api/page/mobius';
const _CloudCtx = _CS.createContext({});

function CloudProvider({ children }) {
  const [cloud, setCloud] = _CS.useState({});
  const [loaded, setLoaded] = _CS.useState(false);
  const ref = _CS.useRef({});
  const timer = _CS.useRef(null);

  _CS.useEffect(() => {
    fetch(MOBIUS_API)
      .then(r => r.json())
      .then(j => {
        const d = j.data && typeof j.data === 'object' && !Array.isArray(j.data) ? j.data : {};

        // ── 跨天归档 ──
        const today = new Date().toISOString().slice(0, 10);
        const lastDate = d._lastDate;
        if (lastDate && lastDate !== today) {
          const history = d.history || {};
          // Archive previous day's daily data
          const hasDailyData = d.events || d.dream || d.reflection || d.share;
          if (hasDailyData) {
            history[lastDate] = {
              events: d.events || [],
              dream: d.dream || null,
              reflection: d.reflection || null,
              share: d.share || null,
              stats: d.stats || null,
              almanac: d.almanac || null,
              butterfly: d.butterfly || null,
            };
          }
          // Prune > 30 days
          const cutoff = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10);
          Object.keys(history).forEach(k => { if (k < cutoff) delete history[k]; });
          d.history = history;
          // Clear daily fields for new day
          d.events = [];
          d.dream = null;
          d.reflection = null;
          d.share = null;
          d._lastDate = today;
          // Persist archived state
          fetch(MOBIUS_API, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ data: d }),
          }).catch(() => {});
        } else if (!lastDate) {
          d._lastDate = today;
          fetch(MOBIUS_API + '/patch', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ key: '_lastDate', value: today }),
          }).catch(() => {});
        }

        ref.current = d;
        setCloud(d);
        setLoaded(true);
      })
      .catch(() => setLoaded(true));
  }, []);

  // Re-fetch when page becomes visible (detect external changes from 溟/备忘录/etc)
  _CS.useEffect(() => {
    function onVisible() {
      if (document.visibilityState === 'visible') {
        fetch(MOBIUS_API)
          .then(r => r.json())
          .then(j => {
            const d = j.data && typeof j.data === 'object' && !Array.isArray(j.data) ? j.data : {};
            ref.current = d;
            setCloud(d);
          })
          .catch(() => {});
      }
    }
    document.addEventListener('visibilitychange', onVisible);
    return () => document.removeEventListener('visibilitychange', onVisible);
  }, []);

  const patchCloud = _CS.useCallback((key, value) => {
    ref.current = { ...ref.current, [key]: value };
    setCloud({ ...ref.current });
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      fetch(MOBIUS_API, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data: { ...ref.current } }),
      }).catch(() => {});
    }, 800);
  }, []);

  return (
    <_CloudCtx.Provider value={{ cloud, loaded, patchCloud }}>
      {children}
    </_CloudCtx.Provider>
  );
}

function useCloud(key) {
  const { cloud, loaded, patchCloud } = _CS.useContext(_CloudCtx);
  const save = _CS.useCallback(val => patchCloud(key, val), [key, patchCloud]);
  return { data: cloud[key], loaded, save };
}

window.CloudProvider = CloudProvider;
window.useCloud = useCloud;
