<?php
require_once('config.php');
$page_title = 'Auto News';

require_once('inc/header.php');

// Categories
$all_categories = showAllttdata("mahamudfutureit_category", "WHERE CategorySataus='Published' ORDER BY CategoryName ASC");
// Divisions
$all_divisions  = showAllttdata("mahamudfutureit_loc_divisions");

// Existing writers (distinct) from already published articles — used for datalist suggestions
$writers_list = [];
try {
    $wq = $conn->query("SELECT DISTINCT PostWriterName FROM mahamudfutureit_article WHERE PostWriterName IS NOT NULL AND PostWriterName != '' ORDER BY PostWriterName ASC LIMIT 200");
    foreach ($wq as $w) {
        $nm = html_entity_decode($w['PostWriterName'], ENT_QUOTES, 'UTF-8');
        if (trim($nm) !== '') $writers_list[] = $nm;
    }
} catch (Exception $e) {}

$status = $_GET['status'] ?? '';
?>
<style>
.an-wrap { max-width: 1400px; margin: 0 auto; }
.an-card { background:#fff; border-radius:12px; box-shadow:0 1px 3px rgba(0,0,0,.06); padding:18px; margin-bottom:18px; }
.an-card h6.an-title { font-weight:700; margin:0 0 14px; padding-bottom:10px; border-bottom:1px solid #eef0f3; display:flex; align-items:center; gap:8px; }
.an-hero { background:linear-gradient(135deg,#fef9c3 0%,#fef3c7 100%); border:1px solid #fde68a; }
.an-hero .form-control, .an-hero .btn { height:50px; font-size:16px; }
.an-toolbar { display:flex; flex-wrap:wrap; gap:6px; }
.an-toolbar .btn { font-size:12px; padding:6px 10px; }
.an-img-box { position:relative; border:2px dashed #d1d5db; border-radius:10px; padding:12px; text-align:center; background:#fafafa; }
.an-img-box img { max-height:280px; max-width:100%; border-radius:6px; }
.an-img-actions { display:flex; flex-wrap:wrap; gap:6px; margin-top:10px; justify-content:center; }
.an-img-tabs { display:flex; gap:4px; margin-bottom:8px; }
.an-img-tabs .btn { flex:1; }
textarea#f_content { font-family: 'SolaimanLipi', system-ui, sans-serif; font-size:15px; line-height:1.7; }
.an-side .form-label { font-size:13px; font-weight:600; margin-bottom:4px; color:#374151; }
.an-side .form-control, .an-side .form-select { font-size:14px; }
.an-flag { background:#f9fafb; border-radius:8px; padding:10px; }
.an-publish-btn { height:54px; font-size:17px; font-weight:600; }
@media (max-width: 767px) {
  .an-card { padding:14px; border-radius:10px; }
  .an-hero .form-control, .an-hero .btn { height:46px; font-size:15px; }
  .an-toolbar .btn { flex:1; min-width:48%; }
  textarea#f_content { font-size:14px; }
}
</style>

<main id="main" class="main">
<div class="an-wrap">

  <div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
    <div class="pagetitle mb-0">
      <h1 class="mb-1"><i class="bi bi-lightning-charge-fill text-warning"></i> Auto News</h1>
      <small class="text-muted">যেকোনো নিউজ সাইটের লিংক দিন — সম্পূর্ণ নিউজ অটো চলে আসবে</small>
    </div>
    <a href="article.php" class="btn btn-outline-primary btn-sm mt-2 mt-md-0">
      <i class="bi bi-grid"></i> All Articles
    </a>
  </div>

  <?php if ($status === 'duplicate'): ?>
    <div class="alert alert-warning">⚠️ এই নিউজ আগেই পোস্ট করা হয়েছে (duplicate source URL)।</div>
  <?php elseif ($status === 'fail'): ?>
    <div class="alert alert-danger">❌ পোস্ট করতে সমস্যা হয়েছে। আবার চেষ্টা করুন।</div>
  <?php endif; ?>

  <!-- ============= URL FETCH BOX ============= -->
  <div class="an-card an-hero">
    <label class="fw-bold mb-2 d-block">📰 নিউজ লিংক দিন</label>
    <div class="input-group input-group-lg">
      <input type="url" id="newsUrl" class="form-control" placeholder="https://example.com/news/...">
      <button id="btnFetch" type="button" class="btn btn-primary">
        <i class="bi bi-download"></i> <span class="d-none d-sm-inline">Fetch News</span><span class="d-inline d-sm-none">Fetch</span>
      </button>
    </div>
    <small class="text-muted d-block mt-2">যেকোনো বাংলা/ইংরেজি নিউজ পোর্টালের আর্টিকেল লিংক — ৫ সেকেন্ডে data চলে আসবে।</small>
    <div id="fetchStatus" class="mt-2"></div>
  </div>

  <!-- ============= PUBLISH FORM (hidden until fetched) ============= -->
  <form id="publishForm" action="auto-news-publish.php" method="post" enctype="multipart/form-data" style="display:none;">
    <input type="hidden" name="publish_auto_news" value="1">
    <input type="hidden" name="image_url" id="f_image_url">
    <input type="hidden" name="image_url_override" id="f_image_url_override">


    <div class="row g-3">
      <!-- LEFT -->
      <div class="col-lg-8">
        <div class="an-card">
          <h6 class="an-title"><i class="bi bi-pencil-square"></i> Article Content</h6>

          <div class="mb-3">
            <label class="form-label fw-bold">Title <span class="text-danger">*</span></label>
            <input name="PostTitle" id="f_title" type="text" class="form-control form-control-lg" required>
          </div>
          <div class="mb-3">
            <label class="form-label fw-bold">Subtitle</label>
            <input name="PostSubtitle" id="f_subtitle" type="text" class="form-control">
          </div>

          <div class="mb-2">
            <div class="d-flex flex-wrap justify-content-between align-items-center pb-2 gap-2">
              <label class="form-label fw-bold mb-0">Content <span class="text-danger">*</span></label>
              <div class="an-toolbar">
                <button type="button" class="btn btn-outline-secondary" id="btnClean" title="HTML/style ক্লিন করুন">
                  <i class="bi bi-eraser"></i> Clean
                </button>
                <button type="button" class="btn btn-outline-secondary" id="btnAutoPara" title="প্যারাগ্রাফ অটো করুন">
                  <i class="bi bi-text-paragraph"></i> Paragraph
                </button>
                <button type="button" class="btn btn-outline-secondary" id="btnStripLinks" title="লিংক বাদ দিন">
                  <i class="bi bi-link-45deg"></i> Strip Links
                </button>
                <button type="button" class="btn btn-outline-danger" id="btnRemoveJunk" title="Login/menu/আরও পড়ুন বাদ দিন">
                  <i class="bi bi-trash"></i> Junk Remove
                </button>
              </div>
            </div>
            <textarea name="PostContent" id="f_content" class="form-control" rows="16" required></textarea>
            <small class="text-muted">HTML supported। উপরের বাটন থেকে clean / paragraph / junk remove করতে পারবেন।</small>
          </div>
        </div>

        <!-- Featured Image -->
        <div class="an-card">
          <h6 class="an-title"><i class="bi bi-image"></i> Featured Image</h6>

          <div class="an-img-box" id="imgBox">
            <div id="imgPreview"><div class="text-muted small">কোনো ছবি নেই</div></div>
            <div class="an-img-actions">
              <button type="button" class="btn btn-sm btn-outline-primary" id="btnImgUpload">
                <i class="bi bi-upload"></i> Upload from Computer
              </button>
              <button type="button" class="btn btn-sm btn-outline-secondary" id="btnImgUrl">
                <i class="bi bi-link"></i> Use Different URL
              </button>
              <button type="button" class="btn btn-sm btn-outline-success" id="btnImgRestore" style="display:none;">
                <i class="bi bi-arrow-counterclockwise"></i> Original
              </button>
              <button type="button" class="btn btn-sm btn-outline-danger" id="btnImgRemove">
                <i class="bi bi-x-lg"></i> Remove
              </button>
            </div>
          </div>

          <input type="file" name="image_file" id="image_file" accept="image/*" style="display:none;">

          <div class="mt-2" id="imgUrlBox" style="display:none;">
            <div class="input-group input-group-sm">
              <input type="url" id="imgUrlInput" class="form-control" placeholder="https://.../image.jpg">
              <button type="button" class="btn btn-primary" id="btnImgUrlApply">Apply</button>
            </div>
          </div>

          <input name="PostImageCaption" id="f_caption" type="text" class="form-control mt-3" placeholder="Image caption (optional)">
        </div>

        <div class="an-card">
          <h6 class="an-title"><i class="bi bi-link-45deg"></i> Source (Editable)</h6>
          <label class="form-label fw-bold">Source URL</label>
          <input name="source_url" id="f_source_url_view" type="url" class="form-control mb-2" placeholder="https://...">
          <label class="form-label fw-bold">Source Name</label>
          <input name="source_name" id="f_source_name_view" type="text" class="form-control" placeholder="যেমন: Prothom Alo">
          <small class="text-muted">Source URL দিয়ে duplicate check হয়। Name / URL ইচ্ছামতো edit করতে পারবেন।</small>

        </div>
      </div>

      <!-- RIGHT -->
      <div class="col-lg-4 an-side">
        <div class="an-card">
          <h6 class="an-title"><i class="bi bi-gear"></i> Publish Settings</h6>

          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="PostStatus" class="form-select">
              <option value="published" selected>Published</option>
              <option value="draft">Draft</option>
              <option value="pending">Pending</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Publish Date</label>
            <input name="publishDateTime" type="datetime-local" class="form-control" value="<?php echo date('Y-m-d\TH:i'); ?>">
          </div>

          <div class="mb-3">
            <label class="form-label">Category <span class="text-danger">*</span></label>
            <select name="PostCategory" class="form-select" required>
              <option value="">Select category</option>
              <?php foreach ($all_categories as $cat): ?>
                <option value="<?php echo $cat['CategoryID']; ?>"><?php echo $cat['CategoryName']; ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Topics / Tags</label>
            <input name="PostTopic" id="f_topics" type="text" class="form-control" placeholder="comma দিয়ে আলাদা করুন">
          </div>

          <div class="mb-3">
            <label class="form-label">Article Writer</label>
            <input name="PostWriterName" id="f_writer" type="text" class="form-control" list="writers_dl" placeholder="Writer name লিখুন বা select করুন">
            <datalist id="writers_dl">
              <?php foreach ($writers_list as $wn): ?>
                <option value="<?php echo htmlspecialchars($wn, ENT_QUOTES); ?>">
              <?php endforeach; ?>
            </datalist>
          </div>


          <div class="mb-3">
            <label class="form-label">Writer Designation</label>
            <input name="PostWriterDesignation" type="text" class="form-control" placeholder="যেমন: বিশেষ প্রতিনিধি">
          </div>

          <div class="mb-3">
            <label class="form-label">Division</label>
            <select name="PostDivision" class="form-select">
              <option value="">Select Division</option>
              <?php foreach ($all_divisions as $d): ?>
                <option value="<?php echo $d['id']; ?>"><?php echo $d['bn_name']; ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="an-flag mb-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="PostLead" value="on" id="ckLead">
              <label class="form-check-label" for="ckLead"><strong>Lead News</strong></label>
            </div>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="PostSpotlight" value="on" id="ckSpot">
              <label class="form-check-label" for="ckSpot"><strong>Spotlight</strong></label>
            </div>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="PostTicker" value="on" id="ckTick">
              <label class="form-check-label" for="ckTick"><strong>Ticker</strong></label>
            </div>
          </div>

          <button type="submit" class="btn btn-success w-100 an-publish-btn">
            <i class="bi bi-cloud-upload"></i> Publish Now
          </button>
        </div>
      </div>
    </div>
  </form>

</div>
</main>

<script>
(function () {
  const $ = (s) => document.querySelector(s);
  const btn = $('#btnFetch');
  const urlInput = $('#newsUrl');
  const form = $('#publishForm');
  const statusBox = $('#fetchStatus');

  let originalImage = '';

  function renderImage(src) {
    if (src) {
      $('#imgPreview').innerHTML = '<img src="' + src + '" alt="featured">';
      $('#btnImgRestore').style.display = (src !== originalImage && originalImage) ? 'inline-block' : 'none';
    } else {
      $('#imgPreview').innerHTML = '<div class="text-muted small py-4">কোনো ছবি নেই</div>';
      $('#btnImgRestore').style.display = originalImage ? 'inline-block' : 'none';
    }
  }

  btn.addEventListener('click', async () => {
    const url = urlInput.value.trim();
    if (!url) { alert('লিংক দিন'); return; }

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Fetching...';
    statusBox.innerHTML = '<div class="text-muted">নিউজ data নিয়ে আসা হচ্ছে...</div>';

    try {
      const fd = new FormData();
      fd.append('url', url);
      const res = await fetch('auto-news-fetch.php', { method: 'POST', body: fd });
      const json = await res.json();

      if (!json.ok) {
        statusBox.innerHTML = '<div class="alert alert-danger">' + json.msg + '</div>';
      } else {
        const d = json.data;
        $('#f_title').value     = d.title || '';
        $('#f_subtitle').value  = d.subtitle || '';
        $('#f_content').value   = d.content || '';
        $('#f_writer').value    = d.author || '';
        $('#f_caption').value   = d.image_caption || '';
        $('#f_topics').value    = '';
        $('#f_source_url_view').value = d.source_url || '';
        $('#f_source_name_view').value = d.source_name || '';
        $('#f_image_url').value = d.image_url || '';
        $('#f_image_url_override').value = '';
        $('#image_file').value = '';
        originalImage = d.image_url || '';
        renderImage(originalImage);


        statusBox.innerHTML = '<div class="alert alert-success">✅ নিউজ লোড হয়েছে। নিচে edit করে publish করুন।</div>';
        form.style.display = 'block';
        form.scrollIntoView({ behavior: 'smooth' });
      }
    } catch (e) {
      statusBox.innerHTML = '<div class="alert alert-danger">Network error: ' + e.message + '</div>';
    } finally {
      btn.disabled = false;
      btn.innerHTML = '<i class="bi bi-download"></i> Fetch News';
    }
  });

  // ========= Image replace =========
  $('#btnImgUpload').addEventListener('click', () => $('#image_file').click());
  $('#image_file').addEventListener('change', (e) => {
    const f = e.target.files[0];
    if (!f) return;
    $('#f_image_url_override').value = '';
    $('#f_image_url').value = ''; // disable remote download — local upload wins
    const reader = new FileReader();
    reader.onload = (ev) => renderImage(ev.target.result);
    reader.readAsDataURL(f);
  });

  $('#btnImgUrl').addEventListener('click', () => {
    const box = $('#imgUrlBox');
    box.style.display = box.style.display === 'none' ? 'block' : 'none';
  });
  $('#btnImgUrlApply').addEventListener('click', () => {
    const v = $('#imgUrlInput').value.trim();
    if (!v) return;
    $('#f_image_url_override').value = v;
    $('#f_image_url').value = v;
    $('#image_file').value = '';
    renderImage(v);
    $('#imgUrlBox').style.display = 'none';
  });

  $('#btnImgRestore').addEventListener('click', () => {
    $('#f_image_url_override').value = '';
    $('#f_image_url').value = originalImage;
    $('#image_file').value = '';
    renderImage(originalImage);
  });

  $('#btnImgRemove').addEventListener('click', () => {
    $('#f_image_url').value = '';
    $('#f_image_url_override').value = '';
    $('#image_file').value = '';
    renderImage('');
  });

  // ========= Cleaning tools (DOM-based, reliable) =========
  const ta = () => $('#f_content');

  const BLOCK_TAGS = ['p','h1','h2','h3','h4','h5','h6','blockquote','ul','ol','li','table','div','section','article','figure','header','footer','aside','nav','form'];
  const KEEP_INLINE = ['a','strong','b','em','i','u','br'];

  // Parse HTML into a DocumentFragment we can walk
  function parseFragment(html) {
    const doc = new DOMParser().parseFromString('<!doctype html><body><div id="root">' + html + '</div>', 'text/html');
    return doc.getElementById('root');
  }

  // Flatten: turn <p><blockquote>x</blockquote><blockquote>y</blockquote></p>
  // into <blockquote>x</blockquote><blockquote>y</blockquote>
  // Recursively unwrap any <p> that contains block-level children.
  function flattenBlocks(root) {
    let changed = true;
    let safety = 0;
    while (changed && safety++ < 10) {
      changed = false;
      const ps = Array.from(root.querySelectorAll('p'));
      for (const p of ps) {
        const blockChild = p.querySelector('h1,h2,h3,h4,h5,h6,blockquote,ul,ol,table,div,figure,section,article,aside,header,footer,nav,form,p');
        if (!blockChild) continue;
        // Move all children of p out before p, then remove p
        const parent = p.parentNode;
        while (p.firstChild) parent.insertBefore(p.firstChild, p);
        parent.removeChild(p);
        changed = true;
      }
    }
  }

  // Unwrap div/span/section/article/figure but keep their children
  function unwrapJunkWrappers(root) {
    const wrappers = Array.from(root.querySelectorAll('div, span, section, article, figure, figcaption, aside, header, footer, nav, form'));
    for (const el of wrappers) {
      const parent = el.parentNode;
      if (!parent) continue;
      while (el.firstChild) parent.insertBefore(el.firstChild, el);
      parent.removeChild(el);
    }
  }

  // Strip attributes from every element except href on <a>
  function stripAttrs(root) {
    const all = root.querySelectorAll('*');
    for (const el of all) {
      const tag = el.tagName.toLowerCase();
      const attrs = Array.from(el.attributes);
      for (const a of attrs) {
        if (tag === 'a' && a.name.toLowerCase() === 'href') continue;
        el.removeAttribute(a.name);
      }
      if (tag === 'a') {
        el.setAttribute('target', '_blank');
        el.setAttribute('rel', 'noopener');
      }
    }
  }

  // Wrap stray text nodes (between block elements) into <p>
  function wrapStrayText(root) {
    const kids = Array.from(root.childNodes);
    for (const node of kids) {
      if (node.nodeType === 3) {
        const t = node.textContent.replace(/\s+/g, ' ').trim();
        if (t) {
          const p = document.createElement('p');
          p.textContent = t;
          root.insertBefore(p, node);
        }
        root.removeChild(node);
      }
    }
  }

  // Remove empty/whitespace-only block tags
  function removeEmptyBlocks(root) {
    const blocks = Array.from(root.querySelectorAll('p, h1, h2, h3, h4, h5, h6, blockquote'));
    for (const b of blocks) {
      if (!b.textContent.replace(/\s|\u00a0/g, '').length && !b.querySelector('img')) {
        b.remove();
      }
    }
  }

  // Pretty-print root's HTML with one block per line
  function serialize(root) {
    let out = '';
    for (const node of root.childNodes) {
      if (node.nodeType === 1) {
        out += node.outerHTML + '\n';
      } else if (node.nodeType === 3) {
        const t = node.textContent.trim();
        if (t) out += '<p>' + t + '</p>\n';
      }
    }
    return out.trim();
  }

  function toast(msg, color) {
    const div = document.createElement('div');
    div.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:' + (color||'#16a34a') + ';color:#fff;padding:10px 18px;border-radius:8px;font-size:14px;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,.2)';
    div.textContent = msg;
    document.body.appendChild(div);
    setTimeout(() => div.remove(), 1800);
  }

  $('#btnClean').addEventListener('click', () => {
    const root = parseFragment(ta().value);
    unwrapJunkWrappers(root);
    flattenBlocks(root);
    stripAttrs(root);
    wrapStrayText(root);
    removeEmptyBlocks(root);
    ta().value = serialize(root);
    toast('✅ Cleaned');
  });

  $('#btnAutoPara').addEventListener('click', () => {
    const root = parseFragment(ta().value);
    flattenBlocks(root);
    // For each <p>, split on double-<br> into separate <p>s
    const ps = Array.from(root.querySelectorAll('p'));
    for (const p of ps) {
      const html = p.innerHTML;
      const parts = html.split(/(?:\s*<br\s*\/?>\s*){2,}/i).map(s => s.trim()).filter(Boolean);
      if (parts.length > 1) {
        const frag = document.createDocumentFragment();
        for (const part of parts) {
          const np = document.createElement('p');
          np.innerHTML = part;
          frag.appendChild(np);
        }
        p.replaceWith(frag);
      }
    }
    wrapStrayText(root);
    removeEmptyBlocks(root);
    ta().value = serialize(root);
    toast('✅ Paragraphs formatted');
  });

  $('#btnStripLinks').addEventListener('click', () => {
    const root = parseFragment(ta().value);
    const links = Array.from(root.querySelectorAll('a'));
    for (const a of links) {
      const text = document.createTextNode(a.textContent);
      a.replaceWith(text);
    }
    ta().value = serialize(root);
    toast(links.length ? ('✅ ' + links.length + ' links removed') : 'ℹ️ No links found', links.length ? '#16a34a' : '#6b7280');
  });

  $('#btnRemoveJunk').addEventListener('click', () => {
    const root = parseFragment(ta().value);
    unwrapJunkWrappers(root);
    flattenBlocks(root);

    // Drop ul/ol/nav/form/table entirely
    root.querySelectorAll('ul, ol, nav, form, table, aside, li').forEach(n => n.remove());

    // Drop single-word junk headings
    root.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(h => {
      const t = h.textContent.trim();
      if (/^(ই-পেপার|Login|EngLogin|Eng\s*Login|খুঁজুন|হোম|মেনু|Menu|Search|Subscribe|সাবস্ক্রাইব)$/i.test(t)) h.remove();
    });

    const junkRe = /(Login|EngLogin|Eng\s*Login|আরও পড়ুন|গুগল নিউজ|ফলো করুন|শেয়ার|বিজ্ঞাপন|ই-পেপার|খুঁজুন|প্রিন্ট|Subscribe|সাবস্ক্রাইব|কপি করুন|Copy link|Read more|রিলেটেড)/i;
    const menuWords = ['সর্বশেষ','বাংলাদেশ','রাজনীতি','বিশ্ব','বাণিজ্য','মতামত','খেলা','বিনোদন','চাকরি','জীবনযাপন','ভিডিও','হোম','লাইফস্টাইল','প্রযুক্তি','শিক্ষা','ধর্ম','স্বাস্থ্য','সম্পাদকীয়','আন্তর্জাতিক'];
    const bylineRe = /^(নিজস্ব প্রতিবেদক|ক্রীড়া প্রতিবেদক|ডেস্ক রিপোর্ট|স্টাফ রিপোর্টার|বিশেষ প্রতিনিধি|প্রথম আলো|বিডিনিউজ|বাংলা ট্রিবিউন|রয়টার্স|বিবিসি|এএফপি)/;
    const dateRe = /^[\d০-৯\s\-\/:\.]+ ?(মে|জানুয়ারি|ফেব্রুয়ারি|মার্চ|এপ্রিল|জুন|জুলাই|আগস্ট|সেপ্টেম্বর|অক্টোবর|নভেম্বর|ডিসেম্বর|ঘণ্টা|মিনিট|সেকেন্ড|আগে)/;
    const urlOnlyRe = /^(https?:\/\/\S+|www\.\S+|[a-z0-9-]+\.(com|net|org|io|co|news|info|bd|in|uk|gov)(\/\S*)?)$/i;

    let removed = 0;
    root.querySelectorAll('p, h1, h2, h3, h4, h5, h6, blockquote').forEach(el => {
      const text = el.textContent.replace(/\s+/g, ' ').trim();
      if (!text) { el.remove(); removed++; return; }
      if (urlOnlyRe.test(text)) { el.remove(); removed++; return; }
      if (junkRe.test(text)) { el.remove(); removed++; return; }
      if (bylineRe.test(text) && text.length < 80) { el.remove(); removed++; return; }
      if (dateRe.test(text) && text.length < 50) { el.remove(); removed++; return; }
      let hits = 0;
      for (const mw of menuWords) if (text.indexOf(mw) !== -1) hits++;
      if (hits >= 3) { el.remove(); removed++; return; }
      if (el.tagName.toLowerCase() === 'p' && text.length < 20) { el.remove(); removed++; return; }
    });

    wrapStrayText(root);
    removeEmptyBlocks(root);
    ta().value = serialize(root);
    toast('🧹 ' + removed + ' junk block(s) removed');
  });
})();
</script>


<?php require_once('inc/footer.php'); ?>

