
/* /survey/static/src/interactions/survey_session_colors.js */
odoo.define('@survey/interactions/survey_session_colors',[],function(require){'use strict';let __exports={};__exports[Symbol.for("default")]=["31,119,180","255,127,14","174,199,232","255,187,120","44,160,44","152,223,138","214,39,40","255,152,150","148,103,189","197,176,213","140,86,75","196,156,148","227,119,194","247,182,210","127,127,127","199,199,199","188,189,34","219,219,141","23,190,207","158,218,229",];return __exports;});;

/* /survey/static/src/interactions/survey_session_chart.js */
odoo.define('@survey/interactions/survey_session_chart',['@web/core/assets','@survey/interactions/survey_session_colors','@web/core/registry','@web/public/interaction'],function(require){'use strict';let __exports={};const{loadJS}=require("@web/core/assets");const SESSION_CHART_COLORS=require("@survey/interactions/survey_session_colors")[Symbol.for("default")];const{registry}=require("@web/core/registry");const{Interaction}=require("@web/public/interaction");const SurveySessionChart=__exports.SurveySessionChart=class SurveySessionChart extends Interaction{static selector=".o_survey_session_chart";dynamicContent={_root:{"t-on-updateState":this.updateState,"t-att-class":()=>({chart_is_ready:!!this.chart}),},};setup(){const sessionManageEl=this.el.closest(".o_survey_session_manage");this.questionType=sessionManageEl.dataset.questionType;this.answersValidity=JSON.parse(sessionManageEl.dataset.answersValidity);this.hasCorrectAnswers=sessionManageEl.dataset.hasCorrectAnswers;this.questionStatistics=this.processQuestionStatistics(JSON.parse(sessionManageEl.dataset.questionStatistics));this.showAnswers=false;this.showInputs=false;}
async willStart(){await loadJS("/survey/static/src/js/libs/chartjs-plugin-datalabels.js");}
start(){const canvas=this.el.querySelector("canvas");const ctx=canvas.getContext("2d");this.chart=new Chart(ctx,this.buildChartConfiguration());this.registerCleanup(()=>this.chart.destroy());this.env.bus.trigger("SURVEY:CHART_INTERACTION_STARTED");}
updateState(ev){if("showInputs"in ev.detail){this.showInputs=ev.detail.showInputs;}
if("showAnswers"in ev.detail){this.showAnswers=ev.detail.showAnswers;}
this.updateChart(ev.detail.questionStatistics);}
updateChart(questionStatistics){if(questionStatistics){this.questionStatistics=this.processQuestionStatistics(questionStatistics);}
if(this.chart){const chartData=this.chart.data.datasets[0].data;for(let i=0;i<chartData.length;i++){const value=this.showInputs?this.questionStatistics[i].count:0;this.chart.data.datasets[0].data[i]=value;}
this.chart.update();}}
buildChartConfiguration(){return{type:"bar",data:{labels:this.extractChartLabels(),datasets:[{backgroundColor:this.getBackgroundColor.bind(this),data:this.extractChartData(),},],},options:{maintainAspectRatio:false,plugins:{datalabels:{color:this.getLabelColor.bind(this),font:{size:"50",weight:"bold",},anchor:"end",align:"top",},legend:{display:false,},tooltip:{enabled:false,},},scales:{y:{ticks:{display:false,},grid:{display:false,},},x:{ticks:{minRotation:20,maxRotation:90,font:{size:"35",weight:"bold",},color:"#212529",autoSkip:false,},grid:{drawOnChartArea:false,color:"rgba(0, 0, 0, 0.2)",},},},layout:{padding:{left:0,right:0,top:70,bottom:0,},},},plugins:[ChartDataLabels,{beforeInit:function(chart){const nbrCol=chart.data.labels.length;const minRatio=0.4;const charPerLineBreakpoints=[[1,2,35,minRatio],[3,4,30,minRatio],[5,6,30,0.45],[7,8,30,0.65],[9,null,30,0.7],];let charPerLine;let fontRatio;charPerLineBreakpoints.forEach(([lowerBound,upperBound,value,ratio])=>{if(nbrCol>=lowerBound&&(upperBound===null||nbrCol<=upperBound)){charPerLine=value;fontRatio=ratio;}});if(charPerLine<35){const allWords=chart.data.labels.reduce((accumulator,words)=>accumulator.concat(" ".concat(words)));const maxWordLength=Math.max(...allWords.split(" ").map((word)=>word.length));fontRatio=maxWordLength>charPerLine?minRatio:fontRatio;chart.options.scales.x.ticks.font.size=Math.min(parseInt(chart.options.scales.x.ticks.font.size),(chart.width*fontRatio)/nbrCol);}
chart.data.labels.forEach(function(label,index,labelsList){const words=label.split(" ");const resultLines=[];let currentLine=[];for(let i=0;i<words.length;i++){let word=words[i];while(word.length>charPerLine){resultLines.push(word.slice(0,charPerLine-1)+"-");word=word.slice(charPerLine-1);}
currentLine.push(word);const nextWord=i+1<words.length?words[i+1]:null;if(nextWord){const nextLength=currentLine.join(" ").length+nextWord.length;if(nextLength<=charPerLine){continue;}}
const newLabelLine=currentLine.join(" ");resultLines.push(newLabelLine);currentLine=[];}
labelsList[index]=resultLines;});},},],};}
extractChartLabels(){return this.questionStatistics.map((point)=>point.text);}
extractChartData(){return Array(this.questionStatistics.length).fill(0);}
getBackgroundColor(metaData){const opacity=this.showAnswers&&this.hasCorrectAnswers&&!this.isValidAnswer(metaData.dataIndex)?"0.2":"0.8";const rgb=SESSION_CHART_COLORS[metaData.dataIndex%SESSION_CHART_COLORS.length];return`rgba(${rgb},${opacity})`;}
getLabelColor(metaData){let color="#212529";if(this.showAnswers&&this.hasCorrectAnswers){color=this.isValidAnswer(metaData.dataIndex)?"#2CBB70":"#D9534F";}
return color;}
isValidAnswer(answerIndex){return this.answersValidity[answerIndex];}
processQuestionStatistics(rawStatistics){if(["multiple_choice","scale"].includes(this.questionType)){return rawStatistics[0].values;}
return rawStatistics;}}
registry.category("public.interactions").add("survey.survey_session_chart",SurveySessionChart);return __exports;});;

