<?php
// ============================================================
//  authors.php  —  SCREEN 4: Authors & Contributors
// ============================================================
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  = 'Authors & Contributors';
$activePage = 'submission';

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

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

// ── Load submission ──────────────────────────────────────────
$stmt = db()->prepare(
    "SELECT s.*, j.name AS journal_name, sp.name AS specialty_name,
            at.name AS article_type_name, at.preliminary_fee_chf
     FROM   submissions s
     LEFT JOIN journals    j  ON j.journal_id    = s.journal_id
     LEFT JOIN specialties sp ON sp.specialty_id = s.specialty_id
     LEFT JOIN article_types at ON at.article_type_id = s.article_type_id
     WHERE  s.submission_id = ? AND s.user_id = ?"
);
$stmt->execute([$submission_id, $user_id]);
$submission = $stmt->fetch();
if (!$submission) { header('Location: submission.php'); exit; }

// ── Load existing authors ────────────────────────────────────
$stmt = db()->prepare(
    "SELECT sa.*, a.name AS affil_name, a.city AS affil_city, a.country AS affil_country
     FROM   submission_authors sa
     LEFT JOIN affiliations a ON a.affiliation_id = sa.affiliation_id
     WHERE  sa.submission_id = ? ORDER BY sa.author_order ASC"
);
$stmt->execute([$submission_id]);
$authors = $stmt->fetchAll();

// ── Load contributions ───────────────────────────────────────
$contributions = [];
if ($authors) {
    $ids  = implode(',', array_column($authors, 'author_id'));
    $rows = db()->query("SELECT * FROM author_contributions WHERE author_id IN ($ids)")->fetchAll();
    foreach ($rows as $r) $contributions[$r['author_id']] = $r;
}

// Seed first author if none
if (!$authors) {
    $authors = [[
        'author_id'=>0,'submission_id'=>$submission_id,'user_id'=>$user_id,
        'email'=>$user['email'],'title'=>$user['title']??'',
        'first_name'=>$user['first_name'],'middle_name'=>$user['middle_name']??'',
        'last_name'=>$user['last_name'],'phone_country_code'=>$user['phone_country_code']??'',
        'phone_number'=>$user['phone_number']??'','institutional_email'=>$user['institutional_email']??'',
        'affiliation_id'=>$user['affiliation_id']??'','affil_name'=>null,'affil_city'=>null,'affil_country'=>null,
        'is_corresponding'=>1,'author_order'=>1,
    ]];
}

$creditFields = [
    'mandatory' => [
        'writing_original_draft' => 'Writing – original draft',
        'writing_review_editing' => 'Writing – review & editing',
    ],
    'additional' => [
        'conceptualization'=>'Conceptualization','data_curation'=>'Data curation',
        'formal_analysis'=>'Formal Analysis','funding_acquisition'=>'Funding acquisition',
        'investigation'=>'Investigation','methodology'=>'Methodology',
        'project_administration'=>'Project administration','resources'=>'Resources',
        'software'=>'Software','supervision'=>'Supervision',
        'validation'=>'Validation','visualization'=>'Visualization',
    ]
];

$countryCodes = [
    '+1'=>'US/CA','+7'=>'RU','+20'=>'EG','+27'=>'ZA','+30'=>'GR','+31'=>'NL','+32'=>'BE','+33'=>'FR',
    '+34'=>'ES','+36'=>'HU','+39'=>'IT','+40'=>'RO','+41'=>'CH','+44'=>'GB','+45'=>'DK','+46'=>'SE',
    '+47'=>'NO','+48'=>'PL','+49'=>'DE','+52'=>'MX','+54'=>'AR','+55'=>'BR','+56'=>'CL','+57'=>'CO',
    '+60'=>'MY','+61'=>'AU','+62'=>'ID','+63'=>'PH','+64'=>'NZ','+65'=>'SG','+66'=>'TH','+81'=>'JP',
    '+82'=>'KR','+84'=>'VN','+86'=>'CN','+90'=>'TR','+91'=>'IN','+92'=>'PK','+94'=>'LK','+98'=>'IR',
    '+212'=>'MA','+213'=>'DZ','+234'=>'NG','+254'=>'KE','+351'=>'PT','+353'=>'IE','+358'=>'FI',
    '+380'=>'UA','+420'=>'CZ','+43'=>'AT',
];
$titles = ['','Mr','Mrs','Ms','Dr','Prof'];

function affilBlock(int $idx, array $author): string {
    $hasAffil = !empty($author['affiliation_id']);
    ob_start(); ?>
              <label class="form-label">Affiliation</label>
              <div class="affil-search-wrap">
                <input type="text" class="form-input" id="affilSearch_<?= $idx ?>"
                       placeholder="Search university / institution..." autocomplete="off"
                       oninput="onAffilSearch(<?= $idx ?>,this)"
                       onblur="hideAffilDropdown(<?= $idx ?>)">
                <div class="affil-dropdown" id="affilDrop_<?= $idx ?>"></div>
              </div>
              <div class="field-error" id="affilErr_<?= $idx ?>" style="display:none">
                <span class="field-error-icon">!</span><span>Please fill this field to continue</span>
              </div>
              <?php if ($hasAffil): ?>
              <div class="affil-label">Selected affiliation</div>
              <?php else: ?>
              <div class="affil-label" id="affilTagsLabel_<?= $idx ?>" style="display:none">Selected affiliation</div>
              <?php endif; ?>
              <div class="affil-tags" id="affilTags_<?= $idx ?>">
                <?php if ($hasAffil): ?>
                <div class="affil-tag" data-affil-id="<?= $author['affiliation_id'] ?>">
                  <span class="affil-tag-name">
                    <?= htmlspecialchars($author['affil_name']??'') ?>
                    <?php if ($author['affil_city']): ?>, <?= htmlspecialchars($author['affil_city']) ?><?php endif; ?>
                    <?php if ($author['affil_country']): ?>, <?= htmlspecialchars($author['affil_country']) ?><?php endif; ?>
                  </span>
                  <div class="affil-tag-actions">
                    <button type="button" class="affil-tag-btn affil-tag-del"
                            onclick="removeAffil(<?= $idx ?>,this)" title="Remove">✕</button>
                  </div>
                </div>
                <?php endif; ?>
              </div>
              <div class="affil-add-form" id="affilAddForm_<?= $idx ?>">
                <div class="affil-add-title">
                  <span>🏛 Add new affiliation</span>
                  <button type="button" class="affil-add-close" onclick="toggleAffilForm(<?= $idx ?>,false)">✕</button>
                </div>
                <div class="affil-add-grid">
                  <div class="affil-add-full">
                    <label class="affil-add-label">Institution / University Name <span style="color:var(--error)">*</span></label>
                    <input type="text" class="affil-add-input" id="newAffilName_<?= $idx ?>" placeholder="e.g. Harvard University">
                  </div>
                  <div>
                    <label class="affil-add-label">Department <span class="affil-add-opt">(optional)</span></label>
                    <input type="text" class="affil-add-input" id="newAffilDept_<?= $idx ?>" placeholder="e.g. Computer Science">
                  </div>
                  <div>
                    <label class="affil-add-label">City <span class="affil-add-opt">(optional)</span></label>
                    <input type="text" class="affil-add-input" id="newAffilCity_<?= $idx ?>" placeholder="e.g. Cambridge">
                  </div>
                  <div>
                    <label class="affil-add-label">State / Province <span class="affil-add-opt">(optional)</span></label>
                    <input type="text" class="affil-add-input" id="newAffilState_<?= $idx ?>" placeholder="e.g. Massachusetts">
                  </div>
                  <div>
                    <label class="affil-add-label">Country <span class="affil-add-opt">(optional)</span></label>
                    <input type="text" class="affil-add-input" id="newAffilCountry_<?= $idx ?>" placeholder="e.g. USA">
                  </div>
                </div>
                <div class="affil-add-actions">
                  <button type="button" class="affil-btn-cancel" onclick="toggleAffilForm(<?= $idx ?>,false)">Cancel</button>
                  <button type="button" class="affil-btn-save" id="affilSaveBtn_<?= $idx ?>"
                          onclick="saveNewAffiliation(<?= $idx ?>)">💾 Save & Select</button>
                </div>
              </div>
<?php
    return ob_get_clean();
}

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

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

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

