<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
$pageTitle = 'Page Builder';
include __DIR__ . '/includes/admin_header.php';

$dataFile = __DIR__ . '/../data/pages.json';
$pages = smurf_read_json($dataFile, []);
if (!is_array($pages)) $pages = [];

function slugify($s){
  $s = strtolower(trim((string)$s));
  $s = preg_replace('/[^a-z0-9\s\-]/', '', $s);
  $s = preg_replace('/\s+/', '-', $s);
  $s = preg_replace('/\-+/', '-', $s);
  $s = trim($s, '-');
  return $s ?: 'page';
}

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

function page_builder_defaults(){
  return [
    ['type'=>'text','title'=>'Welcome','body'=>'<p>Start building your page here.</p>'],
  ];
}

function normalize_blocks($raw){
  if (!is_array($raw)) return [];
  $out = [];
  foreach ($raw as $b) {
    if (!is_array($b)) continue;
    $type = trim((string)($b['type'] ?? 'text'));
    if ($type === '') $type = 'text';
    $out[] = [
      'type' => $type,
      'title' => trim((string)($b['title'] ?? '')),
      'body' => (string)($b['body'] ?? ''),
      'image' => trim((string)($b['image'] ?? '')),
      'button_text' => trim((string)($b['button_text'] ?? '')),
      'button_url' => trim((string)($b['button_url'] ?? '')),
      'extra' => trim((string)($b['extra'] ?? '')),
      'style' => trim((string)($b['style'] ?? 'default')),
    ];
  }
  return $out;
}

function legacy_html_to_blocks($html){
  $html = trim((string)$html);
  if ($html === '') return page_builder_defaults();
  return [['type'=>'html','title'=>'Imported HTML','body'=>$html,'image'=>'','button_text'=>'','button_url'=>'','extra'=>'','style'=>'default']];
}

function render_blocks_html($blocks){
  $html = '';
  foreach ($blocks as $block) {
    $type = $block['type'] ?? 'text';
    $title = trim((string)($block['title'] ?? ''));
    $body = (string)($block['body'] ?? '');
    $image = trim((string)($block['image'] ?? ''));
    $btnT = trim((string)($block['button_text'] ?? ''));
    $btnU = trim((string)($block['button_url'] ?? ''));
    $extra = trim((string)($block['extra'] ?? ''));
    switch ($type) {
      case 'hero':
        $html .= '<section class="content-card builder-hero">';
        if ($image !== '') $html .= '<div class="hero-image"><img src="'.pb_h($image).'" alt=""></div>';
        if ($title !== '') $html .= '<h2>'.pb_h($title).'</h2>';
        if ($body !== '') $html .= '<div class="builder-copy">'.$body.'</div>';
        if ($btnT !== '' && $btnU !== '') $html .= '<div class="page-cta"><a class="btn btn-accent" href="'.pb_h($btnU).'">'.pb_h($btnT).'</a></div>';
        $html .= '</section>';
      break;
      case 'text':
        $html .= '<section class="content-card">';
        if ($title !== '') $html .= '<h2>'.pb_h($title).'</h2>';
        if ($body !== '') $html .= '<div class="builder-copy">'.$body.'</div>';
        $html .= '</section>';
      break;
      case 'image_text':
        $html .= '<section class="split-two builder-split">';
        $html .= '<div class="content-card">';
        if ($image !== '') $html .= '<img class="builder-media" src="'.pb_h($image).'" alt="">';
        $html .= '</div><div class="content-card">';
        if ($title !== '') $html .= '<h2>'.pb_h($title).'</h2>';
        if ($body !== '') $html .= '<div class="builder-copy">'.$body.'</div>';
        if ($btnT !== '' && $btnU !== '') $html .= '<div class="page-cta"><a class="btn btn-accent" href="'.pb_h($btnU).'">'.pb_h($btnT).'</a></div>';
        $html .= '</div></section>';
      break;
      case 'cards':
        $parts = preg_split('/\r\n|\r|\n/', $extra);
        $html .= '<section class="split-two">';
        $left = trim((string)($parts[0] ?? 'Card One|Add details here.'));
        $right = trim((string)($parts[1] ?? 'Card Two|Add details here.'));
        foreach ([$left,$right] as $part){
          [$ct,$cb] = array_pad(explode('|',$part,2),2,'');
          $html .= '<div class="content-card"><h3>'.pb_h($ct).'</h3><p>'.nl2br(pb_h($cb)).'</p></div>';
        }
        $html .= '</section>';
      break;
      case 'quote':
        $html .= '<section class="content-card quote-block">';
        if ($title !== '') $html .= '<h3>'.pb_h($title).'</h3>';
        if ($body !== '') $html .= '<blockquote>'.$body.'</blockquote>';
        if ($extra !== '') $html .= '<p class="quote-source">— '.pb_h($extra).'</p>';
        $html .= '</section>';
      break;
      case 'buttons':
        $lines = preg_split('/\r\n|\r|\n/', $extra);
        $html .= '<section class="content-card center-text">';
        if ($title !== '') $html .= '<h3>'.pb_h($title).'</h3>';
        if ($body !== '') $html .= '<div class="builder-copy">'.$body.'</div>';
        $html .= '<div class="button-row">';
        foreach ($lines as $line){
          $line = trim($line); if ($line==='') continue;
          [$t,$u] = array_pad(explode('|',$line,2),2,'#');
          $html .= '<a class="btn btn-accent" href="'.pb_h(trim($u)).'">'.pb_h(trim($t)).'</a>';
        }
        $html .= '</div></section>';
      break;
      case 'html':
        $html .= '<section class="content-card">'.$body.'</section>';
      break;
    }
    $html .= "\n";
  }
  return $html;
}

