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


<!-- ═══════════════ CONTINUE / NEW POPUP ════════════════════ -->
<?php if ($existingDraft && !$submission_id): ?>
<div class="overlay active" id="continueOverlay">
  <div class="modal" style="max-width:480px">
    <div class="modal-body">
      <div class="continue-popup">
        <div style="font-size:48px">📄</div>
        <h2>Submit your manuscript</h2>
        <p style="font-style:italic;color:var(--primary);font-size:12px;font-weight:600">Rigorous, constructive, transparent and fast peer review</p>
        <p>You have a submission in preparation. Do you want to continue or start a new submission?</p>
        <div class="continue-btns">
          <a href="submission.php?id=<?= $existingDraft['submission_id'] ?>" class="btn btn-blue">
            ▶ Continue
          </a>
          <button class="btn btn-outline" onclick="startNew()">
            ＋ Start new
          </button>
        </div>
        <p style="font-size:11px;color:var(--text-muted)">
          Last saved: <?= date('d M Y, H:i', strtotime($existingDraft['updated_at'])) ?>
        </p>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- ══════════════════ MAIN PAGE CONTENT ════════════════════ -->
<div class="page-wrap">
  <div class="page-header">
    <h1 class="page-title">📝 Submission Details</h1>
    <p class="page-subtitle">Fill in all required fields to submit your manuscript for peer review</p>
  </div>

  <!-- Progress Bar -->
  
    </div>
    <span class="progress-pct" id="progressPct"><?= $score ?>%</span>
    <span class="quality-badge" id="qualityBadge"><?= $score ?>% Complete</span>
    <span class="save-indicator" id="saveIndicator">
      <span class="save-dot"></span> Saved
    </span>
  </div>

  <!-- Steps nav -->
  <div class="main-grid">

    <!-- ════ LEFT — FORM ════ -->
    <div>

      <!-- SECTION 1: Submission Details -->
      <form id="submissionForm" novalidate>
        <input type="hidden" name="submission_id" id="submissionId" value="<?= $submission_id ?>">
        <input type="hidden" name="journal_id"    id="journalId"    value="<?= $submission['journal_id'] ?? '' ?>">
        <input type="hidden" name="specialty_id"  id="specialtyId"  value="<?= $submission['specialty_id'] ?? '' ?>">

        <div class="card" style="margin-bottom:16px">
          <div class="card-header">
            <span class="card-title">📰 Journal & Article Type</span>
            <span class="card-badge <?= $submission && $submission['article_type_id'] ? 'badge-complete' : 'badge-incomplete' ?>">
              <?= $submission && $submission['article_type_id'] ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">

            <!-- Journal Select -->
            <div class="form-group">
              <label class="form-label">
                Journal <span class="info-icon" title="Select the communeglobal journal that best matches your research">i</span>
              </label>
              <?php if ($submission && $submission['journal_id']): ?>
                <div class="journal-selected" id="journalSelected">
                  <?php if ($submission['cover_image_url']): ?>
                    <img src="<?= htmlspecialchars($submission['cover_image_url']) ?>" class="journal-thumb" alt="">
                  <?php else: ?>
                    <div class="journal-thumb" style="display:flex;align-items:center;justify-content:center;font-size:18px">📚</div>
                  <?php endif; ?>
                  <div class="journal-info">
                    <div class="jname">communeglobal in <?= htmlspecialchars($submission['journal_name']) ?></div>
                    <div class="jspecialty"><?= htmlspecialchars($submission['specialty_name'] ?? '') ?></div>
                    <div class="jdesc"><?= htmlspecialchars(substr($submission['specialty_desc'] ?? '', 0, 120)) ?>...</div>
                  </div>
                  <button type="button" class="journal-remove" onclick="removeJournal()" title="Remove journal">×</button>
                </div>
                <div class="journal-placeholder" id="journalPlaceholder" style="display:none" onclick="openJournalModal()">
                  🔍 Search and select a journal...
                </div>
              <?php else: ?>
                <div class="journal-selected" id="journalSelected" style="display:none"></div>
                <div class="journal-placeholder" id="journalPlaceholder" onclick="openJournalModal()">
                  🔍 Search and select a journal...
                </div>
              <?php endif; ?>
              <div class="form-error" id="journalError">Please select a journal</div>
            </div>

            <!-- Article Type -->
            <div class="form-group">
              <label class="form-label">
                Article type <span class="info-icon" title="Select the type of article you are submitting">i</span>
              </label>
              <select class="form-select" name="article_type_id" id="articleTypeSelect"
                      onchange="onArticleTypeChange(this)"
                      <?= !($submission && $submission['journal_id']) ? 'disabled' : '' ?>>
                <option value="">Select or type to search...</option>
                <?php if ($submission && $submission['specialty_id']): ?>
                  <?php
                    $atStmt = db()->prepare("SELECT * FROM article_types WHERE specialty_id = ? ORDER BY display_order");
                    $atStmt->execute([$submission['specialty_id']]);
                    $articleTypes = $atStmt->fetchAll();
                    foreach ($articleTypes as $at):
                  ?>
                  <option value="<?= $at['article_type_id'] ?>"
                    data-desc="<?= htmlspecialchars($at['description'] ?? '') ?>"
                    data-summary="<?= $at['summary_length'] ?>"
                    data-figures="<?= $at['figures_tables_limit'] ?>"
                    data-fee="<?= $at['preliminary_fee_chf'] ?>"
                    <?= $submission['article_type_id'] == $at['article_type_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($at['name']) ?>
                  </option>
                  <?php endforeach; ?>
                <?php endif; ?>
              </select>
              <div class="form-error" id="articleTypeError">Please select an article type</div>

              <!-- Article type detail card -->
              <div class="article-type-info <?= $submission && $submission['article_type_id'] ? 'show' : '' ?>" id="articleTypeInfo">
                <div class="at-name" id="atName"><?= htmlspecialchars($submission['article_type_name'] ?? '') ?></div>
                <div class="at-desc" id="atDesc"><?= htmlspecialchars(substr($submission['at_description'] ?? '', 0, 200)) ?></div>
                <div class="at-guidelines">
                  <span class="at-guideline-item" id="atSummary">Summary: <?= $submission['summary_length'] ?? '' ?> words</span>
                  <span class="at-guideline-item" id="atFigures">Figures & tables: <?= $submission['figures_tables_limit'] ?? '' ?></span>
                </div>
              </div>
            </div>

            <!-- Scope Statement -->
            <div class="form-group">
              <label class="form-label">
                Scope statement
                <span class="info-icon" title="Justify how your manuscript fits within the scope of the journal">i</span>
              </label>
              <textarea class="form-textarea" name="scope_statement" id="scopeStatement"
                        placeholder="Provide a short statement to justify how the contents of your manuscript fit within the scope of the selected journal and specialty..."
                        maxlength="400"
                        oninput="updateCharCount(this,'scopeCount',400)"><?= htmlspecialchars($submission['scope_statement'] ?? '') ?></textarea>
              <div class="char-count"><span id="scopeCount"><?= strlen($submission['scope_statement'] ?? '') ?></span>/400 characters left</div>
              <div class="form-hint">Selecting the best-matching journal and specialty will ensure the fastest peer review process.</div>
            </div>

            <!-- Research Topic (optional) -->
            <div class="form-group">
              <label class="form-label">
                Research Topic <span class="optional">(optional)</span>
                <span class="info-icon" title="If your article is part of a research topic, select it here">i</span>
              </label>
              <select class="form-select" name="research_topic_id" id="researchTopicSelect"
                      <?= (!empty($submission['specialty_id']) && !empty($researchTopics)) ? '' : 'disabled' ?>>
                <option value="">
                  <?= empty($submission['specialty_id']) ? 'Select a journal first...' : 'Select if applicable...' ?>
                </option>
                <?php foreach ($researchTopics as $rt): ?>
                  <option value="<?= $rt['topic_id'] ?>"
                    <?= ($submission['research_topic_id'] ?? '') == $rt['topic_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($rt['title']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="form-hint" id="researchTopicHint">
                <?php if (empty($submission['specialty_id'])): ?>
                  Research topics will appear after selecting a journal &amp; specialty.
                <?php elseif (empty($researchTopics)): ?>
                  No research topics available for this specialty.
                <?php else: ?>
                  <?= count($researchTopics) ?> research topics available.
                <?php endif; ?>
              </div>
            </div>

          </div><!-- card-body -->
        </div><!-- card -->

        <!-- SECTION 2: File Uploads -->
        <div class="card" style="margin-bottom:16px">
          <div class="card-header">
            <span class="card-title">📁 Upload Files</span>
            <span class="card-badge badge-incomplete" id="fileBadge">
              <?= !empty($uploadedFiles['manuscript']) ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">

            <div class="file-upload-grid">

              <!-- Manuscript -->
              <div>
                <div class="form-label">Manuscript <span class="info-icon" title="Upload your manuscript source file">i</span></div>
                <div class="upload-zone" id="manuscriptZone">
                  <input type="file" name="manuscript[]" id="manuscriptFile"
                         accept=".doc,.docx,.tex,.bib,.pdf"
                         onchange="handleFileUpload(this,'manuscript','manuscriptZone','manuscriptFiles')">
                  <span class="upload-icon">📄</span>
                  <div class="upload-title">Drag and drop</div>
                  <div class="upload-subtitle">Word or LaTeX + bib<br>and PDF version</div>
                  <span class="upload-btn-text">Browse files</span>
                </div>
                <div class="upload-warning" id="manuscriptWarning">
                  ⚠ Please provide both an editable version (DOC/DOCX or LaTeX) and a PDF version.
                </div>
                <div id="manuscriptFiles">
                  <?php foreach ($uploadedFiles['manuscript'] ?? [] as $f): ?>
                    <div class="uploaded-file" data-id="<?= $f['file_id'] ?>">
                      <span>📄</span>
                      <span class="fname"><?= htmlspecialchars($f['original_name']) ?></span>
                      <button type="button" class="fremove" onclick="removeFile(<?= $f['file_id'] ?>,this)">×</button>
                    </div>
                  <?php endforeach; ?>
                  <?php foreach ($uploadedFiles['manuscript_pdf'] ?? [] as $f): ?>
                    <div class="uploaded-file" data-id="<?= $f['file_id'] ?>">
                      <span>📕</span>
                      <span class="fname"><?= htmlspecialchars($f['original_name']) ?></span>
                      <button type="button" class="fremove" onclick="removeFile(<?= $f['file_id'] ?>,this)">×</button>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>

              <!-- Figures -->
              <div>
                <div class="form-label">Figures <span class="optional">(optional)</span></div>
                <div class="upload-zone" id="figureZone">
                  <input type="file" name="figures[]" id="figureFile" multiple
                         accept=".tif,.tiff,.jpg,.jpeg,.png"
                         onchange="handleFileUpload(this,'figure','figureZone','figureFiles')">
                  <span class="upload-optional">Optional</span>
                  <span class="upload-icon">🖼</span>
                  <div class="upload-title">Drag and drop figures</div>
                  <div class="upload-subtitle">TIF/TIFF, JPG, 300 DPI<br>8.5 to 20cm width</div>
                  <span class="upload-btn-text">Browse files</span>
                </div>
                <div id="figureFiles">
                  <?php foreach ($uploadedFiles['figure'] ?? [] as $f): ?>
                    <div class="uploaded-file" data-id="<?= $f['file_id'] ?>">
                      <span>🖼</span>
                      <span class="fname"><?= htmlspecialchars($f['original_name']) ?></span>
                      <button type="button" class="fremove" onclick="removeFile(<?= $f['file_id'] ?>,this)">×</button>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>

              <!-- Supplementary -->
              <div>
                <div class="form-label">Supplementary files <span class="optional">(optional)</span></div>
                <div class="upload-zone" id="suppZone">
                  <input type="file" name="supplementary[]" id="suppFile" multiple
                         onchange="handleFileUpload(this,'supplementary','suppZone','suppFiles')">
                  <span class="upload-optional">Optional</span>
                  <span class="upload-icon">📎</span>
                  <div class="upload-title">Drag and drop</div>
                  <div class="upload-subtitle">Data Sheet, Presentation<br>Suppl Image, Table, Audio, Video</div>
                  <span class="upload-btn-text">Browse files</span>
                </div>
                <div id="suppFiles">
                  <?php foreach ($uploadedFiles['supplementary'] ?? [] as $f): ?>
                    <div class="uploaded-file" data-id="<?= $f['file_id'] ?>">
                      <span>📎</span>
                      <span class="fname"><?= htmlspecialchars($f['original_name']) ?></span>
                      <button type="button" class="fremove" onclick="removeFile(<?= $f['file_id'] ?>,this)">×</button>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>

              <!-- Review only -->
              <div>
                <div class="form-label">Review only files <span class="optional">(optional)</span></div>
                <div class="upload-zone" id="reviewZone">
                  <input type="file" name="review_only[]" id="reviewFile" multiple
                         onchange="handleFileUpload(this,'review_only','reviewZone','reviewFiles')">
                  <span class="upload-optional">Optional</span>
                  <span class="upload-icon">👁</span>
                  <div class="upload-title">Drag and drop</div>
                  <div class="upload-subtitle">Data Sheet, Presentation<br>Suppl Image, Table, Audio, Video</div>
                  <span class="upload-btn-text">Browse files</span>
                </div>
                <div id="reviewFiles">
                  <?php foreach ($uploadedFiles['review_only'] ?? [] as $f): ?>
                    <div class="uploaded-file" data-id="<?= $f['file_id'] ?>">
                      <span>👁</span>
                      <span class="fname"><?= htmlspecialchars($f['original_name']) ?></span>
                      <button type="button" class="fremove" onclick="removeFile(<?= $f['file_id'] ?>,this)">×</button>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>

            </div><!-- file-upload-grid -->
          </div><!-- card-body -->
        </div><!-- card -->

        <!-- Form Actions -->
        <div class="form-actions">
          <button type="button" class="btn btn-outline" onclick="saveDraft(false)" id="saveBtn">
            💾 Save
          </button>
          <button type="button" class="btn btn-primary" onclick="saveDraft(true)" id="saveContinueBtn">
            Save &amp; Continue →
          </button>
        </div>

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

    <!-- ════ 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 id="feeCHF"><?= !empty($submission['preliminary_fee_chf']) ? number_format($submission['preliminary_fee_chf'],2).' CHF' : '—' ?></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 id="totalCHF"><?= !empty($submission['preliminary_fee_chf']) ? number_format($submission['preliminary_fee_chf'],2).' CHF' : '—' ?></span>
        </div>
        <p style="font-size:11px;color:var(--text-muted);margin-top:10px">Payment after acceptance</p>
      </div>

      <!-- Submission Steps -->
      <div class="sidebar-card">
        <div class="sidebar-title">📋 Submission Steps</div>
        <ul class="steps-list">
          <?php
          $steps = [
            ['Submission details',    true,  'step-active',  'Active'],
            ['Manuscript information',false, 'step-pending', 'To complete'],
            ['Related articles',      false, 'step-pending', 'To complete'],
            ['Authors & contributors',false, 'step-pending', 'To complete'],
            ['Editorial',             false, 'step-pending', 'To complete'],
            ['Statements',            false, 'step-pending', 'To complete'],
            ['Payment',               false, 'step-pending', 'To complete'],
          ];
          foreach ($steps as $i => [$sname, $sactive, $sclass, $sstatus]):
          ?>
          <li>
            <span class="step-num <?= $sactive ? 'step-active' : 'step-pending' ?>"><?= $i+1 ?></span>
            <span class="step-name"><?= $sname ?></span>
            <span class="step-status <?= $sactive ? 'step-status-active' : 'step-status-pending' ?>"><?= $sstatus ?></span>
          </li>
          <?php endforeach; ?>
        </ul>
      </div>

      <!-- Author Guidelines -->
      <div class="sidebar-card" style="text-align:center">
        <div style="font-size:22px;margin-bottom:8px">📖</div>
        <a href="#" style="color:var(--primary);font-size:13px;font-weight:600;text-decoration:none">
          Author Guidelines ↗
        </a>
        <p style="font-size:11.5px;color:var(--text-muted);margin-top:6px">
          Read before submitting your manuscript
        </p>
      </div>

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

<!-- ═══════ UNIFIED JOURNAL + SPECIALTY MODAL ═══════════════ -->
<!-- Single modal: grid slides left → specialty detail slides in from right -->
<div class="overlay" id="journalOverlay">
  <div class="modal journal-modal journal-modal-inner" style="max-width:900px;width:96%;overflow:hidden;max-height:90vh;display:flex;flex-direction:column">

    <!-- HEADER — changes dynamically -->
    <div class="modal-header journal-modal-top" id="journalModalHeader">
      <span class="modal-title" id="journalModalTitle">🔍 Search and select a journal</span>
      <button type="button" class="modal-close" onclick="closeJournalModal()">×</button>
    </div>

    <!-- TABS + SEARCH — hidden when specialty panel is shown -->
    <div id="journalTopControls">
      <div class="journal-tabs">
        <button class="journal-tab active" onclick="filterByCategory('all',this)" data-cat="all">All</button>
        <?php foreach ($categories as $cat): ?>
          <?php if ($cat['name'] !== 'All'): ?>
          <button class="journal-tab" onclick="filterByCategory(<?= $cat['category_id'] ?>,this)"
                  data-cat="<?= $cat['category_id'] ?>">
            <?= htmlspecialchars($cat['name']) ?>
          </button>
          <?php endif; ?>
        <?php endforeach; ?>
      </div>
      <div class="journal-search-bar">
        <div class="journal-search-wrap">
          <span class="journal-search-icon">🔍</span>
          <input type="text" class="journal-search-input" id="journalSearch"
                 placeholder="Search journals..."
                 oninput="searchJournals(this.value)">
        </div>
      </div>
    </div>

    <!-- SLIDE BODY: grid panel + specialty panel side by side -->
    <div class="journal-modal-body">

      <!-- PANEL 1: Journal Grid -->
      <div class="journal-grid-panel" id="journalGridPanel">
        <!-- filled by JS -->
      </div>

      <!-- PANEL 2: Specialty Detail (slides in from right) -->
      <div class="specialty-panel" id="specialtyPanel">
        <button class="sp-back-btn" onclick="backToJournalGrid()">
          ← Back to journals
        </button>
        <div class="sp-prefix">communeglobal in</div>
        <div class="sp-journal-name" id="spJournalName"></div>
        <div class="sp-desc" id="spJournalDesc"></div>
        <div class="sp-links">
          <a href="#" id="spLinkJournal">Journal</a>
          <a href="#" id="spLinkAbout">About</a>
          <a href="#" id="spLinkEditorial">Editorial Board</a>
        </div>
        <div class="sp-select-title">Select your specialty</div>
        <div class="sp-options-grid" id="spOptionsGrid"></div>
        <div class="sp-footer">
          <button class="btn btn-outline btn-sm" onclick="backToJournalGrid()">Cancel</button>
          <button class="btn btn-primary btn-sm" id="spSelectBtn"
                  onclick="confirmSpecialty()" disabled>
            Select
          </button>
        </div>
      </div>

    </div><!-- /.journal-modal-body -->
  </div>
</div>

<!-- ════════════════ TOAST CONTAINER ════════════════════════ -->
<div class="toast-container" id="toastContainer"></div>

<script>
/* ════════════════════════════════════════════════════════════
   STATE
════════════════════════════════════════════════════════════ */
let selectedJournal   = null;
let selectedSpecialty = null;
let autoSaveTimer     = null;
let currentCategory   = 'all';
let allJournals       = [];

/* ════════════════════════════════════════════════════════════
   ON LOAD
════════════════════════════════════════════════════════════ */
document.addEventListener('DOMContentLoaded', () => {
    loadJournals();
    setupDragDrop();
    // Auto-save every 30 seconds if form dirty
    document.getElementById('submissionForm')
            .addEventListener('input', scheduleAutoSave);
});

/* ════════════════════════════════════════════════════════════
   CONTINUE / NEW
════════════════════════════════════════════════════════════ */
function startNew() {
    const overlay = document.getElementById('continueOverlay');
    if (overlay) overlay.classList.remove('active');
    // Create fresh submission via AJAX
    fetch('ajax/save_draft.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=new'
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.href = 'submission.php?id=' + data.submission_id;
        }
    });
}

