/* Trang hồ sơ học viên: Student Center + hồ sơ hỗ trợ. */
function CProfilePage({ go, onLogout }) {
  const [data, setData] = React.useState(null);
  const [center, setCenter] = React.useState(null);
  const [form, setForm] = React.useState({});
  const [tab, setTab] = React.useState("overview");
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState("");
  const [credits, setCredits] = React.useState(null);
  const [centerErr, setCenterErr] = React.useState("");
  const [rankInfo, setRankInfo] = React.useState(null);
  const [curr, setCurr] = React.useState(null);

  const load = React.useCallback(async () => {
    try {
      const r = await (window.AG && AG.profile ? AG.profile() : {});
      const sc = await (window.AG && AG.studentCenter ? AG.studentCenter().catch(() => null) : null);
      const cr = await (window.AG && AG.credits ? AG.credits().catch(() => null) : null);
      const rank = await (window.AG && AG.myRank ? AG.myRank().catch(() => null) : null);
      const cu = await (window.AG && AG.curriculum ? AG.curriculum().catch(() => null) : null);
      const p = Object.assign({}, (r && r.profile) || {});
      p.contact_email = p.contact_email || p.login_email || (r && r.learn_email) || "";
      p.display_name = p.display_name || p.pronoun || (r && r.name) || "";
      setData(r); setCenter(sc && sc.ok ? sc : null); setCenterErr(sc && sc.ok ? "" : "Chưa tải được dữ liệu học tập.");
      setForm(p); if (cr && cr.ok) setCredits(cr);
      if (rank && rank.ok) setRankInfo(rank);
      setCurr(cu);
    } catch (e) { setData({ ok: false, msg: "Không tải được hồ sơ, thử lại nhé." }); }
  }, []);

  React.useEffect(() => { let alive = true; load().then(() => alive && true); return () => { alive = false; }; }, [load]);
  const set = (k, v) => setForm(Object.assign({}, form, { [k]: v }));
  const save = async (e) => {
    e.preventDefault(); setBusy(true); setMsg("");
    const r = await (window.AG && AG.saveProfile ? AG.saveProfile(form) : { ok: false });
    setBusy(false);
    if (r && r.ok) { setData(Object.assign({}, data, { profile: r.profile })); setMsg(r.msg || "Đã lưu hồ sơ."); }
    else setMsg((r && r.msg) || "Chưa lưu được, anh/chị thử lại nhé.");
  };

  if (!data) return <section className="profile-page"><div className="wrap"><p>Đang tải hồ sơ...</p></div></section>;
  if (data.ok === false) return <section className="profile-page"><div className="wrap profile-wrap">
    <div className="profile-empty"><b>{data.msg || "Cần đăng nhập để xem hồ sơ."}</b>
      <button className="btn btn-gold" onClick={() => go && go("login")}>Đăng nhập lại</button></div>
  </div></section>;

  const z = data.zalo || {};
  const xp = rankInfo ? rankInfo.xp || 0 : 0;
  const lvl = getLevelInfo(xp);
  const hon = profileHonorific(form.gender);
  const displayName = form.display_name || data.name || `${hon} học viên`;
  const tabs = [["overview", "Tổng quan"], ["submissions", "Bài đã nộp"], ["artifacts", "Thành phẩm"],
    ["courses", "Khóa của tôi"], ["profile", "Hồ sơ & Ưu đãi"]];

  return <section className="profile-page">
    <div className="wrap profile-wrap">
      <button className="btn btn-outline" onClick={() => go && go("learn")}>← Về trang học</button>
      <div className="profile-head">
        <div className="dcp-profile-identity">
          <p className="eyebrow">Trung tâm học viên</p>
          <h1>Chào {hon} {displayName}</h1>
          <p className="dcp-profile-level-tag">Danh hiệu: <b>{lvl.name}</b>
            {rankInfo && rankInfo.rank ? <> · Hạng <b>#{rankInfo.rank}</b></> : null}
            {xp > 0 ? <> · <b>{xp}</b> XP</> : null}
          </p>
        </div>
        <span className={"profile-badge " + (z.status === "linked" ? "ok" : "")}>
          Zalo: {z.status === "linked" ? "Đã liên kết" : "Chưa xác nhận group"}
        </span>
      </div>
      <div className="profile-tabs">
        {tabs.map((t) => <button key={t[0]} className={tab === t[0] ? "active" : ""} onClick={() => setTab(t[0])}>{t[1]}</button>)}
      </div>
      {centerErr && <div className="profile-msg">{centerErr}</div>}
      {tab === "overview" && <div className="profile-stack">
        <ProfileStatsPanel center={center} rankInfo={rankInfo} curr={curr} form={form} />
        <ProfileStatsProgress curr={curr} rankInfo={rankInfo} go={go} profile={form} setTab={setTab} />
        <StudentCenterOverview center={center} data={data} go={go} onLogout={onLogout} />
      </div>}
      {tab === "submissions" && <StudentSubmissions center={center} go={go} />}
      {tab === "artifacts" && <StudentArtifacts center={center} />}
      {tab === "courses" && <StudentCourses center={center} />}
      {tab === "profile" && <div className="profile-stack">
        <ProfileBenefitCards data={data} form={form} credits={credits} setCredits={setCredits} go={go} />
        <ProfileFormPanel form={form} set={set} save={save} busy={busy} msg={msg} />
      </div>}
    </div>
  </section>;
}

Object.assign(window, { CProfilePage });