<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();
$user    = getCurrentUser();
$user_id = $user['user_id'];

// ── Shared layout identity ────────────────────────────────────
$pageTitle  = 'Statements';
$activePage = 'submission';

$sid = (int)($_GET['id'] ?? 0);
if (!$sid) { header('Location: submission.php'); exit; }

// Ensure table exists & has all required columns
try {
    db()->exec("CREATE TABLE IF NOT EXISTS submission_statements (
        statement_id               INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id              INT UNSIGNED NOT NULL UNIQUE,
        conflict_of_interest       VARCHAR(10)  DEFAULT NULL,
        conflict_details           TEXT,
        manuscript_submission_type VARCHAR(20)  DEFAULT 'no_previous',
        manuscript_details         TEXT,
        funding_status             VARCHAR(30)  DEFAULT 'no_funding',
        funding_details            TEXT,
        funder_data                TEXT,
        generative_ai_used         TINYINT(1)   DEFAULT NULL,
        generative_ai_details      TEXT,
        ethics_compliant           TINYINT(1)   DEFAULT 0,
        studies_animals            TEXT,
        animals_answers            TEXT,
        studies_humans             TEXT,
        humans_answers             TEXT,
        includes_identifiable_data TEXT,
        identifiable_answers       TEXT,
        data_availability_statement TEXT,
        data_answers               TEXT,
        updated_at                 DATETIME DEFAULT NOW() ON UPDATE NOW()
    )");
    foreach ([
        'conflict_details TEXT','manuscript_details TEXT','funder_data TEXT',
        'animals_answers TEXT','humans_answers TEXT',
        'identifiable_answers TEXT','data_answers TEXT'
    ] as $c) {
        try { db()->exec("ALTER TABLE submission_statements ADD COLUMN $c"); } catch(PDOException $e) {}
    }
    foreach ([
        "MODIFY COLUMN conflict_of_interest VARCHAR(10) DEFAULT NULL",
        "MODIFY COLUMN manuscript_submission_type VARCHAR(20) DEFAULT 'no_previous'",
        "MODIFY COLUMN funding_status VARCHAR(30) DEFAULT 'no_funding'"
    ] as $mod) {
        try { db()->exec("ALTER TABLE submission_statements $mod"); } catch(PDOException $e) {}
    }
} catch(PDOException $e) {}

$q = db()->prepare(
    "SELECT s.*, j.name AS journal_name, at.preliminary_fee_chf
     FROM submissions s
     LEFT JOIN journals j ON j.journal_id = s.journal_id
     LEFT JOIN article_types at ON at.article_type_id = s.article_type_id
     WHERE s.submission_id = ? AND s.user_id = ?"
);
$q->execute([$sid, $user_id]);
$sub = $q->fetch();
if (!$sub) { header('Location: submission.php'); exit; }

try {
    $q2 = db()->prepare("SELECT * FROM submission_statements WHERE submission_id=?");
    $q2->execute([$sid]);
    $ss = $q2->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(PDOException $e) { $ss = []; }

function sv($ss, $k, $d='') { return $ss[$k] ?? $d; }
function ck($ss, $k, $v)    { return (($ss[$k] ?? '') === $v) ? 'checked' : ''; }

require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── page overrides ──────────────────────────────────────── */
.au-main { padding: 0 0 100px 0; }

:root {
  --teal: #1A7F8E; --teal-dk: #136070; --teal-lt: #E0F4F7;
  --primary: #E05A2B; --blue: #1B3F6E;
  --error: #D32F2F; --success: #2E7D32;
  --r: 3px;
}

.page-wrap  { max-width: 980px; margin: 0 auto; padding: 20px 22px; }
.breadcrumb { display: flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); margin-bottom: 16px; }
.breadcrumb a { color: var(--primary); text-decoration: none; font-weight: 500; }
.breadcrumb a:hover { text-decoration: underline; }

