<div style="padding:24px 32px 24px">
<!-- ═══════════════════════ TOPBAR ══════════════════════════ -->


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

  

  <!-- Section heading (collapsible like communeglobal) -->
  <div class="section-heading" onclick="toggleSection()">
    <div class="section-heading-left">
      Authors and contributors
      <span class="info-icon" title="Provide details for all authors who contributed to this work">i</span>
    </div>
    <div style="display:flex;align-items:center;gap:16px">
      <span class="section-badge-incomplete" id="sectionBadge">
        <span style="font-size:14px">●</span> Incomplete
      </span>
      <span class="section-collapse open" id="collapseIcon">∧</span>
    </div>
  </div>

  <div class="section-body" id="sectionBody">

    <!-- Description -->
    <div class="section-desc">
      <p><strong>Authors details</strong> <span class="info-icon">i</span></p>
      <p>Please provide the complete list of authors who contributed to this work and their affiliation details. The author order is from top to bottom, with the first author at the top.</p>
      <p>Please note that authors must ensure the author list is correct and in line with our authorship and contributions policies at the time of submission. Where there are discrepancies in the manuscript doc or text files and the submission system, the author list will be taken from the submission system by default. Please ensure the submission system is accurate, as changes to the author list may not be permitted later in the process (<a href="#">author guidelines</a>).</p>
    </div>

    <!-- Authors container -->
    <div id="authorsContainer">
      <?php foreach ($authors as $idx => $author):
        $authorIdx  = $idx;
        $authorId   = (int)$author['author_id'];
        $contrib    = $contributions[$authorId] ?? [];
        $ordinal    = ['1st','2nd','3rd','4th','5th','6th','7th','8th'][$idx] ?? ($idx+1).'th';
        $isFirst    = $idx === 0;
        $isLast     = $idx === count($authors) - 1;
      ?>

      <?php ob_start(); ?>
      <div class="author-card" id="authorCard_<?= $authorIdx ?>" data-idx="<?= $authorIdx ?>">
        <!-- Author card header -->
        <div class="author-card-header">
          <span class="author-label"><?= $ordinal ?> Author</span>
          <div class="author-actions">
            <button type="button" class="author-action-btn"
                    onclick="moveAuthor(<?= $authorIdx ?>, 'up')"
                    <?= $isFirst ? 'disabled' : '' ?>
                    title="Move up">
              ▲ Move up
            </button>
            <button type="button" class="author-action-btn"
                    onclick="moveAuthor(<?= $authorIdx ?>, 'down')"
                    <?= $isLast ? 'disabled' : '' ?>
                    title="Move down">
              ▼ Move down
            </button>
            <?php if (!$isFirst): ?>
            <button type="button" class="author-action-btn btn-delete"
                    onclick="removeAuthor(<?= $authorIdx ?>)"
                    title="Remove author">
              🗑
            </button>
            <?php endif; ?>
          </div>
        </div>

        <!-- Author fields -->
        <div class="author-card-body">

          <!-- Row: Email | Title | Affiliation -->
          <div class="form-row form-row-email-title">

            <!-- Email -->
            <div class="form-group">
              <label class="form-label">Email</label>
              <input type="email" class="form-input" name="email_<?= $authorIdx ?>"
                     placeholder="Start by entering the email address"
                     value="<?= htmlspecialchars($author['email'] ?? '') ?>"
                     <?= $isFirst ? 'readonly style="background:#F9FAFB;color:var(--text-muted)"' : '' ?>
                     oninput="onFieldChange(<?= $authorIdx ?>,'email',this)"
                     onblur="validateEmail(<?= $authorIdx ?>)">
              <div class="field-error" id="emailErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span>
                <span id="emailErrMsg_<?= $authorIdx ?>">Please enter a valid email address</span>
              </div>
            </div>

            <!-- Title -->
            <div class="form-group">
              <label class="form-label">Title <?= !$isFirst ? '<span class="optional-lbl">(optional)</span>' : '' ?></label>
              <select class="form-select" name="title_<?= $authorIdx ?>"
                      onchange="onFieldChange(<?= $authorIdx ?>,'title',this)">
                <?php foreach ($titles as $t): ?>
                  <option value="<?= $t ?>" <?= ($author['title'] ?? '') === $t ? 'selected' : '' ?>>
                    <?= $t ?: '— Title —' ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <!-- Affiliation (right column, spans rows visually) -->
            <div class="form-group" style="grid-row:1/3">
              <label class="form-label">Affiliation</label>
              <div class="affil-search-wrap">
                <input type="text" class="form-input" id="affilSearch_<?= $authorIdx ?>"
                       placeholder="Select or type to search"
                       autocomplete="off"
                       oninput="onAffilSearch(<?= $authorIdx ?>,this)"
                       onblur="hideAffilDropdown(<?= $authorIdx ?>)">
                <div class="affil-dropdown" id="affilDrop_<?= $authorIdx ?>"></div>
              </div>
              <!-- Validation error -->
              <div class="field-error" id="affilErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span>
                <span>Please fill this field to continue</span>
              </div>

              <!-- Selected affiliation tags -->
              <?php if (!empty($author['affiliation_id'])): ?>
              <div class="affil-label">Selected affiliations</div>
              <div class="affil-tags" id="affilTags_<?= $authorIdx ?>">
                <div class="affil-tag" data-affil-id="<?= $author['affiliation_id'] ?>">
                  <span class="affil-tag-name">
                    <?= htmlspecialchars($author['affil_name'] ?? '') ?>
                    <?php if ($author['affil_city']): ?> , <?= htmlspecialchars($author['affil_city']) ?><?php endif; ?>
                    <?php if ($author['affil_country']): ?> , <?= htmlspecialchars($author['affil_country']) ?><?php endif; ?>
                  </span>
                  <div class="affil-tag-actions">
                    <button type="button" class="affil-tag-btn affil-tag-edit" title="Edit">✏</button>
                    <button type="button" class="affil-tag-btn affil-tag-del"
                            onclick="removeAffil(<?= $authorIdx ?>, this)"
                            title="Remove">✕</button>
                  </div>
                </div>
              </div>
              <?php else: ?>
              <div class="affil-label" id="affilTagsLabel_<?= $authorIdx ?>" style="display:none">Selected affiliations</div>
              <div class="affil-tags" id="affilTags_<?= $authorIdx ?>"></div>
              <?php endif; ?>

              <!-- Institutional Partnership info box (only 1st author) -->
              <?php if ($isFirst): ?>
              <div class="partner-box">
                <span class="partner-box-icon">ℹ️</span>
                <div>
                  <strong>Institutional Partnerships</strong><br>
                  Based on institutional emails and affiliations we can automatically identify partnerships those institutions to cover publishing costs
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Row: First | Middle | Last -->
          <div class="form-row form-row-3" style="margin-bottom:12px">
            <div class="form-group">
              <label class="form-label">First name</label>
              <input type="text" class="form-input" name="first_name_<?= $authorIdx ?>"
                     placeholder="First name"
                     value="<?= htmlspecialchars($author['first_name'] ?? '') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'first_name',this)"
                     onblur="validateRequired(<?= $authorIdx ?>,'first_name')">
              <div class="field-error" id="firstNameErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span> <span>Please fill this field to continue</span>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Middle name <span class="optional-lbl">(optional)</span></label>
              <input type="text" class="form-input" name="middle_name_<?= $authorIdx ?>"
                     placeholder="Middle name"
                     value="<?= htmlspecialchars($author['middle_name'] ?? '') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'middle_name',this)">
            </div>
            <div class="form-group">
              <label class="form-label">Last name</label>
              <input type="text" class="form-input" name="last_name_<?= $authorIdx ?>"
                     placeholder="Last name"
                     value="<?= htmlspecialchars($author['last_name'] ?? '') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'last_name',this)"
                     onblur="validateRequired(<?= $authorIdx ?>,'last_name')">
              <div class="field-error" id="lastNameErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span> <span>Please fill this field to continue</span>
              </div>
            </div>
          </div>

          <!-- Row: Phone + Corresponding + Institutional email -->
          <div class="form-row form-row-3" style="margin-bottom:4px">
            <div class="form-group">
              <label class="form-label">Phone Number</label>
              <div class="phone-wrap">
                <select class="form-select phone-code" name="phone_code_<?= $authorIdx ?>"
                        onchange="onFieldChange(<?= $authorIdx ?>,'phone_country_code',this)">
                  <?php foreach ($countryCodes as $code => $country): ?>
                    <option value="<?= $code ?>" <?= ($author['phone_country_code'] ?? '') === $code ? 'selected' : '' ?>>
                      <?= $code ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <input type="tel" class="form-input phone-num" name="phone_<?= $authorIdx ?>"
                       placeholder="Phone number"
                       value="<?= htmlspecialchars($author['phone_number'] ?? '') ?>"
                       oninput="onFieldChange(<?= $authorIdx ?>,'phone_number',this)">
              </div>
            </div>
            <div class="form-group" style="justify-content:flex-end;padding-bottom:4px">
              <label class="form-label">&nbsp;</label>
              <div class="checkbox-row">
                <input type="checkbox" id="corresponding_<?= $authorIdx ?>"
                       <?= $author['is_corresponding'] ? 'checked' : '' ?>
                       onchange="onFieldChange(<?= $authorIdx ?>,'is_corresponding',this)">
                <label for="corresponding_<?= $authorIdx ?>">
                  This is a corresponding author
                  <span>(optional)</span>
                </label>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Institutional email <span class="optional-lbl">(optional)</span></label>
              <input type="email" class="form-input" name="inst_email_<?= $authorIdx ?>"
                     placeholder="Please provide an institutional email address here"
                     value="<?= htmlspecialchars($author['institutional_email'] ?? '') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'institutional_email',this)">
            </div>
          </div>

          <!-- Contribution section -->
          <div class="contrib-section">
            <div class="contrib-heading">
              Author contribution
              <span class="info-icon" title="CRediT taxonomy — describe each author's contribution">i</span>
            </div>
            <div class="contrib-subtext">Select the areas in which the author contributed</div>
            <div class="field-error contrib-error" id="contribErr_<?= $authorIdx ?>" style="display:none">
              <span class="field-error-icon">!</span>
              Please select at least one mandatory contribution
            </div>

            <div class="contrib-grid">
              <!-- Mandatory -->
              <div class="contrib-group">
                <div class="contrib-group-title">
                  <input type="checkbox" id="mandatoryAll_<?= $authorIdx ?>"
                         onchange="toggleMandatoryAll(<?= $authorIdx ?>,this)"
                         style="accent-color:var(--primary);width:14px;height:14px">
                  <label for="mandatoryAll_<?= $authorIdx ?>" style="cursor:pointer;font-size:12px;font-weight:700">Mandatory contribution</label>
                </div>
                <div class="contrib-checkbox-wrap">
                  <?php foreach ($creditFields['mandatory'] as $key => $label): ?>
                  <label class="contrib-checkbox">
                    <input type="checkbox"
                           id="credit_<?= $key ?>_<?= $authorIdx ?>"
                           name="credit_<?= $key ?>_<?= $authorIdx ?>"
                           value="1"
                           <?= !empty($contrib[$key]) ? 'checked' : '' ?>
                           onchange="onContribChange(<?= $authorIdx ?>)">
                    <?= $label ?>
                  </label>
                  <?php endforeach; ?>
                </div>
              </div>

              <!-- Additional -->
              <div class="contrib-additional">
                <div class="contrib-additional-title">
                  <input type="checkbox" id="additionalAll_<?= $authorIdx ?>"
                         onchange="toggleAdditionalAll(<?= $authorIdx ?>,this)"
                         style="accent-color:var(--primary);width:14px;height:14px">
                  <label for="additionalAll_<?= $authorIdx ?>" style="cursor:pointer;font-size:12px;font-weight:700">
                    Additional contribution <span style="font-weight:400;color:var(--text-muted)">(Optional)</span>
                  </label>
                </div>
                <div class="contrib-extra-grid">
                  <?php foreach ($creditFields['additional'] as $key => $label): ?>
                  <label class="contrib-checkbox">
                    <input type="checkbox"
                           id="credit_<?= $key ?>_<?= $authorIdx ?>"
                           name="credit_<?= $key ?>_<?= $authorIdx ?>"
                           value="1"
                           <?= !empty($contrib[$key]) ? 'checked' : '' ?>
                           onchange="onContribChange(<?= $authorIdx ?>)">
                    <?= $label ?>
                  </label>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>
          </div><!-- /contrib -->

        </div><!-- /author-card-body -->
      </div><!-- /author-card -->
      <?php echo ob_get_clean(); ?>

      <?php endforeach; ?>
    </div><!-- /authorsContainer -->

    <!-- Add another author -->
    <div class="add-author-wrap">
      <button type="button" class="btn-add-author" onclick="addAuthor()">
        ＋ Add another author
      </button>
    </div>

    <!-- Page form actions -->
    <div style="display:flex;gap:12px;justify-content:flex-end;padding-top:16px;border-top:1px solid var(--border)">
      <a href="manuscript.php?id=<?= $submission_id ?>" class="btn btn-back">← Back</a>
      <button type="button" class="btn btn-save" onclick="saveAuthors(false)" id="saveBtn">💾 Save</button>
      <button type="button" class="btn btn-preview" onclick="saveAuthors(true)" id="saveContinueBtn" style="background:var(--blue);color:#fff">
        Save &amp; Continue →
      </button>
    </div>

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