.page-wrap { max-width: 1100px; margin: 0 auto; padding: 22px 24px 20px; }
.breadcrumb { display: flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); margin-bottom: 18px; }
.breadcrumb a { color: var(--primary); text-decoration: none; font-weight: 500; }
.breadcrumb a:hover { text-decoration: underline; }

.section-heading { display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; background: var(--white); border: 1px solid var(--border); border-radius: var(--radius-lg) var(--radius-lg) 0 0; cursor: pointer; user-select: none; }
.section-heading-left { display: flex; align-items: center; gap: 10px; font-size: 15px; font-weight: 700; color: var(--blue); }
.section-badge-incomplete { font-size: 12px; font-weight: 600; color: var(--error); display: flex; align-items: center; gap: 4px; }
.section-badge-complete   { font-size: 12px; font-weight: 600; color: var(--success); display: flex; align-items: center; gap: 4px; }
.section-collapse { font-size: 18px; color: var(--muted); transition: transform .2s; }
.section-collapse.open { transform: rotate(180deg); }
.section-body { background: var(--white); border: 1px solid var(--border); border-top: none; border-radius: 0 0 var(--radius-lg) var(--radius-lg); padding: 22px; }
.section-desc { font-size: 13px; color: var(--muted); line-height: 1.7; margin-bottom: 18px; }
.section-desc p { margin-bottom: 8px; }
.section-desc a { color: var(--primary); }