/* Tile */
.tile { background: var(--white); border-left: 5px solid var(--error); margin-bottom: 3px; }
.tile-trigger { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; cursor: pointer; border-bottom: 1px solid #EBEBEB; user-select: none; }
.tile-trigger:hover { background: #FAFAFA; }
.tile-name   { font-size: 15px; font-weight: 700; }
.tile-status { font-size: 12.5px; color: var(--error); font-weight: 600; margin-top: 2px; }
.tile-body   { padding: 26px 32px 0; max-width: 940px; }

/* Section */
.sec { margin-bottom: 26px; padding-bottom: 26px; border-bottom: 1px solid #EBEBEB; }
.sec:last-of-type { border-bottom: none; }
.sec-title { font-size: 15px; font-weight: 700; margin-bottom: 10px; }
.sec-sub   { font-size: 13.5px; font-weight: 600; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.sec-desc  { font-size: 13px; color: var(--muted); line-height: 1.7; margin-bottom: 12px; }

/* Options */
.opts { display: flex; flex-direction: column; gap: 10px; }
.opt  { display: flex; align-items: flex-start; gap: 10px; font-size: 13.5px; line-height: 1.5; cursor: pointer; }
.opt input[type=radio], .opt input[type=checkbox] { width: 16px; height: 16px; flex-shrink: 0; margin-top: 2px; accent-color: var(--teal); cursor: pointer; }

/* Explain box */
.explain { margin-top: 12px; display: none; }
.explain.show { display: block; }
.ta { width: 100%; padding: 10px 14px; border: 1.5px solid #CBD5E1; border-radius: var(--r); font-family: var(--font); font-size: 13px; resize: vertical; min-height: 88px; outline: none; transition: border-color .15s; line-height: 1.6; }
.ta:focus { border-color: var(--teal); }
.ta::placeholder { color: #9CA3AF; }

/* Info icon */
.iico { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; border-radius: 50%; background: #E3F2FD; color: #1565C0; font-size: 9px; font-weight: 700; cursor: default; flex-shrink: 0; vertical-align: middle; }

/* Funder */
.funder-tip { background: #E3F2FD; border-radius: var(--r); padding: 9px 13px; font-size: 13px; color: #1565C0; margin-bottom: 14px; display: flex; align-items: center; gap: 8px; }
.funder-card { border: 1px solid var(--border); border-radius: 4px; padding: 14px; margin-bottom: 10px; background: var(--white); }
.fname-row { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.fname-inp { flex: 1; padding: 7px 11px; border: 1.5px solid #CBD5E1; border-radius: var(--r); font-family: var(--font); font-size: 13px; outline: none; }
.fname-inp:focus { border-color: var(--teal); }
.frm-btn { background: none; border: none; cursor: pointer; color: #9CA3AF; font-size: 17px; padding: 2px 6px; line-height: 1; }
.frm-btn:hover { color: var(--error); }
.award-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; }
.aw-inp { padding: 5px 9px; border: 1.5px solid #CBD5E1; border-radius: var(--r); font-family: var(--font); font-size: 12.5px; outline: none; width: 160px; }
.aw-inp:focus { border-color: var(--teal); }
.aw-add { background: none; border: none; cursor: pointer; color: var(--teal); font-size: 18px; font-weight: 700; padding: 0 3px; line-height: 1; }
.aw-tag { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; background: var(--teal-lt); border: 1px solid #B2DFDB; border-radius: 2px; font-size: 12px; color: var(--teal); font-weight: 600; }
.aw-tag-rm { background: none; border: none; cursor: pointer; color: var(--teal); font-size: 12px; padding: 0; line-height: 1; }
.apc-row { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-top: 4px; }
.apc-row input { accent-color: var(--teal); width: 14px; height: 14px; }
.add-funder { display: flex; align-items: center; gap: 6px; margin: 10px auto; padding: 8px 22px; border: 1.5px solid var(--teal); border-radius: var(--r); background: var(--white); color: var(--teal); font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; transition: all .15s; }
.add-funder:hover { background: var(--teal-lt); }

/* Survey rows */
.survey-row { display: flex; align-items: center; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #F3F4F6; }
.survey-row:last-child { border-bottom: none; }
.survey-name { font-style: italic; font-size: 13.5px; }
.survey-right { display: flex; align-items: center; gap: 10px; }
.survey-ok { font-size: 11.5px; color: var(--success); font-weight: 600; }
.survey-btn { font-size: 11px; font-weight: 700; letter-spacing: .5px; color: var(--teal); text-transform: uppercase; cursor: pointer; padding: 4px 10px; border: 1.5px solid var(--teal); border-radius: 2px; background: var(--white); font-family: var(--font); transition: all .15s; }
.survey-btn:hover { background: var(--teal); color: #fff; }

/* Statement badge */
.stmt-badge { background: #F0FBF5; border: 1px solid #B2DFDB; border-radius: var(--r); padding: 10px 14px; font-size: 13px; line-height: 1.6; margin-top: 8px; display: none; }
.stmt-badge.show { display: block; }
.stmt-badge-lbl { font-size: 11px; font-weight: 700; color: var(--success); text-transform: uppercase; letter-spacing: .3px; margin-bottom: 5px; }

/* Errors */
.field-err { display: none; align-items: center; gap: 5px; font-size: 12.5px; color: var(--error); margin-top: 8px; font-weight: 500; }
.field-err.show { display: flex; }

/* Buttons */
.btn { display: inline-flex; align-items: center; gap: 5px; padding: 8px 18px; border-radius: var(--r); font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; border: none; transition: all .15s; }
.btn-outline { background: var(--white); border: 1.5px solid var(--teal); color: var(--teal); }
.btn-outline:hover { background: var(--teal-lt); }
.btn-fill { background: var(--teal); color: #fff; }
.btn-fill:hover { background: var(--teal-dk); }
button.btn { font-family: var(--font); }

.tile-nav { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; border-top: 1px solid #EBEBEB; background: var(--white); }
.tile-nav .r { display: flex; gap: 10px; }

/* Bottom bar */
.bottom-bar { position: fixed; bottom: 0; left: var(--sidebar-w, 240px); right: 0; background: var(--white); border-top: 1px solid var(--border); padding: 10px 26px; display: flex; align-items: center; justify-content: space-between; z-index: 300; box-shadow: 0 -2px 6px rgba(0,0,0,.07); flex-wrap: wrap; gap: 10px; }
.btm-fee { font-size: 13px; color: var(--muted); }
.btm-fee strong { color: var(--text); font-weight: 700; }
.btm-q { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.btm-acts { display: flex; gap: 10px; }

/* ═══ SIDEBAR ═══════════════════════════════════════════════ */
.sb-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.4); z-index: 500; display: none; opacity: 0; transition: opacity .25s; }
.sb-overlay.open { display: block; opacity: 1; }
.sidebar { position: fixed; top: 0; right: -520px; width: 500px; max-width: 96vw; height: 100vh; background: var(--white); z-index: 501; display: flex; flex-direction: column; box-shadow: -6px 0 30px rgba(0,0,0,.18); transition: right .3s cubic-bezier(.4,0,.2,1); }
.sidebar.open { right: 0; }
.sb-top { display: flex; align-items: center; justify-content: space-between; padding: 0 20px; height: 50px; border-bottom: 1px solid #EBEBEB; flex-shrink: 0; }
.sb-title { font-size: 13px; font-weight: 700; text-transform: uppercase; letter-spacing: .6px; color: var(--text); }
.sb-x { background: none; border: none; cursor: pointer; color: var(--muted); font-size: 20px; line-height: 1; padding: 4px; border-radius: 3px; }
.sb-x:hover { background: #F3F4F6; color: var(--text); }
.sb-scroll { flex: 1; overflow-y: auto; padding: 0; }
.sq { padding: 20px 24px; border-bottom: 1px solid #F3F4F6; display: none; animation: fadeInUp .2s ease; }
.sq.visible { display: block; }
@keyframes fadeInUp { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }
.sq-num { font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 10px; display: flex; align-items: center; gap: 6px; }
.sq-num-n { color: var(--text); font-weight: 700; }
.sq-num-arrow { color: #9CA3AF; font-size: 11px; }
.sq-txt { font-size: 16px; font-weight: 700; color: var(--text); line-height: 1.5; margin-bottom: 16px; }
.sq-list { background: #F8F9FA; border-radius: var(--r); padding: 8px 14px 8px 28px; margin-bottom: 14px; list-style: disc; }
.sq-list li { font-size: 12.5px; color: var(--muted); margin-bottom: 2px; }
.sq-bool { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 4px; }
.sq-yn { padding: 12px 10px; border: 2px solid var(--border); border-radius: var(--r); background: var(--white); font-family: var(--font); font-size: 15px; font-weight: 700; cursor: pointer; text-align: center; transition: all .15s; color: var(--text); }
.sq-yn:hover:not(.sel) { border-color: var(--teal); color: var(--teal); background: var(--teal-lt); }
.sq-yn.sel { border-color: var(--teal); background: var(--teal); color: #fff; }
.sq-ta-wrap { margin-top: 4px; border-bottom: 2px solid var(--border); padding-bottom: 4px; transition: border-color .15s; }
.sq-ta-wrap:focus-within { border-bottom-color: var(--teal); }
.sq-ta { width: 100%; border: none; outline: none; font-family: var(--font); font-size: 14px; color: var(--text); resize: none; line-height: 1.5; min-height: 36px; padding: 2px 0; }
.sq-hint { font-size: 12px; color: var(--muted); margin-top: 6px; }
.sq-ok-row { display: flex; align-items: center; gap: 10px; margin-top: 10px; }
.sq-ok { padding: 7px 20px; background: var(--teal); color: #fff; border: none; border-radius: var(--r); font-family: var(--font); font-size: 13px; font-weight: 700; cursor: pointer; transition: background .15s; }
.sq-ok:hover { background: var(--teal-dk); }
.sq-ok-hint { font-size: 12px; color: var(--muted); }
.sq-preview { padding: 24px; display: none; animation: fadeInUp .2s ease; }
.sq-preview.visible { display: block; }
.sq-preview-lbl { font-size: 14px; font-weight: 600; color: var(--text); margin-bottom: 12px; }
.sq-preview-box { border: 1px solid var(--border); border-radius: 4px; padding: 2px 0; margin-bottom: 20px; }
.sq-preview-text { font-size: 14px; color: var(--text); line-height: 1.7; padding: 14px 18px; }
.sq-preview-ok { padding: 10px 36px; background: var(--teal); color: #fff; border: none; border-radius: var(--r); font-family: var(--font); font-size: 14px; font-weight: 700; cursor: pointer; }
.sq-preview-ok:hover { background: var(--teal-dk); }
.sq-err { padding: 24px; text-align: center; display: none; }
.sq-err.visible { display: block; }
.sq-err-icon { font-size: 36px; margin-bottom: 12px; }
.sq-err-msg  { font-size: 14px; color: var(--text); line-height: 1.7; margin-bottom: 16px; }
.sq-err-close { padding: 8px 24px; background: var(--teal); color: #fff; border: none; border-radius: var(--r); font-family: var(--font); font-size: 13px; font-weight: 700; cursor: pointer; }

/* Toast */
.toast-wrap { position: fixed; bottom: 70px; right: 18px; display: flex; flex-direction: column; gap: 7px; z-index: 9999; }
.toast { padding: 10px 15px; border-radius: var(--r); font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 7px; animation: su .2s ease; }
.ts { background: #1D8A5E; } .te { background: var(--error); } .ti { background: var(--teal); }
@keyframes su { from{transform:translateY(10px);opacity:0} to{transform:translateY(0);opacity:1} }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: sp .6s linear infinite; }
@keyframes sp { to{transform:rotate(360deg)} }
</style>

<!-- ════ PAGE CONTENT ══════════════════════════════════════════ -->
<div class="page-wrap">

  <!-- Breadcrumb -->
  <div class="breadcrumb">
    <a href="dashboard.php">Overview</a>
    <span>›</span>
    <a href="submission.php?id=<?= $sid ?>">Submission Details</a>
    <span>›</span>
    <a href="editorial.php?id=<?= $sid ?>">Editorial</a>
    <span>›</span>
    <span>Statements</span>
  </div>

  <div class="tile" id="stmtTile">
    <div class="tile-trigger" onclick="toggleTile()">
      <div>
        <div class="tile-name">Statements</div>
        <div class="tile-status" id="tileStatus">⊗ Incomplete</div>
      </div>
      <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);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);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="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);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);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="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);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);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">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="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);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);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="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="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://communeglobal.com/journals/social-science/author-style-guidelines"
           target="_blank" rel="noopener" style="font-size:12.5px;color:var(--teal)">
          ℹ Author guidelines ↗
        </a>
      </div>
    </div><!-- /tile-body -->

    <div class="tile-nav">
      <a href="editorial.php?id=<?= $sid ?>" class="btn btn-outline">← Previous</a>
      <div class="r">
        <button type="button" class="btn btn-fill" id="saveContinueBtn" onclick="doSave(true)">Save &amp; Continue</button>
        <button type="button" class="btn btn-outline" id="saveBtn" onclick="doSave(false)">Save</button>
      </div>
    </div>
    </div><!-- /tileContent -->
  </div><!-- /tile -->

</div><!-- /page-wrap -->

<!-- Sidebar -->
<div class="sb-overlay" id="sbOverlay" onclick="closeSidebar()"></div>
<div class="sidebar" id="sidebar">
  <div class="sb-top">
    <div class="sb-title" id="sbTitle">Survey</div>
    <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 fee: <strong>$35.00 USD</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>

<div class="toast-wrap" id="toastWrap"></div>

<script>
const SID = <?= $sid ?>;
let isDirty = false, autoTimer = null;
let currentSurvey = null;
let visibleQs = [];

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?'∨':'∧';
}
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;dirty()"><button type="button" class="frm-btn" onclick="funders.splice(${i},1);renderFunders();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();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;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 ════════════════════════════════════════ */
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; window._sbAns=Object.assign({},SAVED_ANS[type]||{});
    const sv=SURVEYS[type];
    document.getElementById('sbTitle').textContent=sv.title;
    document.getElementById('sbScroll').innerHTML='';
    visibleQs=[]; replaySurvey();
    document.getElementById('sbOverlay').classList.add('open');
    document.getElementById('sidebar').classList.add('open');
    document.body.style.overflow='hidden';
}
function replaySurvey(){
    const survey=SURVEYS[currentSurvey]; const ans=window._sbAns||{};
    let qId='q1'; const visited=[];
    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){
            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;}
            qId=q.next;
        } else break;
    }
}
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);
        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('${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);
    }
    setTimeout(()=>scroll.scrollTop=scroll.scrollHeight,50);
}

/* ── Answer handlers ──────────────────────────────────────── */
function answerBool(id,answer,nextId,btn){
    const parent=btn.closest('.sq-bool');
    parent.querySelectorAll('.sq-yn').forEach(b=>b.classList.remove('sel'));
    btn.classList.add('sel');
    parent.querySelectorAll('.sq-yn').forEach(b=>b.disabled=true);
    if(!window._sbAns) window._sbAns={};
    window._sbAns[id]=answer;
    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();
    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; SAVED_ANS[type]=Object.assign({},window._sbAns||{});
    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={};
    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||S.data.trim()===''){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||'',
        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(cont&&!silent&&!validate()){
        toast('Please complete all required fields before continuing','e');
        document.querySelector('.field-err.show')?.scrollIntoView({behavior:'smooth',block:'center'});
        return;
    }
    if(!silent&&!validate()) toast('Some required fields are missing. You can still save as draft.','e');
    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(cont?'Saved and continuing...':'Saved!','s');
            if(cont&&!silent)setTimeout(()=>location.href='payment.php?id='+SID,800);
        } 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>

<?php layoutEnd(); ?>