<?php
/*
Plugin Name: SmartProductSEO – SEO Generator for WooCommerce
Plugin URI: https://smartproductseo.com/smartproductseo-generator/
Description: Generate search-intent-focused WooCommerce SEO titles, focus keyphrases, and meta descriptions with Yoast-compatible product SEO tools.
Version: 1.6.9
Author: Jolizzie
Author URI: https://smartproductseo.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: smartproductseo-generator
*/

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

if (!defined('WCSEO_VERSION')) {
    define('WCSEO_VERSION', '1.6.9');
}

register_activation_hook(__FILE__, 'wcseo_activate_defaults');

function wcseo_activate_defaults() {
    $defaults = array(
        'wcseo_enable_dark_mode'       => 0,
        'wcseo_show_notifications'     => 1,
        'wcseo_smart_title_cleanup'    => 1,
        'wcseo_product_type_presets'   => 1,
        'wcseo_ai_ready_wording'       => 1,
        'wcseo_one_click_regenerate'   => 1,
        'wcseo_history_snapshots'      => 1,
    );

    foreach ($defaults as $key => $value) {
        if (get_option($key, null) === null) {
            update_option($key, absint($value));
        }
    }
}

add_action('admin_init', 'wcseo_ensure_defaults');

function wcseo_ensure_defaults() {
    wcseo_activate_defaults();
}

add_action('admin_notices', 'wcseo_dependency_notices');

function wcseo_dependency_notices() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $screen = function_exists('get_current_screen') ? get_current_screen() : null;

    if (!$screen || empty($screen->base)) {
        return;
    }

    $show_on_plugin_pages = in_array(
        $screen->base,
        array('plugins', 'toplevel_page_smartproductseo-generator', 'post'),
        true
    );

    if (!$show_on_plugin_pages) {
        return;
    }

    if (!class_exists('WooCommerce')) {
        echo '<div class="notice notice-error"><p><strong>SmartProductSEO:</strong> WooCommerce is required for this plugin to generate product SEO fields. Please install and activate WooCommerce.</p></div>';
    }

    if (!defined('WPSEO_VERSION')) {
        echo '<div class="notice notice-warning"><p><strong>SmartProductSEO:</strong> Yoast SEO is recommended for full SEO title, focus keyphrase, and meta description field compatibility.</p></div>';
    }
}

function wcseo_sanitize_checkbox($value) {
    return !empty($value) ? 1 : 0;
}

add_action('wp_ajax_wcseo_save_history_snapshot', 'wcseo_save_history_snapshot');

function wcseo_save_history_snapshot() {
    check_ajax_referer('wcseo_history_nonce', 'nonce');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

    if (!$post_id || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error(array('message' => 'Permission denied.'));
    }

    if (!get_option('wcseo_history_snapshots', 1)) {
        wp_send_json_success(array('message' => 'History disabled.'));
    }

    $snapshot = array(
        'time'  => current_time('mysql'),
        'title' => isset($_POST['seo_title']) ? sanitize_text_field(wp_unslash($_POST['seo_title'])) : '',
        'meta'  => isset($_POST['seo_meta']) ? sanitize_textarea_field(wp_unslash($_POST['seo_meta'])) : '',
        'focus' => isset($_POST['seo_focus']) ? sanitize_text_field(wp_unslash($_POST['seo_focus'])) : '',
    );

    if ($snapshot['title'] === '' && $snapshot['meta'] === '' && $snapshot['focus'] === '') {
        wp_send_json_success(array('message' => 'Empty snapshot skipped.'));
    }

    $history = get_post_meta($post_id, '_wcseo_history_snapshots', true);

    if (!is_array($history)) {
        $history = array();
    }

    $latest = isset($history[0]) && is_array($history[0]) ? $history[0] : array();

    if (
        isset($latest['title'], $latest['meta'], $latest['focus']) &&
        $latest['title'] === $snapshot['title'] &&
        $latest['meta'] === $snapshot['meta'] &&
        $latest['focus'] === $snapshot['focus']
    ) {
        wp_send_json_success(array('message' => 'Duplicate snapshot skipped.'));
    }

    array_unshift($history, $snapshot);
    $history = array_slice($history, 0, 10);

    update_post_meta($post_id, '_wcseo_history_snapshots', $history);

    wp_send_json_success(array('message' => 'History snapshot saved.'));
}

add_action('wp_ajax_wcseo_restore_history_snapshot', 'wcseo_restore_history_snapshot');

function wcseo_restore_history_snapshot() {
    check_ajax_referer('wcseo_history_nonce', 'nonce');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

    if (!$post_id || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error(array('message' => 'Permission denied.'));
    }

    if (!get_option('wcseo_history_snapshots', 1)) {
        wp_send_json_error(array('message' => 'History restore is disabled in settings.'));
    }

    $history = get_post_meta($post_id, '_wcseo_history_snapshots', true);

    if (!is_array($history) || empty($history)) {
        wp_send_json_error(array('message' => 'No previous SEO snapshot found.'));
    }

    $snapshot = array_shift($history);

    update_post_meta($post_id, '_wcseo_history_snapshots', array_slice($history, 0, 10));

    wp_send_json_success(array(
        'message'  => 'Previous SEO snapshot restored.',
        'snapshot' => array(
            'time'  => isset($snapshot['time']) ? sanitize_text_field($snapshot['time']) : '',
            'title' => isset($snapshot['title']) ? sanitize_text_field($snapshot['title']) : '',
            'meta'  => isset($snapshot['meta']) ? sanitize_textarea_field($snapshot['meta']) : '',
            'focus' => isset($snapshot['focus']) ? sanitize_text_field($snapshot['focus']) : '',
        ),
    ));
}

add_action('admin_enqueue_scripts', 'wcseo_admin_assets');

function wcseo_admin_assets($hook_suffix) {
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;

    $is_product_edit = (
        $screen &&
        $screen->base === 'post' &&
        isset($screen->post_type) &&
        $screen->post_type === 'product'
    );

    $is_dashboard = ($hook_suffix === 'toplevel_page_smartproductseo-generator');

    if (!$is_product_edit && !$is_dashboard) {
        return;
    }

    wp_register_style('smartproductseo-admin-style', false, array(), WCSEO_VERSION);
    wp_enqueue_style('smartproductseo-admin-style');
    wp_add_inline_style('smartproductseo-admin-style', wcseo_get_admin_css());

    if ($is_product_edit) {
        global $post;

        wp_register_script(
            'smartproductseo-product-generator',
            '',
            array('jquery'),
            WCSEO_VERSION,
            true
        );

        wp_enqueue_script('smartproductseo-product-generator');

        $data = array(
            'postId'         => isset($post->ID) ? absint($post->ID) : 0,
            'logoUrl'        => esc_url(plugin_dir_url(__FILE__) . 'assets/logo-header-40.png'),
            'notifications'  => (bool) get_option('wcseo_show_notifications', 1),
            'smartCleanup'   => (bool) get_option('wcseo_smart_title_cleanup', 1),
            'productPresets' => (bool) get_option('wcseo_product_type_presets', 1),
            'aiReady'        => (bool) get_option('wcseo_ai_ready_wording', 1),
            'oneClick'       => (bool) get_option('wcseo_one_click_regenerate', 1),
            'history'        => (bool) get_option('wcseo_history_snapshots', 1),
            'darkMode'       => (bool) get_option('wcseo_enable_dark_mode', 0),
            'ajaxUrl'        => admin_url('admin-ajax.php'),
            'nonce'          => wp_create_nonce('wcseo_history_nonce'),
        );

        wp_add_inline_script(
            'smartproductseo-product-generator',
            'window.SmartProductSEOData = ' . wp_json_encode($data) . ';',
            'before'
        );

        wp_add_inline_script('smartproductseo-product-generator', wcseo_get_product_generator_js());
    }
}

