<?php
// ============================================================
//  editorial.php
//  • Inline AJAX: save_affiliation, search_affiliations, save_editorial
//  • Preferred handling editor section: HIDDEN (future feature)
//  • Reviewer affiliation typeahead + "Add new" inline
//  • Move up / Move down / Delete per reviewer block
// ============================================================
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  = 'Editorial';
$activePage = 'submission';

// ── INLINE AJAX: Save new affiliation ────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'save_affiliation') {
    header('Content-Type: application/json');
    try {
        db()->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
        $name    = trim($_POST['name']       ?? '');
        $dept    = trim($_POST['department'] ?? '');
        $city    = trim($_POST['city']       ?? '');
        $country = trim($_POST['country']    ?? '');
        if (!$name) { echo json_encode(['success'=>false,'message'=>'Institution name is required.']); exit; }
        $chk = db()->prepare(
            "SELECT affiliation_id FROM affiliations
             WHERE CONVERT(name USING utf8mb4) = CONVERT(? USING utf8mb4)
             AND (CONVERT(COALESCE(city,'') USING utf8mb4) = CONVERT(? USING utf8mb4) OR (city IS NULL AND ? = ''))"
        );
        $chk->execute([$name, $city, $city]);
        if ($existing = $chk->fetch()) {
            echo json_encode(['success'=>true,'affiliation_id'=>(int)$existing['affiliation_id'],'name'=>$name,'duplicate'=>true]); exit;
        }
        $ins = db()->prepare("INSERT INTO affiliations (name, department, city, country) VALUES (?, ?, ?, ?)");
        $ins->execute([$name, $dept?:null, $city?:null, $country?:null]);
        echo json_encode(['success'=>true,'affiliation_id'=>(int)db()->lastInsertId(),'name'=>$name]);
    } catch (Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

// ── INLINE AJAX: Search affiliations ─────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'search_affiliations') {
    header('Content-Type: application/json');
    try {
        db()->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
        $q = trim($_GET['q'] ?? '');
        if (strlen($q) < 2) { echo json_encode(['results'=>[]]); exit; }
        $stmt = db()->prepare(
            "SELECT affiliation_id, name, department, city, state, country, is_institutional_partner
             FROM affiliations
             WHERE CONVERT(name USING utf8mb4) LIKE CONVERT(? USING utf8mb4)
                OR CONVERT(city USING utf8mb4) LIKE CONVERT(? USING utf8mb4)
             ORDER BY is_institutional_partner DESC, name ASC LIMIT 10"
        );
        $like = '%'.$q.'%';
        $stmt->execute([$like, $like]);
        echo json_encode(['results'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    } catch (Exception $e) { echo json_encode(['results'=>[],'error'=>$e->getMessage()]); }
    exit;
}

// ── INLINE AJAX: Save editorial ──────────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'save_editorial') {
    header('Content-Type: application/json');
    try {
        $sid_ajax = (int)($_POST['submission_id'] ?? 0);
        if (!$sid_ajax) { echo json_encode(['success'=>false,'message'=>'Missing submission_id']); exit; }
        $data = json_decode($_POST['data'] ?? '{}', true);
        if (!$data) { echo json_encode(['success'=>false,'message'=>'Invalid data']); exit; }
        db()->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
        $prefIds  = $data['preferred_editor_ids'] ?? [];
        $prefJson = json_encode(array_values(array_filter($prefIds)));
        $chk = db()->prepare("SELECT editorial_id FROM submission_editorial WHERE submission_id=?");
        $chk->execute([$sid_ajax]);
        if ($chk->fetch()) {
            db()->prepare("UPDATE submission_editorial SET preferred_editor_ids=?, updated_at=NOW() WHERE submission_id=?")->execute([$prefJson, $sid_ajax]);
        } else {
            db()->prepare("INSERT INTO submission_editorial (submission_id, preferred_editor_ids, created_at, updated_at) VALUES (?,?,NOW(),NOW())")->execute([$sid_ajax, $prefJson]);
        }
        $sugEditors = $data['suggested_editors'] ?? [];
        db()->prepare("DELETE FROM suggested_editors WHERE submission_id=?")->execute([$sid_ajax]);
        if ($sugEditors) {
            $ins = db()->prepare("INSERT INTO suggested_editors (submission_id, editor_id, name, institution, expertise, display_order) VALUES (?,?,?,?,?,?)");
            foreach ($sugEditors as $se) $ins->execute([$sid_ajax,(int)($se['editor_id']??0),$se['name']??'',$se['institution']??'',$se['expertise']??'',(int)($se['display_order']??1)]);
        }
        $reviewers = $data['reviewers'] ?? [];
        db()->prepare("DELETE FROM suggested_reviewers WHERE submission_id=?")->execute([$sid_ajax]);
        if ($reviewers) {
            $ins = db()->prepare("INSERT INTO suggested_reviewers (submission_id, reviewer_type, email, title, first_name, middle_name, last_name, affiliation_id, affiliation_name, department, additional_comment, display_order) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
            foreach ($reviewers as $rv) {
                $hasData = !empty($rv['first_name'])||!empty($rv['last_name'])||!empty($rv['email']);
                if (!$hasData) continue;
                $ins->execute([$sid_ajax, in_array($rv['reviewer_type']??'',['recommended','excluded'])?$rv['reviewer_type']:'recommended', $rv['email']??'',$rv['title']??'',$rv['first_name']??'',$rv['middle_name']??'',$rv['last_name']??'',(int)($rv['affiliation_id']??0)?:null,$rv['affiliation_name']??'',$rv['department']??'',$rv['additional_comment']??'',(int)($rv['display_order']??1)]);
            }
        }
        echo json_encode(['success'=>true]);
    } catch (Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

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

// Load submission
$stmt = db()->prepare(
    "SELECT s.*, j.name AS journal_name, at.name AS article_type_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 = ?"
);
$stmt->execute([$sid, $user_id]);
$sub = $stmt->fetch();
if (!$sub) { header('Location: submission.php'); exit; }

try { $allEditors = db()->query("SELECT * FROM editors WHERE is_active=1 ORDER BY is_editorial_board DESC, name ASC")->fetchAll(PDO::FETCH_ASSOC); }
catch (PDOException $e) { $allEditors = []; }

try { $stmt = db()->prepare("SELECT * FROM submission_editorial WHERE submission_id=?"); $stmt->execute([$sid]); $editorial = $stmt->fetch() ?: []; }
catch (PDOException $e) { $editorial = []; }

$preferredIds = !empty($editorial['preferred_editor_ids']) ? (json_decode($editorial['preferred_editor_ids'], true) ?: []) : array_slice(array_column($allEditors,'editor_id'),0,6);
$edMap = []; foreach ($allEditors as $e) $edMap[(int)$e['editor_id']] = $e;
$preferredEditors = array_filter(array_map(fn($id) => $edMap[(int)$id] ?? null, $preferredIds));

try {
    $stmt = db()->prepare("SELECT * FROM suggested_reviewers WHERE submission_id=? ORDER BY reviewer_type, display_order ASC");
    $stmt->execute([$sid]); $allRv = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $allRv = []; }

$recRv  = array_values(array_filter($allRv, fn($r) => in_array($r['reviewer_type']??'', ['recommended',''])));
$exclRv = array_values(array_filter($allRv, fn($r) => ($r['reviewer_type']??'') === 'excluded'));
if (!$recRv)  $recRv  = [[]];
if (!$exclRv) $exclRv = [[]];

// ── Helper: render reviewer block ────────────────────────────
function rvBlock($type, $idx, $rv, $total) {
    $em  = htmlspecialchars($rv['email']              ?? '');
    $tt  = htmlspecialchars($rv['title']              ?? '');
    $fn  = htmlspecialchars($rv['first_name']         ?? '');
    $mn  = htmlspecialchars($rv['middle_name']        ?? '');
    $ln  = htmlspecialchars($rv['last_name']          ?? '');
    $afN = htmlspecialchars($rv['affiliation_name']   ?? $rv['affiliation'] ?? '');
    $afI = (int)($rv['affiliation_id']                ?? 0);
    $dp  = htmlspecialchars($rv['department']         ?? '');
    $cm  = htmlspecialchars($rv['additional_comment'] ?? '');
    $up  = $idx === 0        ? 'disabled' : '';
    $dn  = $idx === $total-1 ? 'disabled' : '';
    ob_start(); ?>
<li class="reviewer-block">
  <div class="rv-forms">
    <div class="rv-row rv-row-2">
      <div class="rv-field">
        <input type="email" class="rv-input rv-email" placeholder="Start by entering the email address"
               value="<?= $em ?>" oninput="rvDirty(this)" maxlength="150">
        <div class="rv-err"><span class="err-x">⊗</span> Please enter a valid email address</div>
      </div>
      <div class="rv-field">
        <div class="rv-dd" tabindex="0" onkeydown="ddKey(event,this)">
          <div class="rv-dd-face" onclick="toggleDd(this.parentElement)">
            <span class="rv-dd-val"><?= $tt ?></span>
            <span class="rv-dd-ph" style="<?= $tt?'display:none':'' ?>">Title</span>
            <span class="rv-dd-arrow">▾</span>
          </div>
          <ul class="rv-dd-list">
            <?php foreach (['Dr','Prof','Mr','Mrs','Ms','Miss','Mx','Judge','MD','MD, PhD','PhD','DVM','DVM, PhD'] as $t): ?>
            <li class="rv-dd-opt <?= $tt===$t?'sel':'' ?>" onclick="pickTitle(this,'<?= $t ?>')"><?= $t ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
      </div>
    </div>
    <div class="rv-row rv-row-3">
      <div class="rv-field">
        <input type="text" class="rv-input rv-fname" placeholder="First name" value="<?= $fn ?>" oninput="rvDirty(this)" maxlength="150">
        <div class="rv-err"><span class="err-x">⊗</span> Please fill this field to continue</div>
      </div>
      <div class="rv-field">
        <input type="text" class="rv-input rv-mname" placeholder="Middle name (optional)" value="<?= $mn ?>" oninput="rvDirty(this)" maxlength="50">
      </div>
      <div class="rv-field">
        <input type="text" class="rv-input rv-lname" placeholder="Last name" value="<?= $ln ?>" oninput="rvDirty(this)" maxlength="150">
        <div class="rv-err"><span class="err-x">⊗</span> Please fill this field to continue</div>
      </div>
    </div>
    <div class="rv-row rv-row-1">
      <div class="rv-field rv-affil-wrap">
        <div class="affil-input-row">
          <input type="text" class="rv-input rv-affil-text"
                 placeholder="Search university / institution..."
                 value="<?= $afN ?>" autocomplete="off"
                 oninput="onAffilInput(this)" onfocus="onAffilFocus(this)" onblur="onAffilBlur(this)" maxlength="300">
          <button type="button" class="affil-clear" onclick="clearAffil(this)"
                  style="<?= $afN?'':'display:none' ?>" title="Clear">✕</button>
        </div>
        <input type="hidden" class="rv-affil-id" value="<?= $afI ?>">
        <div class="affil-dropdown" style="display:none">
          <div class="affil-tip">Type at least 2 characters to search</div>
          <div class="affil-spinner" style="display:none"><span class="spin"></span> Searching...</div>
          <ul class="affil-list" style="display:none"></ul>
          <div class="affil-addnew-row" onmousedown="openAddAffil(this)">➕ My university is not listed — Add new</div>
        </div>
        <div class="rv-err"><span class="err-x">⊗</span> Please select one affiliation</div>
        <div class="affil-add-form" id="affilAddForm_<?= $type ?>_<?= $idx ?>">
          <div class="affil-add-title">
            <span>🏛 Add new affiliation</span>
            <button type="button" class="affil-add-close" onclick="closeAffilForm(this)">✕</button>
          </div>
          <div class="affil-add-grid">
            <div class="affil-add-full"><label class="affil-add-label">Institution / University Name <span style="color:#DC2626">*</span></label>
              <input type="text" class="affil-add-input affil-new-name" placeholder="e.g. Harvard University"></div>
            <div><label class="affil-add-label">Department <span class="affil-add-opt">(optional)</span></label>
              <input type="text" class="affil-add-input affil-new-dept" placeholder="e.g. Computer Science"></div>
            <div><label class="affil-add-label">City <span class="affil-add-opt">(optional)</span></label>
              <input type="text" class="affil-add-input affil-new-city" placeholder="e.g. Cambridge"></div>
            <div><label class="affil-add-label">Country <span class="affil-add-opt">(optional)</span></label>
              <input type="text" class="affil-add-input affil-new-country" placeholder="e.g. USA"></div>
          </div>
          <div class="affil-add-actions">
            <button type="button" class="affil-btn-cancel" onclick="closeAffilForm(this)">Cancel</button>
            <button type="button" class="affil-btn-save" onclick="saveNewAffilInline(this)">💾 Save &amp; Select</button>
          </div>
        </div>
      </div>
    </div>
    <div class="rv-row rv-row-1">
      <div class="rv-field">
        <input type="text" class="rv-input rv-dept" placeholder="Department (optional)" value="<?= $dp ?>" oninput="rvDirty(this)" maxlength="300">
      </div>
    </div>
    <div class="rv-row rv-row-1">
      <div class="rv-field">
        <textarea class="rv-input rv-comment" placeholder="Additional comment (optional)" oninput="rvDirty(this)" maxlength="2000"><?= $cm ?></textarea>
      </div>
    </div>
  </div>
  <div class="rv-actions">
    <button type="button" class="btn-rv move-up <?= $up ?>" onclick="moveRv(this,true)" <?= $up ?>>Move up</button>
    <button type="button" class="btn-rv move-down <?= $dn ?>" onclick="moveRv(this,false)" <?= $dn ?>>Move down</button>
    <button type="button" class="btn-rv remove-rv" onclick="openConfirm(this)">
      <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
    </button>
  </div>
</li>
    <?php return ob_get_clean();
}

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; --primary-dark: #BF4520; --primary-light: #FFF0EA;
  --error: #D32F2F; --success: #2E7D32;
  --border-f: #1A7F8E;
  --r: 4px;
}

.page-wrap { max-width: 1100px; 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; display: flex; align-items: center; gap: 5px; margin-top: 2px; }

/* Buttons */
.btn { display: inline-flex; align-items: center; gap: 5px; padding: 7px 15px; border-radius: var(--r); font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; border: none; transition: all .15s; white-space: nowrap; }
.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); }
.btn-grey { background: var(--white); border: 1.5px solid #BDBDBD; color: var(--muted); }
.btn-grey:hover { border-color: #999; }
button.btn { font-family: var(--font); }

/* Block top */
.block-top { padding: 20px 26px 0; }
.title-form { font-size: 14px; font-weight: 700; margin-bottom: 10px; display: flex; align-items: center; gap: 8px; }

/* Reviewer columns */
.block-bottom { display: grid; grid-template-columns: 1fr 1fr; border-top: 1px solid #EBEBEB; margin-top: 20px; }
@media(max-width:860px) { .block-bottom { grid-template-columns: 1fr; } }
.col-l { border-right: 1px solid #EBEBEB; padding: 20px 22px; }
.col-r { padding: 20px 22px; }

/* Reviewer block */
.rv-list { list-style: none; display: flex; flex-direction: column; gap: 0; padding: 0; }
.reviewer-block { background: var(--white); border: 1px solid var(--border); border-radius: 4px; margin-bottom: 12px; overflow: visible; }
.rv-forms { padding: 14px 16px; }
.rv-row { display: grid; gap: 10px; margin-bottom: 10px; }
.rv-row-1 { grid-template-columns: 1fr; }
.rv-row-2 { grid-template-columns: 1fr 160px; }
.rv-row-3 { grid-template-columns: 1fr 1fr 1fr; }
@media(max-width:520px) { .rv-row-2,.rv-row-3 { grid-template-columns: 1fr; } }
.rv-field { display: flex; flex-direction: column; gap: 3px; position: relative; }
.rv-input { width: 100%; padding: 8px 11px; border: 1.5px solid #CBD5E1; border-radius: var(--r); font-family: var(--font); font-size: 13px; color: var(--text); background: var(--white); outline: none; transition: border-color .15s; }
.rv-input:focus { border-color: var(--border-f); box-shadow: 0 0 0 3px rgba(26,127,142,.12); }
textarea.rv-input { resize: vertical; min-height: 76px; }
.rv-err { display: none; align-items: center; gap: 5px; font-size: 12px; color: var(--error); margin-top: 3px; }
.rv-err.show { display: flex; }
.err-x { font-size: 14px; color: var(--error); flex-shrink: 0; }

/* Title dropdown */
.rv-dd { position: relative; width: 100%; outline: none; }
.rv-dd-face { display: flex; align-items: center; justify-content: space-between; padding: 8px 11px; border: 1.5px solid #CBD5E1; border-radius: var(--r); cursor: pointer; background: var(--white); gap: 4px; min-height: 36px; }
.rv-dd:focus-within .rv-dd-face, .rv-dd.open .rv-dd-face { border-color: var(--border-f); box-shadow: 0 0 0 3px rgba(26,127,142,.12); }
.rv-dd-val { font-size: 13px; color: var(--text); font-weight: 600; flex: 1; }
.rv-dd-ph  { font-size: 13px; color: #9CA3AF; flex: 1; }
.rv-dd-arrow { font-size: 11px; color: var(--muted); transition: transform .2s; }
.rv-dd.open .rv-dd-arrow { transform: rotate(180deg); }
.rv-dd-list { position: absolute; top: 100%; left: 0; right: 0; background: var(--white); border: 1.5px solid var(--border-f); border-top: none; border-radius: 0 0 var(--r) var(--r); max-height: 220px; overflow-y: auto; z-index: 500; display: none; box-shadow: 0 4px 12px rgba(0,0,0,.12); list-style: none; }
.rv-dd.open .rv-dd-list { display: block; }
.rv-dd-opt { padding: 8px 12px; cursor: pointer; font-size: 13px; border-bottom: 1px solid #F3F4F6; }
.rv-dd-opt:last-child { border-bottom: none; }
.rv-dd-opt:hover { background: var(--teal-lt); color: var(--teal); }
.rv-dd-opt.sel { background: var(--teal-lt); color: var(--teal); font-weight: 700; }

/* Affiliation typeahead */
.rv-affil-wrap { position: relative; }
.affil-input-row { position: relative; display: flex; align-items: center; }
.affil-input-row .rv-input { padding-right: 30px; }
.affil-clear { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); border: none; background: none; font-size: 14px; cursor: pointer; color: #9CA3AF; line-height: 1; padding: 2px; transition: color .15s; }
.affil-clear:hover { color: var(--error); }
.affil-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: var(--white); border: 1.5px solid var(--border-f); border-top: none; border-radius: 0 0 var(--r) var(--r); z-index: 500; box-shadow: 0 6px 18px rgba(0,0,0,.14); max-height: 240px; overflow-y: auto; }
.affil-tip { padding: 9px 13px; font-size: 12px; color: var(--muted); font-style: italic; }
.affil-spinner { padding: 9px 13px; font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 7px; }
.affil-list { list-style: none; padding: 0; }
.affil-item { padding: 9px 13px; cursor: pointer; border-bottom: 1px solid #F3F4F6; transition: background .1s; }
.affil-item:last-child { border-bottom: none; }
.affil-item:hover { background: var(--teal-lt); }
.affil-item-name { font-size: 13px; font-weight: 600; color: var(--text); }
.affil-item-sub  { font-size: 11.5px; color: var(--muted); margin-top: 1px; }
.affil-partner   { display: inline-flex; align-items: center; gap: 3px; font-size: 10.5px; font-weight: 600; padding: 1px 6px; border-radius: 10px; background: var(--teal-lt); color: var(--teal); margin-left: 6px; }
.affil-addnew-row { padding: 9px 14px; font-size: 13px; font-weight: 600; color: var(--primary); cursor: pointer; display: flex; align-items: center; gap: 6px; border-top: 1.5px dashed #FDDCCC; background: #FFF8F5; transition: background .15s; position: sticky; bottom: 0; }
.affil-addnew-row:hover { background: var(--primary-light); }

/* Inline add-new affiliation form */
.affil-add-form { display: none; margin-top: 10px; background: #F0F9FF; border: 1.5px solid #BFDBFE; border-radius: 8px; padding: 14px 16px; }
.affil-add-form.open { display: block; animation: fadeIn .2s ease; }
@keyframes fadeIn { from{opacity:0;transform:translateY(-4px)} to{opacity:1;transform:translateY(0)} }
.affil-add-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.affil-add-title span { font-size: 13px; font-weight: 700; color: #1D4ED8; }
.affil-add-close { background: none; border: none; cursor: pointer; color: var(--muted); font-size: 18px; line-height: 1; padding: 0; }
.affil-add-close:hover { color: var(--error); }
.affil-add-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px; }
.affil-add-full { grid-column: 1/-1; }
.affil-add-label { display: block; font-size: 11.5px; font-weight: 600; color: var(--text); margin-bottom: 3px; }
.affil-add-opt { font-weight: 400; color: var(--muted); }
.affil-add-input { width: 100%; padding: 7px 10px; border: 1.5px solid #BFDBFE; border-radius: 5px; font-family: var(--font); font-size: 12.5px; color: var(--text); outline: none; background: var(--white); }
.affil-add-input:focus { border-color: var(--primary); box-shadow: 0 0 0 2px rgba(224,90,43,.10); }
.affil-add-input.inp-error { border-color: var(--error); }
.affil-add-actions { display: flex; gap: 8px; justify-content: flex-end; }
.affil-btn-cancel { padding: 6px 13px; border-radius: 5px; background: var(--white); color: var(--muted); border: 1.5px solid var(--border); font-size: 12.5px; font-weight: 600; cursor: pointer; font-family: var(--font); }
.affil-btn-cancel:hover { border-color: var(--teal); color: var(--teal); }
.affil-btn-save { padding: 6px 14px; border-radius: 5px; background: var(--primary); color: #fff; border: none; font-size: 12.5px; font-weight: 600; cursor: pointer; font-family: var(--font); display: flex; align-items: center; gap: 5px; }
.affil-btn-save:hover { background: var(--primary-dark); }
.affil-btn-save:disabled { opacity: .6; cursor: not-allowed; }

/* Reviewer actions */
.rv-actions { display: flex; align-items: center; justify-content: flex-end; gap: 6px; padding: 8px 12px; background: #F9FAFB; border-top: 1px solid var(--border); }
.btn-rv { display: inline-flex; align-items: center; gap: 4px; padding: 5px 12px; border: 1.5px solid var(--border); border-radius: var(--r); background: var(--white); font-size: 12px; font-weight: 600; color: var(--teal); cursor: pointer; font-family: var(--font); transition: all .15s; }
.btn-rv:hover:not([disabled]):not(.disabled) { border-color: var(--teal); background: var(--teal-lt); }
.btn-rv[disabled], .btn-rv.disabled { color: var(--muted); opacity: .4; cursor: not-allowed; }
.btn-rv.remove-rv { color: var(--muted); border-color: var(--border); }
.btn-rv.remove-rv:hover { border-color: var(--error); color: var(--error); background: #FFEBEE; }

/* Add reviewer row */
.add-row { display: flex; align-items: center; gap: 0; margin-top: 4px; }
.add-row .line { flex: 1; height: 1px; background: var(--border); }
.btn-add-rv { margin: 0 10px !important; padding: 7px 15px !important; font-size: 13px !important; }

/* Nav row */
.tile-nav { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; border-top: 1px solid #EBEBEB; background: var(--white); }
.tile-nav .right { 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-quality { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.btm-actions { display: flex; gap: 10px; }

/* Confirm popup */
.confirm-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.4); z-index: 700; display: flex; align-items: center; justify-content: center; }
.confirm-overlay.hidden { display: none; }
.confirm-box { background: var(--white); border-radius: 6px; padding: 24px 28px; max-width: 360px; width: 90%; text-align: center; box-shadow: 0 10px 40px rgba(0,0,0,.2); position: relative; }
.confirm-msg { font-size: 14px; margin-bottom: 18px; }
.confirm-acts { display: flex; justify-content: center; gap: 12px; }
.confirm-x { position: absolute; top: 8px; right: 11px; border: none; background: none; font-size: 18px; cursor: pointer; color: var(--muted); }

/* Toasts */
.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; min-width: 160px; }
.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(0,0,0,.15); border-top-color: var(--teal); border-radius: 50%; animation: spinning .6s linear infinite; flex-shrink: 0; }
@keyframes spinning { 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="authors.php?id=<?= $sid ?>">Authors &amp; Contributors</a>
    <span>›</span>
    <span>Editorial</span>
  </div>

  <!-- ═══ EDITORIAL TILE ════════════════════════════════════ -->
  <div class="tile" id="editorialTile">

    <div class="tile-trigger" onclick="toggleTile()">
      <div>
        <div class="tile-name">Editorial</div>
        <div class="tile-status"><span>⊗</span> Incomplete</div>
      </div>
      <span style="font-size:16px;color:#888" id="tileChev">∧</span>
    </div>

    <div id="tileContent">

      <!-- PREFERRED HANDLING EDITOR — HIDDEN (future feature) -->
      <div id="preferredEditorSection" style="display:none">
        <div class="block-top">
          <div class="title-form">Preferred handling editor</div>
          <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:14px">
            <div style="font-size:13px;color:var(--muted);line-height:1.7;flex:1">
              Please select your preferred handling editor. We have pre-selected the top handling editor recommended for your manuscript.
            </div>
            <button type="button" class="btn btn-outline" onclick="openModal()">
              <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor"><path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"/></svg>
              Change
            </button>
          </div>
          <div id="editorGrid" style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px">
            <?php foreach (array_slice($preferredEditors,0,6) as $e): ?>
            <div style="border:1px solid var(--border);border-radius:4px;padding:14px;background:var(--white)" data-eid="<?= $e['editor_id'] ?>">
              <div style="display:flex;gap:12px;align-items:flex-start;margin-bottom:10px">
                <div style="width:50px;height:50px;border-radius:50%;background:#D1D5DB;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:18px;color:#6B7280;flex-shrink:0">
                  <?= strtoupper(substr($e['name'],0,1)) ?>
                </div>
                <div>
                  <div style="font-size:14px;font-weight:700"><?= htmlspecialchars($e['name']) ?></div>
                  <div style="font-size:12px;color:var(--muted)"><?= htmlspecialchars(implode(', ',array_filter([$e['university']??'',$e['city']??'',$e['country']??'']))) ?></div>
                </div>
              </div>
              <span style="font-size:12px;font-weight:700;color:var(--teal);text-transform:uppercase">VIEW PROFILE</span>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

      <!-- REVIEWER COLUMNS -->
      <div class="block-bottom" style="border-top:none;margin-top:0">

        <div class="col-l" id="divSuggestedRe">
          <div class="title-form">
            Recommend reviewers <span style="font-weight:400;color:var(--muted)">(optional)</span>
            <span style="display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;border-radius:50%;background:#E5E7EB;color:#777;font-size:9px;font-weight:700;cursor:default" title="You may suggest potential reviewers">i</span>
          </div>
          <fieldset>
            <ul class="rv-list" id="recList">
              <?php foreach ($recRv as $i => $rv) echo rvBlock('rec', $i, $rv, count($recRv)); ?>
            </ul>
          </fieldset>
          <fieldset>
            <div class="add-row">
              <div class="line"></div>
              <button type="button" class="btn btn-outline btn-add-rv" onclick="addRv('rec')">
                <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor"><path d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"/></svg>
                Suggest another reviewer
              </button>
              <div class="line"></div>
            </div>
          </fieldset>
        </div>

        <div class="col-r" id="divExcludedRe">
          <div class="title-form">
            Suggest reviewers to exclude <span style="font-weight:400;color:var(--muted)">(optional)</span>
            <span style="display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;border-radius:50%;background:#E5E7EB;color:#777;font-size:9px;font-weight:700;cursor:default" title="Recommend excluding certain reviewers">i</span>
          </div>
          <fieldset>
            <ul class="rv-list" id="exclList">
              <?php foreach ($exclRv as $i => $rv) echo rvBlock('excl', $i, $rv, count($exclRv)); ?>
            </ul>
          </fieldset>
          <fieldset>
            <div class="add-row">
              <div class="line"></div>
              <button type="button" class="btn btn-outline btn-add-rv" onclick="addRv('excl')">
                <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor"><path d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"/></svg>
                Exclude reviewers
              </button>
              <div class="line"></div>
            </div>
          </fieldset>
        </div>

      </div><!-- /block-bottom -->

      <div style="text-align:right;padding:8px 22px;font-size:12.5px;border-top:1px solid #EBEBEB">
        <a href="https://communeglobal.com/journals/social-science/author-style-guidelines"
           target="_blank" rel="noopener">Author guidelines ↗</a>
      </div>

      <div class="tile-nav">
        <a href="authors.php?id=<?= $sid ?>" class="btn btn-outline">← Previous</a>
        <div class="right">
          <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 -->

<!-- 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-quality">
    Submission quality: <strong>90%</strong>
    <span style="font-size:11.5px;color:var(--muted)">ℹ 1 suggested action</span>
  </div>
  <div class="btm-actions">
    <button class="btn btn-outline">Preview</button>
    <button class="btn btn-fill">🔵 Submit</button>
  </div>
</div>

<!-- Confirm remove popup -->
<div class="confirm-overlay hidden" id="confirmOverlay">
  <div class="confirm-box">
    <button class="confirm-x" onclick="closeConfirm()">✕</button>
    <div class="confirm-msg">Are you sure you want to remove this reviewer?</div>
    <div class="confirm-acts">
      <button type="button" class="btn btn-grey" onclick="closeConfirm()">Cancel</button>
      <button type="button" class="btn btn-fill" onclick="doRemove()">Remove</button>
    </div>
  </div>
</div>

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

<!-- Reviewer template for dynamic add -->
<template id="tmplRv">
<li class="reviewer-block">
  <div class="rv-forms">
    <div class="rv-row rv-row-2">
      <div class="rv-field">
        <input type="email" class="rv-input rv-email" placeholder="Start by entering the email address" oninput="rvDirty(this)" maxlength="150">
        <div class="rv-err" style="display:none"><span class="err-x">⊗</span> Please enter a valid email address</div>
      </div>
      <div class="rv-field">
        <div class="rv-dd" tabindex="0" onkeydown="ddKey(event,this)">
          <div class="rv-dd-face" onclick="toggleDd(this.parentElement)">
            <span class="rv-dd-val"></span><span class="rv-dd-ph">Title</span><span class="rv-dd-arrow">▾</span>
          </div>
          <ul class="rv-dd-list">
            <li class="rv-dd-opt" onclick="pickTitle(this,'Dr')">Dr</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Prof')">Prof</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Mr')">Mr</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Mrs')">Mrs</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Ms')">Ms</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Miss')">Miss</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Mx')">Mx</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'Judge')">Judge</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'MD')">MD</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'MD, PhD')">MD, PhD</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'PhD')">PhD</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'DVM')">DVM</li>
            <li class="rv-dd-opt" onclick="pickTitle(this,'DVM, PhD')">DVM, PhD</li>
          </ul>
        </div>
      </div>
    </div>
    <div class="rv-row rv-row-3">
      <div class="rv-field"><input type="text" class="rv-input rv-fname" placeholder="First name" oninput="rvDirty(this)" maxlength="150"><div class="rv-err" style="display:none"><span class="err-x">⊗</span> Please fill this field to continue</div></div>
      <div class="rv-field"><input type="text" class="rv-input rv-mname" placeholder="Middle name (optional)" oninput="rvDirty(this)" maxlength="50"></div>
      <div class="rv-field"><input type="text" class="rv-input rv-lname" placeholder="Last name" oninput="rvDirty(this)" maxlength="150"><div class="rv-err" style="display:none"><span class="err-x">⊗</span> Please fill this field to continue</div></div>
    </div>
    <div class="rv-row rv-row-1">
      <div class="rv-field rv-affil-wrap">
        <div class="affil-input-row">
          <input type="text" class="rv-input rv-affil-text" placeholder="Search university / institution..."
                 autocomplete="off" oninput="onAffilInput(this)" onfocus="onAffilFocus(this)" onblur="onAffilBlur(this)" maxlength="300">
        </div>
        <input type="hidden" class="rv-affil-id" value="">
        <div class="affil-dropdown" style="display:none">
          <div class="affil-tip">Type at least 2 characters to search</div>
          <div class="affil-spinner" style="display:none"><span class="spin"></span> Searching...</div>
          <ul class="affil-list" style="display:none"></ul>
          <div class="affil-addnew-row" onmousedown="openAddAffil(this)">➕ My university is not listed — Add new</div>
        </div>
        <div class="rv-err" style="display:none"><span class="err-x">⊗</span> Please select one affiliation</div>
        <div class="affil-add-form">
          <div class="affil-add-title"><span>🏛 Add new affiliation</span><button type="button" class="affil-add-close" onclick="closeAffilForm(this)">✕</button></div>
          <div class="affil-add-grid">
            <div class="affil-add-full"><label class="affil-add-label">Institution / University Name <span style="color:#DC2626">*</span></label><input type="text" class="affil-add-input affil-new-name" placeholder="e.g. Harvard University"></div>
            <div><label class="affil-add-label">Department <span class="affil-add-opt">(optional)</span></label><input type="text" class="affil-add-input affil-new-dept" placeholder="e.g. Computer Science"></div>
            <div><label class="affil-add-label">City <span class="affil-add-opt">(optional)</span></label><input type="text" class="affil-add-input affil-new-city" placeholder="e.g. Cambridge"></div>
            <div><label class="affil-add-label">Country <span class="affil-add-opt">(optional)</span></label><input type="text" class="affil-add-input affil-new-country" placeholder="e.g. USA"></div>
          </div>
          <div class="affil-add-actions">
            <button type="button" class="affil-btn-cancel" onclick="closeAffilForm(this)">Cancel</button>
            <button type="button" class="affil-btn-save" onclick="saveNewAffilInline(this)">💾 Save &amp; Select</button>
          </div>
        </div>
      </div>
    </div>
    <div class="rv-row rv-row-1"><div class="rv-field"><input type="text" class="rv-input rv-dept" placeholder="Department (optional)" oninput="rvDirty(this)" maxlength="300"></div></div>
    <div class="rv-row rv-row-1"><div class="rv-field"><textarea class="rv-input rv-comment" placeholder="Additional comment (optional)" oninput="rvDirty(this)" maxlength="2000"></textarea></div></div>
  </div>
  <div class="rv-actions">
    <button type="button" class="btn-rv move-up disabled" onclick="moveRv(this,true)" disabled>Move up</button>
    <button type="button" class="btn-rv move-down" onclick="moveRv(this,false)">Move down</button>
    <button type="button" class="btn-rv remove-rv" onclick="openConfirm(this)">
      <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
    </button>
  </div>
</li>
</template>

<script>
const SID         = <?= $sid ?>;
const ALL_EDITORS = <?= json_encode(array_values($allEditors)) ?>;
let   preferredIds = <?= json_encode(array_values($preferredIds)) ?>;
let   isDirty = false, autoTimer = null;
let   _pendingRemoveBtn = null;
let   _affilTimers = new WeakMap();

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

/* ─── Title dropdown ──────────────────────────────────────── */
function toggleDd(dd){ const wasOpen=dd.classList.contains('open'); closeAllDd(); if(!wasOpen)dd.classList.add('open'); }
function closeAllDd(){ document.querySelectorAll('.rv-dd.open').forEach(d=>d.classList.remove('open')); }
function pickTitle(li,val){
    const dd=li.closest('.rv-dd'); dd.querySelector('.rv-dd-val').textContent=val;
    dd.querySelector('.rv-dd-ph').style.display='none';
    dd.querySelectorAll('.rv-dd-opt').forEach(o=>o.classList.remove('sel')); li.classList.add('sel');
    dd.classList.remove('open'); dirty();
}
function ddKey(e,dd){ if(e.key==='Enter'||e.key===' '){e.preventDefault();toggleDd(dd);} if(e.key==='Escape')dd.classList.remove('open'); }
document.addEventListener('click',e=>{ if(!e.target.closest('.rv-dd'))closeAllDd(); if(!e.target.closest('.rv-affil-wrap'))document.querySelectorAll('.affil-dropdown').forEach(d=>d.style.display='none'); });

/* ─── Affiliation typeahead ───────────────────────────────── */
function onAffilInput(inp){
    const wrap=inp.closest('.rv-affil-wrap'); const drop=wrap.querySelector('.affil-dropdown'); const q=inp.value.trim();
    wrap.querySelector('.rv-affil-id').value='';
    const clr=wrap.querySelector('.affil-clear'); if(clr)clr.style.display=q?'':'none';
    if(q.length<2){drop.style.display='none';return;}
    drop.style.display=''; showAffilState(wrap,'tip');
    clearTimeout(_affilTimers.get(inp));
    _affilTimers.set(inp,setTimeout(()=>searchAffil(inp,q),300)); dirty();
}
function onAffilFocus(inp){ if(inp.value.trim().length>=2)inp.closest('.rv-affil-wrap').querySelector('.affil-dropdown').style.display=''; }
function onAffilBlur(inp){ setTimeout(()=>{ const wrap=inp.closest('.rv-affil-wrap'); if(!wrap.querySelector('.affil-dropdown:hover')&&!wrap.querySelector('.affil-add-form.open'))wrap.querySelector('.affil-dropdown').style.display='none'; },200); }
function showAffilState(wrap,which){
    const tip=wrap.querySelector('.affil-tip'); const spin=wrap.querySelector('.affil-spinner'); const list=wrap.querySelector('.affil-list');
    if(tip) tip.style.display =which==='tip' ?'':'none';
    if(spin)spin.style.display=which==='spin'?'':'none';
    if(list)list.style.display=which==='list'?'':'none';
}
function searchAffil(inp,q){
    const wrap=inp.closest('.rv-affil-wrap'); showAffilState(wrap,'spin');
    fetch('editorial.php?ajax=search_affiliations&q='+encodeURIComponent(q))
    .then(r=>r.json())
    .then(d=>{
        const list=wrap.querySelector('.affil-list'); list.innerHTML='';
        if(!d.results||!d.results.length){ showAffilState(wrap,'tip'); wrap.querySelector('.affil-tip').textContent='No results — use "Add new" below'; return; }
        showAffilState(wrap,'list');
        d.results.forEach(a=>{
            const li=document.createElement('li'); li.className='affil-item';
            const sub=[a.department,a.city,a.country].filter(Boolean).join(', ');
            const badge=a.is_institutional_partner==1?'<span class="affil-partner">✓ Partner</span>':'';
            li.innerHTML=`<div class="affil-item-name">${xe(a.name)}${badge}</div>`+(sub?`<div class="affil-item-sub">${xe(sub)}</div>`:'');
            li.addEventListener('mousedown',e=>{ e.preventDefault(); selectAffilInWrap(wrap,a.affiliation_id,a.name,a.department||''); });
            list.appendChild(li);
        });
    }).catch(()=>showAffilState(wrap,'tip'));
}
function selectAffilInWrap(wrap,id,name,dept){
    const inp=wrap.querySelector('.rv-affil-text'); inp.value=name;
    wrap.querySelector('.rv-affil-id').value=id;
    const deptInp=wrap.closest('.rv-forms')?.querySelector('.rv-dept');
    if(deptInp&&!deptInp.value&&dept)deptInp.value=dept;
    wrap.querySelector('.affil-dropdown').style.display='none';
    const clr=wrap.querySelector('.affil-clear'); if(clr)clr.style.display='';
    const err=wrap.querySelector('.rv-err'); if(err)err.classList.remove('show');
    dirty();
}
function clearAffil(btn){
    const wrap=btn.closest('.rv-affil-wrap');
    wrap.querySelector('.rv-affil-text').value=''; wrap.querySelector('.rv-affil-id').value='';
    wrap.querySelector('.affil-dropdown').style.display='none'; btn.style.display='none'; dirty();
}
function openAddAffil(el){
    const wrap=el.closest('.rv-affil-wrap'); const form=wrap.querySelector('.affil-add-form'); if(!form)return;
    const typed=wrap.querySelector('.rv-affil-text')?.value.trim()||'';
    const nameInp=form.querySelector('.affil-new-name');
    if(nameInp&&!nameInp.value&&typed)nameInp.value=typed;
    wrap.querySelector('.affil-dropdown').style.display='none';
    form.classList.add('open'); setTimeout(()=>nameInp?.focus(),60);
}
function closeAffilForm(btn){
    const form=btn.closest('.affil-add-form'); form.classList.remove('open');
    form.querySelectorAll('.affil-add-input').forEach(i=>{i.value='';i.classList.remove('inp-error');});
}
function saveNewAffilInline(btn){
    const form=btn.closest('.affil-add-form'); const wrap=form.closest('.rv-affil-wrap');
    const nameInp=form.querySelector('.affil-new-name'); const name=nameInp?.value.trim()||'';
    if(!name){nameInp?.classList.add('inp-error');nameInp?.focus();toast('Please enter the institution name','e');return;}
    nameInp?.classList.remove('inp-error');
    const dept=form.querySelector('.affil-new-dept')?.value.trim()||'';
    const city=form.querySelector('.affil-new-city')?.value.trim()||'';
    const country=form.querySelector('.affil-new-country')?.value.trim()||'';
    btn.disabled=true; btn.innerHTML='<span class="spin" style="border-top-color:#fff;border-color:rgba(255,255,255,.3)"></span> Saving…';
    const fd=new FormData(); fd.append('name',name); fd.append('department',dept); fd.append('city',city); fd.append('country',country);
    fetch('editorial.php?ajax=save_affiliation',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(data=>{
        btn.disabled=false; btn.innerHTML='💾 Save &amp; Select';
        if(data.success){selectAffilInWrap(wrap,data.affiliation_id,data.name,dept);closeAffilForm(btn);toast(data.duplicate?'✓ Existing affiliation selected!':'✓ Affiliation added and selected!','s');}
        else toast('Error: '+(data.message||'Could not save'),'e');
    }).catch(()=>{btn.disabled=false;btn.innerHTML='💾 Save &amp; Select';toast('Network error — please try again','e');});
}

/* ─── Reviewer: Add / Move / Remove ──────────────────────── */
function addRv(type){
    const list=document.getElementById(type==='rec'?'recList':'exclList');
    const clone=document.getElementById('tmplRv').content.cloneNode(true);
    list.appendChild(clone); refreshBtns(type);
    const newLi=list.lastElementChild; newLi.scrollIntoView({behavior:'smooth',block:'nearest'});
    newLi.querySelector('.rv-email')?.focus(); dirty();
}
function moveRv(btn,up){
    const li=btn.closest('.reviewer-block'); const list=li.parentElement;
    const items=Array.from(list.children); const idx=items.indexOf(li); const tgt=up?idx-1:idx+1;
    if(tgt<0||tgt>=items.length)return;
    if(up)list.insertBefore(li,items[tgt]); else list.insertBefore(items[tgt],li);
    refreshBtns(list.id==='recList'?'rec':'excl'); dirty();
}
function refreshBtns(type){
    const list=document.getElementById(type==='rec'?'recList':'exclList');
    const items=Array.from(list.children);
    items.forEach((li,i)=>{
        const up=li.querySelector('.move-up'); const dn=li.querySelector('.move-down');
        if(up){up.disabled=i===0;up.classList.toggle('disabled',i===0);}
        if(dn){dn.disabled=i===items.length-1;dn.classList.toggle('disabled',i===items.length-1);}
    });
}
function openConfirm(btn){
    const list=btn.closest('ul'); if(list.children.length<=1){toast('At least one form must remain','e');return;}
    _pendingRemoveBtn=btn; document.getElementById('confirmOverlay').classList.remove('hidden');
}
function closeConfirm(){ document.getElementById('confirmOverlay').classList.add('hidden'); _pendingRemoveBtn=null; }
function doRemove(){
    if(!_pendingRemoveBtn)return;
    const li=_pendingRemoveBtn.closest('.reviewer-block'); const list=li.parentElement;
    const type=list.id==='recList'?'rec':'excl';
    li.remove(); refreshBtns(type); dirty(); closeConfirm();
}

/* ─── Save ────────────────────────────────────────────────── */
function dirty(){ isDirty=true; clearTimeout(autoTimer); autoTimer=setTimeout(()=>doSave(false,true),2000); }
const rvDirty=dirty;
function collectList(listId,type){
    return Array.from(document.getElementById(listId).children).map((li,i)=>({
        reviewer_type:type, email:li.querySelector('.rv-email')?.value.trim()||'',
        title:li.querySelector('.rv-dd-val')?.textContent.trim()||'',
        first_name:li.querySelector('.rv-fname')?.value.trim()||'',
        middle_name:li.querySelector('.rv-mname')?.value.trim()||'',
        last_name:li.querySelector('.rv-lname')?.value.trim()||'',
        affiliation_id:+(li.querySelector('.rv-affil-id')?.value)||0,
        affiliation_name:li.querySelector('.rv-affil-text')?.value.trim()||'',
        department:li.querySelector('.rv-dept')?.value.trim()||'',
        additional_comment:li.querySelector('.rv-comment')?.value.trim()||'',
        display_order:i+1,
    }));
}
function validateAndShowErrors(){
    let hasError=false;
    document.querySelectorAll('.reviewer-block').forEach(li=>{
        const email=li.querySelector('.rv-email'); const fname=li.querySelector('.rv-fname'); const lname=li.querySelector('.rv-lname');
        const anyFilled=email?.value.trim()||fname?.value.trim()||lname?.value.trim(); if(!anyFilled)return;
        const emailErr=email?.closest('.rv-field')?.querySelector('.rv-err');
        const fnErr=fname?.closest('.rv-field')?.querySelector('.rv-err');
        const lnErr=lname?.closest('.rv-field')?.querySelector('.rv-err');
        if(email?.value.trim()&&!/\S+@\S+\.\S+/.test(email.value.trim())){if(emailErr)emailErr.classList.add('show');hasError=true;}else if(emailErr)emailErr.classList.remove('show');
        if(fname&&!fname.value.trim()){if(fnErr)fnErr.classList.add('show');hasError=true;}else if(fnErr)fnErr.classList.remove('show');
        if(lname&&!lname.value.trim()){if(lnErr)lnErr.classList.add('show');hasError=true;}else if(lnErr)lnErr.classList.remove('show');
    });
    return !hasError;
}
function doSave(cont=false,silent=false){
    if(!silent&&!validateAndShowErrors()){toast('Please fix the errors before saving','e');document.querySelector('.rv-err.show')?.scrollIntoView({behavior:'smooth',block:'center'});return;}
    const fd=new FormData(); fd.append('submission_id',SID);
    fd.append('data',JSON.stringify({
        preferred_editor_ids:preferredIds,
        suggested_editors:preferredIds.map((eid,i)=>{const e=ALL_EDITORS.find(x=>+x.editor_id===+eid);if(!e)return null;return{editor_id:e.editor_id,name:e.name,institution:e.university||'',expertise:'',display_order:i+1};}).filter(Boolean),
        reviewers:[...collectList('recList','recommended'),...collectList('exclList','excluded')],
    }));
    if(!silent){['saveBtn','saveContinueBtn'].forEach(id=>{const b=document.getElementById(id);b.disabled=true;b.innerHTML='<span class="spin" style="border-top-color:#fff;border-color:rgba(255,255,255,.3)"></span>';});}
    fetch('editorial.php?ajax=save_editorial',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(d=>{
        isDirty=false;
        if(!silent){document.getElementById('saveBtn').disabled=false;document.getElementById('saveBtn').textContent='Save';document.getElementById('saveContinueBtn').disabled=false;document.getElementById('saveContinueBtn').innerHTML='Save &amp; Continue';}
        if(d.success){if(!silent)toast('Saved!','s');if(cont&&!silent)setTimeout(()=>location.href='statements.php?id='+SID,700);}
        else if(!silent)toast(d.message||'Save failed','e');
    }).catch(()=>{
        if(!silent){document.getElementById('saveBtn').disabled=false;document.getElementById('saveBtn').textContent='Save';document.getElementById('saveContinueBtn').disabled=false;document.getElementById('saveContinueBtn').innerHTML='Save &amp; Continue';toast('Network error','e');}
    });
}

/* ─── Utils ───────────────────────────────────────────────── */
function toast(msg,type='i'){
    const w=document.getElementById('toastWrap'); const t=document.createElement('div');
    t.className='toast t'+type; t.innerHTML=(type==='s'?'✅':type==='e'?'❌':'ℹ️')+' '+xe(msg);
    w.appendChild(t); setTimeout(()=>t.remove(),3500);
}
function xe(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}

refreshBtns('rec'); refreshBtns('excl');
window.addEventListener('beforeunload',e=>{if(isDirty){e.preventDefault();e.returnValue='';}});
</script>

<?php layoutEnd(); ?>