// =============================================================================
// API CLIENT — thin fetch wrapper with auth + base URL
// =============================================================================

const API_BASE = import.meta.env.VITE_API_URL || "http://localhost:8000";

function authHeaders() {
  const token = localStorage.getItem("authToken");
  const h = { Accept: "application/json", "Content-Type": "application/json" };
  if (token) h.Authorization = `Bearer ${token}`;
  return h;
}

async function request(path, opts = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    ...opts,
    headers: { ...authHeaders(), ...(opts.headers || {}) },
  });
  const text = await res.text();
  const data = text ? JSON.parse(text) : null;
  if (!res.ok) {
    const err = new Error(data?.message || `Request failed (${res.status})`);
    err.status = res.status;
    err.payload = data;
    throw err;
  }
  return data;
}

window.RvlApi = {
  // Teams
  listTeams: () => request("/api/teams").then(r => r.data),
  createTeam: (payload) => request(`/api/teams`, { method: "POST", body: JSON.stringify(payload) }).then(r => r.data),
  deleteTeam: (id) => request(`/api/teams/${id}`, { method: "DELETE" }),
  updateTeam: (id, patch) => request(`/api/teams/${id}`, { method: "PATCH", body: JSON.stringify(patch) }).then(r => r.data),
  setCaptain: (id, memberId) => request(`/api/teams/${id}/captain`, { method: "POST", body: JSON.stringify({ member_id: memberId }) }).then(r => r.data),
  toggleOneTime: (id, key, done) => request(`/api/teams/${id}/one-time/${key}`, { method: "POST", body: JSON.stringify({ done }) }).then(r => r.data),
  setMcmBonus: (id, weekId, points) => request(`/api/teams/${id}/weeks/${weekId}/mcm-bonus`, { method: "POST", body: JSON.stringify({ points }) }).then(r => r.data),
  setTyfcbBonus: (id, weekId, points) => request(`/api/teams/${id}/weeks/${weekId}/tyfcb-bonus`, { method: "POST", body: JSON.stringify({ points }) }).then(r => r.data),
  setAttendanceBonus: (id, weekId, points) => request(`/api/teams/${id}/weeks/${weekId}/attendance-bonus`, { method: "POST", body: JSON.stringify({ points }) }).then(r => r.data),

  // Weekly scores
  getWeekScores: (week) => request(`/api/scores/${week}`).then(r => r.data),
  upsertScore: (memberId, week, data) => request(`/api/scores/${memberId}/${week}`, { method: "PUT", body: JSON.stringify({ data }) }).then(r => r.data),

  uploadLogo: (id, file) => {
    const fd = new FormData();
    fd.append("logo", file);
    const token = localStorage.getItem("authToken");
    return fetch(`${API_BASE}/api/teams/${id}/logo`, {
      method: "POST",
      headers: { Accept: "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
      body: fd,
    }).then(async res => {
      const text = await res.text();
      const data = text ? JSON.parse(text) : null;
      if (!res.ok) { const e = new Error(data?.message || `Upload failed (${res.status})`); e.status = res.status; throw e; }
      return data.data;
    });
  },
  deleteLogo: (id) => request(`/api/teams/${id}/logo`, { method: "DELETE" }).then(r => r.data),

  importTeams: (file) => {
    const fd = new FormData();
    fd.append("file", file);
    const token = localStorage.getItem("authToken");
    return fetch(`${API_BASE}/api/import/teams`, {
      method: "POST",
      headers: { Accept: "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
      body: fd,
    }).then(async res => {
      const text = await res.text();
      const data = text ? JSON.parse(text) : null;
      if (!res.ok) { const e = new Error(data?.message || `Import failed (${res.status})`); e.status = res.status; throw e; }
      return data;
    });
  },

  // Members
  addMember: (teamId, name) => request(`/api/teams/${teamId}/members`, { method: "POST", body: JSON.stringify({ name }) }),
  renameMember: (memberId, name) => request(`/api/members/${memberId}`, { method: "PATCH", body: JSON.stringify({ name }) }),
  moveMember: (memberId, toTeamId) => request(`/api/members/${memberId}/move`, { method: "PATCH", body: JSON.stringify({ to_team_id: toTeamId }) }),
  removeMember: (memberId) => request(`/api/members/${memberId}`, { method: "DELETE" }),

  // Activities
  listActivities: () => request("/api/activities").then(r => r.data),
  updateActivity: (key, patch) => request(`/api/activities/${key}`, { method: "PATCH", body: JSON.stringify(patch) }).then(r => r.data),

  // CMS / Site settings
  listSiteSettings: () => request("/api/site-settings").then(r => r.data),
  publicSiteSettings: () => request("/api/site-settings/public").then(r => r.data),
  publicStats: () => request("/api/stats/public").then(r => r.data),
  saveSiteSettings: (settings) => request("/api/site-settings", { method: "PATCH", body: JSON.stringify({ settings }) }).then(r => r.data),
};

// Shared hook: fetches all teams + all weekly scores. Returns {teams, scoresByWeek, loading, error, reload}.
window.useLiveSeasonData = function useLiveSeasonData() {
  const [teams, setTeams]               = useState([]);
  const [scoresByWeek, setScoresByWeek] = useState({});
  const [loading, setLoading]           = useState(true);
  const [error, setError]               = useState(null);
  const [tick, setTick]                 = useState(0);

  useEffect(() => {
    let cancel = false;
    setLoading(true);
    Promise.all([
      window.RvlApi.listTeams(),
      ...(window.RVL_WEEKS || []).map(w => window.RvlApi.getWeekScores(w.id).then(d => [w.id, d || {}])),
    ])
      .then(([teamsData, ...pairs]) => {
        if (cancel) return;
        const map = {};
        for (const [wid, d] of pairs) map[wid] = d;
        setTeams(teamsData);
        setScoresByWeek(map);
        setError(null);
      })
      .catch(e => { if (!cancel) setError(e); })
      .finally(() => { if (!cancel) setLoading(false); });
    return () => { cancel = true; };
  }, [tick]);

  return { teams, scoresByWeek, loading, error, reload: () => setTick(t => t + 1) };
};
