/* Huy hiệu gamification — bấm xem tiến độ (mobile-friendly, không hover). */
function ProfileBadgesGrid({ allBadges, rankInfo, onCelebrate }) {
  const [tipId, setTipId] = React.useState("");
  const unlocked = allBadges.filter((b) => b.active);
  const locked = allBadges.filter((b) => !b.active);

  React.useEffect(() => {
    if (!rankInfo) return;
    const activeIds = unlocked.map((b) => b.id);
    const key = "dcp_badges_win_" + (rankInfo.phone || rankInfo.name || "user");
    const celebrated = JSON.parse(localStorage.getItem(key) || "[]");
    const newly = activeIds.filter((id) => !celebrated.includes(id));
    if (newly.length > 0) {
      const match = unlocked.find((b) => b.id === newly[0]);
      if (match) setTimeout(() => onCelebrate(match.cheer, true), 1000);
      localStorage.setItem(key, JSON.stringify([...celebrated, ...newly]));
    }
  }, [rankInfo, unlocked.length]);

  const tapBadge = (b) => {
    setTipId(tipId === b.id ? "" : b.id);
    onCelebrate(b.active ? b.cheer : b.hint, b.active);
  };

  const tipBadge = allBadges.find((b) => b.id === tipId);

  const renderBadge = (b) => {
    const pct = b.isRank
      ? (b.current <= 10 ? 100 : Math.round((10 / b.current) * 100))
      : Math.min(100, Math.round((b.current / b.goal) * 100));
    return (
      <div key={b.id} className={"dcp-badge-item " + (b.active ? "active" : "inactive") + (tipId === b.id ? " selected" : "")} onClick={() => tapBadge(b)}>
        <div className="dcp-badge-circle">
          {b.icon}
          {!b.active && (
            <div className="dcp-badge-progress-bg">
              <div className="dcp-badge-progress-fill" style={{ width: pct + "%" }} />
            </div>
          )}
        </div>
        <div className="dcp-badge-name">{b.name}</div>
        <div className="dcp-badge-status">{b.active ? "✓ Đã đạt" : (b.isRank ? (b.current === 99 ? "—" : "#" + b.current) : `${b.current}/${b.goal}`)}</div>
      </div>
    );
  };

  return (
    <div className="dcp-badges-sec">
      <h3 className="dcp-badges-title dcp-badges-title-unlocked">🏆 Huy hiệu đã chinh phục ({unlocked.length})</h3>
      <div className="dcp-badges-grid dcp-badges-grid-unlocked">
        {unlocked.length > 0 ? unlocked.map(renderBadge) : <p className="dcp-badges-empty">Chưa có huy hiệu. Hoàn thành bài đầu tiên nhé! 🚀</p>}
      </div>
      <h3 className="dcp-badges-title dcp-badges-title-locked">🎯 Mục tiêu tiếp theo ({locked.length})</h3>
      <div className="dcp-badges-grid">{locked.map(renderBadge)}</div>
      {tipBadge && (
        <div className="dcp-badge-detail">
          <b>{tipBadge.icon} {tipBadge.name}</b> — {tipBadge.desc}
          <span>{tipBadge.active ? "🎉 Đã mở khóa! Nhấn lại để chúc mừng." : tipBadge.hint}</span>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ProfileBadgesGrid });