<!-- ══════════════════ BOTTOM STICKY BAR ════════════════════ -->
<div class="bottom-bar">
  <div class="bottom-fee">
    Preliminary fees: <strong><?= $fee ?> CHF</strong><br>
    <span style="font-size:11px">Payment after acceptance</span>
  </div>
  <div class="bottom-quality">
    Submission quality: <span class="quality-score" id="qualityPct">90%</span>
    <div>
      <div style="font-size:11.5px;color:var(--text-muted)">⚠ <span id="suggestedCount">1</span> suggested action</div>
    </div>
  </div>
  <div class="bottom-actions">
    <button class="btn btn-preview">Preview</button>
    <button class="btn btn-submit">🔵 Submit</button>
  </div>
</div>

<!-- Toast container -->
<div class="toast-container" id="toastContainer"></div>

<!-- Author template (hidden) for dynamically adding new authors -->
<template id="authorTemplate">
  <div class="author-card" id="authorCard_IDX" data-idx="IDX">
    <div class="author-card-header">
      <span class="author-label">ORD Author</span>
      <div class="author-actions">
        <button type="button" class="author-action-btn" onclick="moveAuthor(IDX,'up')">▲ Move up</button>
        <button type="button" class="author-action-btn" onclick="moveAuthor(IDX,'down')">▼ Move down</button>
        <button type="button" class="author-action-btn btn-delete" onclick="removeAuthor(IDX)">🗑</button>
      </div>
    </div>
    <div class="author-card-body">
      <div class="form-row form-row-email-title">
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="email" class="form-input" name="email_IDX"
                 placeholder="Start by entering the email address"
                 oninput="onFieldChange(IDX,'email',this)"
                 onblur="validateEmail(IDX)">
          <div class="field-error" id="emailErr_IDX" style="display:none">
            <span class="field-error-icon">!</span>
            <span id="emailErrMsg_IDX">Please enter a valid email address</span>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">Title <span class="optional-lbl">(optional)</span></label>
          <select class="form-select" name="title_IDX" onchange="onFieldChange(IDX,'title',this)">
            <option value="">— Title —</option>
            <option>Mr</option><option>Mrs</option><option>Ms</option>
            <option>Dr</option><option>Prof</option>
          </select>
        </div>
        <div class="form-group" style="grid-row:1/3">
          <label class="form-label">Affiliation</label>
          <div class="affil-search-wrap">
            <input type="text" class="form-input" id="affilSearch_IDX"
                   placeholder="Select or type to search"
                   autocomplete="off"
                   oninput="onAffilSearch(IDX,this)"
                   onblur="hideAffilDropdown(IDX)">
            <div class="affil-dropdown" id="affilDrop_IDX"></div>
          </div>
          <div class="field-error" id="affilErr_IDX" style="display:none">
            <span class="field-error-icon">!</span> <span>Please fill this field to continue</span>
          </div>
          <div class="affil-label" id="affilTagsLabel_IDX" style="display:none">Selected affiliations</div>
          <div class="affil-tags" id="affilTags_IDX"></div>
        </div>
      </div>
      <div class="form-row form-row-3" style="margin-bottom:12px">
        <div class="form-group">
          <label class="form-label">First name</label>
          <input type="text" class="form-input" name="first_name_IDX"
                 placeholder="First name"
                 oninput="onFieldChange(IDX,'first_name',this)"
                 onblur="validateRequired(IDX,'first_name')">
          <div class="field-error" id="firstNameErr_IDX" style="display:none">
            <span class="field-error-icon">!</span> <span>Please fill this field to continue</span>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">Middle name <span class="optional-lbl">(optional)</span></label>
          <input type="text" class="form-input" name="middle_name_IDX" placeholder="Middle name"
                 oninput="onFieldChange(IDX,'middle_name',this)">
        </div>
        <div class="form-group">
          <label class="form-label">Last name</label>
          <input type="text" class="form-input" name="last_name_IDX" placeholder="Last name"
                 oninput="onFieldChange(IDX,'last_name',this)"
                 onblur="validateRequired(IDX,'last_name')">
          <div class="field-error" id="lastNameErr_IDX" style="display:none">
            <span class="field-error-icon">!</span> <span>Please fill this field to continue</span>
          </div>
        </div>
      </div>
      <div class="form-row form-row-3" style="margin-bottom:4px">
        <div class="form-group">
          <label class="form-label">Phone Number</label>
          <div class="phone-wrap">
            <select class="form-select phone-code" name="phone_code_IDX" onchange="onFieldChange(IDX,'phone_country_code',this)">
              <option value="+91">+91</option><option value="+1">+1</option>
              <option value="+44">+44</option><option value="+49">+49</option>
              <option value="+33">+33</option><option value="+81">+81</option>
              <option value="+86">+86</option>
            </select>
            <input type="tel" class="form-input phone-num" name="phone_IDX" placeholder="Phone number"
                   oninput="onFieldChange(IDX,'phone_number',this)">
          </div>
        </div>
        <div class="form-group" style="justify-content:flex-end;padding-bottom:4px">
          <label class="form-label">&nbsp;</label>
          <div class="checkbox-row">
            <input type="checkbox" id="corresponding_IDX" onchange="onFieldChange(IDX,'is_corresponding',this)">
            <label for="corresponding_IDX">This is a corresponding author <span>(optional)</span></label>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">Institutional email <span class="optional-lbl">(optional)</span></label>
          <input type="email" class="form-input" name="inst_email_IDX"
                 placeholder="Please provide an institutional email address here"
                 oninput="onFieldChange(IDX,'institutional_email',this)">
        </div>
      </div>
      <div class="contrib-section">
        <div class="contrib-heading">Author contribution <span class="info-icon">i</span></div>
        <div class="contrib-subtext">Select the areas in which the author contributed</div>
        <div class="field-error contrib-error" id="contribErr_IDX" style="display:none">
          <span class="field-error-icon">!</span> Please select at least one mandatory contribution
        </div>
        <div class="contrib-grid">
          <div class="contrib-group">
            <div class="contrib-group-title">
              <input type="checkbox" id="mandatoryAll_IDX" onchange="toggleMandatoryAll(IDX,this)" style="accent-color:var(--primary);width:14px;height:14px">
              <label for="mandatoryAll_IDX" style="cursor:pointer;font-size:12px;font-weight:700">Mandatory contribution</label>
            </div>
            <div class="contrib-checkbox-wrap">
              <label class="contrib-checkbox"><input type="checkbox" id="credit_writing_original_draft_IDX" onchange="onContribChange(IDX)"> Writing – original draft</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_writing_review_editing_IDX" onchange="onContribChange(IDX)"> Writing – review &amp; editing</label>
            </div>
          </div>
          <div class="contrib-additional">
            <div class="contrib-additional-title">
              <input type="checkbox" id="additionalAll_IDX" onchange="toggleAdditionalAll(IDX,this)" style="accent-color:var(--primary);width:14px;height:14px">
              <label for="additionalAll_IDX" style="cursor:pointer;font-size:12px;font-weight:700">Additional contribution <span style="font-weight:400;color:var(--text-muted)">(Optional)</span></label>
            </div>
            <div class="contrib-extra-grid">
              <label class="contrib-checkbox"><input type="checkbox" id="credit_conceptualization_IDX" onchange="onContribChange(IDX)"> Conceptualization</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_data_curation_IDX" onchange="onContribChange(IDX)"> Data curation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_formal_analysis_IDX" onchange="onContribChange(IDX)"> Formal Analysis</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_funding_acquisition_IDX" onchange="onContribChange(IDX)"> Funding acquisition</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_investigation_IDX" onchange="onContribChange(IDX)"> Investigation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_methodology_IDX" onchange="onContribChange(IDX)"> Methodology</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_project_administration_IDX" onchange="onContribChange(IDX)"> Project administration</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_resources_IDX" onchange="onContribChange(IDX)"> Resources</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_software_IDX" onchange="onContribChange(IDX)"> Software</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_supervision_IDX" onchange="onContribChange(IDX)"> Supervision</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_validation_IDX" onchange="onContribChange(IDX)"> Validation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_visualization_IDX" onchange="onContribChange(IDX)"> Visualization</label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* ════════════════════════════════════════════════════════════
   STATE