$blockTypes = [
  'hero' => 'Hero Banner',
  'text' => 'Text Section',
  'image_text' => 'Image + Text',
  'cards' => 'Two Cards',
  'quote' => 'Quote',
  'buttons' => 'Button Row',
  'html' => 'Raw HTML',
];
$LAYOUTS = [
  'standard' => 'Standard page',
  'fullwidth' => 'Full width page',
  'hero' => 'Hero image first',
  'cards' => 'Card-heavy landing page',
  'promo' => 'Promotion / event page',
  'dj-profile' => 'DJ profile page',
  'event' => 'Event spotlight page',
  'contact' => 'Contact / info page',
  'listen-live' => 'Listen live page',
  'dj-roster' => 'DJ roster page',
  'schedule-grid' => 'Schedule grid page',
  'top50' => 'Top 50 / chart page',
  'sponsors' => 'Sponsor showcase page',
  'team' => 'Station team page',
  'gallery' => 'Media gallery page',
  'podcast' => 'Podcast / replay page',
];

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';
$edit = null;
if ($action === 'edit' && $id !== '' && isset($pages[$id])) $edit = $pages[$id];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) {
    http_response_code(403);
    die('No edit permission for this page.');
  }
  $mode = $_POST['mode'] ?? 'create';
  $oldId = trim((string)($_POST['old_id'] ?? ''));
  $title = trim($_POST['title'] ?? 'Untitled');
  $slug = slugify($_POST['slug'] ?? $title);
  $summary = trim($_POST['summary'] ?? '');
  $buttonText = trim($_POST['button_text'] ?? '');
  $buttonUrl = trim($_POST['button_url'] ?? '');
  $image = trim($_POST['image'] ?? '');
  if ($image === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/content');
    if ($uploaded !== '') $image = '/img/content/' . $uploaded;
  }
  $showNav = !empty($_POST['show_in_nav']);
  $published = !empty($_POST['published']);
  $layoutStyle = $_POST['layout_style'] ?? 'standard';
  if (!isset($LAYOUTS[$layoutStyle])) $layoutStyle = 'standard';

  $types = $_POST['block_type'] ?? [];
  $titles = $_POST['block_title'] ?? [];
  $bodies = $_POST['block_body'] ?? [];
  $images = $_POST['block_image'] ?? [];
  $btnTexts = $_POST['block_button_text'] ?? [];
  $btnUrls = $_POST['block_button_url'] ?? [];
  $extras = $_POST['block_extra'] ?? [];
  $blocks = [];
  $count = max(count($types), count($titles), count($bodies));
  for ($i=0; $i<$count; $i++) {
    $type = trim((string)($types[$i] ?? 'text'));
    if (!isset($blockTypes[$type])) $type = 'text';
    $blocks[] = [
      'type' => $type,
      'title' => trim((string)($titles[$i] ?? '')),
      'body' => (string)($bodies[$i] ?? ''),
      'image' => trim((string)($images[$i] ?? '')),
      'button_text' => trim((string)($btnTexts[$i] ?? '')),
      'button_url' => trim((string)($btnUrls[$i] ?? '')),
      'extra' => trim((string)($extras[$i] ?? '')),
      'style' => 'default',
    ];
  }
  if (!$blocks) $blocks = page_builder_defaults();
  $contentHtml = render_blocks_html($blocks);

  if ($mode === 'create') {
    $base = $slug; $n = 2;
    while (isset($pages[$slug])) { $slug = $base . '-' . $n; $n++; }
  } elseif ($mode === 'update' && $oldId !== '' && isset($pages[$oldId]) && $slug !== $oldId) {
    $base = $slug; $n = 2;
    while (isset($pages[$slug]) && $slug !== $oldId) { $slug = $base . '-' . $n; $n++; }
    $pages[$slug] = $pages[$oldId];
    unset($pages[$oldId]);
    $oldId = $slug;
  }

  $target = ($mode === 'update' && $oldId !== '' && isset($pages[$oldId])) ? $oldId : $slug;
  $pages[$target] = [
    'title' => $title,
    'slug' => $target,
    'content' => $contentHtml,
    'blocks' => $blocks,
    'summary' => $summary,
    'image' => $image,
    'button_text' => $buttonText,
    'button_url' => $buttonUrl,
    'published' => $published,
    'show_in_nav' => $showNav,
    'layout_style' => $layoutStyle,
    'updated' => date('Y-m-d H:i:s'),
  ];
  smurf_write_json($dataFile, $pages);
  header('Location: /admin/pages.php?saved=1');
  exit;
}

