<?php
/**
 * include/seo_fields.php
 * Drop into any admin form that needs SEO fields.
 * Requires $input array with all page fields.
 * Requires $errors array.
 */

// Defaults for all SEO fields
$seoDefaults = [
    'meta_title'          => '',
    'meta_description'    => '',
    'meta_keywords'       => '',
    'canonical_url'       => '',
    'feature_image'       => '',
    'feature_image_alt'   => '',
    'og_title'            => '',
    'og_description'      => '',
    'og_image'            => '',
    'og_type'             => 'article',
    'twitter_card'        => 'summary_large_image',
    'twitter_title'       => '',
    'twitter_description' => '',
    'twitter_image'       => '',
    'twitter_site'        => '',
    'schema_markup'       => '',
    'ai_summary'          => '',
    'faqs'                => '[]',
];

// Merge defaults so keys always exist
$seo = array_merge($seoDefaults, $input ?? []);

// Decode FAQs
$faqList = [];
try {
    $decoded = json_decode($seo['faqs'] ?? '[]', true);
    if (is_array($decoded)) $faqList = $decoded;
} catch(Exception $e) {}
if (empty($faqList)) $faqList = [['q' => '', 'a' => '']];
?>

<!-- ═══════════════════════════════════════════════════════════
     SEO & META SETTINGS — Accordion Panel
