import button from"./templates/button";import marker from"./templates/timeline-marker";import toc from"./templates/toc";import tocItem from"./templates/toc-item";export function addChapterControl(e){let t,r,a,n,o,i,l,p,s,c,d,m,f=0,u={},y={},h=null,g=0;if("undefined"==typeof jQuery)return;if(r=e.detail.plyr,t=function(e=[]){if(!e.length)return e;let t={};return e.forEach(e=>{let r,a=e.time.split(":");a.length>1&&(r=60*parseInt(a[0]));let n=parseInt(a[1])+parseInt(r);t[n]=e}),t}(r?.config?.chapters||[]),"html5"===r.provider&&!r.duration)return void r.on("loadedmetadata",addChapterControl);if(!t||!Object.keys(t).length)return;a=jQuery(r.elements.container).closest(".presto-player__wrapper").find(".plyr"),m=jQuery(r.elements.controls);let _=m.find(".plyr__time");_=_.length?_:m.find(".plyr__progress__container"),l=a.find('[data-plyr="chapters"]'),l.length||(l=jQuery(button).insertAfter(_)),o=a.find(".presto-player-toc__wrapper"),o.length||(o=jQuery(toc).appendTo(a)),p=o.find("[data-player-toc-cover]"),i=o.find("[data-player-toc]"),n=a.find(".plyr__progress__container");let k=jQuery('<div class="presto-player__chapters"></div>').appendTo(n);function v(){f=r.currentTime;let e=Object.keys(t).filter(e=>e<=f).map(e=>parseInt(e,10)),a=Math.max(...e);d&&d.removeClass("is-highlighted"),jQuery(u[a||0]).addClass("is-highlighted")}function j(){r.duration&&(Object.keys(t).forEach(e=>{if(!parseInt(e))return;if(s.find(`[data-timestamp=${e}]`).length)return;const a=t[e];let n=parseInt(e)/r.duration*100,o=jQuery(marker({position:n,name:`${a.title}`})).prependTo(s);o.attr("data-timestamp",e),o.data("timestamp",e),y[e]=o,o.on("click",t=>{r.currentTime=parseInt(e),r.play()})}),c=o.find("[data-timeline-marker]"))}function I(e){void 0!==typeof e?o.toggleClass("is-showing",e):o.toggleClass("is-showing")}s=jQuery('<div class="presto-player__chapter-markers"></div>').appendTo(k),function(){let e=0;i.find(".presto-player-toc__chapter").length||(Object.keys(t).forEach(a=>{e++;const n=t[a],o=jQuery(tocItem({name:n.title,order:e})).appendTo(i);o.data("presto-player-timestamp",a),u[a]=o,o.on("click",()=>{r.currentTime=parseFloat(a),r.playing||(r.play(),r.once("playing",()=>{setTimeout(()=>{r.pause()},50)})),I(!1)})}),d=o.find("[data-chapter-item]"))}(),j(),l.off("click"),l.on("click",I),v(),r.off("timeupdate"),r.on("timeupdate",v),h=window.setInterval(function(){g++,r.duration&&(j(),window.clearInterval(h)),g>50&&window.clearInterval(h)},100),p.off("click"),p.on("click",()=>I(!1)),i.off("mouseleave"),i.on("mouseleave",function e(){if(r.playing){let t=setTimeout(()=>{I(!1),i.off("mouseleave",e)},2e3);i.on("mouseenter",()=>{clearTimeout(t)})}})}