function openCustomerImages(customerUid) {
  const modalEl = document.getElementById('customerImageModal');
  const modal = new bootstrap.Modal(modalEl);

  const body = document.getElementById('customerImageModalBody');
  body.innerHTML = '<div class="text-center text-muted py-5">Loading images...</div>';

  modal.show();

  const params = new URLSearchParams({
    customer_uid: customerUid,
    i_type: 'install_order'
  });

  fetch('/lib/customer_image.php?' + params.toString())
    .then(res => res.text())
    .then(html => {
      body.innerHTML = html;

      // HTML 주입 후, 슬라이더 초기화 (스크립트 실행 기대 X)
      initCustomerImageSlider(body);
    })
    .catch(err => {
      console.error(err);
      body.innerHTML = '<div class="text-danger text-center py-5">Failed to load images.</div>';
    });
}

function initCustomerImageSlider(scopeEl) {
  const slider = scopeEl.querySelector('#customerImageSlider');
  if (!slider) return;

  let images = [];
  let meta = [];

  try {
    images = JSON.parse(slider.dataset.images || '[]');
    meta   = JSON.parse(slider.dataset.meta   || '[]');
  } catch (e) {
    console.error('slider json parse error', e);
    return;
  }

  if (!images.length) return;

  let currentIndex = 0;

  const imgEl  = scopeEl.querySelector('#sliderImage');
  const idxEl  = scopeEl.querySelector('#sliderIndex');
  const metaEl = scopeEl.querySelector('#sliderMeta');
  const btnPrev = scopeEl.querySelector('#btnPrevImage');
  const btnNext = scopeEl.querySelector('#btnNextImage');

  function formatCreated(str) {
    // 기대 포맷: 20260205121137
    if (!str) return '';
    if (/^\d{14}$/.test(str)) {
      return str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6');
    }
    return str; // 이미 datetime 이면 그대로
  }

  function getTypeLabel(type) {
    switch (type) {
      case 'install':
        return 'Install Image';
      case 'install_order':
        return 'Container Request Image';
      default:
        return type || '';
    }
  }

  function update() {
    imgEl.src = images[currentIndex];
    idxEl.textContent = (currentIndex + 1);

    const m = meta[currentIndex] || {};
    metaEl.innerHTML =
      '<b>Type:</b> ' + getTypeLabel(m.type || '') + '<br>' +
      '<b>Note:</b> ' + ((m.note || '').replace(/\n/g, '<br>')) + '<br>' +
      '<b>Created:</b> ' + formatCreated(m.created || '') + '<br>' +
      '<b>By:</b> ' + (m.by || '');
  }

  // 이벤트 중복 방지: 버튼을 클론으로 교체해서 기존 리스너 제거
  const prevClone = btnPrev.cloneNode(true);
  const nextClone = btnNext.cloneNode(true);
  btnPrev.parentNode.replaceChild(prevClone, btnPrev);
  btnNext.parentNode.replaceChild(nextClone, btnNext);

  prevClone.addEventListener('click', () => {
    currentIndex = (currentIndex - 1 + images.length) % images.length;
    update();
  });

  nextClone.addEventListener('click', () => {
    currentIndex = (currentIndex + 1) % images.length;
    update();
  });

  // 초기 렌더
  update();
}