═══════════════════════════════════════════════════════════ -->
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden" id="seoAccordion">

    <!-- Accordion Toggle Header -->
    <button type="button" onclick="toggleSeoPanel()"
        class="w-full px-5 py-4 flex items-center justify-between text-left hover:bg-gray-50 transition">
        <div class="flex items-center gap-2">
            <i class="fas fa-search text-green-600"></i>
            <h2 class="font-semibold text-gray-700">SEO & Meta Settings</h2>
            <span class="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full ml-1">Advanced</span>
        </div>
        <i class="fas fa-chevron-down text-gray-400 transition-transform" id="seoChevron"></i>
    </button>

    <div id="seoPanel" class="border-t border-gray-100" style="display:none;">

        <!-- ── TABS ──────────────────────────────────────────── -->
        <div class="flex border-b border-gray-100 bg-gray-50 overflow-x-auto">
            <?php
            $tabs = [
                ['id'=>'tab-core',    'icon'=>'fa-tag',          'label'=>'Core SEO',       'color'=>'text-green-600'],
                ['id'=>'tab-social',  'icon'=>'fa-share-alt',    'label'=>'Social / OG',    'color'=>'text-blue-600'],
                ['id'=>'tab-schema',  'icon'=>'fa-code',         'label'=>'Schema / JSON-LD','color'=>'text-purple-600'],
                ['id'=>'tab-ai',      'icon'=>'fa-robot',        'label'=>'AI / LLM Seed',  'color'=>'text-indigo-600'],
                ['id'=>'tab-faq',     'icon'=>'fa-question-circle','label'=>'FAQs',          'color'=>'text-orange-600'],
            ];
            foreach ($tabs as $i => $tab): ?>
            <button type="button"
                onclick="switchTab('<?= $tab['id'] ?>')"
                id="btn-<?= $tab['id'] ?>"
                class="seo-tab-btn flex-shrink-0 flex items-center gap-1.5 px-4 py-3 text-xs font-semibold border-b-2 transition whitespace-nowrap
                       <?= $i === 0 ? 'border-green-500 text-green-700 bg-white' : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-white' ?>">
                <i class="fas <?= $tab['icon'] ?> <?= $tab['color'] ?>"></i>
                <?= $tab['label'] ?>
            </button>
            <?php endforeach; ?>
        </div>

        <!-- ── TAB: CORE SEO ─────────────────────────────────── -->
        <div id="tab-core" class="seo-tab-panel p-5 space-y-5">

            <!-- Meta Title -->
            <div>
                <div class="flex items-center justify-between mb-1.5">
                    <label class="block text-sm font-medium text-gray-700">
                        <i class="fas fa-heading text-green-600 mr-1"></i>Meta Title
                    </label>
                    <span class="text-xs text-gray-400">
                        Recommended: <strong>50–60</strong> chars &nbsp;|&nbsp;
                        <span id="metaTitleCount" class="font-mono font-semibold text-gray-600">0</span>/70
                    </span>
                </div>
                <input type="text" name="meta_title" id="metaTitleInput" maxlength="70"
                    value="<?= htmlspecialchars($seo['meta_title']) ?>"
                    class="form-input" placeholder="Leave blank to use page Title">
                <div class="mt-1.5 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                    <div id="metaTitleBar" class="h-full bg-green-500 rounded-full transition-all" style="width:0%"></div>
                </div>
                <p class="text-xs text-gray-400 mt-1">Appears in browser tab &amp; Google results. Keep under 60 chars for best display.</p>
            </div>

            <!-- Meta Description -->
            <div>
                <div class="flex items-center justify-between mb-1.5">
                    <label class="block text-sm font-medium text-gray-700">
                        <i class="fas fa-align-left text-green-600 mr-1"></i>Meta Description
                    </label>
                    <span class="text-xs text-gray-400">
                        Recommended: <strong>150–160</strong> chars &nbsp;|&nbsp;
                        <span id="metaDescCount" class="font-mono font-semibold text-gray-600">0</span>/320
                    </span>
                </div>
                <textarea name="meta_description" id="metaDescInput" maxlength="320" rows="3"
                    class="form-input resize-none"
                    placeholder="Concise page summary for search engines…"><?= htmlspecialchars($seo['meta_description']) ?></textarea>
                <div class="mt-1.5 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                    <div id="metaDescBar" class="h-full bg-green-500 rounded-full transition-all" style="width:0%"></div>
                </div>
                <p class="text-xs text-gray-400 mt-1">Shown under the title in Google. Aim for 150–160 chars — longer text gets cut off.</p>
            </div>

            <!-- Meta Keywords -->
            <div>
                <div class="flex items-center justify-between mb-1.5">
                    <label class="block text-sm font-medium text-gray-700">
                        <i class="fas fa-key text-green-600 mr-1"></i>Meta Keywords
                    </label>
                    <span class="text-xs text-gray-400">
                        Ideal: under <strong>255</strong> chars &nbsp;|&nbsp;
                        <span id="metaKwCount" class="font-mono font-semibold text-gray-600">0</span>/500
                    </span>
                </div>
                <input type="text" name="meta_keywords" id="metaKwInput" maxlength="500"
                    value="<?= htmlspecialchars($seo['meta_keywords']) ?>"
                    class="form-input" placeholder="research, social science, open access, peer review">
                <p class="text-xs text-gray-400 mt-1">Comma-separated. Note: most search engines ignore keywords meta, but it aids internal search &amp; AI indexers.</p>
            </div>

            <!-- Feature Image -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">
                        <i class="fas fa-image text-green-600 mr-1"></i>Feature Image URL
                    </label>
                    <input type="url" name="feature_image" id="featureImageInput"
                        value="<?= htmlspecialchars($seo['feature_image']) ?>"
                        class="form-input" placeholder="https://yoursite.com/images/page.jpg"
                        onchange="updateImagePreview(this.value)">
                    <p class="text-xs text-gray-400 mt-1">Used as OG image fallback. Min 1200×630px recommended.</p>
                    <!-- Preview -->
                    <div id="imgPreviewWrap" class="mt-2 <?= $seo['feature_image'] ? '' : 'hidden' ?>">
                        <img id="imgPreview" src="<?= htmlspecialchars($seo['feature_image']) ?>"
                            alt="Preview" class="w-full h-28 object-cover rounded-lg border border-gray-200">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">
                        <i class="fas fa-comment-alt text-green-600 mr-1"></i>Feature Image Alt Text
                    </label>
                    <input type="text" name="feature_image_alt" maxlength="200"
                        value="<?= htmlspecialchars($seo['feature_image_alt']) ?>"
                        class="form-input" placeholder="Descriptive alt text for accessibility &amp; SEO">
                    <p class="text-xs text-gray-400 mt-1">Describe the image for screen readers and search bots.</p>
                </div>
            </div>

            <!-- Canonical URL -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">
                    <i class="fas fa-link text-green-600 mr-1"></i>Canonical URL
                    <span class="text-gray-400 font-normal text-xs">(optional — leave blank to auto-generate)</span>
                </label>
                <input type="url" name="canonical_url"
                    value="<?= htmlspecialchars($seo['canonical_url']) ?>"
                    class="form-input" placeholder="https://yoursite.com/page-slug">
                <p class="text-xs text-gray-400 mt-1">Prevents duplicate-content penalties. Only set if this page has a specific canonical that differs from its URL.</p>
            </div>

            <!-- SERP Preview -->
            <div class="bg-gray-50 border border-gray-200 rounded-xl p-4">
                <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">
                    <i class="fab fa-google mr-1"></i>Google SERP Preview
                </p>
                <div class="bg-white border border-gray-200 rounded-lg p-3">
                    <div class="text-xs text-green-700 mb-1 font-mono">yoursite.com/<?= htmlspecialchars($seo['slug'] ?? 'page-slug') ?></div>
                    <div id="serpTitle" class="text-blue-700 text-base font-medium hover:underline cursor-pointer leading-tight mb-1">
                        <?= htmlspecialchars($seo['meta_title'] ?: ($seo['title'] ?? 'Page Title')) ?>
                    </div>
                    <div id="serpDesc" class="text-sm text-gray-600 leading-relaxed">
                        <?= htmlspecialchars($seo['meta_description'] ?: ($seo['overview'] ?? 'Page description will appear here…')) ?>
                    </div>
                </div>
            </div>

        </div>

        <!-- ── TAB: SOCIAL / OG ──────────────────────────────── -->
        <div id="tab-social" class="seo-tab-panel p-5 space-y-6" style="display:none;">

            <!-- OG Section -->
            <div>
                <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2 mb-4 pb-2 border-b border-gray-100">
                    <i class="fab fa-facebook text-blue-600"></i>Open Graph (Facebook, LinkedIn, WhatsApp)
                </h3>
                <div class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <div class="flex items-center justify-between mb-1.5">
                                <label class="block text-sm font-medium text-gray-700">OG Title</label>
                                <span class="text-xs text-gray-400"><span id="ogTitleCount">0</span>/200</span>
                            </div>
                            <input type="text" name="og_title" id="ogTitleInput" maxlength="200"
                                value="<?= htmlspecialchars($seo['og_title']) ?>"
                                class="form-input" placeholder="Leave blank to use Meta Title">
                            <p class="text-xs text-gray-400 mt-1">Ideal: 55–60 chars.</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1.5">OG Type</label>
                            <select name="og_type" class="form-input">
                                <?php foreach(['article','website','blog','profile'] as $t): ?>
                                <option value="<?=$t?>" <?= $seo['og_type']===$t?'selected':'' ?>><?= ucfirst($t) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <div class="flex items-center justify-between mb-1.5">
                            <label class="block text-sm font-medium text-gray-700">OG Description</label>
                            <span class="text-xs text-gray-400"><span id="ogDescCount">0</span>/300</span>
                        </div>
                        <textarea name="og_description" id="ogDescInput" maxlength="300" rows="2"
                            class="form-input resize-none"
                            placeholder="Leave blank to use Meta Description"><?= htmlspecialchars($seo['og_description']) ?></textarea>
                        <p class="text-xs text-gray-400 mt-1">Shown in social media cards. Keep under 200 chars for best truncation.</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">OG Image URL</label>
                        <input type="url" name="og_image"
                            value="<?= htmlspecialchars($seo['og_image']) ?>"
                            class="form-input" placeholder="Leave blank to use Feature Image">
                        <p class="text-xs text-gray-400 mt-1">Recommended: 1200×630px. Leave blank to use Feature Image.</p>
                    </div>
                </div>
            </div>

            <!-- Twitter Card Section -->
            <div>
                <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2 mb-4 pb-2 border-b border-gray-100">
                    <i class="fab fa-x-twitter text-gray-900"></i>Twitter / X Card
                </h3>
                <div class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1.5">Card Type</label>
                            <select name="twitter_card" class="form-input">
                                <option value="summary_large_image" <?= $seo['twitter_card']==='summary_large_image'?'selected':'' ?>>Summary Large Image</option>
                                <option value="summary"             <?= $seo['twitter_card']==='summary'?'selected':'' ?>>Summary</option>
                                <option value="app"                 <?= $seo['twitter_card']==='app'?'selected':'' ?>>App</option>
                            </select>
                            <p class="text-xs text-gray-400 mt-1"><code>summary_large_image</code> = big image card (recommended).</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1.5">Twitter Site Handle</label>
                            <input type="text" name="twitter_site"
                                value="<?= htmlspecialchars($seo['twitter_site']) ?>"
                                class="form-input" placeholder="@YourHandle">
                            <p class="text-xs text-gray-400 mt-1">The @username of the website's Twitter account.</p>
                        </div>
                    </div>
                    <div>
                        <div class="flex items-center justify-between mb-1.5">
                            <label class="block text-sm font-medium text-gray-700">Twitter Title</label>
                            <span class="text-xs text-gray-400"><span id="twTitleCount">0</span>/200</span>
                        </div>
                        <input type="text" name="twitter_title" id="twTitleInput" maxlength="200"
                            value="<?= htmlspecialchars($seo['twitter_title']) ?>"
                            class="form-input" placeholder="Leave blank to use OG Title or Meta Title">
                    </div>
                    <div>
                        <div class="flex items-center justify-between mb-1.5">
                            <label class="block text-sm font-medium text-gray-700">Twitter Description</label>
                            <span class="text-xs text-gray-400"><span id="twDescCount">0</span>/300</span>
                        </div>
                        <textarea name="twitter_description" id="twDescInput" maxlength="300" rows="2"
                            class="form-input resize-none"
                            placeholder="Leave blank to use OG Description or Meta Description"><?= htmlspecialchars($seo['twitter_description']) ?></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">Twitter Image URL</label>
                        <input type="url" name="twitter_image"
                            value="<?= htmlspecialchars($seo['twitter_image']) ?>"
                            class="form-input" placeholder="Leave blank to use OG Image or Feature Image">
                        <p class="text-xs text-gray-400 mt-1">Recommended: 1200×628px for large image cards.</p>
                    </div>
                </div>
            </div>

        </div>

        <!-- ── TAB: SCHEMA / JSON-LD ─────────────────────────── -->
        <div id="tab-schema" class="seo-tab-panel p-5 space-y-4" style="display:none;">

            <div class="flex items-start justify-between mb-2">
                <div>
                    <h3 class="text-sm font-semibold text-gray-700">JSON-LD Structured Data</h3>
                    <p class="text-xs text-gray-400 mt-0.5">Paste or build your Schema.org JSON-LD. Rendered verbatim in a &lt;script type="application/ld+json"&gt; tag.</p>
                </div>
                <div class="flex gap-2 flex-shrink-0">
                    <button type="button" onclick="insertSchemaTemplate('article')"
                        class="text-xs bg-purple-50 hover:bg-purple-100 text-purple-700 border border-purple-200 px-2.5 py-1 rounded-lg font-medium transition">
                        + Article
                    </button>
                    <button type="button" onclick="insertSchemaTemplate('faqpage')"
                        class="text-xs bg-orange-50 hover:bg-orange-100 text-orange-700 border border-orange-200 px-2.5 py-1 rounded-lg font-medium transition">
                        + FAQPage
                    </button>
                    <button type="button" onclick="insertSchemaTemplate('org')"
                        class="text-xs bg-blue-50 hover:bg-blue-100 text-blue-700 border border-blue-200 px-2.5 py-1 rounded-lg font-medium transition">
                        + Organization
                    </button>
                </div>
            </div>

            <textarea name="schema_markup" id="schemaEditor" rows="14"
                class="form-input font-mono text-xs resize-y"
                placeholder='{"@context":"https://schema.org","@type":"Article","name":"Page Title",...}'
                style="line-height:1.6;"><?= htmlspecialchars($seo['schema_markup']) ?></textarea>

            <!-- Validate button -->
            <div class="flex items-center gap-3">
                <button type="button" onclick="validateSchema()"
                    class="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-1.5 rounded-lg font-medium transition flex items-center gap-1">
                    <i class="fas fa-check-circle text-green-600"></i> Validate JSON
                </button>
                <span id="schemaValidMsg" class="text-xs hidden"></span>
                <a href="https://search.google.com/test/rich-results" target="_blank"
                    class="text-xs text-blue-600 hover:underline flex items-center gap-1 ml-auto">
                    <i class="fas fa-external-link-alt"></i> Test with Google Rich Results Tool
                </a>
            </div>

            <!-- Schema tips -->
            <div class="bg-purple-50 border border-purple-200 rounded-xl p-4">
                <p class="text-xs font-semibold text-purple-700 mb-2"><i class="fas fa-lightbulb mr-1"></i>Common Schema Types for Academic Journals</p>
                <div class="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-purple-800">
                    <span>• <code>Article</code> — journal articles, posts</span>
                    <span>• <code>FAQPage</code> — FAQ content</span>
                    <span>• <code>ScholarlyArticle</code> — research papers</span>
                    <span>• <code>Organization</code> — journal publisher</span>
                    <span>• <code>WebPage</code> — generic pages</span>
                    <span>• <code>BreadcrumbList</code> — navigation path</span>
                </div>
            </div>

        </div>

        <!-- ── TAB: AI / LLM SEEDING ─────────────────────────── -->
        <div id="tab-ai" class="seo-tab-panel p-5 space-y-4" style="display:none;">

            <div class="bg-indigo-50 border border-indigo-200 rounded-xl p-4 mb-2">
                <p class="text-xs font-semibold text-indigo-700 mb-1">
                    <i class="fas fa-robot mr-1"></i>What is LLM / AI Seeding?
                </p>
                <p class="text-xs text-indigo-800 leading-relaxed">
                    AI search engines (Perplexity, ChatGPT Search, Google AI Overviews, Bing Copilot) look for
                    clear, structured, factual summaries. This field lets you write a plain-text paragraph
                    that LLMs can read and cite directly. It's rendered in an invisible <code>&lt;meta&gt;</code> tag
                    and a hidden <code>&lt;div&gt;</code> with <code>aria-hidden="true"</code> for AI crawlers.
                </p>
            </div>

            <div>
                <div class="flex items-center justify-between mb-1.5">
                    <label class="block text-sm font-medium text-gray-700">
                        <i class="fas fa-brain text-indigo-600 mr-1"></i>AI Summary / LLM Seed Text
                    </label>
                    <span class="text-xs text-gray-400">
                        Ideal: <strong>100–300</strong> words &nbsp;|&nbsp;
                        <span id="aiSummaryWordCount" class="font-mono font-semibold text-gray-600">0</span> words
                    </span>
                </div>
                <textarea name="ai_summary" id="aiSummaryInput" rows="6"
                    class="form-input resize-y"
                    placeholder="Write a clear, factual, plain-text paragraph summarising this page for AI search engines. Use complete sentences. Include key facts, dates, names, and unique identifiers. Avoid marketing language."><?= htmlspecialchars($seo['ai_summary']) ?></textarea>
                <p class="text-xs text-gray-400 mt-1.5">
                    This text is injected as <code class="bg-gray-100 px-1 rounded">data-llm-context</code> attribute and a hidden paragraph.
                    Write factually — AI systems use this verbatim for citations.
                </p>
            </div>

            <!-- AI Checklist -->
            <div class="bg-gray-50 border border-gray-200 rounded-xl p-4">
                <p class="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-3">
                    <i class="fas fa-list-check text-indigo-500 mr-1"></i>AI Optimization Checklist
                </p>
                <div class="space-y-1.5">
                    <?php
                    $checks = [
                        ['title', 'Page Title set'],
                        ['overview', 'Overview / short description filled'],
                        ['meta_description', 'Meta Description filled (150–160 chars)'],
                        ['feature_image', 'Feature Image URL provided'],
                        ['schema_markup', 'JSON-LD Schema added'],
                        ['ai_summary', 'AI Summary / LLM Seed text written'],
                        ['faqs', 'FAQs added (improves People Also Ask coverage)'],
                    ];
                    foreach ($checks as [$field, $label]):
                        $val = $seo[$field] ?? '';
                        $done = !empty($val) && $val !== '[]';
                    ?>
                    <div class="flex items-center gap-2 text-xs <?= $done ? 'text-green-700' : 'text-gray-500' ?>">
                        <i class="fas <?= $done ? 'fa-check-circle text-green-500' : 'fa-circle text-gray-300' ?>"></i>
                        <?= $label ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

        </div>

        <!-- ── TAB: FAQs ─────────────────────────────────────── -->
        <div id="tab-faq" class="seo-tab-panel p-5" style="display:none;">

            <div class="flex items-center justify-between mb-4">
                <div>
                    <h3 class="text-sm font-semibold text-gray-700">FAQs (Frequently Asked Questions)</h3>
                    <p class="text-xs text-gray-400 mt-0.5">Auto-generates FAQPage JSON-LD schema and a visible FAQ section on the page.</p>
                </div>
                <button type="button" onclick="addFaqRow()"
                    class="flex items-center gap-1.5 bg-orange-500 hover:bg-orange-600 text-white text-xs px-3 py-1.5 rounded-lg font-semibold transition">
                    <i class="fas fa-plus"></i> Add FAQ
                </button>
            </div>

            <!-- FAQ Rows -->
            <div id="faqContainer" class="space-y-3">
                <?php foreach ($faqList as $fi => $faq): ?>
                <div class="faq-row bg-gray-50 border border-gray-200 rounded-xl p-4 relative" data-index="<?= $fi ?>">
                    <button type="button" onclick="removeFaqRow(this)"
                        class="absolute top-3 right-3 text-gray-300 hover:text-red-500 transition text-sm">
                        <i class="fas fa-times-circle"></i>
                    </button>
                    <div class="space-y-2">
                        <div>
                            <label class="text-xs font-semibold text-gray-600 mb-1 block">
                                <i class="fas fa-question-circle text-orange-500 mr-1"></i>Question
                            </label>
                            <input type="text" class="faq-q form-input"
                                value="<?= htmlspecialchars($faq['q'] ?? '') ?>"
                                placeholder="e.g. What is the scope of IJRISS?">
                        </div>
                        <div>
                            <label class="text-xs font-semibold text-gray-600 mb-1 block">
                                <i class="fas fa-comment-dots text-green-500 mr-1"></i>Answer
                            </label>
                            <textarea class="faq-a form-input resize-none" rows="2"
                                placeholder="Concise, factual answer…"><?= htmlspecialchars($faq['a'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Hidden serialized FAQs -->
            <input type="hidden" name="faqs" id="faqsInput" value="<?= htmlspecialchars(json_encode($faqList, JSON_UNESCAPED_UNICODE)) ?>">

            <p class="text-xs text-gray-400 mt-4 flex items-center gap-1">
                <i class="fas fa-info-circle text-blue-400"></i>
                FAQs are rendered as FAQPage JSON-LD schema + accordion on the page, boosting Google's "People Also Ask" placement.
            </p>

        </div>
    </div>
</div>

<style>
.seo-tab-btn.active-tab {
    border-bottom-color: #22c55e;
    color: #15803d;
    background: white;
}
</style>

<script>
/* ── SEO Panel Toggle ── */
function toggleSeoPanel() {
    const panel   = document.getElementById('seoPanel');
    const chevron = document.getElementById('seoChevron');
    const open    = panel.style.display !== 'none';
    panel.style.display   = open ? 'none' : 'block';
    chevron.style.transform = open ? '' : 'rotate(180deg)';
}

/* ── Tab switching ── */
function switchTab(id) {
    document.querySelectorAll('.seo-tab-panel').forEach(p => p.style.display = 'none');
    document.querySelectorAll('.seo-tab-btn').forEach(b => {
        b.classList.remove('border-green-500','text-green-700','bg-white');
        b.classList.add('border-transparent','text-gray-500');
    });
    document.getElementById(id).style.display = 'block';
    const btn = document.getElementById('btn-' + id);
    btn.classList.remove('border-transparent','text-gray-500');
    btn.classList.add('border-green-500','text-green-700','bg-white');
}

/* ── Character counters ── */
function bindCounter(inputId, countId, barId, max, idealMin, idealMax) {
    const el    = document.getElementById(inputId);
    const count = document.getElementById(countId);
    const bar   = barId ? document.getElementById(barId) : null;
    if (!el) return;
    function update() {
        const len = el.value.length;
        if (count) count.textContent = len;
        if (bar) {
            const pct = Math.min((len / max) * 100, 100);
            bar.style.width = pct + '%';
            bar.className = 'h-full rounded-full transition-all ' + (
                len >= idealMin && len <= idealMax ? 'bg-green-500' :
                len > idealMax ? 'bg-red-500' : 'bg-yellow-400'
            );
        }
        // Live SERP preview
        if (inputId === 'metaTitleInput') {
            const st = document.getElementById('serpTitle');
            if (st) st.textContent = el.value || (document.getElementById('titleInput')?.value || 'Page Title');
        }
        if (inputId === 'metaDescInput') {
            const sd = document.getElementById('serpDesc');
            if (sd) sd.textContent = el.value || (document.getElementById('overview')?.value || 'Page description…');
        }
    }
    el.addEventListener('input', update);
    update();
}

document.addEventListener('DOMContentLoaded', function() {
    bindCounter('metaTitleInput', 'metaTitleCount', 'metaTitleBar', 70, 50, 60);
    bindCounter('metaDescInput',  'metaDescCount',  'metaDescBar',  320, 150, 160);
    bindCounter('metaKwInput',    'metaKwCount',    null,           500, 0, 255);
    bindCounter('ogTitleInput',   'ogTitleCount',   null,           200, 0, 60);
    bindCounter('ogDescInput',    'ogDescCount',    null,           300, 0, 200);
    bindCounter('twTitleInput',   'twTitleCount',   null,           200, 0, 60);
    bindCounter('twDescInput',    'twDescCount',    null,           300, 0, 200);

    // AI word count
    const aiEl = document.getElementById('aiSummaryInput');
    const aiWc = document.getElementById('aiSummaryWordCount');
    if (aiEl && aiWc) {
        function updateWordCount() {
            const words = aiEl.value.trim().split(/\s+/).filter(w => w).length;
            aiWc.textContent = words;
            aiWc.className = 'font-mono font-semibold ' + (words >= 100 && words <= 300 ? 'text-green-600' : words > 300 ? 'text-red-500' : 'text-yellow-600');
        }
        aiEl.addEventListener('input', updateWordCount);
        updateWordCount();
    }

    // Serialize FAQs on form submit
    const form = document.getElementById('pageForm');
    if (form) {
        form.addEventListener('submit', serializeFaqs);
    }
});

/* ── Image Preview ── */
function updateImagePreview(url) {
    const wrap = document.getElementById('imgPreviewWrap');
    const img  = document.getElementById('imgPreview');
    if (url) {
        img.src = url;
        wrap.classList.remove('hidden');
    } else {
        wrap.classList.add('hidden');
    }
}

/* ── Schema Templates ── */
const schemaTemplates = {
    article: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "Page Title",
        "description": "Page overview/meta description",
        "image": "https://yoursite.com/feature-image.jpg",
        "datePublished": new Date().toISOString().split('T')[0],
        "dateModified": new Date().toISOString().split('T')[0],
        "publisher": {
            "@type": "Organization",
            "name": "RSIS",
            "logo": { "@type": "ImageObject", "url": "https://yoursite.com/logo.png" }
        },
        "author": { "@type": "Organization", "name": "RSIS Editorial Board" }
    }, null, 2),
    faqpage: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": [{
            "@type": "Question",
            "name": "Your FAQ question here?",
            "acceptedAnswer": { "@type": "Answer", "text": "Your answer here." }
        }]
    }, null, 2),
    org: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "Organization",
        "name": "RSIS",
        "url": "https://yoursite.com",
        "logo": "https://yoursite.com/logo.png",
        "sameAs": ["https://twitter.com/handle"]
    }, null, 2),
};

