<?php
/**
 * public_html/journals/specialty.php
 * URL: /journals/{journal-slug}/special-issue/{specialty-slug}
 *
 * .htaccess (root), add BEFORE the 2-segment sub-page rule:
 *   RewriteRule ^journals/([a-z0-9-]+)/special-issue/([a-z0-9-]+)/?$
 *     journals/specialty.php?journal_slug=$1&specialty_slug=$2  [QSA,L]
 */

if (session_status() === PHP_SESSION_NONE) session_start();
ini_set('display_errors', 0);
error_reporting(0);

include_once __DIR__ . '/../config/db_new.php';

// ── slug helper (identical to admin's makeSlug) ───────────────────
function makeSlug(string $s): string {
    return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($s)), '-');
}
function hx($v): string {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}
function sh(array $h, string $key, string $field, string $fb = ''): string {
    return hx($h[$key][$field] ?? $fb);
}

// ── Route params ──────────────────────────────────────────────────
$journalSlug   = trim($_GET['journal_slug']   ?? '');
$specialtySlug = trim($_GET['specialty_slug'] ?? '');

$journal        = null;
$specialty      = null;
$sliders        = [];
$infoCards      = [];
$notices        = [];
$spStats        = [];
$spScope        = [];
$spSteps        = [];
$spBoard        = [];
$spIndexing     = [];
$spEthics       = [];
$spWhy          = [];
$spContact      = [];
$spHeaders      = [];
$researchTopics = [];

