<?php
// FILE: author/public_profile.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

if (!in_array($user['role'] ?? '', ['author', 'reviewer', 'both', 'editor'])) {
    header('Location: dashboard.php'); exit;
}

$pageTitle  = 'Public Profile';
$activePage = 'public_profile';

// ── Auto-create reviewer record if missing (shared profile table) ──
$stmt = db()->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$reviewer = $stmt->fetch();

if (!$reviewer) {
    db()->prepare("INSERT INTO reviewers (user_id, reviewer_come_from, is_available, max_reviews_per_period, preferred_review_duration_days, created_at)
                   VALUES (?, 'author_profile', 1, 5, 21, NOW())")->execute([$user_id]);
    $stmt = db()->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $reviewer = $stmt->fetch();
}
$reviewer_id = $reviewer['id'];

$error = $success = null;

// ── AJAX: Create new affiliation ───────────────────────────────
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_GET['action'] ?? '') === 'create_affiliation'
    && isset($_SESSION['user_id'])
) {
    header('Content-Type: application/json');
    $aff_name    = trim($_POST['aff_name']    ?? '');
    $aff_dept    = trim($_POST['aff_dept']    ?? '');
    $aff_city    = trim($_POST['aff_city']    ?? '');
    $aff_state   = trim($_POST['aff_state']   ?? '');
    $aff_country = trim($_POST['aff_country'] ?? '');

    if (!$aff_name || !$aff_country) {
        echo json_encode(['ok' => false, 'msg' => 'Institution name and country are required.']);
        exit;
    }
    try {
        db()->prepare("INSERT INTO affiliations (name, department, city, state, country, is_institutional_partner, created_at) VALUES (?, ?, ?, ?, ?, 0, NOW())")
             ->execute([$aff_name, $aff_dept ?: null, $aff_city ?: null, $aff_state ?: null, $aff_country]);
        $new_id = db()->lastInsertId();
        echo json_encode([
            'ok' => true, 'id' => $new_id, 'name' => $aff_name,
            'dept' => $aff_dept, 'city' => $aff_city, 'state' => $aff_state, 'country' => $aff_country,
            'label' => $aff_name . ($aff_city ? ', '.$aff_city : '') . ($aff_country ? ', '.$aff_country : ''),
        ]);
    } catch (PDOException $e) {
        echo json_encode(['ok' => false, 'msg' => 'DB error: '.$e->getMessage()]);
    }
    exit;
}

// ── POST: Save Public Profile ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_public_profile'])) {
    $bio       = trim($_POST['bio']                   ?? '');
    $position  = trim($_POST['current_position']      ?? '');
    $exp_yrs   = (int)($_POST['total_experience_yrs'] ?? 0) ?: null;
    $h_index   = (int)($_POST['h_index']              ?? 0) ?: null;
    $citations = (int)($_POST['total_citations']       ?? 0) ?: null;
    $orcid     = trim($_POST['orcid_id']               ?? '');
    $website   = null;
    $affil_id  = (int)($_POST['profile_affiliation_id']?? 0) ?: null;

    $edu = [];
    foreach (($_POST['edu_degree'] ?? []) as $i => $deg) {
        $deg = trim($deg); $inst = trim($_POST['edu_institution'][$i] ?? ''); $yr = (int)($_POST['edu_year'][$i] ?? 0);
        if ($deg && $inst && $yr) $edu[] = ['degree'=>$deg,'institution'=>$inst,'year'=>$yr,'order'=>$i];
    }
    $pubs = [];
    foreach (($_POST['pub_title'] ?? []) as $i => $tit) {
        $tit = trim($tit); $jnl = trim($_POST['pub_journal'][$i] ?? ''); $yr = (int)($_POST['pub_year'][$i] ?? 0);
        if ($tit && $jnl && $yr) $pubs[] = ['title'=>$tit,'journal'=>$jnl,'year'=>$yr,'citations'=>(int)($_POST['pub_cites'][$i]??0),'doi'=>trim($_POST['pub_doi'][$i]??'')];
    }
    $socs = array_values(array_filter(array_map('trim', explode("\n", $_POST['societies'] ?? ''))));

    // Slug
    $check = db()->prepare("SELECT slug FROM reviewer_public_profile WHERE user_id = ?");
    $check->execute([$user_id]);
    $existing_slug = ($check->fetch())['slug'] ?? null;
    $slug = $existing_slug;
    if (!$slug) {
        $base = strtolower(preg_replace('/[^a-z0-9]+/', '-', trim($user['first_name'].' '.$user['last_name'])));
        $slug = $base; $n = 2;
        while (true) { $chk = db()->prepare("SELECT id FROM reviewer_public_profile WHERE slug=?"); $chk->execute([$slug]); if (!$chk->fetch()) break; $slug = $base.'-'.$n++; }
    }

    $existingCheck = db()->prepare("SELECT id, is_published, approval_status FROM reviewer_public_profile WHERE reviewer_id = ?");
    $existingCheck->execute([$reviewer_id]);
    $existingProfile = $existingCheck->fetch();

    try {
        if (!$existingProfile) {
            db()->prepare("INSERT INTO reviewer_public_profile (reviewer_id, user_id, slug, bio, current_position, total_experience_yrs, h_index, total_citations, orcid_id, website_url, profile_affiliation_id, education, publications, societies, is_published, approval_status, submitted_at, version, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?, 0,'pending',NOW(),1,NOW())")
               ->execute([$reviewer_id, $user_id, $slug, $bio?:null, $position?:null, $exp_yrs, $h_index, $citations, $orcid?:null, $website, $affil_id, $edu?json_encode($edu):null, $pubs?json_encode($pubs):null, $socs?json_encode($socs):null]);
            $success = 'Profile submitted for review! It will go live once approved by our team.';
        } elseif ($existingProfile['is_published'] == 1 || $existingProfile['approval_status'] === 'approved') {
            $pendingSnapshot = json_encode(['bio'=>$bio?:null,'current_position'=>$position?:null,'total_experience_yrs'=>$exp_yrs,'h_index'=>$h_index,'total_citations'=>$citations,'orcid_id'=>$orcid?:null,'website_url'=>$website,'profile_affiliation_id'=>$affil_id,'education'=>$edu?json_encode($edu):null,'publications'=>$pubs?json_encode($pubs):null,'societies'=>$socs?json_encode($socs):null]);
            db()->prepare("UPDATE reviewer_public_profile SET pending_changes=?, approval_status='pending', submitted_at=NOW(), admin_note=NULL WHERE id=?")
               ->execute([$pendingSnapshot, $existingProfile['id']]);
            $success = 'Your update has been submitted for review. Your current live profile stays unchanged until admin approves.';
        } else {
            db()->prepare("UPDATE reviewer_public_profile SET bio=?, current_position=?, total_experience_yrs=?, h_index=?, total_citations=?, orcid_id=?, website_url=?, profile_affiliation_id=?, education=?, publications=?, societies=?, approval_status='pending', submitted_at=NOW() WHERE id=?")
               ->execute([$bio?:null, $position?:null, $exp_yrs, $h_index, $citations, $orcid?:null, $website, $affil_id, $edu?json_encode($edu):null, $pubs?json_encode($pubs):null, $socs?json_encode($socs):null, $existingProfile['id']]);
            $success = 'Profile updated and resubmitted for review.';
        }
    } catch (PDOException $e) { $error = 'Save failed: '.$e->getMessage(); }
}

