<?php

defined('ABSPATH') || exit;

if (!defined('AIOMATIC_SUPER_PAGES_JOB_TTL')) {
    define('AIOMATIC_SUPER_PAGES_JOB_TTL', DAY_IN_SECONDS);
}

add_action('wp_ajax_aiomatic_super_pages_start_job', 'aiomatic_super_pages_start_job');
add_action('wp_ajax_aiomatic_super_pages_process_job', 'aiomatic_super_pages_process_job');
add_action('wp_ajax_aiomatic_super_pages_job_status', 'aiomatic_super_pages_job_status');
add_action('wp_ajax_aiomatic_super_pages_cancel_job', 'aiomatic_super_pages_cancel_job');

function aiomatic_super_pages_image_source_options()
{
    return 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',
        ),
        'openai' => array(
            'label' => __('AI images - OpenAI', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_openai',
        ),
        'stable_diffusion' => array(
            'label' => __('AI images - Stable Diffusion', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_stable_diffusion',
        ),
        'google' => array(
            'label' => __('AI images - Google', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_google',
        ),
        'midjourney' => array(
            'label' => __('AI images - Midjourney', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_midjourney',
        ),
        'replicate' => array(
            'label' => __('AI images - Replicate', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_replicate',
        ),
        'ideogram' => array(
            'label' => __('AI images - Ideogram', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_ideogram',
        ),
        'cloudflare' => array(
            'label' => __('AI images - Cloudflare', 'aiomatic-automatic-ai-content-writer'),
            'tool'  => 'generate_ai_image_cloudflare',
        ),
    );
}

function aiomatic_super_pages_image_tool_names()
{
    $tools = array();

    foreach (aiomatic_super_pages_image_source_options() as $option) {
        if (!empty($option['tool'])) {
            $tools[] = $option['tool'];
        }
    }

    return $tools;
}

function aiomatic_super_pages_get_available_image_tools($agent = null)
{
    $settings = get_option('aiomatic_Main_Settings', false);
    $settings = is_array($settings) ? $settings : array();
    $tools = array();

    if (!empty($settings['app_id']) && trim((string) $settings['app_id']) !== '') {
        $tools[] = 'generate_ai_image_openai';
    }

    if (!empty($settings['stability_app_id'])) {
        $tools[] = 'generate_ai_image_stable_diffusion';
    }

    if (!empty($settings['app_id_google'])) {
        $tools[] = 'generate_ai_image_google';
    }

    if (!empty($settings['midjourney_app_id'])) {
        $tools[] = 'generate_ai_image_midjourney';
    }

    if (!empty($settings['replicate_app_id'])) {
        $tools[] = 'generate_ai_image_replicate';
    }

    if (!empty($settings['ideogram_app_id'])) {
        $tools[] = 'generate_ai_image_ideogram';
    }

    if (
        !empty($settings['cloudflare_worker_url']) &&
        !empty($settings['cloudflare_worker_secret'])
    ) {
        $tools[] = 'generate_ai_image_cloudflare';
    }

    $tools[] = 'royalty_free_image_search';

    return array_values(array_unique((array) apply_filters(
        'aimogen_super_page_image_tools',
        $tools,
        $settings,
        $agent
    )));
}

function aiomatic_super_pages_image_source_to_tool($source)
{
    $source = sanitize_key((string) $source);
    $options = aiomatic_super_pages_image_source_options();

    return isset($options[$source]) ? $options[$source]['tool'] : '';
}

function aiomatic_super_pages_image_source_from_tool($tool)
{
    $tool = sanitize_key((string) $tool);

    foreach (aiomatic_super_pages_image_source_options() as $source => $option) {
        if (!empty($option['tool']) && $option['tool'] === $tool) {
            return $source;
        }
    }

    return 'none';
}

function aiomatic_super_pages_get_default_image_source($available_tools = null)
{
    $available_tools = is_array($available_tools)
        ? $available_tools
        : aiomatic_super_pages_get_available_image_tools();

    foreach ($available_tools as $tool) {
        $source = aiomatic_super_pages_image_source_from_tool($tool);

        if ($source !== 'none') {
            return $source;
        }
    }

    return 'none';
}

function aiomatic_super_pages_normalize_image_source($source, $available_tools = null)
{
    if (is_bool($source)) {
        $source = $source ? 'on' : 'none';
    }

    $source = sanitize_key((string) $source);

    if (in_array($source, array('', '0', 'false', 'no', 'off', 'none'), true)) {
        return 'none';
    }

    $available_tools = is_array($available_tools)
        ? $available_tools
        : aiomatic_super_pages_get_available_image_tools();

    if (in_array($source, array('1', 'true', 'yes', 'on'), true)) {
        return aiomatic_super_pages_get_default_image_source($available_tools);
    }

    if (in_array($source, aiomatic_super_pages_image_tool_names(), true)) {
        $source = aiomatic_super_pages_image_source_from_tool($source);
    }

    $tool = aiomatic_super_pages_image_source_to_tool($source);

    if ($source === 'none') {
        return 'none';
    }

    if ($tool !== '' && in_array($tool, $available_tools, true)) {
        return $source;
    }

    return aiomatic_super_pages_get_default_image_source($available_tools);
}

function aiomatic_super_pages_base_allowed_tools()
{
    return array(
        'google_results_parser',
        'website_scraper',
        'process_and_transform_data',
        'youtube_video_search',
        'youtube_video_captions',
        'search_site_posts',
        'get_wp_post_data',
        'get_wp_media_info',
        'wp_taxonomy_discovery',
        'wp_validate_post_state',
        'edit_post_section',
        'get_post_structure',
        'wp_sideload_media',
        'generate_chart',
    );
}

function aiomatic_super_pages_allowed_tools_for_image_source($source, $available_tools = null)
{
    $available_tools = is_array($available_tools)
        ? $available_tools
        : aiomatic_super_pages_get_available_image_tools();

    $source = aiomatic_super_pages_normalize_image_source($source, $available_tools);
    $tools = aiomatic_super_pages_base_allowed_tools();
    $image_tool = aiomatic_super_pages_image_source_to_tool($source);

    if ($image_tool !== '' && in_array($image_tool, $available_tools, true)) {
        $tools[] = $image_tool;
    }

    return array_values(array_unique((array) apply_filters(
        'aiomatic_super_pages_allowed_tools_for_image_source',
        $tools,
        $source,
        $available_tools
    )));
}

function aiomatic_super_pages_job_key($job_id)
{
    return 'aiomatic_super_pages_job_' . sanitize_key((string) $job_id);
}

function aiomatic_super_pages_job_lock_key($job_id)
{
    return 'aiomatic_super_pages_job_lock_' . sanitize_key((string) $job_id);
}

function aiomatic_super_pages_get_job($job_id)
{
    $job = get_transient(aiomatic_super_pages_job_key($job_id));

    return is_array($job) ? $job : false;
}

function aiomatic_super_pages_save_job($job_id, $job)
{
    if (!is_array($job)) {
        return false;
    }

    $job['updated_at'] = time();

    return set_transient(
        aiomatic_super_pages_job_key($job_id),
        $job,
        AIOMATIC_SUPER_PAGES_JOB_TTL
    );
}

function aiomatic_super_pages_update_job($job_id, $updates = array())
{
    $job = aiomatic_super_pages_get_job($job_id);

    if (!$job) {
        return false;
    }
    
    foreach ($updates as $key => $value) {
        $job[$key] = $value;
    }

    aiomatic_super_pages_save_job($job_id, $job);

    return $job;
}

function aiomatic_super_pages_set_job_progress($job_id, $progress, $step, $extra = array())
{
    $updates = array_merge(
        array(
            'progress'     => max(0, min(100, absint($progress))),
            'current_step' => sanitize_text_field((string) $step),
        ),
        is_array($extra) ? $extra : array()
    );

    return aiomatic_super_pages_update_job($job_id, $updates);
}

function aiomatic_super_pages_add_job_to_index($job_id, $user_id)
{
    $user_id = absint($user_id);
    $index_key = 'aiomatic_super_pages_jobs_' . $user_id;
    $index = get_option($index_key, array());

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

    array_unshift($index, sanitize_key((string) $job_id));
    $index = array_values(array_unique(array_slice($index, 0, 30)));

    update_option($index_key, $index, false);
}

function aiomatic_super_pages_get_user_jobs($user_id, $limit = 20)
{
    $index = get_option('aiomatic_super_pages_jobs_' . absint($user_id), array());

    if (!is_array($index)) {
        return array();
    }

    $jobs = array();

    foreach (array_slice($index, 0, absint($limit)) as $job_id) {
        $job = aiomatic_super_pages_get_job($job_id);

        if ($job) {
            $jobs[] = $job;
        }
    }

    return $jobs;
}

function aiomatic_super_pages_prepare_job_payload()
{
    $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : 'single';
    $renderer = isset($_POST['renderer']) ? sanitize_key(wp_unslash($_POST['renderer'])) : 'gutenberg';
    $status = isset($_POST['status']) ? sanitize_key(wp_unslash($_POST['status'])) : 'draft';
    $type = isset($_POST['type']) ? sanitize_key(wp_unslash($_POST['type'])) : 'page';

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

    if ($mode === 'page') {
        $mode = 'single';
    }

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

    if (!in_array($status, array('draft', 'pending', 'publish'), true)) {
        $status = 'draft';
    }

    if (!in_array($type, array('page', 'post'), true)) {
        $type = 'page';
    }

    $content_format = isset($_POST['content_format']) ? sanitize_key(wp_unslash($_POST['content_format'])) : 'auto';
    if (!in_array($content_format, array('auto', 'landing_page', 'article'), true)) {
        $content_format = 'auto';
    }

    $goal = isset($_POST['goal']) ? sanitize_key(wp_unslash($_POST['goal'])) : 'auto';
    if (!in_array($goal, array('auto', 'conversions', 'leads', 'education', 'seo'), true)) {
        $goal = 'auto';
    }

    $depth = isset($_POST['depth']) ? sanitize_key(wp_unslash($_POST['depth'])) : 'comprehensive';
    if (!in_array($depth, array('short', 'standard', 'comprehensive'), true)) {
        $depth = 'comprehensive';
    }

    $image_source = isset($_POST['include_images'])
        ? sanitize_key(wp_unslash($_POST['include_images']))
        : 'none';
    $image_source = aiomatic_super_pages_normalize_image_source($image_source);

    return array(
        'prompt'           => isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : '',
        'mode'             => $mode,
        'renderer'         => $renderer,
        'language'         => isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'English',
        'status'           => $status,
        'model'            => isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '',
        'page_count'       => isset($_POST['page_count']) ? max(1, min(10, absint($_POST['page_count']))) : 1,
        'include_images'   => $image_source,
        'url_parsing_enabled' => !empty($_POST['url_parsing_enabled']) && $_POST['url_parsing_enabled'] === 'yes',
        'research_enabled' => !empty($_POST['research_enabled']) && $_POST['research_enabled'] === 'yes',
        'goal'             => $goal,
        'depth'            => $depth,
        'content_format'   => $content_format,
        'type'             => $type,
    );
}

function aiomatic_super_pages_start_job()
{
    check_ajax_referer('aiomatic_super_pages_nonce', 'nonce');

    if (!current_user_can('access_aiomatic_menu')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to use this feature.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);

    if (!aiomatic_check_api_keys($aiomatic_Main_Settings)) {
        wp_send_json_error(array(
            'message' => esc_html__('Please configure your AI API key first.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    $payload = aiomatic_super_pages_prepare_job_payload();

    if ($payload['prompt'] === '') {
        wp_send_json_error(array(
            'message' => esc_html__('Please enter instructions for the Omni Page generator.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    if ($payload['renderer'] !== 'gutenberg' && $payload['renderer'] !== 'elementor') {
        wp_send_json_error(array(
            'message' => esc_html__('Only Gutenberg and Elementor rendering are currently supported.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    $job_id = 'sp_' . strtolower(wp_generate_password(16, false, false));
    $user_id = get_current_user_id();

    $job = array(
        'id'           => $job_id,
        'user_id'      => $user_id,
        'type'         => 'super_page',
        'status'       => 'queued',
        'progress'     => 0,
        'current_step' => esc_html__('Queued', 'aiomatic-automatic-ai-content-writer'),
        'payload'      => $payload,
        'result'       => array(),
        'message'      => '',
        'error'        => '',
        'created_at'   => time(),
        'updated_at'   => time(),
    );

    aiomatic_super_pages_save_job($job_id, $job);
    aiomatic_super_pages_add_job_to_index($job_id, $user_id);

    wp_send_json_success(array(
        'job_id'  => $job_id,
        'message' => esc_html__('Generation job started.', 'aiomatic-automatic-ai-content-writer'),
    ));
}

function aiomatic_super_pages_job_status()
{
    check_ajax_referer('aiomatic_super_pages_nonce', 'nonce');

    if (!current_user_can('access_aiomatic_menu')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to view this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    $job_id = isset($_POST['job_id']) ? sanitize_key(wp_unslash($_POST['job_id'])) : '';
    $job = aiomatic_super_pages_get_job($job_id);

    if (!$job) {
        wp_send_json_error(array(
            'message' => esc_html__('The generation job was not found or expired.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    if ((int) ($job['user_id'] ?? 0) !== get_current_user_id() && !current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to view this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    wp_send_json_success(aiomatic_super_pages_public_job_data($job));
}

function aiomatic_super_pages_cancel_job()
{
    check_ajax_referer('aiomatic_super_pages_nonce', 'nonce');

    if (!current_user_can('access_aiomatic_menu')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to cancel this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    $job_id = isset($_POST['job_id']) ? sanitize_key(wp_unslash($_POST['job_id'])) : '';
    $job = aiomatic_super_pages_get_job($job_id);

    if (!$job) {
        wp_send_json_error(array(
            'message' => esc_html__('The generation job was not found or expired.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    if ((int) ($job['user_id'] ?? 0) !== get_current_user_id() && !current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to cancel this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    aiomatic_super_pages_update_job($job_id, array(
        'status'       => 'cancelled',
        'current_step' => esc_html__('Cancelled', 'aiomatic-automatic-ai-content-writer'),
        'progress'     => 0,
    ));

    delete_transient(aiomatic_super_pages_job_lock_key($job_id));

    wp_send_json_success(array(
        'message' => esc_html__('Generation job cancelled.', 'aiomatic-automatic-ai-content-writer'),
    ));
}

function aiomatic_super_pages_process_job()
{
    check_ajax_referer('aiomatic_super_pages_nonce', 'nonce');

    if (!current_user_can('access_aiomatic_menu')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to process this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    $job_id = isset($_POST['job_id']) ? sanitize_key(wp_unslash($_POST['job_id'])) : '';
    $job = aiomatic_super_pages_get_job($job_id);

    if (!$job) {
        wp_send_json_error(array(
            'message' => esc_html__('The generation job was not found or expired.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    if ((int) ($job['user_id'] ?? 0) !== get_current_user_id() && !current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to process this job.', 'aiomatic-automatic-ai-content-writer'),
        ), 403);
    }

    if (in_array($job['status'], array('completed', 'failed', 'cancelled'), true)) {
        wp_send_json_success(aiomatic_super_pages_public_job_data($job));
    }

    $lock_key = aiomatic_super_pages_job_lock_key($job_id);
    $lock = get_transient($lock_key);

    if ($lock && !aiomatic_super_pages_is_stale_job($job)) {
        wp_send_json_success(aiomatic_super_pages_public_job_data($job));
    }

    set_transient($lock_key, time(), 10 * MINUTE_IN_SECONDS);

    ignore_user_abort(true);

    if (function_exists('set_time_limit')) {
        @set_time_limit(0);
    }

    aiomatic_super_pages_update_job($job_id, array(
        'status'       => 'running',
        'progress'     => max(2, absint($job['progress'] ?? 0)),
        'current_step' => esc_html__('Starting generation...', 'aiomatic-automatic-ai-content-writer'),
        'error'        => '',
    ));

    try {
        $result = aiomatic_super_pages_run_job_payload($job_id, $job['payload']);

        aiomatic_super_pages_update_job($job_id, array(
            'status'       => 'completed',
            'progress'     => 100,
            'current_step' => esc_html__('Completed', 'aiomatic-automatic-ai-content-writer'),
            'result'       => $result,
            'message'      => !empty($result['message']) ? $result['message'] : esc_html__('Generation completed.', 'aiomatic-automatic-ai-content-writer'),
        ));

        delete_transient($lock_key);

        $job = aiomatic_super_pages_get_job($job_id);

        wp_send_json_success(aiomatic_super_pages_public_job_data($job));
    } catch (Throwable $e) {
        aiomatic_super_pages_update_job($job_id, array(
            'status'       => 'failed',
            'current_step' => esc_html__('Failed', 'aiomatic-automatic-ai-content-writer'),
            'error'        => $e->getMessage(),
        ));

        delete_transient($lock_key);

        wp_send_json_error(array(
            'message' => $e->getMessage(),
            'job'     => aiomatic_super_pages_public_job_data(aiomatic_super_pages_get_job($job_id)),
        ));
    }
}

function aiomatic_super_pages_is_stale_job($job)
{
    $updated_at = isset($job['updated_at']) ? absint($job['updated_at']) : 0;

    return $updated_at > 0 && (time() - $updated_at) > 8 * MINUTE_IN_SECONDS;
}

function aiomatic_super_pages_public_job_data($job)
{
    if (!$job || !is_array($job)) {
        return array();
    }

    return array(
        'id'           => sanitize_key($job['id'] ?? ''),
        'status'       => sanitize_key($job['status'] ?? 'unknown'),
        'progress'     => absint($job['progress'] ?? 0),
        'current_step' => sanitize_text_field($job['current_step'] ?? ''),
        'message'      => isset($job['message']) ? wp_kses_post($job['message']) : '',
        'error'        => isset($job['error']) ? wp_kses_post($job['error']) : '',
        'result'       => isset($job['result']) && is_array($job['result']) ? $job['result'] : array(),
        'created_at'   => absint($job['created_at'] ?? 0),
        'updated_at'   => absint($job['updated_at'] ?? 0),
    );
}

function aiomatic_super_pages_extract_urls_from_text($text)
{
    $text = (string) $text;

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

    $urls = array();

    if (preg_match_all('#https?:\/\/[^\s<>"\'\)\]\}]+#i', $text, $matches)) {
        foreach ($matches[0] as $url) {
            $urls[] = rtrim($url, '.,;:!?)>\'"');
        }
    }

    foreach (preg_split('/\r\n|\r|\n/', $text) as $line) {
        $line = trim($line);

        if ($line === '' || preg_match('#\s#', $line)) {
            continue;
        }

        if (preg_match('#^https?:\/\/#i', $line)) {
            $urls[] = rtrim($line, '.,;:!?)>\'"');
        }
    }

    $urls = array_values(array_unique(array_filter($urls)));

    return $urls;
}

function aiomatic_super_pages_is_allowed_scrape_url($url)
{
    $url = esc_url_raw(trim((string) $url));

    if ($url === '' || !filter_var($url, FILTER_VALIDATE_URL)) {
        return false;
    }

    $parsed = wp_parse_url($url);

    if (!is_array($parsed) || empty($parsed['host']) || empty($parsed['scheme'])) {
        return false;
    }

    $scheme = strtolower((string) $parsed['scheme']);

    if (!in_array($scheme, array('http', 'https'), true)) {
        return false;
    }

    $host = strtolower(trim($parsed['host'], '[]'));

    if ($host === '' || in_array($host, array('localhost', '127.0.0.1', '0.0.0.0', '::1'), true)) {
        return false;
    }

    if (preg_match('/(^|\.)local$/', $host)) {
        return false;
    }

    if (filter_var($host, FILTER_VALIDATE_IP)) {
        return (bool) filter_var(
            $host,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
        );
    }

    if (preg_match('/^(10|127)\./', $host) || preg_match('/^192\.168\./', $host) || preg_match('/^169\.254\./', $host) || preg_match('/^172\.(1[6-9]|2[0-9]|3[0-1])\./', $host)) {
        return false;
    }

    return true;
}

function aiomatic_super_pages_get_scrape_method()
{
    $scrape_method = '0';
    $chatbot_settings = get_option('aiomatic_Chatbot_Settings', false);

    if (is_array($chatbot_settings) && !empty($chatbot_settings['scrape_method'])) {
        $scrape_method = trim((string) $chatbot_settings['scrape_method']);
    }

    return $scrape_method;
}

function aiomatic_super_pages_clean_reference_text($content)
{
    $content = wp_strip_all_tags((string) $content);
    $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5, get_bloginfo('charset') ?: 'UTF-8');
    $content = str_replace("\xc2\xa0", ' ', $content);
    $content = preg_replace("/[ \t]+/", ' ', $content);
    $content = preg_replace("/[ \t]*[\r\n]+[ \t]*/", "\n", $content);
    $content = preg_replace("/\n{3,}/", "\n\n", $content);

    return trim($content);
}

function aiomatic_super_pages_extract_html_title($html)
{
    if (!preg_match('/<title[^>]*>(.*?)<\/title>/is', (string) $html, $matches)) {
        return '';
    }

    return aiomatic_super_pages_clean_reference_text($matches[1]);
}

function aiomatic_super_pages_extract_meta_description($html)
{
    if (!preg_match('/<meta[^>]+(?:name|property)=["\'](?:description|og:description|twitter:description)["\'][^>]*>/is', (string) $html, $matches)) {
        return '';
    }

    if (!preg_match('/content=["\']([^"\']+)["\']/is', $matches[0], $content_matches)) {
        return '';
    }

    return aiomatic_super_pages_clean_reference_text($content_matches[1]);
}

function aiomatic_super_pages_trim_reference_text($content, $max_chars)
{
    $max_chars = absint($max_chars);

    if ($max_chars <= 0) {
        return trim((string) $content);
    }

    if (function_exists('aiomatic_strlen') && aiomatic_strlen($content) > $max_chars) {
        return rtrim(aiomatic_substr($content, 0, $max_chars)) . '...';
    }

    if (!function_exists('aiomatic_strlen') && strlen($content) > $max_chars) {
        return rtrim(substr($content, 0, $max_chars)) . '...';
    }

    return trim((string) $content);
}

function aiomatic_super_pages_scrape_url_for_prompt($url, $scrape_method = '0', $max_chars = 8000)
{
    if (!function_exists('aiomatic_scrape_page') || !function_exists('aiomatic_convert_readable_html')) {
        return new WP_Error(
            'missing_scraper',
            esc_html__('The URL scraper is not available.', 'aiomatic-automatic-ai-content-writer')
        );
    }

    $url = esc_url_raw(trim((string) $url));
    $html = aiomatic_scrape_page($url, $scrape_method, 'raw', '');

    if ($html === false || $html === '') {
        return new WP_Error(
            'scrape_failed',
            esc_html__('Could not download page content.', 'aiomatic-automatic-ai-content-writer')
        );
    }

    $readable = aiomatic_convert_readable_html($html);
    $title = '';
    $content = '';

    if (is_array($readable) && !empty($readable[1])) {
        $title = !empty($readable[0]) ? aiomatic_super_pages_clean_reference_text($readable[0]) : '';
        $content = aiomatic_super_pages_clean_reference_text($readable[1]);
    } else {
        $content = aiomatic_super_pages_clean_reference_text($html);
    }

    if ($title === '') {
        $title = aiomatic_super_pages_extract_html_title($html);
    }

    $description = aiomatic_super_pages_extract_meta_description($html);

    if ($content === '' && $description !== '') {
        $content = $description;
    }

    if ($content === '') {
        return new WP_Error(
            'empty_content',
            esc_html__('No readable content could be extracted.', 'aiomatic-automatic-ai-content-writer')
        );
    }

    $content = aiomatic_super_pages_trim_reference_text($content, $max_chars);

    $block = "Reference source: " . $url . "\n";

    if ($title !== '') {
        $block .= 'Title: ' . $title . "\n";
    }

    if ($description !== '') {
        $block .= 'Summary: ' . $description . "\n";
    }

    $block .= "\nExtracted page content for the AI to use as source material:\n";
    $block .= $content . "\nEnd reference source.";

    return $block;
}

function aiomatic_super_pages_prompt_is_url_only($prompt, $urls)
{
    $stripped = trim((string) $prompt);

    foreach ((array) $urls as $url) {
        $stripped = str_replace($url, '', $stripped);
    }

    $stripped = preg_replace('#https?:\/\/[^\s<>"\']+#i', '', $stripped);
    $stripped = preg_replace('/[\r\n\s,;:\.!?\(\)\[\]\{\}<>"\']+/', '', $stripped);

    return $stripped === '';
}

function aiomatic_super_pages_depth_limits($depth)
{
    $depth = sanitize_key($depth);

    switch ($depth) {
        case 'short':
            return array(
                'max_sections'   => 7,
                'max_components' => 6,
            );
        case 'standard':
            return array(
                'max_sections'   => 10,
                'max_components' => 10,
            );
        case 'comprehensive':
        default:
            return array(
                'max_sections'   => 16,
                'max_components' => 14,
            );
    }
}

function aiomatic_super_pages_enrich_prompt_with_urls($prompt, $urls, $job_id = '')
{
    $prompt = trim((string) $prompt);

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

    if (!function_exists('aiomatic_scrape_page') || !function_exists('aiomatic_convert_readable_html')) {
        return $prompt;
    }
    if (empty($urls)) {
        return $prompt;
    }

    $all_urls = array_values($urls);
    $max_urls = max(1, absint(apply_filters('aiomatic_super_pages_max_scrape_urls', 5)));
    $urls = array_slice($all_urls, 0, $max_urls);
    $skipped_urls = array_slice($all_urls, $max_urls);
    $scrape_method = aiomatic_super_pages_get_scrape_method();
    $max_chars = apply_filters('aiomatic_super_pages_scrape_max_chars', 8000);
    $enriched = $prompt;
    $total = count($urls);
    $index = 0;

    foreach ($urls as $url) {
        $index++;

        if (!aiomatic_super_pages_is_allowed_scrape_url($url)) {
            $enriched = str_replace(
                $url,
                '[Skipped URL (not allowed for scraping): ' . $url . ']',
                $enriched
            );
            continue;
        }

        if ($job_id !== '') {
            aiomatic_super_pages_set_job_progress(
                $job_id,
                min(16, 10 + (int) floor(($index / max(1, $total)) * 6)),
                sprintf(
                    __('Scraping reference URL %1$d of %2$d...', 'aiomatic-automatic-ai-content-writer'),
                    $index,
                    $total
                )
            );
        }

        $scraped_block = aiomatic_super_pages_scrape_url_for_prompt($url, $scrape_method, $max_chars);

        if (is_wp_error($scraped_block)) {
            $replacement = sprintf(
                '[Could not scrape content from %1$s: %2$s]',
                $url,
                $scraped_block->get_error_message()
            );
        } else {
            $replacement = $scraped_block;
        }

        $enriched = str_replace($url, $replacement, $enriched);
    }

    foreach ($skipped_urls as $skipped_url) {
        $enriched = str_replace(
            $skipped_url,
            '[Skipped URL because the maximum number of reference URLs was reached: ' . $skipped_url . ']',
            $enriched
        );
    }

    if (aiomatic_super_pages_prompt_is_url_only($prompt, $all_urls)) {
        $enriched = "Create a comprehensive page based on the following reference source(s):\n\n" . trim($enriched);
    }

    return trim($enriched);
}

function aiomatic_super_pages_run_job_payload($job_id, $payload)
{
    if (!class_exists('Aiomatic_Super_Page_Agent')) {
        throw new Exception(esc_html__('Omni Page Agent class is missing.', 'aiomatic-automatic-ai-content-writer'));
    }

    if (!function_exists('aiomatic_super_pages_create_single_page')) {
        throw new Exception(esc_html__('Missing aiomatic_super_pages_create_single_page(). Load the Omni Pages creation helpers before processing jobs.', 'aiomatic-automatic-ai-content-writer'));
    }
    $job = aiomatic_super_pages_get_job($job_id);
    if (($job['status'] ?? '') === 'cancelled') {
        throw new Exception('Job cancelled.');
    }
    $payload = is_array($payload) ? $payload : array();

    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    $model = !empty($payload['model']) ? sanitize_text_field($payload['model']) : '';

    if ($model === '') {
        if (function_exists('aiomatic_get_default_model_name')) {
            $model = aiomatic_get_default_model_name($aiomatic_Main_Settings);
        } else {
            $model = isset($aiomatic_Main_Settings['model']) ? trim((string) $aiomatic_Main_Settings['model']) : 'gpt-4.1';
        }
    }

    $mode = isset($payload['mode']) ? sanitize_key($payload['mode']) : 'single';
    $status = isset($payload['status']) ? sanitize_key($payload['status']) : 'draft';
    $goal = isset($payload['goal']) ? sanitize_key($payload['goal']) : 'auto';
    if (!in_array($goal, array('auto', 'conversions', 'leads', 'education', 'seo'), true)) {
        $goal = 'auto';
    }
    $depth = isset($payload['depth']) ? sanitize_key($payload['depth']) : 'comprehensive';
    if (!in_array($depth, array('short', 'standard', 'comprehensive'), true)) {
        $depth = 'comprehensive';
    }
    $depth_limits = aiomatic_super_pages_depth_limits($depth);
    $original_prompt = isset($payload['prompt']) ? sanitize_textarea_field($payload['prompt']) : '';
    $prompt = $original_prompt;
    $language = isset($payload['language']) ? sanitize_text_field($payload['language']) : 'English';
    $image_source = aiomatic_super_pages_normalize_image_source($payload['include_images'] ?? 'none');
    $allowed_tools = aiomatic_super_pages_allowed_tools_for_image_source($image_source);
    $url_parsing_enabled = array_key_exists('url_parsing_enabled', $payload) ? !empty($payload['url_parsing_enabled']) : true;
    $research_enabled = !empty($payload['research_enabled']);
    $type = isset($payload['type']) ? sanitize_key($payload['type']) : 'page';

    aiomatic_super_pages_set_job_progress($job_id, 8, __('Preparing agent...', 'aiomatic-automatic-ai-content-writer'));

    $reference_urls = $url_parsing_enabled ? aiomatic_super_pages_extract_urls_from_text($original_prompt) : array();

    if ($url_parsing_enabled && !empty($reference_urls)) {
        aiomatic_super_pages_set_job_progress($job_id, 10, __('Scraping reference URLs...', 'aiomatic-automatic-ai-content-writer'));
        $prompt = aiomatic_super_pages_enrich_prompt_with_urls($original_prompt, $reference_urls, $job_id);
    }
    $agent = Aiomatic_Super_Page_Agent::create_virtual(array(
        'model'            => $model,
        'goal'             => $goal,
        'depth'            => $depth,
        'language'         => $language,
        'include_images'   => $image_source,
        'image_source'     => $image_source,
        'research_enabled' => $research_enabled,
        'allowed_tools'    => $allowed_tools,
        'content_format'   => isset($payload['content_format']) ? sanitize_key($payload['content_format']) : 'auto',
        'post_type'        => $type,
        'job_id'           => $job_id,
        'max_sections'     => $depth_limits['max_sections'],
        'max_components'   => $depth_limits['max_components'],
        'temperature'      => min(
            0.55,
            isset($aiomatic_Main_Settings['temperature']) ? floatval($aiomatic_Main_Settings['temperature']) : 0.55
        ),
    ));

    $created_ids = array();

    if ($mode === 'funnel') {
        $page_count = isset($payload['page_count']) ? max(2, min(10, absint($payload['page_count']))) : 3;

        for ($i = 1; $i <= $page_count; $i++) {
            $progress_base = 10 + (int) floor((($i - 1) / $page_count) * 75);

            aiomatic_super_pages_set_job_progress(
                $job_id,
                $progress_base,
                sprintf(__('Generating funnel page %1$d of %2$d...', 'aiomatic-automatic-ai-content-writer'), $i, $page_count)
            );

            $funnel_agent = Aiomatic_Super_Page_Agent::create_virtual(array(
                'model'            => $model,
                'goal'             => $goal,
                'depth'            => $depth,
                'language'         => $language,
                'include_images'   => $image_source,
                'image_source'     => $image_source,
                'research_enabled' => $research_enabled,
                'allowed_tools'    => $allowed_tools,
                'content_format'   => isset($payload['content_format']) ? sanitize_key($payload['content_format']) : 'auto',
                'post_type'        => $type,
                'job_id'           => $job_id,
                'max_sections'     => $depth_limits['max_sections'],
                'max_components'   => $depth_limits['max_components'],
                'temperature'      => min(
                    0.55,
                    isset($aiomatic_Main_Settings['temperature']) ? floatval($aiomatic_Main_Settings['temperature']) : 0.55
                ),
            ));

            $funnel_prompt = $prompt . "\n\nThis is funnel page #" . $i . ". Create a unique funnel step with a distinct strategic purpose.";

            $generated = $funnel_agent->generate(array(
                'prompt'           => $funnel_prompt,
                'goal'             => $goal,
                'language'         => $language,
                'depth'            => $depth,
                'include_images'   => $image_source,
                'image_source'     => $image_source,
                'research_enabled' => $research_enabled,
            ));

            if (is_wp_error($generated)) {
                throw new Exception($generated->get_error_message());
            }

            aiomatic_super_pages_set_job_progress(
                $job_id,
                min(95, $progress_base + 8),
                sprintf(__('Creating funnel page %1$d of %2$d...', 'aiomatic-automatic-ai-content-writer'), $i, $page_count)
            );

            $created = aiomatic_super_pages_create_single_page(
                $generated,
                $status,
                $original_prompt,
                $goal,
                $depth,
                $type
            );

            if (is_wp_error($created)) {
                throw new Exception($created->get_error_message());
            }

            if (!empty($created['pages'][0]['id'])) {
                $created_ids[] = absint($created['pages'][0]['id']);
            }
        }

        if (empty($created_ids)) {
            throw new Exception(esc_html__('No funnel pages could be generated.', 'aiomatic-automatic-ai-content-writer'));
        }

        return aiomatic_super_pages_success_response(
            $created_ids,
            sprintf(
                esc_html__('%d funnel pages generated successfully.', 'aiomatic-automatic-ai-content-writer'),
                count($created_ids)
            )
        );
    }

    aiomatic_super_pages_set_job_progress($job_id, 18, __('Researching and planning the page...', 'aiomatic-automatic-ai-content-writer'));

    $generated = $agent->generate(array(
        'prompt'           => $prompt,
        'goal'             => $goal,
        'language'         => $language,
        'depth'            => $depth,
        'content_format'   => isset($payload['content_format']) ? sanitize_key($payload['content_format']) : 'auto',
        'include_images'   => $image_source,
        'image_source'     => $image_source,
        'research_enabled' => $research_enabled,
        'job_id'           => $job_id
    ));

    if (is_wp_error($generated)) {
        throw new Exception($generated->get_error_message());
    }

    if (empty($generated['blocks']) || !is_array($generated['blocks'])) {
        throw new Exception(esc_html__('The agent did not generate valid Gutenberg blocks.', 'aiomatic-automatic-ai-content-writer'));
    }

    aiomatic_super_pages_set_job_progress($job_id, 88, __('Creating WordPress page...', 'aiomatic-automatic-ai-content-writer'));

    $created = aiomatic_super_pages_create_single_page(
        $generated,
        $status,
        $original_prompt,
        $goal,
        $depth,
        $type
    );

    if (is_wp_error($created)) {
        throw new Exception($created->get_error_message());
    }

    return $created;
}
function aiomatic_super_pages_is_trusted_image_src($url, $attachment_id = 0)
{
    $url = esc_url_raw((string) $url);
    $attachment_id = absint($attachment_id);

    if ($attachment_id > 0 && get_post($attachment_id) && wp_attachment_is_image($attachment_id)) {
        return true;
    }

    if ($url === '') {
        return false;
    }

    $uploads = wp_upload_dir();

    if (!empty($uploads['baseurl']) && strpos($url, $uploads['baseurl']) === 0) {
        $file = str_replace($uploads['baseurl'], $uploads['basedir'], $url);

        return file_exists($file);
    }

    return (bool) apply_filters('aiomatic_super_pages_allow_external_image_url', false, $url, $attachment_id);
}

function aiomatic_super_pages_strip_untrusted_images($block)
{
    if (!is_array($block)) {
        return $block;
    }

    if (!isset($block['attrs']) || !is_array($block['attrs'])) {
        return $block;
    }

    $attrs = $block['attrs'];

    if (!empty($attrs['image_url']) && !aiomatic_super_pages_is_trusted_image_src($attrs['image_url'], $attrs['attachment_id'] ?? 0)) {
        $attrs['image_url'] = '';
        $attrs['attachment_id'] = 0;
    }

    if (!empty($attrs['visual']) && is_array($attrs['visual']) && !empty($attrs['visual']['image_url']) && !aiomatic_super_pages_is_trusted_image_src($attrs['visual']['image_url'], $attrs['visual']['attachment_id'] ?? 0)) {
        $attrs['visual']['image_url'] = '';
        $attrs['visual']['attachment_id'] = 0;
    }

    if (!empty($attrs['items']) && is_array($attrs['items'])) {
        foreach ($attrs['items'] as $index => $item) {
            if (!is_array($item)) {
                continue;
            }

            if (!empty($item['image_url']) && !aiomatic_super_pages_is_trusted_image_src($item['image_url'], $item['attachment_id'] ?? 0)) {
                $attrs['items'][$index]['image_url'] = '';
                $attrs['items'][$index]['attachment_id'] = 0;
            }
        }
    }

    $block['attrs'] = $attrs;

    return $block;
}

function aiomatic_super_pages_block_signature($block)
{
    if (!is_array($block)) {
        return '';
    }

    $component = sanitize_key($block['component'] ?? $block['block'] ?? '');
    $attrs = isset($block['attrs']) && is_array($block['attrs']) ? $block['attrs'] : array();

    if (!in_array($component, array('feature_grid', 'card_grid', 'product_showcase', 'pricing_cards', 'stats', 'testimonial_grid', 'comparison_table', 'pros_cons'), true)) {
        return '';
    }

    $parts = array(
        $component,
        wp_strip_all_tags((string) ($attrs['title'] ?? '')),
        wp_strip_all_tags((string) ($attrs['headline'] ?? '')),
        wp_strip_all_tags((string) ($attrs['subtitle'] ?? '')),
    );

    if (!empty($attrs['items']) && is_array($attrs['items'])) {
        foreach (array_slice($attrs['items'], 0, 8) as $item) {
            if (!is_array($item)) {
                continue;
            }

            $parts[] = wp_strip_all_tags((string) ($item['title'] ?? $item['name'] ?? $item['value'] ?? $item['question'] ?? ''));
        }
    }

    if (!empty($attrs['columns']) && is_array($attrs['columns'])) {
        $column_parts = array();

        foreach ($attrs['columns'] as $column) {
            if (is_array($column)) {
                $column = $column['title'] ?? $column['label'] ?? $column['name'] ?? '';
            }

            if (is_scalar($column)) {
                $column_parts[] = wp_strip_all_tags((string) $column);
            }
        }

        if (!empty($column_parts)) {
            $parts[] = implode('|', $column_parts);
        }
    }

    $signature = trim(strtolower(preg_replace('/\s+/', ' ', implode(' ', array_filter($parts)))));

    return $signature !== '' ? md5($signature) : '';
}

function aiomatic_super_pages_repair_blocks($blocks, $page_data = array())
{
    if (!is_array($blocks)) {
        return array();
    }

    $seen_signatures = array();

    foreach ($blocks as $key => &$block) {

        if (!is_array($block)) {
            unset($blocks[$key]);
            continue;
        }

        $block = aiomatic_super_pages_strip_untrusted_images($block);

        $signature = aiomatic_super_pages_block_signature($block);

        if ($signature !== '') {
            if (isset($seen_signatures[$signature])) {
                unset($blocks[$key]);
                continue;
            }

            $seen_signatures[$signature] = true;
        }

        $component = sanitize_key(
            $block['component'] ?? $block['block'] ?? ''
        );

        $attrs = $block['attrs'] ?? array();

        /*
         * Fix tables
         */
        if ($component === 'comparison_table') {

            if (!empty($attrs['rows'])) {

                foreach ($attrs['rows'] as &$row) {

                    if (!is_array($row)) {
                        continue;
                    }

                    foreach ($row as &$cell) {

                        if (is_array($cell)) {

                            if (isset($cell['value'])) {
                                $cell = (string)$cell['value'];
                            } else {
                                $cell = implode(
                                    ', ',
                                    aiomatic_super_pages_flatten_table_cell_values($cell)
                                );
                            }
                        }
                    }
                }
            }
        }

        /*
         * Remove raw schema
         */
        if (
            $component === 'text' &&
            !empty($attrs['content'])
        ) {

            $content = trim($attrs['content']);

            if (
                strpos($content, '"@context"') !== false ||
                strpos($content, '"@type"') !== false
            ) {
                unset($blocks[$key]);
                continue;
            }
        }

        /*
         * Remove fake ratings
         */
        if (
            $component === 'text' &&
            !empty($attrs['content'])
        ) {

            $attrs['content'] = preg_replace(
                '/"ratingCount"\s*:\s*"[^"]+"/i',
                '',
                $attrs['content']
            );

            $block['attrs'] = $attrs;
        }

        /*
         * Video request but no video component
         */
        if (
            !empty($page_data['intent']) &&
            stripos($page_data['intent'], 'video') !== false
        ) {

            $has_video = false;

            foreach ($blocks as $b) {

                $c = sanitize_key(
                    $b['component'] ?? ''
                );

                if ($c === 'video_embed') {
                    $has_video = true;
                    break;
                }
            }

            if (!$has_video) {

                $blocks[] = array(
                    'component' => 'video_embed',
                    'attrs' => array(
                        'title' => 'Featured Video',
                        'search_query' => $page_data['title'] ?? ''
                    )
                );
            }
        }
    }

    return array_values($blocks);
}
function aiomatic_super_pages_create_single_page($decoded, $status, $prompt, $goal, $depth, $type)
{
    $title = !empty($decoded['title'])
        ? sanitize_text_field($decoded['title'])
        : esc_html__('AI Omni Page', 'aiomatic-automatic-ai-content-writer');

    if (
        empty($decoded['blocks']) ||
        !is_array($decoded['blocks'])
    ) {
        return new WP_Error(
            'aiomatic_super_page_no_blocks',
            esc_html__('No Gutenberg blocks were generated.', 'aiomatic-automatic-ai-content-writer')
        );
    }
    if (!in_array($status, array('draft', 'pending', 'publish'), true)) {
        $status = 'draft';
    }

    if (!in_array($type, array('page', 'post'), true)) {
        $type = 'page';
    }
    $cap = $type === 'page' ? 'edit_pages' : 'edit_posts';

    if (!current_user_can($cap)) {
        return new WP_Error('permission_denied', 'You cannot create this post type.');
    }
    $decoded['blocks'] = aiomatic_super_pages_repair_blocks(
        $decoded['blocks'],
        $decoded
    );
    $post_content = aiomatic_super_pages_render_blocks(
        $decoded['blocks'],
        $decoded
    );

    if (trim($post_content) === '') {
        return new WP_Error(
            'aiomatic_super_page_empty_content',
            esc_html__('The generated Gutenberg content was empty.', 'aiomatic-automatic-ai-content-writer')
        );
    }

    $post_id = wp_insert_post(
        array(
            'post_title'   => $title,
            'post_content' => $post_content,
            'post_status'  => $status,
            'post_type'    => $type,
            'post_excerpt' => !empty($decoded['excerpt'])
                ? sanitize_text_field($decoded['excerpt'])
                : '',
        ),
        true
    );

    if (is_wp_error($post_id)) {
        return $post_id;
    }

    aiomatic_super_pages_save_page_meta(
        $post_id,
        $decoded,
        $prompt,
        $goal,
        $depth,
        $type
    );

    return aiomatic_super_pages_success_response(
        array($post_id),
        esc_html__('Omni Page generated successfully.', 'aiomatic-automatic-ai-content-writer')
    );
}

function aiomatic_super_pages_save_page_meta($post_id, $decoded, $prompt, $goal, $depth, $mode)
{
    update_post_meta($post_id, '_aiomatic_super_page', 'yes');
    update_post_meta($post_id, '_aiomatic_super_page_prompt', wp_strip_all_tags($prompt));
    update_post_meta($post_id, '_aiomatic_super_page_goal', sanitize_key($goal));
    update_post_meta($post_id, '_aiomatic_super_page_depth', sanitize_key($depth));
    update_post_meta($post_id, '_aiomatic_super_page_mode', sanitize_key($mode));

    update_post_meta(
        $post_id,
        '_aiomatic_super_page_blueprint',
        wp_json_encode($decoded)
    );

    if (!empty($decoded['seo_title'])) {

        $seo_title = sanitize_text_field($decoded['seo_title']);

        update_post_meta($post_id, '_aioseo_title', $seo_title);
        update_post_meta($post_id, '_yoast_wpseo_title', $seo_title);
        update_post_meta($post_id, 'rank_math_title', $seo_title);
    }

    if (!empty($decoded['meta_description'])) {

        $meta_description = sanitize_text_field(
            $decoded['meta_description']
        );

        update_post_meta($post_id, '_aioseo_description', $meta_description);
        update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_description);
        update_post_meta($post_id, 'rank_math_description', $meta_description);
    }

    if (!empty($decoded['research'])) {

        update_post_meta(
            $post_id,
            '_aiomatic_super_page_research',
            wp_json_encode($decoded['research'])
        );
    }

    if (!empty($decoded['quality_audit'])) {

        update_post_meta(
            $post_id,
            '_aiomatic_super_page_quality',
            wp_json_encode($decoded['quality_audit'])
        );
    }
}
function aiomatic_super_pages_get_contrast_color($hex)
{
    $hex = ltrim(trim($hex), '#');

    if (strlen($hex) === 3) {
        $hex =
            $hex[0] . $hex[0] .
            $hex[1] . $hex[1] .
            $hex[2] . $hex[2];
    }

    if (strlen($hex) !== 6) {
        return '#ffffff';
    }

    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));

    $brightness =
        (($r * 299) +
        ($g * 587) +
        ($b * 114)) / 1000;

    return $brightness > 160
        ? '#111827'
        : '#ffffff';
}

function aiomatic_super_pages_hex_to_rgb($hex)
{
    $hex = ltrim(trim((string) $hex), '#');

    if (strlen($hex) === 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }

    if (!preg_match('/^[0-9a-fA-F]{6}$/', $hex)) {
        return false;
    }

    return array(
        hexdec(substr($hex, 0, 2)),
        hexdec(substr($hex, 2, 2)),
        hexdec(substr($hex, 4, 2)),
    );
}

function aiomatic_super_pages_rgb_to_hex($r, $g, $b)
{
    return sprintf(
        '#%02x%02x%02x',
        max(0, min(255, (int) round($r))),
        max(0, min(255, (int) round($g))),
        max(0, min(255, (int) round($b)))
    );
}

function aiomatic_super_pages_mix_hex_colors($color, $with, $color_weight = 0.7)
{
    $rgb = aiomatic_super_pages_hex_to_rgb($color);
    $with_rgb = aiomatic_super_pages_hex_to_rgb($with);

    if (!$rgb || !$with_rgb) {
        return $color;
    }

    $color_weight = max(0, min(1, (float) $color_weight));
    $with_weight = 1 - $color_weight;

    return aiomatic_super_pages_rgb_to_hex(
        ($rgb[0] * $color_weight) + ($with_rgb[0] * $with_weight),
        ($rgb[1] * $color_weight) + ($with_rgb[1] * $with_weight),
        ($rgb[2] * $color_weight) + ($with_rgb[2] * $with_weight)
    );
}

function aiomatic_super_pages_color_metrics($hex)
{
    $rgb = aiomatic_super_pages_hex_to_rgb($hex);

    if (!$rgb) {
        return false;
    }

    $max = max($rgb);
    $min = min($rgb);
    $brightness = (($rgb[0] * 299) + ($rgb[1] * 587) + ($rgb[2] * 114)) / 1000;

    return array(
        'max' => $max,
        'min' => $min,
        'spread' => $max - $min,
        'brightness' => $brightness,
    );
}

function aiomatic_super_pages_tame_hex_color($hex, $fallback = '#2563eb', $role = 'primary')
{
    $hex = aiomatic_super_pages_extract_hex_color($hex) ?: $fallback;
    $metrics = aiomatic_super_pages_color_metrics($hex);

    if (!$metrics) {
        return $fallback;
    }

    $looks_neon = $metrics['max'] > 235 && $metrics['spread'] > 170;
    $too_light_for_ui = $metrics['brightness'] > 188;

    if ($role === 'secondary' && ($looks_neon || $too_light_for_ui)) {
        return '#111827';
    }

    if ($looks_neon) {
        return aiomatic_super_pages_mix_hex_colors($hex, '#111827', 0.42);
    }

    if ($too_light_for_ui) {
        return aiomatic_super_pages_mix_hex_colors($hex, '#111827', 0.68);
    }

    return $hex;
}
function aiomatic_super_pages_success_response($post_ids, $message)
{
    $links = array();

    foreach ($post_ids as $post_id) {

        $links[] = array(
            'id'        => $post_id,
            'title'     => get_the_title($post_id),
            'edit_link' => get_edit_post_link($post_id) ?: '',
            'view_link' => get_permalink($post_id),
        );
    }

    $html = '<strong>' . esc_html($message) . '</strong><br><br>';

    foreach ($links as $link) {

        $html .= '<div style="margin-bottom:12px;">';

        $html .= '<strong>' .
            esc_html($link['title']) .
            '</strong><br><br>';

        $html .= '<a class="button button-primary" href="' .
            esc_url($link['edit_link']) .
            '">' .
            esc_html__('Edit Page', 'aiomatic-automatic-ai-content-writer') .
            '</a> ';

        $html .= '<a class="button button-non-primary" target="_blank" href="' .
            esc_url($link['view_link']) .
            '">' .
            esc_html__('View Page', 'aiomatic-automatic-ai-content-writer') .
            '</a>';

        $html .= '</div>';
    }

    return array(
        'message' => $html,
        'pages'   => $links,
    );
}

/**
 * Backward-compatible renderer entry.
 */
function aiomatic_super_pages_render_block($block)
{
    static $registry = null;

    if ($registry === null) {
        $registry = new Aiomatic_Super_Page_Component_Registry();
    }

    if (isset($block['block']) && !isset($block['component'])) {
        $block['component'] = $block['block'];
    }

    global $aiomatic_super_pages_current_section_id, $aiomatic_super_pages_current_section_aliases;

    $previous_section_id = $aiomatic_super_pages_current_section_id ?? '';
    $previous_section_aliases = $aiomatic_super_pages_current_section_aliases ?? array();
    $aiomatic_super_pages_current_section_id = isset($block['attrs']['section_id'])
        ? sanitize_title((string) $block['attrs']['section_id'])
        : '';
    $aiomatic_super_pages_current_section_aliases = isset($block['attrs']['section_aliases']) && is_array($block['attrs']['section_aliases'])
        ? array_values(array_unique(array_filter(array_map('sanitize_title', $block['attrs']['section_aliases']))))
        : array();

    $html = $registry->render($block);
    $aiomatic_super_pages_current_section_id = $previous_section_id;
    $aiomatic_super_pages_current_section_aliases = $previous_section_aliases;

    return $html;
}



/**
 * Component render helpers.
 */
function aiomatic_super_pages_component_section_start($class)
{
    global $aiomatic_super_pages_current_section_id, $aiomatic_super_pages_current_section_aliases;

    $section_id = !empty($aiomatic_super_pages_current_section_id)
        ? sanitize_title((string) $aiomatic_super_pages_current_section_id)
        : '';

    $attrs = array(
        'className' => $class,
        'layout'    => array('type' => 'constrained'),
    );

    if ($section_id !== '') {
        $attrs['anchor'] = $section_id;
    }

    $id_attr = $section_id !== '' ? ' id="' . esc_attr($section_id) . '"' : '';

    $alias_html = '';
    $aliases = is_array($aiomatic_super_pages_current_section_aliases ?? null)
        ? $aiomatic_super_pages_current_section_aliases
        : array();

    foreach ($aliases as $alias) {
        $alias = sanitize_title((string) $alias);

        if ($alias === '' || $alias === $section_id) {
            continue;
        }

        $alias_html .= '<!-- wp:html --><span id="' . esc_attr($alias) . '" class="aiomatic-super-anchor"></span><!-- /wp:html -->';
    }

    $wrapper_class = trim('wp-block-group ' . $class . ' is-layout-constrained wp-block-group-is-layout-constrained');

    return '<!-- wp:group ' . wp_json_encode($attrs) . ' --><div' . $id_attr . ' class="' . esc_attr($wrapper_class) . '">' . $alias_html;
}

function aiomatic_super_pages_component_section_end()
{
    return '</div><!-- /wp:group -->';
}

function aiomatic_super_pages_render_component_heading($title, $level = 2, $align = '')
{
    if ($title === '') {
        return '';
    }

    $level = max(1, min(6, absint($level)));
    $align_class = $align ? ' class="has-text-align-' . esc_attr($align) . '"' : '';
    $comment = $align ? ' {"level":' . $level . ',"textAlign":"' . esc_attr($align) . '"}' : ' {"level":' . $level . '}';

    return '<!-- wp:heading' . $comment . ' --><h' . $level . $align_class . '>' . esc_html($title) . '</h' . $level . '><!-- /wp:heading -->';
}

function aiomatic_super_pages_render_component_paragraph($content, $align = '')
{
    $content = trim((string)$content);

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

    $standalone_button = aiomatic_super_pages_extract_standalone_button($content);

    if ($standalone_button) {
        return aiomatic_super_pages_render_component_buttons(array($standalone_button));
    }

    $content_with_buttons = aiomatic_super_pages_extract_embedded_buttons($content);

    if ($content_with_buttons) {
        $html = '';

        if ($content_with_buttons['content'] !== '') {
            $html .= aiomatic_super_pages_render_component_paragraph($content_with_buttons['content'], $align);
        }

        $html .= aiomatic_super_pages_render_component_buttons($content_with_buttons['buttons']);

        return $html;
    }

    if (
        preg_match(
            '/<(ul|ol|table|div|figure|h1|h2|h3|h4|h5|h6|blockquote|pre)\b/i',
            $content
        )
    ) {
        return '<!-- wp:html -->' .
               wp_kses_post($content) .
               '<!-- /wp:html -->';
    }

    if (preg_match('/<\/?p\b/i', $content)) {
        return aiomatic_super_pages_render_component_paragraph_tags($content, $align);
    }

    if (aiomatic_super_pages_plain_text_needs_structure($content)) {
        return aiomatic_super_pages_render_structured_plain_text($content, $align);
    }

    return aiomatic_super_pages_render_component_paragraph_block($content, $align);
}

function aiomatic_super_pages_plain_text_needs_structure($content)
{
    $content = trim((string) $content);

    if ($content === '' || strpos($content, "\n") === false) {
        return false;
    }

    if (preg_match('/^\s*(?:[•\-\*]|\d+[\.\)])\s+/m', $content)) {
        return true;
    }

    if (preg_match('/\n\s*\n/', $content)) {
        return true;
    }

    return preg_match('/^[A-Z][A-Za-z0-9 &,\/\-\(\)]+$/m', $content) === 1;
}

function aiomatic_super_pages_render_structured_plain_text($content, $align = '')
{
    $content = trim(str_replace(array("\r\n", "\r"), "\n", (string) $content));

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

    $lines = explode("\n", $content);
    $html = '';
    $paragraph = array();
    $list_items = array();

    $flush_paragraph = function () use (&$html, &$paragraph, $align) {
        if (empty($paragraph)) {
            return;
        }

        $text = trim(implode(' ', array_map('trim', $paragraph)));
        $paragraph = array();

        if ($text !== '') {
            $html .= aiomatic_super_pages_render_component_paragraph_block($text, $align);
        }
    };

    $flush_list = function () use (&$html, &$list_items) {
        if (empty($list_items)) {
            return;
        }

        $html .= '<!-- wp:list --><ul>';

        foreach ($list_items as $item) {
            $item = trim((string) $item);

            if ($item !== '') {
                $html .= '<li>' . wp_kses_post($item) . '</li>';
            }
        }

        $html .= '</ul><!-- /wp:list -->';
        $list_items = array();
    };

    foreach ($lines as $line) {
        $line = trim((string) $line);

        if ($line === '') {
            $flush_paragraph();
            $flush_list();
            continue;
        }

        if (preg_match('/^(?:[•\-\*]|\d+[\.\)])\s*(.+)$/u', $line, $match)) {
            $flush_paragraph();
            $list_items[] = trim($match[1]);
            continue;
        }

        if (aiomatic_super_pages_plain_text_line_is_subheading($line)) {
            $flush_paragraph();
            $flush_list();
            $html .= aiomatic_super_pages_render_component_heading($line, 3);
            continue;
        }

        $flush_list();
        $paragraph[] = $line;
    }

    $flush_paragraph();
    $flush_list();

    return $html;
}

function aiomatic_super_pages_plain_text_line_is_subheading($line)
{
    $line = trim((string) $line);

    if ($line === '') {
        return false;
    }

    if (strlen($line) > 90 || preg_match('/[.!?]$/', $line)) {
        return false;
    }

    if (preg_match('/[:;]$/', $line)) {
        return true;
    }

    $word_count = str_word_count(wp_strip_all_tags($line));

    if ($word_count < 1 || $word_count > 8) {
        return false;
    }

    return preg_match('/^[A-Z0-9][A-Za-z0-9 &,\/\-\(\)]+$/', $line) === 1;
}

function aiomatic_super_pages_render_component_paragraph_tags($content, $align = '')
{
    $content = trim((string)$content);

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

    $balanced = function_exists('force_balance_tags')
        ? force_balance_tags($content)
        : $content;

    if (preg_match_all('/<p\b[^>]*>(.*?)<\/p>/is', $balanced, $matches, PREG_SET_ORDER)) {
        $outside = preg_replace('/<p\b[^>]*>.*?<\/p>/is', '', $balanced);
        $outside = preg_replace('/(?:\s|&nbsp;|<br\s*\/?>)+/i', '', (string)$outside);

        if (trim((string)$outside) === '') {
            $html = '';

            foreach ($matches as $match) {
                $inner = trim($match[1]);

                if ($inner === '') {
                    continue;
                }

                $standalone_button = aiomatic_super_pages_extract_standalone_button($inner);

                if ($standalone_button) {
                    $html .= aiomatic_super_pages_render_component_buttons(array($standalone_button));
                    continue;
                }

                $content_with_buttons = aiomatic_super_pages_extract_embedded_buttons($inner);

                if ($content_with_buttons) {
                    if ($content_with_buttons['content'] !== '') {
                        $html .= aiomatic_super_pages_render_component_paragraph($content_with_buttons['content'], $align);
                    }

                    $html .= aiomatic_super_pages_render_component_buttons($content_with_buttons['buttons']);
                    continue;
                }

                $html .= aiomatic_super_pages_render_component_paragraph_block($inner, $align);
            }

            return $html;
        }
    }

    $content = preg_replace('/<\/?p\b[^>]*>/i', '', $balanced);
    $standalone_button = aiomatic_super_pages_extract_standalone_button($content);

    if ($standalone_button) {
        return aiomatic_super_pages_render_component_buttons(array($standalone_button));
    }

    $content_with_buttons = aiomatic_super_pages_extract_embedded_buttons($content);

    if ($content_with_buttons) {
        $html = '';

        if ($content_with_buttons['content'] !== '') {
            $html .= aiomatic_super_pages_render_component_paragraph($content_with_buttons['content'], $align);
        }

        $html .= aiomatic_super_pages_render_component_buttons($content_with_buttons['buttons']);

        return $html;
    }

    return aiomatic_super_pages_render_component_paragraph_block($content, $align);
}

function aiomatic_super_pages_render_component_paragraph_block($content, $align = '')
{
    $content = trim((string)$content);

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

    $align_class = $align
        ? ' class="has-text-align-' . esc_attr($align) . '"'
        : '';

    $comment = $align
        ? ' {"align":"' . esc_attr($align) . '"}'
        : '';

    return '<!-- wp:paragraph' . $comment . ' --><p' .
           $align_class .
           '>' .
           wp_kses_post($content) .
           '</p><!-- /wp:paragraph -->';
}

function aiomatic_super_pages_extract_standalone_button($html)
{
    $html = trim((string)$html);

    if ($html === '') {
        return false;
    }

    if (preg_match('/^<a\b([^>]*)>(.*?)<\/a>$/is', $html, $match)) {
        $class = aiomatic_super_pages_extract_html_attr($match[1], 'class');

        if (!preg_match('/\b(button|btn|wp-element-button|wp-block-button__link)\b/i', $class)) {
            return false;
        }

        $label = trim(wp_strip_all_tags($match[2]));

        if ($label === '') {
            return false;
        }

        $url = aiomatic_super_pages_extract_html_attr($match[1], 'href');

        return array(
            'label' => sanitize_text_field($label),
            'url'   => $url !== '' ? $url : '#',
        );
    }

    if (preg_match('/^<button\b([^>]*)>(.*?)<\/button>$/is', $html, $match)) {
        $label = trim(wp_strip_all_tags($match[2]));

        if ($label === '') {
            return false;
        }

        $url = aiomatic_super_pages_extract_html_attr($match[1], 'data-url');

        return array(
            'label' => sanitize_text_field($label),
            'url'   => $url !== '' ? $url : '#',
        );
    }

    return false;
}

function aiomatic_super_pages_extract_embedded_buttons($html)
{
    $html = trim((string) $html);

    if ($html === '' || !preg_match('/<(?:a|button)\b/i', $html)) {
        return false;
    }

    $buttons = array();
    $content = preg_replace_callback(
        '/<(a|button)\b([^>]*)>(.*?)<\/\1>/is',
        function ($match) use (&$buttons) {
            $tag = strtolower($match[1]);
            $attrs = $match[2];
            $label = trim(wp_strip_all_tags($match[3]));

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

            if ($tag === 'a') {
                $class = aiomatic_super_pages_extract_html_attr($attrs, 'class');
                $href = aiomatic_super_pages_extract_html_attr($attrs, 'href');

                if (!preg_match('/\b(button|btn|wp-element-button|wp-block-button__link)\b/i', $class) && $href === '') {
                    return $match[0];
                }

                $buttons[] = array(
                    'label' => sanitize_text_field($label),
                    'url'   => $href !== '' ? $href : '#',
                );

                return '';
            }

            $url = aiomatic_super_pages_extract_html_attr($attrs, 'data-url');

            $buttons[] = array(
                'label' => sanitize_text_field($label),
                'url'   => $url !== '' ? $url : '#',
            );

            return '';
        },
        $html
    );

    if (empty($buttons)) {
        return false;
    }

    $content = trim(preg_replace('/(?:\s|&nbsp;|<br\s*\/?>)+$/i', '', (string) $content));

    return array(
        'content' => $content,
        'buttons' => array_slice($buttons, 0, 3),
    );
}

function aiomatic_super_pages_extract_html_attr($attributes, $name)
{
    $attributes = ' ' . (string)$attributes;
    $name = preg_quote($name, '/');

    if (preg_match('/\s' . $name . '\s*=\s*(["\'])(.*?)\1/is', $attributes, $match)) {
        return html_entity_decode($match[2], ENT_QUOTES | ENT_HTML5, get_bloginfo('charset') ?: 'UTF-8');
    }

    if (preg_match('/\s' . $name . '\s*=\s*([^\s"\'>]+)/is', $attributes, $match)) {
        return html_entity_decode($match[1], ENT_QUOTES | ENT_HTML5, get_bloginfo('charset') ?: 'UTF-8');
    }

    return '';
}

function aiomatic_super_pages_render_component_buttons($buttons, $variant = 'default')
{
    if (empty($buttons) || !is_array($buttons)) {
        return '';
    }

    $variant = sanitize_key($variant ?: 'default');
    $wrapper_class = 'wp-block-buttons aiomatic-super-buttons aiomatic-super-buttons-' . $variant;

    $html = '<!-- wp:buttons -->';
    $html .= '<div class="' . esc_attr($wrapper_class) . '">';

    foreach ($buttons as $index => $button) {

        if (empty($button['label'])) {
            continue;
        }

        $url = !empty($button['url']) ? esc_url($button['url']) : '#';

        $classes = array(
            'aiomatic-super-button',
            $index === 0 ? 'aiomatic-super-button-primary' : 'aiomatic-super-button-secondary',
        );

        if (!empty($button['class'])) {
            foreach (preg_split('/\s+/', (string) $button['class']) as $extra_class) {
                $extra_class = sanitize_html_class($extra_class);

                if ($extra_class !== '') {
                    $classes[] = $extra_class;
                }
            }
        }

        $class = implode(' ', array_unique($classes));

        $html .= '<!-- wp:button {"className":"' . esc_attr($class) . '"} -->';
        $html .= '<div class="wp-block-button ' . esc_attr($class) . '">';
        $html .= '<a class="wp-block-button__link wp-element-button" href="' . $url . '">';
        $html .= esc_html($button['label']);
        $html .= '</a>';
        $html .= '</div>';
        $html .= '<!-- /wp:button -->';
    }

    $html .= '</div>';
    $html .= '<!-- /wp:buttons -->';

    return $html;
}

function aiomatic_super_pages_render_component_icon($icon)
{
    $icon = trim((string) $icon);

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

    $key = sanitize_key($icon);
    $symbols = array(
        'check' => '&#10003;',
        'checkmark' => '&#10003;',
        'cross' => '&#10005;',
        'x' => '&#10005;',
        'close' => '&#10005;',
        'star' => '&#9733;',
        'plus' => '+',
        'minus' => '-',
    );

    $symbol = isset($symbols[$key]) ? $symbols[$key] : esc_html(aiomatic_substr($icon, 0, 2));
    $label = ucwords(str_replace(array('-', '_'), ' ', $key ?: $icon));

    return '<!-- wp:html --><span class="aiomatic-super-icon" aria-label="' . esc_attr($label) . '">' . $symbol . '</span><!-- /wp:html -->';
}

function aiomatic_super_pages_render_component_hero($attrs)
{
    $eyebrow = !empty($attrs['eyebrow']) ? sanitize_text_field($attrs['eyebrow']) : '';
    $headline = !empty($attrs['headline']) ? sanitize_text_field($attrs['headline']) : __('Build Better Pages With AI', 'aiomatic-automatic-ai-content-writer');
    $subheadline = !empty($attrs['subheadline']) ? wp_kses_post($attrs['subheadline']) : '';
    $primary_cta = !empty($attrs['primary_cta']) ? sanitize_text_field($attrs['primary_cta']) : __('Get Started', 'aiomatic-automatic-ai-content-writer');
    $primary_url = !empty($attrs['primary_cta_url']) ? esc_url($attrs['primary_cta_url']) : '#';
    $secondary_cta = !empty($attrs['secondary_cta']) ? sanitize_text_field($attrs['secondary_cta']) : '';
    $secondary_url = !empty($attrs['secondary_cta_url']) ? esc_url($attrs['secondary_cta_url']) : '#';
    $layout = sanitize_key($attrs['layout_variant'] ?? 'hero_split');
    $section_class = 'aiomatic-super-section aiomatic-super-hero aiomatic-super-hero--' . $layout;

    $buttons = array(
        array(
            'label' => $primary_cta,
            'url' => $primary_url,
            'class' => 'aiomatic-btn-primary'
        )
    );
    if ($secondary_cta !== '') {
        $buttons[] = array(
            'label' => $secondary_cta,
            'url' => $secondary_url,
            'class' => 'aiomatic-btn-secondary'
        );
    }

    $image_html = '';
    if (
        !empty($attrs['visual']) &&
        is_array($attrs['visual']) &&
        !empty($attrs['visual']['image_url'])
    ) {
        $image_html = aiomatic_super_pages_render_gutenberg_image(
            $attrs['visual']['image_url'],
            $headline,
            intval($attrs['visual']['attachment_id'] ?? 0)
        );
    } elseif (!empty($attrs['media_component']) && is_array($attrs['media_component'])) {
        $image_html = aiomatic_super_pages_render_block($attrs['media_component']);
    }

    $copy_html = '';
    if ($eyebrow !== '') {
        $copy_html .= aiomatic_super_pages_render_component_paragraph('<strong>' . esc_html($eyebrow) . '</strong>');
    }
    $copy_html .= aiomatic_super_pages_render_component_heading($headline, 1);
    $copy_html .= aiomatic_super_pages_render_component_paragraph($subheadline);
    $copy_html .= aiomatic_super_pages_render_component_buttons($buttons);

    $html = aiomatic_super_pages_component_section_start($section_class);

    if ($layout === 'hero_split' && $image_html !== '') {
        $html .= '<!-- wp:columns {"verticalAlignment":"center"} --><div class="wp-block-columns are-vertically-aligned-center aiomatic-super-hero-columns">';
        $html .= '<!-- wp:column {"verticalAlignment":"center","width":"55%"} --><div class="wp-block-column is-vertically-aligned-center" style="flex-basis:55%">';
        $html .= $copy_html;
        $html .= '</div><!-- /wp:column -->';
        $html .= '<!-- wp:column {"verticalAlignment":"center","width":"45%"} --><div class="wp-block-column is-vertically-aligned-center" style="flex-basis:45%">';
        $html .= $image_html;
        $html .= '</div><!-- /wp:column -->';
        $html .= '</div><!-- /wp:columns -->';
    } else {
        $html .= $copy_html;
        if ($image_html !== '') {
            $html .= $image_html;
        }
    }

    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}
function aiomatic_super_pages_render_gutenberg_image($url, $alt = '', $attachment_id = 0)
{
    $attachment_id = absint($attachment_id);
    $url = esc_url_raw((string) $url);

    if ($url === '' && $attachment_id > 0) {
        $url = esc_url_raw((string) wp_get_attachment_url($attachment_id));
    }

    if (!aiomatic_super_pages_is_trusted_image_src($url, $attachment_id)) {
        return '';
    }

    if (function_exists('aiomatic_sanitize_image_src')) {
        $url = aiomatic_sanitize_image_src($url);
        if ($url === false) return '';
    } else {
        $url = esc_url_raw($url);
    }

    $alt = trim(wp_strip_all_tags((string) $alt));
    $attrs = array();
    $image_class = '';
    $figure_class = 'wp-block-image';

    if ($attachment_id > 0 && get_post($attachment_id) && wp_attachment_is_image($attachment_id)) {
        $medium_url = wp_get_attachment_image_url($attachment_id, 'medium');

        if ($medium_url) {
            $url = esc_url_raw((string) $medium_url);
        }

        $attrs = array(
            'id' => $attachment_id,
            'sizeSlug' => 'medium',
            'linkDestination' => 'none',
        );
        $image_class = ' class="wp-image-' . absint($attachment_id) . '"';
        $figure_class .= ' size-medium';
    }

    $json = !empty($attrs) ? ' ' . wp_json_encode($attrs) : '';

    return '<!-- wp:image' . $json . ' -->'
         . '<figure class="' . esc_attr($figure_class) . '">'
         . '<img src="' . esc_url($url) . '" alt="' . esc_attr($alt) . '"' . $image_class . '/>'
         . '</figure>'
         . '<!-- /wp:image -->';
}
function aiomatic_super_pages_render_component_section_heading($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $eyebrow = !empty($attrs['eyebrow']) ? sanitize_text_field($attrs['eyebrow']) : '';
    $align = !empty($attrs['align']) ? sanitize_key($attrs['align']) : 'center';

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-section-heading');

    if ($eyebrow !== '') {
        $html .= aiomatic_super_pages_render_component_paragraph('<strong>' . esc_html($eyebrow) . '</strong>', $align);
    }

    $html .= aiomatic_super_pages_render_component_heading($title, 2, $align);
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle, $align);
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_text($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $layout = sanitize_key($attrs['layout_variant'] ?? 'minimal_text');
    $section_class = 'aiomatic-super-section aiomatic-super-text aiomatic-super-text--' . $layout;

    $html = aiomatic_super_pages_component_section_start($section_class);
    if ($title !== '') {
        $html .= aiomatic_super_pages_render_component_heading($title, 2);
    }
    $html .= aiomatic_super_pages_render_component_paragraph($content);
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_table_of_contents($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('In this guide', 'aiomatic-automatic-ai-content-writer');
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-toc');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:list {"ordered":true} --><ol class="aiomatic-super-toc-list">';

    foreach ($items as $item) {
        if (is_string($item)) {
            $label = sanitize_text_field($item);
            $target = '';
        } elseif (is_array($item)) {
            $label = !empty($item['label']) ? sanitize_text_field($item['label']) : sanitize_text_field($item['title'] ?? '');
            $target = !empty($item['target']) ? sanitize_title((string) $item['target']) : sanitize_title($label);
        } else {
            continue;
        }

        if ($label === '') {
            continue;
        }

        $html .= '<li>';
        $html .= $target !== ''
            ? '<a href="#' . esc_attr($target) . '">' . esc_html($label) . '</a>'
            : esc_html($label);
        $html .= '</li>';
    }

    $html .= '</ol><!-- /wp:list -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_editorial_summary($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('Key Takeaways', 'aiomatic-automatic-ai-content-writer');
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items && !empty($attrs['content'])) {
        $items = array($attrs['content']);
    }

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-editorial-summary');
    $html .= '<!-- wp:group {"className":"aiomatic-super-editorial-summary-box"} --><div class="wp-block-group aiomatic-super-editorial-summary-box">';
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:list --><ul>';

    foreach ($items as $item) {
        $text = is_array($item)
            ? sanitize_text_field($item['text'] ?? $item['label'] ?? '')
            : sanitize_text_field($item);

        if ($text !== '') {
            $html .= '<li>' . esc_html($text) . '</li>';
        }
    }

    $html .= '</ul><!-- /wp:list -->';
    $html .= '</div><!-- /wp:group -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_card_grid($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-card-grid');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle, 'center');
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach ($items as $item) {

        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= '<!-- wp:group {"className":"aiomatic-super-card"} -->';
        $html .= '<div class="wp-block-group aiomatic-super-card">';

        if (!empty($item['image_url'])) {
            $html .= aiomatic_super_pages_render_gutenberg_image(
                $item['image_url'],
                $item['title'],
                intval($item['attachment_id'] ?? 0)
            );
        }
        elseif (
            !empty($item['icon']) &&
            filter_var($item['icon'], FILTER_VALIDATE_URL)
        ) {

            $html .= aiomatic_super_pages_render_gutenberg_image(
                $item['icon'],
                $item['title']
            );
        }
        elseif (!empty($item['icon'])) {
            $html .= aiomatic_super_pages_render_component_icon($item['icon']);
        }

        $html .= aiomatic_super_pages_render_component_heading(
            !empty($item['title']) ? $item['title'] : '',
            3
        );

        $html .= aiomatic_super_pages_render_component_paragraph(
            !empty($item['content']) ? $item['content'] : ''
        );
        $html .= '</div>';
        $html .= '<!-- /wp:group -->';
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_icon_list($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-icon-list');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:list --><ul>';

    foreach ($items as $item) {
        $icon = !empty($item['icon']) ? esc_html($item['icon']) . ' ' : '';
        $text = !empty($item['text']) ? wp_kses_post($item['text']) : '';
        if ($text !== '') {
            $html .= '<li>' . $icon . $text . '</li>';
        }
    }

    $html .= '</ul><!-- /wp:list -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_steps($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('How It Works', 'aiomatic-automatic-ai-content-writer');
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-steps');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle);
    $html .= '<!-- wp:list {"ordered":true} --><ol>';

    foreach ($items as $item) {
        $step_title = !empty($item['title']) ? '<strong>' . esc_html($item['title']) . '</strong>' : '';
        $step_content = !empty($item['content']) ? '<br>' . wp_kses_post($item['content']) : '';
        if ($step_title || $step_content) {
            $html .= '<li>' . $step_title . $step_content . '</li>';
        }
    }

    $html .= '</ol><!-- /wp:list -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_timeline($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-timeline');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);

    foreach ($items as $item) {
        $date = !empty($item['date']) ? sanitize_text_field($item['date']) : '';
        $item_title = !empty($item['title']) ? sanitize_text_field($item['title']) : '';
        $content = !empty($item['content']) ? wp_kses_post($item['content']) : '';

        $html .= '<!-- wp:group {"className":"aiomatic-super-timeline-item"} --><div class="wp-block-group aiomatic-super-timeline-item">';
        if ($date !== '') {
            $html .= aiomatic_super_pages_render_component_paragraph('<strong>' . esc_html($date) . '</strong>');
        }
        $html .= aiomatic_super_pages_render_component_heading($item_title, 3);
        $html .= aiomatic_super_pages_render_component_paragraph($content);
        $html .= '</div><!-- /wp:group -->';
    }

    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_stats($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-stats');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach ($items as $item) {
        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= aiomatic_super_pages_render_component_heading(!empty($item['value']) ? $item['value'] : '', 2, 'center');
        $html .= aiomatic_super_pages_render_component_paragraph(!empty($item['label']) ? $item['label'] : '', 'center');
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_logo_cloud($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-logo-cloud');

    if ($title !== '') {
        $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    }

    if ($subtitle !== '') {
        $html .= aiomatic_super_pages_render_component_paragraph($subtitle, 'center');
    }

    $html .= '<!-- wp:group {"className":"aiomatic-super-logo-grid"} --><div class="wp-block-group aiomatic-super-logo-grid">';

    foreach ($items as $item) {
        if (!is_array($item)) {
            continue;
        }

        $name = !empty($item['name']) ? sanitize_text_field($item['name']) : '';
        $tagline = !empty($item['tagline']) ? sanitize_text_field($item['tagline']) : '';
        $image_url = !empty($item['image_url']) ? esc_url_raw($item['image_url']) : '';
        $attachment_id = !empty($item['attachment_id']) ? absint($item['attachment_id']) : 0;
        $image = '';

        if ($name === '' && $image_url === '') {
            continue;
        }

        $html .= '<!-- wp:group {"className":"aiomatic-super-logo-mark"} --><div class="wp-block-group aiomatic-super-logo-mark">';

        if ($image_url !== '') {
            $image = aiomatic_super_pages_render_image($image_url, $attachment_id, $name);

            if ($image !== '') {
                $html .= '<!-- wp:html --><figure class="aiomatic-super-logo-image">' . $image . '</figure><!-- /wp:html -->';
            }
        }

        if ($image === '') {
            $html .= '<span class="aiomatic-super-logo-name">' . esc_html($name) . '</span>';

            if ($tagline !== '') {
                $html .= '<span class="aiomatic-super-logo-tagline">' . esc_html($tagline) . '</span>';
            }
        }

        $html .= '</div><!-- /wp:group -->';
    }

    $html .= '</div><!-- /wp:group -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_testimonials($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('Testimonials', 'aiomatic-automatic-ai-content-writer');
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-testimonials');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle, 'center');
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach ($items as $item) {
        $quote = !empty($item['quote']) ? wp_kses_post($item['quote']) : '';
        $name = !empty($item['name']) ? sanitize_text_field($item['name']) : '';
        $role = !empty($item['role']) ? sanitize_text_field($item['role']) : '';

        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= '<!-- wp:quote --><blockquote class="wp-block-quote">';
        if ($quote !== '') {
            $html .= '<p>' . $quote . '</p>';
        }
        if ($name !== '') {
            $html .= '<cite>' . esc_html($name . ($role ? ' - ' . $role : '')) . '</cite>';
        }
        $html .= '</blockquote><!-- /wp:quote -->';
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_highlight_box($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';

    if ($title === '' && $content === '') {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-highlight');
    $html .= '<!-- wp:group {"className":"aiomatic-super-highlight-box"} --><div class="wp-block-group aiomatic-super-highlight-box">';
    $html .= aiomatic_super_pages_render_component_heading($title, 3);
    $html .= aiomatic_super_pages_render_component_paragraph($content);
    $html .= '</div><!-- /wp:group -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_comparison_table($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $columns = !empty($attrs['columns']) && is_array($attrs['columns']) ? $attrs['columns'] : array();
    $rows = !empty($attrs['rows']) && is_array($attrs['rows']) ? $attrs['rows'] : array();

    if (!$columns || !$rows) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-comparison');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:table {"className":"aiomatic-super-table"} --><figure class="wp-block-table aiomatic-super-table"><table><thead><tr>';

    foreach ($columns as $column) {
        $html .= '<th>' . aiomatic_super_pages_table_cell($column) . '</th>';
    }

    $html .= '</tr></thead><tbody>';

    foreach ($rows as $row) {
        if (!is_array($row)) {
            continue;
        }

        $html .= '<tr>';
        foreach (aiomatic_super_pages_normalize_table_row($row, $columns) as $cell) {
            $html .= '<td>' . aiomatic_super_pages_table_cell($cell) . '</td>';
        }
        $html .= '</tr>';
    }

    $html .= '</tbody></table></figure><!-- /wp:table -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_normalize_table_row($row, $columns)
{
    $normalized = array();
    $is_assoc = array_keys($row) !== range(0, count($row) - 1);

    if ($is_assoc) {
        foreach ($columns as $column) {
            $key = is_scalar($column) ? (string) $column : '';
            $normalized[] = $key !== '' && array_key_exists($key, $row) ? $row[$key] : '';
        }

        return $normalized;
    }

    $cells = array_values($row);
    $column_count = count($columns);

    for ($i = 0; $i < $column_count; $i++) {
        $normalized[] = $cells[$i] ?? '';
    }

    return $normalized;
}

function aiomatic_super_pages_flatten_table_cell_values($value)
{
    $values = array();

    foreach ((array) $value as $item) {
        if (is_array($item)) {
            $values = array_merge($values, aiomatic_super_pages_flatten_table_cell_values($item));
            continue;
        }

        if (is_object($item)) {
            $item = wp_json_encode($item);
        }

        if (is_scalar($item)) {
            $item = trim((string) $item);

            if ($item !== '') {
                $values[] = $item;
            }
        }
    }

    return $values;
}

function aiomatic_super_pages_table_cell($cell)
{
    if (is_array($cell)) {

        if (!empty($cell['button']) || !empty($cell['button_url']) || !empty($cell['url'])) {
            return aiomatic_super_pages_render_table_button(
                $cell['button'] ?? $cell['label'] ?? __('View Details', 'aiomatic-automatic-ai-content-writer'),
                $cell['button_url'] ?? $cell['url'] ?? '#'
            );
        }

        if (isset($cell['value'])) {
            $cell = $cell['value'];
        } else {
            $cell = implode(
                ', ',
                aiomatic_super_pages_flatten_table_cell_values($cell)
            );
        }
    }

    if (is_object($cell)) {
        $cell = wp_json_encode($cell);
    }

    return aiomatic_super_pages_format_table_cell((string) $cell);
}

function aiomatic_super_pages_render_table_button($label, $url = '#')
{
    $label = sanitize_text_field(wp_strip_all_tags((string) $label));
    $url = trim((string) $url);

    if ($label === '') {
        $label = __('View Details', 'aiomatic-automatic-ai-content-writer');
    }

    if ($url === '' || $url === '#') {
        $url = '#get-started';
    }

    return '<a class="aiomatic-super-table-button" href="' . esc_url($url) . '">' . esc_html($label) . '</a>';
}

function aiomatic_super_pages_format_table_cell($cell)
{
    $cell = trim(html_entity_decode((string) $cell, ENT_QUOTES | ENT_HTML5, get_bloginfo('charset') ?: 'UTF-8'));

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

    if (preg_match('/<a\b([^>]*)>(.*?)<\/a>/is', $cell, $match)) {
        $label = trim(wp_strip_all_tags($match[2]));
        $url = aiomatic_super_pages_extract_html_attr($match[1], 'href');

        return aiomatic_super_pages_render_table_button($label, $url);
    }

    if (preg_match('/<button\b([^>]*)>(.*?)<\/button>/is', $cell, $match)) {
        $label = trim(wp_strip_all_tags($match[2]));
        $url = aiomatic_super_pages_extract_html_attr($match[1], 'data-url');

        return aiomatic_super_pages_render_table_button($label, $url);
    }

    $plain = trim(wp_strip_all_tags($cell));

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

    if (preg_match('/^(?:buy now|check price|learn more|view details|explore|get started)$/i', $plain)) {
        return aiomatic_super_pages_render_table_button($plain, '#get-started');
    }

    $plain = str_replace(array("\xC3\xA2\xE2\x82\xAC\xC2\xA2", '&bull;'), "\xE2\x80\xA2", $plain);
    $parts = preg_split('/\s*(?:[\x{2022}\n\r]+|;\s+)\s*/u', $plain);
    $parts = array_values(array_filter(array_map('trim', (array) $parts)));

    if (count($parts) > 1) {
        $html = '<ul class="aiomatic-super-table-list">';

        foreach (array_slice($parts, 0, 6) as $part) {
            if ($part !== '') {
                $html .= '<li>' . esc_html($part) . '</li>';
            }
        }

        $html .= '</ul>';

        return $html;
    }

    return esc_html($plain);
}
function aiomatic_super_pages_render_component_pros_cons($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $pros_title = !empty($attrs['pros_title']) ? sanitize_text_field($attrs['pros_title']) : __('Pros', 'aiomatic-automatic-ai-content-writer');
    $cons_title = !empty($attrs['cons_title']) ? sanitize_text_field($attrs['cons_title']) : __('Cons', 'aiomatic-automatic-ai-content-writer');
    $pros = !empty($attrs['pros']) && is_array($attrs['pros']) ? $attrs['pros'] : array();
    $cons = !empty($attrs['cons']) && is_array($attrs['cons']) ? $attrs['cons'] : array();

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-pros-cons');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach (array(array($pros_title, $pros), array($cons_title, $cons)) as $column) {
        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= aiomatic_super_pages_render_component_heading($column[0], 3);
        $html .= '<!-- wp:list --><ul>';
        foreach ($column[1] as $item) {
            $html .= '<li>' . wp_kses_post($item) . '</li>';
        }
        $html .= '</ul><!-- /wp:list -->';
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_pricing_cards($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('Pricing', 'aiomatic-automatic-ai-content-writer');
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-pricing');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle, 'center');
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach ($items as $item) {
        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= '<!-- wp:group {"className":"aiomatic-super-pricing-card"} --><div class="wp-block-group aiomatic-super-pricing-card">';
        $html .= aiomatic_super_pages_render_component_heading(!empty($item['name']) ? $item['name'] : '', 3);
        $html .= aiomatic_super_pages_render_component_heading(!empty($item['price']) ? $item['price'] : '', 2);
        if (!empty($item['features']) && is_array($item['features'])) {
            $html .= '<!-- wp:list --><ul>';
            foreach ($item['features'] as $feature) {
                $html .= '<li>' . esc_html($feature) . '</li>';
            }
            $html .= '</ul><!-- /wp:list -->';
        }
        $html .= aiomatic_super_pages_render_component_buttons(array(array(
            'label' => !empty($item['button']) ? $item['button'] : __('Choose Plan', 'aiomatic-automatic-ai-content-writer'),
            'url' => !empty($item['button_url']) ? $item['button_url'] : '#',
        )));
        $html .= '</div><!-- /wp:group -->';
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_faq($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('Frequently Asked Questions', 'aiomatic-automatic-ai-content-writer');
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-faq');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);

    foreach ($items as $item) {
        $question = !empty($item['question'])
            ? sanitize_text_field($item['question'])
            : (!empty($item['title']) ? sanitize_text_field($item['title']) : '');

        $answer = !empty($item['answer'])
            ? wp_kses_post($item['answer'])
            : (!empty($item['content']) ? wp_kses_post($item['content']) : '');

        if ($question === '') {
            continue;
        }

        $html .= '<!-- wp:group {"className":"aiomatic-super-faq-item"} -->';
        $html .= '<div class="wp-block-group aiomatic-super-faq-item">';

        $html .= aiomatic_super_pages_render_component_heading($question, 3);
        $html .= aiomatic_super_pages_render_component_paragraph($answer);

        $html .= '</div><!-- /wp:group -->';
    }

    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_accordion($attrs)
{
    return aiomatic_super_pages_render_component_faq($attrs);
}

function aiomatic_super_pages_render_component_cta_banner($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $button = !empty($attrs['button']) ? sanitize_text_field($attrs['button']) : __('Get Started', 'aiomatic-automatic-ai-content-writer');
    $button_url = !empty($attrs['button_url']) ? esc_url($attrs['button_url']) : '#';

    $buttons = array(
        array(
            'label' => $button,
            'url' => $button_url,
            'class' => 'aiomatic-btn-cta-primary'
        )
    );

    if (!empty($attrs['secondary_button'])) {
        $buttons[] = array(
            'label' => sanitize_text_field($attrs['secondary_button']),
            'url' => !empty($attrs['secondary_button_url']) ? esc_url($attrs['secondary_button_url']) : '#',
        );
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-cta');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= aiomatic_super_pages_render_component_paragraph($content, 'center');
    $html .= aiomatic_super_pages_render_component_buttons($buttons, 'cta');
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_image_banner($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $image_url = !empty($attrs['image_url']) ? esc_url_raw($attrs['image_url']) : '';
    $attachment_id = !empty($attrs['attachment_id']) ? absint($attrs['attachment_id']) : 0;
    $image_prompt = !empty($attrs['image_prompt']) ? sanitize_text_field($attrs['image_prompt']) : '';
    $alt = !empty($attrs['alt']) ? sanitize_text_field($attrs['alt']) : $title;

    $copy_html = '';
    $media_html = '';
    $copy_html .= aiomatic_super_pages_render_component_heading($title, 2);
    $copy_html .= aiomatic_super_pages_render_component_paragraph($content);

    $image = $image_url !== '' ? aiomatic_super_pages_render_image($image_url, $attachment_id, $alt) : '';

    if ($image !== '') {

        $media_html .= '<!-- wp:html -->';
        $media_html .= '<figure class="aiomatic-super-image">';
        $media_html .= $image;
        $media_html .= '</figure>';
        $media_html .= '<!-- /wp:html -->';
    }
    elseif ($image_prompt !== '') {

        $media_html .= '<!-- wp:html -->';
        $media_html .= '<div class="aiomatic-image-placeholder" data-ai-prompt="' . esc_attr($image_prompt) . '">';
        $media_html .= esc_html__('AI Image Placeholder', 'aiomatic-automatic-ai-content-writer');
        $media_html .= '</div>';
        $media_html .= '<!-- /wp:html -->';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-image-banner');
    $html .= '<div class="aiomatic-super-image-copy">' . $copy_html . '</div>';

    if (!empty($media_html)) {
        $html .= '<div class="aiomatic-super-image-media">' . $media_html . '</div>';
    }

    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}
function aiomatic_super_pages_render_component_video_embed($attrs)
{
    $title = !empty($attrs['title'])
        ? sanitize_text_field($attrs['title'])
        : '';

    $content = !empty($attrs['content'])
        ? wp_kses_post($attrs['content'])
        : '';

    $caption = !empty($attrs['caption'])
        ? sanitize_text_field($attrs['caption'])
        : '';

    $url = !empty($attrs['url'])
        ? esc_url_raw($attrs['url'])
        : '';

    $embed_html = !empty($attrs['embed_html'])
        ? wp_kses(
            $attrs['embed_html'],
            aiomatic_super_pages_allowed_embed_html()
        )
        : '';

    if ($url === '' && $embed_html === '') {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start(
        'aiomatic-super-section aiomatic-super-video'
    );

    if ($title !== '') {
        $html .= aiomatic_super_pages_render_component_heading(
            $title,
            2,
            'center'
        );
    }

    if ($content !== '') {
        $html .= aiomatic_super_pages_render_component_paragraph(
            $content,
            'center'
        );
    }

    if ($embed_html === '' && $url !== '') {

        $embed_html = wp_oembed_get(
            $url,
            array(
                'width' => 1200,
            )
        );

        if (empty($embed_html)) {

            $embed_html = wp_embed_shortcode(
                array(
                    'src' => $url,
                ),
                ''
            );
        }
    }

    if (!empty($embed_html)) {

        $html .= '<!-- wp:html -->';

        $html .= '<div class="aiomatic-super-video-frame">';

        $html .= '<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:12px;">';

        if (stripos($embed_html, '<iframe') !== false) {

            $embed_html = preg_replace(
                '/<iframe/i',
                '<iframe style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;"',
                $embed_html,
                1
            );
        }

        $html .= $embed_html;

        $html .= '</div>';

        if ($caption !== '') {

            $html .= '<p class="aiomatic-super-video-caption"><em>' .
                esc_html($caption) .
                '</em></p>';
        }

        $html .= '</div>';

        $html .= '<!-- /wp:html -->';
    }

    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_allowed_embed_html()
{
    $allowed = wp_kses_allowed_html('post');

    $allowed['iframe'] = array(
        'src' => true,
        'width' => true,
        'height' => true,
        'style' => true,
        'allow' => true,
        'allowfullscreen' => true,
        'loading' => true,
        'referrerpolicy' => true,
        'frameborder' => true,
        'title' => true,
    );

    $allowed['form'] = array(
        'class' => true,
        'id' => true,
        'method' => true,
        'action' => true,
    );

    $allowed['input'] = array(
        'type' => true,
        'name' => true,
        'placeholder' => true,
        'value' => true,
        'class' => true,
        'id' => true,
        'required' => true,
    );

    $allowed['button'] = array(
        'type' => true,
        'class' => true,
        'id' => true,
    );

    $allowed['div'] = array(
        'class' => true,
    );

    return $allowed;
}

function aiomatic_super_pages_collect_button_hashes($value)
{
    $hashes = array();

    if (is_string($value)) {
        if (preg_match_all('/\bhref\s*=\s*(["\'])(#[A-Za-z][A-Za-z0-9\-_:.]*)\1/i', $value, $matches)) {
            foreach ($matches[2] as $hash) {
                $hashes[] = sanitize_title(substr($hash, 1));
            }
        }
    } elseif (is_array($value)) {
        foreach ($value as $key => $item) {
            if (is_string($key) && preg_match('/(?:^|_)(?:url|href|link)$/i', $key) && is_string($item)) {
                $item = trim($item);

                if (preg_match('/^#[A-Za-z][A-Za-z0-9\-_:.]*$/', $item)) {
                    $hashes[] = sanitize_title(substr($item, 1));
                }
            }

            if (is_array($item) || is_string($item)) {
                $hashes = array_merge($hashes, aiomatic_super_pages_collect_button_hashes($item));
            }
        }
    }

    return array_values(array_unique(array_filter($hashes)));
}

function aiomatic_super_pages_collect_declared_targets($value)
{
    $targets = array();

    if (is_array($value)) {
        foreach ($value as $key => $item) {
            if (is_string($key) && in_array($key, array('target', 'section_id'), true) && is_string($item)) {
                $target = sanitize_title((string) $item);

                if ($target !== '') {
                    $targets[] = $target;
                }
            }

            if (is_array($item)) {
                $targets = array_merge($targets, aiomatic_super_pages_collect_declared_targets($item));
            }
        }
    }

    return array_values(array_unique(array_filter($targets)));
}

function aiomatic_super_pages_default_section_id($block, $index, $decoded = array())
{
    $tree = isset($decoded['component_tree']) && is_array($decoded['component_tree'])
        ? $decoded['component_tree']
        : array();

    if (!empty($tree[$index]['id'])) {
        return sanitize_title((string) $tree[$index]['id']);
    }

    $type = isset($block['component'])
        ? sanitize_key($block['component'])
        : sanitize_key($block['block'] ?? 'section');

    return sanitize_title($type . '-' . ($index + 1));
}

function aiomatic_super_pages_find_anchor_target_index($blocks, $hash)
{
    $hash = sanitize_title($hash);
    $last_index = max(0, count($blocks) - 1);

    if ($hash === 'learn-more') {
        return count($blocks) > 1 ? 1 : 0;
    }

    if (in_array($hash, array('get-started', 'start', 'contact', 'book', 'signup', 'sign-up', 'pricing'), true)) {
        foreach ($blocks as $index => $block) {
            $type = sanitize_key($block['component'] ?? $block['block'] ?? '');

            if (in_array($type, array('lead_form', 'cta_banner', 'pricing_cards', 'product_showcase'), true)) {
                return $index;
            }
        }

        return $last_index;
    }

    foreach ($blocks as $index => $block) {
        $type = sanitize_key($block['component'] ?? $block['block'] ?? '');
        $attrs = isset($block['attrs']) && is_array($block['attrs']) ? $block['attrs'] : array();
        $title = sanitize_title((string) ($attrs['title'] ?? $attrs['headline'] ?? $type));

        if ($hash === $type || $hash === $title || strpos($title, $hash) !== false) {
            return $index;
        }
    }

    return $last_index;
}

function aiomatic_super_pages_prepare_section_anchors($blocks, $decoded = array())
{
    $blocks = array_values((array) $blocks);
    $hashes = array_values(array_unique(array_merge(
        aiomatic_super_pages_collect_button_hashes($blocks),
        aiomatic_super_pages_collect_declared_targets($blocks)
    )));

    foreach ($blocks as $index => $block) {
        if (!is_array($block)) {
            continue;
        }

        if (empty($blocks[$index]['attrs']) || !is_array($blocks[$index]['attrs'])) {
            $blocks[$index]['attrs'] = array();
        }

        if (empty($blocks[$index]['attrs']['section_id'])) {
            $blocks[$index]['attrs']['section_id'] = aiomatic_super_pages_default_section_id($block, $index, $decoded);
        }
    }

    foreach ($hashes as $hash) {
        $exists = false;

        foreach ($blocks as $block) {
            if (!empty($block['attrs']['section_id']) && sanitize_title((string) $block['attrs']['section_id']) === $hash) {
                $exists = true;
                break;
            }
        }

        if ($exists) {
            continue;
        }

        $target_index = aiomatic_super_pages_find_anchor_target_index($blocks, $hash);

        if (isset($blocks[$target_index]['attrs']) && is_array($blocks[$target_index]['attrs'])) {
            $current_id = !empty($blocks[$target_index]['attrs']['section_id'])
                ? sanitize_title((string) $blocks[$target_index]['attrs']['section_id'])
                : '';

            if ($current_id === '') {
                $blocks[$target_index]['attrs']['section_id'] = $hash;
                continue;
            }

            if ($current_id !== $hash) {
                if (empty($blocks[$target_index]['attrs']['section_aliases']) || !is_array($blocks[$target_index]['attrs']['section_aliases'])) {
                    $blocks[$target_index]['attrs']['section_aliases'] = array();
                }

                $blocks[$target_index]['attrs']['section_aliases'][] = $hash;
                $blocks[$target_index]['attrs']['section_aliases'] = array_values(array_unique(array_filter(array_map('sanitize_title', $blocks[$target_index]['attrs']['section_aliases']))));
            }
        }
    }

    return $blocks;
}

function aiomatic_super_pages_render_blocks($blocks, $decoded = array())
{
    if (empty($blocks) || !is_array($blocks)) {
        return '';
    }

    $blocks = aiomatic_super_pages_prepare_section_anchors($blocks, $decoded);

    $style_id = 'aiomatic-super-page-' . wp_generate_uuid4();

    $content = '<!-- wp:group {"className":"aiomatic-super-page ' . esc_attr($style_id) . '","layout":{"type":"constrained"}} -->';
    $content .= '<div class="wp-block-group aiomatic-super-page ' . esc_attr($style_id) . '">';

    $content .= aiomatic_super_pages_render_inline_style_block(
        $style_id,
        isset($decoded['design_system']) && is_array($decoded['design_system']) ? $decoded['design_system'] : array()
    );

    foreach ($blocks as $block) {
        $content .= aiomatic_super_pages_render_block($block);
    }

    $content .= '</div><!-- /wp:group -->';

    return $content;
}

function aiomatic_super_pages_render_inline_style_block($scope_class, $design_system = array())
{
    $theme = aiomatic_super_pages_normalize_design_system($design_system);

    $css = aiomatic_super_pages_build_css($scope_class, $theme);

    if (trim($css) === '') {
        return '';
    }

    return '<!-- wp:html --><style>' . wp_strip_all_tags($css) . '</style><!-- /wp:html -->';
}

function aiomatic_super_pages_normalize_design_system($design_system)
{
    $design_system = is_array($design_system) ? $design_system : array();

    $visual_style = strtolower((string) ($design_system['visual_style'] ?? ''));

    $palette = array(
        'primary'    => '#2563eb',
        'secondary'  => '#111827',
        'accent'     => '#7c3aed',
        'background' => '#f8fafc',
        'surface'    => '#ffffff',
        'text'       => '#111827',
        'muted'      => '#4b5563',
    );

    if (strpos($visual_style, 'dark') !== false) {
        $palette = array(
            'primary'    => '#60a5fa',
            'secondary'  => '#111827',
            'accent'     => '#a78bfa',
            'background' => '#020617',
            'surface'    => '#0f172a',
            'text'       => '#f9fafb',
            'muted'      => '#cbd5e1',
        );
    }

    $primary = aiomatic_super_pages_tame_hex_color($design_system['primary_color'] ?? '', $palette['primary'], 'primary');
    $secondary = aiomatic_super_pages_tame_hex_color($design_system['secondary_color'] ?? '', $palette['secondary'], 'secondary');
    $accent = aiomatic_super_pages_tame_hex_color($design_system['accent_color'] ?? '', $palette['accent'], 'accent');

    return array(
        'primary'       => $primary,
        'secondary'     => $secondary,
        'accent'        => $accent,
        'background'    => $palette['background'],
        'surface'       => $palette['surface'],
        'text'          => $palette['text'],
        'muted'         => $palette['muted'],
        'radius'        => aiomatic_super_pages_css_radius($design_system['border_radius'] ?? 'large'),
        'shadow'        => aiomatic_super_pages_css_shadow($design_system['shadow_style'] ?? 'soft layered'),
        'spacing'       => aiomatic_super_pages_css_spacing($design_system['spacing_style'] ?? 'generous'),
        'density'       => sanitize_key($design_system['section_density'] ?? 'balanced'),
        'visual_style'  => sanitize_text_field($visual_style),
        'button_style'  => sanitize_text_field($design_system['button_style'] ?? ''),
        'card_style'    => sanitize_text_field($design_system['card_style'] ?? ''),
    );
}

function aiomatic_super_pages_extract_hex_color($value)
{
    $value = trim((string) $value);

    if (preg_match('/#(?:[0-9a-fA-F]{3}){1,2}\b/', $value, $m)) {
        return strtolower($m[0]);
    }

    return '';
}

function aiomatic_super_pages_css_radius($value)
{
    $value = strtolower((string) $value);

    if (strpos($value, 'none') !== false) {
        return '0';
    }

    if (strpos($value, 'small') !== false) {
        return '8px';
    }

    if (strpos($value, 'medium') !== false) {
        return '14px';
    }

    if (strpos($value, 'large') !== false) {
        return '24px';
    }

    if (strpos($value, 'pill') !== false || strpos($value, 'round') !== false || strpos($value, 'circle') !== false) {
        return '24px';
    }

    return '20px';
}

function aiomatic_super_pages_css_shadow($value)
{
    $value = strtolower((string) $value);

    if (strpos($value, 'none') !== false || strpos($value, 'flat') !== false) {
        return 'none';
    }

    if (strpos($value, 'strong') !== false || strpos($value, 'deep') !== false) {
        return '0 24px 80px rgba(15, 23, 42, .18)';
    }

    return '0 18px 55px rgba(15, 23, 42, .10)';
}

function aiomatic_super_pages_css_spacing($value)
{
    $value = strtolower((string) $value);

    if (strpos($value, 'compact') !== false || strpos($value, 'tight') !== false) {
        return '48px';
    }

    if (strpos($value, 'large') !== false || strpos($value, 'generous') !== false) {
        return '96px';
    }

    return '72px';
}

function aiomatic_super_pages_build_css($scope_class, $theme)
{
    $primary_text = aiomatic_super_pages_get_contrast_color(
        $theme['primary']
    );

    $scope = '.' . sanitize_html_class($scope_class);

    return "
{$scope}{
    --aiomatic-sp-primary: {$theme['primary']};
    --aiomatic-sp-secondary: {$theme['secondary']};
    --aiomatic-sp-accent: {$theme['accent']};
    --aiomatic-sp-bg: {$theme['background']};
    --aiomatic-sp-surface: {$theme['surface']};
    --aiomatic-sp-text: {$theme['text']};
    --aiomatic-sp-muted: {$theme['muted']};
    --aiomatic-sp-radius: {$theme['radius']};
    --aiomatic-sp-shadow: {$theme['shadow']};
    --aiomatic-sp-spacing: {$theme['spacing']};
    --aiomatic-sp-button-radius: 8px;
    --aiomatic-sp-button-shadow: 0 14px 30px color-mix(in srgb, var(--aiomatic-sp-primary) 24%, transparent);
    color: var(--aiomatic-sp-text);
    background:
        radial-gradient(circle at top left, color-mix(in srgb, var(--aiomatic-sp-primary) 12%, transparent), transparent 34rem),
        linear-gradient(180deg, var(--aiomatic-sp-bg), #fff);
    padding: 1px 0;
    width: 100%;
    max-width: 100%;
    overflow-x: clip;
}
{$scope},
{$scope} *{
    box-sizing: border-box;
}
{$scope} h1,
{$scope} h2,
{$scope} h3,
{$scope} h4,
{$scope} p,
{$scope} li,
{$scope} a{
    max-width: 100%;
    white-space: normal;
    word-break: normal;
    overflow-wrap: break-word;
    hyphens: none;
}
{$scope} .aiomatic-super-section{
    width: min(calc(100% - 32px), 1120px);
    max-width: 1120px;
    margin-left: auto;
    margin-right: auto;
    margin-top: var(--aiomatic-sp-spacing);
    margin-bottom: var(--aiomatic-sp-spacing);
    overflow: visible;
}
{$scope} .aiomatic-super-anchor{
    display:block;
    position:relative;
    top:-96px;
    width:1px;
    height:1px;
    overflow:hidden;
}
{$scope} .aiomatic-super-section > *{
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
}
{$scope} .aiomatic-feature-grid,
{$scope} .aiomatic-super-steps,
{$scope} .aiomatic-super-stats,
{$scope} .aiomatic-super-testimonials,
{$scope} .aiomatic-super-pricing,
{$scope} .aiomatic-super-faq,
{$scope} .aiomatic-super-comparison,
{$scope} .aiomatic-super-highlight,
{$scope} .aiomatic-super-logo-cloud{
    width: min(calc(100% - 32px), 1120px);
    max-width: 1120px;
    margin-left: auto;
    margin-right: auto;
    margin-top: var(--aiomatic-sp-spacing);
    margin-bottom: var(--aiomatic-sp-spacing);
}
{$scope} .aiomatic-super-hero{
    padding: clamp(48px, 7vw, 84px) clamp(28px, 5vw, 56px);
    border-radius: var(--aiomatic-sp-radius);
    background:
        linear-gradient(135deg, color-mix(in srgb, var(--aiomatic-sp-primary) 14%, white), #fff 48%, color-mix(in srgb, var(--aiomatic-sp-accent) 10%, white));
    box-shadow: var(--aiomatic-sp-shadow);
    overflow: visible;
}
{$scope} .aiomatic-super-hero h1{
    font-size: clamp(34px, 4.8vw, 58px);
    line-height: 1.04;
    letter-spacing: 0;
    margin-bottom: 24px;
}
{$scope} .aiomatic-super-section-heading{
    text-align:center;
    max-width:860px;
}
{$scope} .aiomatic-super-section-heading p strong{
    color:var(--aiomatic-sp-primary);
    font-size:13px;
    font-weight:900;
    letter-spacing:.08em;
    text-transform:uppercase;
}
{$scope} .aiomatic-super-section-heading h2{
    font-size:clamp(34px,4.2vw,54px);
    line-height:1.06;
}
{$scope} .aiomatic-super-hero p{
    font-size: 20px;
    line-height: 1.7;
    color: var(--aiomatic-sp-muted);
    max-width: 760px;
}
{$scope} .aiomatic-super-hero--centered{
    text-align: center;
}
{$scope} .aiomatic-super-hero--centered h1,
{$scope} .aiomatic-super-hero--centered p{
    margin-left: auto;
    margin-right: auto;
}
{$scope} .aiomatic-super-hero--centered .wp-block-buttons{
    justify-content: center;
}
{$scope} .aiomatic-super-hero--dark_band{
    background: linear-gradient(135deg, var(--aiomatic-sp-secondary), color-mix(in srgb, var(--aiomatic-sp-primary) 35%, var(--aiomatic-sp-secondary)));
    color: #fff;
}
{$scope} .aiomatic-super-hero--dark_band p{
    color: rgba(255,255,255,.82);
}
{$scope} .aiomatic-super-hero-columns{
    display: grid !important;
    grid-template-columns: minmax(0, 1.08fr) minmax(280px, .92fr);
    gap: clamp(28px, 5vw, 56px);
    align-items: center;
}
{$scope} .aiomatic-super-hero-columns > .wp-block-column{
    width: auto !important;
    max-width: none !important;
    min-width: 0;
    flex-basis: auto !important;
}
{$scope} .aiomatic-super-text{
    max-width: 860px;
}
{$scope} .aiomatic-super-text p,
{$scope} .aiomatic-super-text .wp-block-html p{
    font-size: 18px;
    line-height: 1.85;
}
{$scope} .aiomatic-super-text h2,
{$scope} .aiomatic-super-text h3,
{$scope} .aiomatic-super-text h4{
    margin-top:1.4em;
}
{$scope} .aiomatic-super-text--minimal_text{
    padding-left: 8px;
    border-left: 4px solid color-mix(in srgb, var(--aiomatic-sp-primary) 35%, transparent);
}
{$scope} .aiomatic-super-toc,
{$scope} .aiomatic-super-editorial-summary{
    max-width:900px;
}
{$scope} .aiomatic-super-toc{
    padding:clamp(24px,4vw,38px);
    border:1px solid rgba(15,23,42,.08);
    border-radius:var(--aiomatic-sp-radius);
    background:color-mix(in srgb, var(--aiomatic-sp-surface) 92%, var(--aiomatic-sp-primary));
    box-shadow:0 16px 38px rgba(15,23,42,.06);
}
{$scope} .aiomatic-super-toc h2{
    margin-top:0;
    font-size:clamp(24px,2.4vw,34px);
}
{$scope} .aiomatic-super-toc-list{
    columns:2;
    column-gap:42px;
    margin-bottom:0;
    padding-left:1.3em;
}
{$scope} .aiomatic-super-toc-list li{
    break-inside:avoid;
    margin-bottom:10px;
    line-height:1.45;
}
{$scope} .aiomatic-super-toc-list a{
    color:var(--aiomatic-sp-text);
    text-decoration:none;
    font-weight:700;
}
{$scope} .aiomatic-super-toc-list a:hover{
    color:var(--aiomatic-sp-primary);
}
{$scope} .aiomatic-super-editorial-summary-box{
    padding:clamp(26px,4vw,44px);
    border-left:5px solid var(--aiomatic-sp-primary);
    border-radius:var(--aiomatic-sp-radius);
    background:var(--aiomatic-sp-surface);
    box-shadow:var(--aiomatic-sp-shadow);
}
{$scope} .aiomatic-super-editorial-summary-box h2{
    margin-top:0;
    font-size:clamp(24px,2.5vw,36px);
}
{$scope} .aiomatic-super-editorial-summary-box li{
    margin-bottom:12px;
    line-height:1.65;
}
{$scope} .wp-block-buttons{
    display:flex;
    flex-wrap:wrap;
    align-items:center;
    gap:12px;
    row-gap:12px;
    margin-top:28px;
    margin-bottom:32px;
}
{$scope} .aiomatic-super-buttons{
    display:flex;
    flex-wrap:wrap;
    align-items:center;
    gap:12px;
    row-gap:12px;
    margin-top:28px;
    margin-bottom:32px;
}

{$scope} .aiomatic-super-button{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    margin:0 0 8px;
    font-weight:700;
    max-width:100%;
}
{$scope} .wp-block-button,
{$scope} .wp-block-button__link{
    max-width:100%;
}
{$scope} .wp-block-button{
    margin:0 0 8px;
}
{$scope} .wp-block-button__link,
{$scope} a.button:not(.wp-block-button__link),
{$scope} .wp-block-html button:not([type=\"submit\"]){
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:48px;
    min-width:142px;
    box-sizing:border-box;
    border-radius:var(--aiomatic-sp-button-radius);
    padding:14px 24px;
    line-height:1.25;
    white-space:normal;
    overflow-wrap:break-word;
    text-align:center;
    text-decoration:none !important;
    font-size:15px;
    font-weight:700;
    border:1px solid transparent;
    box-shadow:var(--aiomatic-sp-button-shadow);
    font-family:inherit;
    letter-spacing:0;
    cursor:pointer;
    transition:transform .18s ease, box-shadow .18s ease, background .18s ease, border-color .18s ease;
}
{$scope} .wp-block-button__link:hover,
{$scope} a.button:not(.wp-block-button__link):hover,
{$scope} .wp-block-html button:not([type=\"submit\"]):hover{
    transform:translateY(-1px);
    box-shadow:0 16px 34px color-mix(in srgb, var(--aiomatic-sp-primary) 28%, transparent);
}

{$scope} .aiomatic-super-button-primary .wp-block-button__link,
{$scope} .aiomatic-btn-primary .wp-block-button__link,
{$scope} a.button:not(.wp-block-button__link),
{$scope} .wp-block-html button:not([type=\"submit\"]){
    background:linear-gradient(135deg, var(--aiomatic-sp-primary), color-mix(in srgb, var(--aiomatic-sp-primary) 72%, #111827)) !important;
    color:{$primary_text} !important;
}

{$scope} .aiomatic-super-button-secondary .wp-block-button__link,
{$scope} .aiomatic-btn-secondary .wp-block-button__link{
    background:color-mix(in srgb, var(--aiomatic-sp-surface) 92%, var(--aiomatic-sp-primary)) !important;
    color:var(--aiomatic-sp-text) !important;
    border-color:color-mix(in srgb, var(--aiomatic-sp-primary) 24%, rgba(15,23,42,.18)) !important;
    box-shadow:0 8px 20px rgba(15,23,42,.08);
}

{$scope} .aiomatic-super-hero .wp-block-buttons{
    margin-top:34px;
    margin-bottom:0;
}
{$scope} .aiomatic-super-text .wp-block-buttons{
    margin-top:30px;
    margin-bottom:40px;
}
{$scope} .wp-block-buttons + h2,
{$scope} .wp-block-buttons + h3,
{$scope} .wp-block-buttons + h4{
    margin-top:38px;
}
{$scope} .aiomatic-super-buttons-cta{
    justify-content:center;
    margin-bottom:0;
}
{$scope} .aiomatic-super-buttons-cta .aiomatic-super-button-primary .wp-block-button__link,
{$scope} .aiomatic-btn-cta-primary .wp-block-button__link{
    background:#ffffff !important;
    color:#111827 !important;
    box-shadow:0 18px 40px rgba(15,23,42,.20);
}

{$scope} .aiomatic-super-buttons-cta .aiomatic-super-button-secondary .wp-block-button__link{
    background:rgba(255,255,255,.16) !important;
    color:#ffffff !important;
    border:1px solid rgba(255,255,255,.28);
    box-shadow:none;
}

{$scope} .aiomatic-super-image img{
    width:100%;
    height:auto;
    display:block;
    border-radius:var(--aiomatic-sp-radius);
    box-shadow:var(--aiomatic-sp-shadow);
}
{$scope} .aiomatic-super-image-banner{
    display:grid;
    grid-template-columns:minmax(0,.9fr) minmax(280px,1.1fr);
    gap:clamp(28px,5vw,58px);
    align-items:center;
    padding:clamp(34px,5vw,64px);
    border-radius:var(--aiomatic-sp-radius);
    background:var(--aiomatic-sp-surface);
    box-shadow:var(--aiomatic-sp-shadow);
}
{$scope} .aiomatic-super-image-copy,
{$scope} .aiomatic-super-image-media{
    min-width:0;
}
{$scope} .aiomatic-super-image-banner h2{
    font-size:clamp(30px,3.4vw,48px);
    line-height:1.08;
}
{$scope} .aiomatic-super-image-banner .wp-block-image,
{$scope} .aiomatic-super-image-banner figure{
    margin:0;
}
{$scope} .aiomatic-super-image-banner img{
    width:100%;
    min-height:320px;
    object-fit:cover;
    border-radius:calc(var(--aiomatic-sp-radius) - 4px);
}
{$scope} .aiomatic-super-card,
{$scope} .aiomatic-super-pricing-card,
{$scope} .aiomatic-pricing-card,
{$scope} .aiomatic-super-product-card,
{$scope} .aiomatic-super-highlight-box,
{$scope} .aiomatic-super-testimonials blockquote,
{$scope} .aiomatic-super-stats > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-feature-grid > .wp-block-columns > .wp-block-column{
    border: 1px solid rgba(15, 23, 42, .08);
    border-radius: var(--aiomatic-sp-radius);
    background: var(--aiomatic-sp-surface);
    box-shadow: var(--aiomatic-sp-shadow);
    padding: clamp(22px, 3vw, 32px);
    height: 100%;
    min-width: 0;
    max-width: 100%;
    overflow: visible;
}
{$scope} .aiomatic-super-logo-cloud{
    padding:clamp(34px,5vw,70px) 0;
}
{$scope} .aiomatic-super-logo-grid{
    display:grid;
    grid-template-columns:repeat(4,minmax(0,1fr));
    gap:clamp(22px,4vw,42px);
    align-items:center;
    justify-items:center;
    margin-top:clamp(26px,4vw,44px);
}
{$scope} .aiomatic-super-logo-mark{
    min-height:72px;
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    gap:4px;
    text-align:center;
    filter:grayscale(1);
    opacity:.68;
    transition:opacity .18s ease, transform .18s ease;
}
{$scope} .aiomatic-super-logo-mark:hover{
    opacity:.92;
    transform:translateY(-2px);
}
{$scope} .aiomatic-super-logo-image{
    margin:0;
}
{$scope} .aiomatic-super-logo-image img{
    max-height:54px;
    width:auto;
    object-fit:contain;
}
{$scope} .aiomatic-super-logo-name{
    display:block;
    color:color-mix(in srgb, var(--aiomatic-sp-text) 62%, transparent);
    font-size:clamp(18px,2.5vw,28px);
    line-height:1;
    font-weight:900;
    letter-spacing:.08em;
    text-transform:uppercase;
}
{$scope} .aiomatic-super-logo-tagline{
    display:block;
    color:color-mix(in srgb, var(--aiomatic-sp-text) 48%, transparent);
    font-size:10px;
    font-weight:800;
    letter-spacing:.16em;
    text-transform:uppercase;
}
{$scope} .aiomatic-super-icon{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    width:40px;
    height:40px;
    margin:0 0 18px;
    border-radius:12px;
    background:color-mix(in srgb, var(--aiomatic-sp-primary) 12%, #fff);
    color:color-mix(in srgb, var(--aiomatic-sp-primary) 82%, #111827);
    font-weight:800;
    font-size:18px;
    line-height:1;
}
{$scope} .aiomatic-super-card-grid > .wp-block-columns,
{$scope} .aiomatic-feature-grid > .wp-block-columns,
{$scope} .aiomatic-super-testimonials > .wp-block-columns,
{$scope} .aiomatic-super-stats > .wp-block-columns,
{$scope} .aiomatic-super-pricing > .wp-block-columns,
{$scope} .aiomatic-super-product-showcase > .wp-block-columns,
{$scope} .aiomatic-super-pros-cons > .wp-block-columns{
    display:grid !important;
    grid-template-columns:repeat(auto-fit, minmax(min(100%, 340px), 1fr));
    gap:clamp(22px, 3vw, 34px);
    align-items:stretch;
}
{$scope} .aiomatic-super-card-grid > .wp-block-columns,
{$scope} .aiomatic-feature-grid > .wp-block-columns,
{$scope} .aiomatic-super-testimonials > .wp-block-columns{
    grid-template-columns:repeat(auto-fit, minmax(min(100%, 380px), 1fr));
}
{$scope} .aiomatic-super-pros-cons > .wp-block-columns{
    grid-template-columns:repeat(auto-fit, minmax(min(100%, 420px), 1fr));
}
{$scope} .aiomatic-super-card-grid > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-feature-grid > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-super-testimonials > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-super-stats > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-super-pricing > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-super-product-showcase > .wp-block-columns > .wp-block-column,
{$scope} .aiomatic-super-pros-cons > .wp-block-columns > .wp-block-column{
    flex-basis:auto !important;
    width:auto !important;
    max-width:none !important;
    min-width:0;
    margin:0 !important;
}
{$scope} .aiomatic-super-comparison{
    overflow:visible;
}
{$scope} .aiomatic-super-table{
    overflow-x:auto;
    margin-top:clamp(22px,3vw,34px);
    border:1px solid rgba(15,23,42,.08);
    border-radius:var(--aiomatic-sp-radius);
    background:var(--aiomatic-sp-surface);
    box-shadow:var(--aiomatic-sp-shadow);
}
{$scope} .aiomatic-super-table table{
    width:100%;
    min-width:920px;
    border-collapse:separate;
    border-spacing:0;
    table-layout:auto;
    font-size:14px;
    line-height:1.45;
}
{$scope} .aiomatic-super-table th,
{$scope} .aiomatic-super-table td{
    vertical-align:top;
    padding:14px 14px;
    border:0;
    border-right:1px solid rgba(15,23,42,.08);
    border-bottom:1px solid rgba(15,23,42,.08);
    max-width:260px;
}
{$scope} .aiomatic-super-table th{
    position:sticky;
    top:0;
    z-index:2;
    background:color-mix(in srgb, var(--aiomatic-sp-primary) 10%, #fff);
    color:var(--aiomatic-sp-text);
    font-size:13px;
    font-weight:900;
    letter-spacing:.02em;
}
{$scope} .aiomatic-super-table th:first-child,
{$scope} .aiomatic-super-table td:first-child{
    position:sticky;
    left:0;
    z-index:1;
    background:var(--aiomatic-sp-surface);
    min-width:180px;
    font-weight:800;
}
{$scope} .aiomatic-super-table th:first-child{
    z-index:3;
    background:color-mix(in srgb, var(--aiomatic-sp-primary) 14%, #fff);
}
{$scope} .aiomatic-super-table tr:last-child td{
    border-bottom:0;
}
{$scope} .aiomatic-super-table th:last-child,
{$scope} .aiomatic-super-table td:last-child{
    border-right:0;
}
{$scope} .aiomatic-super-table-list{
    margin:0;
    padding-left:1.1em;
}
{$scope} .aiomatic-super-table-list li{
    margin-bottom:6px;
}
{$scope} .aiomatic-super-table-list li:last-child{
    margin-bottom:0;
}
{$scope} .aiomatic-super-table-button{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:38px;
    padding:9px 14px;
    border-radius:8px;
    background:var(--aiomatic-sp-primary);
    color:{$primary_text} !important;
    font-size:13px;
    font-weight:800;
    text-decoration:none !important;
    white-space:nowrap;
    box-shadow:0 10px 22px color-mix(in srgb, var(--aiomatic-sp-primary) 24%, transparent);
}
{$scope} .aiomatic-super-table-button:hover{
    transform:translateY(-1px);
}
{$scope} .aiomatic-super-card,
{$scope} .aiomatic-feature-grid > .wp-block-columns > .wp-block-column{
    display:flex;
    flex-direction:column;
    gap:10px;
}
{$scope} .aiomatic-super-card,
{$scope} .aiomatic-super-card h3,
{$scope} .aiomatic-super-card p,
{$scope} .aiomatic-feature-grid,
{$scope} .aiomatic-feature-grid h3,
{$scope} .aiomatic-feature-grid p,
{$scope} .aiomatic-super-pricing-card,
{$scope} .aiomatic-pricing-card,
{$scope} .aiomatic-super-pricing-card h3,
{$scope} .aiomatic-pricing-card h3,
{$scope} .aiomatic-super-pricing-card p,
{$scope} .aiomatic-pricing-card p,
{$scope} .aiomatic-super-product-card,
{$scope} .aiomatic-super-product-card h3,
{$scope} .aiomatic-super-product-card p,
{$scope} .aiomatic-super-testimonials blockquote,
{$scope} .aiomatic-super-stats,
{$scope} .aiomatic-super-pricing{
    word-break:normal;
    overflow-wrap:break-word;
    hyphens:none;
}
{$scope} .aiomatic-super-card h3,
{$scope} .aiomatic-feature-grid h3,
{$scope} .aiomatic-super-pricing-card h3,
{$scope} .aiomatic-pricing-card h3,
{$scope} .aiomatic-super-product-card h3{
    margin-top: 10px;
    font-size: clamp(22px, 2vw, 28px);
    line-height: 1.18;
}
{$scope} .aiomatic-super-pricing-card h2,
{$scope} .aiomatic-pricing-card h2{
    font-size: clamp(30px, 3vw, 42px);
    line-height: 1.12;
    margin-top: 0;
    margin-bottom: 12px;
}
{$scope} .aiomatic-super-pricing-card,
{$scope} .aiomatic-pricing-card,
{$scope} .aiomatic-super-product-card{
    display:flex;
    flex-direction:column;
    gap:14px;
}
{$scope} .aiomatic-super-pricing-card .wp-block-buttons,
{$scope} .aiomatic-pricing-card .wp-block-buttons,
{$scope} .aiomatic-super-product-card .wp-block-buttons{
    margin-top:auto;
    margin-bottom:0;
    padding-top:10px;
}
{$scope} .aiomatic-super-pricing-card ul,
{$scope} .aiomatic-pricing-card ul{
    padding-left: 1.2em;
    margin-top: 4px;
    margin-bottom: 18px;
}
{$scope} .aiomatic-super-pricing-card li,
{$scope} .aiomatic-pricing-card li{
    line-height: 1.65;
    margin-bottom: 9px;
}
{$scope} .aiomatic-super-card figure,
{$scope} .aiomatic-super-product-card figure{
    margin: 0 0 20px;
    max-width: 100%;
    overflow: hidden;
    border-radius: var(--aiomatic-sp-radius);
}
{$scope} .aiomatic-super-card img,
{$scope} .aiomatic-super-image,
{$scope} .wp-block-image img{
    border-radius: var(--aiomatic-sp-radius);
    box-shadow: var(--aiomatic-sp-shadow);
}
{$scope} .aiomatic-super-card-image img{
    width: 100%;
    height: 220px;
    object-fit: cover;
}
{$scope} .aiomatic-super-cta{
    padding: clamp(42px, 6vw, 64px) clamp(26px, 5vw, 46px);
    border-radius: var(--aiomatic-sp-radius);
    background:linear-gradient(135deg, var(--aiomatic-sp-secondary), color-mix(in srgb, var(--aiomatic-sp-primary) 36%, var(--aiomatic-sp-secondary)));
    color:#ffffff;
    text-align:center;
    box-shadow: var(--aiomatic-sp-shadow);
    overflow: visible;
}
{$scope} .aiomatic-super-cta p{
    color:rgba(255,255,255,.82);
    max-width:760px;
}
{$scope} .aiomatic-super-cta .wp-block-button:first-child .wp-block-button__link{
    background:#ffffff !important;
    color:#111827 !important;
    box-shadow:0 18px 40px rgba(15,23,42,.20);
}

{$scope} .aiomatic-super-cta .wp-block-button:nth-child(2) .wp-block-button__link{
    background:rgba(255,255,255,.15) !important;
    color:#ffffff !important;
    border:1px solid rgba(255,255,255,.25);
    box-shadow:none;
}
{$scope} .aiomatic-super-video-frame{
    max-width: 980px;
    margin: 32px auto 0;
    border-radius: var(--aiomatic-sp-radius);
    overflow: hidden;
    box-shadow: var(--aiomatic-sp-shadow);
    background: #000;
}
{$scope} .aiomatic-super-video-frame iframe{
    width: 100%;
    aspect-ratio: 16 / 9;
    height: auto;
    display: block;
}
{$scope} .aiomatic-image-placeholder{
    border:1px dashed rgba(15,23,42,.18);
    border-radius:var(--aiomatic-sp-radius);
    background:color-mix(in srgb, var(--aiomatic-sp-primary) 7%, #fff);
    color:var(--aiomatic-sp-muted);
    padding:28px;
    min-height:180px;
    display:flex;
    align-items:center;
    justify-content:center;
    text-align:center;
    overflow:visible;
}
{$scope} .aiomatic-super-faq-item{
    border: 1px solid rgba(15, 23, 42, .08);
    border-radius: 16px;
    padding: 22px 26px;
    background: var(--aiomatic-sp-surface);
    box-shadow: 0 10px 30px rgba(15, 23, 42, .05);
    margin-bottom: 16px;
}
{$scope} .aiomatic-super-faq-item h3{
    margin-top: 0;
}
{$scope} .wp-block-button.aiomatic-btn-primary,
{$scope} .wp-block-button.aiomatic-btn-secondary,
{$scope} .wp-block-button.aiomatic-btn-cta-primary{
    background:transparent!important;
    color:inherit!important;
}
{$scope} .wp-block-button__link *{
    color:inherit!important;
}
{$scope} .aiomatic-super-form{
    max-width: 100%;
}

{$scope} .aiomatic-super-form p{
    margin-bottom: 16px;
}

{$scope} .aiomatic-super-form input,
{$scope} .aiomatic-super-form textarea,
{$scope} .aiomatic-super-form select{
    width: 100%;
    box-sizing: border-box;
    padding: 14px 16px;
    border: 1px solid rgba(15,23,42,.15);
    border-radius: 12px;
    background: #fff;
    color: var(--aiomatic-sp-text);
    font-size: 16px;
}

{$scope} .aiomatic-super-form textarea{
    min-height: 140px;
    resize: vertical;
}

{$scope} .aiomatic-super-form button{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 14px 24px;
    border: 0;
    border-radius: 999px;
    background: var(--aiomatic-sp-primary);
    color: {$primary_text};
    font-weight: 700;
    cursor: pointer;
}

{$scope} .aiomatic-super-form-response{
    margin-top: 16px;
}
@media (max-width: 781px){
    {$scope} .aiomatic-super-hero{
        padding: 52px 24px;
    }
    {$scope} .aiomatic-super-hero-columns{
        grid-template-columns:1fr;
    }
    {$scope} .aiomatic-super-image-banner{
        grid-template-columns:1fr;
        padding:28px;
    }
    {$scope} .aiomatic-super-section{
        width: min(calc(100% - 24px), 1120px);
        margin-top: 52px;
        margin-bottom: 52px;
    }
    {$scope} .aiomatic-feature-grid,
    {$scope} .aiomatic-super-steps,
    {$scope} .aiomatic-super-stats,
    {$scope} .aiomatic-super-testimonials,
    {$scope} .aiomatic-super-pricing,
    {$scope} .aiomatic-super-faq,
    {$scope} .aiomatic-super-comparison,
    {$scope} .aiomatic-super-highlight,
    {$scope} .aiomatic-super-logo-cloud{
        width: min(calc(100% - 24px), 1120px);
        margin-top: 52px;
        margin-bottom: 52px;
    }
    {$scope} .aiomatic-super-logo-grid{
        grid-template-columns:repeat(2,minmax(0,1fr));
        gap:28px 18px;
    }
    {$scope} .aiomatic-super-logo-name{
        font-size:18px;
    }
    {$scope} .aiomatic-super-card-grid > .wp-block-columns,
    {$scope} .aiomatic-feature-grid > .wp-block-columns,
    {$scope} .aiomatic-super-testimonials > .wp-block-columns,
    {$scope} .aiomatic-super-stats > .wp-block-columns,
    {$scope} .aiomatic-super-pricing > .wp-block-columns,
    {$scope} .aiomatic-super-product-showcase > .wp-block-columns,
    {$scope} .aiomatic-super-pros-cons > .wp-block-columns{
        grid-template-columns:1fr;
    }
}";
}
function aiomatic_super_pages_render_component_shortcode_embed($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $shortcode = !empty($attrs['shortcode']) ? trim((string) $attrs['shortcode']) : '';

    if ($shortcode === '') {
        return aiomatic_super_pages_render_component_text(array('title' => $title, 'content' => $content));
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-shortcode');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= aiomatic_super_pages_render_component_paragraph($content);
    $html .= '<!-- wp:shortcode -->' . wp_kses_post($shortcode) . '<!-- /wp:shortcode -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_lead_form($attrs)
{
    $title     = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : __('Get Started', 'aiomatic-automatic-ai-content-writer');
    $content   = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $shortcode = !empty($attrs['shortcode']) ? trim((string) $attrs['shortcode']) : '';
    $button    = !empty($attrs['button']) ? sanitize_text_field($attrs['button']) : __('Submit', 'aiomatic-automatic-ai-content-writer');

    $fields = !empty($attrs['fields']) && is_array($attrs['fields'])
        ? $attrs['fields']
        : array('name', 'email');

    $form_id = 'aiomatic-super-form-' . wp_generate_uuid4();

    $html  = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-lead-form');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= aiomatic_super_pages_render_component_paragraph($content);

    if ($shortcode !== '') {
        $html .= '<!-- wp:shortcode -->' . wp_kses_post($shortcode) . '<!-- /wp:shortcode -->';
        $html .= aiomatic_super_pages_component_section_end();
        return $html;
    }

    $html .= '<!-- wp:html -->';
    $html .= '<form id="' . esc_attr($form_id) . '" class="aiomatic-super-form" method="post">';
    $html .= '<input type="hidden" name="action" value="aiomatic_super_page_lead_submit">';
    $html .= '<input type="hidden" name="nonce" value="' . esc_attr(wp_create_nonce('aiomatic_super_page_lead_submit')) . '">';
    $html .= '<input type="hidden" name="page_title" value="' . esc_attr(get_the_title()) . '">';

    foreach ($fields as $field) {
        $field = sanitize_key($field);

        switch ($field) {
            case 'name':
                $html .= '<p><input type="text" name="name" placeholder="' . esc_attr__('Your name', 'aiomatic-automatic-ai-content-writer') . '" required></p>';
                break;

            case 'email':
                $html .= '<p><input type="email" name="email" placeholder="' . esc_attr__('Your email', 'aiomatic-automatic-ai-content-writer') . '" required></p>';
                break;

            case 'phone':
                $html .= '<p><input type="tel" name="phone" placeholder="' . esc_attr__('Your phone', 'aiomatic-automatic-ai-content-writer') . '"></p>';
                break;

            case 'website':
                $html .= '<p><input type="url" name="website" placeholder="' . esc_attr__('Your website', 'aiomatic-automatic-ai-content-writer') . '"></p>';
                break;

            case 'message':
                $html .= '<p><textarea name="message" placeholder="' . esc_attr__('Your message', 'aiomatic-automatic-ai-content-writer') . '"></textarea></p>';
                break;
        }
    }

    $html .= '<p><button type="submit">' . esc_html($button) . '</button></p>';
    $html .= '<p class="aiomatic-super-form-response" style="display:none;"></p>';
    $html .= '</form>';

    $html .= '<script>
    (function(){
        var form = document.getElementById("' . esc_js($form_id) . '");
        if(!form){ return; }

        form.addEventListener("submit", function(e){
            e.preventDefault();

            var response = form.querySelector(".aiomatic-super-form-response");
            var button = form.querySelector("button[type=submit]");
            var data = new FormData(form);

            if(button){ button.disabled = true; }

            fetch("' . esc_url(admin_url('admin-ajax.php')) . '", {
                method: "POST",
                credentials: "same-origin",
                body: data
            })
            .then(function(res){ return res.json(); })
            .then(function(json){
                response.style.display = "block";
                response.textContent = json && json.data && json.data.message ? json.data.message : "Thank you. Your message was sent.";

                if(json.success){
                    form.reset();
                }
            })
            .catch(function(){
                response.style.display = "block";
                response.textContent = "Something went wrong. Please try again.";
            })
            .finally(function(){
                if(button){ button.disabled = false; }
            });
        });
    })();
    </script>';

    $html .= '<!-- /wp:html -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_map_embed($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $address = !empty($attrs['address']) ? sanitize_text_field($attrs['address']) : '';
    $embed_url = !empty($attrs['embed_url']) ? esc_url($attrs['embed_url']) : '';
    $caption = !empty($attrs['caption']) ? sanitize_text_field($attrs['caption']) : '';

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-map');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);

    if ($embed_url !== '') {
        $html .= '<!-- wp:html --><iframe src="' . $embed_url . '" width="100%" height="420" style="border:0;" allowfullscreen="" referrerpolicy="no-referrer-when-downgrade"></iframe><!-- /wp:html -->';
    } elseif ($address !== '') {
        $html .= aiomatic_super_pages_render_component_paragraph('<strong>' . esc_html__('Address:', 'aiomatic-automatic-ai-content-writer') . '</strong> ' . esc_html($address));
    }

    $html .= aiomatic_super_pages_render_component_paragraph($caption);
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_code_snippet($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $content = !empty($attrs['content']) ? wp_kses_post($attrs['content']) : '';
    $code = !empty($attrs['code']) ? (string) $attrs['code'] : '';
    $language = !empty($attrs['language']) ? sanitize_key($attrs['language']) : '';

    if ($code === '') {
        return aiomatic_super_pages_render_component_text(array('title' => $title, 'content' => $content));
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-code');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= aiomatic_super_pages_render_component_paragraph($content);
    $html .= '<!-- wp:code --><pre class="wp-block-code"><code class="language-' . esc_attr($language) . '">' . esc_html($code) . '</code></pre><!-- /wp:code -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_html_embed($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $html_raw = !empty($attrs['html']) ? wp_kses($attrs['html'], aiomatic_super_pages_allowed_embed_html()) : '';

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

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-html-embed');
    $html .= aiomatic_super_pages_render_component_heading($title, 2);
    $html .= '<!-- wp:html -->' . $html_raw . '<!-- /wp:html -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}
function aiomatic_super_pages_render_image($image_url, $attachment_id = 0, $alt = '')
{
    $image_url = esc_url_raw($image_url);
    $attachment_id = absint($attachment_id);

    if ($image_url === '' && $attachment_id > 0) {
        $image_url = esc_url_raw((string) wp_get_attachment_url($attachment_id));
    }

    if (empty($image_url) || !aiomatic_super_pages_is_trusted_image_src($image_url, $attachment_id)) {
        return '';
    }

    // Prefer attachment if it exists
    if (
        !empty($attachment_id) &&
        get_post($attachment_id) &&
        wp_attachment_is_image($attachment_id)
    ) {
        return wp_get_attachment_image(
            $attachment_id,
            'medium',
            false,
            array(
                'alt' => $alt,
                'loading' => 'lazy',
            )
        );
    }

    // Verify URL actually exists locally
    $uploads = wp_upload_dir();

    if (
        strpos($image_url, $uploads['baseurl']) === 0
    ) {
        $file = str_replace(
            $uploads['baseurl'],
            $uploads['basedir'],
            $image_url
        );

        if (!file_exists($file)) {
            return '';
        }
    }

    return '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($alt) . '"/>';
}
function aiomatic_super_pages_render_component_product_showcase($attrs)
{
    $title = !empty($attrs['title']) ? sanitize_text_field($attrs['title']) : '';
    $subtitle = !empty($attrs['subtitle']) ? wp_kses_post($attrs['subtitle']) : '';
    $items = !empty($attrs['items']) && is_array($attrs['items']) ? $attrs['items'] : array();

    if (!$items) {
        return '';
    }

    $html = aiomatic_super_pages_component_section_start('aiomatic-super-section aiomatic-super-product-showcase');
    $html .= aiomatic_super_pages_render_component_heading($title, 2, 'center');
    $html .= aiomatic_super_pages_render_component_paragraph($subtitle, 'center');
    $html .= '<!-- wp:columns --><div class="wp-block-columns">';

    foreach ($items as $item) {
        $html .= '<!-- wp:column --><div class="wp-block-column">';
        $html .= '<!-- wp:group {"className":"aiomatic-super-product-card"} --><div class="wp-block-group aiomatic-super-product-card">';
        if (!empty($item['image_url'])) {
            $img = aiomatic_super_pages_render_gutenberg_image(
                $item['image_url'],
                $item['title'] ?? '',
                !empty($item['attachment_id']) ? intval($item['attachment_id']) : 0
            );

            $html .= $img;
        }
        $html .= aiomatic_super_pages_render_component_heading(!empty($item['title']) ? $item['title'] : '', 3);
        if (!empty($item['price'])) {
            $html .= aiomatic_super_pages_render_component_paragraph('<strong>' . esc_html($item['price']) . '</strong>');
        }
        $html .= aiomatic_super_pages_render_component_paragraph(!empty($item['content']) ? $item['content'] : '');
        $html .= aiomatic_super_pages_render_component_buttons(array(array(
            'label' => !empty($item['button']) ? $item['button'] : __('Learn More', 'aiomatic-automatic-ai-content-writer'),
            'url' => !empty($item['button_url']) ? $item['button_url'] : '#',
        )));
        $html .= '</div><!-- /wp:group -->';
        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';
    $html .= aiomatic_super_pages_component_section_end();

    return $html;
}

function aiomatic_super_pages_render_component_separator($attrs)
{
    $height = !empty($attrs['height']) ? sanitize_text_field($attrs['height']) : '50px';

    return '<!-- wp:spacer {"height":"' . esc_attr($height) . '"} --><div style="height:' . esc_attr($height) . '" aria-hidden="true" class="wp-block-spacer"></div><!-- /wp:spacer -->';
}

function aiomatic_super_pages_render_hero($attrs)
{
    $headline = !empty($attrs['headline'])
        ? esc_html($attrs['headline'])
        : '';

    $subheadline = !empty($attrs['subheadline'])
        ? wp_kses_post($attrs['subheadline'])
        : '';

    $primary_cta = !empty($attrs['primary_cta'])
        ? esc_html($attrs['primary_cta'])
        : __('Get Started', 'aiomatic-automatic-ai-content-writer');

    $primary_url = !empty($attrs['primary_cta_url'])
        ? esc_url($attrs['primary_cta_url'])
        : '#';

    $html = '<!-- wp:group {"className":"aiomatic-super-hero"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-hero">';

    $html .= '<!-- wp:heading {"level":1} -->';
    $html .= '<h1>' . $headline . '</h1>';
    $html .= '<!-- /wp:heading -->';

    if ($subheadline !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $subheadline . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $html .= '<!-- wp:buttons -->';
    $html .= '<div class="wp-block-buttons">';

    $html .= '<!-- wp:button -->';
    $html .= '<div class="wp-block-button">';
    $html .= '<a class="wp-block-button__link wp-element-button" href="' . $primary_url . '">';
    $html .= $primary_cta;
    $html .= '</a>';
    $html .= '</div>';
    $html .= '<!-- /wp:button -->';

    $html .= '</div><!-- /wp:buttons -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_feature_grid($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    $html = '<!-- wp:group {"className":"aiomatic-feature-grid"} -->';
    $html .= '<div class="wp-block-group aiomatic-feature-grid">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2} -->';
        $html .= '<h2>' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    $html .= '<!-- wp:columns -->';
    $html .= '<div class="wp-block-columns">';

    foreach ($items as $item) {

        $html .= '<!-- wp:column -->';
        $html .= '<div class="wp-block-column">';

        if (!empty($item['title'])) {

            $html .= '<!-- wp:heading {"level":3} -->';
            $html .= '<h3>' . esc_html($item['title']) . '</h3>';
            $html .= '<!-- /wp:heading -->';
        }

        if (!empty($item['content'])) {

            $html .= '<!-- wp:paragraph -->';
            $html .= '<p>' . wp_kses_post($item['content']) . '</p>';
            $html .= '<!-- /wp:paragraph -->';
        }

        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_text($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $content = !empty($attrs['content'])
        ? wp_kses_post($attrs['content'])
        : '';

    $html = '<!-- wp:group -->';
    $html .= '<div class="wp-block-group">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2} -->';
        $html .= '<h2>' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    if ($content !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $content . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_cta($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $content = !empty($attrs['content'])
        ? wp_kses_post($attrs['content'])
        : '';

    $button = !empty($attrs['button'])
        ? esc_html($attrs['button'])
        : __('Get Started', 'aiomatic-automatic-ai-content-writer');

    $button_url = !empty($attrs['button_url'])
        ? esc_url($attrs['button_url'])
        : '#';

    $html = '<!-- wp:group {"className":"aiomatic-super-cta"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-cta">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2} -->';
        $html .= '<h2>' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    if ($content !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $content . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $html .= '<!-- wp:buttons -->';
    $html .= '<div class="wp-block-buttons">';
    $html .= '<!-- wp:button -->';
    $html .= '<div class="wp-block-button">';
    $html .= '<a class="wp-block-button__link wp-element-button" href="' . $button_url . '">';
    $html .= $button;
    $html .= '</a>';
    $html .= '</div>';
    $html .= '<!-- /wp:button -->';
    $html .= '</div><!-- /wp:buttons -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}
function aiomatic_super_pages_render_faq($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : __('Frequently Asked Questions', 'aiomatic-automatic-ai-content-writer');

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    if (empty($items)) {
        return '';
    }

    $html  = '<!-- wp:group {"className":"aiomatic-super-faq"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-faq">';

    $html .= '<!-- wp:heading {"level":2} -->';
    $html .= '<h2>' . $title . '</h2>';
    $html .= '<!-- /wp:heading -->';

    foreach ($items as $item) {

        $question = !empty($item['question'])
            ? esc_html($item['question'])
            : '';

        $answer = !empty($item['answer'])
            ? wp_kses_post($item['answer'])
            : '';

        if ($question === '') {
            continue;
        }

        $html .= '<!-- wp:group {"className":"aiomatic-super-faq-item"} -->';
        $html .= '<div class="wp-block-group aiomatic-super-faq-item">';

        $html .= '<!-- wp:heading {"level":3} -->';
        $html .= '<h3>' . $question . '</h3>';
        $html .= '<!-- /wp:heading -->';

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $answer . '</p>';
        $html .= '<!-- /wp:paragraph -->';

        $html .= '</div>';
        $html .= '<!-- /wp:group -->';
    }

    $html .= '</div>';
    $html .= '<!-- /wp:group -->';

    return $html;
}
function aiomatic_super_pages_render_steps($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : __('How It Works', 'aiomatic-automatic-ai-content-writer');

    $subtitle = !empty($attrs['subtitle'])
        ? wp_kses_post($attrs['subtitle'])
        : '';

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    if (empty($items)) {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-steps"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-steps">';

    $html .= '<!-- wp:heading {"level":2} -->';
    $html .= '<h2>' . $title . '</h2>';
    $html .= '<!-- /wp:heading -->';

    if ($subtitle !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $subtitle . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $html .= '<!-- wp:list {"ordered":true} -->';
    $html .= '<ol>';

    foreach ($items as $item) {

        $step_title = !empty($item['title'])
            ? esc_html($item['title'])
            : '';

        $step_content = !empty($item['content'])
            ? wp_kses_post($item['content'])
            : '';

        if ($step_title === '' && $step_content === '') {
            continue;
        }

        $html .= '<li>';

        if ($step_title !== '') {
            $html .= '<strong>' . $step_title . '</strong>';
        }

        if ($step_content !== '') {
            $html .= '<br>' . $step_content;
        }

        $html .= '</li>';
    }

    $html .= '</ol>';
    $html .= '<!-- /wp:list -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_stats($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    if (empty($items)) {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-stats"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-stats">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2,"textAlign":"center"} -->';
        $html .= '<h2 class="has-text-align-center">' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    $html .= '<!-- wp:columns -->';
    $html .= '<div class="wp-block-columns">';

    foreach ($items as $item) {

        $value = !empty($item['value'])
            ? esc_html($item['value'])
            : '';

        $label = !empty($item['label'])
            ? esc_html($item['label'])
            : '';

        if ($value === '' && $label === '') {
            continue;
        }

        $html .= '<!-- wp:column -->';
        $html .= '<div class="wp-block-column">';

        if ($value !== '') {

            $html .= '<!-- wp:heading {"level":2,"textAlign":"center"} -->';
            $html .= '<h2 class="has-text-align-center">' . $value . '</h2>';
            $html .= '<!-- /wp:heading -->';
        }

        if ($label !== '') {

            $html .= '<!-- wp:paragraph {"align":"center"} -->';
            $html .= '<p class="has-text-align-center">' . $label . '</p>';
            $html .= '<!-- /wp:paragraph -->';
        }

        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_highlight_box($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $content = !empty($attrs['content'])
        ? wp_kses_post($attrs['content'])
        : '';

    if ($title === '' && $content === '') {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-highlight"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-highlight">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":3} -->';
        $html .= '<h3>' . $title . '</h3>';
        $html .= '<!-- /wp:heading -->';
    }

    if ($content !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $content . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_testimonials($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : __('Testimonials', 'aiomatic-automatic-ai-content-writer');

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    if (empty($items)) {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-testimonials"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-testimonials">';

    $html .= '<!-- wp:heading {"level":2} -->';
    $html .= '<h2>' . $title . '</h2>';
    $html .= '<!-- /wp:heading -->';

    $html .= '<!-- wp:columns -->';
    $html .= '<div class="wp-block-columns">';

    foreach ($items as $item) {

        $quote = !empty($item['quote'])
            ? wp_kses_post($item['quote'])
            : '';

        $name = !empty($item['name'])
            ? esc_html($item['name'])
            : '';

        $role = !empty($item['role'])
            ? esc_html($item['role'])
            : '';

        $html .= '<!-- wp:column -->';
        $html .= '<div class="wp-block-column">';

        $html .= '<!-- wp:quote -->';
        $html .= '<blockquote class="wp-block-quote">';

        if ($quote !== '') {
            $html .= '<p>' . $quote . '</p>';
        }

        if ($name !== '') {

            $html .= '<cite>';

            $html .= $name;

            if ($role !== '') {
                $html .= ' - ' . $role;
            }

            $html .= '</cite>';
        }

        $html .= '</blockquote>';
        $html .= '<!-- /wp:quote -->';

        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_pricing($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : __('Pricing', 'aiomatic-automatic-ai-content-writer');

    $items = !empty($attrs['items']) && is_array($attrs['items'])
        ? $attrs['items']
        : array();

    if (empty($items)) {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-pricing"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-pricing">';

    $html .= '<!-- wp:heading {"level":2,"textAlign":"center"} -->';
    $html .= '<h2 class="has-text-align-center">' . $title . '</h2>';
    $html .= '<!-- /wp:heading -->';

    $html .= '<!-- wp:columns -->';
    $html .= '<div class="wp-block-columns">';

    foreach ($items as $item) {

        $name = !empty($item['name'])
            ? esc_html($item['name'])
            : '';

        $price = !empty($item['price'])
            ? esc_html($item['price'])
            : '';

        $features = !empty($item['features']) && is_array($item['features'])
            ? $item['features']
            : array();

        $button = !empty($item['button'])
            ? esc_html($item['button'])
            : __('Choose Plan', 'aiomatic-automatic-ai-content-writer');

        $button_url = !empty($item['button_url'])
            ? esc_url($item['button_url'])
            : '#';

        $html .= '<!-- wp:column -->';
        $html .= '<div class="wp-block-column">';

        $html .= '<!-- wp:group {"className":"aiomatic-pricing-card"} -->';
        $html .= '<div class="wp-block-group aiomatic-pricing-card">';

        if ($name !== '') {

            $html .= '<!-- wp:heading {"level":3} -->';
            $html .= '<h3>' . $name . '</h3>';
            $html .= '<!-- /wp:heading -->';
        }

        if ($price !== '') {

            $html .= '<!-- wp:heading {"level":2} -->';
            $html .= '<h2>' . $price . '</h2>';
            $html .= '<!-- /wp:heading -->';
        }

        if (!empty($features)) {

            $html .= '<!-- wp:list -->';
            $html .= '<ul>';

            foreach ($features as $feature) {

                $html .= '<li>' .
                    esc_html($feature) .
                    '</li>';
            }

            $html .= '</ul>';
            $html .= '<!-- /wp:list -->';
        }

        $html .= '<!-- wp:buttons -->';
        $html .= '<div class="wp-block-buttons">';
        $html .= '<!-- wp:button -->';
        $html .= '<div class="wp-block-button">';
        $html .= '<a class="wp-block-button__link wp-element-button" href="' . $button_url . '">';
        $html .= $button;
        $html .= '</a>';
        $html .= '</div>';
        $html .= '<!-- /wp:button -->';
        $html .= '</div><!-- /wp:buttons -->';

        $html .= '</div><!-- /wp:group -->';

        $html .= '</div><!-- /wp:column -->';
    }

    $html .= '</div><!-- /wp:columns -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_comparison_table($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $columns = !empty($attrs['columns']) && is_array($attrs['columns'])
        ? $attrs['columns']
        : array();

    $rows = !empty($attrs['rows']) && is_array($attrs['rows'])
        ? $attrs['rows']
        : array();

    if (empty($columns) || empty($rows)) {
        return '';
    }

    $html = '<!-- wp:group {"className":"aiomatic-super-comparison"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-comparison">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2} -->';
        $html .= '<h2>' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    $html .= '<!-- wp:table -->';
    $html .= '<figure class="wp-block-table"><table>';

    $html .= '<thead><tr>';

    foreach ($columns as $column) {

        $html .= '<th>' .
            esc_html($column) .
            '</th>';
    }

    $html .= '</tr></thead>';

    $html .= '<tbody>';

    foreach ($rows as $row) {

        if (!is_array($row)) {
            continue;
        }

        $html .= '<tr>';

        foreach ($row as $cell) {

            $html .= '<td>' .
                wp_kses_post($cell) .
                '</td>';
        }

        $html .= '</tr>';
    }

    $html .= '</tbody>';

    $html .= '</table></figure>';
    $html .= '<!-- /wp:table -->';

    $html .= '</div><!-- /wp:group -->';

    return $html;
}

function aiomatic_super_pages_render_image_banner($attrs)
{
    $title = !empty($attrs['title'])
        ? esc_html($attrs['title'])
        : '';

    $content = !empty($attrs['content'])
        ? wp_kses_post($attrs['content'])
        : '';

    $image_url = !empty($attrs['image_url'])
        ? esc_url_raw($attrs['image_url'])
        : '';

    $attachment_id = !empty($attrs['attachment_id']) ? absint($attrs['attachment_id']) : 0;

    $image_prompt = !empty($attrs['image_prompt'])
        ? esc_attr($attrs['image_prompt'])
        : '';
    $alt = !empty($attrs['alt']) ? esc_attr($attrs['alt']) : esc_attr($title);
    $html = '<!-- wp:group {"className":"aiomatic-super-image-banner"} -->';
    $html .= '<div class="wp-block-group aiomatic-super-image-banner">';

    if ($title !== '') {

        $html .= '<!-- wp:heading {"level":2} -->';
        $html .= '<h2>' . $title . '</h2>';
        $html .= '<!-- /wp:heading -->';
    }

    if ($content !== '') {

        $html .= '<!-- wp:paragraph -->';
        $html .= '<p>' . $content . '</p>';
        $html .= '<!-- /wp:paragraph -->';
    }

    $image = $image_url !== '' ? aiomatic_super_pages_render_image($image_url, $attachment_id, $alt) : '';

    if ($image !== '') {

        $html .= '<!-- wp:html -->';
        $html .= '<figure class="aiomatic-super-image-banner">';
        $html .= $image;
        $html .= '</figure>';
        $html .= '<!-- /wp:html -->';
    }
    elseif ($image_prompt !== '') {

        $html .= '<!-- wp:html -->';
        $html .= '<div class="aiomatic-image-placeholder" data-ai-prompt="' . esc_attr($image_prompt) . '">';
        $html .= esc_html__('AI Image Placeholder', 'aiomatic-automatic-ai-content-writer');
        $html .= '</div>';
        $html .= '<!-- /wp:html -->';
    }

    $html .= '</div><!-- /wp:group -->';

    return $html;
}
add_action('wp_ajax_aiomatic_super_page_lead_submit', 'aiomatic_super_page_lead_submit');
add_action('wp_ajax_nopriv_aiomatic_super_page_lead_submit', 'aiomatic_super_page_lead_submit');

function aiomatic_super_page_lead_submit()
{
    if (
        empty($_POST['nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aiomatic_super_page_lead_submit')
    ) {
        wp_send_json_error(array(
            'message' => esc_html__('Security check failed.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    $name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
    $email   = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
    $phone   = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
    $website = isset($_POST['website']) ? esc_url_raw(wp_unslash($_POST['website'])) : '';
    $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
    $page    = isset($_POST['page_title']) ? sanitize_text_field(wp_unslash($_POST['page_title'])) : '';

    if (!$email || !is_email($email)) {
        wp_send_json_error(array(
            'message' => esc_html__('Please enter a valid email address.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    $to = get_option('admin_email');

    $subject = sprintf(
        __('New lead from %s', 'aiomatic-automatic-ai-content-writer'),
        wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES)
    );

    $body  = "New lead submitted from an AI generated page.\n\n";
    $body .= "Page: " . $page . "\n";
    $body .= "Name: " . $name . "\n";
    $body .= "Email: " . $email . "\n";
    $body .= "Phone: " . $phone . "\n";
    $body .= "Website: " . $website . "\n";
    $body .= "Message:\n" . $message . "\n";

    $headers = array();

    if ($email) {
        $headers[] = 'Reply-To: ' . $name . ' <' . $email . '>';
    }

    $sent = wp_mail($to, $subject, $body, $headers);

    if (!$sent) {
        wp_send_json_error(array(
            'message' => esc_html__('The message could not be sent. Please try again later.', 'aiomatic-automatic-ai-content-writer'),
        ));
    }

    wp_send_json_success(array(
        'message' => esc_html__('Thank you. Your message was sent successfully.', 'aiomatic-automatic-ai-content-writer'),
    ));
}
