<?php
// ============================================================
//  manuscript.php  —  SCREEN 2: Manuscript Information
//  Article Title, Running Title, Abstract, Keywords (min5/max8)
// ============================================================
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  = 'Manuscript Information';
$activePage = 'submission';

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

// ── Load submission ──────────────────────────────────────────
$stmt = db()->prepare(
    "SELECT s.*,
            j.name AS journal_name,
            sp.name AS specialty_name,
            at.name AS article_type_name,
            at.summary_length, at.figures_tables_limit,
            at.preliminary_fee_chf
     FROM   submissions s
     LEFT JOIN journals    j  ON j.journal_id    = s.journal_id
     LEFT JOIN specialties sp ON sp.specialty_id = s.specialty_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([$submission_id, $user_id]);
$submission = $stmt->fetch();
if (!$submission) { header('Location: submission.php'); exit; }

// ── Load manuscript_info row ─────────────────────────────────
$stmt = db()->prepare("SELECT * FROM manuscript_info WHERE submission_id = ?");
$stmt->execute([$submission_id]);
$minfo = $stmt->fetch() ?: [];

// ── Load existing keywords ───────────────────────────────────
$stmt = db()->prepare(
    "SELECT k.keyword_id, k.keyword
     FROM submission_keywords sk
     JOIN keywords k ON k.keyword_id = sk.keyword_id
     WHERE sk.submission_id = ?
     ORDER BY sk.display_order ASC"
);
$stmt->execute([$submission_id]);
$existingKeywords = $stmt->fetchAll();

// ── Completion score ─────────────────────────────────────────
$titleFilled    = !empty($minfo['article_title']);
$abstractFilled = !empty($minfo['abstract']);
$kwCount        = count($existingKeywords);
$kwValid        = $kwCount >= 5;
$score          = (int)((($titleFilled?1:0) + ($abstractFilled?1:0) + ($kwValid?1:0)) / 3 * 100);

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

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

:root {
  --primary-light: #FFF0EA;
  --primary-dark:  #BF4520;
  --border-focus:  #E05A2B;
  --success:       #10B981;
  --warning:       #F59E0B;
  --error:         #EF4444;
  --radius:        10px;
  --radius-lg:     14px;
  --shadow:        0 1px 4px rgba(0,0,0,.08);
  --shadow-md:     0 4px 16px rgba(0,0,0,.1);
  --font-display:  'Fraunces', serif;
}

.page-wrap      { max-width: 1100px; margin: 0 auto; padding: 24px 22px 60px; }
.page-header    { margin-bottom: 18px; }
.page-title     { font-family: var(--font-display,'serif'); font-size: 23px; font-weight: 700; color: var(--blue); margin-bottom: 4px; }
.page-subtitle  { font-size: 13px; color: var(--muted); }

/* Breadcrumb */
.breadcrumb     { display: flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); margin-bottom: 18px; }
.breadcrumb a   { color: var(--primary); text-decoration: none; font-weight: 500; }
.breadcrumb a:hover { text-decoration: underline; }
.breadcrumb-sep { color: var(--border); }

