// Lädt skinview3d von CDN
(function(){
  if(document.getElementById('skinview3d-cdn')) return;
  var s = document.createElement('script');
  s.id = 'skinview3d-cdn';
  s.src = 'https://unpkg.com/skinview3d@4.1.1/bundles/skinview3d.min.js';
  s.onload = function() {
    window.skinview3dReady = true;
  };
  document.head.appendChild(s);
})();

window.showMinecraftSkinModal = function(uuid) {
  if(document.getElementById('minecraft-skin-modal')) return;
  var modal = document.createElement('div');
  modal.id = 'minecraft-skin-modal';
  modal.innerHTML = `
    <div class="sv3d-modal-bg"></div>
    <div class="sv3d-modal-content">
      <button class="sv3d-modal-close" aria-label="Schließen">&times;</button>
      <div id="sv3d-canvas-wrap" style="width:320px;height:320px;"></div>
    </div>
  `;
  document.body.appendChild(modal);
  document.querySelector('.sv3d-modal-close').onclick = function(){ modal.remove(); };
  document.querySelector('.sv3d-modal-bg').onclick = function(){ modal.remove(); };

  function renderSkin() {
    var skinUrl = `https://crafatar.com/skins/${uuid}`;
    var canvas = document.createElement('canvas');
    canvas.width = 320; canvas.height = 320;
    document.getElementById('sv3d-canvas-wrap').appendChild(canvas);
    var viewer = new skinview3d.SkinViewer({
      canvas: canvas,
      width: 320,
      height: 320,
      skin: skinUrl
    });
    viewer.controls.enableZoom = false;
    viewer.animation = new skinview3d.WalkingAnimation();
    viewer.animation.speed = 1.2;
    viewer.animation.play();
  }
  if(window.skinview3dReady) renderSkin();
  else {
    var check = setInterval(function(){
      if(window.skinview3dReady) { clearInterval(check); renderSkin(); }
    }, 100);
  }
};

// Avatar-Widget-Click-Handler
window.addEventListener('DOMContentLoaded', function(){
  var widget = document.getElementById('minecraft-avatar-widget');
  if(widget) {
    widget.style.cursor = 'pointer';
    widget.title = 'Klicke für 3D Skin-Ansicht';
    widget.onclick = function(){
      var uuid = widget.getAttribute('data-uuid');
      if(uuid) window.showMinecraftSkinModal(uuid);
    };
  }
});
