// TextiGreen v4 · hooks

const { useState: useSh4, useEffect: useEh4, useRef: useRh4, useCallback: useCh4 } = React;

function useConnection() {
  const [snap, setSnap] = useSh4(() => window.TGApi.snapshot());
  useEh4(() => {
    const unsub = window.TGApi.subscribe(setSnap);
    window.TGApi.ping();
    return unsub;
  }, []);
  return snap;
}

function useAsync(fn, deps) {
  const [state, setState] = useSh4({ data: null, loading: true, error: null });
  const reqId = useRh4(0);
  const fnRef = useRh4(fn); fnRef.current = fn;
  const run = useCh4(() => {
    const id = ++reqId.current;
    setState(s => ({ data: s.data, loading: true, error: null }));
    Promise.resolve().then(() => fnRef.current())
      .then(data => { if (id === reqId.current) setState({ data, loading: false, error: null }); })
      .catch(err => { if (id === reqId.current) setState({ data: null, loading: false, error: err.message || String(err) }); });
  }, []);
  useEh4(() => { run(); }, deps); // eslint-disable-line
  return { ...state, reload: run };
}

function useDebounced(value, delay = 400) {
  const [v, setV] = useSh4(value);
  useEh4(() => { const t = setTimeout(() => setV(value), delay); return () => clearTimeout(t); }, [value, delay]);
  return v;
}

Object.assign(window, { useConnection, useAsync, useDebounced });