/* /survey/static/src/interactions/survey_session_text_answers.js */
odoo.define('@survey/interactions/survey_session_text_answers',['@web/core/l10n/dates','@web/core/registry','@web/core/utils/render','@web/public/interaction','@survey/interactions/survey_session_colors'],function(require){'use strict';let __exports={};const{formatDate,formatDateTime}=require("@web/core/l10n/dates");const{registry}=require("@web/core/registry");const{renderToElement}=require("@web/core/utils/render");const{Interaction}=require("@web/public/interaction");const SESSION_CHART_COLORS=require("@survey/interactions/survey_session_colors")[Symbol.for("default")];const{DateTime}=luxon;const SurveySessionTextAnswers=__exports.SurveySessionTextAnswers=class SurveySessionTextAnswers extends Interaction{static selector=".o_survey_session_text_answers_container";dynamicContent={_root:{"t-on-updateTextAnswers":this.updateTextAnswers,},};setup(){this.answerIds=[];}
updateTextAnswers(ev){const inputLineValues=ev.detail.inputLineValues;const questionType=ev.detail.questionType;inputLineValues.forEach((inputLineValue)=>{if(!this.answerIds.includes(inputLineValue.id)&&inputLineValue.value){let textValue=inputLineValue.value;if(questionType==="date"){textValue=formatDate(DateTime.fromFormat(textValue,"yyyy-MM-dd"));}else if(questionType==="datetime"){textValue=formatDateTime(DateTime.fromFormat(textValue,"yyyy-MM-dd HH:mm:ss"));}
const textAnswerEl=renderToElement("survey.survey_session_text_answer",{value:textValue,borderColor:`rgb(${SESSION_CHART_COLORS[this.answerIds.length % 10]})`,});this.insert(textAnswerEl,this.el);const spanWidth=textAnswerEl.querySelector("span").offsetWidth;const containerEl=textAnswerEl.querySelector(".o_survey_session_text_answer_container");textAnswerEl.style.width=`calc(${spanWidth}px + 1.2rem)`;containerEl.style.width=`calc(${spanWidth}px + 1.2rem)`;containerEl.style.opacity="1";this.answerIds.push(inputLineValue.id);}});}}
registry.category("public.interactions").add("survey.survey_session_text_answers",SurveySessionTextAnswers);return __exports;});;

