<script>
(function() {
  const svg    = document.getElementById('keyword-cloud-svg');
  const fitG   = document.getElementById('kw-fit');
  const cloudG = document.getElementById('kw-cloud');
  if (!svg || !fitG || !cloudG) return;

  function fitCloud() {
    // 컨테이너 실제 픽셀 크기
    const rect = svg.getBoundingClientRect();
    const targetW = rect.width  || 600;
    const targetH = rect.height || 500;

    // 텍스트 묶음의 현재 바운딩 박스
    const bbox = cloudG.getBBox();
    if (!bbox || bbox.width === 0 || bbox.height === 0) {
      fitG.setAttribute('transform', 'translate(0,0) scale(1)');
      return;
    }

    // 여백 조금(=패딩) 남기기
    const PAD = 0.95;
    const scale = Math.min(targetW / bbox.width, targetH / bbox.height) * PAD;

    // 중심 정렬: 스케일 적용 후 중앙으로 이동
    const scaledW = bbox.width  * scale;
    const scaledH = bbox.height * scale;

    // 스케일 앞쪽에서 원점 이동(bbox.x,y 보정) → 그 다음 중앙 정렬
    const tx = (targetW - scaledW) / 2 - bbox.x * scale;
    const ty = (targetH - scaledH) / 2 - bbox.y * scale;

    fitG.setAttribute('transform', `translate(${tx},${ty}) scale(${scale})`);
  }

  // 초기 렌더 후 1프레임 뒤 실행(브라우저가 텍스트 크기 계산하도록)
  requestAnimationFrame(fitCloud);

  // 리사이즈 대응
  window.addEventListener('resize', fitCloud);

  // 동적으로 키워드가 바뀌는 경우(ajax 등)에도 호출할 수 있도록 전역 훅 제공
  window.__refitKeywordCloud = fitCloud;
})();
</script>
