<div style="padding:24px 32px 24px">
<div class="tile" id="stmtTile">
  
    <span style="font-size:16px;color:#888" id="tileChev">∧</span>
  </div>
  <div id="tileContent">
  <div class="tile-body">

    <!-- 1. CONFLICTS OF INTEREST -->
    <div class="sec">
      <div class="sec-title">Conflicts of interest</div>
      <div class="sec-sub">Commercial or financial <span class="iico" title="Declare any commercial or financial conflicts of interest">i</span></div>
      <div class="opts">
        <label class="opt"><input type="radio" name="coi" value="none" <?= ck($ss,'conflict_of_interest','none') ?> onchange="toggleBox('coiBox',false);stm_dirty()"><span>No commercial or financial conflict of interest was identified for this research</span></label>
        <label class="opt"><input type="radio" name="coi" value="exists" <?= ck($ss,'conflict_of_interest','exists') ?> onchange="toggleBox('coiBox',true);stm_dirty()"><span>A commercial or financial conflict of interest was identified for this research</span></label>
      </div>
      <div class="explain <?= sv($ss,'conflict_of_interest')==='exists'?'show':'' ?>" id="coiBox">
        <textarea class="ta" id="coiDetails" placeholder="Explain why here..." oninput="stm_dirty()" maxlength="3000"><?= htmlspecialchars(sv($ss,'conflict_details')) ?></textarea>
      </div>
      <div class="field-err" id="coiErr"><span>⊗</span> Please select one option</div>
    </div>

    <!-- 2. MANUSCRIPT SUBMISSIONS -->
    <div class="sec">
      <div class="sec-title">Manuscript submissions</div>
      <div class="opts">
        <label class="opt"><input type="radio" name="mst" value="no_previous" <?= ck($ss,'manuscript_submission_type','no_previous')?:(empty($ss)?'checked':'') ?> onchange="toggleBox('mstBox',false);stm_dirty()"><span>No other version of this manuscript was previously submitted to a communeglobal journal</span></label>
        <label class="opt"><input type="radio" name="mst" value="previous" <?= ck($ss,'manuscript_submission_type','previous') ?> onchange="toggleBox('mstBox',true);stm_dirty()"><span>A version of this manuscript was previously submitted to a communeglobal journal</span></label>
      </div>
      <div class="explain <?= sv($ss,'manuscript_submission_type')==='previous'?'show':'' ?>" id="mstBox">
        <textarea class="ta" id="mstDetails" placeholder="Explain why here..." oninput="stm_dirty()" maxlength="3000"><?= htmlspecialchars(sv($ss,'manuscript_details')) ?></textarea>
      </div>
    </div>

    <!-- 3. FUNDING -->
    <div class="sec">
      <div class="sec-title">Funding</div>
      <div class="opts">
        <label class="opt"><input type="radio" name="funding" value="no_funding" <?= ck($ss,'funding_status','no_funding')?:(empty($ss)?'checked':'') ?> onchange="toggleBox('fundSection',false);stm_dirty()"><span>No Funding was received for the research and/or publication of this article</span></label>
        <label class="opt"><input type="radio" name="funding" value="funding_received" <?= ck($ss,'funding_status','funding_received') ?> onchange="toggleBox('fundSection',true);stm_dirty()"><span>Funding was received for the research and/or publication of this article</span></label>
      </div>
      <div class="explain <?= sv($ss,'funding_status')==='funding_received'?'show':'' ?>" id="fundSection">
        <div style="margin-top:14px">
          <div class="sec-sub">Funding information <span class="iico" title="Declare all sources of funding received for the research being submitted">i</span></div>
          <div class="sec-desc">Declare all sources of funding received for the research being submitted, adding a short description of each funder's role. This statement will be shown in the published article.</div>
          <textarea class="ta" id="fundDetails" placeholder="Type here..." oninput="stm_dirty()" maxlength="5000"><?= htmlspecialchars(sv($ss,'funding_details')) ?></textarea>
        </div>
        <div style="margin-top:18px">
          <div class="sec-sub">Funder (optional) <span class="iico" title="Add one or more funding institutions">i</span></div>
          <div class="sec-desc">You can search and add the name of one or more funding institutions in the box below. If available, please add an award or grant number and specify if any of the funders is covering the article publishing charges (APCs) for this article.</div>
          <div class="funder-tip"><span style="font-size:15px">ℹ</span> Please add funder for us to identify and validate partnerships to cover your article publishing charges (APC).</div>
          <div id="funderList"></div>
          <div style="text-align:center"><button type="button" class="add-funder" onclick="addFunder()">+ Add funder</button></div>
        </div>
      </div>
    </div>

    <!-- 4. GENERATIVE AI -->
    <div class="sec">
      <div class="sec-title">Generative AI disclosure <span class="iico" title="Declare any use of Generative AI tools">i</span></div>
      <div class="opts">
        <label class="opt"><input type="radio" name="ai" value="0" <?= (sv($ss,'generative_ai_used')==='0'||sv($ss,'generative_ai_used')===0)?'checked':'' ?> onchange="toggleBox('aiSection',false);stm_dirty()"><span>No Generative AI was used in the preparation of this manuscript.</span></label>
        <label class="opt"><input type="radio" name="ai" value="1" <?= (sv($ss,'generative_ai_used')==='1'||sv($ss,'generative_ai_used')===1)?'checked':'' ?> onchange="toggleBox('aiSection',true);stm_dirty()"><span>Generative AI was used in the preparation of this manuscript.</span></label>
      </div>
      <div class="field-err" id="aiErr"><span>⊗</span> Please select one option</div>
      <div class="explain <?= (sv($ss,'generative_ai_used')==='1'||sv($ss,'generative_ai_used')===1)?'show':'' ?>" id="aiSection">
        <div style="margin-top:14px">
          <div class="sec-sub">Generative AI Statement</div>
          <div class="sec-desc">The author(s) verify and take full responsibility for the use of generative AI in the preparation of this manuscript. Generative AI was used:</div>
          <textarea class="ta" id="aiDetails" placeholder="Detail use of generative AI here..." oninput="stm_dirty()" maxlength="3000"><?= htmlspecialchars(sv($ss,'generative_ai_details')) ?></textarea>
        </div>
      </div>
    </div>

    <!-- 5. ETHICS -->
    <div class="sec">
      <div class="sec-title">Ethics</div>
      <div class="sec-desc">Answer the questionnaires below regarding the involvement of human or animal subjects, and the inclusion of potentially identifiable images or data. The responses will be compiled to create the ethical statement for your manuscript.</div>
      <div class="opts" style="margin-bottom:14px">
        <label class="opt"><input type="checkbox" id="ethicsChk" <?= sv($ss,'ethics_compliant')?'checked':'' ?> onchange="stm_dirty()"><span>This study was conducted in accordance with the local legislation and institution requirements</span></label>
      </div>
      <div class="field-err" id="ethicsErr"><span>⊗</span> Please mark this checkbox to continue</div>
      <div style="border-top:1px solid #F3F4F6;margin-top:12px">
        <div class="survey-row">
          <span class="survey-name">Studies involving research on animals</span>
          <div class="survey-right"><span class="survey-ok" id="animalsOk"><?= (sv($ss,'studies_animals')||sv($ss,'animals_answers'))?'&#10003; Saved':'' ?></span><button type="button" class="survey-btn" onclick="openSurvey('animals')" id="animalsBtn"><?= (sv($ss,'studies_animals')||sv($ss,'animals_answers'))?'CONTINUE':'START' ?></button></div>
        </div>
        <div class="survey-row">
          <span class="survey-name">Studies involving research on humans</span>
          <div class="survey-right"><span class="survey-ok" id="humansOk"><?= (sv($ss,'studies_humans')||sv($ss,'humans_answers'))?'&#10003; Saved':'' ?></span><button type="button" class="survey-btn" onclick="openSurvey('humans')" id="humansBtn"><?= (sv($ss,'studies_humans')||sv($ss,'humans_answers'))?'CONTINUE':'START' ?></button></div>
        </div>
        <div class="survey-row">
          <span class="survey-name">Inclusion of identifiable data</span>
          <div class="survey-right"><span class="survey-ok" id="identOk"><?= (sv($ss,'includes_identifiable_data')||sv($ss,'identifiable_answers'))?'&#10003; Saved':'' ?></span><button type="button" class="survey-btn" onclick="openSurvey('identifiable')" id="identBtn"><?= (sv($ss,'includes_identifiable_data')||sv($ss,'identifiable_answers'))?'CONTINUE':'START' ?></button></div>
        </div>
      </div>
      <div class="stmt-badge <?= sv($ss,'studies_animals')?'show':'' ?>" id="animalsBadge"><div class="stmt-badge-lbl">Animals statement</div><div id="animalsText"><?= htmlspecialchars(sv($ss,'studies_animals')) ?></div></div>
      <div class="stmt-badge <?= sv($ss,'studies_humans')?'show':'' ?>" id="humansBadge"><div class="stmt-badge-lbl">Humans statement</div><div id="humansText"><?= htmlspecialchars(sv($ss,'studies_humans')) ?></div></div>
      <div class="stmt-badge <?= sv($ss,'includes_identifiable_data')?'show':'' ?>" id="identBadge"><div class="stmt-badge-lbl">Identifiable data statement</div><div id="identText"><?= htmlspecialchars(sv($ss,'includes_identifiable_data')) ?></div></div>
    </div>

    <!-- 6. DATA -->
    <div class="sec">
      <div class="sec-title">Data</div>
      <div class="sec-desc">Declare the sources of data supporting the conclusions of the manuscript. This includes both data generated by the authors and data analyzed for the study.</div>
      <div class="survey-row" style="border-bottom:none">
        <span class="survey-name">Data availability and sources</span>
        <div class="survey-right"><span class="survey-ok" id="dataOk"><?= (sv($ss,'data_availability_statement')||sv($ss,'data_answers'))?'&#10003; Saved':'' ?></span><button type="button" class="survey-btn" onclick="openSurvey('data')" id="dataBtn"><?= (sv($ss,'data_availability_statement')||sv($ss,'data_answers'))?'CONTINUE':'START' ?></button></div>
      </div>
      <div class="stmt-badge <?= sv($ss,'data_availability_statement')?'show':'' ?>" id="dataBadge"><div class="stmt-badge-lbl">Data availability statement</div><div id="dataText"><?= htmlspecialchars(sv($ss,'data_availability_statement')) ?></div></div>
      <div class="field-err" id="dataErr"><span>⊗</span> Please complete this statement to continue.</div>
    </div>

    <div style="text-align:right;padding:4px 0 18px"><a href="https://www.communeglobalin.org/about/author-guidelines" target="_blank" style="font-size:12.5px">ℹ Author guidelines</a></div>
  </div><!-- /tile-body -->

  
  </div>
  </div>
