<?php
// project_detail.php — Single submission detail + Continue submission
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();
$user    = getCurrentUser();
$user_id = $user['user_id'];

// ── Shared layout identity ────────────────────────────────────
$pageTitle  = 'Project Detail';
$activePage = 'projects';

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

// Load submission
$q = db()->prepare(
    "SELECT s.*, j.name AS journal_name, sp.name AS specialty_name,
            at.name AS article_type_name, at.preliminary_fee_chf,
            COALESCE(s.submission_status,'draft') AS submission_status,
            s.tracking_code, s.submitted_at,
            mi.article_title, mi.abstract
     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
     LEFT JOIN manuscript_info mi ON mi.submission_id  = s.submission_id
     WHERE s.submission_id = ? AND s.user_id = ?"
);
$q->execute([$sid, $user_id]);
$sub = $q->fetch(PDO::FETCH_ASSOC);
if (!$sub) { header('Location: projects.php'); exit; }

// Authors
try {
    $q2 = db()->prepare(
        "SELECT sa.first_name, sa.last_name, sa.is_corresponding,
                a.name AS affil_name, a.city, a.country
         FROM submission_authors sa
         LEFT JOIN affiliations a ON a.affiliation_id = sa.affiliation_id
         WHERE sa.submission_id = ?
         ORDER BY sa.is_corresponding DESC, sa.author_order ASC"
    );
    $q2->execute([$sid]);
    $authors = $q2->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e){ $authors = []; }

$fullName     = trim(($user['first_name']??'').' '.($user['last_name']??''));
$initials     = strtoupper(substr($user['first_name']??'A',0,1).substr($user['last_name']??'A',0,1));
$articleTitle = $sub['article_title'] ?: '<<untitled>>';
$journal      = $sub['journal_name'] ? 'Communeglobal '.$sub['journal_name'] : null;
$specialty    = $sub['specialty_name'] ?? null;
$journalFull  = $journal ? ($specialty ? "$journal | $specialty" : $journal) : null;
$fee          = $sub['preliminary_fee_chf'] ? number_format($sub['preliminary_fee_chf'], 2) : '—';
$subStatus    = $sub['submission_status'] ?? 'draft';
$trackingCode = $sub['tracking_code'] ?? '';
$submittedAt  = $sub['submitted_at']  ?? '';
$isSubmitted  = in_array($subStatus, ['submitted','under_review','accepted','rejected']);
$activeTab    = $_GET['tab'] ?? ($isSubmitted ? 'preview' : 'detail');

// Override page title with article title
$pageTitle = $articleTitle !== '<<untitled>>' ? $articleTitle : 'Project Detail';

