/* Supernova: visibility-managed animation and media. */ (() => { 'use strict'; const reduced=matchMedia('(prefers-reduced-motion: reduce)'); const root=document.documentElement; const visibilityCallbacks=[]; let scrolling=false,scrollTimer=0; function notify(){visibilityCallbacks.forEach(fn=>fn());} addEventListener('scroll',()=>{ if(!scrolling){scrolling=true;root.classList.add('page-scrolling');notify();} clearTimeout(scrollTimer);scrollTimer=setTimeout(()=>{scrolling=false;root.classList.remove('page-scrolling');notify();},140); },{passive:true}); document.addEventListener('visibilitychange',()=>{root.classList.toggle('page-hidden',document.hidden);notify();}); reduced.addEventListener('change',notify); // Copy only lightweight content: video players are mounted later, never cloned. document.querySelectorAll('.loop-carousel').forEach((box,index)=>{ const track=box.querySelector('.loop-track'),items=[...track.children],n=items.length; for(let copy=0;copy<2;copy++){ const batch=document.createDocumentFragment(); items.forEach(item=>{ const clone=item.cloneNode(true);clone.setAttribute('aria-hidden','true'); clone.querySelectorAll('[id]').forEach(el=>el.removeAttribute('id')); clone.querySelectorAll('a,button,iframe').forEach(el=>el.tabIndex=-1); batch.append(clone); }); if(copy===0)track.prepend(batch);else track.append(batch); } let cycle=0,x=0,previous=0,raf=0,visible=false,hover=false,focus=false,drag=null,tween=null,moved=false; const direction=Number(box.dataset.direction||1),speed=index===0?64:36; function paint(){if(!cycle)return;x=((x-cycle)%cycle+cycle)%cycle+cycle;track.style.transform=`translate3d(${-x}px,0,0)`;} function canRun(){return visible&&!document.hidden&&!scrolling&&(tween||(!reduced.matches&&!hover&&!focus&&!drag));} function wake(){if(canRun()&&!raf){previous=performance.now();raf=requestAnimationFrame(tick);}else if(!canRun()&&raf){cancelAnimationFrame(raf);raf=0;}} function tick(now){ raf=0;if(!canRun())return; const dt=Math.min((now-previous)/1000,.05);previous=now; if(tween){const p=Math.min(1,(now-tween.start)/420),ease=1-Math.pow(1-p,3);x=tween.from+tween.delta*ease;if(p===1)tween=null;} else x+=dt*speed*direction; paint();if(canRun())raf=requestAnimationFrame(tick); } function measure(){const old=cycle;cycle=track.children[n].offsetLeft-track.children[0].offsetLeft;if(cycle>0)x=old?x/old*cycle:cycle;paint();wake();} new ResizeObserver(measure).observe(box);measure(); new IntersectionObserver(es=>{visible=es[0].isIntersecting;box.classList.toggle('motion-visible',visible);wake();}).observe(box); visibilityCallbacks.push(wake); function step(sign){const delta=sign*(items[0].getBoundingClientRect().width+parseFloat(getComputedStyle(track).gap));if(reduced.matches){x+=delta;paint();return;}tween={start:performance.now(),from:x,delta};wake();} box.querySelector('.arrow-left').onclick=()=>step(-1); box.querySelector('.arrow-right').onclick=()=>step(1); box.addEventListener('pointerenter',e=>{if(e.pointerType==='mouse'){hover=true;wake();}}); box.addEventListener('pointerleave',()=>{hover=false;wake();}); box.addEventListener('focusin',()=>{focus=true;wake();}); box.addEventListener('focusout',()=>queueMicrotask(()=>{focus=box.contains(document.activeElement);wake();})); box.addEventListener('pointerdown',e=>{if(e.button!==0||e.target.closest('button'))return;drag={id:e.pointerId,startX:e.clientX,startY:e.clientY,last:e.clientX};moved=false;tween=null;wake();}); box.addEventListener('pointermove',e=>{ if(!drag||drag.id!==e.pointerId)return; const dx=e.clientX-drag.startX,dy=e.clientY-drag.startY; if(!moved&&Math.abs(dy)>8&&Math.abs(dy)>Math.abs(dx)){drag=null;wake();return;} if(!moved&&Math.abs(dx)>6&&Math.abs(dx)>Math.abs(dy)){moved=true;box.setPointerCapture(e.pointerId);box.classList.add('dragging');} if(moved){x+=drag.last-e.clientX;paint();}drag.last=e.clientX; }); function end(e){if(!drag)return;drag=null;if(box.hasPointerCapture(e.pointerId))box.releasePointerCapture(e.pointerId);box.classList.remove('dragging');wake();} box.addEventListener('pointerup',end);box.addEventListener('pointercancel',end); box.addEventListener('lostpointercapture',()=>{drag=null;box.classList.remove('dragging');wake();}); box.addEventListener('dragstart',e=>e.preventDefault()); box.addEventListener('click',e=>{if(moved){e.preventDefault();e.stopPropagation();moved=false;}},true); box.addEventListener('keydown',e=>{if(e.target===box&&['ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();step(e.key==='ArrowLeft'?-1:1);}}); }); // Animate decorative borders only while visible. No per-frame JS needed. const decorObserver=new IntersectionObserver(entries=>entries.forEach(e=>e.target.classList.toggle('motion-visible',e.isIntersecting))); document.querySelectorAll('.btn,button,.whatsapp,.curriculum-nav a,.outcome-link,.ticker-track').forEach(el=>decorObserver.observe(el)); // Stable, untransformed section geometry avoids scale/position feedback. const film=document.querySelector('.hero-film'),feature=film.closest('.sn-feature'); let filmVisible=false,filmRaf=0,lastFilm=''; function updateFilm(){ filmRaf=0;if(!filmVisible||document.hidden||reduced.matches)return; const rect=feature.getBoundingClientRect(); const p=Math.max(0,Math.min(1,(innerHeight-rect.top)/(innerHeight+rect.height))); const swell=Math.sin(p*Math.PI),scale=(.90+.10*swell).toFixed(4),tilt=(-4+2*swell).toFixed(3); if(lastFilm===scale+tilt)return;lastFilm=scale+tilt; film.style.setProperty('--film-scale',scale);film.style.setProperty('--film-tilt',tilt+'deg'); } function queueFilm(){if(filmVisible&&!document.hidden&&!reduced.matches&&!filmRaf)filmRaf=requestAnimationFrame(updateFilm);} new IntersectionObserver(entries=>{filmVisible=entries[0].isIntersecting;if(!filmVisible&&filmRaf){cancelAnimationFrame(filmRaf);filmRaf=0;}queueFilm();}).observe(film); addEventListener('scroll',queueFilm,{passive:true});addEventListener('resize',queueFilm);visibilityCallbacks.push(queueFilm); // Native hero video pauses as soon as it leaves the viewport. const background=document.querySelector('video.hero-art');let backgroundVisible=false; function syncBackground(){if(backgroundVisible&&!document.hidden&&!reduced.matches){background.muted=true;background.play().catch(()=>{});}else background.pause();} new IntersectionObserver(entries=>{backgroundVisible=entries[0].isIntersecting;syncBackground();},{threshold:.01}).observe(background); visibilityCallbacks.push(syncBackground); function loadScript(src){return new Promise((resolve,reject)=>{const s=document.createElement('script');s.src=src;s.async=true;s.onload=resolve;s.onerror=reject;document.head.append(s);});} // Intro uses Bunny's player.js API to pause without resetting the user's position. const intro=document.getElementById('intro-player'); let introVisible=false,introPlayer=null,introReady=false,introStarted=false,introLoading=false,introFailed=false,introActive=null; function syncIntro(){ if(introVisible&&!document.hidden&&!introLoading){ introLoading=true; loadScript('https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js').then(()=>{ intro.src=intro.dataset.src; introPlayer=new playerjs.Player(intro); introPlayer.on('ready',()=>{introReady=true;syncIntro();}); }).catch(()=>{introFailed=true;if(introVisible&&!document.hidden)intro.src=intro.dataset.src;}); } if(introFailed){ if(!introVisible||document.hidden)intro.removeAttribute('src'); else if(!intro.hasAttribute('src'))intro.src=intro.dataset.src; return; } if(!introReady)return; const active=introVisible&&!document.hidden; if(active===introActive)return;introActive=active; if(!active){introPlayer.pause();return;} if(!reduced.matches){if(!introStarted){introPlayer.mute();introStarted=true;}introPlayer.play();} } new IntersectionObserver(entries=>{introVisible=entries[0].isIntersecting;syncIntro();},{threshold:.05}).observe(intro); visibilityCallbacks.push(syncIntro); // Only visible YouTube slots get players; never more than four, regardless of clones. const slots=[...document.querySelectorAll('.student-slot')],ratios=new Map(),players=new Map(),positions=new Map(); let youtubePromise=null,syncQueued=false; function youtubeAPI(){ if(window.YT&&YT.Player)return Promise.resolve(); if(youtubePromise)return youtubePromise; youtubePromise=new Promise((resolve,reject)=>{ const previous=window.onYouTubeIframeAPIReady; window.onYouTubeIframeAPIReady=()=>{if(previous)previous();resolve();}; loadScript('https://www.youtube.com/iframe_api').catch(reject); }).catch(e=>{youtubePromise=null;throw e;});return youtubePromise; } function destroy(slot){ const entry=players.get(slot);if(!entry)return; try{if(entry.ready)positions.set(slot.dataset.youtubeId,entry.player.getCurrentTime());entry.player.destroy();}catch{} players.delete(slot);slot.classList.remove('player-ready');slot.querySelectorAll('iframe,.player-mount').forEach(el=>el.remove()); } function fallback(slot){ if(slot.querySelector('.student-fallback'))return; const a=document.createElement('a');a.className='student-fallback';a.href='https://www.youtube.com/watch?v='+slot.dataset.youtubeId;a.target='_blank';a.rel='noopener';a.textContent='مشاهدة المشروع ↗'; if(slot.closest('[aria-hidden="true"]'))a.tabIndex=-1;slot.append(a); } function desiredSlots(){return document.hidden||reduced.matches?[]:slots.filter(s=>(ratios.get(s)||0)>.12).sort((a,b)=>ratios.get(b)-ratios.get(a)).slice(0,4);} function scheduleVideos(){if(syncQueued)return;syncQueued=true;queueMicrotask(()=>{syncQueued=false;syncVideos();});} function syncVideos(){ const wanted=desiredSlots(); for(const slot of players.keys())if(!wanted.includes(slot))destroy(slot); if(!wanted.length)return; youtubeAPI().then(()=>{ const current=desiredSlots(); for(const slot of current){ if(players.has(slot))continue; const mount=document.createElement('div');mount.className='player-mount';slot.append(mount); const entry={ready:false,player:null};players.set(slot,entry); const vars={autoplay:0,mute:1,playsinline:1,controls:0,disablekb:1,rel:0,loop:1,playlist:slot.dataset.youtubeId}; if(location.protocol==='http:'||location.protocol==='https:')vars.origin=location.origin; entry.player=new YT.Player(mount,{videoId:slot.dataset.youtubeId,width:'100%',height:'100%',playerVars:vars,events:{ onReady:event=>{ if(players.get(slot)!==entry)return; entry.ready=true;const frame=event.target.getIframe();frame.className='student-frame';frame.title=slot.dataset.title;frame.tabIndex=-1; if(!desiredSlots().includes(slot)){destroy(slot);return;} event.target.mute();const at=positions.get(slot.dataset.youtubeId);if(at)event.target.seekTo(at,true);event.target.playVideo(); }, onStateChange:event=>{if(players.get(slot)!==entry)return;if(event.data===1){if(!desiredSlots().includes(slot)){destroy(slot);return;}slot.classList.add('player-ready');}}, onAutoplayBlocked:()=>fallback(slot),onError:()=>fallback(slot) }}); } }).catch(()=>wanted.forEach(fallback)); } const slotObserver=new IntersectionObserver(entries=>{entries.forEach(e=>ratios.set(e.target,e.isIntersecting?e.intersectionRatio:0));scheduleVideos();},{threshold:[0,.01,.12,.25,.5,.75,1]}); slots.forEach(slot=>slotObserver.observe(slot));visibilityCallbacks.push(scheduleVideos); // Reduced-motion users keep explicit watch links instead of automatic playback. if(reduced.matches)slots.forEach(fallback); reduced.addEventListener('change',()=>{if(reduced.matches)slots.forEach(fallback);else slots.forEach(s=>s.querySelector('.student-fallback')?.remove());}); })();