════════════════════════════════════════════════════════════ */
const SUBMISSION_ID = <?= $submission_id ?>;
const ORDINALS = ['1st','2nd','3rd','4th','5th','6th','7th','8th'];

// Build initial author data from PHP
let authorData = <?= json_encode(array_values(array_map(function($a) {
    return [
        'author_id'          => (int)$a['author_id'],
        'email'              => $a['email'] ?? '',
        'title'              => $a['title'] ?? '',
        'first_name'         => $a['first_name'] ?? '',
        'middle_name'        => $a['middle_name'] ?? '',
        'last_name'          => $a['last_name'] ?? '',
        'phone_country_code' => $a['phone_country_code'] ?? '+91',
        'phone_number'       => $a['phone_number'] ?? '',
        'institutional_email'=> $a['institutional_email'] ?? '',
        'affiliation_id'     => (int)($a['affiliation_id'] ?? 0),
        'affil_name'         => $a['affil_name'] ?? '',
        'affil_city'         => $a['affil_city'] ?? '',
        'affil_country'      => $a['affil_country'] ?? '',
        'is_corresponding'   => (int)($a['is_corresponding'] ?? 0),
    ];
}, $authors))) ?>;

let autoSaveTimer = null;

/* ════════════════════════════════════════════════════════════
   SECTION TOGGLE
════════════════════════════════════════════════════════════ */
function toggleSection() {
    const body = document.getElementById('sectionBody');
    const icon = document.getElementById('collapseIcon');
    const visible = body.style.display !== 'none';
    body.style.display = visible ? 'none' : 'block';
    icon.classList.toggle('open', !visible);
}