/* ════════════════════════════════════════════════════════════
   JOURNAL MODAL — 2-panel slide (grid → specialty)
════════════════════════════════════════════════════════════ */
function openJournalModal() {
    // Reset to grid view
    backToJournalGrid(true);
    document.getElementById('journalOverlay').classList.add('active');
    document.getElementById('journalSearch').value = '';
    document.getElementById('journalSearch').focus();
    renderJournalGrid(allJournals);
}
function closeJournalModal() {
    document.getElementById('journalOverlay').classList.remove('active');
}
function filterByCategory(catId, btn) {
    currentCategory = catId;
    document.querySelectorAll('.journal-tab').forEach(t => t.classList.remove('active'));
    btn.classList.add('active');
    filterAndRenderJournals(document.getElementById('journalSearch').value);
}
function searchJournals(q) { filterAndRenderJournals(q); }

function filterAndRenderJournals(q = '') {
    let list = allJournals;
    if (currentCategory !== 'all') {
        list = list.filter(j => j.category_id == currentCategory);
    }
    if (q.trim()) {
        const lq = q.toLowerCase();
        list = list.filter(j => j.name.toLowerCase().includes(lq));
    }
    renderJournalGrid(list);
}

function loadJournals() {
    const panel = document.getElementById('journalGridPanel');
    panel.innerHTML = '<div class="journal-loading">Loading journals...</div>';
    fetch('ajax/get_journals.php')
    .then(r => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
    })
    .then(data => {
        if (data.success && data.journals && data.journals.length > 0) {
            allJournals = data.journals;
            renderJournalGrid(allJournals);
        } else {
            panel.innerHTML = '<div class="journal-loading" style="color:#DC2626">No journals found — check DB data &amp; is_active column</div>';
        }
    })
    .catch(err => {
        panel.innerHTML = '<div class="journal-loading" style="color:#DC2626">Error: ' + err.message + '</div>';
        console.error('loadJournals error:', err);
    });
}