if ($action === 'delete' && $id !== '' && isset($pages[$id])) {
  if (!$CAN_EDIT) { http_response_code(403); die('No edit permission for this page.'); }
  unset($pages[$id]);
  smurf_write_json($dataFile, $pages);
  header('Location: /admin/pages.php?deleted=1');
  exit;
}

$edit = null;
if ($action === 'edit' && $id !== '' && isset($pages[$id])) {
  $edit = $pages[$id];
  $edit['blocks'] = normalize_blocks($edit['blocks'] ?? legacy_html_to_blocks($edit['content'] ?? ''));
}
$seedBlocks = $edit['blocks'] ?? page_builder_defaults();
?>
<section class="content-card">
  <h1 class="admin-title">🧩 Visual Page Builder</h1>
  <p style="opacity:.85;">Build pages with sections instead of one giant text box. You can still drop raw HTML into any block when needed.</p>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Page saved.</div><?php endif; ?>
  <?php if (!empty($_GET['deleted'])): ?><div class="msg success">Page deleted.</div><?php endif; ?>

  <div class="builder-toolbar">
    <?php foreach ($blockTypes as $typeKey => $typeLabel): ?>
      <button type="button" class="admin-btn builder-add" data-type="<?= pb_h($typeKey) ?>">+ <?= pb_h($typeLabel) ?></button>
    <?php endforeach; ?>
  </div>

  <div class="page-builder-grid" style="margin-top:14px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= $edit ? 'Edit Page' : 'Create Page' ?></h3>
      <form method="POST" class="form" enctype="multipart/form-data" id="builderForm">
        <input type="hidden" name="mode" value="<?= $edit ? 'update' : 'create' ?>">
        <input type="hidden" name="old_id" value="<?= pb_h($edit['slug'] ?? '') ?>">

        <div class="admin-form-grid">
          <div>
            <label>Title</label>
            <input class="input-field" name="title" id="pageTitleInput" value="<?= pb_h($edit['title'] ?? '') ?>" required>
          </div>
          <div>
            <label>Slug (URL)</label>
            <input class="input-field" name="slug" value="<?= pb_h($edit['slug'] ?? '') ?>" placeholder="my-page">
          </div>
        </div>

        <div class="page-flags">
          <label style="display:flex;gap:10px;align-items:center;"><input type="checkbox" name="published" <?= !empty($edit['published']) ? 'checked' : '' ?>><span>Published</span></label>
          <label style="display:flex;gap:10px;align-items:center;"><input type="checkbox" name="show_in_nav" <?= !empty($edit['show_in_nav']) ? 'checked' : '' ?>><span>Show in Navigation</span></label>
        </div>

        <label>Layout Style</label>
        <select class="input-field" name="layout_style" id="layoutStyle">
          <?php foreach ($LAYOUTS as $layoutKey => $layoutLabel): ?>
            <option value="<?= pb_h($layoutKey) ?>" <?= (($edit['layout_style'] ?? 'standard') === $layoutKey) ? 'selected' : '' ?>><?= pb_h($layoutLabel) ?></option>
          <?php endforeach; ?>
        </select>

        <label>Summary / Intro</label>
        <textarea class="input-field" name="summary" id="pageSummaryInput" rows="3" placeholder="Short intro text for the top of the page..."><?= pb_h($edit['summary'] ?? '') ?></textarea>

        <label>Hero Image Link (optional)</label>
        <input class="input-field" name="image" id="pageImageInput" placeholder="https://example.com/banner.jpg or /img/content/file.jpg" value="<?= pb_h($edit['image'] ?? '') ?>">

        <label>Or Upload Hero Image</label>
        <div class="upload-box">
          <input type="file" name="image_file" accept="image/*" <?= $CAN_EDIT ? '' : 'disabled' ?>>
          <small class="upload-help">Leave the image link blank if you want to upload a file instead.</small>
        </div>

        <div class="admin-form-grid">
          <div>
            <label>Button Text (optional)</label>
            <input class="input-field" name="button_text" id="pageButtonTextInput" value="<?= pb_h($edit['button_text'] ?? '') ?>" placeholder="Learn More">
          </div>
          <div>
            <label>Button URL (optional)</label>
            <input class="input-field" name="button_url" value="<?= pb_h($edit['button_url'] ?? '') ?>" placeholder="https://... or /contact.php">
          </div>
        </div>

        <div class="builder-blocks" id="builderBlocks">
          <?php foreach ($seedBlocks as $idx => $block): ?>
            <div class="builder-block" data-block>
              <div class="builder-block-head">
                <strong class="builder-block-title">Section <?= $idx + 1 ?></strong>
                <div class="builder-block-actions">
                  <button type="button" class="admin-btn block-up">↑</button>
                  <button type="button" class="admin-btn block-down">↓</button>
                  <button type="button" class="admin-btn block-dup">Duplicate</button>
                  <button type="button" class="admin-btn block-del">Delete</button>
                </div>
              </div>
              <label>Block Type</label>
              <select class="input-field builder-type" name="block_type[]">
                <?php foreach ($blockTypes as $tk => $tl): ?>
                  <option value="<?= pb_h($tk) ?>" <?= (($block['type'] ?? 'text') === $tk) ? 'selected' : '' ?>><?= pb_h($tl) ?></option>
                <?php endforeach; ?>
              </select>
              <div class="admin-form-grid">
                <div>
                  <label>Heading</label>
                  <input class="input-field builder-title" name="block_title[]" value="<?= pb_h($block['title'] ?? '') ?>">
                </div>
                <div>
                  <label>Image / Media URL</label>
                  <input class="input-field builder-image" name="block_image[]" value="<?= pb_h($block['image'] ?? '') ?>" placeholder="/img/content/example.jpg">
                </div>
              </div>
              <label>Body / HTML</label>
              <textarea class="input-field builder-body" name="block_body[]" rows="5" placeholder="Use plain text or HTML"><?= pb_h($block['body'] ?? '') ?></textarea>
              <div class="admin-form-grid">
                <div>
                  <label>Button Text</label>
                  <input class="input-field builder-button-text" name="block_button_text[]" value="<?= pb_h($block['button_text'] ?? '') ?>">
                </div>
                <div>
                  <label>Button URL</label>
                  <input class="input-field builder-button-url" name="block_button_url[]" value="<?= pb_h($block['button_url'] ?? '') ?>">
                </div>
              </div>
              <label>Extra Data</label>
              <textarea class="input-field builder-extra" name="block_extra[]" rows="3" placeholder="For Two Cards: one per line like Title|Text&#10;For Button Row: Button|URL per line&#10;For Quote: put source / byline here"><?= pb_h($block['extra'] ?? '') ?></textarea>
            </div>
          <?php endforeach; ?>
        </div>

        <div class="page-action-row">
          <button class="admin-btn primary" type="submit" <?= !$CAN_EDIT ? 'disabled' : '' ?>><?= $edit ? 'Save Changes' : 'Create Page' ?></button>
          <?php if ($edit): ?><a class="admin-btn" href="/admin/pages.php">Cancel</a><a class="admin-btn" href="/page.php?slug=<?= urlencode($edit['slug'] ?? '') ?>" target="_blank">Preview Live</a><?php endif; ?>
        </div>
      </form>
    </section>

    <section class="page-builder-help">
      <div class="content-card page-preview-card" style="text-align:left;">
        <h3 style="margin-top:0;">Builder guide</h3>
        <ul style="margin:0; padding-left:18px; line-height:1.7;">
          <li><strong>Hero Banner</strong> for your headline section.</li>
          <li><strong>Image + Text</strong> for promos, DJs, sponsors or stories.</li>
          <li><strong>Two Cards</strong> for side-by-side highlights.</li>
          <li><strong>Button Row</strong> for calls to action.</li>
          <li><strong>Raw HTML</strong> if you want full control.</li>
          <li><strong>Layout Style</strong> now includes full width, DJ, event, contact, listen live, roster, schedule, charts, sponsors, team, gallery and podcast templates.</li>
        </ul>
      </div>
      <div class="content-card page-preview-card" style="text-align:left;">
        <h3 style="margin-top:0;">Live page preview</h3>
        <div class="page-wireframe">
          <div class="page-wireframe-label">Hero Area</div>
          <div id="previewHero" class="page-wireframe-hero"><div class="page-wireframe-empty">No hero image selected yet.</div></div>
          <div class="page-wireframe-body">
            <div class="page-wireframe-chip" id="previewLayout">Standard page</div>
            <h2 id="previewTitle">Your Page Title</h2>
            <p id="previewSummary">Your intro text will appear here.</p>
            <div id="previewButtonWrap" style="display:none;"><span id="previewButton" class="admin-btn primary">Call to Action</span></div>
            <div class="page-wireframe-content" id="previewBlocks"></div>
          </div>
        </div>
      </div>
    </section>
  </div>