/* ════════════════════════════════════════════════════════════
   FIELD CHANGE
════════════════════════════════════════════════════════════ */
function onFieldChange(idx, field, el) {
    if (!authorData[idx]) return;
    const val = el.type === 'checkbox' ? (el.checked ? 1 : 0) : el.value;
    authorData[idx][field] = val;
    scheduleAutoSave();
}

/* ════════════════════════════════════════════════════════════
   VALIDATION
════════════════════════════════════════════════════════════ */
function validateEmail(idx) {
    const el  = document.querySelector(`[name="email_${idx}"]`);
    const err = document.getElementById(`emailErr_${idx}`);
    if (!el || !err) return true;
    const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(el.value.trim());
    el.classList.toggle('has-error', !valid && el.value.length > 0);
    err.style.display = (!valid && el.value.length > 0) ? 'flex' : 'none';
    return valid;
}

function validateRequired(idx, field) {
    const el  = document.querySelector(`[name="${field}_${idx}"]`);
    const errId = field === 'first_name' ? `firstNameErr_${idx}` : `lastNameErr_${idx}`;
    const err = document.getElementById(errId);
    if (!el || !err) return true;
    const valid = el.value.trim().length > 0;
    el.classList.toggle('has-error', !valid);
    err.style.display = !valid ? 'flex' : 'none';
    return valid;
}

