(function(){
  const root = document.getElementById('ecm');
  if(!root) return;
  const $  = (s,c=root)=>c.querySelector(s);
  const $$ = (s,c=root)=>Array.from(c.querySelectorAll(s));

  /* collapse lists by default */
  $$('.ecm__mod').forEach(mod=>{
    const btn = $('.ecm__tgl', mod), list = $('.ecm__list', mod);
    if(!btn || !list) return;
    list.style.display = 'none';
    btn.addEventListener('click', ()=>{ list.style.display = (list.style.display==='none')?'block':'none'; });
  });

  /* viewer load */
  const stage = $('#ecmStage'), title = $('#ecmTitle');
  const openBtn = $('#ecmOpen'), doneBtn = $('#ecmDone');
  let currentKey = null;

  function render(url, type){
    stage.innerHTML = '';
    let el;
    if(type==='video' || /\.(mp4|webm)$/i.test(url)){
      el = document.createElement('video'); el.controls = true; el.src = url;
    }else if(type==='pdf' || /\.pdf(\?|$)/i.test(url)){
      el = document.createElement('iframe'); el.src = url;
    }else{
      el = document.createElement('iframe'); el.src = url;
    }
    stage.appendChild(el);
  }

  $$('.ecm__lnk').forEach(a=>{
    a.addEventListener('click', e=>{
      e.preventDefault();
      const url = a.getAttribute('data-url');
      const type = a.getAttribute('data-type') || '';
      const ttl  = a.getAttribute('data-title') || 'Content';
      title.textContent = ttl;
      openBtn.classList.remove('ecm-hide'); openBtn.href = url;
      doneBtn.classList.remove('ecm-hide');
      const cid = $('#ecmTree').getAttribute('data-course-id');
      currentKey = `ecm_done_${cid}_${ttl}`;
      render(url, type);
    });
  });

  /* progress (UI-only) */
  function refreshProgress(){
    const items = $$('.ecm__it');
    const cid = $('#ecmTree').getAttribute('data-course-id');
    let total=0, done=0;
    items.forEach(li=>{
      total++;
      const ttl = $('.ecm__ttl', li)?.textContent || '';
      const key = `ecm_done_${cid}_${ttl}`;
      const isDone = localStorage.getItem(key)==='1';
      li.classList.toggle('is-done', isDone);
      if(isDone) done++;
    });
    const pct = total? Math.round(done*100/total) : 0;
    $('.ecm-progBar').style.width = pct+'%';
    $('#ecmProgTxt').textContent = `${pct}% complete`;
  }
  refreshProgress();

  $('#ecmDone')?.addEventListener('click', ()=>{
    if(!currentKey) return;
    const isDone = localStorage.getItem(currentKey)==='1';
    localStorage.setItem(currentKey, isDone?'0':'1');
    refreshProgress();
  });
})();