</div>

<!-- SIDEBAR -->

    <button class="sb-x" onclick="closeSidebar()">&#x2715;</button>
  </div>
  <div class="sb-scroll" id="sbScroll"></div>
</div>

<!-- Bottom bar -->
<div class="bottom-bar">
  <div class="btm-fee">Preliminary fees: <strong><?= $fee ?> CHF</strong><br><span style="font-size:11px">Payment after acceptance</span></div>
  <div class="btm-q">Submission quality: <strong>90%</strong> <span style="font-size:11.5px;color:var(--muted)">&#x2139; 1 suggested action</span></div>
  <div class="btm-acts"><button class="btn btn-outline">Preview</button><button class="btn btn-fill">Submit</button></div>
</div>

<script>
const SID = <?= $sid ?>;
let isDirty = false, autoTimer = null;
let currentSurvey = null;
let visibleQs = []; // track which question ids are currently visible

// Saved statements & sidebar answers
const S = {
  animals:      <?= json_encode(sv($ss,'studies_animals')) ?>,
  humans:       <?= json_encode(sv($ss,'studies_humans')) ?>,
  identifiable: <?= json_encode(sv($ss,'includes_identifiable_data')) ?>,
  data:         <?= json_encode(sv($ss,'data_availability_statement')) ?>
};
const SAVED_ANS = {
  animals:      <?= json_encode(json_decode(sv($ss,'animals_answers','{}'),true)?:[]) ?>,
  humans:       <?= json_encode(json_decode(sv($ss,'humans_answers','{}'),true)?:[]) ?>,
  identifiable: <?= json_encode(json_decode(sv($ss,'identifiable_answers','{}'),true)?:[]) ?>,
  data:         <?= json_encode(json_decode(sv($ss,'data_answers','{}'),true)?:[]) ?>
};
let funders = <?= json_encode(json_decode(sv($ss,'funder_data','[]'),true)?:[]) ?>;