function validateAffil(idx) {
    const tags  = document.getElementById(`affilTags_${idx}`);
    const err   = document.getElementById(`affilErr_${idx}`);
    const hasTags = tags && tags.querySelectorAll('.affil-tag').length > 0;
    if (err) err.style.display = !hasTags ? 'flex' : 'none';
    return hasTags;
}

function validateContrib(idx) {
    const mandatoryChecks = [
        document.getElementById(`credit_writing_original_draft_${idx}`),
        document.getElementById(`credit_writing_review_editing_${idx}`)
    ];
    const anyChecked = mandatoryChecks.some(c => c && c.checked);
    const err = document.getElementById(`contribErr_${idx}`);
    if (err) err.style.display = !anyChecked ? 'flex' : 'none';
    return anyChecked;
}

function validateAll() {
    let valid = true;
    const count = document.querySelectorAll('.author-card').length;
    for (let i = 0; i < count; i++) {
        if (!validateEmail(i)) valid = false;
        if (!validateRequired(i, 'first_name')) valid = false;
        if (!validateRequired(i, 'last_name')) valid = false;
        if (!validateAffil(i)) valid = false;
        if (!validateContrib(i)) valid = false;
    }
    return valid;
}

/* ════════════════════════════════════════════════════════════
   AFFILIATION SEARCH
════════════════════════════════════════════════════════════ */
let affilTimer = null;

