// =============================================================================
// ADAPTER RESOLVER + REACT HOOK
//
// Selects which adapter is active based on the URL ?adapter= param.
// Exposes:
//   window.JD_ADAPTER         — the live adapter object
//   window.useJarvisData(key) — React hook that returns { data, loading, error, reload }
// =============================================================================

(function () {
  const params = new URLSearchParams(window.location.search);
  const requested = params.get("adapter") || "fixtures";
  const available = window.JD_ADAPTERS || {};
  const adapter = available[requested] || available.fixtures;

  if (!adapter) {
    throw new Error("No adapter available. Did src/adapters/*.js fail to load?");
  }
  if (requested !== adapter.id) {
    console.warn("[Jarvis] Requested adapter '" + requested + "' missing — falling back to '" + adapter.id + "'.");
  }

  window.JD_ADAPTER = adapter;

  // ---- React hook: useJarvisData --------------------------------------------
  // Usage:
  //   const { data, loading, error, reload } = useJarvisData("emails");
  //
  // `key` is the suffix after `get`, lower-camel. Examples:
  //   "user"               → adapter.getUser()
  //   "emails"             → adapter.getEmails()
  //   "calendarEvents"     → adapter.getCalendarEvents()
  //   "highestValueTask"   → adapter.getHighestValueTask()
  //   "meetings72"         → adapter.getMeetings72()
  //   "finance" / "store" / "content" / "command"
  //
  // Hook re-runs when `key` changes or `reload()` is invoked.
  function useJarvisData(key) {
    const [state, setState] = React.useState({ data: null, loading: true, error: null });
    const [nonce, setNonce] = React.useState(0);

    React.useEffect(() => {
      let cancelled = false;
      const methodName = "get" + key.charAt(0).toUpperCase() + key.slice(1);
      const fn = adapter[methodName];
      if (typeof fn !== "function") {
        setState({ data: null, loading: false, error: new Error("Adapter has no method " + methodName) });
        return;
      }
      setState(s => ({ ...s, loading: true, error: null }));
      Promise.resolve(fn.call(adapter)).then(
        (data) => { if (!cancelled) setState({ data, loading: false, error: null }); },
        (err)  => { if (!cancelled) setState({ data: null, loading: false, error: err }); }
      );
      return () => { cancelled = true; };
    }, [key, nonce]);

    const reload = React.useCallback(() => setNonce(n => n + 1), []);
    return { ...state, reload };
  }

  window.useJarvisData = useJarvisData;

  // Convenience: call an adapter mutation and reload one or more keys.
  // Usage:
  //   await window.JD.mutate("toggleTask", id);  // fire-and-forget; UI re-fetches on next render
  window.JD = {
    adapter,
    async mutate(method, ...args) {
      const fn = adapter[method];
      if (typeof fn !== "function") throw new Error("Adapter has no method " + method);
      return await fn.apply(adapter, args);
    },
  };
})();
