<?php
// ============================================================
//  submission.php  —  SCREEN 1: Submission Details
// ============================================================
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  = 'Submit Manuscript';
$activePage = 'submission';

// ── INLINE AJAX: Save new research topic ─────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'save_research_topic') {
    header('Content-Type: application/json');
    try {
        $title        = trim($_POST['title']        ?? '');
        $specialty_id = (int)($_POST['specialty_id'] ?? 0);
        if ($title === '') { echo json_encode(['success'=>false,'message'=>'Topic title is required.']); exit; }
        if ($specialty_id <= 0) { echo json_encode(['success'=>false,'message'=>'Invalid specialty.']); exit; }
        $chk = db()->prepare("SELECT topic_id FROM research_topics WHERE specialty_id = ? AND title = ?");
        $chk->execute([$specialty_id, $title]);
        if ($existing = $chk->fetch()) {
            echo json_encode(['success'=>true,'topic_id'=>$existing['topic_id'],'duplicate'=>true]); exit;
        }
        $ins = db()->prepare("INSERT INTO research_topics (specialty_id, title, is_active) VALUES (?, ?, 1)");
        $ins->execute([$specialty_id, $title]);
        echo json_encode(['success'=>true,'topic_id'=>(int)db()->lastInsertId()]);
    } catch (Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

// ── Data loading ──────────────────────────────────────────────
$stmt = db()->prepare("SELECT * FROM submissions WHERE user_id = ? AND is_draft = 1 ORDER BY updated_at DESC LIMIT 1");
$stmt->execute([$user_id]);
$existingDraft = $stmt->fetch();

$submission_id = (int)($_GET['id'] ?? 0);
$submission    = null;

if ($submission_id) {
    $stmt = db()->prepare(
        "SELECT s.*,
                j.name AS journal_name, j.description AS journal_desc, j.cover_image_url,
                sp.name AS specialty_name, sp.description AS specialty_desc,
                at.name AS article_type_name, at.description AS at_description,
                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();
}

$categories = db()->query("SELECT * FROM journal_categories ORDER BY display_order")->fetchAll();

$uploadedFiles = [];
if ($submission_id) {
    $stmt = db()->prepare("SELECT * FROM submission_files WHERE submission_id = ?");
    $stmt->execute([$submission_id]);
    foreach ($stmt->fetchAll() as $f) { $uploadedFiles[$f['file_type']][] = $f; }
}

$submission = $submission ?: [];

$researchTopics = [];
if ($submission && $submission['specialty_id']) {
    $stmt = db()->prepare("SELECT * FROM research_topics WHERE specialty_id = ? AND is_active = 1");
    $stmt->execute([$submission['specialty_id']]);
    $researchTopics = $stmt->fetchAll();
}

function getCompletionScore(?array $sub): int {
    if (!$sub) return 0;
    $fields = ['journal_id','specialty_id','article_type_id','scope_statement'];
    $filled = 0;
    foreach ($fields as $f) { if (!empty($sub[$f])) $filled++; }
    return (int)(($filled / count($fields)) * 100);
}
$score = getCompletionScore($submission);

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

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

:root {
  --primary-light:#FFF0EA; --primary-dark:#BF4520; --border-focus:#E05A2B;
  --shadow-sm:0 1px 3px rgba(0,0,0,.08); --shadow-md:0 4px 16px rgba(0,0,0,.10);
  --shadow-lg:0 12px 40px rgba(0,0,0,.14); --radius:10px; --radius-lg:16px;
  --font-display:'Fraunces',serif;
}
.page-wrap       { max-width:1100px; margin:28px auto; padding:0 22px; }
.page-header     { margin-bottom:22px; }
.page-title      { font-family:var(--font-display,'serif'); font-size:24px; font-weight:700; color:var(--blue); }
.page-subtitle   { color:var(--muted); margin-top:4px; font-size:13.5px; }
.progress-bar-wrap { background:var(--white); border:1px solid var(--border); border-radius:var(--radius); padding:14px 18px; margin-bottom:18px; display:flex; align-items:center; gap:14px; box-shadow:var(--shadow-sm); flex-wrap:wrap; }
.progress-label  { font-size:13px; font-weight:600; color:var(--text); white-space:nowrap; }
.progress-track  { flex:1; min-width:100px; height:8px; background:#E5E7EB; border-radius:99px; overflow:hidden; }
.progress-fill   { height:100%; background:linear-gradient(90deg,var(--primary),#F08040); border-radius:99px; transition:width .5s ease; }
.progress-pct    { font-size:13px; font-weight:700; color:var(--primary); min-width:36px; text-align:right; }
.quality-badge   { padding:4px 12px; border-radius:99px; font-size:11px; font-weight:700; background:var(--primary-light); color:var(--primary); }
.save-indicator  { font-size:11.5px; color:var(--muted); display:flex; align-items:center; gap:5px; opacity:0; transition:opacity .3s; }
.save-indicator.show { opacity:1; }
.save-dot        { width:6px; height:6px; border-radius:50%; background:#16A34A; }
.main-grid       { display:grid; grid-template-columns:1fr 300px; gap:20px; align-items:start; }
@media(max-width:880px){ .main-grid { grid-template-columns:1fr; } }
.card            { background:var(--white); border:1px solid var(--border); border-radius:var(--radius-lg); box-shadow:var(--shadow-sm); overflow:hidden; margin-bottom:16px; }
.card-header     { padding:16px 20px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; }
.card-title      { font-weight:700; font-size:14.5px; color:var(--blue); }
.card-badge      { font-size:11px; font-weight:600; padding:3px 10px; border-radius:99px; }
.badge-incomplete{ background:#FEF3C7; color:#92400E; }
.badge-complete  { background:#DCFCE7; color:#166534; }
.card-body       { padding:20px; }
.form-group      { margin-bottom:16px; }
.form-label      { display:block; font-size:12.5px; font-weight:600; color:var(--text); margin-bottom:6px; }
.form-label .optional  { font-weight:400; color:var(--muted); font-size:11px; margin-left:4px; }
.form-label .info-icon { display:inline-flex; align-items:center; justify-content:center; width:14px; height:14px; border-radius:50%; background:var(--muted); color:#fff; font-size:9px; margin-left:4px; cursor:help; }
.form-input,.form-select,.form-textarea { width:100%; padding:9px 13px; border:1.5px solid var(--border); border-radius:var(--radius); font-family:var(--font); font-size:13.5px; color:var(--text); background:var(--white); transition:border-color .2s,box-shadow .2s; outline:none; }
.form-input:focus,.form-select:focus,.form-textarea:focus { border-color:var(--border-focus); box-shadow:0 0 0 3px rgba(224,90,43,.12); }
.form-textarea   { resize:vertical; min-height:88px; }
.char-count      { font-size:11px; color:var(--muted); text-align:right; margin-top:3px; }
.form-hint       { font-size:11.5px; color:var(--muted); margin-top:5px; line-height:1.5; }
.form-error      { font-size:11.5px; color:#DC2626; margin-top:4px; display:none; }
.form-error.show { display:block; }
.field-error     { border-color:#DC2626!important; box-shadow:0 0 0 3px rgba(220,38,38,.12)!important; }
.journal-selected    { border:1.5px solid var(--border); border-radius:var(--radius); padding:12px 14px; background:var(--blue-light); display:flex; align-items:flex-start; gap:12px; position:relative; }
.journal-thumb       { width:42px; height:42px; border-radius:6px; object-fit:cover; flex-shrink:0; background:#ddd; }
.journal-info        { flex:1; }
.journal-info .jname { font-size:13px; font-weight:700; color:var(--blue); }
.journal-info .jspecialty { font-size:11.5px; color:var(--muted); margin-top:2px; }
.journal-info .jdesc      { font-size:11px; color:var(--muted); margin-top:4px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
.journal-remove  { position:absolute; top:8px; right:8px; width:20px; height:20px; border:none; background:none; cursor:pointer; color:var(--muted); font-size:16px; display:flex; align-items:center; justify-content:center; border-radius:50%; transition:background .2s; }
.journal-remove:hover { background:#FFE4DA; color:var(--primary); }
.journal-placeholder { border:1.5px dashed var(--border); border-radius:var(--radius); padding:14px; text-align:center; cursor:pointer; transition:all .2s; color:var(--muted); font-size:13px; }
.journal-placeholder:hover { border-color:var(--primary); background:var(--primary-light); color:var(--primary); }
.article-type-info      { margin-top:10px; padding:12px 14px; background:#FFF8F5; border:1px solid #FDDCCC; border-radius:var(--radius); display:none; }
.article-type-info.show { display:block; }
.at-name         { font-weight:700; font-size:13px; color:var(--primary); }
.at-desc         { font-size:11.5px; color:var(--muted); margin-top:4px; line-height:1.6; }
.at-guidelines   { display:flex; gap:12px; margin-top:8px; flex-wrap:wrap; }
.at-guideline-item { font-size:11px; font-weight:600; color:var(--blue); background:var(--blue-light); padding:3px 8px; border-radius:4px; }
.rt-wrap         { display:flex; flex-direction:column; gap:8px; }
.rt-add-toggle   { display:inline-flex; align-items:center; gap:5px; font-size:12px; font-weight:600; color:var(--primary); cursor:pointer; background:none; border:1.5px dashed var(--primary); border-radius:var(--radius); padding:6px 12px; transition:all .2s; width:fit-content; }
.rt-add-toggle:hover { background:var(--primary-light); }
.rt-add-form     { background:#FFF8F5; border:1px solid #FDDCCC; border-radius:var(--radius); padding:12px 14px; display:none; flex-direction:column; gap:8px; }
.rt-add-form.show{ display:flex; }
.rt-add-row      { display:flex; gap:8px; align-items:flex-end; flex-wrap:wrap; }
.rt-add-row .form-input { flex:1; min-width:200px; padding:8px 12px; font-size:13px; }
.rt-add-hint     { font-size:11px; color:var(--muted); }
.file-upload-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-top:14px; }
@media(max-width:600px){ .file-upload-grid { grid-template-columns:1fr; } }
.upload-zone     { border:1.5px dashed var(--border); border-radius:var(--radius); padding:18px 14px; text-align:center; cursor:pointer; transition:all .2s; position:relative; background:var(--white); }
.upload-zone:hover,.upload-zone.drag-over { border-color:var(--primary); background:var(--primary-light); }
.upload-zone.zone-error { border-color:#DC2626!important; background:#FFF5F5!important; }
.upload-zone input[type=file] { position:absolute; inset:0; opacity:0; cursor:pointer; width:100%; height:100%; }
.upload-icon     { font-size:26px; margin-bottom:6px; display:block; }
.upload-title    { font-size:12.5px; font-weight:700; color:var(--text); margin-bottom:3px; }
.upload-subtitle { font-size:11px; color:var(--muted); }
.upload-btn-text { font-size:11.5px; color:var(--primary); font-weight:600; margin-top:6px; display:block; }
.upload-optional { font-size:10px; color:var(--muted); position:absolute; top:6px; right:8px; background:#F3F4F6; padding:2px 6px; border-radius:4px; }
.uploaded-file   { display:flex; align-items:center; gap:8px; padding:6px 10px; background:var(--blue-light); border-radius:6px; margin-top:6px; font-size:12px; }
.uploaded-file .fname  { flex:1; font-weight:500; color:var(--blue); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.uploaded-file .fremove{ background:none; border:none; color:#DC2626; cursor:pointer; font-size:16px; line-height:1; padding:0; }
.upload-warning  { display:none; margin-top:6px; font-size:11px; color:#D97706; font-weight:600; }
.upload-warning.show { display:block; }
.btn             { display:inline-flex; align-items:center; gap:8px; padding:9px 18px; border-radius:var(--radius); font-family:var(--font); font-size:13.5px; font-weight:600; cursor:pointer; transition:all .2s; border:none; text-decoration:none; white-space:nowrap; }
.btn:disabled    { opacity:.5; cursor:not-allowed; }
.btn-primary     { background:var(--primary); color:#fff; }
.btn-primary:hover:not(:disabled) { background:var(--primary-dark); box-shadow:0 4px 12px rgba(224,90,43,.3); }
.btn-outline     { background:var(--white); color:var(--text); border:1.5px solid var(--border); }
.btn-outline:hover:not(:disabled) { border-color:var(--primary); color:var(--primary); }
.btn-blue        { background:var(--blue); color:#fff; }
.btn-blue:hover:not(:disabled) { background:#142F52; }
.btn-sm  { padding:7px 14px; font-size:12.5px; }
.btn-xs  { padding:5px 10px; font-size:12px; }
.form-actions { display:flex; justify-content:flex-end; gap:10px; padding-top:16px; border-top:1px solid var(--border); margin-top:20px; }
.sidebar-card  { background:var(--white); border:1px solid var(--border); border-radius:var(--radius-lg); padding:16px 18px; box-shadow:var(--shadow-sm); margin-bottom:14px; }
.sidebar-title { font-size:13px; font-weight:700; color:var(--blue); margin-bottom:12px; }
.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; }
.steps-list { list-style:none; }
.steps-list li { display:flex; align-items:center; gap:10px; padding:7px 0; font-size:12.5px; border-bottom:1px solid var(--border); }
.steps-list li:last-child { border-bottom:none; }
.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:#16A34A; color:#fff; }
.step-pending    { background:#E5E7EB; color:var(--muted); }
.step-name       { flex:1; font-weight:500; }
.step-status-done    { color:#16A34A; font-size:10px; font-weight:600; }
.step-status-active  { color:var(--primary); font-size:10px; font-weight:600; }
.step-status-pending { color:var(--muted); font-size:10px; font-weight:600; }
.toast-container { position:fixed; bottom:24px; right:24px; z-index:9999; display:flex; flex-direction:column; gap:8px; }
.toast           { padding:12px 18px; border-radius:var(--radius); font-size:13px; font-weight:500; box-shadow:var(--shadow-lg); display:flex; align-items:center; gap:10px; transform:translateX(120%); transition:transform .3s ease; max-width:320px; }
.toast.show      { transform:translateX(0); }
.toast-success   { background:#166534; color:#fff; }
.toast-error     { background:#DC2626; color:#fff; }
.toast-info      { background:var(--blue); color:#fff; }
.overlay { position:fixed; inset:0; background:rgba(0,0,0,.48); z-index:1000; display:none; align-items:center; justify-content:center; backdrop-filter:blur(4px); }
.overlay.active { display:flex; }
.modal { background:var(--white); border-radius:var(--radius-lg); box-shadow:var(--shadow-lg); width:90%; max-width:520px; overflow:hidden; animation:modalIn .25s ease; }
@keyframes modalIn { from{opacity:0;transform:scale(.92)} to{opacity:1;transform:scale(1)} }
.modal-header { padding:18px 22px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; }
.modal-title  { font-size:17px; font-weight:700; color:var(--blue); }
.modal-close  { background:none; border:none; font-size:22px; color:var(--muted); cursor:pointer; line-height:1; padding:0; }
.modal-close:hover { color:var(--primary); }
.modal-body   { padding:22px; }
.modal-footer { padding:14px 22px; border-top:1px solid var(--border); display:flex; justify-content:flex-end; gap:10px; background:#FAFAFA; }
.continue-popup { display:flex; flex-direction:column; align-items:center; text-align:center; gap:14px; }
.continue-popup h2 { font-size:20px; font-weight:700; color:var(--blue); }
.continue-popup p  { font-size:13.5px; color:var(--muted); max-width:320px; }
.continue-btns { display:flex; gap:12px; }
.journal-modal  { max-width:860px; }
.journal-tabs   { display:flex; gap:4px; flex-wrap:wrap; padding:0 22px 14px; border-bottom:1px solid var(--border); }
.journal-tab    { padding:5px 14px; border-radius:99px; font-size:12.5px; font-weight:500; cursor:pointer; border:1.5px solid var(--border); background:var(--white); transition:all .15s; color:var(--muted); }
.journal-tab.active { background:var(--blue); color:#fff; border-color:var(--blue); }
.journal-search-bar   { padding:14px 22px; border-bottom:1px solid var(--border); }
.journal-search-input { width:100%; padding:9px 13px 9px 36px; border:1.5px solid var(--border); border-radius:var(--radius); font-size:13.5px; font-family:var(--font); outline:none; transition:border-color .2s; }
.journal-search-input:focus { border-color:var(--primary); }
.journal-search-wrap { position:relative; }
.journal-search-icon { position:absolute; left:12px; top:50%; transform:translateY(-50%); color:var(--muted); pointer-events:none; }
.journal-card     { border:1.5px solid var(--border); border-radius:var(--radius); overflow:hidden; cursor:pointer; transition:all .2s; background:var(--white); }
.journal-card:hover { border-color:var(--primary); box-shadow:var(--shadow-md); transform:translateY(-2px); }
.journal-card-img  { width:100%; height:70px; object-fit:cover; background:#ddd; display:block; }
.journal-card-body { padding:8px 10px; }
.journal-card-prefix { font-size:9px; color:var(--muted); font-weight:600; text-transform:uppercase; letter-spacing:.05em; }
.journal-card-name   { font-size:12px; font-weight:700; color:var(--blue); margin-top:1px; line-height:1.3; }
.journal-card-count  { font-size:10px; color:var(--muted); margin-top:3px; }
.journal-loading { padding:40px; text-align:center; color:var(--muted); font-size:13px; }
.journal-modal-inner { display:flex; flex-direction:column; }
.journal-modal-body  { flex:1; overflow:hidden; position:relative; min-height:420px; max-height:calc(90vh - 160px); }
.journal-grid-panel  { position:absolute; inset:0; overflow-y:auto; padding:16px 22px; display:grid; grid-template-columns:repeat(3,1fr); gap:12px; transition:transform .32s ease,opacity .32s ease; align-content:start; }
.journal-grid-panel.slide-out { transform:translateX(-110%); opacity:0; pointer-events:none; }
@media(max-width:600px){ .journal-grid-panel { grid-template-columns:1fr 1fr; } }
.specialty-panel  { position:absolute; inset:0; overflow-y:auto; transform:translateX(110%); opacity:0; pointer-events:none; transition:transform .32s ease,opacity .32s ease; padding:26px 30px 20px; }
.specialty-panel.slide-in { transform:translateX(0); opacity:1; pointer-events:auto; }
.sp-back-btn  { display:inline-flex; align-items:center; gap:6px; background:none; border:none; cursor:pointer; font-size:13px; color:var(--muted); font-family:var(--font); padding:0; margin-bottom:18px; transition:color .2s; }
.sp-back-btn:hover { color:var(--primary); }
.sp-prefix      { font-size:13px; color:var(--muted); margin-bottom:2px; }
.sp-journal-name{ font-size:22px; font-weight:700; color:var(--text); margin-bottom:10px; line-height:1.2; }
.sp-desc        { font-size:13px; color:var(--muted); line-height:1.7; margin-bottom:12px; }
.sp-links       { display:flex; gap:16px; margin-bottom:20px; }
.sp-links a     { font-size:13px; color:var(--primary); font-weight:600; text-decoration:none; border-bottom:1.5px solid rgba(224,90,43,.35); padding-bottom:1px; }
.sp-select-title  { font-size:14px; font-weight:700; color:var(--text); margin-bottom:12px; }
.sp-options-grid  { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:18px; }
@media(max-width:520px){ .sp-options-grid { grid-template-columns:1fr; } }
.sp-option { display:flex; align-items:flex-start; gap:10px; padding:12px 14px; border:1.5px solid var(--border); border-radius:var(--radius); cursor:pointer; transition:all .15s; font-size:13px; line-height:1.4; color:var(--text); user-select:none; }
.sp-option:hover { border-color:var(--primary); background:var(--primary-light); }
.sp-option input[type=radio] { accent-color:var(--primary); width:16px; height:16px; margin-top:1px; flex-shrink:0; cursor:pointer; }
.sp-option.selected { border-color:var(--primary); background:var(--primary-light); font-weight:600; color:var(--primary); }
.sp-footer { display:flex; justify-content:flex-end; gap:10px; padding-top:14px; border-top:1px solid var(--border); }
.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>

<?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(--muted)">Last saved: <?= date('d M Y, H:i', strtotime($existingDraft['updated_at'])) ?></p>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<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>

  <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="quality-badge" id="qualityBadge"><?= $score ?>% Complete</span>
    <span class="save-indicator" id="saveIndicator"><span class="save-dot"></span> Saved</span>
  </div>

  <div class="main-grid">
    <div>
      <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'] ?? '' ?>">

        <!-- CARD 1: Journal & Article Type -->
        <div class="card">
          <div class="card-header">
            <span class="card-title">📰 Journal &amp; 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">

            <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(ltrim($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">×</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>

            <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']]);
                    foreach ($atStmt->fetchAll() 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>
              <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 &amp; tables: <?= $submission['figures_tables_limit'] ?? '' ?></span>
                </div>
              </div>
            </div>

            <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-error" id="scopeError">Please provide a scope statement</div>
              <div class="form-hint">Selecting the best-matching journal and specialty will ensure the fastest peer review process.</div>
            </div>

            <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 or create a new one">i</span></label>
              <div class="rt-wrap">
                <select class="form-select" name="research_topic_id" id="researchTopicSelect">
                  <option value="">— 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; ?>
                  <?php if (empty($researchTopics)): ?>
                    <option value="" disabled>No topics available for this specialty yet</option>
                  <?php endif; ?>
                </select>
                <button type="button" class="rt-add-toggle" onclick="toggleAddTopic()">
                  <span id="rtToggleIcon">＋</span> Add new research topic
                </button>
                <div class="rt-add-form" id="rtAddForm">
                  <p class="rt-add-hint">Enter a new research topic title. It will be saved and added to the list.</p>
                  <div class="rt-add-row">
                    <input type="text" class="form-input" id="rtNewTitle" placeholder="e.g. Climate Policy in Developing Nations" maxlength="500">
                    <button type="button" class="btn btn-primary btn-xs" onclick="saveNewTopic()">Save &amp; Select</button>
                    <button type="button" class="btn btn-outline btn-xs" onclick="toggleAddTopic()">Cancel</button>
                  </div>
                </div>
              </div>
              <div class="form-hint" id="rtHint">
                <?= empty($researchTopics) ? 'No topics yet for this specialty — you can create one using "Add new research topic".' : 'Select an existing topic or create a new one.' ?>
              </div>
            </div>

          </div>
        </div>

        <!-- CARD 2: File Uploads -->
        <div class="card">
          <div class="card-header">
            <span class="card-title">📁 Upload Files</span>
            <span class="card-badge <?= !empty($uploadedFiles['manuscript']) ? 'badge-complete' : 'badge-incomplete' ?>" id="fileBadge">
              <?= !empty($uploadedFiles['manuscript']) ? '✓ Completed' : '⚠ Incomplete' ?>
            </span>
          </div>
          <div class="card-body">
            <div class="file-upload-grid">
              <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,.rtf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf"
                         onchange="handleFileUpload(this,'manuscript','manuscriptZone','manuscriptFiles')">
                  <span class="upload-icon">📄</span>
                  <div class="upload-title">Drag and drop</div>
                  <div class="upload-subtitle">DOC · DOCX · RTF only<br>Max 50 MB</div>
                  <span class="upload-btn-text">Browse files</span>
                </div>
                <div class="upload-warning" id="manuscriptWarning">⚠ Only Word/RTF files allowed: .doc, .docx, .rtf</div>
                <div class="form-error" id="manuscriptError" style="margin-top:4px">Please upload your manuscript file</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; ?>
                </div>
              </div>
              <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>
              <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>
              <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>
          </div>
        </div>

        <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>
    </div>

    <!-- SIDEBAR -->
    <div>
      <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(--muted);margin-top:10px">Payment after acceptance</p>
      </div>
      <div class="sidebar-card">
        <div class="sidebar-title">📋 Submission Steps</div>
        <ul class="steps-list">
          <?php
          $steps=[['Submission details',true],['Manuscript information',false],['Related articles',false],['Authors & contributors',false],['Editorial',false],['Statements',false],['Payment',false]];
          foreach($steps as $i=>[$sname,$sactive]):
          ?>
          <li>
            <span class="step-num <?=$sactive?'step-active':'step-pending'?>"><?=$i+1?></span>
            <span class="step-name"><?=htmlspecialchars($sname)?></span>
            <span class="<?=$sactive?'step-status-active':'step-status-pending'?>"><?=$sactive?'Active':'To complete'?></span>
          </li>
          <?php endforeach; ?>
        </ul>
      </div>
      <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(--muted);margin-top:6px">Read before submitting your manuscript</p>
      </div>
    </div>
  </div>
</div>

<!-- JOURNAL + SPECIALTY MODAL -->
<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">
    <div class="modal-header" id="journalModalHeader">
      <span class="modal-title" id="journalModalTitle">🔍 Search and select a journal</span>
      <button type="button" class="modal-close" onclick="closeJournalModal()">×</button>
    </div>
    <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>
    <div class="journal-modal-body">
      <div class="journal-grid-panel" id="journalGridPanel"></div>
      <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>
  </div>
</div>
<div class="toast-container" id="toastContainer"></div>

<script>
let selectedJournal=null,selectedSpecialty=null,autoSaveTimer=null,currentCategory='all',allJournals=[];

document.addEventListener('DOMContentLoaded',()=>{
    loadJournals(); setupDragDrop();
    document.getElementById('submissionForm').addEventListener('input',scheduleAutoSave);
});

function startNew(){
    const o=document.getElementById('continueOverlay'); if(o)o.classList.remove('active');
    fetch('ajax/save_draft.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=new'})
    .then(r=>r.json()).then(d=>{ if(d.success)window.location.href='submission.php?id='+d.submission_id; });
}
function openJournalModal(){ 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 p=document.getElementById('journalGridPanel'); p.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(d=>{ if(d.success&&d.journals&&d.journals.length){allJournals=d.journals;renderJournalGrid(allJournals);}
    else p.innerHTML='<div class="journal-loading" style="color:#DC2626">No journals found</div>'; })
    .catch(err=>{ p.innerHTML='<div class="journal-loading" style="color:#DC2626">Error: '+err.message+'</div>'; });
}
function renderJournalGrid(journals){
    const p=document.getElementById('journalGridPanel');
    if(!journals.length){p.innerHTML='<div class="journal-loading">No journals found</div>';return;}
    p.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('');
}
function selectJournal(jid){
    document.getElementById('spJournalName').textContent='Loading...';
    document.getElementById('spOptionsGrid').innerHTML='<div style="color:var(--muted);font-size:13px">Loading specialties...</div>';
    document.getElementById('spSelectBtn').disabled=true; selectedSpecialty=null; showSpecialtyPanel();
    fetch('ajax/get_specialties.php?journal_id='+jid).then(r=>r.json())
    .then(d=>{ if(!d.success){backToJournalGrid();return;} selectedJournal=d.journal; renderSpecialtyPanel(d.journal,d.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||'';
    document.getElementById('spOptionsGrid').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){
    const r=document.querySelector(`#spOpt_${id} input[type=radio]`); if(r)r.checked=true;
    const sp=document.querySelector(`#spOpt_${id}`); const name=sp?sp.textContent.trim():'';
    selectedSpecialty={specialty_id:id,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;
    document.getElementById('journalId').value=selectedJournal.journal_id;
    document.getElementById('specialtyId').value=selectedSpecialty.specialty_id;
    document.getElementById('journalPlaceholder').style.display='none';
    const card=document.getElementById('journalSelected'); card.style.display='flex';
    const desc=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(desc.substring(0,180))}${desc.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(); 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');
    const rt=document.getElementById('researchTopicSelect'); rt.innerHTML='<option value="">— Select if applicable —</option><option value="" disabled>No topics available — select a specialty first</option>';
    document.getElementById('rtHint').textContent='Select a specialty first to see available research topics.';
    document.getElementById('feeCHF').textContent='—'; document.getElementById('totalCHF').textContent='—';
    selectedJournal=null; selectedSpecialty=null; updateProgress(); scheduleAutoSave();
}
function loadArticleTypes(specId){
    const sel=document.getElementById('articleTypeSelect'); sel.innerHTML='<option value="">Loading...</option>';
    fetch('ajax/get_article_types.php?specialty_id='+specId).then(r=>r.json()).then(d=>{
        sel.innerHTML='<option value="">Select or type to search...</option>';
        (d.article_types||[]).forEach(at=>{ const o=document.createElement('option'); o.value=at.article_type_id; o.textContent=at.name; o.dataset.desc=at.description||''; o.dataset.summary=at.summary_length||''; o.dataset.figures=at.figures_tables_limit||''; o.dataset.fee=at.preliminary_fee_chf||''; sel.appendChild(o); });
        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');
}
function loadResearchTopics(specId){
    fetch('ajax/get_research_topics.php?specialty_id='+specId).then(r=>r.json()).then(d=>{
        const sel=document.getElementById('researchTopicSelect'); const hint=document.getElementById('rtHint');
        sel.innerHTML='<option value="">— Select if applicable —</option>';
        if(d.topics&&d.topics.length){ d.topics.forEach(t=>{ const o=document.createElement('option'); o.value=t.topic_id; o.textContent=t.title; sel.appendChild(o); }); hint.textContent='Select an existing topic or create a new one.'; }
        else{ sel.innerHTML+='<option value="" disabled>No topics available for this specialty yet</option>'; hint.textContent='No topics yet — you can create one using "Add new research topic".'; }
        sel.disabled=false;
    });
}
function toggleAddTopic(){
    const f=document.getElementById('rtAddForm'); const i=document.getElementById('rtToggleIcon'); const open=f.classList.toggle('show');
    i.textContent=open?'−':'＋'; if(open)document.getElementById('rtNewTitle').focus(); else document.getElementById('rtNewTitle').value='';
}
function saveNewTopic(){
    const title=document.getElementById('rtNewTitle').value.trim(); const subId=document.getElementById('submissionId').value; const specId=document.getElementById('specialtyId').value;
    if(!title){showToast('Please enter a topic title.','error');return;} if(!specId){showToast('Please select a journal & specialty first.','error');return;}
    const fd=new FormData(); fd.append('title',title); fd.append('specialty_id',specId); fd.append('submission_id',subId);
    fetch('submission.php?ajax=save_research_topic',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.success){ const sel=document.getElementById('researchTopicSelect'); Array.from(sel.options).forEach(o=>{if(o.disabled)o.remove();}); const opt=document.createElement('option'); opt.value=d.topic_id; opt.textContent=title; opt.selected=true; sel.appendChild(opt); document.getElementById('rtHint').textContent='Select an existing topic or create a new one.'; showToast('✓ Research topic added and selected!','success'); toggleAddTopic(); scheduleAutoSave(); }
        else showToast('Error: '+(d.message||'Could not save topic'),'error');
    }).catch(()=>showToast('Network error saving topic.','error'));
}
function updateCharCount(el,id,max){ document.getElementById(id).textContent=el.value.length; updateProgress(); }
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 inp=zone.querySelector('input[type=file]'); if(inp&&e.dataTransfer.files.length){inp.files=e.dataTransfer.files;inp.dispatchEvent(new Event('change'));} });
    });
}
function handleFileUpload(input,fileType,zoneId,listId){
    const files=Array.from(input.files); if(!files.length)return; input.value='';
    const zone=document.getElementById(zoneId); if(zone)zone.style.opacity='0.6';
    const subId=document.getElementById('submissionId').value;
    if(!subId)saveDraftSilent(()=>uploadFiles(files,fileType,zoneId,listId)); else uploadFiles(files,fileType,zoneId,listId);
}
function uploadFiles(files,fileType,zoneId,listId){
    const zone=document.getElementById(zoneId); const ALLOWED=['.doc','.docx','.rtf'];
    files.forEach(file=>{
        if(file.size>50*1024*1024){showToast('File too large: '+file.name+' (max 50MB)','error');if(zone)zone.style.opacity='1';return;}
        if(fileType==='manuscript'){ const ext='.'+file.name.split('.').pop().toLowerCase(); if(!ALLOWED.includes(ext)){if(zone)zone.style.opacity='1';showToast('Invalid file type: '+file.name+'. Only .doc, .docx, .rtf allowed.','error');return;} }
        const fd=new FormData(); 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('HTTP '+r.status);return r.json();})
        .then(d=>{
            if(zone)zone.style.opacity='1';
            if(d.success){ if(d.submission_id){document.getElementById('submissionId').value=d.submission_id;const url=new URL(window.location.href);url.searchParams.set('id',d.submission_id);history.replaceState({},'',url.toString());}
                const icons={manuscript:'📄',manuscript_pdf:'📕',figure:'🖼',supplementary:'📎',review_only:'👁'};
                const el=document.createElement('div'); el.className='uploaded-file'; el.dataset.id=d.file_id;
                el.innerHTML=`<span>${icons[d.file_type]||icons[fileType]||'📄'}</span><span class="fname">${escHtml(file.name)}</span><button type="button" class="fremove" onclick="removeFile(${d.file_id},this)">×</button>`;
                document.getElementById(listId).appendChild(el); checkManuscriptWarning(); showToast('✓ Uploaded: '+file.name,'success'); updateProgress();
            } else showToast('Upload failed: '+(d.message||'Unknown error'),'error');
        }).catch(err=>{if(zone)zone.style.opacity='1';showToast('Upload error: '+err.message,'error');});
    });
}
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(d=>{if(d.success){btn.closest('.uploaded-file').remove();checkManuscriptWarning();updateProgress();}}); }
function checkManuscriptWarning(){
    const files=document.querySelectorAll('#manuscriptFiles .uploaded-file');
    const bad=Array.from(files).some(f=>{ const n=f.querySelector('.fname').textContent.toLowerCase(); return!n.endsWith('.doc')&&!n.endsWith('.docx')&&!n.endsWith('.rtf'); });
    const w=document.getElementById('manuscriptWarning'); if(bad)w.classList.add('show'); else w.classList.remove('show');
}
function scheduleAutoSave(){ clearTimeout(autoSaveTimer); autoSaveTimer=setTimeout(()=>saveDraftNow(),1500); }
function saveDraftNow(label=''){
    const fd=collectFormData(); fd.append('action','save');
    fetch('ajax/save_draft.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.success){ document.getElementById('submissionId').value=d.submission_id; updateProgress(d.completion_score); showSaveIndicator(); const url=new URL(window.location.href);url.searchParams.set('id',d.submission_id);history.replaceState({},'',url.toString()); }
    }).catch(e=>console.error('saveDraftNow:',e));
}
function saveDraftSilent(callback){
    const fd=collectFormData(); fd.append('action','save');
    fetch('ajax/save_draft.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.success){document.getElementById('submissionId').value=d.submission_id;showSaveIndicator();updateProgress(d.completion_score);const url=new URL(window.location.href);url.searchParams.set('id',d.submission_id);history.replaceState({},'',url.toString());}
        const id=document.getElementById('submissionId').value; if(id&&callback)callback();
    }).catch(()=>{ const id=document.getElementById('submissionId').value; if(id&&callback)callback(); });
}
function validateStep1(){
    let ok=true;
    const je=document.getElementById('journalError');
    if(!document.getElementById('journalId').value){je.classList.add('show');document.getElementById('journalPlaceholder').style.borderColor='#DC2626';ok=false;}
    else{je.classList.remove('show');document.getElementById('journalPlaceholder').style.borderColor='';}
    const ae=document.getElementById('articleTypeError'),as=document.getElementById('articleTypeSelect');
    if(!as.value){ae.classList.add('show');as.classList.add('field-error');ok=false;}else{ae.classList.remove('show');as.classList.remove('field-error');}
    const sc=document.getElementById('scopeStatement'),se=document.getElementById('scopeError');
    if(!sc.value.trim()){sc.classList.add('field-error');se.classList.add('show');ok=false;}else{sc.classList.remove('field-error');se.classList.remove('show');}
    const mf=document.querySelectorAll('#manuscriptFiles .uploaded-file'),me=document.getElementById('manuscriptError');
    if(!mf.length){document.getElementById('manuscriptZone').classList.add('zone-error');me.classList.add('show');ok=false;}
    else{document.getElementById('manuscriptZone').classList.remove('zone-error');me.classList.remove('show');}
    if(!ok)document.querySelector('.form-error.show,.field-error,.zone-error')?.scrollIntoView({behavior:'smooth',block:'center'});
    return ok;
}
function saveDraft(andContinue=false){
    if(andContinue&&!validateStep1()){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=collectFormData(); fd.append('action',andContinue?'save_continue':'save');
    fetch('ajax/save_draft.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        btn.disabled=false; btn.innerHTML=andContinue?'Save &amp; Continue →':'💾 Save';
        if(d.success){ document.getElementById('submissionId').value=d.submission_id; updateProgress(d.completion_score); showSaveIndicator();
            if(andContinue){showToast('Saved! Opening manuscript information...','success');setTimeout(()=>window.location.href='manuscript.php?id='+d.submission_id,800);}
            else showToast('Draft saved successfully!','success');
        } else showToast(d.message||'Save failed.','error');
    }).catch(()=>{ btn.disabled=false; btn.innerHTML=andContinue?'Save &amp; Continue →':'💾 Save'; showToast('Network error.','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;
}
function updateProgress(score){
    if(score===undefined){ let f=0,t=4;
        if(document.getElementById('journalId').value)f++;
        if(document.getElementById('articleTypeSelect').value)f++;
        if(document.getElementById('scopeStatement').value.trim())f++;
        if(document.querySelectorAll('#manuscriptFiles .uploaded-file').length)f++;
        score=Math.round((f/t)*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); }
function showToast(msg,type='info'){
    const c=document.getElementById('toastContainer'); const t=document.createElement('div'); t.className=`toast toast-${type}`;
    t.innerHTML=`<span>${type==='success'?'✓':type==='error'?'✗':'ℹ'}</span> ${escHtml(msg)}`;
    c.appendChild(t); requestAnimationFrame(()=>{requestAnimationFrame(()=>t.classList.add('show'));}); setTimeout(()=>{t.classList.remove('show');setTimeout(()=>t.remove(),400);},3500);
}
function escHtml(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
document.querySelectorAll('.overlay').forEach(o=>{ o.addEventListener('click',e=>{if(e.target===o)o.classList.remove('active');}); });
document.addEventListener('keydown',e=>{ if(e.key==='Escape')document.querySelectorAll('.overlay.active').forEach(o=>o.classList.remove('active')); });
</script>

<?php layoutEnd(); ?>