function onAffilSearch(idx, el) {
    clearTimeout(affilTimer);
    const q = el.value.trim();
    if (!q) { hideAffilDropdown(idx); return; }
    affilTimer = setTimeout(() => {
        fetch(`ajax/search_affiliations.php?q=${encodeURIComponent(q)}`)
        .then(r => r.json())
        .then(data => {
            if (data.success) renderAffilDropdown(idx, data.affiliations, q);
        });
    }, 280);
}

function renderAffilDropdown(idx, results, q) {
    const dd = document.getElementById(`affilDrop_${idx}`);
    if (!results.length) {
        dd.innerHTML = `<div class="affil-dropdown-item" style="color:var(--text-muted);cursor:default">No affiliations found for "${escHtml(q)}"</div>`;
    } else {
        dd.innerHTML = results.map(a =>
            `<div class="affil-dropdown-item"
                  onmousedown="aut_selectAffil(${idx},${a.affiliation_id},'${escAttr(a.name)}','${escAttr(a.city||'')}','${aut_escAttr(a.country||'')}')">
               <strong>${escHtml(a.name)}</strong>
               <div class="affil-sub">${escHtml([a.city,a.country].filter(Boolean).join(', '))}</div>
             </div>`
        ).join('');
    }
    dd.style.display = 'block';
}

function hideAffilDropdown(idx) {
    setTimeout(() => {
        const dd = document.getElementById(`affilDrop_${idx}`);
        if (dd) dd.style.display = 'none';
    }, 150);
}

function selectAffil(idx, affilId, name, city, country) {
    // Add tag
    const tagsEl = document.getElementById(`affilTags_${idx}`);
    const labelEl = document.getElementById(`affilTagsLabel_${idx}`);

    if (tagsEl) {
        // Remove existing (single affiliation for now)
        tagsEl.innerHTML = '';
        tagsEl.innerHTML = `
          <div class="affil-tag" data-affil-id="${affilId}">
            <span class="affil-tag-name">${escHtml(name)}${city ? ', ' + escHtml(city) : ''}${country ? ', ' + escHtml(country) : ''}</span>
            <div class="affil-tag-actions">
              <button type="button" class="affil-tag-btn affil-tag-edit" title="Edit">✏</button>
              <button type="button" class="affil-tag-btn affil-tag-del" onclick="removeAffil(${idx},this)" title="Remove">✕</button>
            </div>
          </div>`;
    }

    if (labelEl) labelEl.style.display = 'block';

    // Update state
    if (authorData[idx]) {
        authorData[idx].affiliation_id = affilId;
        authorData[idx].affil_name     = name;
    }

    // Clear search input
    const searchEl = document.getElementById(`affilSearch_${idx}`);
    if (searchEl) searchEl.value = '';
    hideAffilDropdown(idx);
    validateAffil(idx);
    scheduleAutoSave();
}

