<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');

// ── Auto-add layout2 + journal_id columns if missing ──
try {
    $allFields = [
        'journal_id'           => "INT UNSIGNED NULL DEFAULT NULL",
        'layout_version'       => "TEXT NULL DEFAULT NULL",
        'global_page_title'    => "TEXT NULL DEFAULT NULL",
        'global_page_description' => "TEXT NULL DEFAULT NULL",
        'global_page_subtext'  => "TEXT NULL DEFAULT NULL",
        'global_buttons'       => "TEXT NULL DEFAULT NULL",
        'global_stats'         => "TEXT NULL DEFAULT NULL",
        'about_subtext'        => "TEXT NULL DEFAULT NULL",
        'about_title'          => "TEXT NULL DEFAULT NULL",
        'about_description'    => "TEXT NULL DEFAULT NULL",
        'about_image'          => "TEXT NULL DEFAULT NULL",
        'whychoose_subtext'    => "TEXT NULL DEFAULT NULL",
        'whychoose_heading'    => "TEXT NULL DEFAULT NULL",
        'whychoose_cards'      => "TEXT NULL DEFAULT NULL",
        'missionvision_subtext'=> "TEXT NULL DEFAULT NULL",
        'missionvision_heading'=> "TEXT NULL DEFAULT NULL",
        'missionvision_cards'  => "TEXT NULL DEFAULT NULL",
        'cta_title'            => "TEXT NULL DEFAULT NULL",
        'cta_description'      => "TEXT NULL DEFAULT NULL",
        'cta_buttons'          => "TEXT NULL DEFAULT NULL",
    ];
    foreach ($allFields as $col => $def) {
        try { $pdo->exec("ALTER TABLE pages ADD COLUMN IF NOT EXISTS `$col` $def"); }
        catch(PDOException $e2) {
            try { $pdo->exec("ALTER TABLE pages ADD COLUMN `$col` $def"); }
            catch(PDOException $e3) {}
        }
    }
} catch(PDOException $e) {}

// ── Image upload handler ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_image']) && $_FILES['upload_image']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = dirname(__DIR__) . '/assets/images/pages/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $ext     = strtolower(pathinfo($_FILES['upload_image']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','webp','svg'];
    if (in_array($ext, $allowed)) {
        $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $_FILES['upload_image']['name']);
        if (move_uploaded_file($_FILES['upload_image']['tmp_name'], $uploadDir . $filename)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'url' => '/assets/images/pages/' . $filename]);
            exit;
        }
    }
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Upload failed — check folder permissions on /assets/images/pages/']);
    exit;
}