function renderJournalGrid(journals) {
    const panel = document.getElementById('journalGridPanel');
    if (!journals.length) {
        panel.innerHTML = '<div class="journal-loading">No journals found</div>';
        return;
    }
    panel.innerHTML = journals.map(j => `
      <div class="journal-card" onclick="selectJournal(${j.journal_id})">
        ${j.cover_image_url
          ? `<img src="${j.cover_image_url}" class="journal-card-img" alt="" loading="lazy">`
          : `<div class="journal-card-img" style="display:flex;align-items:center;justify-content:center;font-size:28px">📚</div>`}
        <div class="journal-card-body">
          <div class="journal-card-prefix">communeglobal in</div>
          <div class="journal-card-name">${escHtml(j.name)}</div>
          <div class="journal-card-count">${j.specialty_count} specialties</div>
        </div>
      </div>
    `).join('');
}

/* ── Journal card clicked → slide to specialty panel ─────── */
function selectJournal(journalId) {
    // Show loading in specialty panel
    document.getElementById('spJournalName').textContent  = 'Loading...';
    document.getElementById('spJournalDesc').textContent  = '';
    document.getElementById('spOptionsGrid').innerHTML    = '<div style="color:var(--text-muted);font-size:13px">Loading specialties...</div>';
    document.getElementById('spSelectBtn').disabled       = true;
    selectedSpecialty = null;
    // Slide to specialty panel immediately (before fetch, for snappy feel)
    showSpecialtyPanel();

    fetch('ajax/get_specialties.php?journal_id=' + journalId)
    .then(r => r.json())
    .then(data => {
        if (!data.success) { backToJournalGrid(); return; }
        selectedJournal = data.journal;
        renderSpecialtyPanel(data.journal, data.specialties);
    })
    .catch(() => backToJournalGrid());
}