.author-card { border: 1px solid var(--border); border-radius: var(--radius); margin-bottom: 18px; background: var(--white); box-shadow: var(--shadow-sm); overflow: visible; }
.author-card-header { display: flex; align-items: center; justify-content: space-between; padding: 11px 16px; background: var(--bg); border-bottom: 1px solid var(--border); border-radius: var(--radius) var(--radius) 0 0; }
.author-label { font-size: 13px; font-weight: 700; color: var(--blue); }
.author-actions { display: flex; gap: 6px; }
.author-action-btn { display: inline-flex; align-items: center; gap: 5px; padding: 5px 11px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; border: 1.5px solid var(--border); background: var(--white); color: var(--muted); transition: all .15s; }
.author-action-btn:hover:not(:disabled) { border-color: var(--blue); color: var(--blue); background: var(--blue-light); }
.author-action-btn.btn-delete:hover { border-color: var(--error); color: var(--error); background: #FEF2F2; }
.author-action-btn:disabled { opacity: .4; cursor: not-allowed; }
.author-card-body { padding: 18px 18px 14px; }

.form-row { display: grid; gap: 14px; margin-bottom: 14px; }
.form-row-3 { grid-template-columns: 1fr 1fr 1fr; }
.form-row-2 { grid-template-columns: 1fr 1fr; }
.form-row-email-title { grid-template-columns: 2fr 160px 1fr; }
@media(max-width:860px) { .form-row-3,.form-row-2,.form-row-email-title { grid-template-columns: 1fr; } }
.form-group { display: flex; flex-direction: column; gap: 5px; }
.form-label { font-size: 12.5px; font-weight: 600; color: var(--text); }
.optional-lbl { font-size: 11px; font-weight: 400; color: var(--muted); }
.form-input, .form-select { width: 100%; padding: 8px 12px; border: 1.5px solid var(--border); border-radius: 8px; font-family: var(--font); font-size: 13px; color: var(--text); background: var(--white); outline: none; transition: border-color .15s; }
.form-input:focus, .form-select:focus { border-color: var(--border-focus); box-shadow: 0 0 0 3px rgba(224,90,43,.10); }
.form-input.has-error, .form-select.has-error { border-color: var(--error); }
.field-error { font-size: 11.5px; color: var(--error); display: flex; align-items: center; gap: 4px; margin-top: 2px; }
.field-error-icon { width: 15px; height: 15px; border-radius: 50%; background: var(--error); color: #fff; display: inline-flex; align-items: center; justify-content: center; font-size: 8px; font-weight: 700; flex-shrink: 0; }
.phone-wrap { display: flex; gap: 8px; }
.phone-code { width: 105px; flex-shrink: 0; }
.phone-num  { flex: 1; }
.checkbox-row { display: flex; align-items: flex-start; gap: 8px; margin-top: 6px; }
.checkbox-row input[type=checkbox] { width: 15px; height: 15px; accent-color: var(--primary); margin-top: 2px; flex-shrink: 0; cursor: pointer; }
.checkbox-row label { font-size: 13px; color: var(--text); cursor: pointer; line-height: 1.4; }
.checkbox-row label span { display: block; font-size: 11.5px; color: var(--muted); }
.info-icon { display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px; border-radius: 50%; background: #E5E7EB; color: var(--muted); font-size: 8px; font-weight: 700; cursor: default; font-style: normal; }

/* Affiliation search */
.affil-search-wrap { position: relative; }
.affil-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: var(--white); border: 1.5px solid var(--border-focus); border-top: none; border-radius: 0 0 8px 8px; max-height: 220px; overflow-y: auto; z-index: 400; box-shadow: var(--shadow-md); display: none; }
.affil-dropdown-item { padding: 9px 14px; font-size: 13px; cursor: pointer; transition: background .1s; border-bottom: 1px solid #f3f4f6; }
.affil-dropdown-item:last-child { border-bottom: none; }
.affil-dropdown-item:hover { background: var(--primary-light); }
.affil-dropdown-item .affil-sub { font-size: 11px; color: var(--muted); }
.affil-dropdown-addnew { padding: 9px 14px; font-size: 13px; font-weight: 600; color: var(--primary); cursor: pointer; display: flex; align-items: center; gap: 7px; border-top: 1.5px dashed #FDDCCC; background: #FFF8F5; transition: background .15s; position: sticky; bottom: 0; }
.affil-dropdown-addnew:hover { background: var(--primary-light); }
.affil-tags { display: flex; flex-direction: column; gap: 6px; margin-top: 8px; }
.affil-tag { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--blue-light); border: 1px solid #C7D6EC; border-radius: 8px; font-size: 12.5px; color: var(--blue); }
.affil-tag-name { flex: 1; font-weight: 500; }
.affil-tag-actions { display: flex; gap: 4px; }
.affil-tag-btn { width: 22px; height: 22px; border-radius: 4px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 11px; transition: background .15s; }
.affil-tag-del { background: #FEF2F2; color: var(--error); }
.affil-tag-del:hover { background: #FECACA; }
.affil-label { font-size: 12px; font-weight: 600; color: var(--muted); margin-top: 10px; margin-bottom: 4px; }
.affil-add-form { display: none; margin-top: 10px; background: #F0F9FF; border: 1.5px solid #BFDBFE; border-radius: 10px; padding: 14px 16px; }
.affil-add-form.open { display: block; animation: fadeSlideIn .2s ease; }
@keyframes fadeSlideIn { from{opacity:0;transform:translateY(-6px)} to{opacity:1;transform:translateY(0)} }
.affil-add-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.affil-add-title span { font-size: 13px; font-weight: 700; color: #1D4ED8; }
.affil-add-close { background: none; border: none; cursor: pointer; color: var(--muted); font-size: 18px; line-height: 1; padding: 0; }
.affil-add-close:hover { color: var(--error); }
.affil-add-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 12px; }
.affil-add-full { grid-column: 1/-1; }
.affil-add-label { display: block; font-size: 11.5px; font-weight: 600; color: var(--text); margin-bottom: 4px; }
.affil-add-opt { font-weight: 400; color: var(--muted); }
.affil-add-input { width: 100%; padding: 7px 10px; border: 1.5px solid #BFDBFE; border-radius: 7px; font-family: var(--font); font-size: 12.5px; color: var(--text); outline: none; background: var(--white); transition: border-color .15s; }
.affil-add-input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(224,90,43,.10); }
.affil-add-input.inp-error { border-color: var(--error); }
.affil-add-actions { display: flex; gap: 8px; justify-content: flex-end; }
.affil-btn-cancel { padding: 7px 14px; border-radius: 7px; background: var(--white); color: var(--muted); border: 1.5px solid var(--border); font-size: 12.5px; font-weight: 600; cursor: pointer; font-family: var(--font); }
.affil-btn-cancel:hover { border-color: var(--primary); color: var(--primary); }
.affil-btn-save { padding: 7px 14px; border-radius: 7px; background: var(--primary); color: #fff; border: none; font-size: 12.5px; font-weight: 600; cursor: pointer; font-family: var(--font); display: flex; align-items: center; gap: 5px; }
.affil-btn-save:hover { background: var(--primary-dark); }
.affil-btn-save:disabled { opacity: .6; cursor: not-allowed; }
.partner-box { background: #EFF6FF; border: 1px solid #BFDBFE; border-radius: 8px; padding: 11px 13px; margin-top: 10px; font-size: 12.5px; color: #1E40AF; display: flex; gap: 10px; align-items: flex-start; }

/* Contributions */
.contrib-section { border-top: 1px solid var(--border); margin-top: 16px; padding-top: 16px; }
.contrib-heading { font-size: 13.5px; font-weight: 700; color: var(--text); margin-bottom: 4px; display: flex; align-items: center; gap: 6px; }
.contrib-subtext { font-size: 12.5px; color: var(--muted); margin-bottom: 12px; }
.contrib-error { font-size: 12px; color: var(--error); display: flex; align-items: center; gap: 6px; margin-bottom: 10px; }
.contrib-grid { display: grid; grid-template-columns: 240px 1fr; gap: 14px; align-items: start; }
@media(max-width:700px) { .contrib-grid { grid-template-columns: 1fr; } }
.contrib-group { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; }
.contrib-group-title { font-size: 12px; font-weight: 700; color: var(--text); margin-bottom: 10px; display: flex; align-items: center; gap: 6px; }
.contrib-checkbox-wrap { display: flex; flex-direction: column; gap: 8px; }
.contrib-checkbox { display: flex; align-items: center; gap: 8px; font-size: 12.5px; cursor: pointer; }
.contrib-checkbox input[type=checkbox] { width: 14px; height: 14px; accent-color: var(--primary); cursor: pointer; flex-shrink: 0; }
.contrib-additional { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; }
.contrib-additional-title { font-size: 12px; font-weight: 700; color: var(--text); margin-bottom: 10px; display: flex; align-items: center; gap: 6px; }
.contrib-extra-grid { display: grid; grid-template-columns: repeat(4,1fr); gap: 8px; }
@media(max-width:900px) { .contrib-extra-grid { grid-template-columns: repeat(2,1fr); } }
@media(max-width:500px) { .contrib-extra-grid { grid-template-columns: 1fr; } }

.add-author-wrap { display: flex; justify-content: center; margin: 6px 0 22px; }
.btn-add-author { display: inline-flex; align-items: center; gap: 6px; padding: 10px 24px; border: 1.5px dashed #93C5FD; border-radius: var(--radius); background: #F0F9FF; color: #1D4ED8; font-size: 13px; font-weight: 600; cursor: pointer; font-family: var(--font); transition: all .15s; }
.btn-add-author:hover { background: #DBEAFE; border-color: #60A5FA; }

/* Bottom sticky bar */
.bottom-bar { position: fixed; bottom: 0; left: var(--sidebar-w, 240px); right: 0; background: var(--white); border-top: 1px solid var(--border); padding: 11px 28px; display: flex; align-items: center; justify-content: space-between; z-index: 300; box-shadow: 0 -2px 12px rgba(0,0,0,.08); flex-wrap: wrap; gap: 10px; }
.bottom-fee { font-size: 13px; color: var(--muted); }
.bottom-fee strong { color: var(--text); font-size: 13.5px; }
.bottom-quality { font-size: 13px; display: flex; align-items: center; gap: 8px; }
.quality-score { font-weight: 700; font-size: 15px; color: var(--primary); }
.bottom-actions { display: flex; gap: 10px; align-items: center; }

.btn { display: inline-flex; align-items: center; gap: 6px; padding: 9px 18px; border-radius: 8px; font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; border: none; transition: all .15s; text-decoration: none; }
.btn-preview { background: var(--white); color: var(--blue); border: 1.5px solid var(--blue); }
.btn-preview:hover { background: var(--blue-light); }
.btn-submit  { background: var(--primary); color: #fff; padding: 9px 22px; }
.btn-submit:hover { background: var(--primary-dark); }
.btn-save    { background: var(--white); color: var(--text); border: 1.5px solid var(--border); }
.btn-save:hover { border-color: var(--primary); color: var(--primary); }
.btn-back    { background: var(--white); color: var(--blue); border: 1.5px solid var(--border); }
.btn-back:hover { border-color: var(--blue); background: var(--blue-light); }
.btn:disabled { opacity: .6; cursor: not-allowed; }

.toast-container { position: fixed; bottom: 80px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 11px 16px; border-radius: var(--radius); font-size: 13px; font-weight: 500; box-shadow: var(--shadow-md); min-width: 230px; max-width: 340px; display: flex; align-items: center; gap: 8px; animation: slideUp .25s ease; color: #fff; }
.toast-success { background: #1D8A5E; } .toast-error { background: #DC2626; } .toast-info { background: var(--blue); }
@keyframes slideUp { from{transform:translateY(16px);opacity:0} to{transform:translateY(0);opacity:1} }
.spinner { display: inline-block; width: 14px; height: 14px; 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>

<div class="page-wrap">
  <div class="breadcrumb">
    <a href="dashboard.php">Overview</a>
    <span>›</span>
    <a href="submission.php?id=<?= $submission_id ?>">Submission Details</a>
    <span>›</span>
    <a href="manuscript.php?id=<?= $submission_id ?>">Manuscript Information</a>
    <span>›</span>
    <span>Authors &amp; Contributors</span>
  </div>

  <div class="section-heading" onclick="toggleSection()">
    <div class="section-heading-left">
      Authors and contributors
      <span class="info-icon" title="Provide details for all authors">i</span>
    </div>
    <div style="display:flex;align-items:center;gap:16px">
      <span class="section-badge-incomplete" id="sectionBadge">
        <span style="font-size:14px">●</span> Incomplete
      </span>
      <span class="section-collapse open" id="collapseIcon">∧</span>
    </div>
  </div>

  <div class="section-body" id="sectionBody">

    <div class="section-desc">
      <p><strong>Authors details</strong> <span class="info-icon">i</span></p>
      <p>Please provide the complete list of authors who contributed to this work and their affiliation details. The author order is from top to bottom, with the first author at the top.</p>
      <p>Please note that authors must ensure the author list is correct and in line with our authorship and contributions policies at the time of submission. Where there are discrepancies in the manuscript doc or text files and the submission system, the author list will be taken from the submission system by default.
        Please ensure the submission system is accurate, as changes to the author list may not be permitted later in the process
        (<a href="https://communeglobal.com/journals/social-science/author-style-guidelines" target="_blank" rel="noopener">author guidelines</a>).
      </p>
    </div>

    <div id="authorsContainer">
      <?php foreach ($authors as $idx => $author):
        $authorIdx = $idx;
        $authorId  = (int)$author['author_id'];
        $contrib   = $contributions[$authorId] ?? [];
        $ordinal   = ['1st','2nd','3rd','4th','5th','6th','7th','8th'][$idx] ?? ($idx+1).'th';
        $isFirst   = $idx === 0;
        $isLast    = $idx === count($authors) - 1;
      ?>
      <div class="author-card" id="authorCard_<?= $authorIdx ?>" data-idx="<?= $authorIdx ?>">
        <div class="author-card-header">
          <span class="author-label"><?= $ordinal ?> Author</span>
          <div class="author-actions">
            <button type="button" class="author-action-btn" onclick="moveAuthor(<?= $authorIdx ?>,'up')" <?= $isFirst?'disabled':'' ?>>▲ Move up</button>
            <button type="button" class="author-action-btn" onclick="moveAuthor(<?= $authorIdx ?>,'down')" <?= $isLast?'disabled':'' ?>>▼ Move down</button>
            <?php if (!$isFirst): ?>
            <button type="button" class="author-action-btn btn-delete" onclick="removeAuthor(<?= $authorIdx ?>)">🗑</button>
            <?php endif; ?>
          </div>
        </div>
        <div class="author-card-body">
          <div class="form-row form-row-email-title">
            <div class="form-group">
              <label class="form-label">Email</label>
              <input type="email" class="form-input" name="email_<?= $authorIdx ?>"
                     placeholder="Start by entering the email address"
                     value="<?= htmlspecialchars($author['email']??'') ?>"
                     <?= $isFirst?'readonly style="background:#F9FAFB;color:var(--muted)"':'' ?>
                     oninput="onFieldChange(<?= $authorIdx ?>,'email',this)"
                     onblur="validateEmail(<?= $authorIdx ?>)">
              <div class="field-error" id="emailErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span><span>Please enter a valid email address</span>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Title <?= !$isFirst?'<span class="optional-lbl">(optional)</span>':'' ?></label>
              <select class="form-select" name="title_<?= $authorIdx ?>" onchange="onFieldChange(<?= $authorIdx ?>,'title',this)">
                <?php foreach ($titles as $t): ?>
                  <option value="<?= $t ?>" <?= ($author['title']??'') === $t?'selected':'' ?>><?= $t?:'— Title —' ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group" style="grid-row:1/3">
              <?= affilBlock($authorIdx, $author) ?>
              <?php if ($isFirst): ?>
              <div class="partner-box">
                <span style="font-size:18px;flex-shrink:0">ℹ️</span>
                <div><strong>Institutional Partnerships</strong><br>Based on institutional emails and affiliations we can automatically identify partnerships to cover publishing costs.</div>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <div class="form-row form-row-3" style="margin-bottom:12px">
            <div class="form-group">
              <label class="form-label">First name</label>
              <input type="text" class="form-input" name="first_name_<?= $authorIdx ?>"
                     placeholder="First name" value="<?= htmlspecialchars($author['first_name']??'') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'first_name',this)"
                     onblur="validateRequired(<?= $authorIdx ?>,'first_name')">
              <div class="field-error" id="firstNameErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span><span>Please fill this field</span>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Middle name <span class="optional-lbl">(optional)</span></label>
              <input type="text" class="form-input" name="middle_name_<?= $authorIdx ?>"
                     placeholder="Middle name" value="<?= htmlspecialchars($author['middle_name']??'') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'middle_name',this)">
            </div>
            <div class="form-group">
              <label class="form-label">Last name</label>
              <input type="text" class="form-input" name="last_name_<?= $authorIdx ?>"
                     placeholder="Last name" value="<?= htmlspecialchars($author['last_name']??'') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'last_name',this)"
                     onblur="validateRequired(<?= $authorIdx ?>,'last_name')">
              <div class="field-error" id="lastNameErr_<?= $authorIdx ?>" style="display:none">
                <span class="field-error-icon">!</span><span>Please fill this field</span>
              </div>
            </div>
          </div>
          <div class="form-row form-row-3" style="margin-bottom:4px">
            <div class="form-group">
              <label class="form-label">Phone Number</label>
              <div class="phone-wrap">
                <select class="form-select phone-code" name="phone_code_<?= $authorIdx ?>" onchange="onFieldChange(<?= $authorIdx ?>,'phone_country_code',this)">
                  <?php foreach ($countryCodes as $code => $country): ?>
                    <option value="<?= $code ?>" <?= ($author['phone_country_code']??'')===$code?'selected':'' ?>><?= $code ?></option>
                  <?php endforeach; ?>
                </select>
                <input type="tel" class="form-input phone-num" name="phone_<?= $authorIdx ?>"
                       placeholder="Phone number" value="<?= htmlspecialchars($author['phone_number']??'') ?>"
                       oninput="onFieldChange(<?= $authorIdx ?>,'phone_number',this)">
              </div>
            </div>
            <div class="form-group" style="justify-content:flex-end;padding-bottom:4px">
              <label class="form-label">&nbsp;</label>
              <div class="checkbox-row">
                <input type="checkbox" id="corresponding_<?= $authorIdx ?>"
                       <?= $author['is_corresponding']?'checked':'' ?>
                       onchange="onFieldChange(<?= $authorIdx ?>,'is_corresponding',this)">
                <label for="corresponding_<?= $authorIdx ?>">This is a corresponding author<span>(optional)</span></label>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Institutional email <span class="optional-lbl">(optional)</span></label>
              <input type="email" class="form-input" name="inst_email_<?= $authorIdx ?>"
                     placeholder="Institutional email address"
                     value="<?= htmlspecialchars($author['institutional_email']??'') ?>"
                     oninput="onFieldChange(<?= $authorIdx ?>,'institutional_email',this)">
            </div>
          </div>
          <!-- Contributions -->
          <div class="contrib-section">
            <div class="contrib-heading">Author contribution <span class="info-icon" title="CRediT taxonomy">i</span></div>
            <div class="contrib-subtext">Select the areas in which the author contributed</div>
            <div class="field-error contrib-error" id="contribErr_<?= $authorIdx ?>" style="display:none">
              <span class="field-error-icon">!</span> Please select at least one mandatory contribution
            </div>
            <div class="contrib-grid">
              <div class="contrib-group">
                <div class="contrib-group-title">
                  <input type="checkbox" id="mandatoryAll_<?= $authorIdx ?>" onchange="toggleMandatoryAll(<?= $authorIdx ?>,this)" style="accent-color:var(--primary);width:14px;height:14px">
                  <label for="mandatoryAll_<?= $authorIdx ?>" style="cursor:pointer;font-size:12px;font-weight:700">Mandatory contribution</label>
                </div>
                <div class="contrib-checkbox-wrap">
                  <?php foreach ($creditFields['mandatory'] as $key => $label): ?>
                  <label class="contrib-checkbox">
                    <input type="checkbox" id="credit_<?= $key ?>_<?= $authorIdx ?>"
                           <?= !empty($contrib[$key])?'checked':'' ?>
                           onchange="onContribChange(<?= $authorIdx ?>)">
                    <?= htmlspecialchars($label) ?>
                  </label>
                  <?php endforeach; ?>
                </div>
              </div>
              <div class="contrib-additional">
                <div class="contrib-additional-title">
                  <input type="checkbox" id="additionalAll_<?= $authorIdx ?>" onchange="toggleAdditionalAll(<?= $authorIdx ?>,this)" style="accent-color:var(--primary);width:14px;height:14px">
                  <label for="additionalAll_<?= $authorIdx ?>" style="cursor:pointer;font-size:12px;font-weight:700">Additional contribution <span style="font-weight:400;color:var(--muted)">(Optional)</span></label>
                </div>
                <div class="contrib-extra-grid">
                  <?php foreach ($creditFields['additional'] as $key => $label): ?>
                  <label class="contrib-checkbox">
                    <input type="checkbox" id="credit_<?= $key ?>_<?= $authorIdx ?>"
                           <?= !empty($contrib[$key])?'checked':'' ?>
                           onchange="onContribChange(<?= $authorIdx ?>)">
                    <?= htmlspecialchars($label) ?>
                  </label>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <div class="add-author-wrap">
      <button type="button" class="btn-add-author" onclick="addAuthor()">＋ Add another author</button>
    </div>

    <div style="display:flex;gap:10px;justify-content:flex-end;padding-top:14px;border-top:1px solid var(--border)">
      <a href="manuscript.php?id=<?= $submission_id ?>" class="btn btn-back">← Back</a>
      <button type="button" class="btn btn-save" onclick="saveAuthors(false)" id="saveBtn">💾 Save</button>
      <button type="button" class="btn btn-preview" onclick="saveAuthors(true)" id="saveContinueBtn"
              style="background:var(--blue);color:#fff">Save &amp; Continue →</button>
    </div>
  </div>
</div>

<!-- Bottom sticky bar -->
<div class="bottom-bar">
  <div class="bottom-fee">
    Preliminary fee: <strong>$35.00 USD</strong><br>
    <span style="font-size:11px">Payment after acceptance</span>
  </div>
  <div class="bottom-quality">
    Submission quality: <span class="quality-score" id="qualityPct">90%</span>
    <div><div style="font-size:11.5px;color:var(--muted)">⚠ <span id="suggestedCount">1</span> suggested action</div></div>
  </div>
  <div class="bottom-actions">
    <button class="btn btn-preview">Preview</button>
    <button class="btn btn-submit">🔵 Submit</button>
  </div>
</div>

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

<!-- Author template for dynamic add -->
<template id="authorTemplate">
  <div class="author-card" id="authorCard_IDX" data-idx="IDX">
    <div class="author-card-header">
      <span class="author-label">ORD Author</span>
      <div class="author-actions">
        <button type="button" class="author-action-btn" onclick="moveAuthor(IDX,'up')">▲ Move up</button>
        <button type="button" class="author-action-btn" onclick="moveAuthor(IDX,'down')">▼ Move down</button>
        <button type="button" class="author-action-btn btn-delete" onclick="removeAuthor(IDX)">🗑</button>
      </div>
    </div>
    <div class="author-card-body">
      <div class="form-row form-row-email-title">
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="email" class="form-input" name="email_IDX" placeholder="Email address"
                 oninput="onFieldChange(IDX,'email',this)" onblur="validateEmail(IDX)">
          <div class="field-error" id="emailErr_IDX" style="display:none"><span class="field-error-icon">!</span><span>Please enter a valid email</span></div>
        </div>
        <div class="form-group">
          <label class="form-label">Title <span class="optional-lbl">(optional)</span></label>
          <select class="form-select" name="title_IDX" onchange="onFieldChange(IDX,'title',this)">
            <option value="">— Title —</option>
            <option>Mr</option><option>Mrs</option><option>Ms</option><option>Dr</option><option>Prof</option>
          </select>
        </div>
        <div class="form-group" style="grid-row:1/3">
          <label class="form-label">Affiliation</label>
          <div class="affil-search-wrap">
            <input type="text" class="form-input" id="affilSearch_IDX"
                   placeholder="Search university / institution..." autocomplete="off"
                   oninput="onAffilSearch(IDX,this)" onblur="hideAffilDropdown(IDX)">
            <div class="affil-dropdown" id="affilDrop_IDX"></div>
          </div>
          <div class="field-error" id="affilErr_IDX" style="display:none"><span class="field-error-icon">!</span><span>Please fill this field</span></div>
          <div class="affil-label" id="affilTagsLabel_IDX" style="display:none">Selected affiliation</div>
          <div class="affil-tags" id="affilTags_IDX"></div>
          <div class="affil-add-form" id="affilAddForm_IDX">
            <div class="affil-add-title">
              <span>🏛 Add new affiliation</span>
              <button type="button" class="affil-add-close" onclick="toggleAffilForm(IDX,false)">✕</button>
            </div>
            <div class="affil-add-grid">
              <div class="affil-add-full">
                <label class="affil-add-label">Institution / University Name <span style="color:var(--error)">*</span></label>
                <input type="text" class="affil-add-input" id="newAffilName_IDX" placeholder="e.g. Harvard University">
              </div>
              <div><label class="affil-add-label">Department <span class="affil-add-opt">(optional)</span></label>
                <input type="text" class="affil-add-input" id="newAffilDept_IDX" placeholder="e.g. Computer Science"></div>
              <div><label class="affil-add-label">City <span class="affil-add-opt">(optional)</span></label>
                <input type="text" class="affil-add-input" id="newAffilCity_IDX" placeholder="e.g. Cambridge"></div>
              <div><label class="affil-add-label">State / Province <span class="affil-add-opt">(optional)</span></label>
                <input type="text" class="affil-add-input" id="newAffilState_IDX" placeholder="e.g. Massachusetts"></div>
              <div><label class="affil-add-label">Country <span class="affil-add-opt">(optional)</span></label>
                <input type="text" class="affil-add-input" id="newAffilCountry_IDX" placeholder="e.g. USA"></div>
            </div>
            <div class="affil-add-actions">
              <button type="button" class="affil-btn-cancel" onclick="toggleAffilForm(IDX,false)">Cancel</button>
              <button type="button" class="affil-btn-save" id="affilSaveBtn_IDX" onclick="saveNewAffiliation(IDX)">💾 Save & Select</button>
            </div>
          </div>
        </div>
      </div>
      <div class="form-row form-row-3" style="margin-bottom:12px">
        <div class="form-group"><label class="form-label">First name</label>
          <input type="text" class="form-input" name="first_name_IDX" placeholder="First name"
                 oninput="onFieldChange(IDX,'first_name',this)" onblur="validateRequired(IDX,'first_name')">
          <div class="field-error" id="firstNameErr_IDX" style="display:none"><span class="field-error-icon">!</span><span>Please fill this field</span></div>
        </div>
        <div class="form-group"><label class="form-label">Middle name <span class="optional-lbl">(optional)</span></label>
          <input type="text" class="form-input" name="middle_name_IDX" placeholder="Middle name" oninput="onFieldChange(IDX,'middle_name',this)">
        </div>
        <div class="form-group"><label class="form-label">Last name</label>
          <input type="text" class="form-input" name="last_name_IDX" placeholder="Last name"
                 oninput="onFieldChange(IDX,'last_name',this)" onblur="validateRequired(IDX,'last_name')">
          <div class="field-error" id="lastNameErr_IDX" style="display:none"><span class="field-error-icon">!</span><span>Please fill this field</span></div>
        </div>
      </div>
      <div class="form-row form-row-3" style="margin-bottom:4px">
        <div class="form-group"><label class="form-label">Phone Number</label>
          <div class="phone-wrap">
            <select class="form-select phone-code" name="phone_code_IDX" onchange="onFieldChange(IDX,'phone_country_code',this)">
              <option value="+91">+91</option><option value="+1">+1</option><option value="+44">+44</option>
              <option value="+49">+49</option><option value="+33">+33</option><option value="+81">+81</option>
            </select>
            <input type="tel" class="form-input phone-num" name="phone_IDX" placeholder="Phone number" oninput="onFieldChange(IDX,'phone_number',this)">
          </div>
        </div>
        <div class="form-group" style="justify-content:flex-end;padding-bottom:4px">
          <label class="form-label">&nbsp;</label>
          <div class="checkbox-row">
            <input type="checkbox" id="corresponding_IDX" onchange="onFieldChange(IDX,'is_corresponding',this)">
            <label for="corresponding_IDX">This is a corresponding author<span>(optional)</span></label>
          </div>
        </div>
        <div class="form-group"><label class="form-label">Institutional email <span class="optional-lbl">(optional)</span></label>
          <input type="email" class="form-input" name="inst_email_IDX" placeholder="Institutional email" oninput="onFieldChange(IDX,'institutional_email',this)">
        </div>
      </div>
      <div class="contrib-section">
        <div class="contrib-heading">Author contribution <span class="info-icon">i</span></div>
        <div class="contrib-subtext">Select the areas in which the author contributed</div>
        <div class="field-error contrib-error" id="contribErr_IDX" style="display:none"><span class="field-error-icon">!</span> Please select at least one mandatory contribution</div>
        <div class="contrib-grid">
          <div class="contrib-group">
            <div class="contrib-group-title">
              <input type="checkbox" id="mandatoryAll_IDX" onchange="toggleMandatoryAll(IDX,this)" style="accent-color:var(--primary);width:14px;height:14px">
              <label for="mandatoryAll_IDX" style="cursor:pointer;font-size:12px;font-weight:700">Mandatory contribution</label>
            </div>
            <div class="contrib-checkbox-wrap">
              <label class="contrib-checkbox"><input type="checkbox" id="credit_writing_original_draft_IDX" onchange="onContribChange(IDX)"> Writing – original draft</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_writing_review_editing_IDX" onchange="onContribChange(IDX)"> Writing – review &amp; editing</label>
            </div>
          </div>
          <div class="contrib-additional">
            <div class="contrib-additional-title">
              <input type="checkbox" id="additionalAll_IDX" onchange="toggleAdditionalAll(IDX,this)" style="accent-color:var(--primary);width:14px;height:14px">
              <label for="additionalAll_IDX" style="cursor:pointer;font-size:12px;font-weight:700">Additional contribution <span style="font-weight:400;color:var(--muted)">(Optional)</span></label>
            </div>
            <div class="contrib-extra-grid">
              <label class="contrib-checkbox"><input type="checkbox" id="credit_conceptualization_IDX" onchange="onContribChange(IDX)"> Conceptualization</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_data_curation_IDX" onchange="onContribChange(IDX)"> Data curation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_formal_analysis_IDX" onchange="onContribChange(IDX)"> Formal Analysis</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_funding_acquisition_IDX" onchange="onContribChange(IDX)"> Funding acquisition</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_investigation_IDX" onchange="onContribChange(IDX)"> Investigation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_methodology_IDX" onchange="onContribChange(IDX)"> Methodology</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_project_administration_IDX" onchange="onContribChange(IDX)"> Project administration</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_resources_IDX" onchange="onContribChange(IDX)"> Resources</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_software_IDX" onchange="onContribChange(IDX)"> Software</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_supervision_IDX" onchange="onContribChange(IDX)"> Supervision</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_validation_IDX" onchange="onContribChange(IDX)"> Validation</label>
              <label class="contrib-checkbox"><input type="checkbox" id="credit_visualization_IDX" onchange="onContribChange(IDX)"> Visualization</label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const SUBMISSION_ID = <?= $submission_id ?>;
const ORDINALS = ['1st','2nd','3rd','4th','5th','6th','7th','8th'];

let authorData = <?= json_encode(array_values(array_map(function($a){
    return [
        'author_id'=>(int)$a['author_id'],'email'=>$a['email']??'','title'=>$a['title']??'',
        'first_name'=>$a['first_name']??'','middle_name'=>$a['middle_name']??'','last_name'=>$a['last_name']??'',
        'phone_country_code'=>$a['phone_country_code']??'+91','phone_number'=>$a['phone_number']??'',
        'institutional_email'=>$a['institutional_email']??'','affiliation_id'=>(int)($a['affiliation_id']??0),
        'affil_name'=>$a['affil_name']??'','affil_city'=>$a['affil_city']??'','affil_country'=>$a['affil_country']??'',
        'is_corresponding'=>(int)($a['is_corresponding']??0),
    ];
}, $authors))) ?>;

let autoSaveTimer = null;

function toggleSection() {
    const body = document.getElementById('sectionBody');
    const icon = document.getElementById('collapseIcon');
    const visible = body.style.display !== 'none';
    body.style.display = visible ? 'none' : 'block';
    icon.classList.toggle('open', !visible);
}
function onFieldChange(idx, field, el) {
    if (!authorData[idx]) return;
    authorData[idx][field] = el.type === 'checkbox' ? (el.checked?1:0) : el.value;
    scheduleAutoSave();
}
function validateEmail(idx) {
    const el = document.querySelector(`[name="email_${idx}"]`);
    const err = document.getElementById(`emailErr_${idx}`);
    if (!el||!err) return true;
    const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(el.value.trim());
    el.classList.toggle('has-error', !valid && el.value.length > 0);
    err.style.display = (!valid && el.value.length > 0) ? 'flex' : 'none';
    return valid;
}
function validateRequired(idx, field) {
    const el    = document.querySelector(`[name="${field}_${idx}"]`);
    const errId = field==='first_name' ? `firstNameErr_${idx}` : `lastNameErr_${idx}`;
    const err   = document.getElementById(errId);
    if (!el||!err) return true;
    const valid = el.value.trim().length > 0;
    el.classList.toggle('has-error', !valid);
    err.style.display = !valid ? 'flex' : 'none';
    return valid;
}
function validateAffil(idx) {
    const tags    = document.getElementById(`affilTags_${idx}`);
    const err     = document.getElementById(`affilErr_${idx}`);
    const hasTags = tags && tags.querySelectorAll('.affil-tag').length > 0;
    if (err) err.style.display = !hasTags ? 'flex' : 'none';
    return hasTags;
}
function validateContrib(idx) {
    const m1  = document.getElementById(`credit_writing_original_draft_${idx}`);
    const m2  = document.getElementById(`credit_writing_review_editing_${idx}`);
    const any = (m1&&m1.checked)||(m2&&m2.checked);
    const err = document.getElementById(`contribErr_${idx}`);
    if (err) err.style.display = !any ? 'flex' : 'none';
    return any;
}
function validateAll() {
    let valid = true;
    const count = document.querySelectorAll('.author-card').length;
    for (let i=0;i<count;i++) {
        if (!validateEmail(i))           valid=false;
        if (!validateRequired(i,'first_name')) valid=false;
        if (!validateRequired(i,'last_name'))  valid=false;
        if (!validateAffil(i))           valid=false;
        if (!validateContrib(i))         valid=false;
    }
    return valid;
}

/* ── Affiliation search ── */
let affilTimer = null;
function onAffilSearch(idx, el) {
    clearTimeout(affilTimer);
    const q = el.value.trim();
    if (!q) { hideAffilDropdown(idx); return; }
    affilTimer = setTimeout(() => {
        fetch(`ajax/search_affiliations.php?q=${encodeURIComponent(q)}`)
        .then(r=>r.json())
        .then(data=>{ if(data.success) renderAffilDropdown(idx, data.affiliations, q); })
        .catch(()=>hideAffilDropdown(idx));
    }, 280);
}
function renderAffilDropdown(idx, results, q) {
    const dd = document.getElementById(`affilDrop_${idx}`);
    let html = '';
    if (!results.length) {
        html = `<div class="affil-dropdown-item" style="color:var(--muted);cursor:default;font-size:12px">No results for "<strong>${escHtml(q)}</strong>"</div>`;
    } else {
        html = results.map(a =>
            `<div class="affil-dropdown-item" onmousedown="selectAffil(${idx},${a.affiliation_id},'${escAttr(a.name)}','${escAttr(a.city||'')}','${escAttr(a.country||'')}')">
               <strong>${escHtml(a.name)}</strong>
               <div class="affil-sub">${escHtml([a.city,a.country].filter(Boolean).join(', '))}</div>
             </div>`
        ).join('');
    }
    html += `<div class="affil-dropdown-addnew" onmousedown="toggleAffilForm(${idx},true)">➕ My university is not listed — Add new</div>`;
    dd.innerHTML = html; dd.style.display = 'block';
}
function hideAffilDropdown(idx) {
    setTimeout(()=>{ const dd=document.getElementById(`affilDrop_${idx}`); if(dd) dd.style.display='none'; },150);
}
function selectAffil(idx, affilId, name, city, country) {
    const tagsEl  = document.getElementById(`affilTags_${idx}`);
    const labelEl = document.getElementById(`affilTagsLabel_${idx}`);
    if (tagsEl) {
        tagsEl.innerHTML = `<div class="affil-tag" data-affil-id="${affilId}">
          <span class="affil-tag-name">${escHtml(name)}${city?', '+escHtml(city):''}${country?', '+escHtml(country):''}</span>
          <div class="affil-tag-actions"><button type="button" class="affil-tag-btn affil-tag-del" onclick="removeAffil(${idx},this)" title="Remove">✕</button></div>
        </div>`;
    }
    if (labelEl) labelEl.style.display = 'block';
    if (authorData[idx]) { authorData[idx].affiliation_id=affilId; authorData[idx].affil_name=name; }
    const si = document.getElementById(`affilSearch_${idx}`); if(si) si.value='';
    hideAffilDropdown(idx); validateAffil(idx); scheduleAutoSave();
}
function removeAffil(idx, btn) {
    btn.closest('.affil-tag')?.remove();
    if (authorData[idx]) authorData[idx].affiliation_id=0;
    validateAffil(idx); scheduleAutoSave();
}
function toggleAffilForm(idx, show) {
    const form = document.getElementById(`affilAddForm_${idx}`);
    if (!form) return;
    if (show) {
        const q = document.getElementById(`affilSearch_${idx}`)?.value.trim()||'';
        const nameEl = document.getElementById(`newAffilName_${idx}`);
        if (nameEl && !nameEl.value && q) nameEl.value = q;
        form.classList.add('open'); hideAffilDropdown(idx);
        setTimeout(()=>document.getElementById(`newAffilName_${idx}`)?.focus(),60);
    } else {
        form.classList.remove('open');
        ['Name','Dept','City','State','Country'].forEach(f=>{
            const el=document.getElementById(`newAffil${f}_${idx}`);
            if(el){el.value='';el.classList.remove('inp-error');}
        });
    }
}
function saveNewAffiliation(idx) {
    const nameEl = document.getElementById(`newAffilName_${idx}`);
    const name   = nameEl?.value.trim()||'';
    if (!name) { nameEl?.classList.add('inp-error'); nameEl?.focus(); showToast('Please enter the institution name.','error'); return; }
    nameEl?.classList.remove('inp-error');
    const dept    = document.getElementById(`newAffilDept_${idx}`)?.value.trim()||'';
    const city    = document.getElementById(`newAffilCity_${idx}`)?.value.trim()||'';
    const state   = document.getElementById(`newAffilState_${idx}`)?.value.trim()||'';
    const country = document.getElementById(`newAffilCountry_${idx}`)?.value.trim()||'';
    const btn = document.getElementById(`affilSaveBtn_${idx}`);
    if (btn) { btn.disabled=true; btn.innerHTML='<span class="spinner"></span> Saving…'; }
    const fd=new FormData(); fd.append('name',name); fd.append('department',dept);
    fd.append('city',city); fd.append('state',state); fd.append('country',country);
    fetch('authors.php?ajax=save_affiliation',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(data=>{
        if(btn){btn.disabled=false;btn.innerHTML='💾 Save & Select';}
        if(data.success){ selectAffil(idx,data.affiliation_id,name,city,country); toggleAffilForm(idx,false);
            showToast(data.duplicate?'✓ Existing affiliation selected!':'✓ Affiliation created and selected!','success');
        } else showToast('Error: '+(data.message||'Could not save'),'error');
    })
    .catch(()=>{ if(btn){btn.disabled=false;btn.innerHTML='💾 Save & Select';} showToast('Network error — please try again.','error'); });
}

/* ── Contributions ── */
function onContribChange(idx) {
    validateContrib(idx);
    const m1=document.getElementById(`credit_writing_original_draft_${idx}`);
    const m2=document.getElementById(`credit_writing_review_editing_${idx}`);
    const master=document.getElementById(`mandatoryAll_${idx}`);
    if(master&&m1&&m2){ master.checked=m1.checked&&m2.checked; master.indeterminate=(m1.checked||m2.checked)&&!(m1.checked&&m2.checked); }
    scheduleAutoSave();
}
function toggleMandatoryAll(idx,master){
    ['writing_original_draft','writing_review_editing'].forEach(k=>{const el=document.getElementById(`credit_${k}_${idx}`);if(el)el.checked=master.checked;});
    validateContrib(idx); scheduleAutoSave();
}
function toggleAdditionalAll(idx,master){
    ['conceptualization','data_curation','formal_analysis','funding_acquisition','investigation','methodology',
     'project_administration','resources','software','supervision','validation','visualization'].forEach(k=>{
        const el=document.getElementById(`credit_${k}_${idx}`);if(el)el.checked=master.checked;
    });
    scheduleAutoSave();
}

/* ── Add / Remove / Move ── */
function addAuthor(){
    const idx=authorData.length; const ord=ORDINALS[idx]||(idx+1)+'th';
    const tmpl=document.getElementById('authorTemplate');
    let html=tmpl.innerHTML.replaceAll('IDX',idx).replaceAll('ORD',ord);
    const temp=document.createElement('div'); temp.innerHTML=html;
    document.getElementById('authorsContainer').appendChild(temp.firstElementChild);
    authorData.push({author_id:0,email:'',title:'',first_name:'',middle_name:'',last_name:'',
        phone_country_code:'+91',phone_number:'',institutional_email:'',affiliation_id:0,affil_name:'',is_corresponding:0});
    refreshAuthorButtons();
    temp.firstElementChild?.scrollIntoView({behavior:'smooth',block:'start'});
}
function removeAuthor(idx){
    if(idx===0)return; if(!confirm('Remove this author?'))return;
    document.getElementById(`authorCard_${idx}`)?.remove();
    authorData.splice(idx,1); rebuildAuthorIndices(); scheduleAutoSave();
}
function moveAuthor(idx,dir){
    const swapIdx=dir==='up'?idx-1:idx+1;
    if(swapIdx<0||swapIdx>=authorData.length)return;
    [authorData[idx],authorData[swapIdx]]=[authorData[swapIdx],authorData[idx]];
    rebuildAuthorIndices(); scheduleAutoSave();
}
function rebuildAuthorIndices(){
    Array.from(document.querySelectorAll('#authorsContainer .author-card')).forEach((card,i)=>{
        const lbl=card.querySelector('.author-label');
        if(lbl)lbl.textContent=(ORDINALS[i]||(i+1)+'th')+' Author';
    });
    refreshAuthorButtons();
}
function refreshAuthorButtons(){
    const cards=Array.from(document.querySelectorAll('.author-card'));
    cards.forEach((card,i)=>{
        const btns=card.querySelectorAll('.author-action-btn');
        if(btns[0])btns[0].disabled=i===0;
        if(btns[1])btns[1].disabled=i===cards.length-1;
    });
}

/* ── Collect & save ── */
function collectAuthorsPayload(){
    return Array.from(document.querySelectorAll('.author-card')).map((card,i)=>{
        const g=sel=>card.querySelector(sel)?.value??'';
        const creditKeys=['writing_original_draft','writing_review_editing','conceptualization','data_curation',
            'formal_analysis','funding_acquisition','investigation','methodology','project_administration',
            'resources','software','supervision','validation','visualization'];
        const contrib={};
        creditKeys.forEach(k=>{contrib[k]=card.querySelector(`[id^="credit_${k}_"]`)?.checked?1:0;});
        const affilTag=card.querySelector('.affil-tag');
        return {
            author_id:(authorData[i]?.author_id||0), author_order:i+1,
            email:g(`[name="email_${i}"]`), title:g(`[name="title_${i}"]`),
            first_name:g(`[name="first_name_${i}"]`), middle_name:g(`[name="middle_name_${i}"]`),
            last_name:g(`[name="last_name_${i}"]`),
            phone_country_code:g(`[name="phone_code_${i}"]`)||'+91',
            phone_number:g(`[name="phone_${i}"]`),
            institutional_email:g(`[name="inst_email_${i}"]`),
            affiliation_id:affilTag?parseInt(affilTag.dataset.affilId)||0:0,
            is_corresponding:card.querySelector(`[id^="corresponding_"]`)?.checked?1:0,
            contributions:contrib,
        };
    });
}
function scheduleAutoSave(){
    clearTimeout(autoSaveTimer);
    autoSaveTimer=setTimeout(()=>{
        const fd=new FormData(); fd.append('submission_id',SUBMISSION_ID);
        fd.append('authors',JSON.stringify(collectAuthorsPayload()));
        fetch('ajax/save_authors.php',{method:'POST',body:fd})
        .then(r=>r.json()).then(d=>{if(d.success)showToast('Auto-saved','info');})
        .catch(e=>console.error(e));
    },1800);
}
function saveAuthors(andContinue=false){
    if(andContinue&&!validateAll()){
        showToast('Please fill all required fields before continuing.','error');
        document.querySelector('.has-error,.contrib-error[style*="flex"]')?.scrollIntoView({behavior:'smooth',block:'center'});
        return;
    }
    const btn=andContinue?document.getElementById('saveContinueBtn'):document.getElementById('saveBtn');
    btn.disabled=true; btn.innerHTML='<span class="spinner"></span> Saving...';
    const fd=new FormData(); fd.append('submission_id',SUBMISSION_ID);
    fd.append('authors',JSON.stringify(collectAuthorsPayload()));
    fetch('ajax/save_authors.php',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(d=>{
        btn.disabled=false; btn.innerHTML=andContinue?'Save &amp; Continue →':'💾 Save';
        if(d.success){
            showToast('Authors saved!','success');
            if(andContinue)setTimeout(()=>window.location.href=`editorial.php?id=${SUBMISSION_ID}`,800);
        } else showToast(d.message||'Save failed','error');
    })
    .catch(()=>{btn.disabled=false;btn.innerHTML=andContinue?'Save &amp; Continue →':'💾 Save';showToast('Network error','error');});
}

function showToast(msg,type='info'){
    const c=document.getElementById('toastContainer');
    const t=document.createElement('div'); t.className='toast toast-'+type;
    t.innerHTML=`<span>${{success:'✅',error:'❌',info:'ℹ️'}[type]||''}</span> ${escHtml(msg)}`;
    c.appendChild(t); setTimeout(()=>t.remove(),3200);
}
function escHtml(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function escAttr(s){return String(s).replace(/'/g,"\\'").replace(/"/g,'&quot;');}

refreshAuthorButtons();
</script>

<?php layoutEnd(); ?>