$errors = [];
$input  = [
    'title' => '', 'slug' => '', 'overview' => '', 'description' => '', 'status' => 'draft',
    'journal_id' => 0,
    'layout_version' => '1',
    'global_page_title' => '', 'global_page_description' => '', 'global_page_subtext' => '',
    'global_buttons' => '[]', 'global_stats' => '[]',
    'about_subtext' => '', 'about_title' => '', 'about_description' => '', 'about_image' => '',
    'whychoose_subtext' => '', 'whychoose_heading' => '', 'whychoose_cards' => '[]',
    'missionvision_subtext' => '', 'missionvision_heading' => '', 'missionvision_cards' => '[]',
    'cta_title' => '', 'cta_description' => '', 'cta_buttons' => '[]',
    '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' => '[]',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_page'])) {
    // Basic fields
    foreach (['title','slug','overview','description','status'] as $f) {
        $input[$f] = $f === 'description' ? ($_POST[$f] ?? '') : trim($_POST[$f] ?? '');
    }
    $input['status']     = in_array($input['status'], ['draft','published','archived']) ? $input['status'] : 'draft';
    $input['journal_id'] = !empty($_POST['journal_id']) ? (int)$_POST['journal_id'] : null;

    // Layout 2 fields
    $input['layout_version']          = trim($_POST['layout_version'] ?? '1');
    $input['global_page_title']       = trim($_POST['global_page_title']       ?? '');
    $input['global_page_description'] = trim($_POST['global_page_description'] ?? '');
    $input['global_page_subtext']     = trim($_POST['global_page_subtext']     ?? '');

    $gbp = $_POST['global_buttons'] ?? null;
    $input['global_buttons'] = is_array($gbp) ? json_encode($gbp) : '[]';

    $gsp = $_POST['global_stats'] ?? null;
    $input['global_stats'] = is_array($gsp) ? json_encode($gsp) : '[]';

    $input['about_subtext']     = trim($_POST['about_subtext']     ?? '');
    $input['about_title']       = trim($_POST['about_title']       ?? '');
    $input['about_description'] = $_POST['about_description']      ?? '';
    $input['about_image']       = trim($_POST['about_image']       ?? '');

    $wcp = $_POST['whychoose_cards'] ?? null;
    $input['whychoose_cards'] = is_array($wcp) ? json_encode($wcp) : '[]';

    $mvp = $_POST['missionvision_cards'] ?? null;
    $input['missionvision_cards'] = is_array($mvp) ? json_encode($mvp) : '[]';

    $input['whychoose_subtext']     = trim($_POST['whychoose_subtext']     ?? '');
    $input['whychoose_heading']     = trim($_POST['whychoose_heading']     ?? '');
    $input['missionvision_subtext'] = trim($_POST['missionvision_subtext'] ?? '');
    $input['missionvision_heading'] = trim($_POST['missionvision_heading'] ?? '');

    $cbp = $_POST['cta_buttons'] ?? null;
    $input['cta_buttons']     = is_array($cbp) ? json_encode($cbp) : '[]';
    $input['cta_title']       = trim($_POST['cta_title']       ?? '');
    $input['cta_description'] = trim($_POST['cta_description'] ?? '');

    // SEO fields
    $seoFields = ['meta_title','meta_description','meta_keywords','canonical_url',
        'feature_image','feature_image_alt','og_title','og_description','og_image','og_type',
        'twitter_card','twitter_title','twitter_description','twitter_image','twitter_site',
        'schema_markup','ai_summary','faqs'];
    foreach ($seoFields as $f) { $input[$f] = trim($_POST[$f] ?? ''); }
    if (!in_array($input['twitter_card'], ['summary','summary_large_image','app'])) $input['twitter_card'] = 'summary_large_image';
    if (!in_array($input['og_type'], ['article','website','blog','profile']))        $input['og_type'] = 'article';
    if (!json_decode($input['faqs'])) $input['faqs'] = '[]';

    // Validation
    if (!$input['title']) $errors['title'] = 'Title is required.';
    if (!$input['slug'])  $errors['slug']  = 'Slug is required.';
    elseif (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $input['slug']))
        $errors['slug'] = 'Slug must contain only lowercase letters, numbers, and hyphens.';

    if (!$errors) {
        try {
            $chk = $pdo->prepare("SELECT id FROM pages WHERE slug = ?");
            $chk->execute([$input['slug']]);
            if ($chk->fetch()) {
                $errors['slug'] = 'This slug is already taken.';
            } else {
                $pdo->prepare("
                    INSERT INTO pages
                    (journal_id, title, slug, overview, description, status,
                     layout_version, global_page_title, global_page_description, global_page_subtext,
                     global_buttons, global_stats, about_subtext, about_title, about_description,
                     about_image, whychoose_subtext, whychoose_heading, whychoose_cards,
                     missionvision_subtext, missionvision_heading, missionvision_cards,
                     cta_title, cta_description, cta_buttons,
                     meta_title, meta_description, meta_keywords, canonical_url,
                     feature_image, feature_image_alt,
                     og_title, og_description, og_image, og_type,
                     twitter_card, twitter_title, twitter_description, twitter_image, twitter_site,
                     schema_markup, ai_summary, faqs)
                    VALUES (?,?,?,?,?,?, ?,?,?,?, ?,?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?,?, ?,?, ?,?,?,?, ?,?,?,?,?, ?,?,?)
                ")->execute([
                    $input['journal_id'], $input['title'], $input['slug'],
                    $input['overview'], $input['description'], $input['status'],
                    $input['layout_version'], $input['global_page_title'], $input['global_page_description'],
                    $input['global_page_subtext'], $input['global_buttons'], $input['global_stats'],
                    $input['about_subtext'], $input['about_title'], $input['about_description'],
                    $input['about_image'], $input['whychoose_subtext'], $input['whychoose_heading'],
                    $input['whychoose_cards'], $input['missionvision_subtext'], $input['missionvision_heading'],
                    $input['missionvision_cards'], $input['cta_title'], $input['cta_description'],
                    $input['cta_buttons'],
                    $input['meta_title'], $input['meta_description'], $input['meta_keywords'],
                    $input['canonical_url'], $input['feature_image'], $input['feature_image_alt'],
                    $input['og_title'], $input['og_description'], $input['og_image'], $input['og_type'],
                    $input['twitter_card'], $input['twitter_title'], $input['twitter_description'],
                    $input['twitter_image'], $input['twitter_site'],
                    $input['schema_markup'], $input['ai_summary'], $input['faqs'],
                ]);
                header('Location: pages.php?created=1');
                exit;
            }
        } catch (PDOException $e) {
            $errors['db'] = 'Database error: ' . $e->getMessage();
        }
    }
}

