(()=>{
 const dialog=document.querySelector('#pp-dialog'),calendar=document.querySelector('#pp-calendar'),daySelect=document.querySelector('#pp-day-select'),discipline=document.querySelector('#pp-discipline'),type=document.querySelector('#pp-type'),start=document.querySelector('#pp-start'),end=document.querySelector('#pp-end'),duration=document.querySelector('#pp-duration'),preview=document.querySelector('#pp-preview'),capacity=document.querySelector('#pp-capacity-wrap'),selectedDay=document.querySelector('#pp-selected-day'),selectedHours=document.querySelector('#pp-selected-hours');
 let current='lundi',drag=null;
 const dayNames={lundi:'Lundi',mardi:'Mardi',mercredi:'Mercredi',jeudi:'Jeudi',vendredi:'Vendredi',samedi:'Samedi',dimanche:'Dimanche'};
 const minutes=v=>{const p=v.split(':').map(Number);return p[0]*60+p[1]};
 const clock=v=>String(Math.floor(v/60)).padStart(2,'0')+':'+String(v%60).padStart(2,'0');
 const gridMinute=(grid,clientY)=>Math.max(0,Math.min(840,Math.round((clientY-grid.getBoundingClientRect().top)/15)*15));
 function refresh(){
  const option=discipline.selectedOptions[0],size=+(type.value==='individuel'?option?.dataset.individual:option?.dataset.collective)||30;
  duration.textContent='Durée prévue : '+size+' minutes par cours';capacity.hidden=type.value==='individuel';
  selectedDay.textContent=dayNames[daySelect.value]||daySelect.value;selectedHours.textContent=start.value+'–'+end.value;
  const from=minutes(start.value),to=minutes(end.value);
  if(to<=from){preview.textContent='La plage doit avoir une durée positive.';return}
  if(type.value==='collectif'){preview.textContent='Un bloc collectif de '+start.value+' à '+end.value+'.';return}
  const count=(to-from)/size;
  preview.textContent=Number.isInteger(count)?count+' créneau(x) généré(s) : '+Array.from({length:count},(_,i)=>clock(from+i*size)+'–'+clock(from+(i+1)*size)).join(' · '):'La plage doit être divisible par '+size+' minutes.';
 }
 function selectDay(day){
  current=day;calendar.classList.remove('week');
  document.querySelectorAll('.pp-days button').forEach(x=>x.classList.toggle('active',x.dataset.day===day));
  document.querySelectorAll('[data-day-column]').forEach(x=>x.classList.toggle('active',x.dataset.dayColumn===day));
  daySelect.value=day;
 }
 function openSelection(day,from,to){current=day;daySelect.value=day;start.value=clock(8*60+from);end.value=clock(8*60+to);refresh();dialog.showModal()}
 function removeDraft(){document.querySelectorAll('.pp-draft').forEach(x=>x.remove())}
 function paintDraft(){
  if(!drag)return;const lo=Math.min(drag.anchor,drag.edge),hi=Math.max(lo+15,Math.max(drag.anchor,drag.edge));
  drag.draft.style.top=lo+'px';drag.draft.style.height=(hi-lo)+'px';
  drag.draft.innerHTML='<b>'+clock(8*60+lo)+'–'+clock(8*60+hi)+'</b><span>Relâchez pour choisir la discipline</span>';
 }
 document.querySelectorAll('.pp-days button').forEach(b=>b.addEventListener('click',()=>selectDay(b.dataset.day)));
 document.querySelector('#pp-week').addEventListener('click',()=>calendar.classList.toggle('week'));
 document.querySelector('#pp-new').addEventListener('click',()=>{daySelect.value=current;start.value='15:00';end.value='17:00';refresh();dialog.showModal()});
 document.querySelector('#pp-close').addEventListener('click',()=>dialog.close());
 document.querySelectorAll('.pp-grid').forEach(grid=>{
  grid.addEventListener('pointerdown',e=>{if(e.target.closest('.pp-slot'))return;e.preventDefault();removeDraft();grid.setPointerCapture(e.pointerId);const anchor=gridMinute(grid,e.clientY),draft=document.createElement('div');draft.className='pp-draft';grid.appendChild(draft);drag={grid,anchor,edge:anchor+15,draft};paintDraft()});
  grid.addEventListener('pointermove',e=>{if(!drag||drag.grid!==grid)return;drag.edge=gridMinute(grid,e.clientY);paintDraft()});
  grid.addEventListener('pointerup',()=>{if(!drag||drag.grid!==grid)return;const lo=Math.min(drag.anchor,drag.edge),hi=Math.max(lo+15,Math.max(drag.anchor,drag.edge)),day=grid.dataset.day;removeDraft();drag=null;openSelection(day,lo,hi)});
  grid.addEventListener('pointercancel',()=>{removeDraft();drag=null});
 });
 [discipline,type,daySelect].forEach(x=>x.addEventListener('change',refresh));refresh();
})();