function removeAffil(idx, btn) {
    const tag = btn.closest('.affil-tag');
    if (tag) tag.remove();
    if (authorData[idx]) authorData[idx].affiliation_id = 0;
    validateAffil(idx);
    scheduleAutoSave();
}

/* ════════════════════════════════════════════════════════════
   CONTRIBUTIONS
════════════════════════════════════════════════════════════ */
function onContribChange(idx) {
    validateContrib(idx);
    // Sync "mandatory all" master checkbox
    const m1 = document.getElementById(`credit_writing_original_draft_${idx}`);
    const m2 = document.getElementById(`credit_writing_review_editing_${idx}`);
    const master = document.getElementById(`mandatoryAll_${idx}`);
    if (master && m1 && m2) {
        master.checked = m1.checked && m2.checked;
        master.indeterminate = (m1.checked || m2.checked) && !(m1.checked && m2.checked);
    }
    scheduleAutoSave();
}

function toggleMandatoryAll(idx, master) {
    ['writing_original_draft','writing_review_editing'].forEach(k => {
        const el = document.getElementById(`credit_${k}_${idx}`);
        if (el) el.checked = master.checked;
    });
    validateContrib(idx);
    scheduleAutoSave();
}

function toggleAdditionalAll(idx, master) {
    ['conceptualization','data_curation','formal_analysis','funding_acquisition',
     'investigation','methodology','project_administration','resources',
     'software','supervision','validation','visualization'].forEach(k => {
        const el = document.getElementById(`credit_${k}_${idx}`);
        if (el) el.checked = master.checked;
    });
    scheduleAutoSave();
}

/* ════════════════════════════════════════════════════════════
   ADD / REMOVE / REORDER AUTHORS
════════════════════════════════════════════════════════════ */
function addAuthor() {
    const idx = authorData.length;
    const ord = ORDINALS[idx] || (idx+1)+'th';

    // Clone template
    const tmpl   = document.getElementById('authorTemplate');
    let   html   = tmpl.innerHTML;
    html = html.replaceAll('IDX', idx).replaceAll('ORD', ord);

    const container = document.getElementById('authorsContainer');
    const temp = document.createElement('div');
    temp.innerHTML = html;
    container.appendChild(temp.firstElementChild);

    // Push empty data
    authorData.push({
        author_id:0, email:'', title:'', first_name:'', middle_name:'',
        last_name:'', phone_country_code:'+91', phone_number:'',
        institutional_email:'', affiliation_id:0, affil_name:'',
        is_corresponding:0
    });

    refreshAuthorButtons();
    temp.firstElementChild?.scrollIntoView({ behavior:'smooth', block:'start' });
}

function removeAuthor(idx) {
    if (idx === 0) return; // Cannot remove 1st author
    if (!confirm('Remove this author?')) return;

    const card = document.getElementById(`authorCard_${idx}`);
    if (card) card.remove();
    authorData.splice(idx, 1);

    // Re-index remaining cards
    rebuildAuthorIndices();
    scheduleAutoSave();
}

function moveAuthor(idx, dir) {
    const swapIdx = dir === 'up' ? idx - 1 : idx + 1;
    if (swapIdx < 0 || swapIdx >= authorData.length) return;

    // Swap data
    [authorData[idx], authorData[swapIdx]] = [authorData[swapIdx], authorData[idx]];

    // Re-render all cards
    rebuildAuthorIndices();
    scheduleAutoSave();
}

function rebuildAuthorIndices() {
    const container = document.getElementById('authorsContainer');
    const cards = Array.from(container.querySelectorAll('.author-card'));
    cards.forEach((card, i) => {
        const ord = ORDINALS[i] || (i+1)+'th';
        const lbl = card.querySelector('.author-label');
        if (lbl) lbl.textContent = ord + ' Author';
    });
    refreshAuthorButtons();
}

function refreshAuthorButtons() {
    const cards = Array.from(document.querySelectorAll('.author-card'));
    cards.forEach((card, i) => {
        const btns = card.querySelectorAll('.author-action-btn');
        if (btns[0]) btns[0].disabled = i === 0;                  // Move up
        if (btns[1]) btns[1].disabled = i === cards.length - 1;  // Move down
    });
}

