// Data layer — fetches from /api/*
window.TRN_DATA  = { EVALS: [], ACTIVITY: [] };
window.TRN_STATS = null;

async function jsonOrThrow(res) {
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`HTTP ${res.status}: ${body}`);
  }
  return res.json();
}

async function authHeaders() {
  const token = await window.TRN_AUTH.getAccessToken().catch(() => null);
  return token ? { Authorization: `Bearer ${token}` } : {};
}

async function apiFetch(url, opts = {}) {
  const headers = { ...(await authHeaders()), ...(opts.headers || {}) };
  return fetch(url, { ...opts, headers });
}

window.TRN_API = {
  async loadAll() {
    const [evalsRes, stats] = await Promise.all([
      apiFetch("/api/evaluations?limit=200").then(jsonOrThrow),
      apiFetch("/api/dashboard/stats").then(jsonOrThrow).catch(() => null),
    ]);
    window.TRN_DATA  = { EVALS: evalsRes.data || [] };
    window.TRN_STATS = stats;
    return window.TRN_DATA;
  },

  async getEval(id) {
    return apiFetch(`/api/evaluations/${id}`).then(jsonOrThrow);
  },

  async createEval(payload) {
    const res = await apiFetch("/api/evaluations", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(payload),
    });
    return jsonOrThrow(res);
  },

  async updateEval(id, patch) {
    const res = await apiFetch(`/api/evaluations/${id}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(patch),
    });
    return jsonOrThrow(res);
  },

  async deleteEval(id) {
    const res = await apiFetch(`/api/evaluations/${id}`, { method: "DELETE" });
    return jsonOrThrow(res);
  },

  async me() {
    return apiFetch("/api/me").then(jsonOrThrow).catch(() => ({ email: "guest", name: "Guest" }));
  },
};

// Evaluation questions (shared with frontend)
window.EVAL_QUESTIONS = [
  { key:"q1",  label:"การนำไปใช้",           en:"Application" },
  { key:"q2",  label:"คุณภาพของงาน",          en:"Quality" },
  { key:"q3",  label:"ประสิทธิภาพ",           en:"Efficiency" },
  { key:"q4",  label:"การแก้ปัญหา",           en:"Problem Solving" },
  { key:"q5",  label:"ความกระตือรือร้น",      en:"Enthusiasm" },
  { key:"q6",  label:"การแบ่งปันความรู้",     en:"Knowledge Sharing" },
  { key:"q7",  label:"ทัศนคติและการปรับตัว",  en:"Attitude" },
  { key:"q8",  label:"ความเชื่อมั่น",          en:"Confidence" },
  { key:"q9",  label:"ความสม่ำเสมอ",           en:"Consistency" },
  { key:"q10", label:"ผลลัพธ์ภาพรวม",         en:"Overall Impact" },
];

// Helpers
window.fmtThaiDate = (iso) => {
  if (!iso) return "—";
  const d = new Date(iso.includes("T") ? iso : iso + "T00:00:00");
  const m = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
  return `${d.getDate()} ${m[d.getMonth()]} ${d.getFullYear() + 543}`;
};

window.relativeTime = (iso) => {
  if (!iso) return "";
  const t = new Date(iso.replace(" ","T")+"Z").getTime();
  const mins = Math.floor(Math.max(0, Date.now() - t) / 60000);
  if (mins < 1)  return "เมื่อสักครู่";
  if (mins < 60) return `${mins} นาทีที่แล้ว`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24)  return `${hrs} ชม.ที่แล้ว`;
  const days = Math.floor(hrs / 24);
  return days === 1 ? "เมื่อวาน" : `${days} วันที่แล้ว`;
};

window.selfAvg = (row) => {
  const vals = [1,2,3,4,5,6,7,8,9,10].map(i => row[`self_q${i}`]).filter(v => v != null);
  return vals.length ? (vals.reduce((a,b) => a+b, 0) / vals.length).toFixed(1) : null;
};

window.supAvg = (row) => {
  const vals = [1,2,3,4,5,6,7,8,9,10].map(i => row[`sup_q${i}`]).filter(v => v != null);
  return vals.length ? (vals.reduce((a,b) => a+b, 0) / vals.length).toFixed(1) : null;
};