function showSpecialtyPanel() {
    document.getElementById('journalGridPanel').classList.add('slide-out');
    document.getElementById('specialtyPanel').classList.add('slide-in');
    document.getElementById('journalTopControls').style.display = 'none';
    document.getElementById('journalModalTitle').textContent     = 'Select your specialty';
}

function backToJournalGrid(silent = false) {
    document.getElementById('journalGridPanel').classList.remove('slide-out');
    document.getElementById('specialtyPanel').classList.remove('slide-in');
    document.getElementById('journalTopControls').style.display = '';
    document.getElementById('journalModalTitle').textContent     = '🔍 Search and select a journal';
    if (!silent) selectedJournal = null;
}

function renderSpecialtyPanel(journal, specialties) {
    document.getElementById('spJournalName').textContent = journal.name;
    document.getElementById('spJournalDesc').textContent = journal.description || '';

    const grid = document.getElementById('spOptionsGrid');
    grid.innerHTML = specialties.map(sp => `
      <label class="sp-option" id="spOpt_${sp.specialty_id}" onclick="onSpecialtySelect(${sp.specialty_id}, event)">
        <input type="radio" name="specialty_radio" value="${sp.specialty_id}">
        ${escHtml(sp.name)}
      </label>
    `).join('');
}

function onSpecialtySelect(id, e) {
    // manually set radio (label click already does it, but let's sync state)
    const radio = document.querySelector(`#spOpt_${id} input[type=radio]`);
    if (radio) radio.checked = true;

    const sp = document.querySelector(`#spOpt_${id}`);
    const name = sp ? sp.textContent.trim() : '';
    selectedSpecialty = { specialty_id: id, name: name };

    document.querySelectorAll('.sp-option').forEach(el => el.classList.remove('selected'));
    document.getElementById('spOpt_' + id)?.classList.add('selected');
    document.getElementById('spSelectBtn').disabled = false;
}