/* ════════════════════════════════════════════════════════════
   COLLECT & SAVE
════════════════════════════════════════════════════════════ */
function collectAuthorsPayload() {
    const cards = Array.from(document.querySelectorAll('.author-card'));
    return cards.map((card, i) => {
        const get = (sel) => (card.querySelector(sel)?.value ?? '');
        const checked = (id) => card.querySelector(`#${id}`)?.checked || false;

        const creditFields = [
            'writing_original_draft','writing_review_editing',
            'conceptualization','data_curation','formal_analysis','funding_acquisition',
            'investigation','methodology','project_administration','resources',
            'software','supervision','validation','visualization'
        ];

        const contrib = {};
        creditFields.forEach(k => {
            contrib[k] = card.querySelector(`[id^="credit_${k}_"]`)?.checked ? 1 : 0;
        });

        const affilTag = card.querySelector('.affil-tag');

        return {
            author_id      : (authorData[i]?.author_id) || 0,
            author_order   : i + 1,
            email          : get(`[name="email_${i}"]`) || get('[name^="email_"]'),
            title          : get(`[name="title_${i}"]`) || get('[name^="title_"]') || '',
            first_name     : get(`[name="first_name_${i}"]`) || get('[name^="first_name_"]'),
            middle_name    : get(`[name="middle_name_${i}"]`) || '',
            last_name      : get(`[name="last_name_${i}"]`) || '',
            phone_country_code: get(`[name="phone_code_${i}"]`) || '+91',
            phone_number   : get(`[name="phone_${i}"]`) || '',
            institutional_email: get(`[name="inst_email_${i}"]`) || '',
            affiliation_id : affilTag ? parseInt(affilTag.dataset.affilId) || 0 : 0,
            is_corresponding: card.querySelector(`[id^="corresponding_"]`)?.checked ? 1 : 0,
            contributions  : contrib,
        };
    });
}

function scheduleAutoSave() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => saveAuthorsSilent(), 1800);
}

function saveAuthorsSilent() {
    const fd = new FormData();
    fd.append('submission_id', SUBMISSION_ID);
    fd.append('authors', JSON.stringify(collectAuthorsPayload()));
    fetch('ajax/save_authors.php', { method:'POST', body:fd })
    .then(r => r.json())
    .then(d => {
        if (d.success) showSaveIndicator();
    })
    .catch(e => console.error('saveAuthorsSilent:', e));
}

function saveAuthors(andContinue = false) {
    const btn = andContinue
        ? document.getElementById('saveContinueBtn')
        : document.getElementById('saveBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Saving...';

    const fd = new FormData();
    fd.append('submission_id', SUBMISSION_ID);
    fd.append('authors', JSON.stringify(collectAuthorsPayload()));

    fetch('ajax/save_authors.php', { method:'POST', body:fd })
    .then(r => r.json())
    .then(d => {
        btn.disabled = false;
        btn.innerHTML = andContinue ? 'Save &amp; Continue →' : '💾 Save';
        if (d.success) {
            showToast('Authors saved!', 'success');
            if (andContinue) {
                setTimeout(() => window.location.href = `editorial.php?id=${SUBMISSION_ID}`, 800);
            }
        } else {
            showToast(d.message || 'Save failed', 'error');
        }
    })
    .catch(() => {
        btn.disabled = false;
        btn.innerHTML = andContinue ? 'Save &amp; Continue →' : '💾 Save';
        showToast('Network error', 'error');
    });
}

/* ════════════════════════════════════════════════════════════
   SECTION BADGE
════════════════════════════════════════════════════════════ */
function updateSectionBadge() {
    const cards = document.querySelectorAll('.author-card').length;
    const badge = document.getElementById('sectionBadge');
    // Simple check: all have first/last name
    let complete = cards > 0;
    document.querySelectorAll('.author-card').forEach((card, i) => {
        const fn = card.querySelector(`[name^="first_name_"]`)?.value.trim();
        const ln = card.querySelector(`[name^="last_name_"]`)?.value.trim();
        if (!fn || !ln) complete = false;
    });
    if (complete) {
        badge.className = 'section-badge-complete';
        badge.innerHTML = '<span style="font-size:14px">●</span> Completed';
    } else {
        badge.className = 'section-badge-incomplete';
        badge.innerHTML = '<span style="font-size:14px">●</span> Incomplete';
    }
}

/* ════════════════════════════════════════════════════════════
   UTILS
════════════════════════════════════════════════════════════ */
function showSaveIndicator() {
    // Small visual cue (can add element if needed)
}

function showToast(msg, type = 'info') {
    const c = document.getElementById('toastContainer');
    const t = document.createElement('div');
    t.className = 'toast toast-' + type;
    const icons = { success:'✅', error:'❌', info:'ℹ️' };
    t.innerHTML = `<span>${icons[type]||''}</span> ${escHtml(msg)}`;
    c.appendChild(t);
    setTimeout(() => t.remove(), 3200);
}

function escHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function escAttr(s) {
    return String(s).replace(/'/g,"\\'").replace(/"/g,'&quot;');
}

// Init
refreshAuthorButtons();
</script>
</div>