// ── Data loaders ───────────────────────────────────────────────
$pub_profile    = null;
$pub_affil      = null;
$pub_interests  = [];
$all_affiliations = [];
$published_pubs = [];
$ra_stats = ['completed'=>0,'accepted'=>0,'declined'=>0,'total'=>0];

try {
    $q = db()->prepare("SELECT rpp.*, pa.affiliation_id AS pa_id, pa.name AS pa_name, pa.department AS pa_dept, pa.city AS pa_city, pa.country AS pa_country FROM reviewer_public_profile rpp LEFT JOIN affiliations pa ON rpp.profile_affiliation_id = pa.affiliation_id WHERE rpp.reviewer_id = ? LIMIT 1");
    $q->execute([$reviewer_id]);
    $pub_profile = $q->fetch();
} catch (PDOException $e) {}

if (!empty($user['affiliation_id'])) {
    try { $q = db()->prepare("SELECT * FROM affiliations WHERE affiliation_id=?"); $q->execute([$user['affiliation_id']]); $pub_affil = $q->fetch(); } catch (PDOException $e) {}
}
if ($pub_profile && !empty($pub_profile['profile_affiliation_id'])) {
    try { $q = db()->prepare("SELECT * FROM affiliations WHERE affiliation_id=?"); $q->execute([$pub_profile['profile_affiliation_id']]); $pub_affil = $q->fetch() ?: $pub_affil; } catch (PDOException $e) {}
}

try {
    $q = db()->prepare("SELECT rt.title FROM user_research_interests uri JOIN research_topics rt ON uri.topic_id = rt.topic_id WHERE uri.user_id = ? AND uri.source IN ('manual','auto_suggested') ORDER BY uri.created_at ASC LIMIT 10");
    $q->execute([$user_id]);
    $pub_interests = array_column($q->fetchAll(), 'title');
} catch (PDOException $e) {}

try {
    $q = db()->prepare("SELECT affiliation_id, name, city, state, country FROM affiliations ORDER BY name ASC");
    $q->execute(); $all_affiliations = $q->fetchAll();
} catch (PDOException $e) { $all_affiliations = []; }

// Published articles by this author (for quick-add)
try {
    $q = db()->prepare("SELECT DISTINCT s.submission_id, mi.article_title AS title, j.name AS journal_name, sf.publication_date, sf.doi, YEAR(sf.publication_date) AS pub_year, s.tracking_code FROM submissions s INNER JOIN submission_files sf ON sf.submission_id = s.submission_id LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id LEFT JOIN journals j ON j.journal_id = s.journal_id WHERE s.user_id = ? AND sf.publication_date IS NOT NULL AND sf.doi IS NOT NULL AND sf.doi != '' ORDER BY sf.publication_date DESC");
    $q->execute([$user_id]);
    $published_pubs = $q->fetchAll();
} catch (PDOException $e) { $published_pubs = []; }

// Submission stats
$sub_stats = ['total'=>0,'published'=>0];
try {
    $q = db()->prepare("SELECT submission_status FROM submissions WHERE user_id=?");
    $q->execute([$user_id]);
    foreach ($q->fetchAll() as $r) { $sub_stats['total']++; if ($r['submission_status']==='published') $sub_stats['published']++; }
} catch (PDOException $e) {}

function pubAlreadySaved($saved_pubs, $doi) {
    if (!$doi || empty($saved_pubs)) return false;
    foreach ($saved_pubs as $p) { if (($p['doi'] ?? '') === $doi) return true; }
    return false;
}

// Profile display vars
$pp_bio       = $pub_profile['bio']                    ?? '';
$pp_position  = $pub_profile['current_position']       ?? '';
$pp_exp       = $pub_profile['total_experience_yrs']   ?? '';
$pp_hindex    = $pub_profile['h_index']                ?? '';
$pp_citations = $pub_profile['total_citations']        ?? '';
$pp_orcid     = $pub_profile['orcid_id']               ?? '';
$pp_affil_id  = $pub_profile['profile_affiliation_id'] ?? ($user['affiliation_id'] ?? '');
$pp_edu       = $pub_profile ? json_decode($pub_profile['education']    ?? '[]', true) : [];
$pp_pubs      = $pub_profile ? json_decode($pub_profile['publications'] ?? '[]', true) : [];
$pp_socs      = $pub_profile ? json_decode($pub_profile['societies']    ?? '[]', true) : [];
$pp_slug      = $pub_profile['slug']         ?? '';
$pp_published = $pub_profile['is_published'] ?? 0;

$display_title = ($user['title'] ? $user['title'].'. ' : '');
$full_nm  = $display_title . trim(($user['first_name']??'').($user['middle_name']?' '.$user['middle_name']:'').' '.($user['last_name']??''));
$initials = strtoupper(substr($user['first_name']??'A',0,1).substr($user['last_name']??'',0,1));
$member_yr = date('Y', strtotime($user['created_at'] ?? 'now'));

$affil_name    = $pub_affil['name']    ?? '';
$affil_city    = $pub_affil['city']    ?? '';
$affil_country = $pub_affil['country'] ?? '';

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

<style>
:root {
  --navy:#0c1f3f; --cobalt:#1a3a8f; --sky:#2563eb; --sky-lt:#eff6ff;
  --green:#059669; --gold:#d4a017; --muted:#64748b; --border:#e2e8f0;
  --surface:#f8fafc; --text:#1e293b;
}

