<?php
defined('ABSPATH') || exit;
function aiomatic_pages_panel()
{
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);

    if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) {
        echo '<h1>' . esc_html__("You must add an AI service API Key into the plugin's 'Settings' -> 'API Keys' tab before you can use this feature!", 'aiomatic-automatic-ai-content-writer') . '</h1>';
        return;
    }
    $mode     = isset($_GET['mode']) ? sanitize_key(wp_unslash($_GET['mode'])) : 'single';
    $renderer = isset($_GET['renderer']) ? sanitize_key(wp_unslash($_GET['renderer'])) : 'gutenberg';

    if (!in_array($mode, array('single', 'funnel'), true)) {
        $mode = 'single';
    }

    if (!in_array($renderer, array('gutenberg', 'elementor'), true)) {
        $renderer = 'gutenberg';
    }

    $settings = get_option('aiomatic_super_pages_settings', array());
    $available_image_tools = function_exists('aiomatic_super_pages_get_available_image_tools')
        ? aiomatic_super_pages_get_available_image_tools()
        : array('royalty_free_image_search');
    $default_image_source = function_exists('aiomatic_super_pages_get_default_image_source')
        ? aiomatic_super_pages_get_default_image_source($available_image_tools)
        : 'royalty_free';

    $defaults = array(
        'default_status'       => 'draft',
        'default_type'         => 'page',
        'default_renderer'     => 'gutenberg',
        'include_images'       => $default_image_source,
        'research_enabled'     => 'on',
        'url_parsing_enabled'  => 'on',
        'default_language'     => 'English',
        'default_page_count'   => 3,
        'content_format'     => 'auto',
        'goal'               => 'auto',
        'depth'              => 'standard',
    );

    $settings = wp_parse_args($settings, $defaults);
    $settings['include_images'] = function_exists('aiomatic_super_pages_normalize_image_source')
        ? aiomatic_super_pages_normalize_image_source($settings['include_images'], $available_image_tools)
        : $settings['include_images'];

    ?>
    <div class="wrap aiomatic-admin-shell aiomatic-super-pages-wrap">
        <section class="aiomatic-admin-main">
            <div class="aiomatic-super-hero">
                <div>
                    <span class="aiomatic-super-kicker"><?php echo esc_html__('AI Page Builder', 'aiomatic-automatic-ai-content-writer'); ?></span>
                    <h1><?php echo esc_html__('AI Omni Pages', 'aiomatic-automatic-ai-content-writer'); ?></h1>
                    <p><?php echo esc_html__('Generate complete Gutenberg pages or multi-page funnels from a prompt, reference URL(s) or mixed instructions with URLs.', 'aiomatic-automatic-ai-content-writer'); ?></p>
                    <br/>
                    <div class="aiomatic-super-badge">
    <?php echo esc_html__('Aimogen generates complete page structures automatically, but human review is recommended before publishing.', 'aiomatic-automatic-ai-content-writer'); ?>
</div>
                </div>
            </div>

            <?php
            aiomatic_super_pages_render_builder($mode, $renderer, $settings, $available_image_tools);
            ?>
        </section>
    </div>

    <?php aiomatic_super_pages_inline_assets($mode, $renderer); ?>
<hr/>
<?php if(!isset($aiomatic_Main_Settings['hide_videos']) || trim($aiomatic_Main_Settings['hide_videos']) != 'on'){
?>
<div class="wrap">
        <h3><?php echo esc_html__("AI Omni Pages Tutorial Video", 'aiomatic-automatic-ai-content-writer');?></h3>
        <div id="ai-video-container"><br/>
            <iframe class="ai-video" width="560" height="315" src="https://www.youtube.com/embed/hiIwxyftnBU" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
    </div>
<?php
   }
}

function aiomatic_super_pages_tooltip($text)
{
    $text = wp_strip_all_tags((string) $text);

    if ($text === '') {
        return;
    }

    ?>
    <button type="button" class="aiomatic-super-tooltip" aria-label="<?php echo esc_attr($text); ?>" data-tooltip="<?php echo esc_attr($text); ?>">?</button>
    <?php
}