/* Progress bar */
.progress-bar-wrap { display: flex; align-items: center; gap: 10px; margin-bottom: 22px; flex-wrap: wrap; }
.progress-label    { font-size: 12px; font-weight: 600; color: var(--muted); }
.progress-track    { flex: 1; min-width: 120px; height: 8px; background: #E5E7EB; border-radius: 99px; overflow: hidden; }
.progress-fill     { height: 100%; background: linear-gradient(90deg,var(--primary),#FF8C5A); border-radius: 99px; transition: width .5s ease; }
.progress-pct      { font-size: 12px; font-weight: 700; color: var(--primary); }
.save-indicator    { display: flex; align-items: center; gap: 5px; font-size: 11.5px; color: var(--muted); opacity: 0; transition: opacity .3s; margin-left: auto; }
.save-indicator.show { opacity: 1; }
.save-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--success); }

/* Grid */
.main-grid { display: grid; grid-template-columns: 1fr 290px; gap: 22px; align-items: start; }
@media(max-width:860px){ .main-grid { grid-template-columns: 1fr; } }

/* Cards */
.card         { background: var(--white); border-radius: var(--radius-lg); border: 1px solid var(--border); box-shadow: var(--shadow); margin-bottom: 16px; overflow: hidden; }
.card-header  { display: flex; align-items: center; justify-content: space-between; padding: 15px 20px; border-bottom: 1px solid var(--border); }
.card-title   { font-size: 14px; font-weight: 700; color: var(--blue); }
.card-badge   { font-size: 11px; font-weight: 600; padding: 3px 10px; border-radius: 99px; }
.badge-complete   { background: #D1FAE5; color: #059669; }
.badge-incomplete { background: #FEF3C7; color: #92400E; }
.card-body    { padding: 20px; }

/* Form elements */
.form-group   { margin-bottom: 18px; }
.form-label   { display: block; font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 6px; }
.optional     { font-weight: 400; color: var(--muted); font-size: 12px; }
.info-icon    { display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px; border-radius: 50%; background: #E5E7EB; color: var(--muted); font-size: 9px; font-weight: 700; cursor: default; margin-left: 4px; font-style: normal; }
.form-input, .form-textarea { width: 100%; padding: 9px 13px; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: var(--font); font-size: 13px; color: var(--text); background: var(--white); transition: border-color .15s; outline: none; }
.form-input:focus, .form-textarea:focus { border-color: var(--border-focus); box-shadow: 0 0 0 3px rgba(224,90,43,.1); }
.form-textarea { resize: vertical; min-height: 140px; line-height: 1.6; }
.char-counter { font-size: 11px; color: var(--muted); text-align: right; margin-top: 4px; }
.char-counter.warn { color: var(--warning); }
.char-counter.over { color: var(--error); }
.form-hint    { font-size: 11.5px; color: var(--muted); margin-top: 5px; }
.word-counter { font-size: 11px; color: var(--muted); margin-top: 4px; }
.form-error   { font-size: 11.5px; color: var(--error); margin-top: 5px; display: none; }
.form-error.show { display: block; }
.field-error  { border-color: var(--error) !important; box-shadow: 0 0 0 3px rgba(239,68,68,.1) !important; }

/* Abstract progress bar */
.abstract-limit-bar  { height: 4px; background: #E5E7EB; border-radius: 99px; margin-top: 6px; overflow: hidden; }
.abstract-limit-fill { height: 100%; background: var(--success); border-radius: 99px; transition: width .3s, background .3s; }

/* Keywords */
.kw-wrap-outer { position: relative; }
.kw-wrap { border: 1.5px solid var(--border); border-radius: var(--radius); padding: 10px 12px; min-height: 50px; display: flex; flex-wrap: wrap; gap: 6px; cursor: text; transition: border-color .15s; background: var(--white); }
.kw-wrap:focus-within { border-color: var(--border-focus); box-shadow: 0 0 0 3px rgba(224,90,43,.1); }
.kw-wrap.kw-field-error { border-color: var(--error) !important; box-shadow: 0 0 0 3px rgba(239,68,68,.1) !important; }
.kw-tag { display: inline-flex; align-items: center; gap: 5px; padding: 4px 10px; background: var(--blue-light); border: 1px solid #C7D6EC; border-radius: 99px; font-size: 12px; font-weight: 500; color: var(--blue); }
.kw-tag-remove { background: none; border: none; cursor: pointer; color: var(--muted); font-size: 14px; line-height: 1; padding: 0; transition: color .15s; }
.kw-tag-remove:hover { color: var(--error); }
.kw-input { flex: 1; min-width: 150px; border: none; outline: none; font-family: var(--font); font-size: 13px; color: var(--text); padding: 2px 0; background: transparent; }
.kw-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: var(--white); border: 1.5px solid var(--border-focus); border-top: none; border-radius: 0 0 var(--radius) var(--radius); max-height: 200px; overflow-y: auto; z-index: 400; box-shadow: var(--shadow-md); }
.kw-dropdown-item { padding: 9px 14px; font-size: 13px; cursor: pointer; display: flex; align-items: center; justify-content: space-between; transition: background .1s; }
.kw-dropdown-item:hover, .kw-dropdown-item.active { background: var(--primary-light); color: var(--primary); }
.kw-dropdown-item .kw-add-hint { font-size: 11px; color: var(--muted); }
.kw-dropdown-create { padding: 9px 14px; font-size: 13px; cursor: pointer; color: var(--primary); font-weight: 600; border-top: 1px solid var(--border); transition: background .1s; }
.kw-dropdown-create:hover { background: var(--primary-light); }
.kw-count { font-size: 11.5px; margin-top: 6px; color: var(--muted); }
.kw-count.kw-ok   { color: var(--success); font-weight: 600; }
.kw-count.kw-warn { color: var(--warning); font-weight: 600; }
.kw-count.kw-error{ color: var(--error);   font-weight: 600; }

/* Journal mini card */
.journal-mini      { display: flex; align-items: center; gap: 12px; padding: 12px 14px; background: var(--blue-light); border-radius: var(--radius); border: 1px solid #C7D6EC; margin-bottom: 16px; }
.journal-mini-icon { width: 38px; height: 38px; border-radius: 8px; background: var(--blue); display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; color: #fff; }
.journal-mini-name { font-size: 13px; font-weight: 700; color: var(--blue); }
.journal-mini-spec { font-size: 11.5px; color: var(--muted); }

/* Sidebar cards */
.sidebar-card  { background: var(--white); border-radius: var(--radius-lg); border: 1px solid var(--border); padding: 16px 18px; margin-bottom: 14px; box-shadow: var(--shadow); }
.sidebar-title { font-size: 12px; font-weight: 700; color: var(--blue); margin-bottom: 12px; text-transform: uppercase; letter-spacing: .4px; }
.steps-list    { list-style: none; display: flex; flex-direction: column; gap: 9px; }
.steps-list li { display: flex; align-items: center; gap: 10px; font-size: 12.5px; }
.step-num      { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; flex-shrink: 0; }
.step-active   { background: var(--primary); color: #fff; }
.step-done     { background: var(--success); color: #fff; }
.step-pending  { background: #F3F4F6; color: var(--muted); }
.step-name     { flex: 1; font-weight: 500; }
.step-status   { font-size: 10px; font-weight: 600; padding: 2px 7px; border-radius: 99px; }
.step-status-active  { background: var(--primary-light); color: var(--primary); }
.step-status-done    { background: #D1FAE5; color: #059669; }
.step-status-pending { background: #F3F4F6; color: var(--muted); }

/* Fee row */
.fee-row { display: flex; justify-content: space-between; font-size: 13px; padding: 5px 0; border-bottom: 1px solid var(--border); }
.fee-row:last-child { border-bottom: none; font-weight: 700; color: var(--primary); font-size: 13.5px; }

/* Form actions */
.form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 6px; padding-top: 16px; border-top: 1px solid var(--border); }
.btn          { display: inline-flex; align-items: center; gap: 6px; padding: 9px 18px; border-radius: var(--radius); font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; border: none; transition: all .15s; text-decoration: none; }
.btn-primary  { background: var(--primary); color: #fff; }
.btn-primary:hover { background: var(--primary-dark); }
.btn-outline  { background: var(--white); color: var(--text); border: 1.5px solid var(--border); }
.btn-outline:hover { border-color: var(--primary); color: var(--primary); }
.btn-back     { background: var(--white); color: var(--blue); border: 1.5px solid var(--border); }
.btn-back:hover { border-color: var(--blue); background: var(--blue-light); }
.btn:disabled { opacity: .6; cursor: not-allowed; }

/* Toast */
.toast-container { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 12px 18px; border-radius: var(--radius); font-size: 13px; font-weight: 500; box-shadow: var(--shadow-md); min-width: 240px; max-width: 360px; display: flex; align-items: center; gap: 10px; animation: slideUp .3s ease; color: #fff; }
.toast-success { background: #1D8A5E; }
.toast-error   { background: #DC2626; }
.toast-info    { background: var(--blue); }
@keyframes slideUp { from{transform:translateY(20px);opacity:0} to{transform:translateY(0);opacity:1} }

.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: spin .6s linear infinite; }
@keyframes spin { to{ transform: rotate(360deg); } }
</style>

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

  <!-- Breadcrumb -->
  <div class="breadcrumb">
    <a href="dashboard.php">Overview</a>
    <span class="breadcrumb-sep">›</span>
    <a href="submission.php?id=<?= $submission_id ?>">Submission Details</a>
    <span class="breadcrumb-sep">›</span>
    <span>Manuscript Information</span>
  </div>

  <div class="page-header">
    <h1 class="page-title">📄 Manuscript Information</h1>
    <p class="page-subtitle">Provide your article title, abstract, and keywords for your submission</p>
  </div>

  <!-- Progress Bar -->
  <div class="progress-bar-wrap">
    <span class="progress-label">Submission Quality</span>
    <div class="progress-track">
      <div class="progress-fill" id="progressFill" style="width:<?= $score ?>%"></div>
    </div>
    <span class="progress-pct" id="progressPct"><?= $score ?>%</span>
    <span class="save-indicator" id="saveIndicator">
      <span class="save-dot"></span> Saved
    </span>
  </div>

  <div class="main-grid">

    <!-- ════ LEFT — FORM ════════════════════════════════════ -->
    <div>
      <form id="manuscriptForm" novalidate>
        <input type="hidden" id="submissionId" value="<?= $submission_id ?>">
        <input type="hidden" id="manuscriptId" value="<?= $minfo['manuscript_id'] ?? '' ?>">

        <!-- Journal context mini card -->
        <div class="journal-mini">
          <div class="journal-mini-icon">📚</div>
          <div>
            <div class="journal-mini-name">
              Communeglobal in <?= htmlspecialchars($submission['journal_name'] ?? '') ?>
            </div>
            <div class="journal-mini-spec">
              <?= htmlspecialchars($submission['specialty_name'] ?? '') ?>
              <?php if ($submission['article_type_name']): ?>
                · <?= htmlspecialchars($submission['article_type_name']) ?>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- CARD 1: Article Title -->
        <div class="card">
          <div class="card-header">
            <span class="card-title">✏️ Article Title</span>
            <span class="card-badge <?= $titleFilled ? 'badge-complete' : 'badge-incomplete' ?>" id="titleBadge">
              <?= $titleFilled ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">

            <div class="form-group">
              <label class="form-label" for="articleTitle">
                Article Title
                <span class="info-icon" title="Enter the full title of your article. Avoid abbreviations.">i</span>
              </label>
              <input type="text" class="form-input" id="articleTitle"
                     placeholder="Enter the full title of your article..."
                     maxlength="1000"
                     value="<?= htmlspecialchars($minfo['article_title'] ?? '') ?>"
                     oninput="onTitleInput(this)">
              <div class="form-error" id="titleError">Please enter the article title</div>
              <div class="char-counter" id="titleCounter">
                <span id="titleCount"><?= mb_strlen($minfo['article_title'] ?? '') ?></span>/1000 characters
              </div>
              <div class="form-hint">Avoid abbreviations and formulae where possible. The title should be clear and concise.</div>
            </div>

            <div class="form-group" style="margin-bottom:0">
              <label class="form-label" for="runningTitle">
                Running Title
                <span class="optional">(optional)</span>
                <span class="info-icon" title="A short version of the title, max 5 words, used in headers/footers">i</span>
              </label>
              <input type="text" class="form-input" id="runningTitle"
                     placeholder="Short title, max 5 words..."
                     maxlength="255"
                     value="<?= htmlspecialchars($minfo['running_title'] ?? '') ?>"
                     oninput="onRunningTitleInput(this)">
              <div class="word-counter" id="runningTitleWords">
                <span id="runningTitleWordCount"><?= str_word_count($minfo['running_title'] ?? '') ?></span>/5 words recommended
              </div>
            </div>

          </div>
        </div>

        <!-- CARD 2: Abstract -->
        <div class="card">
          <div class="card-header">
            <span class="card-title">📝 Abstract</span>
            <span class="card-badge <?= $abstractFilled ? 'badge-complete' : 'badge-incomplete' ?>" id="abstractBadge">
              <?= $abstractFilled ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">
            <div class="form-group" style="margin-bottom:0">
              <label class="form-label" for="abstract">
                Abstract
                <span class="info-icon" title="Plain text abstract only. No HTML, no references, no footnotes.">i</span>
              </label>
              <textarea class="form-textarea" id="abstract"
                        placeholder="Write a concise summary of your research. Plain text only — no formatting, references, or footnotes..."
                        rows="8"
                        oninput="onAbstractInput(this)"><?= htmlspecialchars($minfo['abstract'] ?? '') ?></textarea>
              <div class="form-error" id="abstractError">Please provide an abstract (minimum 50 characters)</div>
              <div class="abstract-limit-bar">
                <div class="abstract-limit-fill" id="abstractBar" style="width:0%"></div>
              </div>
              <div style="display:flex;justify-content:space-between;align-items:center;margin-top:5px;flex-wrap:wrap;gap:6px">
                <div class="form-hint">Plain text only. No HTML tags, references, or footnotes.</div>
                <div class="char-counter" id="abstractCounter">
                  <span id="abstractCount"><?= mb_strlen($minfo['abstract'] ?? '') ?></span> characters
                  <?php if ($submission['summary_length']): ?>
                    · <span id="abstractWordCount">0</span>/<?= $submission['summary_length'] ?> words
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- CARD 3: Keywords -->
        <div class="card">
          <div class="card-header">
            <span class="card-title">🏷️ Keywords</span>
            <span class="card-badge <?= $kwValid ? 'badge-complete' : 'badge-incomplete' ?>" id="kwBadge">
              <?= $kwValid ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">
            <div class="form-group" style="margin-bottom:0">
              <label class="form-label">
                Keywords
                <span class="info-icon" title="Minimum 5, maximum 8 keywords. Type to search existing or press Enter to add new.">i</span>
              </label>

              <div class="kw-wrap-outer">
                <div class="kw-wrap" id="kwWrap" onclick="focusKwInput()">
                  <?php foreach ($existingKeywords as $kw): ?>
                  <span class="kw-tag" data-id="<?= $kw['keyword_id'] ?>" data-keyword="<?= htmlspecialchars($kw['keyword']) ?>">
                    <?= htmlspecialchars($kw['keyword']) ?>
                    <button type="button" class="kw-tag-remove"
                            onclick="removeKeyword(<?= $kw['keyword_id'] ?>,this)" title="Remove">×</button>
                  </span>
                  <?php endforeach; ?>
                  <input type="text" class="kw-input" id="kwInput"
                         placeholder="<?= count($existingKeywords) === 0 ? 'Type to search keywords...' : '' ?>"
                         autocomplete="off"
                         oninput="onKwInput(this)"
                         onkeydown="onKwKeydown(event)">
                </div>
                <div class="kw-dropdown" id="kwDropdown" style="display:none"></div>
              </div>

              <div class="kw-count <?= $kwValid ? 'kw-ok' : ($kwCount > 0 ? 'kw-warn' : '') ?>" id="kwCount">
                <?php
                  echo match(true) {
                      $kwCount === 0 => 'Add at least 5 keywords (minimum 5, maximum 8)',
                      $kwCount < 5   => $kwCount.'/5 added — need '.(5-$kwCount).' more',
                      $kwCount <= 8  => '✓ '.$kwCount.' keywords added',
                      default        => $kwCount.' keywords — maximum is 8, please remove '.($kwCount-8),
                  };
                ?>
              </div>
              <div class="form-error" id="kwError">Please add at least 5 keywords</div>
              <div class="form-hint" style="margin-top:6px">
                Search existing keywords or press <strong>Enter</strong> to create a new one.
                Min 5, max 8 keywords per submission.
              </div>
            </div>
          </div>
        </div>

        <!-- Form Actions -->
        <div class="form-actions">
          <a href="submission.php?id=<?= $submission_id ?>" class="btn btn-back">← Back</a>
          <button type="button" class="btn btn-outline" onclick="saveManuscript(false)" id="saveBtn">💾 Save</button>
          <button type="button" class="btn btn-primary" onclick="saveManuscript(true)" id="saveContinueBtn">Save &amp; Continue →</button>
        </div>

      </form>
    </div><!-- /left -->

    <!-- ════ RIGHT — SIDEBAR ════════════════════════════════ -->
    <div>

      <!-- Preliminary Fee -->
      <div class="sidebar-card">
        <div class="sidebar-title">💰 Preliminary Fee</div>
        <div class="fee-row"><span>Article Processing Fee</span><span>$35.00 USD</span></div>
        <div class="fee-row"><span>VAT rate</span><span>0.00%</span></div>
        <div class="fee-row"><span>TOTAL DUE (after acceptance)</span><span>$35.00 USD</span></div>
        <p style="font-size:11px;color:var(--muted);margin-top:10px">Payment required after acceptance</p>
      </div>

      <!-- Writing Tips -->
      <div class="sidebar-card">
        <div class="sidebar-title">📋 Writing Tips</div>
        <div style="font-size:12.5px;color:var(--muted);line-height:1.8">
          <div style="margin-bottom:10px">
            <strong style="color:var(--text)">Title</strong><br>
            Clear, specific, free of abbreviations. Max 1000 characters.
          </div>
          <div style="margin-bottom:10px">
            <strong style="color:var(--text)">Running Title</strong><br>
            Short version for headers. Keep under 5 words.
          </div>
          <div style="margin-bottom:10px">
            <strong style="color:var(--text)">Abstract</strong><br>
            Plain text only. No HTML, no references.
            <?php if ($submission['summary_length']): ?>
              Max <?= $submission['summary_length'] ?> words for this article type.
            <?php endif; ?>
          </div>
          <div>
            <strong style="color:var(--text)">Keywords</strong><br>
            Min 5, max 8. Choose terms that best describe your research topic.
          </div>
        </div>
      </div>

      <!-- Submission Steps -->
      <div class="sidebar-card">
        <div class="sidebar-title">📋 Submission Steps</div>
        <ul class="steps-list">
          <?php
          $steps = [
            ['Submission details',    'done',   'Done',       'submission.php?id='.$submission_id],
            ['Manuscript information','active', 'Active',     '#'],
            ['Related articles',      'pending','To complete','#'],
            ['Authors & contributors','pending','To complete','#'],
            ['Editorial',             'pending','To complete','#'],
            ['Statements',            'pending','To complete','#'],
            ['Payment',               'pending','To complete','#'],
          ];
          foreach ($steps as $i => [$sname,$sstate,$sstatus,$slink]):
          ?>
          <li>
            <span class="step-num step-<?= $sstate ?>"><?= $sstate === 'done' ? '✓' : $i+1 ?></span>
            <?php if ($sstate !== 'pending'): ?>
              <a href="<?= $slink ?>" class="step-name"
                 style="color:var(--<?= $sstate==='done'?'success':'primary' ?>);text-decoration:none;font-weight:600">
                <?= htmlspecialchars($sname) ?>
              </a>
            <?php else: ?>
              <span class="step-name"><?= htmlspecialchars($sname) ?></span>
            <?php endif; ?>
            <span class="step-status step-status-<?= $sstate ?>"><?= $sstatus ?></span>
          </li>
          <?php endforeach; ?>
        </ul>
      </div>

      <!-- Author Guidelines -->
      <div class="sidebar-card" style="text-align:center">
        <div style="font-size:30px;margin-bottom:8px">📖</div>
        <a href="https://communeglobal.com/journals/social-science/author-style-guidelines"
           target="_blank" rel="noopener"
           style="color:var(--primary);font-weight:700;font-size:13px;text-decoration:none">
          Author Guidelines ↗
        </a>
        <p style="font-size:12px;color:var(--muted);margin-top:4px">Read before submitting your manuscript</p>
      </div>

    </div><!-- /sidebar -->
  </div><!-- /main-grid -->
</div><!-- /page-wrap -->

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

<script>
/* ══ STATE ════════════════════════════════════════════════════ */
const SUBMISSION_ID  = <?= $submission_id ?>;
const MAX_WORD_LIMIT = <?= $submission['summary_length'] ?: 'null' ?>;
let autoSaveTimer    = null;
let kwDebounceTimer  = null;
let dropdownActive   = -1;

let keywords = <?= json_encode(array_map(
    fn($k) => ['id' => (int)$k['keyword_id'], 'keyword' => $k['keyword']],
    $existingKeywords
)) ?>;

/* ══ TITLE ════════════════════════════════════════════════════ */
function onTitleInput(el) {
    const len = el.value.length;
    document.getElementById('titleCount').textContent = len;
    const ctr = document.getElementById('titleCounter');
    ctr.className = 'char-counter' + (len > 950 ? ' warn' : '') + (len >= 1000 ? ' over' : '');
    updateTitleBadge();
    scheduleAutoSave();
}
function updateTitleBadge() {
    const filled = document.getElementById('articleTitle').value.trim().length > 0;
    const b = document.getElementById('titleBadge');
    b.textContent = filled ? '✓ Completed' : '⚠ Incomplete';
    b.className = 'card-badge ' + (filled ? 'badge-complete' : 'badge-incomplete');
}
function onRunningTitleInput(el) {
    const words = el.value.trim() ? el.value.trim().split(/\s+/).length : 0;
    const wc = document.getElementById('runningTitleWordCount');
    wc.textContent = words;
    wc.parentElement.className = 'word-counter' + (words > 5 ? ' warn' : '');
    scheduleAutoSave();
}

/* ══ ABSTRACT ═════════════════════════════════════════════════ */
function onAbstractInput(el) {
    const len   = el.value.length;
    const words = el.value.trim() ? el.value.trim().split(/\s+/).length : 0;
    document.getElementById('abstractCount').textContent = len;
    const wcEl = document.getElementById('abstractWordCount');
    if (wcEl) wcEl.textContent = words;
    const limit = MAX_WORD_LIMIT || 600;
    const pct   = Math.min(100, Math.round((words / limit) * 100));
    const bar   = document.getElementById('abstractBar');
    bar.style.width      = pct + '%';
    bar.style.background = pct >= 100 ? 'var(--error)' : pct >= 90 ? 'var(--warning)' : 'var(--success)';
    const filled = el.value.trim().length > 50;
    const b = document.getElementById('abstractBadge');
    b.textContent = filled ? '✓ Completed' : '⚠ Incomplete';
    b.className = 'card-badge ' + (filled ? 'badge-complete' : 'badge-incomplete');
    scheduleAutoSave();
}
(function initAbstract() {
    const el = document.getElementById('abstract');
    if (el && el.value) onAbstractInput(el);
})();

/* ══ KEYWORDS ═════════════════════════════════════════════════ */
function focusKwInput() { document.getElementById('kwInput').focus(); }

function onKwInput(el) {
    clearTimeout(kwDebounceTimer);
    const q = el.value.trim();
    if (!q) { closeKwDropdown(); return; }
    kwDebounceTimer = setTimeout(() => searchKeywords(q), 280);
}

function searchKeywords(q) {
    fetch('ajax/search_keywords.php?q=' + encodeURIComponent(q))
    .then(r => r.json())
    .then(data => { if (data.success) renderKwDropdown(q, data.keywords); })
    .catch(() => closeKwDropdown());
}

function renderKwDropdown(q, results) {
    const dd = document.getElementById('kwDropdown');
    const existingIds = keywords.map(k => k.id);
    const filtered = results.filter(k => !existingIds.includes(k.keyword_id));
    let html = '';
    filtered.forEach((k, i) => {
        html += `<div class="kw-dropdown-item" data-id="${k.keyword_id}"
                      onclick="addKeywordById(${k.keyword_id},'${escAttr(k.keyword)}')"
                      onmouseover="setDropdownActive(${i})">
                   <span>${highlightMatch(escHtml(k.keyword), escHtml(q))}</span>
                   <span class="kw-add-hint">+ Add</span>
                 </div>`;
    });
    const exactMatch = results.find(k => k.keyword.toLowerCase() === q.toLowerCase());
    if (!exactMatch && keywords.length < 8) {
        html += `<div class="kw-dropdown-create" onclick="createAndAddKeyword('${escAttr(q)}')">
                   ✚ Create new keyword: "<strong>${escHtml(q)}</strong>"
                 </div>`;
    }
    if (!filtered.length && exactMatch === undefined) {
        html = `<div class="kw-dropdown-item" style="color:var(--muted);cursor:default">No results for "${escHtml(q)}"</div>`;
        if (keywords.length < 8) {
            html += `<div class="kw-dropdown-create" onclick="createAndAddKeyword('${escAttr(q)}')">
                       ✚ Create new keyword: "<strong>${escHtml(q)}</strong>"
                     </div>`;
        }
    }
    dd.innerHTML = html;
    dd.style.display = 'block';
    dropdownActive = -1;
}

function setDropdownActive(i) {
    dropdownActive = i;
    document.querySelectorAll('.kw-dropdown-item').forEach((el, idx) => el.classList.toggle('active', idx === i));
}

function closeKwDropdown() {
    document.getElementById('kwDropdown').style.display = 'none';
    document.getElementById('kwInput').value = '';
}

function onKwKeydown(e) {
    const dd    = document.getElementById('kwDropdown');
    const items = dd.querySelectorAll('.kw-dropdown-item');
    const input = document.getElementById('kwInput');
    if (e.key === 'Enter') {
        e.preventDefault();
        const q = input.value.trim(); if (!q) return;
        if (dropdownActive >= 0 && items[dropdownActive]) items[dropdownActive].click();
        else createAndAddKeyword(q);
    } else if (e.key === 'ArrowDown') {
        e.preventDefault(); setDropdownActive(Math.min(dropdownActive + 1, items.length - 1));
    } else if (e.key === 'ArrowUp') {
        e.preventDefault(); setDropdownActive(Math.max(dropdownActive - 1, 0));
    } else if (e.key === 'Escape') {
        closeKwDropdown();
    } else if (e.key === 'Backspace' && !input.value && keywords.length > 0) {
        removeKeyword(keywords[keywords.length - 1].id, null);
    }
}

document.addEventListener('click', e => {
    if (!document.getElementById('kwWrap').contains(e.target)) closeKwDropdown();
});

function addKeywordById(id, keyword) {
    if (keywords.length >= 8) { showToast('Maximum 8 keywords allowed', 'error'); return; }
    if (keywords.find(k => k.id === id)) { showToast('"' + keyword + '" already added', 'info'); closeKwDropdown(); return; }
    keywords.push({ id, keyword });
    renderKwTags(); closeKwDropdown(); updateKwCount(); saveKeywords(); scheduleAutoSave();
}

function createAndAddKeyword(text) {
    text = text.trim(); if (!text) return;
    if (keywords.length >= 8) { showToast('Maximum 8 keywords allowed', 'error'); return; }
    if (keywords.find(k => k.keyword.toLowerCase() === text.toLowerCase())) {
        showToast('"' + text + '" already added', 'info'); closeKwDropdown(); return;
    }
    closeKwDropdown();
    const fd = new FormData(); fd.append('keyword', text);
    fetch('ajax/create_keyword.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.success) addKeywordById(data.keyword_id, text);
        else showToast('Could not create keyword: ' + data.message, 'error');
    });
}

function removeKeyword(id, btnEl) {
    keywords = keywords.filter(k => k.id !== id);
    renderKwTags(); updateKwCount(); saveKeywords(); scheduleAutoSave();
}

function renderKwTags() {
    const wrap  = document.getElementById('kwWrap');
    const input = document.getElementById('kwInput');
    wrap.querySelectorAll('.kw-tag').forEach(t => t.remove());
    keywords.forEach(k => {
        const tag = document.createElement('span');
        tag.className = 'kw-tag';
        tag.dataset.id = k.id;
        tag.innerHTML = `${escHtml(k.keyword)}<button type="button" class="kw-tag-remove" onclick="removeKeyword(${k.id},this)">×</button>`;
        wrap.insertBefore(tag, input);
    });
    input.placeholder = keywords.length === 0 ? 'Type to search keywords...' : '';
}

function updateKwCount() {
    const n = keywords.length;
    const el = document.getElementById('kwCount');
    const badge = document.getElementById('kwBadge');
    let msg = '', cls = '';
    if (n === 0)     { msg = 'Add at least 5 keywords (minimum 5, maximum 8)'; cls = ''; }
    else if (n < 5)  { msg = n + '/5 added — need ' + (5-n) + ' more'; cls = 'kw-warn'; }
    else if (n <= 8) { msg = '✓ ' + n + ' keywords added'; cls = 'kw-ok'; }
    else             { msg = n + ' keywords — max is 8, remove ' + (n-8); cls = 'kw-error'; }
    el.textContent = msg; el.className = 'kw-count ' + cls;
    const valid = n >= 5 && n <= 8;
    badge.textContent = valid ? '✓ Completed' : '⚠ Incomplete';
    badge.className = 'card-badge ' + (valid ? 'badge-complete' : 'badge-incomplete');
    updateProgress();
}

function saveKeywords() {
    const fd = new FormData();
    fd.append('submission_id', SUBMISSION_ID);
    fd.append('keyword_ids', JSON.stringify(keywords.map(k => k.id)));
    fetch('ajax/save_keywords.php', { method: 'POST', body: fd })
    .catch(err => console.error('saveKeywords:', err));
}

function highlightMatch(text, q) {
    if (!q) return text;
    const re = new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi');
    return text.replace(re, '<strong>$1</strong>');
}

/* ══ SAVE ═════════════════════════════════════════════════════ */
function scheduleAutoSave() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => saveManuscriptSilent(), 1500);
}

function collectData() {
    return {
        submission_id : SUBMISSION_ID,
        manuscript_id : document.getElementById('manuscriptId').value,
        article_title : document.getElementById('articleTitle').value,
        running_title : document.getElementById('runningTitle').value,
        abstract      : document.getElementById('abstract').value,
    };
}

function saveManuscriptSilent() {
    const fd = new FormData();
    Object.entries(collectData()).forEach(([k,v]) => fd.append(k, v));
    fd.append('action', 'save');
    fetch('ajax/save_manuscript.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('manuscriptId').value = data.manuscript_id;
            showSaveIndicator(); updateProgress();
        }
    })
    .catch(err => console.error('saveManuscriptSilent:', err));
}

function validateManuscript() {
    let ok = true;
    const title = document.getElementById('articleTitle');
    const titleErr = document.getElementById('titleError');
    if (!title.value.trim()) { title.classList.add('field-error'); titleErr.classList.add('show'); ok = false; }
    else { title.classList.remove('field-error'); titleErr.classList.remove('show'); }

    const abs = document.getElementById('abstract');
    const absErr = document.getElementById('abstractError');
    if (abs.value.trim().length < 50) { abs.classList.add('field-error'); absErr.classList.add('show'); ok = false; }
    else { abs.classList.remove('field-error'); absErr.classList.remove('show'); }

    const kwWrap = document.getElementById('kwWrap');
    const kwErr  = document.getElementById('kwError');
    if (keywords.length < 5) { kwWrap.classList.add('kw-field-error'); kwErr.classList.add('show'); ok = false; }
    else { kwWrap.classList.remove('kw-field-error'); kwErr.classList.remove('show'); }

    if (!ok) document.querySelector('.field-error,.kw-field-error')?.scrollIntoView({ behavior:'smooth', block:'center' });
    return ok;
}

function saveManuscript(andContinue = false) {
    if (andContinue && !validateManuscript()) {
        showToast('Please fill all required fields before continuing.', 'error'); return;
    }
    const btn = andContinue ? document.getElementById('saveContinueBtn') : document.getElementById('saveBtn');
    btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Saving...';

    const fd = new FormData();
    Object.entries(collectData()).forEach(([k,v]) => fd.append(k, v));
    fd.append('action', andContinue ? 'save_continue' : 'save');

    fetch('ajax/save_manuscript.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = andContinue ? 'Save &amp; Continue →' : '💾 Save';
        if (data.success) {
            document.getElementById('manuscriptId').value = data.manuscript_id;
            updateProgress(); showSaveIndicator();
            if (andContinue) {
                showToast('Saved! Opening authors page...', 'success');
                setTimeout(() => window.location.href = 'authors.php?id=' + SUBMISSION_ID, 800);
            } else {
                showToast('Manuscript information saved!', 'success');
            }
        } else {
            showToast(data.message || 'Save failed. Please try again.', 'error');
        }
    })
    .catch(() => {
        btn.disabled = false;
        btn.innerHTML = andContinue ? 'Save &amp; Continue →' : '💾 Save';
        showToast('Network error. Please check your connection.', 'error');
    });
}

/* ══ PROGRESS ═════════════════════════════════════════════════ */
function updateProgress() {
    let filled = 0;
    if (document.getElementById('articleTitle').value.trim()) filled++;
    if (document.getElementById('abstract').value.trim().length > 50) filled++;
    const n = keywords.length;
    if (n >= 5 && n <= 8) filled++;
    const pct = Math.round((filled / 3) * 100);
    document.getElementById('progressFill').style.width = pct + '%';
    document.getElementById('progressPct').textContent  = pct + '%';
}

/* ══ UTILS ════════════════════════════════════════════════════ */
function showSaveIndicator() {
    const el = document.getElementById('saveIndicator');
    el.classList.add('show');
    setTimeout(() => el.classList.remove('show'), 2500);
}

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(), 3500);
}

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;');
}

updateProgress();
</script>

<?php layoutEnd(); ?>