/* ─── Tile ─────────────────────────────── */
function toggleTile(){const c=document.getElementById('tileContent');const o=c.style.display!=='none';c.style.display=o?'none':'';document.getElementById('tileChev').textContent=o?'∨':'∧';}

/* ─── Explain box ─────────────────────── */
function toggleBox(id, show){document.getElementById(id).classList.toggle('show', show);}

/* ─── Funder ──────────────────────────── */
function xe(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function renderFunders(){
  const list=document.getElementById('funderList');list.innerHTML='';
  funders.forEach((f,i)=>{
    const d=document.createElement('div');d.className='funder-card';
    d.innerHTML=`<div class="fname-row"><input class="fname-inp" type="text" placeholder="Funder name..." value="${xe(f.name)}" oninput="funders[${i}].name=this.value;stm_dirty()"><button type="button" class="frm-btn" onclick="funders.splice(${i},1);renderFunders();stm_dirty()" title="Remove">&#x1F5D1;</button></div><div class="award-row" id="aw${i}">${f.awards.map((a,j)=>`<span class="aw-tag">${xe(a)}<button type="button" class="aw-tag-rm" onclick="funders[${i}].awards.splice(${j},1);renderFunders();stm_dirty()">&#x2715;</button></span>`).join('')}<input class="aw-inp" id="awInp${i}" type="text" placeholder="Award number" onkeydown="if(event.key==='Enter'){event.preventDefault();addAward(${i});}"><button type="button" class="aw-add" onclick="addAward(${i})">+</button></div><label class="apc-row"><input type="checkbox" ${f.apc?'checked':''} onchange="funders[${i}].apc=this.checked;stm_dirty()"><span>I will use these funds to cover the article publishing charges (APCs).</span></label>`;
    list.appendChild(d);
  });
}
function addFunder(){funders.push({name:'',awards:[],apc:false});renderFunders();dirty();}
function addAward(i){const inp=document.getElementById('awInp'+i);const v=inp.value.trim();if(!v)return;funders[i].awards.push(v);inp.value='';renderFunders();dirty();}
renderFunders();

/* ═══════════════════════════════════════════
   SURVEY DEFINITIONS
   Each survey = array of question objects
   q = question text, type = bool|text|preview|end
   yes/no = next question id for bool
   next = next id for text
   buildStmt = function for preview
═══════════════════════════════════════════ */
const SURVEYS = {

animals:{
  title:'STUDIES INVOLVING RESEARCH ON ANIMALS',
  qs:[
    {id:'q1',n:1,type:'bool',q:'Does your manuscript present the results of research on vertebrate/higher invertebrate animals?',yes:'q2',no:'endNo'},
    {id:'q2',n:2,type:'bool',q:'Was this study approved by an animal ethics committee?',yes:'q3',no:'q6'},
    {id:'q3',n:3,type:'bool',q:'Did this study use client-owned animals (non-commercially available animals, e.g. pets or livestock)?',yes:'q4',no:'q5'},
    {id:'q4',n:4,type:'bool',q:'Was written informed consent obtained from the owners for the participation of their animals in this study?',yes:'q5ta',no:'endNoConsent'},
    {id:'q5',n:4,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board:',next:'preview'},
    {id:'q5ta',n:5,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board:',next:'preview'},
    {id:'q6',n:3,type:'bool',q:'Was a waiver obtained from the ethics committee/institutional review board?',yes:'q6ta',no:'endNoWaiver'},
    {id:'q6ta',n:4,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board and reason for waiver:',next:'preview'},
    {id:'endNo',type:'end',msg:'No animal research involved. No ethics statement required for animals.'},
    {id:'endNoConsent',type:'end',msg:'Written informed consent from animal owners is required. Please obtain consent before submission.'},
    {id:'endNoWaiver',type:'end',msg:'Ethics committee approval or waiver is required. Please obtain this before submission.'},
    {id:'preview',type:'preview',build:(ans)=>{const board=ans.q5||ans.q5ta||ans.q6ta||'[ethics committee name]';return `The animal study was approved by ${board}. The study was conducted in accordance with the local legislation and institutional requirements.`;}}
  ]
},

humans:{
  title:'STUDIES INVOLVING RESEARCH ON HUMANS',
  qs:[
    {id:'q1',n:1,type:'bool',q:'Does the manuscript present the results of direct human research?',yes:'q2',no:'endNo'},
    {id:'q2',n:2,type:'bool',q:'Was this study approved by an ethics committee?',yes:'q3',no:'q8'},
    {id:'q3',n:3,type:'bool',q:'Did the study involve participants who could be considered vulnerable? Vulnerable participants include children/minors under the age of 18, or other vulnerable individuals or populations from the country in which the research was conducted.',yes:'q4',no:'q6'},
    {id:'q4',n:4,type:'bool',q:"Did the participants' legal guardians/next of kin provide written informed consent for their participation in this study?",yes:'q5',no:'endNoConsent'},
    {id:'q5',n:5,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board:',next:'preview'},
    {id:'q6',n:4,type:'bool',q:'Did the participants provide written informed consent for their participation in this study?',yes:'q7',no:'q9'},
    {id:'q7',n:5,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board:',next:'preview'},
    {id:'q8',n:3,type:'bool',q:'Was a waiver obtained from the ethics committee/institutional review board?',yes:'q8ta',no:'endNoWaiver'},
    {id:'q8ta',n:4,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board and reason for waiver:',next:'preview'},
    {id:'q9',n:5,type:'bool',q:'Was a waiver of informed consent obtained from the ethics committee/institutional review board?',yes:'q9ta',no:'endNoConsent'},
    {id:'q9ta',n:6,type:'text',q:'Please insert the full name and affiliation of the ethics committee/institutional review board and reason for waiver of consent:',next:'preview'},
    {id:'endNo',type:'end',msg:'No direct human research involved. No ethics statement required for human subjects.'},
    {id:'endNoConsent',type:'end',msg:'Written informed consent is required. Please obtain appropriate consent documentation before submission.'},
    {id:'endNoWaiver',type:'end',msg:'Ethics committee approval or waiver is required. Please obtain this before submission.'},
    {id:'preview',type:'preview',build:(ans)=>{const board=ans.q5||ans.q7||ans.q8ta||ans.q9ta||'[ethics committee name]';return `The studies involving humans were approved by ${board}. The studies were conducted in accordance with the local legislation and institutional requirements. The participants provided their written informed consent to participate in this study.`;}}
  ]
},

identifiable:{
  title:'INCLUSION OF IDENTIFIABLE DATA',
  qs:[
    {id:'q1',n:1,type:'bool',q:'Is your manuscript a Case Report on humans? Please note that written informed consent for publication is required for all case report articles on humans.',yes:'q2',no:'q6'},
    {id:'q2',n:2,type:'bool',q:'Are any of the potentially identifiable individual(s) under the age of 18 (or considered minors in the country where the research was conducted)?',yes:'q3',no:'q2b'},
    {id:'q2b',n:3,type:'bool',q:'Was written informed consent obtained from the individual(s) for the publication of the images/data included in this article?',yes:'previewAdult',no:'endNoConsent'},
    {id:'q3',n:3,type:'bool',q:'Are there also potentially identifiable adult individual(s) with the legal right to consent to the publication of the images/data?',yes:'q4',no:'q5'},
    {id:'q4',n:4,type:'bool',q:"Was written informed consent obtained from the adult participant(s) and from the minor(s)' legal guardian/next of kin for the publication of these images/data?",yes:'previewBoth',no:'endNoConsent'},
    {id:'q5',n:4,type:'bool',q:"Was written informed consent obtained from the minor(s)' legal guardian/next of kin for the publication of these images/data?",yes:'previewMinor',no:'endNoConsent'},
    {id:'q6',n:2,type:'bool',q:'Does your manuscript include any potentially identifiable images or data of a person?',yes:'q7',no:'endNoIdent'},
    {id:'q7',n:3,type:'bool',q:'Was written informed consent obtained from the individual(s) for the publication of the potentially identifiable images or data included in this article?',yes:'previewAdult',no:'endNoConsent'},
    {id:'endNoIdent',type:'end',msg:'No identifiable data or images included. No statement required.'},
    {id:'endNoConsent',type:'end',msg:'Written informed consent is required for identifiable data. Please obtain consent before submission.'},
    {id:'previewAdult',type:'preview',build:()=>'Written informed consent was obtained from the individual(s) for the publication of any potentially identifiable images or data included in this article.'},
    {id:'previewBoth',type:'preview',build:()=>"Written informed consent was obtained from the individual(s), and minor(s)' legal guardian/next of kin, for the publication of any potentially identifiable images or data included in this article."},
    {id:'previewMinor',type:'preview',build:()=>"Written informed consent was obtained from the minor(s)' legal guardian/next of kin for the publication of any potentially identifiable images or data included in this article."}
  ]
},

data:{
  title:'DATA AVAILABILITY STATEMENT',
  qs:[
    {id:'q1',n:1,type:'bool',q:'Was original data generated for this article?',yes:'q2',no:'q1b'},
    {id:'q1b',n:2,type:'bool',q:'Was data from a third party used in this manuscript?',yes:'q1c',no:'previewNone'},
    {id:'q1c',n:3,type:'bool',q:'Is this data publicly available?',yes:'previewThird',no:'previewRestricted'},
    {id:'q2',n:2,type:'bool',
      q:'Does your manuscript include any of the following data?',
      list:['Genetic/genomic (DNA/RNA) sequence','Metagenomic sequence','DNA/RNA trace or short read sequencing data','Genetic polymorphism data','Gene expression data','50 genes or more (deep sequencing or microarray)','Data linking genotype to phenotype','Protein sequencing data','Proteome profiling data','Small molecule, protein, protein complex structural data','Taxonomy data'],
      yes:'q3',no:'q4'},
    {id:'q3',n:3,type:'bool',q:'Has this data been uploaded to a repository, as per author guidelines? Please note that this data must be made publicly available prior to publication of the article.',yes:'q5',no:'endNoRepo'},
    {id:'q4',n:3,type:'bool',q:'Are the datasets included in the manuscript/supplementary material? Note: if greater than 10, please upload as supplementary material in the manuscript tile.',yes:'previewInMs',no:'q4b'},
    {id:'q4b',n:4,type:'bool',q:'Has the data been deposited in a publicly accessible repository?',yes:'previewRepo',no:'previewOnRequest'},
    {id:'q5',n:4,type:'bool',q:'Are the datasets included in the manuscript/supplementary material? Note: if greater than 10, please upload as supplementary material in the manuscript tile.',yes:'previewBoth',no:'q5b'},
    {id:'q5b',n:5,type:'bool',q:'Has the data been deposited in a publicly accessible repository?',yes:'previewRepo',no:'previewOnRequest'},
    {id:'endNoRepo',type:'end',msg:'Data must be uploaded to a public repository per communeglobal guidelines before submission.'},
    {id:'previewNone',type:'preview',build:()=>'The manuscript does not include any data.'},
    {id:'previewThird',type:'preview',build:()=>'Publicly available datasets were analyzed in this study. This data can be found here: [LINK/ACCESSION NUMBER].'},
    {id:'previewRestricted',type:'preview',build:()=>'The data analyzed in this study is subject to the following licenses/restrictions: [RESTRICTIONS]. Requests to access these datasets should be directed to [CONTACT].'},
    {id:'previewInMs',type:'preview',build:()=>'The original data presented in the study are included in the article/supplementary material, further inquiries can be directed to the corresponding author.'},
    {id:'previewRepo',type:'preview',build:()=>'The datasets presented in this study can be found in online repositories. The names of the repository/repositories and accession number(s) can be found in the article/supplementary material.'},
    {id:'previewBoth',type:'preview',build:()=>'The datasets presented in this study can be found in online repositories. The names of the repository/repositories and accession number(s) can be found in the article/supplementary material.'},
    {id:'previewOnRequest',type:'preview',build:()=>'The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation.'}
  ]
}
};

/* ─── Open / close sidebar ─────────────── */
function openSurvey(type){
  currentSurvey=type;
  // Load previously saved answers for this survey
  window._sbAns = Object.assign({}, SAVED_ANS[type] || {});
  const sv=SURVEYS[type];
  document.getElementById('sbTitle').textContent=sv.title;
  document.getElementById('sbScroll').innerHTML='';
  visibleQs=[];
  // Replay questions based on saved answers
  replaySurvey();
  document.getElementById('sbOverlay').classList.add('open');
  document.getElementById('sidebar').classList.add('open');
  document.body.style.overflow='hidden';
}
function replaySurvey(){
  // Walk through saved answers to render all previously answered questions
  const survey=SURVEYS[currentSurvey];
  const ans=window._sbAns||{};
  let qId='q1';
  const visited=[];
  // Follow the answer path
  while(qId && !visited.includes(qId)){
    visited.push(qId);
    const q=survey.qs.find(x=>x.id===qId);
    if(!q) break;
    showQ(qId);
    if(q.type==='bool' && ans[qId]!==undefined){
      // Pre-select button
      const stepEl=document.getElementById('sq_'+qId);
      if(stepEl){
        const btns=stepEl.querySelectorAll('.sq-yn');
        btns.forEach(b=>{ if(b.textContent.trim().toLowerCase()===ans[qId]) b.classList.add('sel'); b.disabled=true; });
      }
      qId = ans[qId]==='yes' ? q.yes : q.no;
    } else if(q.type==='text' && ans[qId]!==undefined){
      const ta=document.getElementById('sqta_'+qId);
      if(ta){ ta.value=ans[qId]; ta.disabled=true; stepEl && stepEl.querySelector('.sq-ok') && (stepEl.querySelector('.sq-ok').disabled=true); }
      qId=q.next;
    } else {
      break; // Stop - unanswered or preview/end
    }
  }
}
function closeSidebar(){
  document.getElementById('sbOverlay').classList.remove('open');
  document.getElementById('sidebar').classList.remove('open');
  document.body.style.overflow='';
  currentSurvey=null;visibleQs=[];
}

/* ─── Show a question ──────────────────── */
function showQ(id){
  const survey=SURVEYS[currentSurvey];
  const q=survey.qs.find(x=>x.id===id);
  if(!q)return;
  visibleQs.push(id);
  const scroll=document.getElementById('sbScroll');

  if(q.type==='bool'){
    const div=document.createElement('div');
    div.className='sq visible'; div.id='sq_'+id;
    const list=q.list?`<ul class="sq-list">${q.list.map(l=>`<li>${l}</li>`).join('')}</ul>`:'';
    div.innerHTML=`<div class="sq-num"><span class="sq-num-n">${q.n}</span><span class="sq-num-arrow">&#x27A4;</span></div><div class="sq-txt">${q.q}</div>${list}<div class="sq-bool"><button type="button" class="sq-yn" onclick="answerBool('${id}','yes','${q.yes}',this)">Yes</button><button type="button" class="sq-yn" onclick="answerBool('${id}','no','${q.no}',this)">No</button></div>`;
    scroll.appendChild(div);
  }
  else if(q.type==='text'){
    const div=document.createElement('div');
    div.className='sq visible'; div.id='sq_'+id;
    div.innerHTML=`<div class="sq-num"><span class="sq-num-n">${q.n}</span><span class="sq-num-arrow">&#x27A4;</span></div><div class="sq-txt">${q.q}</div><div class="sq-ta-wrap"><textarea class="sq-ta" id="sqta_${id}" placeholder="Type your answer here ..." rows="1"></textarea></div><div class="sq-hint"><b>SHIFT + ENTER</b> to make a line break</div><div class="sq-ok-row"><button type="button" class="sq-ok" onclick="answerText('${id}','${q.next}')">OK</button><span class="sq-ok-hint">press <b>ENTER</b></span></div>`;
    scroll.appendChild(div);
    // auto-resize
    const ta=div.querySelector('.sq-ta');
    ta.addEventListener('input',()=>{ta.style.height='auto';ta.style.height=ta.scrollHeight+'px';});
    ta.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();answerText(id,q.next);}});
    setTimeout(()=>ta.focus(),50);
  }
  else if(q.type==='preview'){
    const text=q.build(getAnswers());
    const div=document.createElement('div');
    div.className='sq-preview visible'; div.id='sq_'+id;
    div.innerHTML=`<div class="sq-preview-lbl">Please review your statement:</div><div class="sq-preview-box"><div class="sq-preview-text">${xe(text)}</div></div><button type="button" class="sq-preview-ok" onclick="acceptStmt('${stm_xe(text).replace(/'/g,"\\'")}')">OK</button>`;
    scroll.appendChild(div);
  }
  else if(q.type==='end'){
    const div=document.createElement('div');
    div.className='sq-err visible'; div.id='sq_'+id;
    div.innerHTML=`<div class="sq-err-icon">&#x2705;</div><div class="sq-err-msg">${q.msg}</div><button type="button" class="sq-err-close" onclick="closeSidebar()">Close</button>`;
    scroll.appendChild(div);
  }

  // scroll to bottom
  setTimeout(()=>scroll.scrollTop=scroll.scrollHeight,50);
}

/* ─── Answer handlers ─────────────────── */
function answerBool(id, answer, nextId, btn){
  // Mark selected
  const parent=btn.closest('.sq-bool');
  parent.querySelectorAll('.sq-yn').forEach(b=>b.classList.remove('sel'));
  btn.classList.add('sel');
  // Disable both after answer
  parent.querySelectorAll('.sq-yn').forEach(b=>b.disabled=true);
  // Store answer
  if(!window._sbAns) window._sbAns={};
  window._sbAns[id]=answer;
  // Show next
  setTimeout(()=>showQ(nextId),300);
}

function answerText(id, nextId){
  const ta=document.getElementById('sqta_'+id);
  if(!ta||!ta.value.trim()){if(ta)ta.style.borderBottomColor='var(--error)';return;}
  if(!window._sbAns) window._sbAns={};
  window._sbAns[id]=ta.value.trim();
  // Disable
  ta.disabled=true;
  document.querySelectorAll(`#sq_${id} .sq-ok`).forEach(b=>b.disabled=true);
  setTimeout(()=>showQ(nextId),200);
}

function getAnswers(){return window._sbAns||{};}

/* ─── Accept statement ────────────────── */
function acceptStmt(text){
  const type=currentSurvey;
  S[type]=text;
  // Save answers for this survey so they persist across reloads
  SAVED_ANS[type]=Object.assign({}, window._sbAns||{});
  // Update badge
  const map={animals:['animalsBadge','animalsText','animalsOk','animalsBtn'],
             humans:['humansBadge','humansText','humansOk','humansBtn'],
             identifiable:['identBadge','identText','identOk','identBtn'],
             data:['dataBadge','dataText','dataOk','dataBtn']};
  const [bid,tid,oid,bBtnId]=map[type];
  document.getElementById(bid).classList.add('show');
  document.getElementById(tid).textContent=text;
  document.getElementById(oid).textContent='✓ Saved';
  document.getElementById(bBtnId).textContent='CONTINUE';
  document.getElementById('dataErr')?.classList.remove('show');
  closeSidebar();
  window._sbAns={};
  // Save immediately so DB is updated — button shows CONTINUE on next refresh
  doSave(false, true);
}

/* ─── Dirty / autosave ─────────────────── */
function dirty(){isDirty=true;clearTimeout(autoTimer);autoTimer=setTimeout(()=>doSave(false,true),2000);}

/* ─── Validate ─────────────────────────── */
function validate(){
  let ok=true;
  if(!document.querySelector('input[name="coi"]:checked')){document.getElementById('coiErr').classList.add('show');ok=false;}else document.getElementById('coiErr').classList.remove('show');
  if(!document.querySelector('input[name="ai"]:checked')){document.getElementById('aiErr').classList.add('show');ok=false;}else document.getElementById('aiErr').classList.remove('show');
  if(!document.getElementById('ethicsChk').checked){document.getElementById('ethicsErr').classList.add('show');ok=false;}else document.getElementById('ethicsErr').classList.remove('show');
  if(!S.data){document.getElementById('dataErr').classList.add('show');ok=false;}else document.getElementById('dataErr').classList.remove('show');
  return ok;
}

/* ─── Collect ──────────────────────────── */
function collect(){
  return {
    conflict_of_interest:       document.querySelector('input[name="coi"]:checked')?.value||'',
    conflict_details:           document.getElementById('coiDetails').value.trim(),
    manuscript_submission_type: document.querySelector('input[name="mst"]:checked')?.value||'no_previous',
    manuscript_details:         document.getElementById('mstDetails').value.trim(),
    funding_status:             document.querySelector('input[name="funding"]:checked')?.value||'no_funding',
    funding_details:            document.getElementById('fundDetails').value.trim(),
    funder_data:                JSON.stringify(funders),
    generative_ai_used:         document.querySelector('input[name="ai"]:checked')?.value??'',
    generative_ai_details:      document.getElementById('aiDetails').value.trim(),
    ethics_compliant:           document.getElementById('ethicsChk').checked?1:0,
    studies_animals:            S.animals||'',
    studies_humans:             S.humans||'',
    includes_identifiable_data: S.identifiable||'',
    data_availability_statement:S.data||'',
    // Sidebar Yes/No answers — saved as JSON per survey
    animals_answers:      JSON.stringify(SAVED_ANS.animals||{}),
    humans_answers:       JSON.stringify(SAVED_ANS.humans||{}),
    identifiable_answers: JSON.stringify(SAVED_ANS.identifiable||{}),
    data_answers:         JSON.stringify(SAVED_ANS.data||{})
  };
}

/* ─── Save ─────────────────────────────── */
function doSave(cont=false,silent=false){
  if(!silent&&!validate()){toast('Please fix the errors before saving','e');document.querySelector('.field-err.show')?.scrollIntoView({behavior:'smooth',block:'center'});return;}
  if(!silent){['saveBtn','saveContinueBtn'].forEach(id=>{const b=document.getElementById(id);b.disabled=true;b.innerHTML='<span class="spin"></span>';});}
  const fd=new FormData();fd.append('submission_id',SID);fd.append('data',JSON.stringify(collect()));
  fetch('ajax/save_statements.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    isDirty=false;
    if(!silent){['saveBtn','saveContinueBtn'].forEach(id=>{const b=document.getElementById(id);b.disabled=false;});document.getElementById('saveBtn').textContent='Save';document.getElementById('saveContinueBtn').innerHTML='Save &amp; Continue';}
    if(d.success){if(!silent)toast('Saved!','s');if(cont&&!silent)setTimeout(()=>location.href='submission_files.php?id='+SID,700);}
    else if(!silent)toast(d.message||'Save failed','e');
  }).catch(()=>{if(!silent){['saveBtn','saveContinueBtn'].forEach(id=>{const b=document.getElementById(id);b.disabled=false;});document.getElementById('saveBtn').textContent='Save';document.getElementById('saveContinueBtn').innerHTML='Save &amp; Continue';toast('Network error','e');}});
}

function toast(msg,t='i'){const w=document.getElementById('toastWrap');const d=document.createElement('div');d.className='toast t'+t;d.innerHTML=(t==='s'?'✅':t==='e'?'❌':'ℹ️')+' '+xe(msg);w.appendChild(d);setTimeout(()=>d.remove(),3500);}
window.addEventListener('beforeunload',e=>{if(isDirty){e.preventDefault();e.returnValue='';}});
</script>
</div>