<?php
/**
 * firefly-admin-head-seo.php
 * Front-end admin-only SEO overlay for the CURRENT PAGE
 *
 * Now expects $page_id to be set in the global scope (for AJAX) or falls back
 * to the queried object when included normally.
 */

if (!defined('ABSPATH')) exit;

// Allow an explicit page ID (used by AJAX)
if (!isset($page_id) || !$page_id) {
    $page_id = (int) get_queried_object_id();
}

if (!$page_id) return;

$post = get_post($page_id);
if (!$post) return;
if ($post->post_type !== 'page') return;

// ---------------------------------------------------------------------
// Pull SEO meta
// ---------------------------------------------------------------------
$SEOtarget   = (string) get_post_meta($page_id, 'SEOtarget', true);
$SEOsynonyms = (string) get_post_meta($page_id, 'SEOsynonyms', true);
$SEOkeywords = (string) get_post_meta($page_id, 'SEOkeywords', true);

// ---------------------------------------------------------------------
// Optional: if you have an existing engine, use it (but we will still
// compute pills if maps are missing).
// ---------------------------------------------------------------------
$checklist = function_exists('firefly_get_page_seo_checklist')
    ? firefly_get_page_seo_checklist($page_id)
    : ['checks'=>[], 'score'=>0, 'detail'=>[]];

$detail = isset($checklist['detail']) && is_array($checklist['detail']) ? $checklist['detail'] : [];
$score  = isset($checklist['score']) ? (int)$checklist['score'] : 0;

// ---------------------------------------------------------------------
// Labels
// ---------------------------------------------------------------------
$labels = [
    'a' => 'URL includes SEOtarget',
    'b' => 'Page title includes SEOtarget',
    'c' => 'H1 includes SEOtarget',
    'd' => 'Body text includes SEOtarget',
    'e' => 'Image ALT includes SEOtarget',
    'f' => 'H2 includes any SEOsynonyms',
    'g' => 'Image ALT includes any SEOsynonyms',
    'h' => 'All SEOkeywords appear in body',
    'i' => 'Menu label includes SEOtarget',
    'j' => 'Inbound link uses SEOtarget as anchor',
];

// ---------------------------------------------------------------------
// Helpers: term parsing + matching + pill map building
// (All original helper functions remain unchanged – they are copied here)
// ---------------------------------------------------------------------
$ff_norm = function($s){
    $s = (string)$s;
    $s = wp_strip_all_tags($s);
    $s = html_entity_decode($s, ENT_QUOTES, 'UTF-8');
    $s = strtolower($s);
    $s = preg_replace('/[^\p{L}\p{N}\s\-]+/u', ' ', $s);
    $s = str_replace(['-', '_'], ' ', $s);
    $s = preg_replace('/\s+/u', ' ', $s);
    $s = trim($s);
    return $s;
};

$ff_stem = function($w){
    $w = (string)$w;
    $w = trim($w);
    if ($w === '') return '';
    if (strlen($w) > 3 && substr($w, -1) === 's') {
        return substr($w, 0, -1);
    }
    return $w;
};

$ff_terms_from = function($s) use ($ff_norm, $ff_stem){
    $s = $ff_norm($s);
    if ($s === '') return [];
    $parts = preg_split('/\s+/u', $s);
    $out = [];
    foreach ($parts as $p) {
        $p = $ff_stem($p);
        if ($p !== '') $out[] = $p;
    }
    $seen = [];
    $uniq = [];
    foreach ($out as $t) {
        if (isset($seen[$t])) continue;
        $seen[$t] = true;
        $uniq[] = $t;
    }
    return $uniq;
};

$ff_groups_from_synonyms = function($s) use ($ff_norm, $ff_terms_from){
    $s = (string)$s;
    $s = str_replace(["\r\n", "\r"], "\n", $s);
    $chunks = preg_split("/[;\n]+/u", $s);
    $groups = [];
    foreach ($chunks as $chunk) {
        $chunk = trim($chunk);
        if ($chunk === '') continue;
        $chunk = str_replace([',', '|'], ' ', $chunk);
        $terms = $ff_terms_from($chunk);
        if (!empty($terms)) $groups[] = $terms;
    }
    return $groups;
};