function confirmSpecialty() {
    if (!selectedJournal || !selectedSpecialty) return;

    // 1. Update hidden form fields immediately
    document.getElementById('journalId').value   = selectedJournal.journal_id;
    document.getElementById('specialtyId').value = selectedSpecialty.specialty_id;

    // 2. Build journal selected card
    document.getElementById('journalPlaceholder').style.display = 'none';
    const card = document.getElementById('journalSelected');
    card.style.display = 'flex';
    const descText = (selectedSpecialty.description || selectedJournal.description || '');
    card.innerHTML = `
      <div class="journal-thumb" style="background:var(--blue-light);display:flex;align-items:center;justify-content:center;font-size:20px">📚</div>
      <div class="journal-info">
        <div class="jname">communeglobal in ${escHtml(selectedJournal.name)} — ${escHtml(selectedSpecialty.name)}</div>
        <div class="jdesc">${escHtml(descText.substring(0,180))}${descText.length > 180 ? '...' : ''}</div>
      </div>
      <button type="button" class="journal-remove" onclick="removeJournal()" title="Remove">×</button>
    `;

    closeJournalModal();
    loadArticleTypes(selectedSpecialty.specialty_id);
    loadResearchTopics(selectedSpecialty.specialty_id);
    updateProgress();

    // 3. IMMEDIATELY save draft (not delayed) so refresh keeps data
    saveDraftNow('Journal selected');
}