// ── 1. Fetch journal ──────────────────────────────────────────────
if ($journalSlug && $pdo) {
    try {
        $s = $pdo->prepare("SELECT * FROM journals WHERE slug=? AND is_active=1 LIMIT 1");
        $s->execute([$journalSlug]);
        $journal = $s->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

// ── 2. Match specialty by PHP-generated slug ──────────────────────
// Fetches all active specialties for the journal, generates a slug
// from each name using makeSlug(), and compares to the URL segment.
// This handles names with &, commas, accents, etc. correctly.
if ($journal && $specialtySlug && $pdo) {
    $jid = (int)$journal['journal_id'];
    try {
        $all = $pdo->prepare(
            "SELECT * FROM specialties WHERE journal_id=? AND is_active=1 ORDER BY name ASC"
        );
        $all->execute([$jid]);
        foreach ($all->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if (makeSlug($row['name']) === $specialtySlug) {
                $specialty = $row;
                break;
            }
        }
    } catch (PDOException $e) {}
}

if (!$specialty) {
    http_response_code(404);
}

// ── 3. Load all content sections ─────────────────────────────────
if ($specialty && $pdo) {
    $sid = (int)$specialty['specialty_id'];
    try {
        $q = function(string $sql, array $p = []) use ($pdo): array {
            $s = $pdo->prepare($sql);
            $s->execute($p);
            return $s->fetchAll(PDO::FETCH_ASSOC);
        };

        $sliders    = $q("SELECT * FROM sp_sliders    WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $infoCards  = $q("SELECT * FROM sp_info_cards WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $notices    = $q("SELECT * FROM sp_notices    WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spStats    = $q("SELECT * FROM sp_stats      WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spScope    = $q("SELECT * FROM sp_scope_tags WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spSteps    = $q("SELECT * FROM sp_steps      WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spBoard    = $q("SELECT * FROM sp_board      WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spIndexing = $q("SELECT * FROM sp_indexing   WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spEthics   = $q("SELECT * FROM sp_ethics     WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spWhy      = $q("SELECT * FROM sp_why        WHERE specialty_id=? ORDER BY sort_order", [$sid]);
        $spContact  = $q("SELECT * FROM sp_contact    WHERE specialty_id=? ORDER BY sort_order", [$sid]);

        foreach ($q("SELECT * FROM sp_section_headers WHERE specialty_id=?", [$sid]) as $h) {
            $spHeaders[$h['section_key']] = $h;
        }

        $researchTopics = $q(
            "SELECT * FROM research_topics WHERE specialty_id=? AND is_active=1 ORDER BY title ASC",
            [$sid]
        );
    } catch (PDOException $e) {}
}

// Scope items: sp_scope_tags first, fall back to research_topics
$scopeItems = !empty($spScope)
    ? $spScope
    : array_map(fn($rt) => ['label' => $rt['title'], 'link_url' => null], $researchTopics);

// Hero background: specialty bg → journal bg
$heroBg = !empty($specialty['bg_image_url'])
    ? $specialty['bg_image_url']
    : ($journal['bg_image_url'] ?? '');

// ── 4. SEO ───────────────────────────────────────────────────────
$siteUrl  = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$siteName = 'Communeglobal';

if ($specialty) {
    $specName    = $specialty['name']        ?? '';
    $specDesc    = $specialty['description'] ?? '';
    $journalName = $journal['name']          ?? '';

    $htmlTitle      = !empty($specialty['meta_title'])
                        ? $specialty['meta_title']
                        : $specName . ' | ' . $journalName . ' | ' . $siteName;
    $finalDesc      = !empty($specialty['meta_description'])
                        ? $specialty['meta_description']
                        : (strlen($specDesc) > 160 ? substr($specDesc, 0, 157) . '...' : $specDesc);
    $finalKeywords  = !empty($specialty['meta_keywords'])
                        ? $specialty['meta_keywords']
                        : strtolower($specName) . ', ' . strtolower($journalName) . ', open access, peer review';
    $pageUrl        = $siteUrl . '/journals/' . $journalSlug . '/special-issue/' . $specialtySlug;
    $finalCanonical = !empty($specialty['canonical_url']) ? $specialty['canonical_url'] : $pageUrl;

    $coverRaw = $specialty['cover_image_url'] ?? '';
    if      (!empty($specialty['og_image']))      $finalFeatureImg = str_starts_with($specialty['og_image'], 'http') ? $specialty['og_image'] : $siteUrl . '/' . ltrim($specialty['og_image'], '/');
    elseif  (!empty($coverRaw))                   $finalFeatureImg = $siteUrl . '/' . ltrim($coverRaw, '/');
    elseif  (!empty($journal['cover_image_url'])) $finalFeatureImg = $siteUrl . '/' . ltrim($journal['cover_image_url'], '/');
    else                                          $finalFeatureImg = $siteUrl . '/asset/og-default.jpg';

    $ogTitle  = !empty($specialty['og_title'])            ? $specialty['og_title']            : $htmlTitle;
    $ogDesc   = !empty($specialty['og_description'])      ? $specialty['og_description']      : $finalDesc;
    $ogType   = !empty($specialty['og_type'])             ? $specialty['og_type']             : 'website';
    $twCard   = !empty($specialty['twitter_card'])        ? $specialty['twitter_card']        : 'summary_large_image';
    $twTitle  = !empty($specialty['twitter_title'])       ? $specialty['twitter_title']       : $ogTitle;
    $twDesc   = !empty($specialty['twitter_description']) ? $specialty['twitter_description'] : $ogDesc;
    $twImage  = !empty($specialty['twitter_image'])       ? $specialty['twitter_image']       : $finalFeatureImg;
    $twSite   = !empty($specialty['twitter_site'])        ? $specialty['twitter_site']        : '@communeglobal';
    $schemaRaw = (!empty($specialty['schema_markup']) && json_decode($specialty['schema_markup'])) ? $specialty['schema_markup'] : '';
    $aiSummary = $specialty['ai_summary'] ?? '';

    $faqSchema = '';
    if (!empty($specialty['faqs'])) {
        $faqData = json_decode($specialty['faqs'], true);
        if (is_array($faqData) && count($faqData)) {
            $entities = [];
            foreach ($faqData as $f) {
                $fq = trim($f['q'] ?? ''); $fa = trim($f['a'] ?? '');
                if ($fq && $fa) $entities[] = ['@type' => 'Question', 'name' => $fq, 'acceptedAnswer' => ['@type' => 'Answer', 'text' => $fa]];
            }
            if ($entities) $faqSchema = json_encode(['@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $entities], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
    }
} else {
    $specName = $specDesc = $journalName = $htmlTitle = $finalDesc = $finalKeywords = '';
    $pageUrl = $finalCanonical = $siteUrl . '/journals/' . $journalSlug . '/special-issue/' . $specialtySlug;
    $finalFeatureImg = $siteUrl . '/asset/og-default.jpg';
    $ogTitle = $ogDesc = $ogType = $twCard = $twTitle = $twDesc = $twSite = $schemaRaw = $aiSummary = $faqSchema = '';
    $twImage = $finalFeatureImg;
}

include __DIR__ . '/../include/header.php';
?>

<style>
h2{margin:30px 0}
.messages-section{background:#fff;padding:90px 0}
.messages-section h2.main-title{font-size:2.2rem;font-weight:500}
.messages-content p{color:#6c757d;font-size:1.05rem;line-height:1.7;max-width:520px}
.messages-content a{color:#0d6efd;font-weight:500;text-decoration:none}
.messages-content a:hover{text-decoration:underline}
.custom-indicators{position:relative;margin-top:50px;justify-content:flex-start;gap:14px}
.custom-indicators [data-bs-target]{width:8px;height:8px;border-radius:50%;background:#bdbdbd;border:none;opacity:1;transition:all .3s}
.custom-indicators .active{background:#333;position:relative}
.custom-indicators .active::after{content:"";position:absolute;width:22px;height:22px;border:1px solid #dcdcdc;border-radius:50%;top:50%;left:50%;transform:translate(-50%,-50%)}
.card-container{background:#f4f4f4}
.card-wrapper{display:grid;grid-template-columns:repeat(5,1fr);gap:1.5rem}
.card-wrapper .card{border:none;box-shadow:0 4px 20px rgba(0,0,0,.1);border-radius:8px;overflow:hidden;transition:transform .2s}
.card-wrapper .card:hover{transform:translateY(-5px)}
.card-wrapper .card-img-top{height:180px;object-fit:cover}
.card-wrapper .card-title{font-size:1.25rem;font-weight:600}
.card-wrapper .card-text{font-size:.9rem;color:#6c757d}
@media(max-width:1200px){.card-wrapper{grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}}
.journal-faqs{background:#f9fafb;padding:60px 0}
.faq-item{border:1px solid #e5e7eb;border-radius:10px;margin-bottom:10px;background:#fff;overflow:hidden}
.faq-question{width:100%;background:none;border:none;text-align:left;padding:16px 20px;font-size:1rem;font-weight:600;color:#1f2937;cursor:pointer;display:flex;justify-content:space-between;align-items:center;gap:12px}
.faq-question:hover{color:#009FD1}
.faq-icon{font-size:18px;flex-shrink:0;transition:transform .25s;color:#6b7280}
.faq-item.open .faq-icon{transform:rotate(45deg);color:#009FD1}
.faq-answer{max-height:0;overflow:hidden;transition:max-height .3s ease}
.faq-answer-inner{padding:0 20px 16px;font-size:.95rem;color:#4b5563;line-height:1.7}
.llm-seed{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap}

/* 404 */
.spec-404{min-height:60vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#2d1b69,#1e1035)}
.spec-404-inner{text-align:center;color:#fff;padding:48px 24px}
.spec-404-inner h1{font-size:2rem;font-weight:700;margin-bottom:.5rem}
.back-link{display:inline-flex;align-items:center;gap:6px;background:#4f46e5;color:#fff;padding:10px 22px;border-radius:8px;font-weight:600;text-decoration:none;margin-top:20px}

/* breadcrumb */
.sp-breadcrumb{background:#f8f6f2;border-bottom:1px solid #e2ddd6;padding:10px 0}
.sp-breadcrumb .container{display:flex;align-items:center;gap:6px;font-size:13px;color:#5a6070;flex-wrap:wrap}
.sp-breadcrumb a{color:#1a3a6e;text-decoration:none;font-weight:500}
.sp-breadcrumb a:hover{text-decoration:underline}
.sp-breadcrumb .sep{color:#bbb}

/* CSS vars — indigo/purple palette */
:root{
    --sp-navy:#2d1b69; --sp-mid:#4338ca; --sp-accent:#c8602a;
    --sp-gold:#d4a853; --sp-off:#f8f6ff; --sp-border:#e2ddd6; --sp-muted:#5a6070;
}
.sp-sec       {padding:72px 0}
.sp-sec-alt   {background:var(--sp-off)}
.sp-sec-dark  {background:var(--sp-navy)}
.sp-hdr       {text-align:center;margin-bottom:48px}
.sp-eyebrow   {font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:var(--sp-accent);margin-bottom:10px}
.sp-title     {font-size:clamp(22px,3vw,36px);font-weight:800;color:var(--sp-navy);letter-spacing:-.5px;line-height:1.2;font-family:Georgia,serif}
.sp-title-light{color:#fff}
.sp-desc      {font-size:14.5px;color:var(--sp-muted);max-width:520px;margin:10px auto 0}
.sp-desc-light{color:rgba(255,255,255,.65)}

/* stats */
.sp-stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--sp-border);border:1px solid var(--sp-border);border-radius:16px;overflow:hidden}
.sp-stat-box  {background:#fff;padding:32px 24px;text-align:center;transition:background .2s}
.sp-stat-box:hover{background:var(--sp-off)}
.sp-stat-num  {font-size:clamp(30px,4vw,52px);font-weight:800;color:var(--sp-mid);letter-spacing:-2px;font-family:Georgia,serif;line-height:1}
.sp-stat-lbl  {font-size:13px;color:var(--sp-muted);margin-top:8px;font-weight:500}

/* tags */
.sp-tags-wrap {display:flex;flex-wrap:wrap;gap:10px;justify-content:center}
.sp-tag       {background:#fff;border:1.5px solid var(--sp-border);border-radius:8px;padding:9px 18px;font-size:13.5px;font-weight:500;color:var(--sp-navy);text-decoration:none;transition:all .2s;cursor:default}
.sp-tag a     {color:inherit;text-decoration:none}
.sp-tag:hover {background:var(--sp-navy);color:#fff;border-color:var(--sp-navy)}

/* steps */
.sp-steps-row {display:grid;grid-template-columns:repeat(6,1fr);gap:0;position:relative}
.sp-steps-row::before{content:'';position:absolute;top:26px;left:8%;right:8%;height:2px;background:linear-gradient(90deg,var(--sp-accent),var(--sp-gold));z-index:0}
.sp-step      {text-align:center;position:relative;z-index:1;padding:0 8px}
.sp-step-num  {width:54px;height:54px;border-radius:50%;background:#ede9fe;border:2px solid #c4b5fd;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;color:#4338ca;margin:0 auto 14px;position:relative;z-index:2}
.sp-step-title{font-size:13px;font-weight:700;color:var(--sp-navy);margin-bottom:6px}
.sp-step-desc {font-size:12px;color:var(--sp-muted);line-height:1.5}

/* board */
.sp-board-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
.sp-board-card{background:#fff;border:1.5px solid var(--sp-border);border-radius:14px;padding:18px 20px;display:flex;align-items:center;gap:14px;transition:all .25s}
.sp-board-card:hover{border-color:rgba(200,96,42,.3);box-shadow:0 8px 24px rgba(45,27,105,.08);transform:translateY(-2px)}
.sp-avatar    {width:52px;height:52px;border-radius:50%;background:#4338ca;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;color:#fff !important;flex-shrink:0;font-family:Arial,sans-serif;letter-spacing:.5px}
.sp-board-name{font-size:14px;font-weight:700;color:var(--sp-navy)}
.sp-board-role{font-size:12px;color:var(--sp-muted);margin-top:3px}

/* indexing */
.sp-index-wrap{display:flex;flex-wrap:wrap;gap:10px}
.sp-index-tag {background:#fff;border:1.5px solid var(--sp-border);border-radius:8px;padding:10px 20px;font-size:13.5px;font-weight:500;color:#1c1c1e;transition:border-color .2s}
.sp-index-tag:hover{border-color:var(--sp-navy);color:var(--sp-navy)}
.sp-index-badge{font-size:10px;font-weight:700;background:#ede9fe;color:#4338ca;border-radius:4px;padding:1px 7px;margin-left:6px;vertical-align:middle}

/* ethics */
.sp-ethics-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
.sp-ethics-card{background:#fff;border:1.5px solid var(--sp-border);border-radius:14px;padding:26px 22px;transition:all .25s}
.sp-ethics-card:hover{border-color:rgba(200,96,42,.25);box-shadow:0 8px 28px rgba(45,27,105,.08);transform:translateY(-3px)}
.sp-ethics-title{font-size:15px;font-weight:700;color:var(--sp-navy);margin-bottom:9px}
.sp-ethics-desc {font-size:13px;color:var(--sp-muted);line-height:1.65}

/* why */
.sp-why-grid  {display:grid;grid-template-columns:repeat(3,1fr);gap:20px}
.sp-why-card  {background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);border-radius:16px;padding:30px 26px;transition:all .25s}
.sp-why-card:hover{background:rgba(255,255,255,.12)}
.sp-why-title {font-size:17px;font-weight:700;color:var(--sp-gold);margin-bottom:12px;font-family:Georgia,serif}
.sp-why-desc  {font-size:14px;color:rgba(255,255,255,.65);line-height:1.65}

/* contact */
.sp-contact-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:20px}
.sp-contact-card{background:#3b2a80;border:1px solid rgba(255,255,255,.12);border-radius:16px;padding:30px 26px;transition:all .25s}
.sp-contact-card:hover{background:#4c3799;transform:translateY(-4px)}
.sp-contact-title{font-size:17px;font-weight:700;color:#fff;margin-bottom:11px;font-family:Georgia,serif}
.sp-contact-desc {font-size:13.5px;color:rgba(255,255,255,.65);line-height:1.6;margin-bottom:18px}
.sp-contact-link {display:inline-flex;align-items:center;gap:6px;color:var(--sp-gold);font-size:13px;font-weight:600;text-decoration:none;transition:gap .2s}
.sp-contact-link:hover{gap:10px}

/* responsive */
@media(max-width:1024px){
    .sp-stats-grid{grid-template-columns:repeat(2,1fr)}
    .sp-steps-row{grid-template-columns:repeat(3,1fr);gap:20px}
    .sp-steps-row::before{display:none}
    .sp-board-grid,.sp-ethics-grid,.sp-why-grid,.sp-contact-grid{grid-template-columns:repeat(2,1fr)}
}
@media(max-width:600px){
    .sp-stats-grid,.sp-board-grid,.sp-ethics-grid,.sp-why-grid,.sp-contact-grid{grid-template-columns:1fr}
    .sp-steps-row{grid-template-columns:repeat(2,1fr)}
    .sp-sec{padding:48px 0}
    .card-wrapper{grid-template-columns:1fr}
}
</style>

<?php if (!$specialty): ?>
<!-- ════ 404 ════════════════════════════════════════════════════ -->
<div class="spec-404">
    <div class="spec-404-inner">
        <div style="font-size:3rem;margin-bottom:1rem">🔬</div>
        <h1>Specialty Not Found</h1>
        <p style="color:rgba(255,255,255,.7);margin-top:.5rem">
            The specialty <em><?= hx($specialtySlug) ?></em> doesn't exist or isn't published yet.
        </p>
        <?php if ($journal): ?>
        <a href="/journals/<?= hx($journalSlug) ?>" class="back-link">← Back to <?= hx($journal['name']) ?></a>
        <?php else: ?>
        <a href="/" class="back-link">← Back to Home</a>
        <?php endif; ?>
    </div>
</div>
<?php include __DIR__ . '/../include/footer.php'; ?>
<?php exit; endif; ?>

<?php if (!empty($aiSummary)): ?>
<div class="llm-seed" aria-hidden="true"><?= hx($aiSummary) ?></div>
<?php endif; ?>

<main>

<!-- ════ BREADCRUMB ════════════════════════════════════════════════ -->
<nav class="sp-breadcrumb" aria-label="Breadcrumb">
    <div class="container">
        <a href="/">Home</a><span class="sep">›</span>
        <a href="/journals">Journals</a><span class="sep">›</span>
        <a href="/journals/<?= hx($journalSlug) ?>"><?= hx($journal['name']) ?></a><span class="sep">›</span>
        <span><?= hx($specialty['name']) ?></span>
    </div>
</nav>

<!-- ════ HERO ══════════════════════════════════════════════════════ -->
<div class="hero"<?php if (!empty($heroBg)): ?> style="background-image:url('/<?= hx(ltrim($heroBg,'/')) ?>');background-size:cover;background-position:center;"<?php endif; ?>>
    <div class="hero-title me-5"><?= hx($specialty['description'] ?: $specialty['name']) ?></div>
    <div class="hero-stats">
        <?php if (!empty($specialty['stat_citations'])): ?><div class="stat-box"><div class="val">Review Process</div><div class="lbl"><?= hx($specialty['stat_citations']) ?></div></div><?php endif; ?>
        <?php if (!empty($specialty['stat_hindex'])): ?><div class="stat-box"><div class="val">Editorial Board</div><div class="lbl"><?= hx($specialty['stat_hindex']) ?></div></div><?php endif; ?>
        <?php if (!empty($specialty['stat_articles'])): ?><div class="stat-box"><div class="val">Global Reach</div><div class="lbl"><?= hx($specialty['stat_articles']) ?></div></div><?php endif; ?>
        <a href="https://communeglobal.com/author/submission.php" class="stat-submit">Submit →</a>
    </div>
</div>


<!-- ════ SLIDER ════════════════════════════════════════════════════ -->
<?php if (!empty($sliders)): ?>
<section class="messages-section">
    <div class="container">
        <div id="specCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner">
                <?php foreach ($sliders as $idx => $slide): ?>
                <div class="carousel-item <?= $idx === 0 ? 'active' : '' ?>">
                    <div class="row align-items-center">
                        <div class="col-lg-6"><h2 class="main-title"><?= hx($slide['title']) ?></h2></div>
                        <div class="col-lg-6 messages-content">
                            <?php if (!empty($slide['description'])): ?><p><?= nl2br(hx($slide['description'])) ?></p><?php endif; ?>
                            <?php if (!empty($slide['btn_name']) && !empty($slide['btn_link'])): ?><a href="<?= hx($slide['btn_link']) ?>"><?= hx($slide['btn_name']) ?> →</a><?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php if (count($sliders) > 1): ?>
            <div class="carousel-indicators custom-indicators">
                <?php foreach ($sliders as $idx => $sl): ?>
                <button type="button" data-bs-target="#specCarousel" data-bs-slide-to="<?= $idx ?>"
                    <?= $idx === 0 ? 'class="active" aria-current="true"' : '' ?>
                    aria-label="Slide <?= $idx + 1 ?>"></button>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>
<?php elseif (!empty($specialty['description'])): ?>
<section class="messages-section">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6"><h2 class="main-title"><?= hx($specialty['name']) ?></h2></div>
            <div class="col-lg-6 messages-content"><p><?= nl2br(hx($specialty['description'])) ?></p></div>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ INFO CARDS + NOTICES ══════════════════════════════════════ -->
<?php if (!empty($infoCards) || !empty($notices)): ?>
<section class="card-container py-5">
    <div class="container">
        <?php if (!empty($infoCards)): ?>
        <div class="card-wrapper">
            <?php foreach ($infoCards as $card): ?>
            <a href="<?= !empty($card['link']) ? hx($card['link']) : '#' ?>" class="text-decoration-none">
                <div class="card">
                    <?php if (!empty($card['image_url'])): ?>
                    <img src="/<?= hx(ltrim($card['image_url'],'/')) ?>" alt="<?= hx($card['title']) ?>" class="card-img-top" loading="eager" onerror="this.src='https://via.placeholder.com/300x180?text=Image'">
                    <?php else: ?>
                    <img src="https://via.placeholder.com/300x180?text=<?= urlencode($card['title']) ?>" alt="<?= hx($card['title']) ?>" class="card-img-top" loading="eager">
                    <?php endif; ?>
                    <div class="card-body p-4">
                        <h3 class="card-title"><?= hx($card['title']) ?></h3>
                        <?php if (!empty($card['description'])): ?><p class="card-text"><?= hx($card['description']) ?></p><?php endif; ?>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($notices)): ?>
        <h2>Specialty notices</h2>
        <div class="card-wrapper">
            <?php foreach ($notices as $notice): ?>
            <a href="<?= !empty($notice['link']) ? hx($notice['link']) : '#' ?>" class="text-decoration-none">
                <div class="card">
                    <?php if (!empty($notice['image_url'])): ?>
                    <img src="/<?= hx(ltrim($notice['image_url'],'/')) ?>" alt="<?= hx($notice['title']) ?>" class="card-img-top" loading="eager" onerror="this.src='https://via.placeholder.com/300x180?text=Image'">
                    <?php else: ?>
                    <img src="https://via.placeholder.com/300x180?text=<?= urlencode($notice['title']) ?>" alt="<?= hx($notice['title']) ?>" class="card-img-top" loading="eager">
                    <?php endif; ?>
                    <div class="card-body p-4">
                        <h3 class="card-title"><?= hx($notice['title']) ?></h3>
                        <?php if (!empty($notice['description'])): ?><p class="card-text"><?= hx($notice['description']) ?></p><?php endif; ?>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 3: SPECIALTY STATS ════════════════════════════════ -->
<?php if (!empty($spStats)): ?>
<section class="sp-sec sp-sec-alt">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'jstats','eyebrow','By The Numbers') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'jstats','title','Specialty Stats') ?></h2>
            <?php if (!empty($spHeaders['jstats']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'jstats','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-stats-grid" style="grid-template-columns:repeat(<?= min(count($spStats),4) ?>,1fr)">
            <?php foreach ($spStats as $stat): ?>
            <div class="sp-stat-box">
                <div class="sp-stat-num"><?= hx($stat['number']) ?></div>
                <div class="sp-stat-lbl"><?= hx($stat['label']) ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 4: AIMS & SCOPE ═══════════════════════════════════ -->
<?php if (!empty($scopeItems)): ?>
<section class="sp-sec">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'scope','eyebrow','Browse by Topic') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'scope','title','Aims &amp; Scope') ?></h2>
            <?php if (!empty($spHeaders['scope']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'scope','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-tags-wrap">
            <?php foreach ($scopeItems as $tag): ?>
            <span class="sp-tag">
                <?php if (!empty($tag['link_url']) && $tag['link_url'] !== '#'): ?><a href="<?= hx($tag['link_url']) ?>"><?= hx($tag['label']) ?></a><?php else: ?><?= hx($tag['label']) ?><?php endif; ?>
            </span>
            <?php endforeach; ?>
        </div>
        <?php if (!empty($specialty['about_url'])): ?>
        <div class="text-center my-4">
            <a href="<?= hx($specialty['about_url']) ?>" class="btn btn-primary px-4 py-2 fw-semibold shadow-sm">View All</a>
        </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 5: SUBMISSION PROCESS ════════════════════════════ -->
<?php if (!empty($spSteps)): ?>
<section class="sp-sec sp-sec-alt">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'steps','eyebrow','How It Works') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'steps','title','Submission Process') ?></h2>
            <?php if (!empty($spHeaders['steps']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'steps','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-steps-row" style="grid-template-columns:repeat(<?= min(count($spSteps),6) ?>,1fr)">
            <?php foreach ($spSteps as $step): ?>
            <div class="sp-step">
                <div class="sp-step-num"><?= hx($step['step_number']) ?></div>
                <div class="sp-step-title"><?= hx($step['title']) ?></div>
                <?php if (!empty($step['description'])): ?><div class="sp-step-desc"><?= hx($step['description']) ?></div><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 6: EDITORIAL BOARD ════════════════════════════════ -->
<?php if (!empty($spBoard)): ?>
<section class="sp-sec">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'board','eyebrow','Our Experts') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'board','title','Editorial Board') ?></h2>
            <?php if (!empty($spHeaders['board']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'board','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-board-grid">
            <?php foreach ($spBoard as $m): ?>
            <div class="sp-board-card">
                <div class="sp-avatar">
                    <?php
                    $ini = $m['initials'] ?? '';
                    if (empty($ini)) {
                        $parts = explode(' ', trim($m['name'] ?? ''));
                        $ini   = strtoupper(substr($parts[0]??'',0,1).substr($parts[1]??$parts[0]??'',0,1));
                    }
                    echo hx($ini ?: '?');
                    ?>
                </div>
                <div>
                    <div class="sp-board-name"><?= hx($m['name']) ?></div>
                    <div class="sp-board-role">
                        <?= hx($m['role'] ?? '') ?>
                        <?php if (!empty($m['institution'])): ?> · <?= hx($m['institution']) ?><?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php if (!empty($specialty['editorial_board_url'])): ?>
        <div class="text-center mt-4">
            <a href="<?= hx($specialty['editorial_board_url']) ?>" class="btn btn-outline-primary px-4 py-2 fw-semibold">View Full Editorial Board</a>
        </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 7: INDEXING ════════════════════════════════════════ -->
<?php if (!empty($spIndexing)): ?>
<section class="sp-sec sp-sec-alt">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'indexing','eyebrow','Visibility') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'indexing','title','Indexing &amp; Databases') ?></h2>
            <?php if (!empty($spHeaders['indexing']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'indexing','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-index-wrap">
            <?php foreach ($spIndexing as $tag): ?>
            <span class="sp-index-tag">
                <?= hx($tag['label']) ?>
                <?php if (!empty($tag['badge'])): ?><span class="sp-index-badge"><?= hx($tag['badge']) ?></span><?php endif; ?>
            </span>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 8: PUBLICATION ETHICS ════════════════════════════ -->
<?php if (!empty($spEthics)): ?>
<section class="sp-sec">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow"><?= sh($spHeaders,'ethics','eyebrow','Our Standards') ?></div>
            <h2 class="sp-title"><?= sh($spHeaders,'ethics','title','Publication Ethics') ?></h2>
            <?php if (!empty($spHeaders['ethics']['description'])): ?><p class="sp-desc"><?= sh($spHeaders,'ethics','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-ethics-grid" style="grid-template-columns:repeat(<?= min(count($spEthics),4) ?>,1fr)">
            <?php foreach ($spEthics as $ec): ?>
            <div class="sp-ethics-card">
                <div class="sp-ethics-title"><?= hx($ec['title']) ?></div>
                <?php if (!empty($ec['description'])): ?><div class="sp-ethics-desc"><?= hx($ec['description']) ?></div><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 9: WHY PUBLISH ════════════════════════════════════ -->
<?php if (!empty($spWhy)): ?>
<section class="sp-sec sp-sec-dark">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow" style="color:var(--sp-gold)"><?= sh($spHeaders,'why','eyebrow','Benefits') ?></div>
            <h2 class="sp-title sp-title-light"><?= sh($spHeaders,'why','title','Why Publish With Us') ?></h2>
            <?php if (!empty($spHeaders['why']['description'])): ?><p class="sp-desc sp-desc-light"><?= sh($spHeaders,'why','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-why-grid">
            <?php foreach ($spWhy as $wc): ?>
            <div class="sp-why-card">
                <div class="sp-why-title"><?= hx($wc['title']) ?></div>
                <?php if (!empty($wc['description'])): ?><div class="sp-why-desc"><?= hx($wc['description']) ?></div><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ SECTION 10: CONTACT & QUICK LINKS ═════════════════════════ -->
<?php if (!empty($spContact)): ?>
<section class="sp-sec sp-sec-dark" style="padding-top:0">
    <div class="container">
        <div class="sp-hdr">
            <div class="sp-eyebrow" style="color:var(--sp-gold)"><?= sh($spHeaders,'contact','eyebrow','Get Started') ?></div>
            <h2 class="sp-title sp-title-light"><?= sh($spHeaders,'contact','title','Contact &amp; Quick Links') ?></h2>
            <?php if (!empty($spHeaders['contact']['description'])): ?><p class="sp-desc sp-desc-light"><?= sh($spHeaders,'contact','description') ?></p><?php endif; ?>
        </div>
        <div class="sp-contact-grid">
            <?php foreach ($spContact as $cc): ?>
            <div class="sp-contact-card">
                <div class="sp-contact-title"><?= hx($cc['title']) ?></div>
                <?php if (!empty($cc['description'])): ?><div class="sp-contact-desc"><?= hx($cc['description']) ?></div><?php endif; ?>
                <?php if (!empty($cc['link_text']) && !empty($cc['link_url'])): ?>
                <a href="<?= hx($cc['link_url']) ?>" class="sp-contact-link"><?= hx($cc['link_text']) ?> →</a>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════ FAQ ════════════════════════════════════════════════════════ -->
<?php
$faqList = [];
if (!empty($specialty['faqs'])) {
    $decoded = json_decode($specialty['faqs'], true);
    if (is_array($decoded)) $faqList = array_values(array_filter($decoded, fn($f) => !empty($f['q']) && !empty($f['a'])));
}
?>
<?php if (!empty($faqList)): ?>
<section class="journal-faqs">
    <div class="container">
        <h2>Frequently Asked Questions</h2>
        <div class="faq-list">
            <?php foreach ($faqList as $fi => $faq): ?>
            <div class="faq-item" id="faq-<?= $fi ?>">
                <button class="faq-question" onclick="toggleFaq(<?= $fi ?>)" aria-expanded="false">
                    <span><?= hx($faq['q']) ?></span>
                    <span class="faq-icon">+</span>
                </button>
                <div class="faq-answer" id="faq-answer-<?= $fi ?>">
                    <div class="faq-answer-inner"><?= nl2br(hx($faq['a'])) ?></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

</main>

<script>
function toggleFaq(idx) {
    const item   = document.getElementById('faq-' + idx);
    const answer = document.getElementById('faq-answer-' + idx);
    const btn    = item.querySelector('.faq-question');
    const isOpen = item.classList.contains('open');
    document.querySelectorAll('.faq-item.open').forEach(el => {
        el.classList.remove('open');
        el.querySelector('.faq-answer').style.maxHeight = null;
        el.querySelector('.faq-question').setAttribute('aria-expanded', 'false');
    });
    if (!isOpen) {
        item.classList.add('open');
        answer.style.maxHeight = answer.scrollHeight + 'px';
        btn.setAttribute('aria-expanded', 'true');
    }
}
</script>

<?php include __DIR__ . '/../include/footer.php'; ?>