// Load extra data for preview tab
$keywords = []; $editorial = []; $statements = []; $payment = []; $files = [];
if ($isSubmitted) {
    try {
        $kq = db()->prepare(
            "SELECT k.keyword FROM submission_keywords sk
             JOIN keywords k ON k.keyword_id = sk.keyword_id
             WHERE sk.submission_id = ?"
        );
        $kq->execute([$sid]);
        $keywords = $kq->fetchAll(PDO::FETCH_COLUMN);
    } catch(PDOException $e) {}
    try {
        $eq = db()->prepare("SELECT * FROM submission_editorial WHERE submission_id = ? LIMIT 1");
        $eq->execute([$sid]); $editorial = $eq->fetch(PDO::FETCH_ASSOC) ?: [];
    } catch(PDOException $e) {}
    try {
        $sq = db()->prepare("SELECT * FROM submission_statements WHERE submission_id = ? LIMIT 1");
        $sq->execute([$sid]); $statements = $sq->fetch(PDO::FETCH_ASSOC) ?: [];
    } catch(PDOException $e) {}
    try {
        $pq = db()->prepare("SELECT * FROM submission_payment WHERE submission_id = ? LIMIT 1");
        $pq->execute([$sid]); $payment = $pq->fetch(PDO::FETCH_ASSOC) ?: [];
    } catch(PDOException $e) {}
    try {
        $fq = db()->prepare(
            "SELECT original_name, file_type, uploaded_at
             FROM submission_files WHERE submission_id = ? ORDER BY uploaded_at"
        );
        $fq->execute([$sid]);
        $files = $fq->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {}
}

function p($v){ return htmlspecialchars($v ?? ''); }

// Include shared layout
require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── project_detail page styles ─────────────────────────── */
.au-main { padding: 20px 28px; }

/* Breadcrumb + back */
.back-row {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 16px; flex-wrap: wrap; gap: 10px;
}
.btn-back {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 7px 16px; border: 1.5px solid var(--border);
  border-radius: 20px; font-size: 12.5px; font-weight: 600;
  color: var(--muted); background: var(--white); cursor: pointer;
  text-decoration: none; transition: all .15s;
}
.btn-back:hover { border-color: #9CA3AF; color: var(--text); }
.breadcrumb {
  display: flex; align-items: center; gap: 8px;
  font-size: 12.5px; color: var(--muted); flex-wrap: wrap;
}
.breadcrumb a { color: var(--muted); }
.breadcrumb a:hover { color: var(--teal); }
.breadcrumb-sep { color: #CBD5E1; }

/* 2-col layout */
.detail-layout {
  display: grid;
  grid-template-columns: 1fr 290px;
  gap: 26px;
  align-items: start;
  margin-top: 20px;
}

/* Status badges */
.sb { display: inline-flex; align-items: center; gap: 5px; font-size: 12.5px; font-weight: 700; padding: 4px 12px; border-radius: 20px; }
.sb::before { content:''; width:7px; height:7px; border-radius:50%; flex-shrink:0; }
.sb-draft        { background:#F3F4F6; color:#6B7280;  } .sb-draft::before        { background:#9CA3AF; }
.sb-submitted    { background:#EFF6FF; color:#1D4ED8;  } .sb-submitted::before    { background:#3B82F6; }
.sb-under_review { background:#FEF3C7; color:#D97706;  } .sb-under_review::before { background:#F59E0B; }
.sb-accepted     { background:#DCFCE7; color:#15803D;  } .sb-accepted::before     { background:#22C55E; }
.sb-rejected     { background:#FEE2E2; color:#DC2626;  } .sb-rejected::before     { background:#EF4444; }

.tracking-badge {
  font-family: monospace; font-size: 12px; font-weight: 800;
  color: #1E40AF; background: #EFF6FF; border: 1px solid #BFDBFE;
  border-radius: 5px; padding: 3px 10px; letter-spacing: .5px;
}

/* Main title — word-wrap instead of ellipsis clipping */
.main-title {
  font-size: 22px; font-weight: 700; color: var(--text);
  margin-bottom: 10px; line-height: 1.3;
  word-break: break-word; overflow-wrap: break-word;
}
.meta-row   { display: flex; flex-direction: column; gap: 4px; margin-bottom: 18px; }
.meta-item  { font-size: 13px; color: var(--muted); }
.meta-item strong { color: var(--text); }

/* Tabs — scrollable at all widths */
.detail-tabs {
  display: flex;
  gap: 0;
  border-bottom: 2px solid var(--border);
  margin-bottom: 22px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}
.detail-tabs::-webkit-scrollbar { display: none; }
.detail-tab {
  flex-shrink: 0;
  white-space: nowrap;
  padding: 9px 20px; font-size: 13.5px; font-weight: 600;
  text-decoration: none; border-bottom: 2.5px solid transparent;
  margin-bottom: -2px; transition: all .15s; color: var(--muted);
}
.detail-tab.active { border-bottom-color: var(--teal); color: var(--teal); }
.detail-tab:hover:not(.active) { color: var(--text); }

/* Incomplete notice */
.notice {
  background:#EFF6FF; border:1px solid #BFDBFE; border-radius:8px;
  padding:16px 18px; margin-bottom:22px; display:flex; gap:10px;
}
.notice-icon { font-size:16px; flex-shrink:0; margin-top:1px; }
.notice-text { font-size:13.5px; color:#1E40AF; line-height:1.6; }
.notice-btn {
  display:inline-flex; align-items:center; padding:6px 14px;
  border:1.5px solid #93C5FD; border-radius:20px; font-size:12px;
  font-weight:600; color:#1D4ED8; background:var(--white); cursor:pointer; margin-top:8px;
}
.notice-btn:hover { background:#EFF6FF; }

/* Detail sections */
.detail-section { margin-bottom:26px; }
.detail-section-title {
  font-size:15px; font-weight:700; color:var(--text);
  margin-bottom:12px; padding-bottom:8px; border-bottom:1px solid var(--border);
}
.detail-empty {
  font-size:13.5px; color:var(--muted); font-style:italic;
  display:flex; align-items:center; gap:6px;
}
.abstract-text {
  font-size:13.5px; color:var(--text); line-height:1.8;
  background:#FAFAFA; border-radius:6px; padding:14px 16px;
  border:1px solid var(--border);
}

/* Authors list */
.authors-grid { display:flex; flex-direction:column; gap:10px; }
.author-row {
  display:flex; align-items:center; gap:12px; padding:10px 14px;
  background:#FAFAFA; border-radius:6px; border:1px solid var(--border);
}
.author-av {
  width:34px; height:34px; border-radius:50%; background:#E2E8F0;
  display:flex; align-items:center; justify-content:center;
  font-size:11px; font-weight:700; color:#475569; flex-shrink:0;
}
.author-name  { font-size:13px; font-weight:600; }
.author-affil { font-size:12px; color:var(--muted); }
.corr-badge {
  display:inline-flex; padding:1px 6px; background:#DCFCE7;
  color:#166534; font-size:9.5px; font-weight:700; border-radius:10px; margin-left:5px;
}

/* Sidebar cards */
.sidebar-card {
  background:var(--white); border:1px solid var(--border);
  border-radius:8px; overflow:hidden; margin-bottom:14px;
}
.status-box { padding:18px 20px; }
.status-label {
  font-size:11.5px; font-weight:700; text-transform:uppercase;
  letter-spacing:.5px; color:var(--muted); margin-bottom:10px;
}
.status-val   { font-size:14px; font-weight:700; color:var(--text); margin-bottom:14px; }
.btn-continue {
  display:block; width:100%; padding:11px 14px;
  background:var(--blue); color:#fff; border:none; border-radius:6px;
  font-family:var(--font); font-size:13.5px; font-weight:700;
  cursor:pointer; text-align:center; text-decoration:none;
  margin-bottom:10px; transition:background .15s;
}
.btn-continue:hover { background:#132B50; }
.btn-remove {
  display:flex; width:100%; padding:9px 14px; align-items:center; justify-content:center; gap:7px;
  background:var(--white); color:var(--muted);
  border:1.5px solid var(--border); border-radius:6px;
  font-family:var(--font); font-size:13px; font-weight:600; cursor:pointer;
  transition:all .15s;
}
.btn-remove:hover { border-color:#EF4444; color:#EF4444; }
.links-row {
  padding:10px 16px; display:flex; gap:16px;
  border-top:1px solid var(--border); flex-wrap:wrap;
}
.ext-link { font-size:12px; color:var(--muted); display:flex; align-items:center; gap:3px; }
.ext-link:hover { color:var(--teal); }
.fee-card { padding:14px 18px; }
.fee-label {
  font-size:11px; font-weight:700; text-transform:uppercase;
  letter-spacing:.5px; color:var(--muted); margin-bottom:4px;
}
.fee-val  { font-size:20px; font-weight:700; color:var(--teal); }
.fee-note { font-size:11px; color:var(--muted); margin-top:2px; }

/* Preview card */
.preview-card {
  background:var(--white); border:1px solid var(--border);
  border-radius:8px; overflow:hidden; margin-bottom:20px;
}
.preview-header { background:linear-gradient(135deg,#1B3F6E,#1A7F8E); padding:20px 24px; color:#fff; }
.preview-header-title {
  font-size:17px; font-weight:700; margin-bottom:8px;
  /* wrap instead of clip */
  word-break: break-word; overflow-wrap: break-word;
}
.preview-section { padding:16px 22px; border-bottom:1px solid #F1F5F9; }
.preview-section-title {
  font-size:12px; font-weight:700; color:var(--teal);
  margin-bottom:12px; text-transform:uppercase; letter-spacing:.4px;
}
.preview-row { display:flex; gap:12px; margin-bottom:8px; font-size:13px; }
.preview-row-label { min-width:150px; font-weight:600; color:var(--muted); flex-shrink:0; }
.preview-row-val { color:#1E293B; line-height:1.6; word-break:break-word; overflow-wrap:break-word; }

/* Modal */
.modal-bg {
  position:fixed; inset:0; background:rgba(0,0,0,.4);
  z-index:600; display:none; align-items:center; justify-content:center;
}
.modal-bg.open { display:flex; }
.modal {
  background:var(--white); border-radius:10px; padding:26px;
  width:400px; max-width:90vw;
  box-shadow:0 20px 60px rgba(0,0,0,.2);
}
.modal-title { font-size:15px; font-weight:700; margin-bottom:8px; }
.modal-desc  { font-size:13px; color:var(--muted); margin-bottom:18px; line-height:1.6; }
.modal-actions { display:flex; gap:10px; justify-content:flex-end; }
.btn-cancel {
  padding:8px 18px; border:1.5px solid var(--border); border-radius:4px;
  background:var(--white); font-family:var(--font);
  font-size:13px; font-weight:600; cursor:pointer;
}
.btn-danger {
  padding:8px 18px; border:none; border-radius:4px;
  background:#EF4444; color:#fff;
  font-family:var(--font); font-size:13px; font-weight:700; cursor:pointer;
}
.btn-danger:hover { background:#DC2626; }

/* Toast */
.toast-wrap { position:fixed; bottom:20px; right:20px; z-index:999; }
.toast {
  padding:10px 16px; color:#fff; border-radius:4px;
  font-size:13px; font-weight:500;
  box-shadow:0 4px 12px rgba(0,0,0,.2); animation:tup .2s ease;
}
@keyframes tup { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }


/* ── RESPONSIVE ─────────────────────────────────────────────── */

/* Tablet ≤ 960px: single column, sidebar drops below */
@media (max-width: 960px) {
  .detail-layout { grid-template-columns: 1fr; }
}

/* Mobile ≤ 768px */
@media (max-width: 768px) {
  .au-main { padding: 14px 16px; }

  .back-row { flex-direction: column; align-items: flex-start; gap: 8px; margin-bottom: 12px; }

  .main-title { font-size: 17px; }

  .preview-header { padding: 14px 16px; }
  .preview-header-title { font-size: 15px; }

  /* Stack label above value in preview rows */
  .preview-row { flex-direction: column; gap: 3px; margin-bottom: 12px; }
  .preview-row-label { min-width: unset; font-size: 11px; text-transform: uppercase; letter-spacing: .3px; }
  .preview-row-val   { font-size: 13px; }
  .preview-section   { padding: 14px 16px; }

  .notice { padding: 12px 14px; gap: 8px; }
  .notice-text { font-size: 13px; }

  .abstract-text { font-size: 13px; padding: 12px 13px; }

  .author-row { padding: 10px 12px; gap: 10px; }
  .author-name { font-size: 12.5px; }

  /* Modal: full-width, stacked actions */
  .modal { width: 94vw; padding: 20px 18px; }
  .modal-actions { flex-direction: column-reverse; gap: 8px; }
  .modal-actions button { width: 100%; padding: 10px; text-align: center; }
}

/* Extra small ≤ 480px */
@media (max-width: 480px) {
  .au-main { padding: 12px; }

  .main-title { font-size: 15px; }

  .tracking-badge { font-size: 11px; padding: 2px 8px; }

  .sb { font-size: 11.5px; padding: 3px 10px; }

  .detail-tab { padding: 7px 12px; font-size: 12.5px; }

  .fee-val { font-size: 17px; }

  .btn-continue { font-size: 13px; padding: 10px 12px; }
  .btn-remove   { font-size: 12.5px; }

  .preview-section-title { font-size: 11px; }
  .detail-section-title  { font-size: 14px; }
}
</style>

<!-- ── BREADCRUMB + BACK ────────────────────────────────────── -->
<div class="back-row">
  <div class="breadcrumb">
    <span>🏠</span>
    <a href="dashboard.php">Overview</a>
    <span class="breadcrumb-sep">›</span>
    <a href="projects.php">My Projects</a>
    <span class="breadcrumb-sep">›</span>
    <span><?= p(mb_strlen($articleTitle) > 60 ? mb_substr($articleTitle,0,60).'…' : $articleTitle) ?></span>
  </div>
  <a href="projects.php" class="btn-back">‹ Back to my projects</a>
</div>

<!-- ── 2-COL LAYOUT ────────────────────────────────────────── -->
<div class="detail-layout">

  <!-- ══ LEFT COLUMN ══════════════════════════════════════════ -->
  <div>

    <!-- Status row -->
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px">
      <span class="sb sb-<?= $subStatus ?>"><?= ucfirst(str_replace('_',' ',$subStatus)) ?></span>
      <?php if ($trackingCode): ?>
      <span class="tracking-badge">🔖 <?= p($trackingCode) ?></span>
      <?php if ($submittedAt): ?>
      <span style="font-size:12px;color:var(--muted)">Submitted: <?= date('d M Y, H:i', strtotime($submittedAt)) ?></span>
      <?php endif; ?>
      <?php endif; ?>
    </div>

    <!-- Title + meta -->
    <h1 class="main-title"><?= p($articleTitle) ?></h1>
    <div class="meta-row">
      <div class="meta-item">Article type: <strong><?= $sub['article_type_name'] ? p($sub['article_type_name']) : 'not selected' ?></strong></div>
      <div class="meta-item">Journal: <strong><?= $journalFull ? p($journalFull) : 'not selected' ?></strong></div>
    </div>

    <!-- Tabs -->
    <div class="detail-tabs">
      <a href="?id=<?= $sid ?>&tab=detail"
         class="detail-tab <?= $activeTab==='detail' ? 'active' : '' ?>">
        📄 Details
      </a>
      <?php if ($isSubmitted): ?>
      <a href="?id=<?= $sid ?>&tab=preview"
         class="detail-tab <?= $activeTab==='preview' ? 'active' : '' ?>">
        👁 Preview Submission
      </a>
      <?php endif; ?>
    </div>

    <!-- ══ PREVIEW TAB ═══════════════════════════════════════ -->
    <?php if ($activeTab === 'preview' && $isSubmitted): ?>

    <div class="preview-card">

      <!-- Header -->
      <div class="preview-header">
        <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;opacity:.8;margin-bottom:6px">
          Final Submission Preview
        </div>
        <div class="preview-header-title"><?= p($articleTitle) ?></div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:6px">
          <span style="background:rgba(255,255,255,.2);border-radius:4px;padding:2px 10px;font-size:12px;font-weight:700">
            <?= ucfirst(str_replace('_',' ',$subStatus)) ?>
          </span>
          <?php if ($trackingCode): ?>
          <span style="font-family:monospace;font-size:13px;font-weight:800;background:rgba(255,255,255,.15);border-radius:4px;padding:2px 10px">
            🔖 <?= p($trackingCode) ?>
          </span>
          <?php endif; ?>
          <?php if ($submittedAt): ?>
          <span style="font-size:12px;opacity:.8">📅 <?= date('d M Y, H:i', strtotime($submittedAt)) ?></span>
          <?php endif; ?>
        </div>
      </div>

      <!-- Submission Details -->
      <div class="preview-section">
        <div class="preview-section-title">📋 Submission Details</div>
        <?php foreach (array_filter([
          ['Journal',      $sub['journal_name'] ? 'Communeglobal '.$sub['journal_name'] : null],
          ['Specialty',    $sub['specialty_name'] ?? null],
          ['Article Type', $sub['article_type_name'] ?? null],
          ['Fee',          $fee !== '—' ? $fee.' CHF' : null],
        ]) as $row): ?>
        <div class="preview-row">
          <div class="preview-row-label"><?= p($row[0]) ?></div>
          <div class="preview-row-val"><?= p($row[1]) ?></div>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- Manuscript -->
      <div class="preview-section">
        <div class="preview-section-title">📝 Manuscript</div>
        <?php foreach (array_filter([
          ['Title',    $sub['article_title'] ?? null],
          ['Abstract', $sub['abstract']      ?? null],
          ['Keywords', $keywords ? implode(', ', $keywords) : null],
        ]) as $row): ?>
        <div class="preview-row">
          <div class="preview-row-label"><?= p($row[0]) ?></div>
          <div class="preview-row-val"><?= nl2br(p($row[1])) ?></div>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- Authors -->
      <?php if ($authors): ?>
      <div class="preview-section">
        <div class="preview-section-title">👥 Authors</div>
        <?php foreach ($authors as $a):
          $aName = trim(($a['first_name']??'').' '.($a['last_name']??''));
        ?>
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
          <div style="width:32px;height:32px;border-radius:50%;background:var(--teal);color:#fff;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;flex-shrink:0">
            <?= strtoupper(substr($a['first_name']??'A',0,1).substr($a['last_name']??'',0,1)) ?>
          </div>
          <div>
            <div style="font-size:13px;font-weight:600">
              <?= p($aName) ?>
              <?php if ($a['is_corresponding']): ?>
              <span style="font-size:10px;font-weight:700;background:#EFF6FF;color:#1D4ED8;border-radius:3px;padding:1px 6px;margin-left:5px">CORRESPONDING</span>
              <?php endif; ?>
            </div>
            <?php if (!empty($a['affil_name'])): ?>
            <div style="font-size:12px;color:var(--muted)"><?= p($a['affil_name']) ?></div>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Statements -->
      <?php $stRows = array_filter([
        ['Conflict of Interest', $statements['conflict_of_interest'] ?? null],
        ['Data Availability',    $statements['data_availability_statement'] ?? null],
        ['Funding',              $statements['funding_details'] ?? null],
      ]); if ($stRows): ?>
      <div class="preview-section">
        <div class="preview-section-title">📜 Statements</div>
        <?php foreach ($stRows as $row): ?>
        <div class="preview-row">
          <div class="preview-row-label"><?= p($row[0]) ?></div>
          <div class="preview-row-val"><?= nl2br(p($row[1])) ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Billing -->
      <?php $billRows = array_filter([
        ['Billing Email', $payment['billing_email']   ?? null],
        ['Phone',         trim(($payment['phone_country_code']??'').($payment['phone_number']??'')) ?: null],
        ['Address',       $payment['address']         ?? null],
        ['City',          $payment['city']            ?? null],
        ['Country',       $payment['country_region']  ?? null],
      ]); if ($billRows): ?>
      <div class="preview-section">
        <div class="preview-section-title">💳 Billing Details</div>
        <?php foreach ($billRows as $row): ?>
        <div class="preview-row">
          <div class="preview-row-label"><?= p($row[0]) ?></div>
          <div class="preview-row-val"><?= p($row[1]) ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Files -->
      <?php if ($files): ?>
      <div class="preview-section">
        <div class="preview-section-title">📎 Uploaded Files</div>
        <?php foreach ($files as $f): ?>
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px">
          <span>📄</span>
          <span style="font-weight:500"><?= p($f['original_name'] ?? $f['file_name'] ?? '') ?></span>
          <span style="font-size:11px;color:var(--muted)">(<?= p($f['file_type']) ?>)</span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <div style="padding:12px 22px;background:#F8FAFC;font-size:12px;color:var(--muted);display:flex;align-items:center;gap:6px">
        🔒 This submission is locked for editing. Contact the editorial team for changes.
      </div>
    </div>

    <?php endif; // preview tab ?>

    <!-- ══ DETAIL TAB ════════════════════════════════════════ -->
    <?php if ($activeTab !== 'preview'): ?>

    <?php if (!$sub['article_title'] || !$sub['journal_id']): ?>
    <div class="notice">
      <div class="notice-icon">ℹ️</div>
      <div>
        <div class="notice-text">You have not yet completed your submission.</div>
        <div style="font-size:13px;color:#3B82F6;margin-top:4px">
          Learn more about our publishing model or contact us if you need assistance.
        </div>
        <button class="notice-btn">How we publish</button>
      </div>
    </div>
    <?php endif; ?>

    <!-- Abstract -->
    <div class="detail-section">
      <div class="detail-section-title">Abstract</div>
      <?php if ($sub['abstract']): ?>
        <div class="abstract-text"><?= p($sub['abstract']) ?></div>
      <?php else: ?>
        <div class="detail-empty">ℹ️ No abstract provided yet</div>
      <?php endif; ?>
    </div>

    <!-- Authors -->
    <div class="detail-section">
      <div class="detail-section-title">Authors</div>
      <?php if ($authors): ?>
      <div class="authors-grid">
        <?php foreach ($authors as $a):
          $aName = trim(($a['first_name']??'').' '.($a['last_name']??''));
          $aInit = strtoupper(substr($a['first_name']??'A',0,1).substr($a['last_name']??'',0,1));
          $aLoc  = array_filter([$a['affil_name']??null, $a['city']??null, $a['country']??null]);
        ?>
        <div class="author-row">
          <div class="author-av"><?= p($aInit) ?></div>
          <div>
            <div class="author-name">
              <?= p($aName) ?>
              <?php if ($a['is_corresponding']): ?><span class="corr-badge">Corresponding</span><?php endif; ?>
            </div>
            <?php if ($aLoc): ?>
            <div class="author-affil"><?= p(implode(', ', $aLoc)) ?></div>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div class="detail-empty">ℹ️ No authors added yet</div>
      <?php endif; ?>
    </div>

    <?php endif; // detail tab ?>

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

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

    <!-- Status + action card -->
    <div class="sidebar-card">
      <div class="status-box">
        <div class="status-label">Status</div>
        <div class="status-val" style="color:<?= $isSubmitted ? '#1D4ED8' : 'var(--text)' ?>">
          <?= ucfirst(str_replace('_',' ', $subStatus)) ?>
        </div>

        <?php if ($trackingCode): ?>
        <div style="font-family:monospace;font-size:13px;font-weight:800;color:#1E40AF;background:#EFF6FF;border:1px solid #BFDBFE;border-radius:5px;padding:5px 10px;margin-bottom:14px;letter-spacing:.5px">
          🔖 <?= p($trackingCode) ?>
        </div>
        <?php endif; ?>

        <?php if (!$isSubmitted): ?>
        <a href="submission.php?id=<?= $sid ?>" class="btn-continue">
          Continue submission
        </a>
        <?php else: ?>
        <a href="?id=<?= $sid ?>&tab=preview" class="btn-continue"
           style="background:var(--teal);margin-bottom:8px">
          👁 Preview Submission
        </a>
        <div style="font-size:12px;color:var(--muted);text-align:center;margin-bottom:10px">
          🔒 Editing disabled after submission
        </div>
        <?php endif; ?>

        <button class="btn-remove" onclick="document.getElementById('delModal').classList.add('open')">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="3 6 5 6 21 6"/>
            <path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/>
          </svg>
          Remove this draft
        </button>
      </div>
      <div class="links-row">
        <a href="#" class="ext-link">Author resources ↗</a>
        <a href="#" class="ext-link">Fee policy ↗</a>
      </div>
    </div>

    <!-- Fee card -->
    <?php if ($fee !== '—'): ?>
    <div class="sidebar-card">
      <div class="fee-card">
        <div class="fee-label">Preliminary fee</div>
        <div class="fee-val"><?= p($fee) ?> CHF</div>
        <div class="fee-note">Payment after acceptance</div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Last updated -->
    <div style="font-size:11.5px;color:var(--muted);text-align:center;margin-top:4px">
      Last updated: <?= $sub['updated_at'] ? date('d M Y, H:i', strtotime($sub['updated_at'])) : '—' ?>
    </div>

  </div><!-- /sidebar -->

</div><!-- /detail-layout -->

<!-- Delete modal -->
<div class="modal-bg" id="delModal">
  <div class="modal">
    <div class="modal-title">Remove this draft?</div>
    <div class="modal-desc">
      This will permanently delete <strong>"<?= p($articleTitle) ?>"</strong>. This action cannot be undone.
    </div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="document.getElementById('delModal').classList.remove('open')">Cancel</button>
      <button class="btn-danger" onclick="doDelete()">Remove draft</button>
    </div>
  </div>
</div>
<div class="toast-wrap" id="toastWrap"></div>

<script>
function doDelete() {
  fetch('ajax/delete_submission.php', {
    method: 'POST',
    body: new URLSearchParams({ submission_id: <?= $sid ?> })
  })
  .then(r => r.json())
  .then(d => {
    document.getElementById('delModal').classList.remove('open');
    if (d.success) {
      const t = document.createElement('div');
      t.className = 'toast'; t.style.background = '#1D8A5E';
      t.textContent = 'Draft removed';
      document.getElementById('toastWrap').appendChild(t);
      setTimeout(() => window.location = 'projects.php', 1000);
    }
  });
}
</script>

<?php layoutEnd(); ?>