function removeJournal() {
    document.getElementById('journalId').value   = '';
    document.getElementById('specialtyId').value = '';
    document.getElementById('journalSelected').style.display    = 'none';
    document.getElementById('journalPlaceholder').style.display = 'block';
    document.getElementById('articleTypeSelect').innerHTML = '<option value="">Select or type to search...</option>';
    document.getElementById('articleTypeSelect').disabled = true;
    document.getElementById('articleTypeInfo').classList.remove('show');
    document.getElementById('researchTopicSelect').innerHTML = '<option value="">Select if applicable...</option>';
    document.getElementById('researchTopicSelect').disabled = true;
    document.getElementById('feeCHF').textContent   = '—';
    document.getElementById('totalCHF').textContent = '—';
    selectedJournal   = null;
    selectedSpecialty = null;
    updateProgress();
    scheduleAutoSave();
}


/* ════════════════════════════════════════════════════════════
   ARTICLE TYPES
════════════════════════════════════════════════════════════ */
function loadArticleTypes(specialtyId) {
    const sel = document.getElementById('articleTypeSelect');
    sel.innerHTML = '<option value="">Loading...</option>';
    fetch('ajax/get_article_types.php?specialty_id=' + specialtyId)
    .then(r => r.json())
    .then(data => {
        sel.innerHTML = '<option value="">Select or type to search...</option>';
        (data.article_types || []).forEach(at => {
            const opt = document.createElement('option');
            opt.value = at.article_type_id;
            opt.textContent = at.name;
            opt.dataset.desc    = at.description || '';
            opt.dataset.summary = at.summary_length || '';
            opt.dataset.figures = at.figures_tables_limit || '';
            opt.dataset.fee     = at.preliminary_fee_chf || '';
            sel.appendChild(opt);
        });
        sel.disabled = false;
    });
}

function onArticleTypeChange(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (!opt.value) {
        document.getElementById('articleTypeInfo').classList.remove('show');
        document.getElementById('feeCHF').textContent  = '—';
        document.getElementById('totalCHF').textContent = '—';
        return;
    }
    document.getElementById('atName').textContent    = opt.textContent;
    document.getElementById('atDesc').textContent    = opt.dataset.desc.substring(0,200);
    document.getElementById('atSummary').textContent = 'Summary: ' + opt.dataset.summary + ' words';
    document.getElementById('atFigures').textContent = 'Figures & tables: ' + opt.dataset.figures;
    document.getElementById('articleTypeInfo').classList.add('show');
    const fee = parseFloat(opt.dataset.fee) || 0;
    document.getElementById('feeCHF').textContent   = fee ? fee.toFixed(2) + ' CHF' : '—';
    document.getElementById('totalCHF').textContent = fee ? fee.toFixed(2) + ' CHF' : '—';
    updateProgress();
    saveDraftNow('Article type selected'); // immediate save
}

