/* ============================================================
   Oziq AI — API client
   Talks to the Cloudflare Worker at WORKER_URL.
   ============================================================ */

const WORKER_URL = 'https://oziq-ai.baholash-cf.workers.dev';

// useApi(path, { pollMs?: number })
// Returns { data, loading, error, refresh }.
function useApi(path, opts = {}) {
  const { pollMs = 0 } = opts;
  const [state, setState] = React.useState({ data: null, loading: !!path, error: null });

  const refresh = React.useCallback(() => {
    if (!path) { setState({ data: null, loading: false, error: null }); return; }
    setState((s) => ({ ...s, loading: true }));
    fetch(WORKER_URL + path)
      .then((r) => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
      })
      .then((data) => setState({ data, loading: false, error: null }))
      .catch((error) => setState((s) => ({ data: s.data, loading: false, error })));
  }, [path]);

  React.useEffect(() => {
    refresh();
    if (pollMs > 0 && path) {
      const id = setInterval(refresh, pollMs);
      return () => clearInterval(id);
    }
  }, [refresh, pollMs, path]);

  return { ...state, refresh };
}

Object.assign(window, { WORKER_URL, useApi });
