(()=>{
 const dialog=document.querySelector('#pp-dialog'),form=dialog?.querySelector('form'),calendar=document.querySelector('#pp-calendar');
 if(!dialog||!form||!calendar)return;
 const room=document.querySelector('#pp-room'),archive=document.querySelector('#pp-archive'),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'),capacityWrap=document.querySelector('#pp-capacity-wrap'),capacity=document.querySelector('#pp-capacity'),selectedDay=document.querySelector('#pp-selected-day'),selectedHours=document.querySelector('#pp-selected-hours'),slotId=document.querySelector('#pp-slot-id'),dateStart=document.querySelector('#pp-date-start'),dateEnd=document.querySelector('#pp-date-end'),save=document.querySelector('#pp-save'),title=document.querySelector('#pp-dialog-title'),kicker=document.querySelector('#pp-dialog-kicker');
 let current='lundi',gesture=null;
 const dayNames={lundi:'Lundi',mardi:'Mardi',mercredi:'Mercredi',jeudi:'Jeudi',vendredi:'Vendredi',samedi:'Samedi',dimanche:'Dimanche'};
 const minutes=v=>{const p=String(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 snapDelta=v=>Math.round(v/15)*15;
 const snap=v=>Math.max(0,Math.min(840,snapDelta(v)));
 const boundedMove=(top,height)=>Math.max(0,Math.min(840-height,snap(top)));
 const gridMinute=(grid,y)=>snap(y-grid.getBoundingClientRect().top);
 const schoolYear=window.CDA_PLANNING_YEAR||{};
 const validDate=v=>/^\d{4}-\d{2}-\d{2}$/.test(String(v||''))&&Number(String(v).slice(0,4))>=2000;
 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';capacityWrap.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(slotId.value){preview.textContent='Les horaires et le contenu de cette plage existante seront remplacés.';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) seront générés.':'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 createMode(day,from,to){
  slotId.value='';if(room)room.value='';if(archive)archive.hidden=true;form.action=form.dataset.createAction;kicker.textContent='NOUVELLE DISPONIBILITÉ';title.textContent='Choisir la discipline';save.textContent='Créer les créneaux';
  dateStart.value=validDate(schoolYear.start)?schoolYear.start:'';
  dateEnd.value=validDate(schoolYear.end)?schoolYear.end:'';
  daySelect.value=day;start.value=clock(8*60+from);end.value=clock(8*60+to);refresh();dialog.showModal();
 }
 function editMode(slot,day=slot.dataset.day,from=minutes(slot.dataset.start)-480,to=minutes(slot.dataset.end)-480){
  slotId.value=slot.dataset.slotId;if(room)room.value=slot.dataset.roomId||'';if(archive)archive.hidden=false;form.action=form.dataset.updateAction;kicker.textContent='MODIFICATION DE LA PLAGE';title.textContent='Modifier le créneau';save.textContent='Enregistrer les modifications';
  daySelect.value=day;discipline.value=slot.dataset.disciplineId;type.value=slot.dataset.type;capacity.value=slot.dataset.capacity||1;dateStart.value=validDate(slot.dataset.dateStart)?slot.dataset.dateStart:(validDate(schoolYear.start)?schoolYear.start:'');dateEnd.value=validDate(slot.dataset.dateEnd)?slot.dataset.dateEnd:(validDate(schoolYear.end)?schoolYear.end:'');start.value=clock(480+from);end.value=clock(480+to);refresh();dialog.showModal();
 }
 function draft(grid,lo,hi,text){let el=grid.querySelector('.pp-draft');if(!el){el=document.createElement('div');el.className='pp-draft';grid.appendChild(el)}el.style.top=lo+'px';el.style.height=Math.max(15,hi-lo)+'px';el.innerHTML='<b>'+clock(480+lo)+'–'+clock(480+hi)+'</b><span>'+text+'</span>';return el}
 function clearDraft(){document.querySelectorAll('.pp-draft').forEach(x=>x.remove())}
 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',()=>createMode(current,420,540));
 const remoteDialog=document.querySelector('#pp-remote-dialog'),remoteButton=document.querySelector('#pp-new-remote');
 if(remoteDialog&&remoteButton){
  remoteButton.addEventListener('click',()=>{
   const today=new Date().toISOString().slice(0,10),yearStart=validDate(schoolYear.start)?schoolYear.start:today,yearEnd=validDate(schoolYear.end)?schoolYear.end:today;
   document.querySelector('#pp-remote-date').value=today<yearStart?yearStart:(today>yearEnd?yearEnd:today);
   document.querySelector('#pp-remote-start').value=start.value||'09:00';
   document.querySelector('#pp-remote-end').value=end.value||'12:00';
   remoteDialog.showModal();
  });
  document.querySelector('#pp-remote-close').addEventListener('click',()=>remoteDialog.close());
 }
 document.querySelector('#pp-close').addEventListener('click',()=>dialog.close());
 document.querySelectorAll('.pp-slot').forEach(slot=>{
  slot.addEventListener('click',e=>{if(slot.dataset.justDragged==='1'){slot.dataset.justDragged='';return}editMode(slot)});
  slot.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();editMode(slot)}});
  slot.addEventListener('pointerdown',e=>{
   if(e.button!==undefined&&e.button!==0)return;
   e.preventDefault();e.stopPropagation();const grid=slot.parentElement,resize=!!e.target.closest('.pp-resize-handle'),originTop=parseFloat(slot.style.top),originHeight=parseFloat(slot.style.height),originY=e.clientY;
   gesture={kind:resize?'resize':'move',pointerId:e.pointerId,slot,grid,originTop,originHeight,originY,lo:originTop,hi:originTop+originHeight,moved:false};
   try{slot.setPointerCapture(e.pointerId)}catch(_){}
   slot.classList.add('is-dragging');document.body.classList.add(resize?'pp-is-resizing':'pp-is-dragging');
  });
 });
 function finishSlotGesture(cancelled=false){
  if(!gesture||!gesture.slot)return;
  const g=gesture,slot=g.slot;slot.classList.remove('is-dragging');document.body.classList.remove('pp-is-dragging','pp-is-resizing');
  try{if(slot.hasPointerCapture(g.pointerId))slot.releasePointerCapture(g.pointerId)}catch(_){}
  if(cancelled){slot.style.top=g.originTop+'px';slot.style.height=g.originHeight+'px'}
  else if(g.moved){slot.dataset.justDragged='1';editMode(slot,g.grid.dataset.day,g.lo,g.hi)}
  gesture=null;
 }
 window.addEventListener('pointermove',e=>{
  if(!gesture||!gesture.slot||e.pointerId!==gesture.pointerId)return;
  e.preventDefault();const delta=snapDelta(e.clientY-gesture.originY);if(Math.abs(e.clientY-gesture.originY)>4)gesture.moved=true;
  if(gesture.kind==='move'){gesture.lo=boundedMove(gesture.originTop+delta,gesture.originHeight);gesture.hi=gesture.lo+gesture.originHeight}
  else{gesture.lo=gesture.originTop;gesture.hi=Math.max(gesture.lo+15,Math.min(840,snap(gesture.originTop+gesture.originHeight+delta)))}
  gesture.slot.style.top=gesture.lo+'px';gesture.slot.style.height=(gesture.hi-gesture.lo)+'px';
 },{passive:false});
 window.addEventListener('pointerup',e=>{if(gesture?.slot&&e.pointerId===gesture.pointerId)finishSlotGesture(false)},true);
 window.addEventListener('pointercancel',e=>{if(gesture?.slot&&e.pointerId===gesture.pointerId)finishSlotGesture(true)});
 document.querySelectorAll('.pp-grid').forEach(grid=>{
  grid.addEventListener('pointerdown',e=>{if(e.target.closest('.pp-slot'))return;e.preventDefault();grid.setPointerCapture(e.pointerId);const anchor=gridMinute(grid,e.clientY);gesture={kind:'create',grid,anchor,edge:anchor+15};draft(grid,anchor,anchor+15,'Relâchez pour choisir la discipline')});
  grid.addEventListener('pointermove',e=>{if(!gesture||gesture.kind!=='create'||gesture.grid!==grid)return;gesture.edge=gridMinute(grid,e.clientY);const lo=Math.min(gesture.anchor,gesture.edge),hi=Math.max(lo+15,Math.max(gesture.anchor,gesture.edge));draft(grid,lo,hi,'Relâchez pour choisir la discipline')});
  grid.addEventListener('pointerup',()=>{if(!gesture||gesture.kind!=='create'||gesture.grid!==grid)return;const lo=Math.min(gesture.anchor,gesture.edge),hi=Math.max(lo+15,Math.max(gesture.anchor,gesture.edge)),day=grid.dataset.day;clearDraft();gesture=null;createMode(day,lo,hi)});
  grid.addEventListener('pointercancel',()=>{if(gesture?.kind==='create'){clearDraft();gesture=null}});
 });
 [discipline,type,daySelect,start,end].forEach(x=>{x.addEventListener('change',refresh);x.addEventListener('input',refresh)});refresh();
})();