/* ════════════════════════════════════════════════════════════
   RESEARCH TOPICS
════════════════════════════════════════════════════════════ */
function loadResearchTopics(specialtyId) {
    const sel  = document.getElementById('researchTopicSelect');
    const hint = document.getElementById('researchTopicHint');
    sel.innerHTML = '<option value="">Loading...</option>';
    sel.disabled  = true;

    fetch('ajax/get_research_topics.php?specialty_id=' + specialtyId)
    .then(r => r.json())
    .then(data => {
        sel.innerHTML = '<option value="">Select if applicable...</option>';

        if (data.topics && data.topics.length > 0) {
            // Topics found — enable dropdown
            data.topics.forEach(t => {
                const opt = document.createElement('option');
                opt.value       = t.topic_id;
                opt.textContent = t.title;
                sel.appendChild(opt);
            });
            sel.disabled = false;
            if (hint) hint.textContent = data.topics.length + ' research topics available.';
        } else {
            // No topics for this specialty — still show as enabled with placeholder
            sel.disabled = false;
            sel.innerHTML = '<option value="">No research topics for this specialty</option>';
            if (hint) hint.textContent = 'No research topics available for this specialty.';
        }
    })
    .catch(err => {
        sel.disabled  = false;
        sel.innerHTML = '<option value="">Could not load topics</option>';
        console.error('loadResearchTopics error:', err);
    });
}

/* ════════════════════════════════════════════════════════════
   CHAR COUNT
════════════════════════════════════════════════════════════ */
function updateCharCount(el, counterId, max) {
    const remaining = max - el.value.length;
    document.getElementById(counterId).textContent = el.value.length;
    updateProgress();
}

/* ════════════════════════════════════════════════════════════
   FILE UPLOADS
════════════════════════════════════════════════════════════ */
function setupDragDrop() {
    document.querySelectorAll('.upload-zone').forEach(zone => {
        zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
        zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
        zone.addEventListener('drop', e => {
            e.preventDefault();
            zone.classList.remove('drag-over');
            const input = zone.querySelector('input[type=file]');
            if (input && e.dataTransfer.files.length) {
                input.files = e.dataTransfer.files;
                input.dispatchEvent(new Event('change'));
            }
        });
    });
}

function handleFileUpload(input, fileType, zoneId, listId) {
    const files = Array.from(input.files);
    if (!files.length) return;

    // Reset input so same file can be re-selected if needed
    input.value = '';

    // Show uploading state on zone
    const zone = document.getElementById(zoneId);
    if (zone) zone.style.opacity = '0.6';

    const subId = document.getElementById('submissionId').value;
    if (!subId) {
        // No draft yet — save draft first, then upload
        saveDraftSilent(() => uploadFiles(files, fileType, zoneId, listId));
    } else {
        uploadFiles(files, fileType, zoneId, listId);
    }
}

function uploadFiles(files, fileType, zoneId, listId) {
    const zone = document.getElementById(zoneId);

    files.forEach(file => {
        // Client-side size check
        if (file.size > 50 * 1024 * 1024) {
            showToast('File too large: ' + file.name + ' (max 50MB)', 'error');
            if (zone) zone.style.opacity = '1';
            return;
        }

        const fd = new FormData();
        // Always read submissionId fresh — may have been set by saveDraftSilent
        fd.append('submission_id', document.getElementById('submissionId').value);
        fd.append('file_type', fileType);
        fd.append('file', file);

        showToast('Uploading ' + file.name + '...', 'info');

        fetch('ajax/upload_file.php', { method: 'POST', body: fd })
        .then(r => {
            if (!r.ok) throw new Error('Server error: HTTP ' + r.status);
            return r.json();
        })
        .then(data => {
            if (zone) zone.style.opacity = '1';
            if (data.success) {
                // If server auto-created a draft, update our submission_id + URL
                if (data.submission_id) {
                    const newId = data.submission_id;
                    document.getElementById('submissionId').value = newId;
                    const url = new URL(window.location.href);
                    url.searchParams.set('id', newId);
                    history.replaceState({ submission_id: newId }, '', url.toString());
                }

                const icons = {
                    manuscript:'📄', manuscript_pdf:'📕',
                    figure:'🖼', supplementary:'📎', review_only:'👁'
                };
                const icon = icons[data.file_type] || icons[fileType] || '📄';
                const el   = document.createElement('div');
                el.className   = 'uploaded-file';
                el.dataset.id  = data.file_id;
                el.innerHTML   = `<span>${icon}</span>
                  <span class="fname">${escHtml(file.name)}</span>
                  <button type="button" class="fremove"
                          onclick="removeFile(${data.file_id},this)">×</button>`;
                document.getElementById(listId).appendChild(el);

                checkManuscriptWarning();
                showToast('✓ Uploaded: ' + file.name, 'success');
                updateProgress();
            } else {
                showToast('Upload failed: ' + (data.message || 'Unknown error'), 'error');
            }
        })
        .catch(err => {
            if (zone) zone.style.opacity = '1';
            showToast('Upload error: ' + err.message, 'error');
            console.error('Upload error:', err);
        });
    });
}

function removeFile(fileId, btn) {
    fetch('ajax/upload_file.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=delete&file_id=' + fileId
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            btn.closest('.uploaded-file').remove();
            checkManuscriptWarning();
            updateProgress();
        }
    });
}