$ff_contains_term = function($haystack, $term) use ($ff_norm, $ff_stem){
    $h = $ff_norm($haystack);
    $t = $ff_stem($ff_norm($term));
    if ($h === '' || $t === '') return false;
    $h2 = ' ' . $h . ' ';
    $t2 = ' ' . $t . ' ';
    if (strpos($h2, $t2) !== false) return true;
    if (strlen($t) > 3) {
        $t_s = $t . 's';
        if (strpos($h2, ' ' . $t_s . ' ') !== false) return true;
    }
    if (strlen($t) > 4 && substr($t, -1) === 's') {
        $t0 = substr($t, 0, -1);
        if ($t0 !== '' && strpos($h2, ' ' . $t0 . ' ') !== false) return true;
    }
    return false;
};

$ff_pill_map_for_terms = function($haystack, $terms) use ($ff_contains_term){
    $map = [];
    foreach ($terms as $t) {
        $map[$t] = $ff_contains_term($haystack, $t);
    }
    return $map;
};

$ff_pill_map_for_syn_groups = function($haystack, $groups) use ($ff_contains_term){
    $map = [];
    foreach ($groups as $g) {
        foreach ($g as $t) {
            $map[$t] = $ff_contains_term($haystack, $t);
        }
    }
    return $map;
};

$ff_hits_tot_from_map = function($map){
    $tot = is_array($map) ? count($map) : 0;
    $hits = 0;
    if (is_array($map)) {
        foreach ($map as $ok) if ($ok) $hits++;
    }
    return [$hits, $tot];
};

// ---------------------------------------------------------------------
// Gather page “signals” (URL slug, title, H1, H2, body, image alts)
// ---------------------------------------------------------------------
$page_title = get_the_title($page_id);
$page_slug  = (string) ($post->post_name ?? '');
$page_edit_url = get_edit_post_link($page_id);

// Full Wizard URL (Customizer) – kept for reference, but we'll use inline forms
$permalink = get_permalink($page_id);
$edit_url  = admin_url('customize.php?url=' . rawurlencode($permalink));
$content_html = apply_filters('the_content', (string)$post->post_content);

$h1_text = '';
if (preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $content_html, $m1)) {
    $h1_text = wp_strip_all_tags($m1[1]);
}

$h2_text = '';
if (preg_match_all('/<h2[^>]*>(.*?)<\/h2>/is', $content_html, $m2)) {
    $pieces = [];
    foreach ($m2[1] as $x) $pieces[] = wp_strip_all_tags($x);
    $h2_text = implode(' ', $pieces);
}

$img_alt_text = '';
if (preg_match_all('/<img[^>]*\salt=(["\'])(.*?)\1/is', $content_html, $mi)) {
    $alts = [];
    foreach ($mi[2] as $alt) $alts[] = (string)$alt;
    $img_alt_text = implode(' ', $alts);
}

// Menu label text (best-effort)
$menu_label_text = '';
$menus = wp_get_nav_menus();
if ($menus && !is_wp_error($menus)) {
    $labels_found = [];
    foreach ($menus as $menu_obj) {
        $items = wp_get_nav_menu_items($menu_obj->term_id);
        if (!$items || is_wp_error($items)) continue;
        foreach ($items as $it) {
            if (!empty($it->object_id) && (int)$it->object_id === $page_id) {
                if (!empty($it->title)) $labels_found[] = (string)$it->title;
            }
        }
    }
    if (!empty($labels_found)) $menu_label_text = implode(' ', $labels_found);
}

// Inbound anchor best-effort
$anchor_text = '';
if (preg_match_all('/<a[^>]*>(.*?)<\/a>/is', $content_html, $ma)) {
    $anchors = [];
    foreach ($ma[1] as $a) $anchors[] = wp_strip_all_tags($a);
    $anchor_text = implode(' ', $anchors);
}

// ---------------------------------------------------------------------
// Build pill maps for each check
// ---------------------------------------------------------------------
$target_terms = $ff_terms_from($SEOtarget);
$syn_groups   = $ff_groups_from_synonyms($SEOsynonyms);
$keyword_terms= $ff_terms_from($SEOkeywords);

