<?php
/**
 * public_html/journals/journal.php
 * Dynamic journal page — renders all per-journal sections from DB.
 */

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

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

// ── Slug from query string only ────────────────────────────────
$journalSlug = trim($_GET['slug'] ?? '');

$journal   = null;
$sliders   = [];
$infoCards = [];
$notices   = [];

// ── New per-journal section data ──────────────────────────────
$jlStats    = [];
$jlScope    = [];
$jlSteps    = [];
$jlBoard    = [];
$jlIndexing = [];
$jlEthics   = [];
$jlWhy      = [];
$jlContact  = [];
$jlHeaders  = [];   // keyed by section_key

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) {}
}

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

if ($journal && $pdo) {
    $jid = (int)$journal['journal_id'];
    try {
        // ── Original sections ──────────────────────────────────
        $s = $pdo->prepare("SELECT * FROM journal_sliders    WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $sliders   = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM journal_info_cards WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $infoCards = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM journal_notices    WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $notices   = $s->fetchAll(PDO::FETCH_ASSOC);

        // ── New dynamic sections ───────────────────────────────
        $s = $pdo->prepare("SELECT * FROM jl_stats      WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlStats    = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_scope_tags WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlScope    = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_steps      WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlSteps    = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_board      WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlBoard    = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_indexing   WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlIndexing = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_ethics     WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlEthics   = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_why        WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlWhy      = $s->fetchAll(PDO::FETCH_ASSOC);
        $s = $pdo->prepare("SELECT * FROM jl_contact    WHERE journal_id=? AND is_active=1 ORDER BY sort_order"); $s->execute([$jid]); $jlContact  = $s->fetchAll(PDO::FETCH_ASSOC);

        // Section headers keyed by section_key
        $s = $pdo->prepare("SELECT * FROM jl_section_headers WHERE journal_id=?");
        $s->execute([$jid]);
        foreach ($s->fetchAll(PDO::FETCH_ASSOC) as $h) {
            $jlHeaders[$h['section_key']] = $h;
        }
    } catch (PDOException $e) {}
}

function hx($v): string { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// Helper: get section header field with fallback
function sh(array $headers, string $key, string $field, string $fallback = ''): string {
    return hx($headers[$key][$field] ?? $fallback);
}

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

if ($journal) {
    $journalName    = $journal['name'] ?? '';
    $journalDesc    = $journal['description'] ?? '';
    $htmlTitle      = !empty($journal['meta_title'])       ? $journal['meta_title']       : $journalName . ' | ' . $siteName;
    $finalTitle     = $htmlTitle;
    $finalDesc      = !empty($journal['meta_description']) ? $journal['meta_description'] : (strlen($journalDesc) > 160 ? substr($journalDesc, 0, 157) . '...' : $journalDesc);
    $finalKeywords  = !empty($journal['meta_keywords'])    ? $journal['meta_keywords']    : strtolower($journalName) . ', open access journal, peer review, research';
    $pageUrl        = $siteUrl . '/journals/' . $journalSlug;
    $finalCanonical = !empty($journal['canonical_url'])    ? $journal['canonical_url']    : $pageUrl;
    $coverRaw       = $journal['cover_image_url'] ?? '';
    $bgRaw          = $journal['bg_image_url']    ?? '';
    if (!empty($journal['og_image']))        $finalFeatureImg = str_starts_with($journal['og_image'],'http') ? $journal['og_image'] : $siteUrl.'/'.ltrim($journal['og_image'],'/');
    elseif (!empty($coverRaw))              $finalFeatureImg = $siteUrl.'/'.ltrim($coverRaw,'/');
    elseif (!empty($bgRaw))                 $finalFeatureImg = $siteUrl.'/'.ltrim($bgRaw,'/');
    else                                    $finalFeatureImg = $siteUrl.'/asset/og-default.jpg';
    $finalImgAlt    = $journalName;
    $ogTitle        = !empty($journal['og_title'])              ? $journal['og_title']              : $finalTitle;
    $ogDesc         = !empty($journal['og_description'])        ? $journal['og_description']        : $finalDesc;
    $ogImage        = $finalFeatureImg;
    $ogType         = !empty($journal['og_type'])               ? $journal['og_type']               : 'website';
    $twCard         = !empty($journal['twitter_card'])          ? $journal['twitter_card']          : 'summary_large_image';
    $twTitle        = !empty($journal['twitter_title'])         ? $journal['twitter_title']         : $ogTitle;
    $twDesc         = !empty($journal['twitter_description'])   ? $journal['twitter_description']   : $ogDesc;
    $twImage        = !empty($journal['twitter_image'])         ? $journal['twitter_image']         : $ogImage;
    $twSite         = !empty($journal['twitter_site'])          ? $journal['twitter_site']          : '@communeglobal';
    $schemaRaw      = (!empty($journal['schema_markup']) && json_decode($journal['schema_markup'])) ? $journal['schema_markup'] : '';
    $aiSummary      = $journal['ai_summary'] ?? '';
    $faqSchema      = '';
    if (!empty($journal['faqs'])) {
        $faqList = json_decode($journal['faqs'], true);
        if (is_array($faqList) && count($faqList)) {
            $entities = [];
            foreach ($faqList as $faq) {
                $q = trim($faq['q'] ?? ''); $a = trim($faq['a'] ?? '');
                if ($q && $a) $entities[] = ['@type'=>'Question','name'=>$q,'acceptedAnswer'=>['@type'=>'Answer','text'=>$a]];
            }
            if ($entities) $faqSchema = json_encode(['@context'=>'https://schema.org','@type'=>'FAQPage','mainEntity'=>$entities], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }
    }
    $pageData = ['title'=>$journalName,'created_at'=>$journal['created_at']??date('Y-m-d H:i:s'),'updated_at'=>$journal['created_at']??date('Y-m-d H:i:s')];
} else {
    $pageUrl=$siteUrl.'/journals/'.$journalSlug; $htmlTitle=$finalTitle='Journal Not Found | Communeglobal';
    $finalDesc=$finalKeywords=''; $finalCanonical=$pageUrl; $finalFeatureImg=$siteUrl.'/asset/og-default.jpg'; $finalImgAlt='Communeglobal';
    $ogTitle=$finalTitle; $ogDesc=$finalDesc; $ogImage=$finalFeatureImg; $ogType='website';
    $twCard='summary_large_image'; $twTitle=$finalTitle; $twDesc=$finalDesc; $twImage=$finalFeatureImg; $twSite='@communeglobal';
    $schemaRaw=$aiSummary=$faqSchema=''; $pageData=null;
}

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

<!-- ═══════════════════════════ PAGE STYLES ═══════════════════════════ -->
<style>
/* ── existing styles ── */
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-color:#bdbdbd;border:none;opacity:1;transition:all 0.3s ease}
.custom-indicators .active{background-color:#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}
.journal-404{min-height:400px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#1e3a5f,#0d2540)}
.journal-404-inner{text-align:center;color:#fff;padding:48px 24px}
.journal-404-inner h1{font-size:2rem;font-weight:700;margin-bottom:.5rem}
.back-link{display:inline-flex;align-items:center;gap:6px;background:#0d9488;color:#fff;padding:10px 22px;border-radius:8px;font-weight:600;text-decoration:none;margin-top:20px}

/* ════════════════════════════
   NEW SECTION STYLES
════════════════════════════ */
:root {
    --jl-navy:   #0f2443;
    --jl-mid:    #1a3a6e;
    --jl-accent: #c8602a;
    --jl-gold:   #d4a853;
    --jl-off:    #f8f6f2;
    --jl-border: #e2ddd6;
    --jl-muted:  #5a6070;
}

/* shared section wrapper */
.jl-sec          { padding: 72px 0; }
.jl-sec-alt      { background: var(--jl-off); }
.jl-sec-dark     { background: var(--jl-navy); }

/* section header */
.jl-hdr          { text-align: center; margin-bottom: 48px; }
.jl-eyebrow      { font-size: 11px; font-weight: 700; letter-spacing: 2.5px; text-transform: uppercase; color: var(--jl-accent); margin-bottom: 10px; }
.jl-title        { font-size: clamp(22px, 3vw, 36px); font-weight: 800; color: var(--jl-navy); letter-spacing: -.5px; line-height: 1.2; font-family: Georgia, serif; }
.jl-title-light  { color: #fff; }
.jl-desc         { font-size: 14.5px; color: var(--jl-muted); max-width: 520px; margin: 10px auto 0; }
.jl-desc-light   { color: rgba(255,255,255,.65); }

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

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

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

/* ── SECTION 6: Editorial Board ── */
.jl-board-grid   { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
.jl-board-card   { background: #fff; border: 1.5px solid var(--jl-border); border-radius: 14px; padding: 18px 20px; display: flex; align-items: center; gap: 14px; transition: all .25s; }
.jl-board-card:hover { border-color: rgba(200,96,42,.3); box-shadow: 0 8px 24px rgba(15,36,67,.08); transform: translateY(-2px); }
/* AFTER */
.jl-avatar {
    width: 52px; height: 52px; border-radius: 50%;
    background: #1a3a6e;
    display: flex; align-items: center; justify-content: center;
    font-size: 14px; font-weight: 800; color: #ffffff;
    flex-shrink: 0; font-family: Arial, sans-serif;
    letter-spacing: 0.5px;
    flex-shrink: 0;
}
.jl-board-name   { font-size: 14px; font-weight: 700; color: var(--jl-navy); }
.jl-board-role   { font-size: 12px; color: var(--jl-muted); margin-top: 3px; }

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

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

/* ── SECTION 9: Why Publish ── */
.jl-why-grid     { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
.jl-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; }
.jl-why-card:hover { background: rgba(255,255,255,.12); }
.jl-why-title    { font-size: 17px; font-weight: 700; color: var(--jl-gold); margin-bottom: 12px; font-family: Georgia, serif; }
.jl-why-desc     { font-size: 14px; color: rgba(255,255,255,.65); line-height: 1.65; }

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

/* ════════════════════════════
   RESPONSIVE — TABLET  ≤ 1024px
   NOTE: !important needed on grid properties to override
   inline style="grid-template-columns:…" attributes
════════════════════════════ */
@media (max-width: 1024px) {
    .jl-stats-grid  { grid-template-columns: repeat(2, 1fr) !important; }
    .jl-steps-row   { grid-template-columns: repeat(3, 1fr) !important; gap: 20px; }
    .jl-steps-row::before { display: none; }
    .jl-ethics-grid { grid-template-columns: repeat(2, 1fr) !important; }
    .jl-board-grid, .jl-why-grid, .jl-contact-grid { grid-template-columns: repeat(2, 1fr); }
    .card-wrapper   { grid-template-columns: repeat(3, 1fr); }
}

/* ════════════════════════════
   RESPONSIVE — MOBILE  ≤ 768px
════════════════════════════ */
@media (max-width: 768px) {
    /* prevent any section from creating horizontal scroll */
    body, main { overflow-x: hidden; }

    /* Messages / Slider section */
    .messages-section { padding: 40px 0; }
    .messages-section h2.main-title { font-size: 1.5rem; }
    .messages-content p { font-size: .95rem; max-width: 100%; }
    .custom-indicators { margin-top: 28px; justify-content: center; }

    /* Card grid */
    .card-wrapper { grid-template-columns: repeat(2, 1fr); gap: 1rem; }
    .card-wrapper .card-img-top { height: 140px; }
    .card-wrapper .card-title { font-size: 1.05rem; }

    /* FAQ */
    .journal-faqs { padding: 40px 0; }
    .faq-question { font-size: .95rem; padding: 14px 16px; }
    .faq-answer-inner { font-size: .9rem; padding: 0 16px 14px; }

    /* New sections — header */
    .jl-hdr         { margin-bottom: 28px; }
    .jl-desc        { font-size: 13.5px; }

    /* Stats — 2-col, override inline style */
    .jl-stats-grid  { grid-template-columns: repeat(2, 1fr) !important; }

    /* Steps — 2-col, override inline style */
    .jl-steps-row   { grid-template-columns: repeat(2, 1fr) !important; gap: 20px; }
    .jl-steps-row::before { display: none; }

    /* Board */
    .jl-board-grid  { grid-template-columns: 1fr; }

    /* Ethics — 2-col, override inline style */
    .jl-ethics-grid { grid-template-columns: repeat(2, 1fr) !important; gap: 12px; }
    .jl-ethics-card { padding: 20px 16px; }

    /* Why & Contact */
    .jl-why-grid    { grid-template-columns: repeat(2, 1fr); }
    .jl-contact-grid { grid-template-columns: 1fr; }
}

/* ════════════════════════════
   RESPONSIVE — SMALL MOBILE  ≤ 600px
════════════════════════════ */
@media (max-width: 600px) {
    body, main { overflow-x: hidden; }

    /* Section padding */
    .jl-sec         { padding: 36px 0; }

    /* Messages */
    .messages-section { padding: 32px 0; }
    .messages-section h2.main-title { font-size: 1.3rem; }

    /* Cards — single column */
    .card-wrapper   { grid-template-columns: 1fr; gap: .875rem; }
    .card-wrapper .card-img-top { height: 160px; }

    /* Stats — 2-col on small mobile, override inline style */
    .jl-stats-grid  { grid-template-columns: repeat(2, 1fr) !important; }
    .jl-stat-box    { padding: 20px 14px; }
    .jl-stat-num    { font-size: 28px; letter-spacing: -1px; }
    .jl-stat-lbl    { font-size: 12px; }

    /* Steps — single column, override inline style */
    .jl-steps-row   { grid-template-columns: 1fr !important; gap: 16px; }
    .jl-step        { display: flex; align-items: flex-start; gap: 16px; text-align: left; padding: 0; }
    .jl-step-num    { margin: 0; flex-shrink: 0; width: 42px; height: 42px; font-size: 15px; }
    .jl-step-title  { font-size: 13px; }
    .jl-step-desc   { font-size: 12px; }

    /* Board */
    .jl-board-grid  { grid-template-columns: 1fr; }
    .jl-board-card  { padding: 14px 16px; }
    .jl-avatar      { width: 44px; height: 44px; font-size: 12px; }

    /* Ethics — single column, override inline style */
    .jl-ethics-grid { grid-template-columns: 1fr !important; gap: 10px; }
    .jl-ethics-card { padding: 18px 16px; }
    .jl-ethics-title { font-size: 14px; }
    .jl-ethics-desc  { font-size: 12.5px; }

    /* Why & Contact */
    .jl-why-grid, .jl-contact-grid { grid-template-columns: 1fr; }
    .jl-why-card    { padding: 20px 16px; }
    .jl-contact-card { padding: 20px 16px; }

    /* Index tags */
    .jl-index-wrap  { gap: 8px; }
    .jl-index-tag   { font-size: 12px; padding: 8px 12px; }

    /* Scope tags */
    .jl-tags-wrap   { gap: 8px; }
    .jl-tag         { font-size: 12px; padding: 7px 13px; }

    /* FAQ */
    .journal-faqs   { padding: 28px 0; }
    .faq-question   { font-size: .9rem; padding: 13px 14px; }

    /* Section headers */
    .jl-hdr         { margin-bottom: 20px; }
    .jl-title       { font-size: 20px; }

    /* 404 */
    .journal-404-inner h1 { font-size: 1.4rem; }
    .journal-404-inner    { padding: 28px 16px; }
}

/* ════════════════════════════
   RESPONSIVE — EXTRA SMALL  ≤ 400px
════════════════════════════ */
@media (max-width: 400px) {
    .jl-stats-grid  { grid-template-columns: 1fr !important; }
    .jl-stat-box    { padding: 16px 12px; }
    .messages-section h2.main-title { font-size: 1.15rem; }
    .card-wrapper .card-img-top { height: 130px; }
    .jl-board-name  { font-size: 13px; }
    .jl-board-role  { font-size: 11px; }
}
</style>

<?php if (!$journal): ?>
<div class="journal-404">
    <div class="journal-404-inner">
        <h1>Journal Not Found</h1>
        <p>The journal <em><?= hx($journalSlug) ?></em> doesn't exist or isn't published yet.</p>
        <a href="/" class="back-link">← Back to Home</a>
    </div>
</div>
<?php include __DIR__ . '/../include/footer.php'; ?>
<?php exit; endif; ?>

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

<main>

<!-- ════ HERO ════════════════════════════════════════════════ -->
<div class="hero"<?php if (!empty($journal['bg_image_url'])): ?> style="background-image:url('/<?= hx(ltrim($journal['bg_image_url'],'/')) ?>');background-size:cover;background-position:center;"<?php endif; ?>>
    <div class="hero-title me-5"><?= hx($journal['description']) ?></div>
    <div class="hero-stats">
        <?php if (!empty($journal['stat_citations'])): ?><div class="stat-box"><div class="val">Review Process</div><div class="lbl"><?= hx($journal['stat_citations']) ?></div></div><?php endif; ?>
        <?php if (!empty($journal['stat_hindex'])): ?><div class="stat-box"><div class="val">Editorial board member</div><div class="lbl"><?= hx($journal['stat_hindex']) ?></div></div><?php endif; ?>
        <?php if (!empty($journal['stat_articles'])): ?><div class="stat-box"><div class="val">Global Reach</div><div class="lbl"><?= hx($journal['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="messagesCarousel" 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 => $s): ?>
                <button type="button" data-bs-target="#messagesCarousel" 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($journal['description'])): ?>
<section class="messages-section">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6"><h2 class="main-title"><?= hx($journal['name']) ?></h2></div>
            <div class="col-lg-6 messages-content"><p><?= nl2br(hx($journal['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">
                    <picture>
                        <?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; ?>
                    </picture>
                    <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>Journal 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">
                    <picture>
                        <?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; ?>
                    </picture>
                    <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 — JOURNAL STATS
════════════════════════════════════════════════════════════ -->
<?php if (!empty($jlStats)): ?>
<section class="jl-sec jl-sec-alt">
    <div class="container">
        <div class="jl-hdr">
            <?php if (sh($jlHeaders,'jstats','eyebrow','')): ?><div class="jl-eyebrow"><?= sh($jlHeaders,'jstats','eyebrow','By The Numbers') ?></div><?php else: ?><div class="jl-eyebrow">By The Numbers</div><?php endif; ?>
            <h2 class="jl-title"><?= sh($jlHeaders,'jstats','title','Journal Stats') ?></h2>
            <?php if (!empty($jlHeaders['jstats']['description'])): ?><p class="jl-desc"><?= sh($jlHeaders,'jstats','description') ?></p><?php endif; ?>
        </div>
        <div class="jl-stats-grid" style="grid-template-columns:repeat(<?= min(count($jlStats),4) ?>,1fr)">
            <?php foreach ($jlStats as $stat): ?>
            <div class="jl-stat-box">
                <div class="jl-stat-num"><?= hx($stat['number']) ?></div>
                <div class="jl-stat-lbl"><?= hx($stat['label']) ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ════════════════════════════════════════════════════════════
     SECTION 4 — AIMS & SCOPE
════════════════════════════════════════════════════════════ -->
<?php if (!empty($jlScope)): ?>
<section class="jl-sec">
    <div class="container">
        <div class="jl-hdr">
            <div class="jl-eyebrow"><?= sh($jlHeaders,'scope','eyebrow','Browse by Discipline') ?></div>
            <h2 class="jl-title"><?= sh($jlHeaders,'scope','title','Aims &amp; Scope') ?></h2>
            <?php if (!empty($jlHeaders['scope']['description'])): ?><p class="jl-desc" style="display:none;"><?= sh($jlHeaders,'scope','description') ?></p><?php endif; ?>
        </div>
        <div class="jl-tags-wrap">
            <?php foreach ($jlScope as $tag): ?>
            <span class="jl-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>
        <div class="text-center my-4">
            <a href="https://communeglobal.com/journals/social-science/research-areas" 
               class="btn btn-primary px-4 py-2 fw-semibold shadow-sm">
                View All
            </a>
        </div>        
    </div>
</section>
<?php endif; ?>


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


<!-- ════════════════════════════════════════════════════════════
     SECTION 6 — EDITORIAL BOARD
════════════════════════════════════════════════════════════ -->
<?php if (!empty($jlBoard)): ?>
<section class="jl-sec">
    <div class="container">
        <div class="jl-hdr">
            <div class="jl-eyebrow"><?= sh($jlHeaders,'board','eyebrow','Our Experts') ?></div>
            <h2 class="jl-title"><?= sh($jlHeaders,'board','title','Editorial Board') ?></h2>
            <?php if (!empty($jlHeaders['board']['description'])): ?><p class="jl-desc"><?= sh($jlHeaders,'board','description') ?></p><?php endif; ?>
        </div>
        <div class="jl-board-grid">
            <?php foreach ($jlBoard as $m): ?>
            <div class="jl-board-card">
                <div class="jl-avatar" style="color:#fff!important;font-size:15px!important;">
                <?php
                    $initials = $m['initials'] ?? '';
                    if (empty($initials)) {
                        // Try common field name variations
                        $nameVal = $m['name'] ?? $m['member_name'] ?? $m['full_name'] ?? '';
                        $parts = explode(' ', trim($nameVal));
                        $initials = strtoupper(
                            substr($parts[0] ?? '', 0, 1) . substr($parts[1] ?? $parts[0] ?? '', 0, 1)
                        );
                    }
                    echo hx($initials ?: '?');
                ?>
                </div>
                <div>
                    <div class="jl-board-name"><?= hx($m['name']) ?></div>
                    <div class="jl-board-role">
                        <?= hx($m['role'] ?? '') ?>
                        <?php if (!empty($m['institution'])): ?> · <?= hx($m['institution']) ?><?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


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


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


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


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


<!-- ════ FAQ ═════════════════════════════════════════════════ -->
<?php
$faqList = [];
if (!empty($journal['faqs'])) {
    $decoded = json_decode($journal['faqs'], true);
    if (is_array($decoded)) $faqList = 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>
<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 endif; ?>

</main>

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