/* /survey/static/src/interactions/survey_session_leaderboard.js */
odoo.define('@survey/interactions/survey_session_leaderboard',['@survey/utils','@web/public/interaction','@web/core/registry','@web/core/network/rpc','@survey/interactions/survey_session_colors'],function(require){'use strict';let __exports={};const{fadeIn,fadeOut}=require("@survey/utils");const{Interaction}=require("@web/public/interaction");const{registry}=require("@web/core/registry");const{rpc}=require("@web/core/network/rpc");const SESSION_CHART_COLORS=require("@survey/interactions/survey_session_colors")[Symbol.for("default")];const SurveySessionLeaderboard=__exports.SurveySessionLeaderboard=class SurveySessionLeaderboard extends Interaction{static selector=".o_survey_session_manage .o_survey_session_leaderboard";dynamicContent={_root:{"t-on-showLeaderboard":this.showLeaderboard,"t-on-hideLeaderboard":this.hideLeaderboard,},".o_survey_session_leaderboard_bar":{"t-att-style":this.getBarStyle,},".o_survey_session_leaderboard_bar_question":{"t-att-style":this.getBarQuestionStyle,},};getBarStyle(barEl){if(this.leaderboardAnimationPhase==="prepareScores"){const currentScore=parseInt(barEl.closest(".o_survey_session_leaderboard_item").dataset.currentScore);if(currentScore&&currentScore!==0){return{transition:"width 1s cubic-bezier(.4,0,.4,1)",width:this.BAR_MIN_WIDTH,};}}else if(this.leaderboardAnimationPhase==="sumScores"){const{baseRatio,questionRatio}=this.getBarRatios(barEl);const updatedScoreRatio=1-questionRatio;const updatedScoreWidth=`calc(calc(100% - ${this.BAR_WIDTH}) * ${
                updatedScoreRatio * baseRatio
            })`;return{transition:"width ease .5s cubic-bezier(.5,0,.66,1.11)",width:updatedScoreWidth,minWidth:"0px",};}
return{};}
getBarQuestionStyle(barEl){if(this.leaderboardAnimationPhase==="showQuestionScores"){return{transition:"width 1s ease-out",width:`calc(calc(100% - ${this.BAR_WIDTH}) * ${barEl.dataset.widthRatio} + ${this.BAR_MIN_WIDTH})`,};}else if(this.leaderboardAnimationPhase==="sumScores"){const{baseRatio,questionRatio}=this.getBarRatios(barEl);const questionWidth=`calc(calc(calc(100% - ${this.BAR_WIDTH}) * ${
                questionRatio * baseRatio
            }) + ${this.BAR_MIN_WIDTH})`;return{transition:"width ease .5s cubic-bezier(.5,0,.66,1.11)",width:questionWidth,};}
return{};}
getBarRatios(barEl){const item=barEl.closest(".o_survey_session_leaderboard_item");const updatedScore=parseInt(item.dataset.updatedScore);const questionScore=parseInt(item.dataset.questionScore);const maxUpdatedScore=parseInt(item.dataset.maxUpdatedScore);const baseRatio=maxUpdatedScore?updatedScore/maxUpdatedScore:1;const questionRatio=questionScore/(updatedScore||1);return{baseRatio,questionRatio};}
setup(){this.fadeInOutTime=400;this.BAR_MIN_WIDTH="3rem";this.BAR_WIDTH="24rem";this.BAR_HEIGHT="3.8rem";this.surveyAccessToken=this.el.closest(".o_survey_session_manage").dataset.surveyAccessToken;this.sessionResults=this.el.parentElement.querySelector(".o_survey_session_results");}
showLeaderboard(ev){let resolveFadeOut;let fadeOutPromise;const resultsEl=this.el.parentElement.querySelector(".o_survey_session_results");if(ev.detail.fadeOut){fadeOutPromise=new Promise((resolve,reject)=>{resolveFadeOut=resolve;});fadeOut(resultsEl,this.fadeInOutTime,()=>{resultsEl.dispatchEvent(new CustomEvent("setDisplayNone"));resolveFadeOut();});}else{fadeOutPromise=Promise.resolve();resultsEl.dispatchEvent(new CustomEvent("setDisplayNone"));this.removeChildren(this.el.querySelector(".o_survey_session_leaderboard_container"));}
const leaderboardPromise=rpc(`/survey/session/leaderboard/${this.surveyAccessToken}`);this.waitFor(Promise.all([fadeOutPromise,leaderboardPromise])).then(this.protectSyncAfterAsync((results)=>{const leaderboardResults=results[1];const renderedTemplate=document.createElement("div");const parser=new DOMParser();const parsedResults=parser.parseFromString(leaderboardResults,"text/html").body.firstChild;if(parsedResults){this.insert(parsedResults,renderedTemplate);}
this.insert(renderedTemplate,this.el.querySelector(".o_survey_session_leaderboard_container"));this.el.querySelectorAll(".o_survey_session_leaderboard_item").forEach((item,index)=>{const rgb=SESSION_CHART_COLORS[index%10];item.querySelector(".o_survey_session_leaderboard_bar").style.backgroundColor=`rgba(${rgb},1)`;item.querySelector(".o_survey_session_leaderboard_bar_question").style.backgroundColor=`rgba(${rgb},0.4)`;});fadeIn(this.el,this.fadeInOutTime,async()=>{if(ev.detail.isScoredQuestion){await this.waitFor(this.prepareScores());await this.waitFor(this.showQuestionScores());await this.waitFor(this.sumScores());await this.waitFor(this.reorderScores());this.leaderboardAnimationPhase=null;}});}));}
hideLeaderboard(){fadeOut(this.el,this.fadeInOutTime,()=>{this.removeChildren(this.el.querySelector(".o_survey_session_leaderboard_container"));fadeIn(this.sessionResults,this.fadeInOutTime);});}
animateScoreCounter(scoreEl,currentScore,totalScore,increment,plusSign){this.waitForTimeout(()=>{const nextScore=Math.min(totalScore,currentScore+increment);scoreEl.textContent=`${plusSign ? "+ " : ""}${Math.round(nextScore)} p`;if(nextScore<totalScore){this.animateScoreCounter(scoreEl,nextScore,totalScore,increment,plusSign);}},25);}
animateMoveTo(scoreEl,position,offset,timeout){let animationDone;const animationPromise=new Promise(function(resolve){animationDone=resolve;});scoreEl.style.top=`calc(calc(${this.BAR_HEIGHT} * ${position}) + ${offset}rem)`;this.waitForTimeout(animationDone,timeout);return animationPromise;}
async prepareScores(){let animationDone;const animationPromise=new Promise(function(resolve){animationDone=resolve;});this.waitForTimeout(()=>{this.leaderboardAnimationPhase="prepareScores";this.waitForTimeout(animationDone,1000);},300);return animationPromise;}
async reorderScores(){let animationDone;const animationPromise=new Promise(function(resolve){animationDone=resolve;});this.waitForTimeout(()=>{this.leaderboardAnimationPhase="reorderScores";this.el.querySelectorAll(".o_survey_session_leaderboard_item").forEach(async(item)=>{const currentPosition=parseInt(item.dataset.currentPosition);const newPosition=parseInt(item.dataset.newPosition);if(currentPosition!==newPosition){const offset=newPosition>currentPosition?2:-2;await this.waitFor(this.animateMoveTo(item,newPosition,offset,300));item.style.transition="top ease-in-out .1s";await this.waitFor(this.animateMoveTo(item,newPosition,offset*-0.3,100));await this.waitFor(this.animateMoveTo(item,newPosition,0,0));animationDone();}});},1800);return animationPromise;}
async showQuestionScores(){let animationDone;const animationPromise=new Promise(function(resolve){animationDone=resolve;});this.waitForTimeout(()=>{this.leaderboardAnimationPhase="showQuestionScores";this.el.querySelectorAll(".o_survey_session_leaderboard_bar_question").forEach((barEl)=>{const scoreEl=barEl.querySelector(".o_survey_session_leaderboard_bar_question_score");scoreEl.textContent="0 p";const questionScore=parseInt(barEl.dataset.questionScore);if(questionScore&&questionScore>0){let increment=parseInt(barEl.dataset.maxQuestionScore/40);if(!increment||increment===0){increment=1;}
scoreEl.textContent="+ 0 p";this.waitForTimeout(()=>{this.animateScoreCounter(scoreEl,0,questionScore,increment,true);},400);}
this.waitForTimeout(animationDone,1400);});},300);return animationPromise;}
async sumScores(){let animationDone;const animationPromise=new Promise(function(resolve){animationDone=resolve;});this.waitForTimeout(()=>{this.leaderboardAnimationPhase="sumScores";this.el.querySelectorAll(".o_survey_session_leaderboard_item").forEach((item)=>{const currentScore=parseInt(item.dataset.currentScore);const updatedScore=parseInt(item.dataset.updatedScore);let increment=parseInt(item.dataset.maxQuestionScore/40);if(!increment||increment===0){increment=1;}
this.animateScoreCounter(item.querySelector(".o_survey_session_leaderboard_score"),currentScore,updatedScore,increment,false);this.waitForTimeout(animationDone,500);});},1400);return animationPromise;}}
registry.category("public.interactions").add("survey.survey_session_leaderboard",SurveySessionLeaderboard);return __exports;});;