function checkManuscriptWarning() {
    // Warn if only PDF uploaded without editable version
    const files = document.querySelectorAll('#manuscriptFiles .uploaded-file');
    const hasPdf  = Array.from(files).some(f => f.querySelector('.fname').textContent.toLowerCase().endsWith('.pdf'));
    const hasEdit = Array.from(files).some(f => {
        const n = f.querySelector('.fname').textContent.toLowerCase();
        return n.endsWith('.doc') || n.endsWith('.docx') || n.endsWith('.tex');
    });
    const warn = document.getElementById('manuscriptWarning');
    if (hasPdf && !hasEdit) { warn.classList.add('show'); }
    else                    { warn.classList.remove('show'); }
}

/* ════════════════════════════════════════════════════════════
   SAVE DRAFT
════════════════════════════════════════════════════════════ */
function scheduleAutoSave() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => saveDraftNow(), 1500); // 1.5s debounce
}

// saveDraftNow — immediate save with toast label (used after journal select, article type select)
function saveDraftNow(label = '') {
    const fd = collectFormData();
    fd.append('action', 'save');
    fetch('ajax/save_draft.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            const newId = data.submission_id;
            document.getElementById('submissionId').value = newId;
            updateProgress(data.completion_score);
            showSaveIndicator();
            // Update browser URL with ?id= so refresh reloads this draft
            const url = new URL(window.location.href);
            url.searchParams.set('id', newId);
            history.replaceState({ submission_id: newId }, '', url.toString());
        } else {
            console.warn('saveDraftNow failed:', data.message);
        }
    })
    .catch(err => console.error('saveDraftNow error:', err));
}

// saveDraftSilent — auto-save with callback (used before file upload)
function saveDraftSilent(callback) {
    const fd = collectFormData();
    fd.append('action', 'save');
    fetch('ajax/save_draft.php', { method: 'POST', body: fd })
    .then(r => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
    })
    .then(data => {
        if (data.success) {
            const newId = data.submission_id;
            document.getElementById('submissionId').value = newId;
            showSaveIndicator();
            updateProgress(data.completion_score);
            // Update URL so refresh works
            const url = new URL(window.location.href);
            url.searchParams.set('id', newId);
            history.replaceState({ submission_id: newId }, '', url.toString());
            if (callback) callback();
        } else {
            console.warn('saveDraftSilent failed:', data.message);
            // Still try callback if subId already set
            const existingId = document.getElementById('submissionId').value;
            if (existingId && callback) callback();
        }
    })
    .catch(err => {
        console.error('saveDraftSilent error:', err);
        // Still try callback if subId already set
        const existingId = document.getElementById('submissionId').value;
        if (existingId && callback) callback();
    });
}

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

    const fd = collectFormData();
    fd.append('action', andContinue ? 'save_continue' : 'save');

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

function collectFormData() {
    const fd = new FormData();
    fd.append('submission_id',    document.getElementById('submissionId').value);
    fd.append('journal_id',       document.getElementById('journalId').value);
    fd.append('specialty_id',     document.getElementById('specialtyId').value);
    fd.append('article_type_id',  document.getElementById('articleTypeSelect').value);
    fd.append('research_topic_id',document.getElementById('researchTopicSelect').value);
    fd.append('scope_statement',  document.getElementById('scopeStatement').value);
    return fd;
}

/* ════════════════════════════════════════════════════════════
   PROGRESS
════════════════════════════════════════════════════════════ */
function updateProgress(score) {
    if (score === undefined) {
        // Calculate locally
        let filled = 0, total = 4;
        if (document.getElementById('journalId').value)     filled++;
        if (document.getElementById('articleTypeSelect').value) filled++;
        if (document.getElementById('scopeStatement').value.trim()) filled++;
        const files = document.querySelectorAll('#manuscriptFiles .uploaded-file');
        if (files.length) filled++;
        score = Math.round((filled / total) * 100);
    }
    document.getElementById('progressFill').style.width = score + '%';
    document.getElementById('progressPct').textContent  = score + '%';
    document.getElementById('qualityBadge').textContent = score + '% Complete';
}

function showSaveIndicator() {
    const el = document.getElementById('saveIndicator');
    el.classList.add('show');
    setTimeout(() => el.classList.remove('show'), 3000);
}

/* ════════════════════════════════════════════════════════════
   TOAST
════════════════════════════════════════════════════════════ */
function showToast(msg, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<span>${type==='success'?'✓':type==='error'?'✗':'ℹ'}</span> ${escHtml(msg)}`;
    container.appendChild(toast);
    requestAnimationFrame(() => { requestAnimationFrame(() => toast.classList.add('show')); });
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 400);
    }, 3500);
}

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

// Close modals on overlay click
document.querySelectorAll('.overlay').forEach(ov => {
    ov.addEventListener('click', e => {
        if (e.target === ov) ov.classList.remove('active');
    });
});
// ESC key
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') {
        document.querySelectorAll('.overlay.active').forEach(ov => ov.classList.remove('active'));
    }
});
</script>
</div>