</section>

<template id="builderBlockTemplate">
  <div class="builder-block" data-block>
    <div class="builder-block-head">
      <strong class="builder-block-title">New Section</strong>
      <div class="builder-block-actions">
        <button type="button" class="admin-btn block-up">↑</button>
        <button type="button" class="admin-btn block-down">↓</button>
        <button type="button" class="admin-btn block-dup">Duplicate</button>
        <button type="button" class="admin-btn block-del">Delete</button>
      </div>
    </div>
    <label>Block Type</label>
    <select class="input-field builder-type" name="block_type[]">
      <?php foreach ($blockTypes as $tk => $tl): ?>
        <option value="<?= pb_h($tk) ?>"><?= pb_h($tl) ?></option>
      <?php endforeach; ?>
    </select>
    <div class="admin-form-grid">
      <div><label>Heading</label><input class="input-field builder-title" name="block_title[]"></div>
      <div><label>Image / Media URL</label><input class="input-field builder-image" name="block_image[]" placeholder="/img/content/example.jpg"></div>
    </div>
    <label>Body / HTML</label>
    <textarea class="input-field builder-body" name="block_body[]" rows="5" placeholder="Use plain text or HTML"></textarea>
    <div class="admin-form-grid">
      <div><label>Button Text</label><input class="input-field builder-button-text" name="block_button_text[]"></div>
      <div><label>Button URL</label><input class="input-field builder-button-url" name="block_button_url[]"></div>
    </div>
    <label>Extra Data</label>
    <textarea class="input-field builder-extra" name="block_extra[]" rows="3" placeholder="For Two Cards: one per line like Title|Text&#10;For Button Row: Button|URL per line&#10;For Quote: put source / byline here"></textarea>
  </div>