/* /survey/static/src/interactions/survey_session_manage.js */
odoo.define('@survey/interactions/survey_session_manage',['@survey/js/survey_preload_image_mixin','@web/core/l10n/translation','@web/core/network/rpc','@web/core/browser/browser','@web/public/interaction','@web/core/registry','@survey/utils','@web/core/hotkeys/hotkey_service'],function(require){'use strict';let __exports={};const{preloadBackground}=require("@survey/js/survey_preload_image_mixin");const{appTranslateFn}=require("@web/core/l10n/translation");const _t=(str,...args)=>appTranslateFn(str,"survey",...args);const{rpc}=require("@web/core/network/rpc");const{browser}=require("@web/core/browser/browser");const{Interaction}=require("@web/public/interaction");const{registry}=require("@web/core/registry");const{fadeIn,fadeOut}=require("@survey/utils");const{getActiveHotkey}=require("@web/core/hotkeys/hotkey_service");const nextPageTooltips={closingWords:_t("End of Survey"),leaderboard:_t("Show Leaderboard"),leaderboardFinal:_t("Show Final Leaderboard"),nextQuestion:_t("Next"),results:_t("Show Correct Answer(s)"),startScreen:_t("Start"),userInputs:_t("Show Results"),};const SurveySessionManage=__exports.SurveySessionManage=class SurveySessionManage extends Interaction{static selector=".o_survey_session_manage";dynamicContent={_document:{"t-on-keydown":this.onKeyDown,},".o_survey_session_copy":{"t-on-click.prevent":this.onCopySessionLink,},".o_survey_session_navigation_next":{"t-on-click.prevent":this.onNext,"t-att-class":()=>({"d-none":this.isSessionClosed||(this.isLastQuestion&&this.currentScreen==="leaderboardFinal"),}),},".o_survey_session_navigation_previous":{"t-on-click.prevent":this.onBack,"t-att-class":()=>({"d-none":this.isFirstQuestion||this.isSessionClosed}),},".o_survey_session_close":{"t-on-click.prevent":this.onEndSessionClick,},".o_survey_session_attendees_count":{"t-out":()=>this.sessionAttendeesCountText,},".o_survey_session_navigation_next_label":{"t-out":()=>this.sessionNavigationNextLabel,},".o_survey_session_results":{"t-att-class":()=>({"d-none":this.isSessionClosed||this.leaderboardIsFadingOut||this.hideResults,}),"t-on-setDisplayNone":()=>{this.hideResults=true;},},".o_survey_session_description_done":{"t-att-class":()=>({"d-none":!this.isSessionClosed}),},};setup(){if(this.el.dataset.isSessionClosed){this.isSessionClosed=true;this.el.classList.remove("invisible");return;}
this.fadeInOutTime=500;this.answersRefreshDelay=2000;this.isSessionClosed=false;this.leaderboardIsFadingOut=false;this.hideResults=false;this.chartEl=this.el.querySelector(".o_survey_session_chart");this.leaderboardEl=this.el.querySelector(".o_survey_session_leaderboard");this.timerEl=this.el.querySelector(".o_survey_timer_container .o_survey_timer");this.textAnswersEl=this.el.querySelector(".o_survey_session_text_answers_container");this.surveyId=parseInt(this.el.dataset.surveyId);this.attendeesCount=this.el.dataset.attendeesCount?parseInt(this.el.dataset.attendeesCount,10):0;this.surveyHasConditionalQuestions=this.el.dataset.surveyHasConditionalQuestions;this.surveyAccessToken=this.el.dataset.surveyAccessToken;this.isStartScreen=this.el.dataset.isStartScreen;this.isFirstQuestion=this.el.dataset.isFirstQuestion;this.isLastQuestion=this.el.dataset.isLastQuestion;this.surveyLastTriggeringAnswers=JSON.parse(this.el.dataset.surveyLastTriggeringAnswers||"[]");this.isScoredQuestion=this.el.dataset.isScoredQuestion;this.sessionShowLeaderboard=this.el.dataset.sessionShowLeaderboard;this.hasCorrectAnswers=this.el.dataset.hasCorrectAnswers;this.showBarChart=this.el.dataset.showBarChart;this.showTextAnswers=this.el.dataset.showTextAnswers;this.stopNextQuestion=false;this.refreshBackground=this.el.dataset.refreshBackground;this.copyBtnTooltip=window.Tooltip.getOrCreateInstance(this.el.querySelector(".o_survey_session_copy"),{title:_t("Click to copy link"),placement:"right",container:"body",trigger:"hover",offset:"0, 3",delay:0,});this.registerCleanup(()=>{this.copyBtnPopover?.dispose();this.copyBtnTooltip?.dispose();});this.sessionAttendeesCountText="";this.sessionNavigationNextLabel="";this.el.classList.remove("invisible");this.setupIntervals();}
async willStart(){if(this.chartEl&&!this.chartEl.classList.contains("chart_is_ready")){let resolveChartPromise;const chartPromise=new Promise(function(resolve){resolveChartPromise=resolve;});this.env.bus.addEventListener("SURVEY:CHART_INTERACTION_STARTED",resolveChartPromise);await chartPromise;}}
start(){this.setupCurrentScreen();this.startTimer();if(this.el.dataset.goingBack){this.chartUpdateState({showInputs:true,showAnswers:true});if(this.sessionShowLeaderboard&&this.isScoredQuestion){this.currentScreen="leaderboard";this.leaderboardEl.dispatchEvent(new CustomEvent("showLeaderboard",{detail:{fadeOut:false,isScoredQuestion:this.isScoredQuestion,},}));}else{this.currentScreen="results";}
this.refreshResults();}}
async onCopySessionLink(ev){const copyBtnTooltipHideDelay=800;this.copyBtnTooltip?.dispose();delete this.copyBtnTooltip;this.copyBtnPopover=window.Popover.getOrCreateInstance(ev.currentTarget,{content:_t("Copied!"),trigger:"manual",placement:"right",container:"body",offset:"0, 3",});await this.waitFor(browser.navigator.clipboard.writeText(ev.currentTarget.innerText.trim()));this.protectSyncAfterAsync(()=>{this.copyBtnPopover.show();this.waitForTimeout(()=>this.copyBtnPopover.hide(),copyBtnTooltipHideDelay);})();}
onNext(ev){const screenToDisplay=this.getNextScreen();switch(screenToDisplay){case"userInputs":this.chartUpdateState({showInputs:true});break;case"results":this.chartUpdateState({showAnswers:true});clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;break;case"leaderboard":case"leaderboardFinal":if(!this.currentScreen.startsWith("leaderboard")){this.leaderboardEl.dispatchEvent(new CustomEvent("showLeaderboard",{detail:{fadeOut:true,isScoredQuestion:this.isScoredQuestion,},}));}
break;default:if(!this.isLastQuestion||!this.sessionShowLeaderboard){this.goToNextQuestion();}
break;}
this.currentScreen=screenToDisplay;if(!["question","nextQuestion"].includes(screenToDisplay)){this.updateNextScreenTooltip();}}
onBack(ev){const screenToDisplay=this.getPreviousScreen();switch(screenToDisplay){case"question":this.chartUpdateState({showInputs:false});break;case"userInputs":this.chartUpdateState({showAnswers:false});if(!this.resultsRefreshInterval){this.resultsRefreshInterval=setInterval(this.refreshResults.bind(this),this.answersRefreshDelay);}
break;case"results":if(this.isScoredQuestion||this.isLastQuestion){this.leaderboardEl.dispatchEvent(new Event("hideLeaderboard"));}
clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;break;case"previousQuestion":if(this.isFirstQuestion){return;}
this.goToNextQuestion(true);break;}
this.currentScreen=screenToDisplay;if(!["question","nextQuestion"].includes(screenToDisplay)){this.updateNextScreenTooltip();}}
getNextScreen(){if(this.currentScreen==="question"&&this.isScoredQuestion){return"userInputs";}else if(this.hasCorrectAnswers&&["question","userInputs"].includes(this.currentScreen)){return"results";}else if(this.sessionShowLeaderboard){if(this.isLastQuestion){return"leaderboardFinal";}else if(["question","userInputs","results"].includes(this.currentScreen)&&this.isScoredQuestion){return"leaderboard";}}
return"nextQuestion";}
getPreviousScreen(){if(this.currentScreen==="userInputs"&&this.isScoredQuestion){return"question";}else if((this.currentScreen==="results"&&this.isScoredQuestion)||(this.currentScreen==="leaderboard"&&!this.isScoredQuestion)||(this.currentScreen==="leaderboardFinal"&&this.isScoredQuestion)){return"userInputs";}else if((this.currentScreen==="leaderboard"&&this.isScoredQuestion)||(this.currentScreen==="leaderboardFinal"&&!this.isScoredQuestion)){return"results";}
return"previousQuestion";}
async goToNextQuestion(goBack){if(this.stopNextQuestion){return;}
this.stopNextQuestion=true;this.leaderboardIsFadingOut=true;this.isStartScreen=false;let resolveFadeOut;const fadeOutPromise=new Promise(function(resolve){resolveFadeOut=resolve;});fadeOut(this.el,this.fadeInOutTime,()=>{this.leaderboardIsFadingOut=false;resolveFadeOut();});if(this.refreshBackground){document.querySelector("div.o_survey_background").classList.add("o_survey_background_transition");}
if(this.resultsRefreshInterval){clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;}
this.nextQuestion=await this.waitFor(rpc(`/survey/session/next_question/${this.surveyAccessToken}`,{go_back:goBack,}));let preloadBgPromise;if(this.refreshBackground&&this.nextQuestion.background_image_url){preloadBgPromise=preloadBackground(this.nextQuestion.background_image_url);}else{preloadBgPromise=Promise.resolve();}
await this.waitFor(Promise.all([fadeOutPromise,preloadBgPromise]));this.protectSyncAfterAsync(()=>this.onNextQuestionDone(goBack))();}
async onNextQuestionDone(goBack){if(!this.nextQuestion.question_html){this.isSessionClosed=true;this.onEndSessionClick();return;}
const parser=new DOMParser();const newContent=parser.parseFromString(this.nextQuestion.question_html,"text/html").body.firstChild;newContent.style.opacity=0;if(goBack){newContent.dataset.goingBack=true;}
if(this.refreshBackground){const surveyBackground=newContent.querySelector("div.o_survey_background");if(surveyBackground){surveyBackground.style.backgroundImage=`url(${this.nextQuestion.background_image_url})`;surveyBackground.classList.remove("o_survey_background_transition");}}
this.el.parentNode.replaceChild(newContent,this.el);fadeIn(newContent,this.fadeInOutTime);await this.services["public.interactions"].startInteractions(newContent);this.services["public.interactions"].stopInteractions(this.el);}
async onEndSessionClick(ev){const showResults=ev?.currentTarget?.dataset?.showResults;await this.waitFor(this.services.orm.call("survey.survey","action_end_session",[[this.surveyId]]));this.protectSyncAfterAsync(()=>{if(showResults){window.location.href=`/survey/results/${encodeURIComponent(this.surveyId)}`;}else{window.location.reload();}})();}
onKeyDown(ev){const hotkey=getActiveHotkey(ev);if(hotkey==="arrowright"||hotkey==="space"){this.onNext(ev);}else if(hotkey==="arrowleft"){this.onBack(ev);}}
setupCurrentScreen(){if(this.isStartScreen){this.currentScreen="startScreen";}else if(!this.isScoredQuestion&&this.showBarChart){this.currentScreen="userInputs";}else{this.currentScreen="question";}
this.chartUpdateState({showInputs:this.currentScreen==="userInputs"});this.updateNextScreenTooltip();}
chartUpdateState(options){this.chartEl?.dispatchEvent(new CustomEvent("updateState",{detail:options,}));}
updateNextScreenTooltip(){let tooltip;if(this.currentScreen==="startScreen"){tooltip=nextPageTooltips.startScreen;}else if(this.isLastQuestion&&!this.surveyHasConditionalQuestions&&!this.isScoredQuestion&&!this.sessionShowLeaderboard){tooltip=nextPageTooltips.closingWords;}else{const nextScreen=this.getNextScreen();if(nextScreen==="nextQuestion"||this.surveyHasConditionalQuestions){tooltip=nextPageTooltips.nextQuestion;}
tooltip=nextPageTooltips[nextScreen];}
const sessionNavigationNextEl=this.el.querySelector(".o_survey_session_navigation_next_label");if(sessionNavigationNextEl&&tooltip){this.sessionNavigationNextLabel=tooltip;this.updateContent();}}
setupIntervals(){if(this.isStartScreen){this.attendeesRefreshInterval=setInterval(this.refreshAttendeesCount.bind(this),this.answersRefreshDelay);}else{if(this.attendeesRefreshInterval){clearInterval(this.attendeesRefreshInterval);}
if(!this.resultsRefreshInterval){this.resultsRefreshInterval=setInterval(this.refreshResults.bind(this),this.answersRefreshDelay);}}}
startTimer(el){const surveyManagerEl=el||this.el;const timerData=surveyManagerEl.dataset;const questionTimeLimitReached=!!timerData.questionTimeLimitReached;const timeLimitMinutes=Number(timerData.timeLimitMinutes);const hasAnswered=!!timerData.hasAnswered;if(this.timerEl&&!questionTimeLimitReached&&!hasAnswered&&timeLimitMinutes){this.addListener(surveyManagerEl,"time_up",async()=>{if(this.currentScreen==="question"&&this.isScoredQuestion){this.onNext();}});this.timerEl.dispatchEvent(new CustomEvent("start_timer",{detail:{timeLimitMinutes:timeLimitMinutes,timer:timerData.timer,},}));}}
refreshResults(){this.waitFor(rpc(`/survey/session/results/${this.surveyAccessToken}`)).then(this.protectSyncAfterAsync((questionResults)=>{if(questionResults){this.attendeesCount=questionResults.attendees_count;if(!this.isStartScreen&&this.showBarChart&&questionResults.question_statistics_graph){const parsedStatistics=JSON.parse(questionResults.question_statistics_graph);if(parsedStatistics.length>0){this.chartUpdateState({questionStatistics:parsedStatistics});}}else if(!this.isStartScreen&&this.showTextAnswers){this.textAnswersEl.dispatchEvent(new CustomEvent("updateTextAnswers",{detail:{questionType:this.el.dataset.questionType,inputLineValues:questionResults.input_line_values,},}));}
if(this.surveyLastTriggeringAnswers.length){this.isLastQuestion=!questionResults.answer_count||!this.surveyLastTriggeringAnswers.some((answerId)=>questionResults.selected_answers.includes(answerId));this.updateNextScreenTooltip();}
const progressBar=this.el.querySelector(".progress-bar");if(progressBar){const max=this.attendeesCount>0?this.attendeesCount:1;const percentage=Math.min(Math.round((questionResults.answer_count/max)*100),100);progressBar.style.width=`${percentage}%`;}
if(this.attendeesCount&&this.attendeesCount>0){const answerCount=Math.min(questionResults.answer_count,this.attendeesCount);const answerCountElement=this.el.querySelector(".o_survey_session_answer_count");const progressBarTextElement=this.el.querySelector(".progress-bar.o_survey_session_progress_small span");if(answerCountElement){answerCountElement.textContent=answerCount;}
if(progressBarTextElement){progressBarTextElement.textContent=`${answerCount} / ${this.attendeesCount}`;}}}}),this.protectSyncAfterAsync(()=>{clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;}));}
refreshAttendeesCount(){this.waitFor(this.services.orm.read("survey.survey",[this.surveyId],["session_answer_count"])).then(this.protectSyncAfterAsync((result)=>{if(result&&result.length===1){this.sessionAttendeesCountText=String(result[0].session_answer_count);}}),this.protectSyncAfterAsync((err)=>{clearInterval(this.attendeesRefreshInterval);console.error(err);}));}}
registry.category("public.interactions").add("survey.survey_session_manage",SurveySessionManage);return __exports;});

                    /*******************************************
                    *  Templates                               *
                    *******************************************/

                    odoo.define("survey.survey_user_input_session_assets.bundle.xml", ["@web/core/templates"], function(require) {
                        "use strict";
                        const { checkPrimaryTemplateParents, registerTemplate, registerTemplateExtension } = require("@web/core/templates");
                        /* survey.survey_user_input_session_assets */
                        registerTemplate("survey.survey_session_text_answer", `/survey/static/src/xml/survey_session_text_answer_template.xml`, `<div t-name="survey.survey_session_text_answer" class="o_survey_session_text_answer d-inline-block m-1" xml:space="preserve">
    <div class="o_survey_session_text_answer_container d-inline-block p-2 fw-bold" t-attf-style="border-color: #{borderColor}">
        <span class="d-inline-block text-truncate" t-esc="value" style="max-width: 22ch;"/>
    </div>
</div>

`);
                    });