if (empty($detail['a']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($page_slug, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['a'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['b']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($page_title, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['b'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['c']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($h1_text, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['c'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['d']['map']) && !empty($target_terms)) {
    $body_text = wp_strip_all_tags($content_html);
    $map = $ff_pill_map_for_terms($body_text, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['d'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['e']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($img_alt_text, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['e'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['f']['map']) && !empty($syn_groups)) {
    $map = $ff_pill_map_for_syn_groups($h2_text, $syn_groups);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['f'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['g']['map']) && !empty($syn_groups)) {
    $map = $ff_pill_map_for_syn_groups($img_alt_text, $syn_groups);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['g'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['h']['map']) && !empty($keyword_terms)) {
    $body_text = wp_strip_all_tags($content_html);
    $map = $ff_pill_map_for_terms($body_text, $keyword_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['h'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['i']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($menu_label_text, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['i'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}
if (empty($detail['j']['map']) && !empty($target_terms)) {
    $map = $ff_pill_map_for_terms($anchor_text, $target_terms);
    [$hits,$tot] = $ff_hits_tot_from_map($map);
    $detail['j'] = ['map'=>$map,'hits'=>$hits,'tot'=>$tot];
}

// ---------------------------------------------------------------------
// Status + pill renderer
// ---------------------------------------------------------------------
$ff_status_label = function($hits, $tot) {
    $hits = (int)$hits; $tot = (int)$tot;
    if ($tot <= 0) return ['FAIL', 'ff-fail'];
    if ($hits >= $tot) return ['PASS', 'ff-pass'];
    if ($hits <= 0) return ['FAIL', 'ff-fail'];
    return ['PARTIAL FAIL', 'ff-partial'];
};

$ff_render_pills = function($map) {
    if (empty($map) || !is_array($map)) return '';
    $out = '<div style="display:flex; gap:8px; flex-wrap:wrap; margin-top:10px;">';
    foreach ($map as $term => $ok) {
        $ok = (bool)$ok;
        $border = $ok ? '#0a6b2b' : '#b00020';
        $color  = $ok ? '#0a6b2b' : '#b00020';
        $bg     = $ok ? 'rgba(10,107,43,.06)' : 'rgba(176,0,32,.06)';
        $out .= '<span style="display:inline-flex;align-items:center;padding:7px 14px;border-radius:999px;font-size:13px;border:1px solid '.$border.';color:'.$color.';background:'.$bg.';">'
             . esc_html((string)$term) . '</span>';
    }
    $out .= '</div>';
    return $out;
};

// ---------------------------------------------------------------------
// Progress bar
// ---------------------------------------------------------------------
$tasks_total = 10;
$tasks_done  = max(0, min($tasks_total, $score));
$percentage  = (int) round(($tasks_done / $tasks_total) * 100);

// AJAX
$ajax_url   = admin_url('admin-ajax.php');
$save_nonce = wp_create_nonce('firefly_seo_quick_save');

// Unique IDs
$uid      = 'ffseo_' . $page_id;
$link_id  = $uid . '_toggle';
$box_id   = $uid . '_box';
$edit_id  = $uid . '_editbox';

// ---------------------------------------------------------------------
// OUTPUT
// ---------------------------------------------------------------------
echo '<div id="'.esc_attr($box_id).'" style="margin-top:10px; padding:18px; background:#fff; color:#111; border:1px solid #ddd; border-radius:12px;">';

echo '<div style="display:flex; align-items:flex-start; justify-content:space-between; gap:12px; flex-wrap:wrap;">';
echo '<div>';
echo '<div style="font-size:18px; font-weight:900; margin-bottom:4px;">SEO report for this page</div>';
echo '<div style="color:#666; font-size:13px;" id="'.$uid.'_page_title_display">' . esc_html($page_title) . '</div>';
echo '</div>';

echo '<div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">';
echo '<div style="padding:6px 12px; border-radius:999px; border:1px solid rgba(10,107,43,.25); background:rgba(10,107,43,.06); color:#0a6b2b; font-weight:900;">'
   . (int)$tasks_done . '/10</div>';

if ($page_edit_url) {
    echo '<a class="button" style="text-decoration:none;" href="'.esc_url($page_edit_url).'">Open page editor</a>';
}
echo '</div>';
echo '</div>';

// Progress bar
echo '<div style="margin-top:12px;">';
echo '<div style="font-weight:800; margin-bottom:6px;">Progress: ' . (int)$percentage . '% completed</div>';
echo '<div style="background:#f0f0f0; border-radius:10px; height:22px; width:100%; overflow:hidden; border:1px solid #e6e6e6;">';
echo '<div id="'.$uid.'_progress_fill" style="background:#0a6b2b; height:22px; width:'.(int)$percentage.'%; text-align:center; color:#fff; font-size:12px; line-height:22px; font-weight:800;">'.(int)$percentage.'%</div>';
echo '</div>';
echo '</div>';

// === MODIFIED ACTION LINKS ===
echo '<div style="margin: 10px 0;">';
echo '<a href="#" class="button-link firefly-quick-edit" data-page-id="'.(int)$page_id.'" onclick="return false;">Quick Edit</a> | ';
echo '<a href="#" class="button-link firefly-full-wizard" data-page-id="'.(int)$page_id.'" onclick="return false;">Full Wizard</a> | ';
if ($page_edit_url) {
    echo '<a class="button-link" href="'.esc_url($page_edit_url).'">Open page editor</a>';
}
echo '</div>';

/* NEW: Quick Edit Form (page title + URL slug) – hidden initially */
echo '<div id="quick-edit-'.(int)$page_id.'" style="display:none; margin-top:15px; border-top:1px solid #ddd; padding-top:15px;">';
echo '  <form class="firefly-quick-edit-simple" data-page-id="'.(int)$page_id.'">';
echo '    <input type="hidden" name="action" value="firefly_seo_quick_save">';
echo '    <input type="hidden" name="nonce" value="'.esc_attr($save_nonce).'">';
echo '    <input type="hidden" name="page_id" value="'.(int)$page_id.'">';
echo '    <p><label>Page title:<br><input type="text" name="post_title" value="'.esc_attr($page_title).'" style="width:100%;"></label></p>';
echo '    <p><label>URL slug:<br><input type="text" name="post_name" value="'.esc_attr($page_slug).'" style="width:100%;"></label></p>';
echo '    <p><button type="submit" class="button button-primary">Save</button> ';
echo '       <button type="button" class="button firefly-cancel-quick-edit" data-page-id="'.(int)$page_id.'">Cancel</button>';
echo '       <span class="spinner" style="float:none; margin-top:0; display:none;"></span></p>';
echo '  </form>';
echo '</div>';

/* MODIFIED: Full Wizard Form (SEO fields) – originally was for Quick Edit, now renamed and toggled by Full Wizard link */
echo '<div id="full-wizard-'.(int)$page_id.'" style="display:none; margin-top:15px; border-top:1px solid #ddd; padding-top:15px;">';
echo '  <form class="firefly-full-wizard-form" data-page-id="'.(int)$page_id.'">';
echo '    <input type="hidden" name="action" value="firefly_seo_quick_save">';
echo '    <input type="hidden" name="nonce" value="'.esc_attr(wp_create_nonce("firefly_seo_quick_save")).'">';
echo '    <input type="hidden" name="page_id" value="'.(int)$page_id.'">';
echo '    <p><label>SEOtarget:<br><input type="text" name="firefly_SEOtarget" value="'.esc_attr($SEOtarget).'" style="width:100%;"></label></p>';
echo '    <p><label>SEOsynonyms:<br><textarea name="firefly_SEOsynonyms" rows="3" style="width:100%;">'.esc_textarea($SEOsynonyms).'</textarea></label></p>';
echo '    <p><label>SEOkeywords:<br><textarea name="firefly_SEOkeywords" rows="3" style="width:100%;">'.esc_textarea($SEOkeywords).'</textarea></label></p>';
echo '    <p><button type="submit" class="button button-primary">Save</button> ';
echo '       <button type="button" class="button firefly-cancel-full-wizard" data-page-id="'.(int)$page_id.'">Cancel</button> ';
echo '       <span class="spinner" style="float:none; margin-top:0; display:none;"></span></p>';
echo '  </form>';
echo '</div>';

// No SEO warning
if ($SEOtarget === '' && $SEOsynonyms === '' && $SEOkeywords === '') {
    echo '<div style="margin-top:12px; background:#b00020; color:#fff; padding:10px; border-radius:10px; text-align:center; font-weight:900;">THERE IS NO SEO FOR THIS PAGE!!</div>';
}

echo '<hr style="border:none;border-top:1px solid #eee;margin:16px 0;">';

// Checklist
echo '<h3 style="margin:0 0 8px 0;">Checklist</h3>';

foreach ($labels as $k => $lab) {
    $d = isset($detail[$k]) && is_array($detail[$k]) ? $detail[$k] : ['map'=>[], 'hits'=>0, 'tot'=>0];
    $hits = isset($d['hits']) ? (int)$d['hits'] : 0;
    $tot  = isset($d['tot'])  ? (int)$d['tot']  : 0;
    $map  = isset($d['map'])  && is_array($d['map']) ? $d['map'] : [];

    [$statusText, $statusCls] = $ff_status_label($hits, $tot);
    $statusColor = ($statusText === 'PASS') ? '#0a6b2b' : (($statusText === 'PARTIAL FAIL') ? '#b35b00' : '#b00020');

    echo '<div style="border:1px solid #eee; border-radius:12px; padding:12px; margin:10px 0; background:#fff;">';
    echo '<div style="display:flex; align-items:baseline; justify-content:space-between; gap:12px; flex-wrap:wrap;">';
    echo '<div style="font-weight:900;">' . esc_html($k) . '. ' . esc_html($lab) . ($tot > 0 ? ' <span style="color:#666;font-weight:700;">(' . $hits . '/' . $tot . ')</span>' : '') . '</div>';
    echo '<div style="font-weight:900; font-size:16px; color:'.$statusColor.';">' . esc_html($statusText) . '</div>';
    echo '</div>';

    echo $ff_render_pills($map);

    // Inline editors for a and b (unchanged from original, but kept as is)
    if ($k === 'a') {
        echo '<div style="margin-top:10px;">';
        echo '<form class="ffseo-inline-save" data-page-id="'.(int)$page_id.'">';
        echo '<input type="hidden" name="action" value="firefly_seo_quick_save">';
        echo '<input type="hidden" name="nonce" value="'.esc_attr($save_nonce).'">';
        echo '<input type="hidden" name="page_id" value="'.(int)$page_id.'">';
        echo '<label style="font-weight:600;">Edit page URL:</label> ';
        echo '<input type="text" name="post_name" value="'.esc_attr($page_slug).'" style="width:260px; max-width:70%;"> ';
        echo '<button type="submit" class="button">Save</button>';
        echo '<span class="ff-save-msg" style="margin-left:8px; color:#0a6b2b; display:none;">Saved</span>';
        echo '</form>';
        echo '</div>';
    }
    if ($k === 'b') {
        echo '<div style="margin-top:10px;">';
        echo '<form class="ffseo-inline-save" data-page-id="'.(int)$page_id.'">';
        echo '<input type="hidden" name="action" value="firefly_seo_quick_save">';
        echo '<input type="hidden" name="nonce" value="'.esc_attr($save_nonce).'">';
        echo '<input type="hidden" name="page_id" value="'.(int)$page_id.'">';
        echo '<label style="font-weight:600;">Edit page title:</label> ';
        echo '<input type="text" name="post_title" value="'.esc_attr($page_title).'" style="width:420px; max-width:85%;"> ';
        echo '<button type="submit" class="button">Save</button>';
        echo '<span class="ff-save-msg" style="margin-left:8px; color:#0a6b2b; display:none;">Saved</span>';
        echo '</form>';
        echo '</div>';
    }

    echo '</div>';
}

echo '</div>'; // main box
?>

<script id="ffseo-boot-<?php echo (int)$page_id; ?>">
(function(){
    // Guard: install delegated listeners only once per page load
    if (window._ffseoListenersInstalled) return;
    window._ffseoListenersInstalled = true;

    var ajaxUrl = <?php echo json_encode($ajax_url); ?>;

    function showSpinner(form) {
        var sp = form.querySelector('.spinner');
        if (sp) sp.style.visibility = 'visible';
    }
    function hideSpinner(form) {
        var sp = form.querySelector('.spinner');
        if (sp) sp.style.visibility = 'hidden';
    }
    function showMsg(form) {
        var msg = form.querySelector('.ff-save-msg');
        if (msg) { msg.style.display = 'inline'; setTimeout(function(){ msg.style.display = 'none'; }, 2000); }
    }

    /**
     * Build the redirect URL after a save.
     * If the slug changed, swap the last meaningful path segment so we land
     * on the new URL — not the old one that no longer exists.
     */
    function buildRedirectUrl(newSlug) {
        var u = new URL(window.location.href);

        if (newSlug) {
            // Strip trailing slash, split path into segments
            var path = u.pathname.replace(/\/$/, '');
            var parts = path.split('/');
            // Replace the last non-empty segment with the new slug
            for (var i = parts.length - 1; i >= 0; i--) {
                if (parts[i] !== '') {
                    parts[i] = newSlug;
                    break;
                }
            }
            u.pathname = parts.join('/') + '/';
        }

        u.searchParams.set('ffseo_open', '1');
        return u.toString();
    }

    function doAjaxSave(form, onSuccess) {
        var fd = new FormData(form);
        if (!fd.get('action')) fd.append('action', 'firefly_seo_quick_save');
        showSpinner(form);
        fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(res){
                hideSpinner(form);
                if (!res || !res.success) {
                    alert((res && res.data) ? res.data : 'Save failed');
                    return;
                }
                showMsg(form);
                if (onSuccess) onSuccess(res);
                var newSlug = (res.data && res.data.post_name) ? res.data.post_name : null;
                setTimeout(function(){
                    window.location.href = buildRedirectUrl(newSlug);
                }, 800);
            })
            .catch(function(){
                hideSpinner(form);
                alert('Save failed – check your connection.');
            });
    }

    // ── Delegated CLICK handler ──────────────────────────────────────────
    document.addEventListener('click', function(e) {
        var t = e.target;
        if (!t) return;

        // Quick Edit toggle
        if (t.classList && t.classList.contains('firefly-quick-edit')) {
            e.preventDefault();
            var pid = t.getAttribute('data-page-id');
            var box = document.getElementById('quick-edit-' + pid);
            if (box) box.style.display = (box.style.display === 'none' || box.style.display === '') ? 'block' : 'none';
            return;
        }
        // Cancel Quick Edit
        if (t.classList && t.classList.contains('firefly-cancel-quick-edit')) {
            e.preventDefault();
            var box = document.getElementById('quick-edit-' + t.getAttribute('data-page-id'));
            if (box) box.style.display = 'none';
            return;
        }
        // Full Wizard toggle
        if (t.classList && t.classList.contains('firefly-full-wizard')) {
            e.preventDefault();
            var pid = t.getAttribute('data-page-id');
            var box = document.getElementById('full-wizard-' + pid);
            if (!box) return;
            box.style.display = (box.style.display === 'none' || box.style.display === '') ? 'block' : 'none';
            return;
        }
        // Cancel Full Wizard
        if (t.classList && t.classList.contains('firefly-cancel-full-wizard')) {
            e.preventDefault();
            var box = document.getElementById('full-wizard-' + t.getAttribute('data-page-id'));
            if (box) box.style.display = 'none';
            return;
        }
        // Wizard tab click
        if (t.classList && t.classList.contains('ff-wiz-tab')) {
            e.preventDefault();
            ffWizShow(t.getAttribute('data-wiz'), t.getAttribute('data-step'));
            return;
        }
        // Wizard Next
        if (t.classList && t.classList.contains('ff-wiz-next')) {
            e.preventDefault();
            ffWizShow(t.getAttribute('data-wiz'), t.getAttribute('data-next'));
            return;
        }
        // Wizard Prev
        if (t.classList && t.classList.contains('ff-wiz-prev')) {
            e.preventDefault();
            ffWizShow(t.getAttribute('data-wiz'), t.getAttribute('data-prev'));
            return;
        }
    });

    function ffWizShow(pid, stepNum) {
        var container = document.getElementById('full-wizard-' + pid);
        if (!container) return;
        container.querySelectorAll('.ff-wiz-step[data-wiz="' + pid + '"]').forEach(function(el){
            el.style.display = 'none';
        });
        var step = container.querySelector('.ff-wiz-step[data-wiz="' + pid + '"][data-step="' + stepNum + '"]');
        if (step) step.style.display = 'block';
        container.querySelectorAll('.ff-wiz-tab[data-wiz="' + pid + '"]').forEach(function(tab){
            var active = tab.getAttribute('data-step') == stepNum;
            tab.style.background = active ? '#e1e1e1' : '#f1f1f1';
            tab.style.fontWeight = active ? 'bold' : 'normal';
        });
    }

    // ── Delegated SUBMIT handler ─────────────────────────────────────────
    document.addEventListener('submit', function(e) {
        var form = e.target;
        if (!form || !form.classList) return;

        // Inline URL / title editors under checklist rows a and b
        if (form.classList.contains('ffseo-inline-save')) {
            e.preventDefault();
            doAjaxSave(form, null);
            return;
        }
        // Quick Edit (SEOtarget / synonyms / keywords)
        if (form.classList.contains('firefly-quick-edit-simple')) {
            e.preventDefault();
            doAjaxSave(form, function(){
                var box = document.getElementById('quick-edit-' + form.getAttribute('data-page-id'));
                if (box) box.style.display = 'none';
            });
            return;
        }
        // Full Wizard
        if (form.classList.contains('firefly-full-wizard-form')) {
            e.preventDefault();
            doAjaxSave(form, function(){
                var box = document.getElementById('full-wizard-' + form.getAttribute('data-page-id'));
                if (box) box.style.display = 'none';
            });
            return;
        }
    });

})();
</script>