(function () {
  const json = (r) => r.json().then(d => {
    if (!r.ok) {
      const err = new Error(d?.error || `${r.status}`);
      if (d?.code) err.code = d.code;
      err.status = r.status;
      throw err;
    }
    return d;
  });
  const J = (method, url, body) => fetch(url, {
    method, credentials: "same-origin",
    headers: body ? { "Content-Type": "application/json" } : undefined,
    body: body ? JSON.stringify(body) : undefined,
  }).then(json);

  // Backend course tree → UI course shape used by browser.jsx / creator.jsx
  function backendToUi(c) {
    const totalLessons = (c.modules || []).reduce((a, m) => a + m.lessons.length + (m.quiz ? 1 : 0), 0);
    return {
      id: c.id,
      title: c.title,
      subtitle: c.description?.split(/[.!?]\s/)[0]?.slice(0, 140) || "",
      description: c.description,
      cat: window.guessCat ? window.guessCat(c.title) : "data",
      level: ({ beginner: "Beginner", intermediate: "Intermediate", advanced: "Advanced" })[c.difficulty] || "Beginner",
      rating: 4.9, learners: 0,
      hours: ((c.moduleCount || 1) * 0.8).toFixed(1),
      author: { name: c.audience || "AI-generated", kind: "ai" },
      lessonsN: totalLessons, quizzes: (c.modules || []).filter(m => m.quiz).length,
      tags: [c.difficulty, c.tone].filter(Boolean),
      modules: (c.modules || []).map(m => ({
        id: m.id,
        title: m.title, summary: m.summary,
        learningObjectives: m.learningObjectives,
        lessons: [
          ...m.lessons.map(l => ({ id: l.id, title: l.title, type: "lesson", dur: estDur(l.body), body: l.body, slideNotes: l.slideNotes, order: l.order })),
          ...(m.quiz ? [{ id: m.quiz.id, title: `Module quiz`, type: "quiz", dur: "5m", _quiz: m.quiz }] : []),
        ],
      })),
      _raw: c,
    };
  }
  function estDur(text) { const w = (text || "").split(/\s+/).length; return `${Math.max(3, Math.round(w / 180))}m`; }

  window.API = {
    me: () => J("GET", "/api/me").catch(() => null),
    upgradePlan: (plan) => J("POST", "/api/me/upgrade", { plan }),
    downgradePlan: () => J("DELETE", "/api/me/upgrade"),
    login: (email, password) => J("POST", "/api/auth/login", { email, password }),
    register: (email, password, name) => J("POST", "/api/auth/register", { email, password, name }),
    logout: () => J("POST", "/api/auth/logout"),
    listCourses: () => J("GET", "/api/courses"),
    getCourse: (id) => J("GET", `/api/courses/${id}`).then(d => backendToUi(d.course)),
    createDraft: (input) => J("POST", "/api/courses/draft", input).then(d => d.course),
    generateCourse: (input) => J("POST", "/api/courses", input).then(d => backendToUi(d.course)),
    regenerateCourse: (id) => J("POST", `/api/courses/${id}/regenerate`).then(d => backendToUi(d.course)),
    exportCourse: (id, format) => { window.open('/api/courses/' + id + '/export?format=' + encodeURIComponent(format), "_blank"); },
    patchCourse: (id, body) => J("PATCH", `/api/courses/${id}`, body),
    patchModule: (id, body) => J("PATCH", `/api/modules/${id}`, body),
    patchLesson: (id, body) => J("PATCH", `/api/lessons/${id}`, body),
    addLesson: (moduleId, body) => J("POST", `/api/modules/${moduleId}/lessons`, body),
    addModule: (courseId, body) => J("POST", `/api/courses/${courseId}/modules`, body || {}),
    deleteModule: (moduleId) => J("DELETE", `/api/modules/${moduleId}`),
    deleteLesson: (lessonId) => J("DELETE", `/api/lessons/${lessonId}`),
    regenerateLesson: (lessonId, body) => J("POST", `/api/lessons/${lessonId}/regenerate`, body || {}),
    searchImages: (query, count = 12) => J("POST", `/api/tools/image-search`, { query, count }),
    patchQuestion: (id, body) => J("PATCH", `/api/quiz-questions/${id}`, body),
    improveLesson: (body) => J("POST", "/api/tools/lesson-improver", body),
    copywriter: (id) => J("POST", `/api/courses/${id}/copywriter`),
    getCourseHistory: (id, limit = 50) => J("GET", `/api/courses/${id}/history?limit=${limit}`),
    chatRefine: (id, message, history) => J("POST", `/api/courses/${id}/chat`, { message, history }),
    chatLesson: (lessonId, message, history) => J("POST", `/api/lessons/${lessonId}/chat`, { message, history }),
    reorderModules: (courseId, orderedModuleIds) =>
      J("POST", `/api/courses/${courseId}/reorder-modules`, { orderedModuleIds }),
    reorderLessons: (moduleId, orderedLessonIds) =>
      J("POST", `/api/modules/${moduleId}/reorder-lessons`, { orderedLessonIds }),
    regenerateQuiz: (moduleId, body) =>
      J("POST", `/api/modules/${moduleId}/quiz/regenerate`, body || {}),
    addQuizQuestion: (moduleId, body) =>
      J("POST", `/api/modules/${moduleId}/quiz/questions`, body || {}),
    adminStats: () => J("GET", "/api/admin/stats"),
    adminUsers: (limit = 50) => J("GET", `/api/admin/users?limit=${limit}`),
    adminGetSettings: () => J("GET", "/api/admin/settings"),
    adminSetSettings: (body) => J("PATCH", "/api/admin/settings", body),
    adminPromoteUser: (id, isSuperAdmin) =>
      J("POST", `/api/admin/users/${id}/promote`, { isSuperAdmin }),
    billingCheckout: (plan) => J("POST", "/api/billing/checkout", { plan }),
    trackVisit: (path) =>
      fetch("/api/track/visit", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ path }),
        keepalive: true,
      }).catch(() => {}),
  };
  window.backendToUi = backendToUi;
})();