// Parse JSON for re-display on validation error
$decode = function($v) { if (empty($v)||!is_string($v)) return []; $d=json_decode($v,true); return is_array($d)?$d:[]; };
$globalButtons      = $decode($input['global_buttons']);
$globalStats        = $decode($input['global_stats']);
$whychooseCards     = $decode($input['whychoose_cards']);
$missionvisionCards = $decode($input['missionvision_cards']);
$ctaButtons         = $decode($input['cta_buttons']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Create Page — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden}
body.dark{background-color:#1a202c;color:#e2e8f0}
.sidebar{width:250px;background:#2d3748;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}.sidebar.collapsed .sidebar-title{display:none}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto}
.content.collapsed-sidebar{margin-left:70px}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#4a5568}.nav-item.active{background:#4a5568;border-left:4px solid #4299e1}
body.dark .bg-white{background-color:#2d3748}
body.dark input,body.dark select,body.dark textarea{background-color:#374151;color:#e5e7eb;border-color:#4b5563}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}
.form-input{width:100%;border:1px solid #d1d5db;border-radius:.5rem;padding:.6rem .875rem;font-size:.875rem;color:#374151;transition:border-color .15s,box-shadow .15s;outline:none}
.form-input:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.15)}
.form-input.has-error{border-color:#ef4444}
.error-msg{color:#ef4444;font-size:.75rem;margin-top:4px;display:flex;align-items:center;gap:4px}
.layout2-section{display:none}
.layout2-section.active{display:block}
.dynamic-item{transition:all .2s}
.dynamic-item.removing{opacity:.5;transform:translateX(-10px)}

/* ── Image Upload Modal ── */
.img-modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:9999;display:flex;align-items:center;justify-content:center;}
.img-modal{background:#fff;border-radius:14px;padding:28px;width:480px;max-width:95vw;box-shadow:0 20px 60px rgba(0,0,0,.25);}
body.dark .img-modal{background:#2d3748;color:#e2e8f0;}
.img-modal h3{font-size:1rem;font-weight:700;margin-bottom:16px;color:#1f2937;}
body.dark .img-modal h3{color:#e2e8f0;}
.upload-zone{border:2px dashed #d1d5db;border-radius:10px;padding:32px;text-align:center;cursor:pointer;transition:all .2s;background:#f9fafb;}
.upload-zone:hover,.upload-zone.drag-over{border-color:#3b82f6;background:#eff6ff;}
body.dark .upload-zone{background:#374151;border-color:#4b5563;}
.upload-zone p{font-size:.875rem;color:#6b7280;margin-top:8px;}
.img-preview{width:100%;max-height:200px;object-fit:contain;border-radius:8px;margin-top:12px;display:none;}
.img-url-row{display:flex;gap:8px;margin-top:12px;}
.img-url-row input{flex:1;border:1px solid #d1d5db;border-radius:8px;padding:8px 12px;font-size:.875rem;outline:none;}
.img-url-row input:focus{border-color:#3b82f6;}
body.dark .img-url-row input{background:#374151;color:#e2e8f0;border-color:#4b5563;}
.img-field-row{display:flex;gap:8px;align-items:center;}
.img-field-row input{flex:1;}
.img-upload-btn{flex-shrink:0;padding:8px 14px;background:#f3f4f6;border:1px solid #d1d5db;border-radius:8px;font-size:.8rem;font-weight:500;color:#374151;cursor:pointer;display:flex;align-items:center;gap:6px;white-space:nowrap;transition:all .15s;}
.img-upload-btn:hover{background:#e5e7eb;}
body.dark .img-upload-btn{background:#374151;color:#e2e8f0;border-color:#4b5563;}
.img-thumb{width:40px;height:40px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb;flex-shrink:0;display:none;}
</style>
</head>
<body class="bg-gray-100">
<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<!-- ── Image Upload Modal ── -->
<div id="imgModal" class="img-modal-overlay" style="display:none;" onclick="if(event.target===this)closeImgModal()">
  <div class="img-modal">
    <h3><i class="fas fa-image mr-2 text-blue-500"></i>Upload / Select Image</h3>
    <div class="upload-zone" id="uploadZone"
         ondragover="event.preventDefault();this.classList.add('drag-over')"
         ondragleave="this.classList.remove('drag-over')"
         ondrop="handleDrop(event)"
         onclick="document.getElementById('fileInput').click()">
      <i class="fas fa-cloud-upload-alt text-3xl text-blue-400"></i>
      <p>Drag & drop an image here, or <span class="text-blue-600 font-medium">click to browse</span></p>
      <p class="text-xs mt-1">JPG, PNG, GIF, WebP, SVG supported</p>
    </div>
    <input type="file" id="fileInput" accept="image/*" style="display:none" onchange="handleFileSelect(this)">
    <img id="imgPreview" class="img-preview" alt="Preview">
    <div id="uploadProgress" style="display:none;margin-top:12px;">
      <div style="background:#e5e7eb;border-radius:4px;height:6px;overflow:hidden;">
        <div id="uploadBar" style="background:#3b82f6;height:100%;width:0%;transition:width .3s;"></div>
      </div>
      <p style="font-size:.75rem;color:#6b7280;margin-top:6px;" id="uploadStatus">Uploading…</p>
    </div>
    <div style="display:flex;align-items:center;gap:8px;margin-top:14px;color:#9ca3af;font-size:.8rem;">
      <div style="flex:1;height:1px;background:#e5e7eb;"></div><span>OR paste URL</span><div style="flex:1;height:1px;background:#e5e7eb;"></div>
    </div>
    <div class="img-url-row">
      <input type="text" id="modalUrlInput" placeholder="https://example.com/image.jpg" oninput="previewFromUrl(this.value)">
      <button type="button" onclick="applyModalUrl()" style="padding:8px 14px;background:#3b82f6;color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:.875rem;font-weight:500;">Use URL</button>
    </div>
    <div style="display:flex;justify-content:flex-end;gap:10px;margin-top:16px;">
      <button type="button" onclick="closeImgModal()" style="padding:8px 18px;border:1px solid #d1d5db;border-radius:8px;cursor:pointer;font-size:.875rem;background:#f9fafb;">Cancel</button>
      <button type="button" onclick="confirmImageSelection()" id="confirmBtn" style="padding:8px 18px;background:#2563eb;color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:.875rem;font-weight:500;" disabled>
        <i class="fas fa-check mr-1"></i> Insert Image
      </button>
    </div>
  </div>
</div>

<div class="content" id="content">
  <!-- Topbar -->
  <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <div class="flex items-center gap-2 text-sm text-gray-500">
        <a href="pages.php" class="hover:text-blue-600 flex items-center gap-1"><i class="fas fa-file-alt"></i> Pages</a>
        <i class="fas fa-chevron-right text-xs text-gray-400"></i>
        <span class="text-gray-800 font-medium">Create New Page</span>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon"></i>
      </button>
      <a href="pages.php" class="border border-gray-300 hover:bg-gray-50 text-gray-600 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-medium">
        <i class="fas fa-arrow-left"></i> Back
      </a>
    </div>
  </div>

  <main class="p-6">
    <div class="mb-5">
      <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
        <i class="fas fa-plus-circle text-blue-600"></i> Create New Page
      </h1>
      <p class="text-gray-500 text-sm mt-0.5">Fill in the details below to add a new page</p>
    </div>

    <?php if(!empty($errors['db'])): ?>
    <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg flex items-center gap-2">
      <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($errors['db']) ?>
    </div>
    <?php endif; ?>

    <form method="POST" id="pageForm">
    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">

      <!-- LEFT (2/3) -->
      <div class="xl:col-span-2 space-y-5">

        <!-- Page Details -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-info-circle text-blue-600"></i>
            <h2 class="font-semibold text-gray-700">Page Details</h2>
          </div>
          <div class="p-5 space-y-4">

            <!-- Layout Selector -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Layout Version</label>
              <select name="layout_version" id="layoutSelector" class="form-input" onchange="toggleLayout()">
                <option value="1" <?= $input['layout_version'] === '1' ? 'selected' : '' ?>>Layout 1 (Classic)</option>
                <option value="2" <?= $input['layout_version'] === '2' ? 'selected' : '' ?>>Layout 2 (Global Pages)</option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Title <span class="text-red-500">*</span></label>
              <input type="text" name="title" id="titleInput"
                     value="<?= htmlspecialchars($input['title']) ?>"
                     class="form-input <?= isset($errors['title'])?'has-error':'' ?>"
                     placeholder="Enter page title" autofocus>
              <?php if(isset($errors['title'])): ?><div class="error-msg"><i class="fas fa-exclamation-circle"></i><?= $errors['title'] ?></div><?php endif; ?>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Slug <span class="text-red-500">*</span></label>
              <div class="flex items-center">
                <span class="text-gray-500 text-sm font-mono bg-gray-100 border border-gray-300 px-3 py-2 rounded-l-lg border-r-0 whitespace-nowrap">communeglobal.com/</span>
                <input type="text" name="slug" id="slugInput"
                       value="<?= htmlspecialchars($input['slug']) ?>"
                       class="form-input rounded-l-none <?= isset($errors['slug'])?'has-error':'' ?>"
                       placeholder="page-slug">
              </div>
              <?php if(isset($errors['slug'])): ?><div class="error-msg"><i class="fas fa-exclamation-circle"></i><?= $errors['slug'] ?></div><?php endif; ?>
              <p class="text-xs text-gray-400 mt-1">Auto-generated from title. Only lowercase letters, numbers, hyphens.</p>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Overview <span class="text-gray-400 font-normal">(short summary)</span></label>
              <textarea name="overview" rows="3" class="form-input resize-none" placeholder="Brief description..."><?= htmlspecialchars($input['overview']) ?></textarea>
            </div>
          </div>
        </div>

        <!-- LAYOUT 2: Hero -->
        <div id="layout2-hero" class="layout2-section bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-star text-yellow-500"></i>
            <h2 class="font-semibold text-gray-700">Global Page Hero</h2>
          </div>
          <div class="p-5 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">Title</label>
                <input type="text" name="global_page_title" value="<?= htmlspecialchars($input['global_page_title']) ?>" class="form-input" placeholder="Main hero title">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">Subtext / Eyebrow</label>
                <input type="text" name="global_page_subtext" value="<?= htmlspecialchars($input['global_page_subtext']) ?>" class="form-input" placeholder="e.g. Academic Publishing Platform">
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Description</label>
              <textarea name="global_page_description" rows="3" class="form-input resize-none"><?= htmlspecialchars($input['global_page_description']) ?></textarea>
            </div>

            <!-- Hero Buttons -->
            <div id="globalButtonsContainer">
              <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-mouse-pointer mr-1"></i> Buttons</label>
              <?php foreach($globalButtons as $index => $btn): ?>
              <div class="dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3">
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
                  <input type="text" name="global_buttons[<?= $index ?>][name]" value="<?= htmlspecialchars($btn['name'] ?? '') ?>" class="form-input" placeholder="Button text">
                </div>
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Link</label>
                  <input type="text" name="global_buttons[<?= $index ?>][link]" value="<?= htmlspecialchars($btn['link'] ?? '') ?>" class="form-input" placeholder="https://">
                </div>
                <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>
              </div>
              <?php endforeach; ?>
              <button type="button" onclick="addGlobalButton()" class="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-1 mt-1">
                <i class="fas fa-plus"></i> Add Button
              </button>
            </div>

            <!-- Stats -->
            <div id="globalStatsContainer">
              <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-chart-bar mr-1"></i> Stats</label>
              <?php foreach($globalStats as $index => $stat): ?>
              <div class="dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3">
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
                  <input type="text" name="global_stats[<?= $index ?>][name]" value="<?= htmlspecialchars($stat['name'] ?? '') ?>" class="form-input" placeholder="e.g. Countries">
                </div>
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Value <span class="text-gray-400 font-normal">(text or number)</span></label>
                  <input type="text" name="global_stats[<?= $index ?>][number]" value="<?= htmlspecialchars($stat['number'] ?? '') ?>" class="form-input" placeholder="e.g. 40+, 100%, Fast">
                </div>
                <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>
              </div>
              <?php endforeach; ?>
              <button type="button" onclick="addGlobalStat()" class="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-1 mt-1">
                <i class="fas fa-plus"></i> Add Stat
              </button>
            </div>
          </div>
        </div>

        <!-- LAYOUT 2: About -->
        <div id="layout2-about" class="layout2-section bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-info text-green-500"></i>
            <h2 class="font-semibold text-gray-700">About Section</h2>
          </div>
          <div class="p-5 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">Label / Subtext</label>
                <input type="text" name="about_subtext" value="<?= htmlspecialchars($input['about_subtext']) ?>" class="form-input" placeholder="e.g. About Commune Global">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">Heading</label>
                <input type="text" name="about_title" value="<?= htmlspecialchars($input['about_title']) ?>" class="form-input" placeholder="About heading">
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Description (paragraphs)</label>
              <textarea name="about_description" id="aboutEditor" rows="5" class="form-input resize-none"><?= htmlspecialchars($input['about_description']) ?></textarea>
              <p class="text-xs text-gray-400 mt-1">Write plain paragraphs. Avoid pasting full-page HTML — the globe illustration is added automatically on the right.</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Right-side Image <span class="text-gray-400 font-normal text-xs">(optional — defaults to globe SVG)</span></label>
              <div class="img-field-row">
                <img id="about_image_thumb" class="img-thumb" src="" alt="" onerror="this.style.display='none'">
                <input type="text" name="about_image" id="about_image" value="<?= htmlspecialchars($input['about_image']) ?>" class="form-input" placeholder="https://… or upload →" oninput="syncThumb('about_image')">
                <button type="button" class="img-upload-btn" onclick="openImgModal('about_image')">
                  <i class="fas fa-upload"></i> Upload
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- LAYOUT 2: Why Choose Us -->
        <div id="layout2-whychoose" class="layout2-section bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-star text-orange-500"></i>
            <h2 class="font-semibold text-gray-700">Why Choose Us / Key Highlights</h2>
          </div>
          <div class="p-5 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">Label / Subtext</label>
                <input type="text" name="whychoose_subtext" value="<?= htmlspecialchars($input['whychoose_subtext']) ?>" class="form-input" placeholder="e.g. Why Choose Us">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">Heading</label>
                <input type="text" name="whychoose_heading" value="<?= htmlspecialchars($input['whychoose_heading']) ?>" class="form-input" placeholder="e.g. Key Highlights">
              </div>
            </div>
            <div id="whychooseCardsContainer">
              <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-th-large mr-1"></i> Cards</label>
              <?php foreach($whychooseCards as $index => $card): ?>
              <div class="dynamic-item p-4 bg-gray-50 rounded-lg border mb-3">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                  <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Card Title</label>
                    <input type="text" name="whychoose_cards[<?= $index ?>][title]" value="<?= htmlspecialchars($card['title'] ?? '') ?>" class="form-input" placeholder="Card title">
                  </div>
                  <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Card Image <span class="text-gray-400 font-normal">(optional)</span></label>
                    <div class="img-field-row">
                      <img id="whychoose_img_<?= $index ?>_thumb" class="img-thumb" src="<?= htmlspecialchars($card['image'] ?? '') ?>" alt="" onerror="this.style.display='none'" style="<?= !empty($card['image']) ? 'display:block;' : '' ?>">
                      <input type="text" name="whychoose_cards[<?= $index ?>][image]" id="whychoose_img_<?= $index ?>" value="<?= htmlspecialchars($card['image'] ?? '') ?>" class="form-input" placeholder="https://…" oninput="syncThumb('whychoose_img_<?= $index ?>')">
                      <button type="button" class="img-upload-btn" onclick="openImgModal('whychoose_img_<?= $index ?>')"><i class="fas fa-upload"></i></button>
                    </div>
                  </div>
                </div>
                <div>
                  <label class="block text-xs font-medium text-gray-600 mb-1">Description</label>
                  <textarea name="whychoose_cards[<?= $index ?>][description]" rows="2" class="form-input resize-none"><?= htmlspecialchars($card['description'] ?? '') ?></textarea>
                </div>
                <button type="button" class="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded text-xs hover:bg-red-200" onclick="removeDynamicItem(this)">Remove Card</button>
              </div>
              <?php endforeach; ?>
              <button type="button" onclick="addWhychooseCard()" class="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-1 mt-1">
                <i class="fas fa-plus"></i> Add Card
              </button>
            </div>
          </div>
        </div>

        <!-- LAYOUT 2: Mission & Vision -->
        <div id="layout2-missionvision" class="layout2-section bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-eye text-purple-500"></i>
            <h2 class="font-semibold text-gray-700">Mission & Vision</h2>
          </div>
          <div class="p-5 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">Label / Subtext</label>
                <input type="text" name="missionvision_subtext" value="<?= htmlspecialchars($input['missionvision_subtext']) ?>" class="form-input" placeholder="e.g. Our Foundation">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">Heading</label>
                <input type="text" name="missionvision_heading" value="<?= htmlspecialchars($input['missionvision_heading']) ?>" class="form-input" placeholder="e.g. Mission & Vision">
              </div>
            </div>
            <div id="missionvisionCardsContainer">
              <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-columns mr-1"></i> Cards</label>
              <?php foreach($missionvisionCards as $index => $card): ?>
              <div class="dynamic-item p-4 bg-gray-50 rounded-lg border mb-3">
                <div class="mb-3">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Card Title</label>
                  <input type="text" name="missionvision_cards[<?= $index ?>][title]" value="<?= htmlspecialchars($card['title'] ?? '') ?>" class="form-input" placeholder="e.g. Empowering Researchers">
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Description</label>
                    <textarea name="missionvision_cards[<?= $index ?>][description]" rows="3" class="form-input resize-none"><?= htmlspecialchars($card['description'] ?? '') ?></textarea>
                  </div>
                  <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Tag / Badge Label</label>
                    <input type="text" name="missionvision_cards[<?= $index ?>][button_name]" value="<?= htmlspecialchars($card['button_name'] ?? '') ?>" class="form-input" placeholder="e.g. Mission">
                  </div>
                </div>
                <button type="button" class="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded text-xs hover:bg-red-200" onclick="removeDynamicItem(this)">Remove Card</button>
              </div>
              <?php endforeach; ?>
              <button type="button" onclick="addMissionVisionCard()" class="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-1 mt-1">
                <i class="fas fa-plus"></i> Add Card
              </button>
            </div>
          </div>
        </div>

        <!-- LAYOUT 2: CTA -->
        <div id="layout2-cta" class="layout2-section bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-bullhorn text-red-500"></i>
            <h2 class="font-semibold text-gray-700">Call to Action Banner</h2>
          </div>
          <div class="p-5 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">Heading</label>
                <input type="text" name="cta_title" value="<?= htmlspecialchars($input['cta_title']) ?>" class="form-input" placeholder="e.g. Ready to Share Your Research?">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">Subtext</label>
                <textarea name="cta_description" rows="2" class="form-input resize-none"><?= htmlspecialchars($input['cta_description']) ?></textarea>
              </div>
            </div>
            <div id="ctaButtonsContainer">
              <label class="block text-sm font-medium text-gray-700 mb-2"><i class="fas fa-mouse-pointer mr-1"></i> Buttons</label>
              <?php foreach($ctaButtons as $index => $btn): ?>
              <div class="dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3">
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
                  <input type="text" name="cta_buttons[<?= $index ?>][name]" value="<?= htmlspecialchars($btn['name'] ?? '') ?>" class="form-input" placeholder="Button text">
                </div>
                <div class="flex-1">
                  <label class="block text-xs font-medium text-gray-600 mb-1">Link</label>
                  <input type="text" name="cta_buttons[<?= $index ?>][link]" value="<?= htmlspecialchars($btn['link'] ?? '') ?>" class="form-input" placeholder="https://">
                </div>
                <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>
              </div>
              <?php endforeach; ?>
              <button type="button" onclick="addCtaButton()" class="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-1 mt-1">
                <i class="fas fa-plus"></i> Add Button
              </button>
            </div>
          </div>
        </div>

        <!-- Rich Text (Layout 1) -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-edit text-blue-600"></i>
            <h2 class="font-semibold text-gray-700">Page Content (Layout 1)</h2>
            <span class="text-xs text-gray-400 ml-auto">Rich text editor</span>
          </div>
          <div class="p-5">
            <textarea name="description" id="descriptionEditor"><?= htmlspecialchars($input['description']) ?></textarea>
          </div>
        </div>

        <!-- SEO -->
        <?php include __DIR__ . '/include/seo_fields.php'; ?>
        <?php include __DIR__ . '/include/seo_analysis.php'; ?>

      </div>

      <!-- RIGHT (1/3) -->
      <div class="space-y-5">
        <?php include __DIR__ . '/include/journal_selector.php'; ?>

        <!-- Publish -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-paper-plane text-blue-600"></i>
            <h2 class="font-semibold text-gray-700">Publish</h2>
          </div>
          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1.5">Status</label>
              <select name="status" class="form-input">
                <option value="draft"     <?= $input['status']==='draft'    ?'selected':''?>>📝 Draft</option>
                <option value="published" <?= $input['status']==='published'?'selected':''?>>✅ Published</option>
                <option value="archived"  <?= $input['status']==='archived' ?'selected':''?>>📦 Archived</option>
              </select>
            </div>
            <div class="space-y-2">
              <button type="submit" name="save_page"
                      class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2.5 rounded-lg font-semibold flex items-center justify-center gap-2 shadow transition">
                <i class="fas fa-save"></i> Save Page
              </button>
              <a href="pages.php" class="w-full block text-center border border-gray-300 hover:bg-gray-50 text-gray-600 py-2.5 rounded-lg text-sm font-medium">Cancel</a>
            </div>
          </div>
        </div>

        <!-- URL Preview -->
        <div class="bg-blue-50 border border-blue-200 rounded-xl p-4">
          <div class="text-xs font-semibold text-blue-700 uppercase tracking-wide mb-2">
            <i class="fas fa-link mr-1"></i>URL Preview
          </div>
          <code class="text-blue-700 text-xs break-all">
            communeglobal.com/<span id="slugPreview" class="font-semibold"><?= htmlspecialchars($input['slug'] ?: 'page-slug') ?></span>
          </code>
        </div>

        <!-- SEO Score -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
            <i class="fas fa-chart-pie text-green-600"></i>
            <h2 class="font-semibold text-gray-700">SEO Readiness</h2>
          </div>
          <div class="p-5">
            <div class="text-3xl font-bold text-center mb-1" id="seoScore">—</div>
            <div class="text-xs text-gray-500 text-center mb-3">/ 100</div>
            <div class="h-2 bg-gray-200 rounded-full overflow-hidden">
              <div id="seoScoreBar" class="h-full bg-green-500 rounded-full transition-all" style="width:0%"></div>
            </div>
            <ul class="mt-3 space-y-1.5 text-xs" id="seoChecklist"></ul>
          </div>
        </div>
      </div>
    </div>
    </form>
  </main>
</div>

<script>
// ── TinyMCE ────────────────────────────────────────────
tinymce.init({
    selector:'#descriptionEditor,#aboutEditor',height:320,skin:'oxide',
    plugins:['advlist','autolink','lists','link','image','charmap','preview','anchor','searchreplace','visualblocks','code','fullscreen','insertdatetime','media','table','help','wordcount'],
    toolbar:'undo redo | blocks | bold italic underline | alignleft aligncenter alignright | bullist numlist | link image table | code fullscreen',
    menubar:'file edit view insert format tools table',branding:false,promotion:false,
    setup:function(ed){ed.on('change',function(){ed.save();});}
});

// ── Auto-slug ──────────────────────────────────────────
const titleInput  = document.getElementById('titleInput');
const slugInput   = document.getElementById('slugInput');
const slugPreview = document.getElementById('slugPreview');
let slugTouched   = false;
function toSlug(s){ return s.toLowerCase().replace(/[^\w\s-]/g,'').replace(/[\s_]+/g,'-').replace(/^-+|-+$/g,''); }
titleInput.addEventListener('input', function(){
    if (!slugTouched) { const s=toSlug(this.value); slugInput.value=s; if(slugPreview) slugPreview.textContent=s||'page-slug'; }
});
slugInput.addEventListener('input', function(){
    slugTouched=true; if(slugPreview) slugPreview.textContent=this.value||'page-slug';
});

// ── Layout toggle ──────────────────────────────────────
function toggleLayout() {
    const layout = document.getElementById('layoutSelector').value;
    document.querySelectorAll('.layout2-section').forEach(el => el.classList.toggle('active', layout === '2'));
}
toggleLayout();

// ── Dynamic counters ───────────────────────────────────
let globalButtonIndex      = <?= count($globalButtons) ?>;
let globalStatIndex        = <?= count($globalStats) ?>;
let whychooseCardIndex     = <?= count($whychooseCards) ?>;
let missionvisionCardIndex = <?= count($missionvisionCards) ?>;
let ctaButtonIndex         = <?= count($ctaButtons) ?>;

function addGlobalButton() {
    const c = document.getElementById('globalButtonsContainer');
    const d = document.createElement('div');
    d.className = 'dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3';
    d.innerHTML = `
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
        <input type="text" name="global_buttons[${globalButtonIndex}][name]" class="form-input" placeholder="Button text"></div>
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Link</label>
        <input type="text" name="global_buttons[${globalButtonIndex}][link]" class="form-input" placeholder="https://"></div>
        <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>`;
    c.insertBefore(d, c.lastElementChild);
    globalButtonIndex++;
}

function addGlobalStat() {
    const c = document.getElementById('globalStatsContainer');
    const d = document.createElement('div');
    d.className = 'dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3';
    d.innerHTML = `
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
        <input type="text" name="global_stats[${globalStatIndex}][name]" class="form-input" placeholder="e.g. Countries"></div>
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Value <span class="text-gray-400 font-normal">(text ok)</span></label>
        <input type="text" name="global_stats[${globalStatIndex}][number]" class="form-input" placeholder="e.g. 40+, 100%, Fast"></div>
        <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>`;
    c.insertBefore(d, c.lastElementChild);
    globalStatIndex++;
}

function addWhychooseCard() {
    const c   = document.getElementById('whychooseCardsContainer');
    const idx = whychooseCardIndex;
    const d   = document.createElement('div');
    d.className = 'dynamic-item p-4 bg-gray-50 rounded-lg border mb-3';
    d.innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
          <div><label class="block text-xs font-medium text-gray-600 mb-1">Card Title</label>
          <input type="text" name="whychoose_cards[${idx}][title]" class="form-input" placeholder="Card title"></div>
          <div><label class="block text-xs font-medium text-gray-600 mb-1">Card Image <span class="text-gray-400 font-normal">(optional)</span></label>
          <div class="img-field-row">
            <img id="whychoose_img_${idx}_thumb" class="img-thumb" alt="">
            <input type="text" name="whychoose_cards[${idx}][image]" id="whychoose_img_${idx}" class="form-input" placeholder="https://…" oninput="syncThumb('whychoose_img_${idx}')">
            <button type="button" class="img-upload-btn" onclick="openImgModal('whychoose_img_${idx}')"><i class="fas fa-upload"></i></button>
          </div></div>
        </div>
        <div><label class="block text-xs font-medium text-gray-600 mb-1">Description</label>
        <textarea name="whychoose_cards[${idx}][description]" rows="2" class="form-input resize-none"></textarea></div>
        <button type="button" class="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded text-xs hover:bg-red-200" onclick="removeDynamicItem(this)">Remove Card</button>`;
    c.insertBefore(d, c.lastElementChild);
    whychooseCardIndex++;
}

function addMissionVisionCard() {
    const c = document.getElementById('missionvisionCardsContainer');
    const d = document.createElement('div');
    d.className = 'dynamic-item p-4 bg-gray-50 rounded-lg border mb-3';
    d.innerHTML = `
        <div class="mb-3"><label class="block text-xs font-medium text-gray-600 mb-1">Card Title</label>
        <input type="text" name="missionvision_cards[${missionvisionCardIndex}][title]" class="form-input" placeholder="e.g. Empowering Researchers"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div><label class="block text-xs font-medium text-gray-600 mb-1">Description</label>
          <textarea name="missionvision_cards[${missionvisionCardIndex}][description]" rows="3" class="form-input resize-none"></textarea></div>
          <div><label class="block text-xs font-medium text-gray-600 mb-1">Tag / Badge Label</label>
          <input type="text" name="missionvision_cards[${missionvisionCardIndex}][button_name]" class="form-input" placeholder="e.g. Mission"></div>
        </div>
        <button type="button" class="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded text-xs hover:bg-red-200" onclick="removeDynamicItem(this)">Remove Card</button>`;
    c.insertBefore(d, c.lastElementChild);
    missionvisionCardIndex++;
}

function addCtaButton() {
    const c = document.getElementById('ctaButtonsContainer');
    const d = document.createElement('div');
    d.className = 'dynamic-item p-3 bg-gray-50 rounded-lg border mb-2 flex items-end gap-3';
    d.innerHTML = `
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Label</label>
        <input type="text" name="cta_buttons[${ctaButtonIndex}][name]" class="form-input" placeholder="Button text"></div>
        <div class="flex-1"><label class="block text-xs font-medium text-gray-600 mb-1">Link</label>
        <input type="text" name="cta_buttons[${ctaButtonIndex}][link]" class="form-input" placeholder="https://"></div>
        <button type="button" class="px-3 py-2 text-red-500 hover:text-red-700" onclick="removeDynamicItem(this)"><i class="fas fa-trash"></i></button>`;
    c.insertBefore(d, c.lastElementChild);
    ctaButtonIndex++;
}

function removeDynamicItem(btn) {
    const item = btn.closest('.dynamic-item');
    item.classList.add('removing');
    setTimeout(() => item.remove(), 200);
}

// ── Image Upload Modal ─────────────────────────────────
let activeImageField = null;
let selectedImageUrl = '';

function openImgModal(fieldId) {
    activeImageField = fieldId;
    selectedImageUrl = '';
    document.getElementById('imgPreview').style.display = 'none';
    document.getElementById('imgPreview').src = '';
    document.getElementById('modalUrlInput').value = '';
    document.getElementById('uploadProgress').style.display = 'none';
    document.getElementById('uploadBar').style.width = '0%';
    document.getElementById('confirmBtn').disabled = true;
    document.getElementById('fileInput').value = '';
    const existing = document.getElementById(fieldId)?.value;
    if (existing) { document.getElementById('modalUrlInput').value = existing; previewFromUrl(existing); }
    document.getElementById('imgModal').style.display = 'flex';
}

function closeImgModal() {
    document.getElementById('imgModal').style.display = 'none';
    activeImageField = null;
}

function previewFromUrl(url) {
    const prev = document.getElementById('imgPreview');
    if (url && (url.match(/\.(jpg|jpeg|png|gif|webp|svg)(\?.*)?$/i) || url.startsWith('http'))) {
        prev.src = url;
        prev.style.display = 'block';
        selectedImageUrl = url;
        document.getElementById('confirmBtn').disabled = false;
    }
}

function applyModalUrl() {
    const url = document.getElementById('modalUrlInput').value.trim();
    if (url) { selectedImageUrl = url; confirmImageSelection(); }
}

function confirmImageSelection() {
    if (!activeImageField || !selectedImageUrl) return;
    const inp = document.getElementById(activeImageField);
    if (inp) { inp.value = selectedImageUrl; syncThumb(activeImageField); }
    closeImgModal();
}

function syncThumb(fieldId) {
    const inp   = document.getElementById(fieldId);
    const thumb = document.getElementById(fieldId + '_thumb');
    if (!inp || !thumb) return;
    if (inp.value) {
        thumb.onerror = () => { thumb.style.display = 'none'; };
        thumb.onload  = () => { thumb.style.display = 'block'; };
        thumb.src = inp.value;
        thumb.style.display = 'block';
    } else {
        thumb.style.display = 'none';
    }
}

function handleFileSelect(input) {
    if (input.files && input.files[0]) uploadFile(input.files[0]);
}

function handleDrop(e) {
    e.preventDefault();
    document.getElementById('uploadZone').classList.remove('drag-over');
    if (e.dataTransfer.files && e.dataTransfer.files[0]) uploadFile(e.dataTransfer.files[0]);
}

function uploadFile(file) {
    if (!file.type.startsWith('image/')) { alert('Please select an image file.'); return; }
    const prog = document.getElementById('uploadProgress');
    const bar  = document.getElementById('uploadBar');
    const stat = document.getElementById('uploadStatus');
    prog.style.display = 'block';
    bar.style.width = '0%';
    stat.textContent = 'Uploading…';
    const reader = new FileReader();
    reader.onload = e => { const p=document.getElementById('imgPreview'); p.src=e.target.result; p.style.display='block'; };
    reader.readAsDataURL(file);
    const formData = new FormData();
    formData.append('upload_image', file);
    const xhr = new XMLHttpRequest();
    xhr.open('POST', window.location.href, true);
    xhr.upload.onprogress = e => {
        if (e.lengthComputable) { const pct=Math.round(e.loaded/e.total*100); bar.style.width=pct+'%'; stat.textContent='Uploading… '+pct+'%'; }
    };
    xhr.onload = () => {
        try {
            const res = JSON.parse(xhr.responseText);
            if (res.success) {
                selectedImageUrl = res.url;
                bar.style.width = '100%';
                stat.textContent = '✅ Upload complete!';
                document.getElementById('confirmBtn').disabled = false;
                document.getElementById('modalUrlInput').value = res.url;
            } else { stat.textContent = '❌ Upload failed: ' + (res.error || 'Unknown error'); }
        } catch(e) { stat.textContent = '❌ Server error.'; }
    };
    xhr.onerror = () => { stat.textContent = '❌ Network error.'; };
    xhr.send(formData);
}

// ── SEO Score ──────────────────────────────────────────
function calcSeoScore(){
    const checks=[
        {label:'Meta Title',       done:!!document.getElementById('metaTitleInput')?.value?.trim()},
        {label:'Meta Description', done:!!document.getElementById('metaDescInput')?.value?.trim()},
        {label:'Meta Keywords',    done:!!document.getElementById('metaKwInput')?.value?.trim()},
        {label:'Feature Image',    done:!!document.getElementById('featureImageInput')?.value?.trim()},
        {label:'OG Title',         done:!!document.getElementById('ogTitleInput')?.value?.trim()},
        {label:'OG Description',   done:!!document.getElementById('ogDescInput')?.value?.trim()},
        {label:'Twitter Title',    done:!!document.getElementById('twTitleInput')?.value?.trim()},
        {label:'Schema Markup',    done:!!document.getElementById('schemaEditor')?.value?.trim()},
        {label:'AI Summary',       done:!!document.getElementById('aiSummaryInput')?.value?.trim()},
        {label:'FAQs Added',       done:document.querySelectorAll('.faq-q').length>0&&!!document.querySelector('.faq-q')?.value?.trim()},
    ];
    const score=Math.round((checks.filter(c=>c.done).length/checks.length)*100);
    const el=document.getElementById('seoScore');
    const bar=document.getElementById('seoScoreBar');
    const list=document.getElementById('seoChecklist');
    if(el)el.textContent=score;
    if(bar){bar.style.width=score+'%';bar.className='h-full rounded-full transition-all '+(score>=80?'bg-green-500':score>=50?'bg-yellow-500':'bg-red-500');}
    if(list)list.innerHTML=checks.map(c=>`<li class="flex items-center gap-1.5 ${c.done?'text-green-600':'text-gray-400'}"><i class="fas ${c.done?'fa-check-circle':'fa-circle'} text-xs"></i>${c.label}</li>`).join('');
}
setInterval(calcSeoScore,2000); calcSeoScore();

function toggleMobileSidebar(){document.getElementById('sidebar').classList.toggle('mobile-open');}
let sidebarCollapsed=false;
function toggleSidebar(){sidebarCollapsed=!sidebarCollapsed;document.getElementById('sidebar').classList.toggle('collapsed',sidebarCollapsed);document.getElementById('content').classList.toggle('collapsed-sidebar',sidebarCollapsed);}
document.getElementById('darkModeToggle').addEventListener('click',function(){document.body.classList.toggle('dark');this.querySelector('i').classList.toggle('fa-moon');this.querySelector('i').classList.toggle('fa-sun');localStorage.setItem('darkMode',document.body.classList.contains('dark')?'enabled':'disabled');});
if(localStorage.getItem('darkMode')==='enabled'){document.body.classList.add('dark');document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');}
</script>
</body>
</html>