function aiomatic_super_pages_render_builder($mode, $renderer, $settings, $available_image_tools = array())
{
    if (!is_array($available_image_tools)) {
        $available_image_tools = array();
    }

    $single_url = add_query_arg(
        array(
            'page'     => 'aiomatic_bulk_creators',
            'tab'      => 'aiomatic_pages_panel',
            'mode'     => 'single',
            'renderer' => $renderer,
        ),
        admin_url('admin.php')
    );

    $funnel_url = add_query_arg(
        array(
            'page'     => 'aiomatic_bulk_creators',
            'tab'      => 'aiomatic_pages_panel',
            'mode'     => 'funnel',
            'renderer' => $renderer,
        ),
        admin_url('admin.php')
    );

    ?>
    <div class="aiomatic-super-layout">
        <div class="aiomatic-super-main-card">
<?php
/*
            <div class="aiomatic-super-mode-switch">

                <a href="<?php echo esc_url($single_url); ?>" class="<?php echo $mode === 'single' ? 'active' : ''; ?>">
                    <?php echo esc_html__('Single Page', 'aiomatic-automatic-ai-content-writer'); ?>
                </a>

                <a href="<?php echo esc_url($funnel_url); ?>" class="<?php echo $mode === 'funnel' ? 'active' : ''; ?>">
                    <?php echo esc_html__('Funnel', 'aiomatic-automatic-ai-content-writer'); ?>
                </a>

            </div>
*/
?>
            <div class="aiomatic-super-prompt-card">
                <h2>
                    <?php
                    echo $mode === 'funnel'
                        ? esc_html__('What funnel should Aimogen build?', 'aiomatic-automatic-ai-content-writer')
                        : esc_html__('What page should Aimogen build?', 'aiomatic-automatic-ai-content-writer');
                    ?>
                </h2>

                <textarea id="aiomatic_super_prompt" placeholder="<?php echo esc_attr__('Example: Create a high-converting comparison page for the best WordPress AI content plugins. You can also paste one or more reference URLs, or mix normal instructions with URLs. Aimogen will extract readable source content and use it in the AI prompt.', 'aiomatic-automatic-ai-content-writer'); ?>"></textarea>


<div class="aiomatic-super-examples">
<?php
if ($mode === 'funnel') {
    $examples = array(
        array(
            'title'    => '🚀 Product Launch Funnel',
            'subtitle' => 'Launch a new AI WordPress plugin',
            'prompt'   => 'Create a complete product launch funnel for a new AI WordPress plugin. Include a landing page, features page, pricing page, FAQ page, and final checkout CTA page.',
        ),

        array(
            'title'    => '🎯 Lead Magnet Funnel',
            'subtitle' => 'Free SEO checklist campaign',
            'prompt'   => 'Create a lead magnet funnel for a free SEO checklist. Include benefit-driven copy, opt-in form section, trust elements, email sequence preview, and thank-you page CTA.',
        ),

        array(
            'title'    => '🎥 Webinar Funnel',
            'subtitle' => 'WordPress automation training',
            'prompt'   => 'Create a webinar funnel for a WordPress automation training. Include registration page, agenda section, speaker section, video embed placeholder, reminders, and replay CTA.',
        ),

        array(
            'title'    => '📈 SaaS Sales Funnel',
            'subtitle' => 'Analytics software promotion',
            'prompt'   => 'Create a software sales funnel for a SaaS analytics tool. Include problem/solution page, feature deep-dive page, comparison page, pricing page, testimonials, and final CTA.',
        ),

        array(
            'title'    => '✨ Free Trial Funnel',
            'subtitle' => 'Convert trial users to customers',
            'prompt'   => 'Create a free trial funnel for a productivity app. Include trial signup page, onboarding explanation, use cases, pricing upgrade section, FAQ, and strong conversion CTAs.',
        ),
    );
} else {
    $examples = array(

        array(
            'title'    => '🛒 Product Comparison',
            'subtitle' => 'Gaming laptop buyer guide',
            'prompt'   => 'Create a buyer\'s guide for the best gaming laptops. Include comparison tables, ratings, reviews, pros and cons, specifications, buying recommendations, affiliate links, CTA buttons, and an Editor\'s Choice recommendation.',
        ),

        array(
            'title'    => '🏠 Local Service Page',
            'subtitle' => 'Roofing company in Chicago',
            'prompt'   => 'Create a local service page for "roofing in Chicago". Include service descriptions, trust badges, emergency repair CTA, phone CTAs using "555-123-4567", FAQ, and an interactive map for "123 N Michigan Ave, Chicago, IL 60601".',
        ),

        array(
            'title'    => '🌱 Educational Article',
            'subtitle' => 'Environmental technology',
            'prompt'   => 'Create an article with images about "environmental technology". Use "https://en.wikipedia.org/wiki/Environmental_technology" as reference, include key innovations, benefits, examples, challenges, and future trends.',
        ),

        array(
            'title'    => '🎵 Video Review Page',
            'subtitle' => 'Top music videos',
            'prompt'   => 'Create a page reviewing the "top 10 music videos from the 2000s". Embed relevant YouTube videos, include short reviews, cultural impact, release year, artist details, and a ranked summary table.',
        ),

        array(
            'title'    => '🏕️ Travel Guide',
            'subtitle' => 'America\'s national parks',
            'prompt'   => 'Create a comprehensive guide featuring "America\'s 10 most stunning national parks" with spectacular imagery at the beginning of each section. For each park, include must-see attractions, best hiking trails, and ideal visiting seasons. Between parks 3 and 4, parks 6 and 7, and after park 10, insert camping gear recommendations with Amazon affiliate links using "https://amazon.com/dp/PRODUCTID?tag=myrefid-20". Feature a hiking backpack, durable tent, and hiking boots with image and Check Price CTAs.',
        ),

        array(
            'title'    => '🤖 SaaS Landing Page',
            'subtitle' => 'AI meeting assistant',
            'prompt'   => 'Create a SaaS landing page for an AI meeting notes app. Include hero section, feature screenshots, how it works, integrations, pricing cards, testimonials, FAQ, and a final CTA banner.',
        ),

        array(
            'title'    => '🔍 Affiliate Review',
            'subtitle' => 'Best WordPress SEO plugins',
            'prompt'   => 'Create an affiliate review page for "best WordPress SEO plugins". Include comparison table, individual plugin reviews, pros/cons, ideal use cases, pricing notes, screenshots, affiliate CTA buttons, and a final recommendation.',
        ),

        array(
            'title'    => '📞 Lead Generation Page',
            'subtitle' => 'Digital marketing agency',
            'prompt'   => 'Create a lead generation page for a digital marketing agency. Include services, case study section, audit offer, lead capture form placeholder, client logos, FAQ, and strong booking CTAs.',
        ),
    );
}
foreach ($examples as $example) {
    ?>
    <button
        type="button"
        class="aiomatic-super-chip"
        data-prompt="<?php echo esc_attr($example['prompt']); ?>"
        title="<?php echo esc_attr($example['prompt']); ?>"
    >
        <span class="aiomatic-super-example-title">
            <?php echo esc_html($example['title']); ?>
        </span>

        <span class="aiomatic-super-example-subtitle">
            <?php echo esc_html($example['subtitle']); ?>
        </span>
    </button>
    <?php
}
?>
</div>
                <div class="aiomatic-super-actions">
                    <button type="button" id="aiomatic_generate_super_pages" class="button button-primary button-hero">
                        <?php
                        echo $mode === 'funnel'
                            ? esc_html__('Generate Funnel', 'aiomatic-automatic-ai-content-writer')
                            : esc_html__('Generate Omni Page', 'aiomatic-automatic-ai-content-writer');
                        ?>
                    </button>
                    <span class="spinner"></span>
                </div>

                <div id="aiomatic_super_result" class="aiomatic-super-result hidden"></div>
            </div>
        </div>

        <aside class="aiomatic-super-side-card">
            <h3><?php echo esc_html__('Build Options', 'aiomatic-automatic-ai-content-writer'); ?></h3>
<?php
$elementor_active = false;

if (
    did_action('elementor/loaded') ||
    class_exists('\Elementor\Plugin')
) {
    $elementor_active = true;
}
?>
            <label>
                <?php echo esc_html__('Language', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Sets the language used for generated titles, copy, headings, and metadata.', 'aiomatic-automatic-ai-content-writer')); ?>
                <input type="text" id="aiomatic_super_language" value="<?php echo esc_attr($settings['default_language']); ?>">
            </label>

            <label>
                <?php echo esc_html__('Content Format', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Auto detect chooses between a conversion page and an editorial article based on your prompt.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_content_format">
                    <option value="auto" <?php selected($settings['content_format'] ?? 'auto', 'auto'); ?>><?php echo esc_html__('Auto detect', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="landing_page" <?php selected($settings['content_format'] ?? 'auto', 'landing_page'); ?>><?php echo esc_html__('Landing page', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="article" <?php selected($settings['content_format'] ?? 'auto', 'article'); ?>><?php echo esc_html__('Article / guide', 'aiomatic-automatic-ai-content-writer'); ?></option>
                </select>
            </label>

            <label>
                <?php echo esc_html__('Primary Goal', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Guides the page strategy: sales, lead capture, education, or search-focused authority. Auto detect infers this from the prompt.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_goal">
                    <option value="auto" <?php selected($settings['goal'] ?? 'auto', 'auto'); ?>><?php echo esc_html__('Auto Detect', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="conversions" <?php selected($settings['goal'] ?? 'auto', 'conversions'); ?>><?php echo esc_html__('Conversions', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="leads" <?php selected($settings['goal'] ?? 'auto', 'leads'); ?>><?php echo esc_html__('Lead generation', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="education" <?php selected($settings['goal'] ?? 'auto', 'education'); ?>><?php echo esc_html__('Education', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="seo" <?php selected($settings['goal'] ?? 'auto', 'seo'); ?>><?php echo esc_html__('SEO / authority', 'aiomatic-automatic-ai-content-writer'); ?></option>
                </select>
            </label>

            <label>
                <?php echo esc_html__('Content Depth', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Controls page length and detail. Short is compact, Standard is balanced, and Comprehensive creates more sections with fuller copy.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_depth">
                    <option value="short" <?php selected($settings['depth'] ?? 'comprehensive', 'short'); ?>><?php echo esc_html__('Short', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="standard" <?php selected($settings['depth'] ?? 'comprehensive', 'standard'); ?>><?php echo esc_html__('Standard', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="comprehensive" <?php selected($settings['depth'] ?? 'comprehensive', 'comprehensive'); ?>><?php echo esc_html__('Comprehensive', 'aiomatic-automatic-ai-content-writer'); ?></option>
                </select>
            </label>

            <?php if ($mode === 'funnel') : ?>
                <label>
                    <?php echo esc_html__('Number of Funnel Pages', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Sets how many connected pages Aimogen should create for this funnel.', 'aiomatic-automatic-ai-content-writer')); ?>
                    <input type="number" min="2" max="10" id="aiomatic_super_page_count" value="<?php echo esc_attr((int) $settings['default_page_count']); ?>">
                </label>
            <?php endif; ?>

<label>
    <?php echo esc_html__('AI Model', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Selects the AI model used for planning and writing the page.', 'aiomatic-automatic-ai-content-writer')); ?>

    <select id="aiomatic_ai_model" name="aiomatic_ai_model">
        <?php
        $models = aiomatic_get_all_function_models(true);

        $selected_model = isset($settings['ai_model'])
            ? $settings['ai_model']
            : '';

        foreach ($models as $model) :
        ?>
            <option value="<?php echo esc_attr($model); ?>"
                <?php selected($selected_model, $model); ?>>
                <?php echo esc_html($model) . esc_html(aiomatic_get_model_provider($model));?>
            </option>
        <?php endforeach; ?>
    </select>
</label>

<label>
                <?php echo esc_html__('Post Type', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Chooses whether the generated content is saved as a WordPress page or blog post.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_type">
                    <option value="page" <?php selected($settings['default_type'], 'page'); ?>><?php echo esc_html__('Page', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="post" <?php selected($settings['default_type'], 'post'); ?>><?php echo esc_html__('Post', 'aiomatic-automatic-ai-content-writer'); ?></option>
                </select>
            </label>

            <label>
                <?php echo esc_html__('Post Status', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Controls whether generated content is saved privately as a draft, queued for review, or published immediately.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_status">
                    <option value="draft" <?php selected($settings['default_status'], 'draft'); ?>><?php echo esc_html__('Draft', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="pending" <?php selected($settings['default_status'], 'pending'); ?>><?php echo esc_html__('Pending Review', 'aiomatic-automatic-ai-content-writer'); ?></option>
                    <option value="publish" <?php selected($settings['default_status'], 'publish'); ?>><?php echo esc_html__('Publish', 'aiomatic-automatic-ai-content-writer'); ?></option>
                </select>
            </label>

<label>
    <?php echo esc_html__('Renderer', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Chooses the builder format for the generated page content.', 'aiomatic-automatic-ai-content-writer')); ?>
    <select id="aiomatic_super_renderer">

        <option value="gutenberg" <?php selected($renderer, 'gutenberg'); ?>>
            <?php echo esc_html__('Gutenberg Blocks', 'aiomatic-automatic-ai-content-writer'); ?>
        </option>
<?php
/*

        <option
            value="elementor"
            <?php selected($renderer, 'elementor'); ?>
            <?php disabled(!$elementor_active); ?>
        >
            <?php
            echo $elementor_active
                ? esc_html__('Elementor', 'aiomatic-automatic-ai-content-writer')
                : esc_html__('Elementor (Plugin Not Installed)', 'aiomatic-automatic-ai-content-writer');
            ?>
        </option>
*/
?>
    </select>
</label>

            <label>
                <?php echo esc_html__('Image Source', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Controls whether Aimogen adds images and which configured image provider it may use.', 'aiomatic-automatic-ai-content-writer')); ?>
                <select id="aiomatic_super_include_images">
                    <?php
                    $image_source_options = function_exists('aiomatic_super_pages_image_source_options')
                        ? aiomatic_super_pages_image_source_options()
                        : array(
                            'none' => array(
                                'label' => __('Don\'t include images', 'aiomatic-automatic-ai-content-writer'),
                                'tool'  => '',
                            ),
                            'royalty_free' => array(
                                'label' => __('Use royalty free images', 'aiomatic-automatic-ai-content-writer'),
                                'tool'  => 'royalty_free_image_search',
                            ),
                        );

                    foreach ($image_source_options as $source => $option) :
                        $tool = isset($option['tool']) ? (string) $option['tool'] : '';
                        $is_available = $tool === '' || in_array($tool, $available_image_tools, true);
                        $label = isset($option['label']) ? (string) $option['label'] : $source;

                        if (!$is_available) {
                            $label .= ' ' . __('(not configured)', 'aiomatic-automatic-ai-content-writer');
                        }
                        ?>
                        <option
                            value="<?php echo esc_attr($source); ?>"
                            <?php selected($settings['include_images'], $source); ?>
                            <?php disabled(!$is_available); ?>
                        >
                            <?php echo esc_html($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <div class="aiomatic-super-checks">
                <label><input type="checkbox" id="aiomatic_super_url_parsing_enabled" <?php checked($settings['url_parsing_enabled'], 'on'); ?>> <?php echo esc_html__('Enable URL parsing', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('When enabled, URLs pasted in the prompt are scraped and inserted as source context before generation.', 'aiomatic-automatic-ai-content-writer')); ?></label>
                <label><input type="checkbox" id="aiomatic_super_research_enabled" <?php checked($settings['research_enabled'], 'on'); ?>> <?php echo esc_html__('Enable research', 'aiomatic-automatic-ai-content-writer'); ?> <?php aiomatic_super_pages_tooltip(__('Allows the agent to use research tools such as search, competitor analysis, and semantic extraction.', 'aiomatic-automatic-ai-content-writer')); ?></label>
            </div>
        </aside>
    </div>

    <input type="hidden" id="aiomatic_super_mode" value="<?php echo esc_attr($mode); ?>">
    <input type="hidden" id="aiomatic_super_nonce" value="<?php echo esc_attr(wp_create_nonce('aiomatic_super_pages_nonce')); ?>">
    <?php
}

function aiomatic_super_pages_inline_assets($mode, $renderer)
{
?>
<style>
.aiomatic-super-hero {
    background: linear-gradient(135deg,#10182d,#17233f);
    color: #fff;
    border-radius: 18px;
    padding: 28px 32px;
    margin: 18px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 12px 30px rgba(15,23,42,.16);
}
.aiomatic-super-hero h1 { color:#fff; margin:6px 0 8px; font-size:30px; }
.aiomatic-super-hero p { color:#cbd5e1; margin:0; font-size:15px; }
.aiomatic-super-kicker { color:#8ea7ff; text-transform:uppercase; letter-spacing:1.4px; font-size:11px; font-weight:700; }
.aiomatic-super-badge { border:1px solid rgba(255,255,255,.14); border-radius:999px; padding:8px 14px; color:#dbeafe; background:rgba(255,255,255,.05); }
.aiomatic-super-nav { display:flex; gap:8px; margin-bottom:18px; }
.aiomatic-super-nav a {
    text-decoration:none;
    padding:10px 16px;
    border-radius:12px;
    background:#fff;
    border:1px solid #dfe3ea;
    color:#1f2937;
    font-weight:600;
}
.aiomatic-super-nav a.active { background:#3b5bfd; color:#fff; border-color:#3b5bfd; }
.aiomatic-super-layout { display:grid; grid-template-columns: minmax(0, 1fr) 340px; gap:18px; }
.aiomatic-super-main-card, .aiomatic-super-side-card, .aiomatic-super-panel {
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:18px;
    padding:24px;
    box-shadow:0 8px 24px rgba(15,23,42,.06);
}
.aiomatic-super-mode-switch { display:flex; gap:10px; margin-bottom:20px; }
.aiomatic-super-mode-switch a {
    padding:10px 16px;
    border-radius:12px;
    text-decoration:none;
    border:1px solid #dfe3ea;
    color:#111827;
    font-weight:700;
    background:#f8fafc;
}
.aiomatic-super-mode-switch a.active { background:#111827; color:#fff; border-color:#111827; }
.aiomatic-super-prompt-card h2 { font-size:26px; margin:4px 0 18px; }
#aiomatic_super_prompt {
    width:100%;
    min-height:190px;
    border:1px solid #d9dee8;
    border-radius:18px;
    padding:18px;
    font-size:15px;
    resize:vertical;
    box-shadow: inset 0 1px 2px rgba(0,0,0,.03);
}
.aiomatic-super-examples { display:flex; flex-wrap:wrap; gap:10px; margin-top:16px; }
.aiomatic-super-chip {
    border:1px solid #dfe3ea;
    background:#f8fafc;
    border-radius:999px;
    padding:9px 14px;
    cursor:pointer;
    font-weight:600;
}
.aiomatic-super-chip:hover { background:#eef2ff; border-color:#b9c4ff; }
.aiomatic-super-actions { margin-top:22px; display:flex; align-items:center; gap:12px; }
.aiomatic-super-side-card h3 { margin-top:0; font-size:18px; }
.aiomatic-super-side-card label { display:block; margin-bottom:16px; font-weight:700; }
.aiomatic-super-side-card input[type="text"],
.aiomatic-super-side-card input[type="number"],
.aiomatic-super-side-card select {
    width:100%;
    margin-top:7px;
    border-radius:10px;
    border-color:#d9dee8;
    min-height:38px;
}
.aiomatic-super-checks label { font-weight:500; margin-bottom:10px; }
.aiomatic-super-tooltip {
    position:relative;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    width:18px;
    height:18px;
    margin-left:5px;
    padding:0;
    border:1px solid #cbd5e1;
    border-radius:999px;
    background:#f8fafc;
    color:#475569;
    font-size:11px;
    line-height:1;
    font-weight:700;
    cursor:help;
    vertical-align:middle;
}
.aiomatic-super-tooltip:hover,
.aiomatic-super-tooltip:focus {
    background:#111827;
    border-color:#111827;
    color:#fff;
    outline:none;
}
.aiomatic-super-tooltip:focus-visible {
    box-shadow:0 0 0 2px #fff, 0 0 0 4px #3b82f6;
}
.aiomatic-super-tooltip::before {
    content:attr(data-tooltip);
    position:absolute;
    z-index:20;
    right:50%;
    bottom:calc(100% + 10px);
    width:240px;
    max-width:calc(100vw - 48px);
    padding:10px 12px;
    border-radius:10px;
    background:#111827;
    color:#fff;
    box-shadow:0 12px 30px rgba(15,23,42,.22);
    font-size:12px;
    line-height:1.45;
    font-weight:500;
    text-align:left;
    white-space:normal;
    opacity:0;
    pointer-events:none;
    transform:translate(50%, 4px);
    transition:opacity .16s ease, transform .16s ease;
}
.aiomatic-super-tooltip::after {
    content:'';
    position:absolute;
    z-index:21;
    right:50%;
    bottom:calc(100% + 4px);
    border:6px solid transparent;
    border-top-color:#111827;
    opacity:0;
    pointer-events:none;
    transform:translate(50%, 4px);
    transition:opacity .16s ease, transform .16s ease;
}
.aiomatic-super-tooltip:hover::before,
.aiomatic-super-tooltip:hover::after,
.aiomatic-super-tooltip:focus::before,
.aiomatic-super-tooltip:focus::after {
    opacity:1;
    transform:translate(50%, 0);
}
.aiomatic-super-note {
    background:#f8fafc;
    border:1px solid #e5e7eb;
    border-radius:14px;
    padding:14px;
    color:#475569;
    line-height:1.5;
}
.aiomatic-super-result {
    margin-top:20px;
    border-radius:14px;
    padding:16px;
    background:#f0fdf4;
    border:1px solid #bbf7d0;
}
.aiomatic-super-progress-wrap {
    background:#e5e7eb;
    border-radius:999px;
    height:12px;
    overflow:hidden;
    margin:12px 0;
}
.aiomatic-super-progress-bar {
    height:12px;
    width:0%;
    background:#3b5bfd;
    transition:width .35s ease;
}
.aiomatic-super-job-meta {
    color:#475569;
    font-size:13px;
    margin-top:8px;
}
.aiomatic-super-job-actions {
    margin-top:12px;
}
.aiomatic-super-template-grid {
    display:grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap:14px;
    margin-top:16px;
}
.aiomatic-super-template {
    border:1px solid #e5e7eb;
    border-radius:14px;
    padding:18px;
    background:#f8fafc;
}
.aiomatic-super-template h3 { margin-top:0; }
@media (max-width: 1100px) {
    .aiomatic-super-layout { grid-template-columns:1fr; }
    .aiomatic-super-hero { flex-direction:column; align-items:flex-start; gap:16px; }
}
    </style>

    <script>
jQuery(function($){
    var pollTimer = null;
    var processStarted = false;
    var storageKey = 'aiomatic_super_pages_active_job';

    function getPayload() {
        return {
            nonce: $('#aiomatic_super_nonce').val(),
            prompt: $.trim($('#aiomatic_super_prompt').val()),
            mode: $('#aiomatic_super_mode').val(),
            renderer: $('#aiomatic_super_renderer').val(),
            language: $('#aiomatic_super_language').val(),
            content_format: $('#aiomatic_super_content_format').val(),
            goal: $('#aiomatic_super_goal').val(),
            depth: $('#aiomatic_super_depth').val(),
            status: $('#aiomatic_super_status').val(),
            type: $('#aiomatic_super_type').val(),
            model: $('#aiomatic_ai_model').val(),
            page_count: $('#aiomatic_super_page_count').length ? $('#aiomatic_super_page_count').val() : 1,
            include_images: $('#aiomatic_super_include_images').val(),
            url_parsing_enabled: $('#aiomatic_super_url_parsing_enabled').is(':checked') ? 'yes' : 'no',
            research_enabled: $('#aiomatic_super_research_enabled').is(':checked') ? 'yes' : 'no',
        };
    }

    function setLoading(isLoading) {
        $('#aiomatic_generate_super_pages').prop('disabled', isLoading);
        $('#aiomatic_generate_super_pages').siblings('.spinner').toggleClass('is-active', isLoading);
    }

    function renderJob(job) {
        var result = $('#aiomatic_super_result');
        var progress = parseInt(job.progress || 0, 10);
        var status = job.status || 'unknown';
        var step = job.current_step || '';
        var html = '';

        result.removeClass('hidden').show();

        html += '<strong>' + escapeHtml(status.charAt(0).toUpperCase() + status.slice(1)) + '</strong>';
        html += '<div class="aiomatic-super-progress-wrap"><div class="aiomatic-super-progress-bar" style="width:' + progress + '%"></div></div>';
        html += '<div>' + progress + '% - ' + escapeHtml(step) + '</div>';
        html += '<div class="aiomatic-super-job-meta">Job ID: <code>' + escapeHtml(job.id || '') + '</code></div>';

        if (status === 'completed') {
            html += '<div class="aiomatic-super-job-actions">' + (job.message || '<?php echo esc_js(__('Generation completed.', 'aiomatic-automatic-ai-content-writer')); ?>') + '</div>';
        }

        if (status === 'failed') {
            html += '<div style="margin-top:10px;color:#b91c1c;">' + escapeHtml(job.error || '<?php echo esc_js(__('Generation failed.', 'aiomatic-automatic-ai-content-writer')); ?>') + '</div>';
        }

        if (status === 'running' || status === 'queued') {
            html += '<div class="aiomatic-super-job-actions"><button type="button" class="button aiomatic-cancel-super-job" data-job-id="' + escapeHtml(job.id || '') + '"><?php echo esc_js(__('Cancel Job', 'aiomatic-automatic-ai-content-writer')); ?></button></div>';
        }

        result.html(html);
    }

    function escapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function startWorker(jobId) {
        if (processStarted) {
            return;
        }

        processStarted = true;

        $.post(ajaxurl, {
            action: 'aiomatic_super_pages_process_job',
            nonce: $('#aiomatic_super_nonce').val(),
            job_id: jobId
        }).always(function(){
            processStarted = false;
            pollJob(jobId);
        });
    }

    function pollJob(jobId) {
        $.post(ajaxurl, {
            action: 'aiomatic_super_pages_job_status',
            nonce: $('#aiomatic_super_nonce').val(),
            job_id: jobId
        }).done(function(response){
            if (!response || !response.success || !response.data) {
                return;
            }

            var job = response.data;
            renderJob(job);

            if (job.status === 'queued') {
                startWorker(jobId);
                setLoading(true);
                return;
            }

            if (job.status === 'running') {
                setLoading(true);
                return;
            }

            if (job.status === 'completed' || job.status === 'failed' || job.status === 'cancelled') {
                localStorage.removeItem(storageKey);
                setLoading(false);
                if (pollTimer) {
                    clearInterval(pollTimer);
                    pollTimer = null;
                }
            }
        }).fail(function(){
            $('#aiomatic_super_result').removeClass('hidden').show().html('<?php echo esc_js(__('Could not read job status. Retrying...', 'aiomatic-automatic-ai-content-writer')); ?>');
        });
    }

    function watchJob(jobId) {
        localStorage.setItem(storageKey, jobId);
        setLoading(true);
        pollJob(jobId);
        startWorker(jobId);

        if (pollTimer) {
            clearInterval(pollTimer);
        }

        pollTimer = setInterval(function(){
            pollJob(jobId);
        }, 3000);
    }

    $('#aiomatic_super_renderer').on('change', function(){
        window.location.href = '<?php echo esc_url_raw(admin_url('admin.php?page=aiomatic_bulk_creators&tab=aiomatic_pages_panel&mode=' . $mode)); ?>' + '&renderer=' + encodeURIComponent($(this).val());
    });

    $(document).on('click', '.aiomatic-super-chip, .aiomatic-super-example-card', function () {

        var prompt = $(this).data('prompt');

        if(prompt) {
            $('#aiomatic_super_prompt').val(prompt);
        } else {
            $('#aiomatic_super_prompt').val($.trim($(this).text()));
        }
    });

    $('#aiomatic_generate_super_pages').on('click', function(){
        var payload = getPayload();
        var result = $('#aiomatic_super_result');

        if (!payload.prompt) {
            alert('<?php echo esc_js(__('Please describe what you want to build first.', 'aiomatic-automatic-ai-content-writer')); ?>');
            return;
        }

        result.removeClass('hidden').show().html('<?php echo esc_js(__('Creating generation job...', 'aiomatic-automatic-ai-content-writer')); ?>');
        setLoading(true);

        payload.action = 'aiomatic_super_pages_start_job';

        $.post(ajaxurl, payload).done(function(response){
            if (response && response.success && response.data && response.data.job_id) {
                watchJob(response.data.job_id);
            } else {
                setLoading(false);
                result.html(response && response.data ? response.data.message : '<?php echo esc_js(__('Could not create generation job.', 'aiomatic-automatic-ai-content-writer')); ?>');
            }
        }).fail(function(){
            setLoading(false);
            result.html('<?php echo esc_js(__('Request failed. Please try again.', 'aiomatic-automatic-ai-content-writer')); ?>');
        });
    });

    $(document).on('click', '.aiomatic-cancel-super-job', function(){
        var jobId = $(this).data('job-id');

        $.post(ajaxurl, {
            action: 'aiomatic_super_pages_cancel_job',
            nonce: $('#aiomatic_super_nonce').val(),
            job_id: jobId
        }).always(function(){
            localStorage.removeItem(storageKey);
            setLoading(false);
            if (pollTimer) {
                clearInterval(pollTimer);
                pollTimer = null;
            }
            pollJob(jobId);
        });
    });

    var activeJob = localStorage.getItem(storageKey);

    if (activeJob) {
        watchJob(activeJob);
    }
});
</script>
<?php
}