/* ── Public Profile Preview — exact copy from reviewer dashboard ── */
.pp-preview { font-family:'DM Sans',sans-serif;background:#f8fafc;border-radius:14px;overflow:hidden;border:1px solid var(--border); }
.pp-stripe  { height:5px;background:linear-gradient(90deg,#0c1f3f 0%,#2563eb 60%,#60a5fa 100%); }
.pp-header  { background:#fff;padding:16px 18px 0;border-bottom:1px solid var(--border); }
.pp-avatar  { width:60px;height:60px;border-radius:10px;background:linear-gradient(145deg,#1a3a8f,#2563eb);display:flex;align-items:center;justify-content:center;font-size:1.2rem;font-weight:700;color:#fff;flex-shrink:0; }
.pp-name    { font-family:'DM Serif Display',serif;font-size:.95rem;font-weight:700;color:#0c1f3f; }
.pp-contrib { display:grid;grid-template-columns:repeat(4,1fr);background:#f0f7ff;border-top:1px solid var(--border); }
.pp-contrib-cell { text-align:center;padding:8px 4px;border-right:1px solid var(--border);font-size:.62rem; }
.pp-contrib-cell:last-child { border-right:none; }
.pp-contrib-num { font-family:'DM Serif Display',serif;font-size:1rem;font-weight:700;color:#0c1f3f;display:block;line-height:1; }
.pp-contrib-lbl { color:#64748b;font-size:.58rem;text-transform:uppercase;letter-spacing:.05em;margin-top:2px; }
.pp-body  { display:grid;grid-template-columns:1fr 160px;gap:10px;padding:12px; }
.pp-sec   { background:#fff;border:1px solid var(--border);border-radius:8px;margin-bottom:8px;overflow:hidden; }
.pp-sec-head { font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#0c1f3f;padding:6px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:5px; }
.pp-sec-body { padding:8px 10px; }
.pp-bio   { font-size:.67rem;color:#475569;line-height:1.65; }
.pp-area-row { margin-bottom:6px; }
.pp-area-lbl { display:flex;justify-content:space-between;font-size:.62rem;color:#475569;margin-bottom:2px; }
.pp-track { height:4px;background:#e2e8f0;border-radius:10px;overflow:hidden; }
.pp-fill  { height:100%;background:linear-gradient(90deg,#2563eb,#3b82f6);border-radius:10px; }
.pp-pub   { padding:6px 0;border-bottom:1px solid var(--border); }
.pp-pub:last-child { border-bottom:none;padding-bottom:0; }
.pp-pub-title { font-size:.66rem;font-weight:600;color:#0c1f3f;line-height:1.3;margin-bottom:3px; }
.pp-pub-meta  { display:flex;flex-wrap:wrap;gap:4px;font-size:.58rem;color:#64748b;align-items:center; }
.pp-pub-badge { padding:1px 5px;border-radius:3px;font-weight:600;font-size:.57rem; }
.pp-pub-yr    { background:#e0e7ff;color:#3730a3; }
.pp-pub-cite  { background:#eff6ff;color:#2563eb; }
.pp-side-card { background:#fff;border:1px solid var(--border);border-radius:8px;margin-bottom:8px;overflow:hidden; }
.pp-side-head { font-size:.58rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#0c1f3f;padding:6px 10px;border-bottom:1px solid var(--border); }
.pp-side-body { padding:8px 10px; }
.pp-edu-item  { display:flex;gap:6px;padding-bottom:8px;position:relative; }
.pp-edu-item:last-child { padding-bottom:0; }
.pp-edu-item::before { content:'';position:absolute;left:9px;top:20px;bottom:0;width:1px;background:var(--border); }
.pp-edu-item:last-child::before { display:none; }
.pp-edu-dot { width:18px;height:18px;border-radius:50%;background:#eff6ff;border:2px solid #93c5fd;display:flex;align-items:center;justify-content:center;font-size:.45rem;font-weight:700;color:#2563eb;flex-shrink:0;z-index:1; }
.pp-edu-deg  { font-size:.64rem;font-weight:600;color:#0c1f3f; }
.pp-edu-inst { font-size:.58rem;color:#64748b; }
.pp-edu-yr   { display:inline-block;font-size:.55rem;font-weight:700;color:#2563eb;background:#eff6ff;border:1px solid #bfdbfe;border-radius:3px;padding:0 4px;margin-top:1px; }
.pp-soc { display:flex;align-items:flex-start;gap:5px;font-size:.62rem;color:#475569;padding:3px 0;border-bottom:1px solid var(--border);line-height:1.4; }
.pp-soc:last-child { border-bottom:none; }
.pp-badge-grid { display:grid;grid-template-columns:repeat(3,1fr);gap:4px; }
.pp-badge-cell { text-align:center;padding:6px 3px;border:1px solid var(--border);border-radius:6px;background:#fafafa; }
.pp-badge-ico  { width:24px;height:24px;border-radius:50%;margin:0 auto 3px;display:flex;align-items:center;justify-content:center;font-size:.65rem; }
.pp-badge-lbl  { font-size:.52rem;color:#64748b;font-weight:500;line-height:1.2; }

/* ── Form helpers ── */
.pp-fieldset { background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:14px 16px;margin-bottom:12px; }
.pp-legend   { font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#0c1f3f;margin-bottom:10px;display:flex;align-items:center;gap:6px; }
.pp-legend i { color:#2563eb; }
.pp-label    { display:block;font-size:.7rem;font-weight:600;color:#475569;margin-bottom:3px; }
.pp-input    { width:100%;padding:7px 9px;border:1px solid #e2e8f0;border-radius:7px;font-size:.8rem;color:#1e293b;outline:none;transition:border-color .15s,box-shadow .15s;background:#fff; }
.pp-input:focus { border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.1); }
.pp-textarea { resize:vertical;min-height:70px; }
.pp-row   { display:grid;grid-template-columns:1fr 1fr;gap:8px; }
.pp-row-3 { display:grid;grid-template-columns:2fr 1fr 1fr;gap:7px; }
.pp-btn-add { font-size:.7rem;color:#2563eb;background:#eff6ff;border:1px dashed #93c5fd;border-radius:6px;padding:5px 10px;cursor:pointer;width:100%;margin-top:6px;transition:background .15s; }
.pp-btn-add:hover { background:#dbeafe; }
.pp-btn-remove { font-size:.62rem;color:#ef4444;background:none;border:none;cursor:pointer;padding:2px 5px;opacity:.7; }
.pp-btn-remove:hover { opacity:1; }
.pp-repeater-row { background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:9px 10px;margin-bottom:7px;position:relative; }

/* ── New affiliation panel ── */
.new-affil-panel { background:#f0f7ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px 14px 10px;margin-top:12px; }
.new-affil-header { display:flex;align-items:center;justify-content:space-between;margin-bottom:10px; }
.new-affil-title { font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#1e40af;display:flex;align-items:center;gap:6px; }
.new-affil-cancel { font-size:.65rem;color:#64748b;background:none;border:none;cursor:pointer; }
.new-affil-submit { width:100%;background:#2563eb;color:#fff;border:none;border-radius:8px;padding:8px 0;font-size:.8rem;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;transition:background .15s; }
.new-affil-submit:hover { background:#1d4ed8; }
.new-affil-submit:disabled { opacity:.6;cursor:not-allowed; }
.na-msg { font-size:.72rem;border-radius:6px;padding:6px 10px;margin-bottom:8px; }
.na-msg-error   { background:#fef2f2;color:#991b1b;border:1px solid #fecaca; }
.na-msg-success { background:#f0fdf4;color:#166534;border:1px solid #bbf7d0; }

.avail-dot { width:7px;height:7px;border-radius:50%;background:#059669;animation:avPulse 2s infinite; }
@keyframes avPulse { 0%,100%{box-shadow:0 0 0 2px rgba(5,150,105,.2)} 50%{box-shadow:0 0 0 4px rgba(5,150,105,.07)} }
</style>

<div class="p-4 md:p-6">

<?php if ($error): ?>
<div class="mb-4 flex items-start gap-3 bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm">
    <i class="fas fa-exclamation-circle flex-shrink-0 mt-0.5"></i><span><?= htmlspecialchars($error) ?></span>
</div>
<?php endif; ?>

<?php if ($success): ?>
<div class="mb-4 flex items-start gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
    <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i><span><?= htmlspecialchars($success) ?></span>
</div>
<?php endif; ?>

<!-- Status banner -->
<?php if ($pp_published && $pp_slug): ?>
<div class="mb-4 flex items-center gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
    <i class="fas fa-globe flex-shrink-0"></i>
    <span>Your public profile is <strong>live</strong> at
        <a href="/reviewer/<?= htmlspecialchars($pp_slug) ?>" target="_blank" class="underline font-semibold">/reviewer/<?= htmlspecialchars($pp_slug) ?></a>
    </span>
</div>
<?php else: ?>
<div class="mb-4 flex items-center gap-3 bg-amber-50 border border-amber-200 text-amber-700 rounded-xl px-4 py-3 text-sm">
    <i class="fas fa-eye-slash flex-shrink-0"></i>
    <span>Profile is saved as <strong>draft</strong>. Admin review required before it goes live.</span>
</div>
<?php endif; ?>

<div class="flex gap-5 items-start" style="max-width:1400px;">

<!-- ══════════════ LEFT: FORM ══════════════ -->
<div class="flex-1 min-w-0 pb-6">
<form method="POST" id="ppForm">
<input type="hidden" name="save_public_profile" value="1">

<!-- Bio -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-user-pen"></i>About / Bio</div>
    <label class="pp-label">Professional Bio *</label>
    <textarea name="bio" id="f_bio" class="pp-input pp-textarea" rows="5"
              placeholder="Write 2–4 sentences about your research focus, current role, and experience…"
              oninput="syncPreview()"><?= htmlspecialchars($pp_bio) ?></textarea>
</div>

<!-- Position & Experience -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-briefcase"></i>Position & Experience</div>
    <div class="pp-row">
        <div>
            <label class="pp-label">Current Position</label>
            <input type="text" name="current_position" id="f_position" class="pp-input"
                   value="<?= htmlspecialchars($pp_position) ?>" placeholder="e.g. Professor, Computer Science" oninput="syncPreview()">
        </div>
        <div>
            <label class="pp-label">Years of Experience</label>
            <input type="number" name="total_experience_yrs" id="f_exp" class="pp-input"
                   value="<?= htmlspecialchars($pp_exp) ?>" placeholder="15" min="0" max="60" oninput="syncPreview()">
        </div>
    </div>
</div>

<!-- Affiliation -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-building-columns"></i>Affiliation for Public Profile</div>
    <p class="text-xs text-slate-500 mb-2">Select your institution. If not listed, choose <strong>"➕ Add new institution…"</strong></p>
    <select name="profile_affiliation_id" id="f_affil" class="pp-input" onchange="handleAffilChange(this)">
        <option value="__new__">➕ Add new institution…</option>
        <option value="" <?= empty($pp_affil_id) ? 'selected' : '' ?>>— Use account affiliation (<?= htmlspecialchars($affil_name ?: 'not set') ?>) —</option>
        <?php foreach ($all_affiliations as $aff): ?>
        <option value="<?= $aff['affiliation_id'] ?>"
                data-name="<?= htmlspecialchars($aff['name']) ?>"
                data-city="<?= htmlspecialchars($aff['city'] ?? '') ?>"
                data-state="<?= htmlspecialchars($aff['state'] ?? '') ?>"
                data-country="<?= htmlspecialchars($aff['country'] ?? '') ?>"
                <?= ($pp_affil_id == $aff['affiliation_id']) ? 'selected' : '' ?>>
            <?= htmlspecialchars($aff['name'].($aff['city']?', '.$aff['city']:'').($aff['country']?', '.$aff['country']:'')) ?>
        </option>
        <?php endforeach; ?>
    </select>
    <div id="new-affil-panel" style="display:none;">
        <div class="new-affil-panel">
            <div class="new-affil-header">
                <span class="new-affil-title"><i class="fas fa-plus-circle" style="color:#3b82f6;"></i>New Institution</span>
                <button type="button" class="new-affil-cancel" onclick="cancelNewAffil()"><i class="fas fa-times"></i> Cancel</button>
            </div>
            <div style="margin-bottom:8px;"><label class="pp-label">Institution / University Name <span style="color:#ef4444;">*</span></label><input type="text" id="na_name" class="pp-input" placeholder="e.g. University of Hyderabad"></div>
            <div style="margin-bottom:8px;"><label class="pp-label">Department <span style="font-weight:400;color:#94a3b8;">(optional)</span></label><input type="text" id="na_dept" class="pp-input" placeholder="e.g. Department of Biotechnology"></div>
            <div class="pp-row" style="margin-bottom:8px;">
                <div><label class="pp-label">City</label><input type="text" id="na_city" class="pp-input" placeholder="Hyderabad"></div>
                <div><label class="pp-label">State / Province</label><input type="text" id="na_state" class="pp-input" placeholder="Telangana"></div>
            </div>
            <div style="margin-bottom:12px;"><label class="pp-label">Country <span style="color:#ef4444;">*</span></label><input type="text" id="na_country" class="pp-input" placeholder="India"></div>
            <div id="na_msg" style="display:none;" class="na-msg"></div>
            <button type="button" id="na_submit_btn" onclick="submitNewAffil()" class="new-affil-submit"><i class="fas fa-save"></i> Save &amp; Select</button>
        </div>
    </div>
</div>

<!-- Research Areas -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-flask-vial"></i>Research Areas</div>
    <p class="text-xs text-slate-500 mb-2">Pulled from your research interests. Edit them in the <a href="profile.php" class="text-blue-600 underline">My Profile</a> tab.</p>
    <div class="flex flex-wrap gap-1.5">
        <?php if ($pub_interests): foreach ($pub_interests as $tag): ?>
        <span class="text-xs bg-blue-50 text-blue-700 border border-blue-200 rounded-full px-2.5 py-0.5"><?= htmlspecialchars($tag) ?></span>
        <?php endforeach; else: ?>
        <span class="text-xs text-slate-400 italic">No research interests found. Add them in My Profile.</span>
        <?php endif; ?>
    </div>
</div>

<!-- Education -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-graduation-cap"></i>Education</div>
    <div id="edu-list">
        <?php if (empty($pp_edu)): ?>
        <div class="pp-repeater-row" data-edu-row>
            <div class="pp-row-3">
                <div><label class="pp-label">Degree</label><input type="text" name="edu_degree[]" class="pp-input" placeholder="Ph.D. in Computer Science" oninput="syncPreview()"></div>
                <div><label class="pp-label">Institution</label><input type="text" name="edu_institution[]" class="pp-input" placeholder="IIT Bombay" oninput="syncPreview()"></div>
                <div><label class="pp-label">Year</label><input type="number" name="edu_year[]" class="pp-input" placeholder="2010" min="1950" max="2099" oninput="syncPreview()"></div>
            </div>
            <button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button>
        </div>
        <?php else: foreach ($pp_edu as $e): ?>
        <div class="pp-repeater-row" data-edu-row>
            <div class="pp-row-3">
                <div><label class="pp-label">Degree</label><input type="text" name="edu_degree[]" class="pp-input" value="<?= htmlspecialchars($e['degree']??'') ?>" oninput="syncPreview()"></div>
                <div><label class="pp-label">Institution</label><input type="text" name="edu_institution[]" class="pp-input" value="<?= htmlspecialchars($e['institution']??'') ?>" oninput="syncPreview()"></div>
                <div><label class="pp-label">Year</label><input type="number" name="edu_year[]" class="pp-input" value="<?= $e['year']??'' ?>" oninput="syncPreview()"></div>
            </div>
            <button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button>
        </div>
        <?php endforeach; endif; ?>
    </div>
    <button type="button" class="pp-btn-add" onclick="addEduRow()"><i class="fas fa-plus mr-1"></i>Add Education</button>
</div>

<!-- Publications -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-book-open"></i>Publications</div>
    <?php if (!empty($published_pubs)): ?>
    <div class="mb-3">
        <label class="pp-label mb-2 flex items-center gap-2"><i class="fas fa-circle-check text-emerald-500" style="font-size:.7rem;"></i>Add from your published articles on CommuneGlobal</label>
        <div class="space-y-2">
            <?php foreach ($published_pubs as $pb):
                $data_json = htmlspecialchars(json_encode(['title'=>$pb['title']??'','journal'=>$pb['journal_name']??'','year'=>(int)($pb['pub_year']??0),'citations'=>0,'doi'=>$pb['doi']??'']));
            ?>
            <div class="flex items-start gap-2 p-2.5 bg-emerald-50 border border-emerald-200 rounded-lg">
                <input type="checkbox" id="psub_<?= $pb['submission_id'] ?>" value="<?= (int)$pb['submission_id'] ?>" data-pub='<?= $data_json ?>' onchange="togglePublishedPub(this)" class="mt-0.5 flex-shrink-0 accent-emerald-600" <?= pubAlreadySaved($pp_pubs, $pb['doi']) ? 'checked disabled' : '' ?>>
                <label for="psub_<?= $pb['submission_id'] ?>" class="text-xs text-slate-700 cursor-pointer leading-snug flex-1">
                    <span class="font-semibold"><?= htmlspecialchars($pb['title']??'Untitled') ?></span><br>
                    <span class="text-slate-500"><?= htmlspecialchars($pb['journal_name']??'') ?></span>
                    <?php if ($pb['pub_year']): ?><span class="ml-1 text-xs bg-blue-100 text-blue-700 px-1.5 rounded font-semibold"><?= $pb['pub_year'] ?></span><?php endif; ?>
                    <?php if ($pb['doi']): ?><span class="ml-1 text-xs text-slate-400 font-mono">DOI: <?= htmlspecialchars($pb['doi']) ?></span><?php endif; ?>
                </label>
                <?php if (pubAlreadySaved($pp_pubs, $pb['doi'])): ?><span class="text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full font-medium flex-shrink-0">Added</span><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <div class="border-t border-dashed border-slate-200 my-3"></div>
    <?php else: ?>
    <p class="text-xs text-slate-400 italic mb-3 flex items-center gap-1.5"><i class="fas fa-info-circle text-slate-300"></i>No published articles yet. Once an article goes live it will appear here.</p>
    <?php endif; ?>

    <label class="pp-label mb-2">Other publications <span class="font-normal text-slate-400">(add manually)</span></label>
    <div id="pub-list">
        <?php if (empty($pp_pubs)): ?>
        <div class="pp-repeater-row" data-pub-row>
            <div class="mb-2"><label class="pp-label">Title</label><input type="text" name="pub_title[]" class="pp-input" placeholder="Full article title…" oninput="syncPreview()"></div>
            <div class="pp-row mb-2">
                <div><label class="pp-label">Journal</label><input type="text" name="pub_journal[]" class="pp-input" placeholder="Journal name" oninput="syncPreview()"></div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                    <div><label class="pp-label">Year</label><input type="number" name="pub_year[]" class="pp-input" placeholder="2024" oninput="syncPreview()"></div>
                    <div><label class="pp-label">Citations</label><input type="number" name="pub_cites[]" class="pp-input" placeholder="0" oninput="syncPreview()"></div>
                </div>
            </div>
            <div><label class="pp-label">DOI <span class="font-normal text-slate-400">(optional)</span></label><input type="text" name="pub_doi[]" class="pp-input" placeholder="10.xxxx/…"></div>
            <button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button>
        </div>
        <?php else: foreach ($pp_pubs as $p): ?>
        <div class="pp-repeater-row" data-pub-row>
            <div class="mb-2"><label class="pp-label">Title</label><input type="text" name="pub_title[]" class="pp-input" value="<?= htmlspecialchars($p['title']??'') ?>" oninput="syncPreview()"></div>
            <div class="pp-row mb-2">
                <div><label class="pp-label">Journal</label><input type="text" name="pub_journal[]" class="pp-input" value="<?= htmlspecialchars($p['journal']??'') ?>" oninput="syncPreview()"></div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                    <div><label class="pp-label">Year</label><input type="number" name="pub_year[]" class="pp-input" value="<?= $p['year']??'' ?>" oninput="syncPreview()"></div>
                    <div><label class="pp-label">Citations</label><input type="number" name="pub_cites[]" class="pp-input" value="<?= $p['citations']??0 ?>" oninput="syncPreview()"></div>
                </div>
            </div>
            <div><label class="pp-label">DOI</label><input type="text" name="pub_doi[]" class="pp-input" value="<?= htmlspecialchars($p['doi']??'') ?>"></div>
            <button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button>
        </div>
        <?php endforeach; endif; ?>
    </div>
    <button type="button" class="pp-btn-add" onclick="addPubRow()"><i class="fas fa-plus mr-1"></i>Add Manually</button>
</div>

<!-- Societies -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-users"></i>Professional Societies</div>
    <label class="pp-label">One society per line</label>
    <textarea name="societies" id="f_societies" class="pp-input pp-textarea" rows="4"
              placeholder="Association for Computing Machinery (ACM)&#10;IEEE Computer Society"
              oninput="syncPreview()"><?= htmlspecialchars(implode("\n", $pp_socs)) ?></textarea>
</div>

<!-- Academic Metrics -->
<div class="pp-fieldset">
    <div class="pp-legend"><i class="fas fa-chart-line"></i>Academic Metrics</div>
    <div class="pp-row mb-3">
        <div><label class="pp-label">h-Index</label><input type="number" name="h_index" id="f_hindex" class="pp-input" min="0" max="300" value="<?= htmlspecialchars($pp_hindex) ?>" placeholder="e.g. 24" oninput="syncPreview()"></div>
        <div><label class="pp-label">Total Citations</label><input type="number" name="total_citations" id="f_citations" class="pp-input" min="0" value="<?= htmlspecialchars($pp_citations) ?>" placeholder="e.g. 1840" oninput="syncPreview()"></div>
    </div>
    <div><label class="pp-label">ORCID iD</label><input type="text" name="orcid_id" id="f_orcid" class="pp-input" value="<?= htmlspecialchars($pp_orcid) ?>" placeholder="0000-0002-1825-0097"></div>
</div>

<!-- Save -->
<div class="pp-fieldset">
    <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-xl font-semibold text-sm flex items-center justify-center gap-2 transition-colors">
        <i class="fas fa-save"></i>Save Public Profile
    </button>
    <p class="text-center text-xs text-slate-400 mt-2">Saved profiles are reviewed by admin before going live.</p>
</div>
</form>
</div><!-- /form col -->


<!-- ══════════════ RIGHT: LIVE PREVIEW ══════════════ -->
<div class="w-96 flex-shrink-0 hidden lg:block">
<div class="sticky top-6">
    <div class="flex items-center justify-between mb-3">
        <p class="text-xs font-semibold text-slate-500 uppercase tracking-widest flex items-center gap-2">
            <i class="fas fa-eye text-blue-400"></i>Live Preview
        </p>
        <span class="text-xs text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full">Updates as you type</span>
    </div>

    <div class="pp-preview">
        <div class="pp-stripe"></div>
        <div class="pp-header">
            <div style="display:flex;gap:12px;align-items:flex-start;padding-bottom:12px;">
                <div class="pp-avatar"><?= $initials ?></div>
                <div style="flex:1;min-width:0;">
                    <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:2px;">
                        <span class="pp-name"><?= htmlspecialchars($full_nm) ?></span>
                        <span style="display:inline-flex;align-items:center;gap:3px;font-size:.58rem;font-weight:600;background:#eff6ff;color:#1e40af;border:1px solid #bfdbfe;border-radius:20px;padding:1px 6px;">
                            ✍ Author
                        </span>
                    </div>
                    <div id="pv-position" style="font-size:.7rem;color:#64748b;margin-bottom:2px;"><?= htmlspecialchars($pp_position ?: 'Author / Researcher') ?></div>
                    <div id="pv-affil" style="font-size:.65rem;color:#64748b;display:flex;align-items:center;gap:3px;margin-bottom:6px;">
                        <i class="fas fa-building-columns" style="font-size:.55rem;"></i>
                        <?= $affil_name ? htmlspecialchars($affil_name.($affil_city?', '.$affil_city:'').($affil_country?', '.$affil_country:'')) : '<span style="color:#94a3b8">Affiliation not set</span>' ?>
                    </div>
                    <div style="display:flex;flex-wrap:wrap;gap:3px;margin-bottom:8px;">
                        <span style="display:inline-flex;align-items:center;gap:3px;font-size:.6rem;color:#475569;background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:2px 6px;">
                            <i class="fas fa-calendar-days" style="color:#2563eb;font-size:.55rem;"></i>Since <?= $member_yr ?>
                        </span>
                        <span style="display:inline-flex;align-items:center;gap:3px;font-size:.6rem;color:#475569;background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:2px 6px;">
                            <i class="fas fa-file-alt" style="color:#2563eb;font-size:.55rem;"></i><?= $sub_stats['total'] ?> submissions
                        </span>
                        <?php if ($pp_hindex): ?>
                        <span id="pv-hindex-tag" style="display:inline-flex;align-items:center;gap:3px;font-size:.6rem;color:#475569;background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:2px 6px;">
                            <i class="fas fa-chart-bar" style="color:#2563eb;font-size:.55rem;"></i>h-<?= htmlspecialchars($pp_hindex) ?>
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <!-- Contribution strip -->
            <div class="pp-contrib">
                <div class="pp-contrib-cell"><span class="pp-contrib-num" style="color:#2563eb;"><?= $sub_stats['total'] ?></span><span class="pp-contrib-lbl">Submissions</span></div>
                <div class="pp-contrib-cell"><span class="pp-contrib-num" style="color:#059669;"><?= $sub_stats['published'] ?></span><span class="pp-contrib-lbl">Published</span></div>
                <div class="pp-contrib-cell"><span class="pp-contrib-num" id="pv-hindex"><?= $pp_hindex ?: '—' ?></span><span class="pp-contrib-lbl">h-Index</span></div>
                <div class="pp-contrib-cell"><span class="pp-contrib-num" style="color:#d4a017;" id="pv-citations"><?= $pp_citations ? number_format((int)$pp_citations) : '—' ?></span><span class="pp-contrib-lbl">Citations</span></div>
            </div>
        </div><!-- /pp-header -->

        <div class="pp-body">
            <div>
                <!-- About -->
                <div class="pp-sec">
                    <div class="pp-sec-head"><i class="fas fa-user-pen" style="color:#2563eb;font-size:.65rem;"></i>About</div>
                    <div class="pp-sec-body">
                        <p class="pp-bio" id="pv-bio"><?= $pp_bio ? htmlspecialchars($pp_bio) : '<span style="color:#94a3b8;font-style:italic;">Your bio will appear here…</span>' ?></p>
                    </div>
                </div>

                <!-- Research Areas -->
                <?php if ($pub_interests): ?>
                <div class="pp-sec">
                    <div class="pp-sec-head"><i class="fas fa-flask-vial" style="color:#2563eb;font-size:.65rem;"></i>Research Areas</div>
                    <div class="pp-sec-body" id="pv-areas">
                        <?php foreach (array_slice($pub_interests, 0, 5) as $idx => $tag):
                            $pct = max(18, 40 - $idx * 4); ?>
                        <div class="pp-area-row">
                            <div class="pp-area-lbl"><span><?= htmlspecialchars($tag) ?></span><span><?= $pct ?>%</span></div>
                            <div class="pp-track"><div class="pp-fill" style="width:<?= $pct ?>%"></div></div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Publications -->
                <div class="pp-sec">
                    <div class="pp-sec-head"><i class="fas fa-book-open" style="color:#2563eb;font-size:.65rem;"></i>Publications</div>
                    <div class="pp-sec-body" id="pv-pubs">
                        <?php if ($pp_pubs): foreach ($pp_pubs as $p): ?>
                        <div class="pp-pub">
                            <div class="pp-pub-title"><?= htmlspecialchars($p['title']) ?></div>
                            <div class="pp-pub-meta">
                                <span><?= htmlspecialchars($p['journal']) ?></span>
                                <span class="pp-pub-badge pp-pub-yr"><?= $p['year'] ?></span>
                                <span class="pp-pub-badge pp-pub-cite"><?= $p['citations']??0 ?> cit.</span>
                            </div>
                        </div>
                        <?php endforeach; else: ?>
                        <p style="font-size:.62rem;color:#94a3b8;font-style:italic;">Add publications in the form</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Education -->
                <div class="pp-sec">
                    <div class="pp-sec-head"><i class="fas fa-graduation-cap" style="color:#2563eb;font-size:.65rem;"></i>Education</div>
                    <div class="pp-sec-body" id="pv-edu">
                        <?php if ($pp_edu): foreach ($pp_edu as $e): ?>
                        <div class="pp-edu-item">
                            <div class="pp-edu-dot">🎓</div>
                            <div>
                                <div class="pp-edu-deg"><?= htmlspecialchars($e['degree']) ?></div>
                                <div class="pp-edu-inst"><?= htmlspecialchars($e['institution']) ?></div>
                                <span class="pp-edu-yr"><?= $e['year'] ?></span>
                            </div>
                        </div>
                        <?php endforeach; else: ?>
                        <p style="font-size:.62rem;color:#94a3b8;font-style:italic;">Add education in the form</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div><!-- /main col -->

            <!-- Sidebar -->
            <div>
                <!-- Affiliation card -->
                <?php if ($affil_name): ?>
                <div class="pp-side-card">
                    <div class="pp-side-head">Affiliation</div>
                    <div class="pp-side-body" id="pv-affil-card">
                        <div style="font-size:.68rem;font-weight:600;color:#0c1f3f;"><?= htmlspecialchars($affil_name) ?></div>
                        <div style="font-size:.6rem;color:#64748b;margin-top:2px;"><?= htmlspecialchars(trim($affil_city.($affil_country?', '.$affil_country:''))) ?></div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Societies -->
                <div class="pp-side-card">
                    <div class="pp-side-head">Societies</div>
                    <div class="pp-side-body" id="pv-soc">
                        <?php if ($pp_socs): foreach ($pp_socs as $s): ?>
                        <div class="pp-soc"><i class="fas fa-circle-dot" style="color:#93c5fd;font-size:.55rem;margin-top:3px;flex-shrink:0;"></i><span><?= htmlspecialchars($s) ?></span></div>
                        <?php endforeach; else: ?>
                        <p style="font-size:.6rem;color:#94a3b8;font-style:italic;">Add societies in the form</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Badges -->
                <div class="pp-side-card">
                    <div class="pp-side-head">Badges</div>
                    <div class="pp-side-body">
                        <div class="pp-badge-grid">
                            <?php
                            $badges = [];
                            if ($sub_stats['published'] >= 1) $badges[] = ['Published',    '#fef9c3','#92400e','fa-newspaper'];
                            if ($sub_stats['total']    >= 3)  $badges[] = ['Active Author', '#fce7f3','#9d174d','fa-pen-nib'];
                            if ($pp_orcid)                    $badges[] = ['ORCID Linked',  '#e0f2fe','#075985','fa-link'];
                            if (empty($badges))               $badges[] = ['Author',        '#e0f2fe','#075985','fa-id-badge'];
                            foreach ($badges as $b): ?>
                            <div class="pp-badge-cell">
                                <div class="pp-badge-ico" style="background:<?= $b[1] ?>;color:<?= $b[2] ?>;"><i class="fas <?= $b[3] ?>"></i></div>
                                <div class="pp-badge-lbl"><?= htmlspecialchars($b[0]) ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div><!-- /sidebar -->
        </div><!-- /pp-body -->
    </div><!-- /pp-preview -->

    <p class="text-center text-xs text-slate-400 mt-3">
        <i class="fas fa-info-circle mr-1"></i>Save to submit for admin review.
    </p>
</div>
</div><!-- /preview col -->

</div><!-- /flex -->
</div><!-- /page wrapper -->

<script>
// ── Affiliation ───────────────────────────────────────────────
function handleAffilChange(sel) {
    if (sel.value === '__new__') {
        document.getElementById('new-affil-panel').style.display = 'block';
        ['na_name','na_dept','na_city','na_state','na_country'].forEach(function(id){ var el=document.getElementById(id); if(el) el.value=''; });
        var msg=document.getElementById('na_msg'); if(msg){msg.style.display='none';msg.textContent='';}
        return;
    }
    document.getElementById('new-affil-panel').style.display = 'none';
    syncAffilFromSelect(sel);
}
function cancelNewAffil() {
    document.getElementById('new-affil-panel').style.display = 'none';
    var sel=document.getElementById('f_affil'); if(sel) sel.value='';
    updateAffilPreview('','','');
}
function submitNewAffil() {
    var name=(document.getElementById('na_name')?.value||'').trim();
    var dept=(document.getElementById('na_dept')?.value||'').trim();
    var city=(document.getElementById('na_city')?.value||'').trim();
    var state=(document.getElementById('na_state')?.value||'').trim();
    var country=(document.getElementById('na_country')?.value||'').trim();
    var btn=document.getElementById('na_submit_btn');
    if(!name||!country){showNaMsg('error','Institution name and country are required.');return;}
    btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Saving…';
    var fd=new FormData();
    fd.append('aff_name',name);fd.append('aff_dept',dept);fd.append('aff_city',city);fd.append('aff_state',state);fd.append('aff_country',country);
    fetch('?action=create_affiliation',{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        btn.disabled=false; btn.innerHTML='<i class="fas fa-save"></i> Save &amp; Select';
        if(!data.ok){showNaMsg('error',data.msg||'Could not save affiliation.');return;}
        var sel=document.getElementById('f_affil');
        var opt=document.createElement('option');
        opt.value=data.id; opt.textContent=data.label;
        opt.dataset.name=data.name; opt.dataset.city=data.city; opt.dataset.state=data.state; opt.dataset.country=data.country;
        opt.selected=true;
        sel.insertBefore(opt,sel.options[2]||null); sel.value=data.id;
        updateAffilPreview(data.name,data.city,data.country);
        showNaMsg('success','✓ "'+data.name+'" added and selected.');
        setTimeout(function(){document.getElementById('new-affil-panel').style.display='none';},1400);
    })
    .catch(function(){
        btn.disabled=false; btn.innerHTML='<i class="fas fa-save"></i> Save &amp; Select';
        showNaMsg('error','Network error. Please try again.');
    });
}
function showNaMsg(type,text){
    var el=document.getElementById('na_msg'); if(!el)return;
    el.style.display='block'; el.textContent=text;
    el.className='na-msg '+(type==='error'?'na-msg-error':'na-msg-success');
}
function syncAffilFromSelect(sel){
    var opt=sel.options[sel.selectedIndex];
    updateAffilPreview(opt.dataset.name||'',opt.dataset.city||'',opt.dataset.country||'');
}
function updateAffilPreview(name,city,country){
    var combo=name+(city?', '+city:'')+(country?', '+country:'');
    var hdr=document.getElementById('pv-affil');
    if(hdr) hdr.innerHTML=name?'<i class="fas fa-building-columns" style="font-size:.55rem;"></i> '+escHtml(combo):'<span style="color:#94a3b8">Affiliation not set</span>';
    var card=document.getElementById('pv-affil-card');
    if(card&&name) card.innerHTML='<div style="font-size:.68rem;font-weight:600;color:#0c1f3f;">'+escHtml(name)+'</div><div style="font-size:.6rem;color:#64748b;margin-top:2px;">'+escHtml(city+(country?', '+country:''))+'</div>';
}

// ── Repeater rows ─────────────────────────────────────────────
function addEduRow(){
    document.getElementById('edu-list').insertAdjacentHTML('beforeend',
    '<div class="pp-repeater-row" data-edu-row style="position:relative;"><div class="pp-row-3">'+
    '<div><label class="pp-label">Degree</label><input type="text" name="edu_degree[]" class="pp-input" placeholder="Ph.D." oninput="syncPreview()"></div>'+
    '<div><label class="pp-label">Institution</label><input type="text" name="edu_institution[]" class="pp-input" placeholder="University" oninput="syncPreview()"></div>'+
    '<div><label class="pp-label">Year</label><input type="number" name="edu_year[]" class="pp-input" placeholder="2010" oninput="syncPreview()"></div>'+
    '</div><button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button></div>');
}
function addPubRow(){
    document.getElementById('pub-list').insertAdjacentHTML('beforeend',
    '<div class="pp-repeater-row" data-pub-row style="position:relative;">'+
    '<div class="mb-2"><label class="pp-label">Title</label><input type="text" name="pub_title[]" class="pp-input" placeholder="Full article title…" oninput="syncPreview()"></div>'+
    '<div class="pp-row mb-2"><div><label class="pp-label">Journal</label><input type="text" name="pub_journal[]" class="pp-input" oninput="syncPreview()"></div>'+
    '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;"><div><label class="pp-label">Year</label><input type="number" name="pub_year[]" class="pp-input" placeholder="2024" oninput="syncPreview()"></div>'+
    '<div><label class="pp-label">Citations</label><input type="number" name="pub_cites[]" class="pp-input" placeholder="0" oninput="syncPreview()"></div></div></div>'+
    '<div><label class="pp-label">DOI</label><input type="text" name="pub_doi[]" class="pp-input" placeholder="10.xxxx/…"></div>'+
    '<button type="button" class="pp-btn-remove" onclick="removeRow(this)" style="position:absolute;top:8px;right:10px;"><i class="fas fa-times"></i></button></div>');
}
function removeRow(btn){btn.closest('[data-edu-row],[data-pub-row]').remove();syncPreview();}

function togglePublishedPub(cb){
    var rowId='pubrow_db_'+cb.value;
    if(cb.checked){
        var data={};try{data=JSON.parse(cb.dataset.pub||'{}');}catch(e){}
        document.getElementById('pub-list').insertAdjacentHTML('beforeend',
        '<div class="pp-repeater-row" data-pub-row id="'+rowId+'" style="position:relative;display:none;">'+
        '<input type="hidden" name="pub_title[]" value="'+escAttr(data.title||'')+'">'+
        '<input type="hidden" name="pub_journal[]" value="'+escAttr(data.journal||'')+'">'+
        '<input type="hidden" name="pub_year[]" value="'+escAttr(String(data.year||''))+'">'+
        '<input type="hidden" name="pub_cites[]" value="0">'+
        '<input type="hidden" name="pub_doi[]" value="'+escAttr(data.doi||'')+'">'+
        '</div>');
    } else {
        var el=document.getElementById(rowId); if(el) el.remove();
    }
    syncPreview();
}

// ── Live preview sync ─────────────────────────────────────────
function syncPreview(){
    var bio=(document.getElementById('f_bio')?.value||'').trim();
    var bioEl=document.getElementById('pv-bio');
    if(bioEl) bioEl.innerHTML=bio?escHtml(bio):'<span style="color:#94a3b8;font-style:italic;">Your bio will appear here…</span>';

    var pos=(document.getElementById('f_position')?.value||'').trim();
    var posEl=document.getElementById('pv-position'); if(posEl) posEl.textContent=pos||'Author / Researcher';

    var hi=(document.getElementById('f_hindex')?.value||'').trim();
    var cit=(document.getElementById('f_citations')?.value||'').trim();
    var hiEl=document.getElementById('pv-hindex'); if(hiEl) hiEl.textContent=hi||'—';
    var citEl=document.getElementById('pv-citations'); if(citEl) citEl.textContent=cit?Number(cit).toLocaleString():'—';
    var hiTag=document.getElementById('pv-hindex-tag'); if(hiTag) hiTag.style.display=hi?'':'none';

    var eduEl=document.getElementById('pv-edu');
    if(eduEl){
        var html='';
        document.querySelectorAll('[data-edu-row]').forEach(function(r){
            var deg=r.querySelector('[name="edu_degree[]"]')?.value.trim()||'';
            var inst=r.querySelector('[name="edu_institution[]"]')?.value.trim()||'';
            var yr=r.querySelector('[name="edu_year[]"]')?.value.trim()||'';
            if(!deg&&!inst)return;
            html+='<div class="pp-edu-item"><div class="pp-edu-dot">🎓</div><div>'+
                  '<div class="pp-edu-deg">'+escHtml(deg)+'</div>'+
                  '<div class="pp-edu-inst">'+escHtml(inst)+'</div>'+
                  (yr?'<span class="pp-edu-yr">'+escHtml(yr)+'</span>':'')+
                  '</div></div>';
        });
        eduEl.innerHTML=html||'<p style="font-size:.62rem;color:#94a3b8;font-style:italic;">Add education in the form</p>';
    }

    var pubEl=document.getElementById('pv-pubs');
    if(pubEl){
        var html='';
        document.querySelectorAll('[data-pub-row]').forEach(function(r){
            var tit=r.querySelector('[name="pub_title[]"]')?.value.trim()||'';
            var jnl=r.querySelector('[name="pub_journal[]"]')?.value.trim()||'';
            var yr=r.querySelector('[name="pub_year[]"]')?.value.trim()||'';
            var cit=r.querySelector('[name="pub_cites[]"]')?.value.trim()||'0';
            if(!tit)return;
            html+='<div class="pp-pub"><div class="pp-pub-title">'+escHtml(tit)+'</div>'+
                  '<div class="pp-pub-meta">'+(jnl?'<span>'+escHtml(jnl)+'</span>':'')+
                  (yr?'<span class="pp-pub-badge pp-pub-yr">'+escHtml(yr)+'</span>':'')+
                  '<span class="pp-pub-badge pp-pub-cite">'+escHtml(cit)+' cit.</span></div></div>';
        });
        pubEl.innerHTML=html||'<p style="font-size:.62rem;color:#94a3b8;font-style:italic;">Add publications in the form</p>';
    }

    var socEl=document.getElementById('pv-soc');
    if(socEl){
        var raw=document.getElementById('f_societies')?.value||'';
        var lines=raw.split('\n').map(function(l){return l.trim();}).filter(Boolean);
        var html='';
        lines.forEach(function(l){html+='<div class="pp-soc"><i class="fas fa-circle-dot" style="color:#93c5fd;font-size:.55rem;margin-top:3px;flex-shrink:0;"></i><span>'+escHtml(l)+'</span></div>';});
        socEl.innerHTML=html||'<p style="font-size:.6rem;color:#94a3b8;font-style:italic;">Add societies in the form</p>';
    }
}

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,'&quot;').replace(/'/g,'&#039;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

syncPreview();
</script>

<?php layoutEnd(); ?>