// useCampaignData.jsx — live Givebutter campaign data, shared app-wide
//
// HOW THE REAL API CALL WORKS
// ─────────────────────────────────────────────────────────────────────
// The fetch hits a Cloudflare Pages Function at /api/campaign-total
// (file: functions/api/campaign-total.js).
//
// That function calls the Givebutter Campaigns API:
//   GET https://api.givebutter.com/v1/campaigns/<CAMPAIGN_ID>
//   Headers: Authorization: Bearer <GIVEBUTTER_API_KEY>
//
// It must return JSON in this shape:
//   { raised: 12500, goal: 50000, donors: 87 }
//
// RUNNING LOCALLY (no Cloudflare):
//   The fetch will 404 → the catch block fires → fallback value is used.
//   Use the Tweaks slider ("Amount raised $") to preview any value.
//
// ENV VARS needed in Cloudflare Pages dashboard (Settings → Environment variables):
//   GIVEBUTTER_API_KEY   — your private API key
// ─────────────────────────────────────────────────────────────────────

var CampaignDataContext = React.createContext({
  raised:  0,
  goal:    50000,
  donors:  0,
  loading: true,
});

function CampaignDataProvider({ children, fallback = 0 }) {
  var [data, setData] = React.useState({
    raised:  fallback,
    goal:    50000,
    donors:  0,
    loading: true,
  });

  React.useEffect(function () {
    fetch('/api/campaign-total')
      .then(function (res) {
        if (!res.ok) throw new Error('fetch failed ' + res.status);
        return res.json();
      })
      .then(function (json) {
        setData({
          raised:  typeof json.raised === 'number' ? json.raised : fallback,
          goal:    typeof json.goal   === 'number' && json.goal > 0 ? json.goal : 50000,
          donors:  typeof json.donors === 'number' ? json.donors : 0,
          loading: false,
        });
      })
      .catch(function () {
        // API unreachable (local dev, or Netlify function not deployed) —
        // fall back to the master fallback value and stop the loading state.
        setData(function (prev) {
          return { raised: fallback, goal: prev.goal, donors: prev.donors, loading: false };
        });
      });
  }, []); // runs once on mount

  return React.createElement(CampaignDataContext.Provider, { value: data }, children);
}

function useCampaignData() {
  return React.useContext(CampaignDataContext);
}

Object.assign(window, { CampaignDataProvider, useCampaignData });