function insertSchemaTemplate(type) {
    const el = document.getElementById('schemaEditor');
    if (!el) return;
    if (el.value.trim() && !confirm('Replace existing schema with ' + type + ' template?')) return;
    el.value = schemaTemplates[type] || '';
}

function validateSchema() {
    const el  = document.getElementById('schemaEditor');
    const msg = document.getElementById('schemaValidMsg');
    try {
        JSON.parse(el.value);
        msg.textContent = '✓ Valid JSON';
        msg.className   = 'text-xs text-green-600';
    } catch(e) {
        msg.textContent = '✗ Invalid JSON: ' + e.message;
        msg.className   = 'text-xs text-red-600';
    }
    msg.classList.remove('hidden');
}

/* ── FAQs ── */
function addFaqRow() {
    const container = document.getElementById('faqContainer');
    const idx = container.querySelectorAll('.faq-row').length;
    const div = document.createElement('div');
    div.className = 'faq-row bg-gray-50 border border-gray-200 rounded-xl p-4 relative';
    div.setAttribute('data-index', idx);
    div.innerHTML = `
        <button type="button" onclick="removeFaqRow(this)" class="absolute top-3 right-3 text-gray-300 hover:text-red-500 transition text-sm">
            <i class="fas fa-times-circle"></i>
        </button>
        <div class="space-y-2">
            <div>
                <label class="text-xs font-semibold text-gray-600 mb-1 block"><i class="fas fa-question-circle text-orange-500 mr-1"></i>Question</label>
                <input type="text" class="faq-q form-input" placeholder="e.g. How do I submit a manuscript?">
            </div>
            <div>
                <label class="text-xs font-semibold text-gray-600 mb-1 block"><i class="fas fa-comment-dots text-green-500 mr-1"></i>Answer</label>
                <textarea class="faq-a form-input resize-none" rows="2" placeholder="Concise, factual answer…"></textarea>
            </div>
        </div>
    `;
    container.appendChild(div);
}

function removeFaqRow(btn) {
    btn.closest('.faq-row').remove();
}

function serializeFaqs() {
    const rows = document.querySelectorAll('.faq-row');
    const data = [];
    rows.forEach(row => {
        const q = row.querySelector('.faq-q')?.value?.trim() || '';
        const a = row.querySelector('.faq-a')?.value?.trim() || '';
        if (q || a) data.push({ q, a });
    });
    const input = document.getElementById('faqsInput');
    if (input) input.value = JSON.stringify(data);
}
</script>