</template>

<script>
(function(){
  const blocksWrap = document.getElementById('builderBlocks');
  const template = document.getElementById('builderBlockTemplate');
  const addButtons = document.querySelectorAll('.builder-add');
  const titleInput = document.getElementById('pageTitleInput');
  const summaryInput = document.getElementById('pageSummaryInput');
  const imageInput = document.getElementById('pageImageInput');
  const layoutSelect = document.getElementById('layoutStyle');
  const pageButtonTextInput = document.getElementById('pageButtonTextInput');
  const previewTitle = document.getElementById('previewTitle');
  const previewSummary = document.getElementById('previewSummary');
  const previewHero = document.getElementById('previewHero');
  const previewLayout = document.getElementById('previewLayout');
  const previewBlocks = document.getElementById('previewBlocks');
  const previewButtonWrap = document.getElementById('previewButtonWrap');
  const previewButton = document.getElementById('previewButton');

  function renumber(){
    [...blocksWrap.querySelectorAll('[data-block]')].forEach((block, idx)=>{
      const title = block.querySelector('.builder-block-title');
      if (title) title.textContent = 'Section ' + (idx + 1);
    });
  }

  function createBlock(type='text'){
    const node = template.content.firstElementChild.cloneNode(true);
    node.querySelector('.builder-type').value = type;
    blocksWrap.appendChild(node);
    renumber();
    bindBlock(node);
    renderPreview();
  }

  function bindBlock(block){
    block.querySelector('.block-up').addEventListener('click', ()=>{
      const prev = block.previousElementSibling;
      if (prev) blocksWrap.insertBefore(block, prev);
      renumber(); renderPreview();
    });
    block.querySelector('.block-down').addEventListener('click', ()=>{
      const next = block.nextElementSibling;
      if (next) blocksWrap.insertBefore(next, block);
      renumber(); renderPreview();
    });
    block.querySelector('.block-del').addEventListener('click', ()=>{
      if (blocksWrap.children.length <= 1) return;
      block.remove(); renumber(); renderPreview();
    });
    block.querySelector('.block-dup').addEventListener('click', ()=>{
      const clone = block.cloneNode(true);
      blocksWrap.insertBefore(clone, block.nextElementSibling);
      bindBlock(clone); renumber(); renderPreview();
    });
    block.querySelectorAll('input, textarea, select').forEach(el=>el.addEventListener('input', renderPreview));
  }

  function esc(str){
    return (str || '').replace(/[&<>\"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m]));
  }

  function renderPreview(){
    previewTitle.textContent = titleInput.value || 'Your Page Title';
    previewSummary.textContent = summaryInput.value || 'Your intro text will appear here.';
    const layoutText = layoutSelect.options[layoutSelect.selectedIndex]?.text || 'Standard page';
    previewLayout.textContent = layoutText;
    if ((imageInput.value || '').trim()) {
      previewHero.innerHTML = '<img src="'+esc(imageInput.value.trim())+'" alt="" style="width:100%;height:100%;object-fit:cover;">';
    } else {
      previewHero.innerHTML = '<div class="page-wireframe-empty">No hero image selected yet.</div>';
    }
    if ((pageButtonTextInput.value || '').trim()) {
      previewButtonWrap.style.display = 'block';
      previewButton.textContent = pageButtonTextInput.value.trim();
    } else {
      previewButtonWrap.style.display = 'none';
    }
    const cards = [...blocksWrap.querySelectorAll('[data-block]')].map(block=>{
      const type = block.querySelector('.builder-type').value;
      const heading = block.querySelector('.builder-title').value;
      const body = block.querySelector('.builder-body').value;
      const image = block.querySelector('.builder-image').value;
      const extra = block.querySelector('.builder-extra').value;
      let inner = '<div class="preview-block-card"><div class="preview-badge">'+esc(type.replace('_',' '))+'</div>';
      if (heading) inner += '<h4>'+esc(heading)+'</h4>';
      if (image) inner += '<div class="preview-thumb">Image: '+esc(image)+'</div>';
      if (body) inner += '<p>'+esc(body).replace(/\n/g,'<br>')+'</p>';
      if (extra) inner += '<small>'+esc(extra).replace(/\n/g,'<br>')+'</small>';
      inner += '</div>';
      return inner;
    });
    previewBlocks.innerHTML = cards.join('') || '<div class="page-wireframe-empty">Add a block to begin.</div>';
  }

  addButtons.forEach(btn=>btn.addEventListener('click', ()=>createBlock(btn.dataset.type || 'text')));
  blocksWrap.querySelectorAll('[data-block]').forEach(bindBlock);
  [titleInput, summaryInput, imageInput, layoutSelect, pageButtonTextInput].forEach(el=>el.addEventListener('input', renderPreview));
  renderPreview();
})();
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