function wcseo_get_admin_css() {
    return '
        #wcseo-generator-box{margin:20px 0;padding:24px;background:linear-gradient(135deg,#fff7fc 0%,#ffffff 100%);border:1px solid #ffc5ec;border-radius:18px;box-shadow:0 8px 24px rgba(255,0,170,.08);}
        #wcseo-generator-box.wcseo-generator-dark{background:linear-gradient(135deg,#17111f 0%,#24142d 100%);border-color:#4d265d;box-shadow:0 8px 24px rgba(0,0,0,.18);color:#f8ecff;}
        #wcseo-generator-box.wcseo-generator-dark h2,#wcseo-generator-box.wcseo-generator-dark .wcseo-section-label{color:#fff;}
        #wcseo-generator-box.wcseo-generator-dark p{color:#d9c8e8;}
        .wcseo-header{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;margin-bottom:20px;}
        .wcseo-brand-row{display:flex;align-items:center;gap:12px;margin-bottom:8px;}
        .wcseo-logo{width:40px;height:40px;border-radius:10px;object-fit:cover;box-shadow:0 4px 12px rgba(255,0,170,.16);flex:0 0 auto;}
        .wcseo-header-left h2{margin:0;font-size:22px;font-weight:800;color:#1d2327;line-height:1.2;}
        .wcseo-header-left p{margin:0;color:#646970;font-size:13px;line-height:1.6;}
        .wcseo-badges{display:flex;flex-wrap:wrap;gap:8px;}
        .wcseo-badge{display:inline-flex;align-items:center;padding:5px 10px;border-radius:999px;background:#fff;border:1px solid #ffd3ef;color:#c4008b;font-size:11px;font-weight:700;}
        #wcseo-generator-box.wcseo-generator-dark .wcseo-badge{background:#25172f;border-color:#5b2b68;color:#ff7adf;}
        .wcseo-section-label{margin:16px 0 10px;font-size:11px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:#1d2327;}
        .wcseo-button-row{display:flex;flex-wrap:wrap;gap:10px;}
        #wcseo-generator-box .button{display:inline-flex !important;align-items:center;gap:7px;border-radius:10px !important;min-height:40px;padding:8px 16px !important;font-weight:700;transition:all .18s ease;border-width:1px;}
        #wcseo-generator-box .button:hover{transform:translateY(-1px);}
        #wcseo-generator-box .dashicons{font-size:17px;width:17px;height:17px;line-height:17px;}
        .wcseo-primary-btn{background:linear-gradient(135deg,#2271b1 0%,#135e96 100%) !important;border-color:#135e96 !important;color:#fff !important;}
        .wcseo-secondary-btn{background:#fff !important;border-color:#2271b1 !important;color:#2271b1 !important;}
        .wcseo-main-btn{background:linear-gradient(135deg,#ff00b8 0%,#7b2cff 100%) !important;border-color:#d0009b !important;color:#fff !important;box-shadow:0 8px 18px rgba(255,0,180,.22);}
        .wcseo-restore-btn{background:#fff !important;border-color:#d63638 !important;color:#b32d2e !important;}
        .wcseo-main-btn:hover{box-shadow:0 10px 24px rgba(255,0,180,.34);}
        .wcseo-main-btn:disabled,.wcseo-restore-btn:disabled{opacity:.55;cursor:not-allowed;transform:none !important;}
        .wcseo-help-text{margin:14px 0 0;font-size:12px;line-height:1.6;color:#555;}
        #wcseo-success-toast{display:none;position:fixed;top:45px;right:25px;z-index:999999;background:#18a558;color:#fff;padding:14px 18px;border-radius:12px;box-shadow:0 10px 28px rgba(0,0,0,.18);font-size:14px;font-weight:700;}
        #wcseo-success-toast.wcseo-toast-error{background:#d63638;}
        .wcseo-dashboard-wrap{margin-top:20px;}
        .wcseo-dashboard{max-width:1200px;}
        .wcseo-dashboard-card{background:#fff;border:1px solid #f1d4e8;border-radius:18px;padding:28px;margin-bottom:24px;box-shadow:0 8px 24px rgba(255,0,170,.06);}
        .wcseo-dashboard-header{display:flex;align-items:center;gap:18px;margin-bottom:18px;}
        .wcseo-dashboard-logo{width:58px;height:58px;border-radius:16px;box-shadow:0 6px 18px rgba(255,0,170,.18);}
        .wcseo-dashboard-title{margin:0;font-size:30px;font-weight:800;color:#1d2327;}
        .wcseo-dashboard-subtitle{margin-top:6px;color:#666;font-size:15px;}
        .wcseo-section-title{font-size:22px;margin:0 0 18px;font-weight:800;}
        .wcseo-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:20px;}
        .wcseo-feature-card,.wcseo-preset-card{background:#fff;border:1px solid #f3d8ea;border-radius:16px;padding:22px;}
        .wcseo-feature-card h3,.wcseo-preset-card h3{margin-top:0;margin-bottom:10px;font-size:18px;}
        .wcseo-feature-card p,.wcseo-preset-card p{margin:0;color:#555;line-height:1.7;}
        .wcseo-settings-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;}
        .wcseo-toggle-row{display:flex;align-items:center;justify-content:space-between;gap:16px;border:1px solid #f3d8ea;border-radius:14px;padding:16px;background:#fff;}
        .wcseo-toggle-row strong{display:block;margin-bottom:4px;}
        .wcseo-toggle-row span{color:#666;font-size:13px;}
        .wcseo-toggle{position:relative;width:48px;height:26px;flex:0 0 auto;}
        .wcseo-toggle input{opacity:0;width:0;height:0;}
        .wcseo-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background:#ddd;transition:.2s;border-radius:999px;}
        .wcseo-slider:before{position:absolute;content:"";height:20px;width:20px;left:3px;bottom:3px;background:white;transition:.2s;border-radius:50%;box-shadow:0 2px 6px rgba(0,0,0,.18);}
        .wcseo-toggle input:checked + .wcseo-slider{background:linear-gradient(135deg,#ff00b8,#7b2cff);}
        .wcseo-toggle input:checked + .wcseo-slider:before{transform:translateX(22px);}
        .wcseo-save-button{margin-top:20px !important;background:linear-gradient(135deg,#ff00b8,#7b2cff) !important;border-color:#d0009b !important;color:#fff !important;border-radius:10px !important;padding:8px 18px !important;font-weight:700 !important;}
        .wcseo-pro-list li,.wcseo-logic-list li,.wcseo-quick-list li{margin-bottom:10px;}
        .wcseo-footer{text-align:center;color:#666;font-size:13px;margin:30px 0;}
        /* v1.6.7 dashboard visual polish only */
        .wcseo-dashboard-wrap{position:relative;padding:18px 18px 28px;border-radius:28px;background:radial-gradient(circle at 8% 4%,rgba(255,0,184,.13),transparent 24%),radial-gradient(circle at 92% 12%,rgba(123,44,255,.13),transparent 25%),linear-gradient(135deg,#fff7fd 0%,#f8f4ff 48%,#f3fbff 100%);overflow:hidden;}
        .wcseo-dashboard-wrap:before,.wcseo-dashboard-wrap:after{content:"";position:absolute;border-radius:50%;filter:blur(2px);pointer-events:none;animation:wcseoFloatGlow 8s ease-in-out infinite;}
        .wcseo-dashboard-wrap:before{width:180px;height:180px;right:3%;top:110px;background:rgba(255,0,184,.08);}
        .wcseo-dashboard-wrap:after{width:140px;height:140px;left:2%;top:520px;background:rgba(42,197,255,.08);animation-delay:-4s;}
        .wcseo-dashboard{position:relative;z-index:1;}
        .wcseo-dashboard-card{position:relative;overflow:hidden;border:1px solid rgba(255,0,184,.18);box-shadow:0 14px 34px rgba(78,24,105,.09);transition:transform .25s ease,box-shadow .25s ease,border-color .25s ease;background:linear-gradient(145deg,rgba(255,255,255,.98),rgba(255,250,254,.96));}
        .wcseo-dashboard-card:hover{transform:translateY(-2px);box-shadow:0 18px 42px rgba(126,39,145,.14);border-color:rgba(255,0,184,.32);}
        .wcseo-dashboard-card:before{content:"";position:absolute;left:0;top:0;width:100%;height:5px;background:linear-gradient(90deg,#ff00b8,#7b2cff,#24c7ff,#42d98a,#ffb300,#ff00b8);background-size:220% 100%;animation:wcseoRainbowBar 7s linear infinite;}
        .wcseo-dashboard-card:first-child{background:radial-gradient(circle at 90% 20%,rgba(36,199,255,.11),transparent 24%),radial-gradient(circle at 72% 100%,rgba(255,0,184,.12),transparent 30%),linear-gradient(135deg,#fff 0%,#fff7fd 52%,#f5f1ff 100%);}
        .wcseo-dashboard-logo{animation:wcseoLogoPulse 3.2s ease-in-out infinite;}
        .wcseo-dashboard-title{background:linear-gradient(90deg,#17171b,#7b2cff 45%,#ff00b8);-webkit-background-clip:text;background-clip:text;color:transparent;}
        .wcseo-section-title{display:flex;align-items:center;gap:10px;}
        .wcseo-dashboard-card:nth-of-type(2) .wcseo-section-title:before{content:"🚀";}
        .wcseo-dashboard-card:nth-of-type(3) .wcseo-section-title:before{content:"✨";}
        .wcseo-dashboard-card:nth-of-type(4) .wcseo-section-title:before{content:"⚙️";}
        .wcseo-dashboard-card:nth-of-type(5) .wcseo-section-title:before{content:"🎯";}
        .wcseo-dashboard-card:nth-of-type(6) .wcseo-section-title:before{content:"🧠";}
        .wcseo-dashboard-card:nth-of-type(7) .wcseo-section-title:before{content:"💎";}
        .wcseo-dashboard-card:nth-of-type(8) .wcseo-section-title:before{content:"💬";}
        .wcseo-feature-card,.wcseo-preset-card,.wcseo-toggle-row{position:relative;overflow:hidden;transition:transform .22s ease,box-shadow .22s ease,border-color .22s ease;background:linear-gradient(145deg,#fff,#fff9fd);}
        .wcseo-feature-card:hover,.wcseo-preset-card:hover,.wcseo-toggle-row:hover{transform:translateY(-3px);box-shadow:0 12px 26px rgba(123,44,255,.11);border-color:rgba(255,0,184,.34);}
        .wcseo-feature-card:before,.wcseo-preset-card:before{display:block;font-size:26px;line-height:1;margin-bottom:12px;filter:drop-shadow(0 3px 5px rgba(123,44,255,.15));}
        .wcseo-feature-card:nth-child(1):before{content:"🏷️"}.wcseo-feature-card:nth-child(2):before{content:"🔎"}.wcseo-feature-card:nth-child(3):before{content:"✍️"}.wcseo-feature-card:nth-child(4):before{content:"↩️"}
        .wcseo-preset-card:nth-child(4n+1):before{content:"✨"}.wcseo-preset-card:nth-child(4n+2):before{content:"🎯"}.wcseo-preset-card:nth-child(4n+3):before{content:"🛍️"}.wcseo-preset-card:nth-child(4n):before{content:"💖"}
        .wcseo-feature-card:nth-child(4n+1),.wcseo-preset-card:nth-child(4n+1){border-top:4px solid #ff00b8}.wcseo-feature-card:nth-child(4n+2),.wcseo-preset-card:nth-child(4n+2){border-top:4px solid #7b2cff}.wcseo-feature-card:nth-child(4n+3),.wcseo-preset-card:nth-child(4n+3){border-top:4px solid #24c7ff}.wcseo-feature-card:nth-child(4n),.wcseo-preset-card:nth-child(4n){border-top:4px solid #42d98a}
        .wcseo-toggle-row:nth-child(3n+1){border-left:4px solid #ff00b8}.wcseo-toggle-row:nth-child(3n+2){border-left:4px solid #7b2cff}.wcseo-toggle-row:nth-child(3n){border-left:4px solid #24c7ff}
        .wcseo-quick-list{counter-reset:wcseoStep;list-style:none;padding-left:0;display:grid;gap:10px;}
        .wcseo-quick-list li{counter-increment:wcseoStep;position:relative;margin:0;padding:11px 14px 11px 52px;border-radius:12px;background:linear-gradient(90deg,rgba(255,0,184,.07),rgba(123,44,255,.035));}
        .wcseo-quick-list li:before{content:counter(wcseoStep);position:absolute;left:12px;top:8px;width:28px;height:28px;display:grid;place-items:center;border-radius:50%;color:#fff;font-weight:800;background:linear-gradient(135deg,#ff00b8,#7b2cff);box-shadow:0 4px 10px rgba(123,44,255,.22);}
        .wcseo-logic-list,.wcseo-pro-list{list-style:none;padding-left:0;display:grid;gap:8px;}
        .wcseo-logic-list li,.wcseo-pro-list li{position:relative;margin:0;padding:9px 12px 9px 38px;border-radius:10px;background:rgba(123,44,255,.045);}
        .wcseo-logic-list li:before{content:"⚡";position:absolute;left:11px;top:8px}.wcseo-pro-list li:before{content:"💎";position:absolute;left:11px;top:8px}
        .wcseo-badge{box-shadow:0 4px 12px rgba(255,0,184,.08);}
        .wcseo-save-button{box-shadow:0 8px 20px rgba(255,0,184,.22) !important;transition:transform .2s ease,box-shadow .2s ease !important;}
        .wcseo-save-button:hover{transform:translateY(-2px);box-shadow:0 12px 26px rgba(123,44,255,.28) !important;}
        @keyframes wcseoRainbowBar{0%{background-position:0 0}100%{background-position:220% 0}}
        @keyframes wcseoLogoPulse{0%,100%{transform:translateY(0) scale(1);box-shadow:0 6px 18px rgba(255,0,170,.18)}50%{transform:translateY(-3px) scale(1.035);box-shadow:0 10px 26px rgba(123,44,255,.24)}}
        @keyframes wcseoFloatGlow{0%,100%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(0,18px,0) scale(1.08)}}
        @media (prefers-reduced-motion:reduce){.wcseo-dashboard-card,.wcseo-feature-card,.wcseo-preset-card,.wcseo-toggle-row,.wcseo-dashboard-logo,.wcseo-dashboard-card:before,.wcseo-dashboard-wrap:before,.wcseo-dashboard-wrap:after{animation:none !important;transition:none !important;transform:none !important;}}
        /* v1.6.8 product edit generator visual polish only */
        #wcseo-generator-box{position:relative;overflow:hidden;border:1px solid rgba(255,0,184,.28);background:radial-gradient(circle at 92% 12%,rgba(36,199,255,.13),transparent 24%),radial-gradient(circle at 70% 110%,rgba(255,0,184,.14),transparent 30%),linear-gradient(135deg,#fff 0%,#fff7fd 52%,#f5f1ff 100%);box-shadow:0 14px 34px rgba(78,24,105,.11);transition:transform .25s ease,box-shadow .25s ease,border-color .25s ease;}
        #wcseo-generator-box:hover{transform:translateY(-2px);box-shadow:0 18px 42px rgba(126,39,145,.16);border-color:rgba(255,0,184,.42);}
        #wcseo-generator-box:before{content:"";position:absolute;left:0;top:0;width:100%;height:5px;background:linear-gradient(90deg,#ff00b8,#7b2cff,#24c7ff,#42d98a,#ffb300,#ff00b8);background-size:220% 100%;animation:wcseoRainbowBar 7s linear infinite;z-index:2;}
        #wcseo-generator-box:after{content:"";position:absolute;width:145px;height:145px;right:-28px;bottom:-48px;border-radius:50%;background:rgba(123,44,255,.08);pointer-events:none;animation:wcseoFloatGlow 7s ease-in-out infinite;}
        #wcseo-generator-box .wcseo-header,#wcseo-generator-box .wcseo-section-label,#wcseo-generator-box .wcseo-button-row,#wcseo-generator-box .wcseo-help-text{position:relative;z-index:3;}
        #wcseo-generator-box .wcseo-logo{animation:wcseoLogoPulse 3.2s ease-in-out infinite;}
        #wcseo-generator-box .wcseo-header-left h2{background:linear-gradient(90deg,#17171b,#7b2cff 46%,#ff00b8);-webkit-background-clip:text;background-clip:text;color:transparent;}
        #wcseo-generator-box .wcseo-badge{background:linear-gradient(135deg,#fff,#fff7fd);border-color:rgba(255,0,184,.24);box-shadow:0 4px 12px rgba(255,0,184,.10);transition:transform .2s ease,box-shadow .2s ease;}
        #wcseo-generator-box .wcseo-badge:hover{transform:translateY(-2px);box-shadow:0 8px 18px rgba(123,44,255,.15);}
        #wcseo-generator-box .wcseo-badge:nth-child(1):before{content:"✨";margin-right:5px}#wcseo-generator-box .wcseo-badge:nth-child(2):before{content:"🛍️";margin-right:5px}#wcseo-generator-box .wcseo-badge:nth-child(3):before{content:"⚡";margin-right:5px}
        #wcseo-generator-box .wcseo-section-label{display:flex;align-items:center;gap:7px;margin-top:18px;padding-bottom:7px;border-bottom:1px dashed rgba(123,44,255,.18);}
        #wcseo-generator-box .wcseo-section-label:first-of-type:before{content:"✨"}#wcseo-generator-box .wcseo-section-label:nth-of-type(2):before{content:"⚡"}
        #wcseo-generator-box .button{position:relative;overflow:hidden;box-shadow:0 7px 16px rgba(38,35,115,.10);transition:transform .2s ease,box-shadow .2s ease,filter .2s ease !important;}
        #wcseo-generator-box .button:hover{transform:translateY(-3px) scale(1.015);filter:saturate(1.08);box-shadow:0 12px 24px rgba(123,44,255,.18);}
        #wcseo-generator-box .wcseo-primary-btn:nth-child(1){background:linear-gradient(135deg,#1d8cff,#2754d7) !important;border-color:#1d74dd !important;}
        #wcseo-generator-box .wcseo-primary-btn:nth-child(2){background:linear-gradient(135deg,#7b2cff,#b42cff) !important;border-color:#8b2bd2 !important;}
        #wcseo-generator-box .wcseo-primary-btn:nth-child(3){background:linear-gradient(135deg,#00b7d6,#1b8fdb) !important;border-color:#128bb9 !important;}
        #wcseo-generator-box .wcseo-secondary-btn{background:linear-gradient(135deg,#fff,#f4fbff) !important;border-color:#24a8ff !important;color:#1478b8 !important;}
        #wcseo-generator-box .wcseo-main-btn{animation:wcseoActionPulse 2.6s ease-in-out infinite;}
        #wcseo-generator-box .wcseo-restore-btn{background:linear-gradient(135deg,#fff,#fff6f6) !important;box-shadow:0 7px 16px rgba(214,54,56,.08);}
        #wcseo-generator-box .wcseo-help-text{margin-top:16px;padding:11px 14px 11px 40px;border-radius:12px;background:linear-gradient(90deg,rgba(255,0,184,.07),rgba(123,44,255,.04));border:1px solid rgba(255,0,184,.10);}
        #wcseo-generator-box .wcseo-help-text:before{content:"💡";position:absolute;left:13px;top:10px;font-size:18px;}
        @keyframes wcseoActionPulse{0%,100%{box-shadow:0 8px 18px rgba(255,0,180,.22)}50%{box-shadow:0 10px 28px rgba(123,44,255,.36),0 0 0 5px rgba(255,0,184,.07)}}
        @media (prefers-reduced-motion:reduce){#wcseo-generator-box,#wcseo-generator-box:before,#wcseo-generator-box:after,#wcseo-generator-box .wcseo-logo,#wcseo-generator-box .wcseo-main-btn,#wcseo-generator-box .button,#wcseo-generator-box .wcseo-badge{animation:none !important;transition:none !important;transform:none !important;}}
        .wcseo-dark-mode .wcseo-dashboard-card,.wcseo-dark-mode .wcseo-feature-card,.wcseo-dark-mode .wcseo-preset-card,.wcseo-dark-mode .wcseo-toggle-row{background:#16131f;border-color:#3f2a4e;color:#f7e9ff;}
        .wcseo-dark-mode .wcseo-dashboard-title,.wcseo-dark-mode .wcseo-section-title,.wcseo-dark-mode h3{color:#fff;}
        .wcseo-dark-mode p,.wcseo-dark-mode span,.wcseo-dark-mode li,.wcseo-dark-mode .wcseo-dashboard-subtitle{color:#d9c8e8;}
        .wcseo-dark-mode .wcseo-badge{background:#25172f;border-color:#5b2b68;color:#ff7adf;}
    ';
}

function wcseo_get_product_generator_js() {
    return <<<'JS'
jQuery(document).ready(function($){
    const wcseoSettings = window.SmartProductSEOData || {};
    const postId = wcseoSettings.postId || 0;
    const logoUrl = wcseoSettings.logoUrl || '';
    const darkClass = wcseoSettings.darkMode ? ' wcseo-generator-dark' : '';
    const oneClickDisabled = wcseoSettings.oneClick ? '' : 'disabled';
    const restoreDisabled = wcseoSettings.history ? '' : 'disabled';

    const generatorBox = `
        <div id="wcseo-generator-box" class="${darkClass}">
            <div class="wcseo-header">
                <div class="wcseo-header-left">
                    <div class="wcseo-brand-row">
                        <img class="wcseo-logo" src="${logoUrl}" alt="SmartProductSEO logo">
                        <h2>SmartProductSEO</h2>
                    </div>
                    <p>Create cleaner, search-intent-focused WooCommerce SEO titles, focus keyphrases, and meta descriptions for this product.</p>
                </div>
                <div class="wcseo-badges">
                    <span class="wcseo-badge">Yoast Compatible</span>
                    <span class="wcseo-badge">WooCommerce Ready</span>
                    <span class="wcseo-badge">v1.6.9</span>
                </div>
            </div>

            <div class="wcseo-section-label">Generate SEO Fields</div>

            <div class="wcseo-button-row">
                <button type="button" class="button wcseo-primary-btn" id="wcseo-generate-focuskw"><span class="dashicons dashicons-search"></span>Generate Focus Keyphrase</button>
                <button type="button" class="button wcseo-primary-btn" id="wcseo-generate-title"><span class="dashicons dashicons-edit"></span>Generate SEO Title</button>
                <button type="button" class="button wcseo-primary-btn" id="wcseo-generate-meta-title"><span class="dashicons dashicons-media-text"></span>Generate Meta From Title</button>
                <button type="button" class="button wcseo-secondary-btn" id="wcseo-generate-meta-desc"><span class="dashicons dashicons-text-page"></span>Generate Meta From Short Description</button>
            </div>

            <div class="wcseo-section-label">Quick Actions</div>

            <div class="wcseo-button-row">
                <button type="button" class="button wcseo-main-btn" id="wcseo-generate-all" ${oneClickDisabled}><span class="dashicons dashicons-lightbulb"></span>Generate All 3</button>
                <button type="button" class="button wcseo-restore-btn" id="wcseo-restore-last" ${restoreDisabled}><span class="dashicons dashicons-undo"></span>Restore Previous SEO</button>
            </div>

            <p class="wcseo-help-text">
                Generate search-intent-focused SEO metadata, review the Yoast fields, then click Update to save.
                ${wcseoSettings.oneClick ? '' : '<br><strong>Generate All 3 is disabled in SmartProductSEO settings.</strong>'}
                ${wcseoSettings.history ? '' : '<br><strong>Restore Previous SEO is disabled because History / Undo is turned off.</strong>'}
            </p>
        </div>
        <div id="wcseo-success-toast"></div>
    `;

    const yoastBox = $('#wpseo_meta');
    const productDataBox = $('#woocommerce-product-data');
    const titleBox = $('#titlediv');

    if (!$('#wcseo-generator-box').length) {
        if (yoastBox.length) {
            yoastBox.before(generatorBox);
        } else if (productDataBox.length) {
            productDataBox.before(generatorBox);
        } else if (titleBox.length) {
            titleBox.after(generatorBox);
        }
    }

    function removeDuplicateYoastButtonBox(){
        const yoast = document.querySelector('#wpseo_meta');
        if(!yoast){ return; }

        const buttons = Array.from(yoast.querySelectorAll('button, .button, input[type="button"]'));

        buttons.forEach(function(button){
            const text = (button.textContent || button.value || '').replace(/\s+/g, ' ').trim();

            const isDuplicateButton =
                text === 'Generate Focus Keyphrase' ||
                text === 'Generate SEO Title' ||
                text === 'Generate Meta Description' ||
                text === 'Generate Meta From Title' ||
                text === 'Generate Meta From Short Description';

            if(!isDuplicateButton){ return; }

            let box = button.closest('#wcseo-generator-box');

            if(!box){
                box = button.closest('.wcseo-yoast-box, .wcseo-yoast-generator, .wcseo-generator-box, .wcseo-box, .inside > div, div');
            }

            if(box && box.id !== 'wpseo_meta' && box.id !== 'wcseo-generator-box'){
                box.remove();
            } else {
                button.remove();
            }
        });

        const yoastTextBlocks = Array.from(yoast.querySelectorAll('p, div, span'));
        yoastTextBlocks.forEach(function(el){
            const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
            if(text === 'Generates SEO fields from your product title, short description, and product content.'){
                const parent = el.closest('.wcseo-yoast-box, .wcseo-yoast-generator, .wcseo-generator-box, .wcseo-box, .inside > div, div');
                if(parent && parent.id !== 'wpseo_meta' && parent.id !== 'wcseo-generator-box'){
                    parent.remove();
                } else {
                    el.remove();
                }
            }
        });
    }

    removeDuplicateYoastButtonBox();
    setTimeout(removeDuplicateYoastButtonBox, 500);
    setTimeout(removeDuplicateYoastButtonBox, 1500);

    function showSuccess(message, isError = false){
        if(!wcseoSettings.notifications){return;}
        const toast = $('#wcseo-success-toast');
        toast.stop(true,true).toggleClass('wcseo-toast-error', !!isError).html((isError ? '!' : '✓') + ' ' + message).fadeIn(180);
        setTimeout(function(){toast.fadeOut(350);},2400);
    }

    function cleanText(text){
        return String(text || '').replace(/<[^>]*>/g,'').replace(/\[[^\]]*\]/g,'').replace(/&nbsp;/g,' ').replace(/&amp;/g,'&').replace(/\s+/g,' ').trim();
    }

    function getProductTitle(){
        return cleanText($('#title').val() || $('input[name="post_title"]').val() || '');
    }

    function trimNice(text,maxLength,addPeriod=false){
        text = cleanText(text);

        if(!wcseoSettings.smartCleanup){
            if(text.length > maxLength){text = text.substring(0, maxLength).trim();}
            if(addPeriod && !/[.!?]$/.test(text)){text += '.';}
            return text;
        }

        if(text.length <= maxLength){
            if(!addPeriod){text = text.replace(/[.,\-:;|]+$/g,'').trim();}
            if(addPeriod && !/[.!?]$/.test(text)){text += '.';}
            return text;
        }

        text = text.substring(0,maxLength - 8).trim();
        text = text.replace(/\s+\S*$/,'');
        text = text.replace(/\b(with|and|for|to|in|on|at|by|of|a|an|the|from|that|while|when|because)$/i,'');
        text = text.replace(/[.,\-:;|]+$/g,'').trim();

        if(addPeriod && !/[.!?]$/.test(text)){text += '.';}
        return text;
    }

    function ensurePeriod(text){
        text = cleanText(text);

        if(wcseoSettings.smartCleanup){
            text = text.replace(/\b(with|for|and|or|to|a|an|the|in|on|of|by|from|that|while|when|because)$/i,'');
            text = text.replace(/[,\-:;|\s]+$/g,'').trim();
        }

        if(!/[.!?]$/.test(text)){text += '.';}
        return text;
    }

    function nativeSet(el,value){
        if(!el) return false;
        const tag = el.tagName ? el.tagName.toLowerCase() : '';

        if(tag === 'input'){
            const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;
            setter.call(el,value);
        } else if(tag === 'textarea'){
            const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,'value').set;
            setter.call(el,value);
        } else {
            el.value = value;
            el.textContent = value;
        }

        el.dispatchEvent(new Event('input',{ bubbles:true }));
        el.dispatchEvent(new Event('change',{ bubbles:true }));
        el.dispatchEvent(new KeyboardEvent('keyup',{ bubbles:true }));
        el.dispatchEvent(new KeyboardEvent('keydown',{ bubbles:true }));
        el.dispatchEvent(new KeyboardEvent('keypress',{ bubbles:true }));

        return true;
    }

    function setBySelectors(selectors,value){
        let updated = false;
        selectors.forEach(function(selector){
            document.querySelectorAll(selector).forEach(function(el){
                if(nativeSet(el,value)){updated = true;}
            });
        });
        return updated;
    }

    function getCurrentValue(selectors){
        let value = '';
        selectors.some(function(selector){
            const el = document.querySelector(selector);
            if(el){
                value = el.value || el.textContent || '';
                return true;
            }
            return false;
        });
        return cleanText(value);
    }

    function getCurrentYoastTitle(){
        return getCurrentValue(['#yoast_wpseo_title','input[name="yoast_wpseo_title"]','input[name="_yoast_wpseo_title"]','#yoast-google-preview-title-metabox','input[aria-label*="SEO title"]']);
    }

    function getCurrentYoastMeta(){
        return getCurrentValue(['#yoast_wpseo_metadesc','textarea[name="yoast_wpseo_metadesc"]','textarea[name="_yoast_wpseo_metadesc"]','#yoast-google-preview-description-metabox','textarea[aria-label*="Meta description"]']);
    }

    function getCurrentYoastFocus(){
        return getCurrentValue(['#yoast_wpseo_focuskw','#focus-keyword-input-metabox','#yoast_wpseo_focuskw_text_input','input[name="yoast_wpseo_focuskw"]','input[name="_yoast_wpseo_focuskw"]']);
    }

    function saveHistorySnapshot(){
        if(!wcseoSettings.history){return $.Deferred().resolve().promise();}
        return $.post(wcseoSettings.ajaxUrl, {
            action: 'wcseo_save_history_snapshot',
            nonce: wcseoSettings.nonce,
            post_id: postId,
            seo_title: getCurrentYoastTitle(),
            seo_meta: getCurrentYoastMeta(),
            seo_focus: getCurrentYoastFocus()
        });
    }

    function restoreHistorySnapshot(){
        if(!wcseoSettings.history){
            showSuccess('History restore is disabled in settings.', true);
            return;
        }

        $.post(wcseoSettings.ajaxUrl, {
            action: 'wcseo_restore_history_snapshot',
            nonce: wcseoSettings.nonce,
            post_id: postId
        }).done(function(response){
            if(!response || !response.success || !response.data || !response.data.snapshot){
                const msg = response && response.data && response.data.message ? response.data.message : 'No previous SEO snapshot found.';
                showSuccess(msg, true);
                return;
            }

            const snapshot = response.data.snapshot;
            setYoastTitle(snapshot.title || '');
            setYoastMeta(snapshot.meta || '');
            setYoastFocus(snapshot.focus || '');
            forceYoastRefresh();
            showSuccess('Previous SEO fields restored. Click Update to save.');
        }).fail(function(){
            showSuccess('Restore failed. Please try again.', true);
        });
    }

    function setYoastTitle(value){
        const updated = setBySelectors([
            '#yoast_wpseo_title',
            'input[name="yoast_wpseo_title"]',
            'input[name="_yoast_wpseo_title"]',
            '#yoast-google-preview-title-metabox',
            'input[id*="title"][id*="metabox"]',
            'input[aria-label*="SEO title"]',
            'input[aria-label*="Title"]',
            'input[placeholder*="SEO title"]',
            'textarea[aria-label*="SEO title"]'
        ], value);

        const editableTitle = document.querySelector('[contenteditable="true"][aria-label*="SEO title"], [contenteditable="true"][aria-label*="Title"]');
        if(editableTitle){
            editableTitle.focus();
            editableTitle.textContent = value;
            editableTitle.dispatchEvent(new Event('input',{ bubbles:true }));
            editableTitle.dispatchEvent(new Event('change',{ bubbles:true }));
        }

        return updated;
    }

    function setYoastMeta(value){
        const updated = setBySelectors([
            '#yoast_wpseo_metadesc',
            'textarea[name="yoast_wpseo_metadesc"]',
            'textarea[name="_yoast_wpseo_metadesc"]',
            '#yoast-google-preview-description-metabox',
            'textarea[id*="description"][id*="metabox"]',
            'textarea[aria-label*="Meta description"]',
            'textarea[aria-label*="description"]',
            'textarea[placeholder*="Meta description"]',
            'textarea[placeholder*="description"]'
        ], value);

        const editableMeta = document.querySelector('[contenteditable="true"][aria-label*="Meta description"], [contenteditable="true"][aria-label*="description"]');
        if(editableMeta){
            editableMeta.focus();
            editableMeta.textContent = value;
            editableMeta.dispatchEvent(new Event('input',{ bubbles:true }));
            editableMeta.dispatchEvent(new Event('change',{ bubbles:true }));
        }

        return updated;
    }

    function setYoastFocus(value){
        return setBySelectors([
            '#yoast_wpseo_focuskw',
            '#focus-keyword-input-metabox',
            '#yoast_wpseo_focuskw_text_input',
            'input[name="yoast_wpseo_focuskw"]',
            'input[name="_yoast_wpseo_focuskw"]',
            'input[aria-label*="Focus keyphrase"]',
            'input[aria-label*="Focus keyword"]',
            'input[placeholder*="Focus keyphrase"]',
            'input[placeholder*="Focus keyword"]'
        ], value);
    }

    function forceYoastRefresh(){
        setTimeout(function(){
            $(document).trigger('yoast-seo-refresh');
            $(window).trigger('resize');
            if (window.YoastSEO && window.YoastSEO.app) {
                try {window.YoastSEO.app.refresh();} catch(e) {}
            }
        },100);
    }

    function detectCategory(title){
        const t = title.toLowerCase();
        if(!wcseoSettings.productPresets){return 'fashion';}
        if(/bikini|swimwear|swimsuit|one piece|one-piece|monokini|poolside|beachwear/.test(t)) return 'swimwear';
        if(/dress|mini dress|maxi dress|midi dress|bodycon|sundress|gown|slip dress|tube dress|corset dress/.test(t)) return 'dresses';
        if(/handbag|purse|tote|clutch|crossbody|shoulder bag|mini bag|bucket bag|satchel|hobo bag|wallet|bag/.test(t)) return 'handbags';
        if(/earring|earrings|necklace|bracelet|ring|jewelry|anklet|belly chain|body chain|waist chain|charm/.test(t)) return 'jewelry';
        if(/sandals|heels|shoes|slides|platforms|boots|wedges|flats|sneakers|pumps|mules|stilettos|flip flops/.test(t)) return 'shoes';
        if(/skincare|skin care|serum|moisturizer|cleanser|toner|face cream|eye cream|sunscreen|spf|exfoliant|mask|facial|body lotion|body oil/.test(t)) return 'skincare';
        if(/makeup|cosmetic|cosmetics|lipstick|lip gloss|foundation|concealer|blush|bronzer|highlighter|mascara|eyeliner|eyeshadow|brow|primer|setting spray/.test(t)) return 'cosmetics';
        if(/wig|wigs|lace front|hair extension|hair extensions|bundle|closure|frontal|human hair|synthetic hair/.test(t)) return 'wigs';
        if(/lashes|lash|eyelashes|false lashes|strip lashes|lash extension|mink lashes/.test(t)) return 'lashes';
        if(/home decor|decor|pillow|throw blanket|blanket|vase|wall art|lamp|rug|mirror|decorative|bedding|table decor/.test(t)) return 'home';
        if(/candle|candles|wax melt|room spray|diffuser|home fragrance/.test(t)) return 'candles';
        if(/activewear|gym|workout|athletic|yoga|fitness|sports bra|training|running/.test(t)) return 'activewear';
        if(/lingerie|babydoll|nightwear|sleepwear|bralette|panty|teddy|lace bra|intimates/.test(t)) return 'lingerie';
        if(/phone case|airpod|airpods|laptop sleeve|tablet case|ipad case|charger|charging cable|tech accessory|tech accessories|phone charm|screen protector/.test(t)) return 'tech';
        return 'fashion';
    }

    function getPresetPhrase(category){
        const phrases = {
            fashion: 'for everyday outfits, weekend plans, seasonal styling, and trend-focused looks',
            swimwear: 'for beach days, pool parties, resort trips, tropical getaways, and vacation-ready swim style',
            dresses: 'for vacations, brunch dates, party plans, weekend events, and feminine outfit moments',
            handbags: 'for everyday styling, travel days, polished outfits, city looks, and outfit finishing touches',
            jewelry: 'for layered styling, party outfits, special occasions, everyday shine, and statement accessorizing',
            shoes: 'for vacation outfits, casual styling, summer plans, polished looks, and easy outfit pairing',
            skincare: 'for daily routines, glowing skin goals, self-care moments, and beauty shelf essentials',
            cosmetics: 'for everyday makeup, soft glam, beauty routines, photo-ready looks, and polished finishes',
            wigs: 'for protective styling, glam installs, confidence, everyday wear, and easy hair changes',
            lashes: 'for soft glam, party makeup, date nights, photo-ready beauty looks, and eye-enhancing style',
            home: 'for cozy rooms, home styling, decorative refreshes, polished spaces, and everyday comfort',
            candles: 'for cozy nights, home fragrance, relaxing routines, warm room vibes, and thoughtful gifting',
            activewear: 'for workouts, errands, athleisure styling, everyday comfort, and movement-ready outfits',
            lingerie: 'for feminine styling, soft layering, confidence, romantic wardrobe moments, and delicate details',
            tech: 'for daily use, travel days, organized essentials, everyday tech styling, and practical protection'
        };
        return phrases[category] || phrases.fashion;
    }

    function getMetaOpening(){
        const openings = ['Shop the ','Discover the ','Style the ','Refresh your look with the ','Create a polished outfit with the '];
        return openings[Math.floor(Math.random() * openings.length)];
    }

    function generateFocusKeyphrase(skipSnapshot = false){
        const title = getProductTitle();
        if(!title){showSuccess('No product title found.', true);return '';}
        if(!skipSnapshot){saveHistorySnapshot();}
        setYoastFocus(title);
        forceYoastRefresh();
        return title;
    }

    function generateSeoTitle(skipSnapshot = false){
        const title = getProductTitle();
        if(!title){showSuccess('No product title found.', true);return '';}
        if(!skipSnapshot){saveHistorySnapshot();}
        const seoTitle = trimNice(title,65,false);
        setYoastTitle(seoTitle);
        forceYoastRefresh();
        return seoTitle;
    }

    function generateMetaFromTitle(skipSnapshot = false){
        const title = getProductTitle();
        if(!title){showSuccess('No product title found.', true);return '';}
        if(!skipSnapshot){saveHistorySnapshot();}

        const category = detectCategory(title);
        const phrase = getPresetPhrase(category);
        let meta;

        if(wcseoSettings.aiReady){
            meta = getMetaOpening() + title + ', a search-intent-friendly product choice made ' + phrase + '.';
        } else {
            meta = 'Shop the ' + title + ' for stylish everyday wear, vacations, special occasions, and trend-focused ecommerce looks.';
        }

        meta = trimNice(meta,155,true);
        meta = ensurePeriod(meta);

        setYoastMeta(meta);
        forceYoastRefresh();

        return meta;
    }

    function generateMetaFromDescription(skipSnapshot = false){
        const shortDesc = $('#excerpt').val();
        const mainDesc = $('#content').val();
        let content = shortDesc && shortDesc.length > 40 ? shortDesc : mainDesc;

        content = cleanText(content);

        if(!content){showSuccess('No product description found.', true);return '';}
        if(!skipSnapshot){saveHistorySnapshot();}

        let meta;

        if(wcseoSettings.aiReady){
            const title = getProductTitle();
            const category = detectCategory(title);
            const phrase = getPresetPhrase(category);
            meta = title + ' gives shoppers a clear, search-friendly product match made ' + phrase + '.';
        } else {
            meta = content;
        }

        meta = trimNice(meta,155,true);
        meta = ensurePeriod(meta);

        setYoastMeta(meta);
        forceYoastRefresh();

        return meta;
    }

    $(document).on('click','#wcseo-generate-focuskw',function(){
        generateFocusKeyphrase();
        showSuccess('Focus keyphrase generated successfully.');
    });

    $(document).on('click','#wcseo-generate-title',function(){
        generateSeoTitle();
        showSuccess('SEO title generated successfully.');
    });

    $(document).on('click','#wcseo-generate-meta-title',function(){
        generateMetaFromTitle();
        showSuccess('Meta description generated from title.');
    });

    $(document).on('click','#wcseo-generate-meta-desc',function(){
        generateMetaFromDescription();
        showSuccess('Meta description generated from short description.');
    });

    $(document).on('click','#wcseo-generate-all',function(){
        if(!wcseoSettings.oneClick){
            showSuccess('Generate All 3 is disabled in settings.', true);
            return;
        }

        saveHistorySnapshot().always(function(){
            generateFocusKeyphrase(true);
            generateSeoTitle(true);
            generateMetaFromTitle(true);
            showSuccess('Focus keyphrase, SEO title, and meta description generated.');
        });
    });

    $(document).on('click','#wcseo-restore-last',function(){
        restoreHistorySnapshot();
    });
});
JS;
}

add_action('admin_menu', 'wcseo_add_admin_menu');
add_action('admin_init', 'wcseo_register_dashboard_settings');

function wcseo_register_dashboard_settings() {
    $settings = array(
        'wcseo_enable_dark_mode' => 0,
        'wcseo_show_notifications' => 1,
        'wcseo_smart_title_cleanup' => 1,
        'wcseo_product_type_presets' => 1,
        'wcseo_ai_ready_wording' => 1,
        'wcseo_one_click_regenerate' => 1,
        'wcseo_history_snapshots' => 1,
    );

    foreach ($settings as $option_name => $default_value) {
        register_setting(
            'wcseo_settings_group',
            $option_name,
            array(
                'type'              => 'boolean',
                'sanitize_callback' => 'wcseo_sanitize_checkbox',
                'default'           => absint($default_value),
            )
        );
    }
}

function wcseo_add_admin_menu() {
    add_menu_page(
        'SmartProductSEO',
        'Product SEO',
        'manage_options',
        'smartproductseo-generator',
        'wcseo_dashboard_page',
        'dashicons-chart-line',
        56
    );
}

function wcseo_dashboard_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $logo = plugin_dir_url(__FILE__) . 'assets/logo-header-40.png';
    $dark_mode = get_option('wcseo_enable_dark_mode');
    ?>

    <div class="wrap wcseo-dashboard-wrap <?php echo $dark_mode ? 'wcseo-dark-mode' : ''; ?>">
        <div class="wcseo-dashboard">

            <div class="wcseo-dashboard-card">
                <div class="wcseo-dashboard-header">
                    <img src="<?php echo esc_url($logo); ?>" class="wcseo-dashboard-logo" alt="SmartProductSEO">

                    <div>
                        <h1 class="wcseo-dashboard-title">SmartProductSEO</h1>
                        <div class="wcseo-dashboard-subtitle">Search-intent SEO metadata for WooCommerce products.</div>

                        <div class="wcseo-badges">
                            <span class="wcseo-badge">Yoast Compatible</span>
                            <span class="wcseo-badge">WooCommerce Ready</span>
                            <span class="wcseo-badge">Version <?php echo esc_html(WCSEO_VERSION); ?></span>
                        </div>
                    </div>
                </div>

                <p>
                    SmartProductSEO helps WooCommerce store owners create cleaner SEO titles, focus keyphrases, and meta descriptions from product titles and descriptions. It is built to support search intent, ecommerce product discovery, and faster Yoast-compatible product optimization while keeping the final review and save process in your hands.
                </p>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">Quick Start Guide</h2>

                <ol class="wcseo-quick-list">
                    <li>Edit any WooCommerce product.</li>
                    <li>Find the SmartProductSEO box above the Yoast SEO section.</li>
                    <li>Click Generate Focus Keyphrase, Generate SEO Title, Generate Meta Description, or Generate All 3.</li>
                    <li>Review the generated SEO fields inside Yoast SEO.</li>
                    <li>Use Restore Previous SEO if you want to undo the latest generated change.</li>
                    <li>Click Update to save the final product SEO fields.</li>
                </ol>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">Current Features</h2>

                <div class="wcseo-grid">
                    <div class="wcseo-feature-card">
                        <h3>SEO Title Generator</h3>
                        <p>Generate cleaner WooCommerce SEO titles using smart formatting, title cleanup, and search-intent-focused wording.</p>
                    </div>

                    <div class="wcseo-feature-card">
                        <h3>Focus Keyphrase Generator</h3>
                        <p>Create Yoast-compatible focus keyphrases directly from the product title for faster product optimization.</p>
                    </div>

                    <div class="wcseo-feature-card">
                        <h3>Meta Description Generator</h3>
                        <p>Generate polished meta descriptions from product titles or WooCommerce descriptions using ecommerce-friendly language.</p>
                    </div>

                    <div class="wcseo-feature-card">
                        <h3>Undo / Restore Support</h3>
                        <p>Restore the previous SEO title, focus keyphrase, and meta description before saving the product update.</p>
                    </div>
                </div>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">Settings</h2>

                <form method="post" action="options.php">
                    <?php settings_fields('wcseo_settings_group'); ?>

                    <div class="wcseo-settings-grid">

                        <?php
                        $settings = array(
                            'wcseo_enable_dark_mode' => array(
                                'title' => 'Dark Mode Admin Styling',
                                'desc'  => 'Switch this dashboard and product generator into a darker premium admin view.',
                            ),
                            'wcseo_show_notifications' => array(
                                'title' => 'Floating Success Notifications',
                                'desc'  => 'Show success messages after generating or restoring SEO fields.',
                            ),
                            'wcseo_smart_title_cleanup' => array(
                                'title' => 'Smart Title Cleanup',
                                'desc'  => 'Trim long titles and prevent awkward punctuation endings.',
                            ),
                            'wcseo_product_type_presets' => array(
                                'title' => 'Product Type Presets',
                                'desc'  => 'Use tailored SEO wording structures by WooCommerce product type.',
                            ),
                            'wcseo_ai_ready_wording' => array(
                                'title' => 'AI-Ready Wording',
                                'desc'  => 'Use natural wording designed for search intent, Google snippets, and AI assistant discovery.',
                            ),
                            'wcseo_one_click_regenerate' => array(
                                'title' => 'One-Click Generate All 3',
                                'desc'  => 'Enable or disable the Generate All 3 quick action button.',
                            ),
                            'wcseo_history_snapshots' => array(
                                'title' => 'History / Undo Restore',
                                'desc'  => 'Save recent SEO field snapshots so users can restore the previous SEO values before saving.',
                            ),
                        );

                        foreach ($settings as $option_name => $setting) :
                        ?>
                            <label class="wcseo-toggle-row">
                                <span>
                                    <strong><?php echo esc_html($setting['title']); ?></strong>
                                    <span><?php echo esc_html($setting['desc']); ?></span>
                                </span>
                                <span class="wcseo-toggle">
                                    <input type="checkbox" name="<?php echo esc_attr($option_name); ?>" value="1" <?php checked(1, get_option($option_name), true); ?>>
                                    <span class="wcseo-slider"></span>
                                </span>
                            </label>
                        <?php endforeach; ?>

                    </div>

                    <?php submit_button('Save Settings', 'primary wcseo-save-button'); ?>
                </form>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">All Product Type Presets</h2>
                <p>Tailored search-intent wording structures for different WooCommerce product categories.</p>

                <div class="wcseo-grid">
                    <?php
                    $presets = array(
                        'Fashion', 'Swimwear', 'Dresses', 'Handbags',
                        'Jewelry', 'Shoes', 'Beauty', 'Skincare',
                        'Wigs', 'Lashes', 'Cosmetics', 'Home Decor',
                        'Candles', 'Tech Accessories', 'Activewear', 'Lingerie'
                    );

                    foreach ($presets as $preset) :
                    ?>
                        <div class="wcseo-preset-card">
                            <h3><?php echo esc_html($preset); ?></h3>
                            <p>SEO wording support for <?php echo esc_html(strtolower($preset)); ?> products, buyer intent, and ecommerce search discovery.</p>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">SEO Logic</h2>

                <ul class="wcseo-logic-list">
                    <li>Rotating SEO sentence structures to reduce repetitive metadata.</li>
                    <li>Smart product type detection for more relevant wording.</li>
                    <li>Clean SEO title trimming for better Yoast-friendly lengths.</li>
                    <li>Meta description generation from product titles or short descriptions.</li>
                    <li>Yoast-compatible field targeting and instant refresh support.</li>
                    <li>Search-intent-focused phrasing designed for natural-language product discovery.</li>
                    <li>History snapshots before generated values overwrite existing fields.</li>
                    <li>Restore Previous SEO button for safer manual optimization.</li>
                    <li>Settings sanitization for safer stored admin options.</li>
                </ul>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">Future Pro Version Features</h2>

                <ul class="wcseo-pro-list">
                    <li>Bulk SEO generation</li>
                    <li>Category-wide SEO generation</li>
                    <li>Generate only missing SEO fields</li>
                    <li>AI-generated SEO descriptions</li>
                    <li>Export/import templates</li>
                    <li>Internal linking suggestions</li>
                    <li>Schema recommendations</li>
                    <li>Advanced restore and revision history tools</li>
                </ul>
            </div>

            <div class="wcseo-dashboard-card">
                <h2 class="wcseo-section-title">Support / Documentation</h2>

                <p>Need help, have a feature request, or want to report an issue?</p>

                <p>
                    Email support:
                    <a href="mailto:jolizzieseo@gmail.com">jolizzieseo@gmail.com</a>
                </p>

                <p>
                    Website:
                    <a href="https://smartproductseo.com/" target="_blank" rel="noopener noreferrer">https://smartproductseo.com/</a>
                </p>
            </div>

            <div class="wcseo-footer">
                <strong>SmartProductSEO v<?php echo esc_html(WCSEO_VERSION); ?></strong><br>
                Built for WooCommerce product SEO and Yoast SEO.
            </div>

        </div>
    </div>

    <?php
}