<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/templates/modules.php
// Description: Modules tab -- AI providers, image providers, social channel cards, module sections - NUCLEAR+++
// Last Edited: 2026-05-18
// ==================================================
if (!defined('ABSPATH')) {
    exit;
}

$current_plan    = (string) get_option('automarketer_ai_plan_id', 'free');
$module_over_limit = (int) get_option('amai_module_over_limit', 0);
$active_ai_count = 0;
$active_img_count = 0;
$active_modules  = (array) get_option('amai_active_modules', []);
foreach ($active_modules as $mod_id) {
    if (is_string($mod_id) && str_starts_with($mod_id, 'ai-')) {
        $active_ai_count++;
    }
    if (is_string($mod_id) && str_starts_with($mod_id, 'img-')) {
        $active_img_count++;
    }
}
$free_limit_reached     = $active_ai_count >= 1;
$img_free_limit_reached = $active_img_count >= 1;
$starter_slots_full     = in_array($current_plan, ['starter', 'starter_pro'], true)
    && PlanEnforcer::starterSlotsFull($active_modules);

$active_provider_name = 'Unknown';
$single_model_notice  = '';
foreach ($ai_providers as $provider) {
    if (in_array($provider->get_id(), $active_modules)) {
        $pid                  = $provider->get_id();
        $active_provider_name = $provider->get_name();
        $single_model_notice  = $provider->get_single_model_notice();
        break;
    }
}

$active_img_provider_name = 'Unknown';
foreach ($image_providers as $provider) {
    if (in_array($provider->get_id(), $active_modules)) {
        $pid               = $provider->get_id();
        $saved_label       = (string) get_option('amai_model_label_' . $pid, '');
        $saved_model       = (string) get_option('amai_model_' . $pid, '');
        $available_models  = $provider->get_available_models();
        if ($saved_label !== '') {
            $active_img_provider_name = explode(' -- ', $saved_label)[0];
        } elseif ($saved_model !== '' && isset($available_models[$saved_model])) {
            $active_img_provider_name = explode(' -- ', $available_models[$saved_model])[0];
        } else {
            $active_img_provider_name = $provider->get_name();
        }
        break;
    }
}

$ajax_nonce = wp_create_nonce('amai_provider_actions');

// Help steps
$all_help_steps = (function (): array {
    $path = AMAI_PLUGIN_DIR . 'includes/provider-help-steps.php';
    return is_file($path) ? (require $path) : [];
})();

// Copy provider meta
$provider_meta = [
    'ai-claude' => [
        'icon'          => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M17.153 10.408 12.38 1.503a.538.538 0 0 0-.958 0l-1.938 3.62 4.97 9.29 2.699-3.997v-.008Zm2.428 6.128-3.699-6.914-2.7 4.004 2.34 4.373a.538.538 0 0 0 .959 0l1.1-2.055v1.592ZM6.437 22.5l1.938-3.622 4.97-9.289-4.97-9.086L6.437 3.5v19ZM4.01 16.536l3.699 6.914 2.7-4.004-2.34-4.373a.538.538 0 0 0-.959 0l-1.1 2.055V16.536Z" fill="currentColor"/></svg>',
        'icon_color'    => '#1C1917',
        'tagline'       => 'Best for long-form copy',
        'recommended'   => true,
        'blurb'         => 'Anthropic\'s Claude is exceptional at long-form writing, nuanced copy, and careful reasoning - our top pick for marketing content.',
        'prefix'        => 'sk-ant-',
        'default_model' => 'claude-sonnet-4-6',
        'console'       => 'https://console.anthropic.com',
        'help_steps'    => $all_help_steps['ai-claude'] ?? [],
    ],
    'ai-gemini' => [
        'icon'          => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M12 24A14.304 14.304 0 000 12 14.304 14.304 0 0012 0a14.304 14.304 0 0012 12 14.304 14.304 0 00-12 12z" fill="currentColor"/></svg>',
        'icon_color'    => '#4285F4',
        'tagline'       => 'Best for research & multi-format content',
        'recommended'   => false,
        'blurb'         => 'Gemini handles text, images, and long documents naturally - ideal for research-heavy campaigns and multi-format marketing.',
        'prefix'        => 'AIzaSy',
        'default_model' => 'gemini-1.5-pro',
        'console'       => 'https://aistudio.google.com',
        'help_steps'    => $all_help_steps['ai-gemini'] ?? [],
    ],
    'ai-grok'   => [
        'icon'          => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M14.095 11.079 20.9 3h-1.595l-5.897 6.886L8.745 3H3.5l7.131 10.383L3.5 21h1.595l6.237-7.284L16.255 21H21.5l-7.405-9.921Zm-2.208 2.579-.723-1.037L5.76 4.19h2.476l4.64 6.641.723 1.037 6.035 8.635h-2.476l-4.271-6.845Z" fill="currentColor"/></svg>',
        'icon_color'    => '#1C1917',
        'tagline'       => 'Best for real-time & trending content',
        'recommended'   => false,
        'blurb'         => 'Grok taps into real-time information and sharp reasoning - great for trend-driven content and campaigns that need to stay current.',
        'prefix'        => 'xai-',
        'default_model' => 'grok-beta',
        'console'       => 'https://console.x.ai',
        'help_steps'    => $all_help_steps['ai-grok'] ?? [],
    ],
    'ai-openai' => [
        'icon'          => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M22.282 9.821a5.985 5.985 0 00-.516-4.91 6.046 6.046 0 00-6.51-2.9A6.065 6.065 0 004.981 4.18a5.985 5.985 0 00-3.998 2.9 6.046 6.046 0 00.743 7.097 5.98 5.98 0 00.51 4.911 6.051 6.051 0 006.515 2.9A5.985 5.985 0 0013.26 24a6.056 6.056 0 005.772-4.206 5.99 5.99 0 003.997-2.9 6.056 6.056 0 00-.747-7.073zM13.26 22.43a4.476 4.476 0 01-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 00.392-.681v-6.737l2.02 1.168a.071.071 0 01.038.052v5.583a4.504 4.504 0 01-4.494 4.494zM3.6 18.304a4.47 4.47 0 01-.535-3.014l.142.085 4.783 2.759a.771.771 0 00.78 0l5.843-3.369v2.332a.08.08 0 01-.032.067L9.77 19.99a4.5 4.5 0 01-6.17-1.686zm-1.15-9.836a4.474 4.474 0 012.343-1.968V13.3a.776.776 0 00.388.676l5.815 3.355-2.02 1.168a.076.076 0 01-.071 0L4.03 15.71a4.5 4.5 0 01-.58-7.242zm16.625 3.864l-5.843-3.37 2.02-1.163a.076.076 0 01.071 0l4.876 2.815a4.5 4.5 0 01-.676 8.105v-5.81a.79.79 0 00-.448-.677zm2.013-3.02l-.141-.085-4.774-2.782a.776.776 0 00-.785 0L9.56 10.81V8.473a.08.08 0 01.032-.067l4.878-2.815a4.5 4.5 0 016.66 4.664zm-12.64 4.135l-2.02-1.164a.08.08 0 01-.038-.057V6.075a4.5 4.5 0 017.375-3.453l-.142.08L8.85 5.46a.795.795 0 00-.392.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z" fill="currentColor"/></svg>',
        'icon_color'    => '#10A37F',
        'tagline'       => 'Best for versatility & integrations',
        'recommended'   => false,
        'blurb'         => 'OpenAI\'s GPT models are battle-tested across industries - reliable, versatile, and supported by more tools than any other provider.',
        'prefix'        => 'sk-proj-',
        'default_model' => 'gpt-4o',
        'console'       => 'https://platform.openai.com',
        'help_steps'    => $all_help_steps['ai-openai'] ?? [],
    ],
    'ai-mistral' => [
        'icon'          => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M3 3h4v4H3zm0 7h4v4H3zm0 7h4v4H3zm7-14h4v4h-4zm0 7h4v4h-4zm0 7h4v4h-4zm7-14h4v4h-4zm0 14h4v4h-4zm0-7h4v4h-4z" fill="currentColor"/></svg>',
        'icon_color'    => '#FF7000',
        'tagline'       => 'Best for cost-efficient & multilingual content',
        'recommended'   => false,
        'blurb'         => 'Mistral delivers high-quality marketing copy with no monthly minimum. Pay only for what you use - ideal for businesses watching their costs.',
        'prefix'        => '',
        'default_model' => 'mistral-small-latest',
        'console'       => 'https://console.mistral.ai',
        'help_steps'    => $all_help_steps['ai-mistral'] ?? [],
    ],
];

// Image provider meta
$image_provider_meta = [
    'img-dalle' => [
        'icon'           => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M22.282 9.821a5.985 5.985 0 00-.516-4.91 6.046 6.046 0 00-6.51-2.9A6.065 6.065 0 004.981 4.18a5.985 5.985 0 00-3.998 2.9 6.046 6.046 0 00.743 7.097 5.98 5.98 0 00.51 4.911 6.051 6.051 0 006.515 2.9A5.985 5.985 0 0013.26 24a6.056 6.056 0 005.772-4.206 5.99 5.99 0 003.997-2.9 6.056 6.056 0 00-.747-7.073zM13.26 22.43a4.476 4.476 0 01-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 00.392-.681v-6.737l2.02 1.168a.071.071 0 01.038.052v5.583a4.504 4.504 0 01-4.494 4.494zM3.6 18.304a4.47 4.47 0 01-.535-3.014l.142.085 4.783 2.759a.771.771 0 00.78 0l5.843-3.369v2.332a.08.08 0 01-.032.067L9.77 19.99a4.5 4.5 0 01-6.17-1.686zm-1.15-9.836a4.474 4.474 0 012.343-1.968V13.3a.776.776 0 00.388.676l5.815 3.355-2.02 1.168a.076.076 0 01-.071 0L4.03 15.71a4.5 4.5 0 01-.58-7.242zm16.625 3.864l-5.843-3.37 2.02-1.163a.076.076 0 01.071 0l4.876 2.815a4.5 4.5 0 01-.676 8.105v-5.81a.79.79 0 00-.448-.677zm2.013-3.02l-.141-.085-4.774-2.782a.776.776 0 00-.785 0L9.56 10.81V8.473a.08.08 0 01.032-.067l4.878-2.815a4.5 4.5 0 016.66 4.664zm-12.64 4.135l-2.02-1.164a.08.08 0 01-.038-.057V6.075a4.5 4.5 0 017.375-3.453l-.142.08L8.85 5.46a.795.795 0 00-.392.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z" fill="currentColor"/></svg>',
        'icon_color'     => '#10A37F',
        'tagline'        => 'Best for prompt accuracy',
        'recommended'    => true,
        'blurb'          => 'OpenAI\'s DALL-E 3 generates high-quality, prompt-accurate marketing visuals. Uses your existing OpenAI API key.',
        'prefix'         => 'sk-',
        'default_model'  => 'dall-e-3',
        'console'        => 'https://platform.openai.com',
        'help_steps'     => $all_help_steps['img-dalle'] ?? [],
        'cost_per_image' => '$0.04 / image',
    ],
    'img-imagen' => [
        'icon'           => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M12 24c-.2-6.3-5.7-11.8-12-12 6.3-.2 11.8-5.7 12-12 .2 6.3 5.7 11.8 12 12-6.3.2-11.8 5.7-12 12z" fill="currentColor"/></svg>',
        'icon_color'     => '#4285F4',
        'tagline'        => 'Best for photorealism',
        'recommended'    => false,
        'blurb'          => 'Google\'s Imagen produces photorealistic images with significantly improved detail and prompt accuracy. Uses your existing Google AI API key.',
        'prefix'         => 'AIzaSy',
        'default_model'  => 'imagen-4.0-generate-001',
        'console'        => 'https://aistudio.google.com',
        'help_steps'     => $all_help_steps['img-imagen'] ?? [],
        'cost_per_image' => '$0.04 / image',
    ],
    'img-aurora' => [
        'icon'           => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M14.095 11.079 20.9 3h-1.595l-5.897 6.886L8.745 3H3.5l7.131 10.383L3.5 21h1.595l6.237-7.284L16.255 21H21.5l-7.405-9.921Zm-2.208 2.579-.723-1.037L5.76 4.19h2.476l4.64 6.641.723 1.037 6.035 8.635h-2.476l-4.271-6.845Z" fill="currentColor"/></svg>',
        'icon_color'     => '#1C1917',
        'tagline'        => 'Best for stylized & bold visuals',
        'recommended'    => false,
        'blurb'          => 'xAI\'s Aurora creates striking, stylized visuals with a distinct aesthetic. Uses your existing Grok API key.',
        'prefix'         => 'xai-',
        'default_model'  => 'aurora',
        'console'        => 'https://console.x.ai',
        'help_steps'     => $all_help_steps['img-aurora'] ?? [],
        'cost_per_image' => '$0.02 / image',
    ],
    'img-flux' => [
        'icon'           => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M4 4h4v4H4zm0 6h4v4H4zm0 6h4v4H4zm6-12h4v4h-4zm0 12h4v4h-4zm6-12h4v4h-4zm0 6h4v4h-4zm0 6h4v4h-4zM10 10h4v4h-4z" fill="currentColor"/></svg>',
        'icon_color'     => '#6B21A8',
        'tagline'        => 'Best for speed and quality',
        'recommended'    => false,
        'blurb'          => 'Black Forest Labs\' Flux produces high-quality, prompt-accurate marketing visuals with fast generation times.',
        'prefix'         => '',
        'default_model'  => 'flux-pro-1.1',
        'console'        => 'https://dashboard.bfl.ai',
        'help_steps'     => $all_help_steps['img-flux'] ?? [],
        'cost_per_image' => '$0.04 / image',
    ],
    'img-sd' => [
        'icon'           => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z" fill="currentColor"/></svg>',
        'icon_color'     => '#7C3AED',
        'tagline'        => 'Best for creative range',
        'recommended'    => false,
        'blurb'          => 'Stability AI\'s Stable Diffusion generates diverse, high-quality marketing visuals with strong creative range and competitive pricing.',
        'prefix'         => 'sk-',
        'default_model'  => 'core',
        'console'        => 'https://platform.stability.ai',
        'help_steps'     => $all_help_steps['img-sd'] ?? [],
        'cost_per_image' => '$0.03 / image',
    ],
];

// New-model flags from ModelWatcher
$new_model_flags = [];
foreach (array_merge(array_keys($ai_providers ?? []), array_keys($image_providers ?? [])) as $pid) {
    $new = (array) get_option('amai_new_models_' . $pid, []);
    if (!empty($new)) {
        $new_model_flags[$pid] = $new;
    }
}

// Connection state
$fb_connection    = \AutoMarketerAI\FacebookAuth::getConnection();
$fb_connected     = $fb_connection !== null;
$ig_account_id    = \AutoMarketerAI\FacebookAuth::getInstagramAccountId();
$ig_connected     = $ig_account_id !== null;
$tk_connection    = \AutoMarketerAI\TikTokAuth::getConnection();
$tk_connected     = $tk_connection !== null;
$x_connection     = \AutoMarketerAI\XAuth::getConnection();
$x_connected      = $x_connection !== null;
$google_connection = \AutoMarketerAI\GoogleAuth::getConnection();
$google_connected  = $google_connection !== null;
$show_image_step  = true;
?>

<!-- PAGE HEADER -->
<div id="amai-mod-header">
    <h1>Modules</h1>
    <p>Connect your AI provider, then link your social channels to start generating and scheduling posts.</p>
    <?php include AMAI_PLUGIN_DIR . 'templates/partials/tabs.php'; ?>
</div>

<?php if (empty($license_key)): ?>
    <div id="amai-modules-license-warn">
        Please activate a license (free or paid) to use any modules.
    </div>
<?php else: ?>

<div id="amai-root">
<?php if ($module_over_limit > 0 && in_array($current_plan, ['starter', 'starter_pro'], true)): ?>
    <div class="amai-over-limit-banner">
        <strong>You are over your Starter plan module limit.</strong>
        Please deactivate <?php echo esc_html((string) $module_over_limit); ?> module<?php echo $module_over_limit > 1 ? 's' : ''; ?> to stay within your plan.
    </div>
<?php endif; ?>

    <?php
    $nudge_engine = \AutoMarketerAI\NudgeEngine::init();
    $nudge_key    = $nudge_engine->getActiveNudge();
    if ($nudge_key !== null) {
        $nudge_context = 'modules';
        include AMAI_PLUGIN_DIR . 'templates/partials/nudge-card.php';
    }
    ?>

    <!-- COPY PROVIDER -->
    <div class="am-section-head">
        <div class="am-section-step">Copy Provider</div>
        <h2>Choose Your AI Provider</h2>
        <p>Each provider uses your own API key - you control your data and costs directly. Not sure which to pick? Start with Claude - it's our recommendation for most users.</p>
    </div>

    <?php if (empty($ai_providers)): ?>
        <div class="am-empty">No AI providers found.</div>
    <?php else: ?>
        <div class="am-provider-grid">
            <?php foreach ($ai_providers as $module):
                $id               = $module->get_id();
                $is_active        = in_array($id, $active_modules);
                $meta             = $provider_meta[$id] ?? [];
                $icon_color       = $meta['icon_color'] ?? '#D97757';
                $is_recommended   = !empty($meta['recommended']) && !$is_active;
                $show_deactivate  = $is_active;
                $show_change      = $is_active && $module->get_model_count() > 1;
                $show_activate    = !$is_active && !$free_limit_reached;
                $show_locked      = !$is_active && $free_limit_reached;
            ?>
                <div class="am-card <?php echo $is_active ? 'is-active' : ($is_recommended ? 'is-recommended' : ''); ?>" data-module-id="<?php echo esc_attr($id); ?>">

                    <?php if ($is_active): ?>
                        <div class="am-ribbon am-ribbon--active">Active</div>
                    <?php elseif ($is_recommended): ?>
                        <div class="am-ribbon am-ribbon--recommended">&#11088; Recommended</div>
                    <?php endif; ?>
                    <?php if (!empty($new_model_flags[$id])): ?>
                        <div class="am-new-model-badge" title="<?php echo esc_attr(implode(', ', $new_model_flags[$id])); ?>">New model</div>
                    <?php endif; ?>

                    <?php $logo = $module->get_logo_url(); if ($logo !== '') : ?>
                    <div class="am-card-icon" style="background:none;padding:0;overflow:hidden;">
                        <img src="<?php echo esc_url($logo); ?>" alt="<?php echo esc_attr($module->get_name()); ?>" style="width:100%;height:100%;object-fit:cover;border-radius:8px;" />
                    </div>
                    <?php else : ?>
                    <div class="am-card-icon" style="background:<?php echo esc_attr($icon_color); ?>1a;color:<?php echo esc_attr($icon_color); ?>;">
                        <?php echo $meta['icon'] ?? esc_html(substr($module->get_name(), 0, 1)); ?>
                    </div>
                    <?php endif; ?>

                    <div class="am-card-tagline"><?php echo esc_html($meta['tagline'] ?? ''); ?></div>
                    <?php
                    $copy_label = '';
                    if ($is_active) {
                        $copy_label = (string) get_option('amai_model_label_' . $id, '');
                        if ($copy_label !== '') {
                            $copy_label = substr($copy_label, 0, (strpos($copy_label, ' -- ') ?: strlen($copy_label)));
                        }
                    }
                    if ($copy_label === '') {
                        $copy_label = $module->get_name();
                    }
                    ?>
                    <h3 class="am-card-name"><?php echo esc_html($copy_label); ?></h3>
                    <?php
                    $copy_desc = '';
                    if ($is_active && method_exists($module, 'get_model_descriptions')) {
                        $saved_copy_model = (string) get_option('amai_model_' . $id, $module->get_default_model());
                        $copy_descs       = $module->get_model_descriptions();
                        $copy_desc        = $copy_descs[$saved_copy_model] ?? '';
                    }
                    if ($copy_desc === '') {
                        $copy_desc = $meta['blurb'] ?? $module->get_description();
                    }
                    ?>
                    <p class="am-card-desc"><?php echo esc_html($copy_desc); ?></p>

                    <div class="am-card-actions">
                        <?php if ($show_deactivate): ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="amai-toggle-form" data-module-id="<?php echo esc_attr($id); ?>">
                                <input type="hidden" name="action"        value="amai_module_toggle">
                                <input type="hidden" name="module_action" value="deactivate">
                                <input type="hidden" name="module_id"     value="<?php echo esc_attr($id); ?>">
                                <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                                <button type="submit" class="am-btn-deactivate">Deactivate</button>
                            </form>
                            <?php if ($id === 'sms-twilio'): ?>
                            <a href="https://console.twilio.com/us1/billing/manage-billing/billing-overview" target="_blank" rel="noopener noreferrer" class="am-card-note am-card-note--link">Top up Twilio credits</a>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if ($show_change): ?>
                            <button type="button" class="am-btn-change amai-change-model"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>">
                                Change Model
                            </button>
                        <?php endif; ?>
                        <?php if ($show_activate): ?>
                            <button type="button" class="am-btn-activate amai-activate-modal-btn"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>"
                                    data-default-model="<?php echo esc_attr($meta['default_model'] ?? ''); ?>">
                                Activate <?php echo esc_html($module->get_name()); ?>
                            </button>
                            <button type="button" class="am-act-help-link amai-card-help-trigger"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>">
                                <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                                    <circle cx="6.5" cy="6.5" r="5.5" stroke="currentColor" stroke-width="1.3"/>
                                    <path d="M6.5 7.3V7c0-.6.35-.95.78-1.3.35-.27.52-.52.52-.87C7.8 4.13 7.28 3.7 6.5 3.7c-.7 0-1.2.43-1.3 1.04" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
                                    <circle cx="6.5" cy="9.1" r="0.65" fill="currentColor"/>
                                </svg>
                                What you'll need &rarr;
                            </button>
                        <?php endif; ?>
                        <?php if ($show_locked): ?>
                            <div class="am-locked">
                                <button type="button" class="am-locked-btn" disabled>Switch to <?php echo esc_html($module->get_name()); ?></button>
                                <p class="am-locked-hint">Deactivate <?php echo esc_html($active_provider_name); ?> first</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if ($show_image_step): ?>
    <!-- IMAGE PROVIDER -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Image Provider</div>
        <h2>Choose Your Image Provider</h2>
        <p>Instagram posts require an image. Choose an AI image provider and AutoMarketer AI will generate on-brand visuals automatically - no design work needed.</p>
    </div>

    <?php if (empty($image_providers)): ?>
        <div class="am-empty">No image providers found.</div>
    <?php else: ?>
        <div class="am-provider-grid">
            <?php foreach ($image_providers as $module):
                $id                  = $module->get_id();
                $is_active           = in_array($id, $active_modules);
                $meta                = $image_provider_meta[$id] ?? [];
                $icon_color          = $meta['icon_color'] ?? '#D97757';
                $is_recommended      = !empty($meta['recommended']) && !$is_active;
                $img_show_deactivate = $is_active;
                $img_show_change     = $is_active && $module->get_model_count() > 1;
                $img_show_activate   = !$is_active && !$img_free_limit_reached;
                $img_show_locked     = !$is_active && $img_free_limit_reached;
                $saved_img_model     = $is_active ? (string) get_option('amai_model_' . $id, '') : '';
                $saved_img_label     = $is_active ? (string) get_option('amai_model_label_' . $id, '') : '';
                $all_img_models      = $module->get_available_models();
                if ($saved_img_label !== '') {
                    $display_name = explode(' -- ', $saved_img_label)[0];
                } elseif ($saved_img_model !== '' && isset($all_img_models[$saved_img_model])) {
                    $display_name = explode(' -- ', $all_img_models[$saved_img_model])[0];
                } else {
                    $display_name = $module->get_name();
                }
            ?>
                <div class="am-card <?php echo $is_active ? 'is-active' : ($is_recommended ? 'is-recommended' : ''); ?>" data-module-id="<?php echo esc_attr($id); ?>">
                    <?php if ($is_active): ?>
                        <div class="am-ribbon am-ribbon--active">Active</div>
                    <?php elseif ($is_recommended): ?>
                        <div class="am-ribbon am-ribbon--recommended">&#11088; Recommended</div>
                    <?php endif; ?>
                    <?php if (!empty($new_model_flags[$id])): ?>
                        <div class="am-new-model-badge" title="<?php echo esc_attr(implode(', ', $new_model_flags[$id])); ?>">New model</div>
                    <?php endif; ?>
                    <div class="am-card-icon" style="background:<?php echo esc_attr($icon_color); ?>1a;color:<?php echo esc_attr($icon_color); ?>;">
                        <?php echo $meta['icon'] ?? esc_html(substr($module->get_name(), 0, 1)); ?>
                    </div>
                    <div class="am-card-tagline"><?php echo esc_html($meta['tagline'] ?? ''); ?></div>
                    <h3 class="am-card-name" data-base-name="<?php echo esc_attr($module->get_name()); ?>"><?php echo esc_html($display_name); ?></h3>
                    <?php
                    $resolved_cost = '';
                    if ($saved_img_model !== '' && method_exists($module, 'get_model_costs')) {
                        $cost_map      = $module->get_model_costs();
                        $resolved_cost = $cost_map[$saved_img_model] ?? '';
                    }
                    if ($resolved_cost === '') {
                        $resolved_cost = $meta['cost_per_image'] ?? '';
                    }
                    if (!empty($resolved_cost)): ?>
                        <div class="am-card-cost"><?php echo esc_html($resolved_cost); ?></div>
                    <?php endif; ?>
                    <?php
                    $img_card_desc = '';
                    if ($is_active && $saved_img_model !== '' && method_exists($module, 'get_model_descriptions')) {
                        $img_model_descs = $module->get_model_descriptions();
                        $img_card_desc   = $img_model_descs[$saved_img_model] ?? '';
                    }
                    if ($img_card_desc === '') {
                        $img_card_desc = $meta['blurb'] ?? $module->get_description();
                    }
                    ?>
                    <p class="am-card-desc"><?php echo esc_html($img_card_desc); ?></p>
                    <div class="am-card-actions">
                        <?php if ($img_show_deactivate): ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="amai-toggle-form" data-module-id="<?php echo esc_attr($id); ?>">
                                <input type="hidden" name="action"        value="amai_module_toggle">
                                <input type="hidden" name="module_action" value="deactivate">
                                <input type="hidden" name="module_id"     value="<?php echo esc_attr($id); ?>">
                                <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                                <button type="submit" class="am-btn-deactivate">Deactivate</button>
                            </form>
                        <?php endif; ?>
                        <?php if ($img_show_change): ?>
                            <button type="button" class="am-btn-change amai-change-model"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($display_name); ?>">
                                Change Model
                            </button>
                        <?php endif; ?>
                        <?php if ($img_show_activate): ?>
                            <button type="button" class="am-btn-activate amai-activate-modal-btn"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($display_name); ?>"
                                    data-default-model="<?php echo esc_attr($meta['default_model'] ?? ''); ?>">
                                Activate <?php echo esc_html($display_name); ?>
                            </button>
                        <?php endif; ?>
                        <?php if ($img_show_activate && !empty($meta['help_steps'])): ?>
                            <button type="button" class="am-act-help-link amai-card-help-trigger"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>">
                                <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                                    <circle cx="6.5" cy="6.5" r="5.5" stroke="currentColor" stroke-width="1.3"/>
                                    <path d="M6.5 7.3V7c0-.6.35-.95.78-1.3.35-.27.52-.52.52-.87C7.8 4.13 7.28 3.7 6.5 3.7c-.7 0-1.2.43-1.3 1.04" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
                                    <circle cx="6.5" cy="9.1" r="0.65" fill="currentColor"/>
                                </svg>
                                What you'll need &rarr;
                            </button>
                        <?php endif; ?>
                        <?php if ($img_show_locked): ?>
                            <div class="am-locked">
                                <button type="button" class="am-locked-btn" disabled>Switch to <?php echo esc_html($module->get_name()); ?></button>
                                <p class="am-locked-hint">Deactivate <?php echo esc_html($active_img_provider_name); ?> first</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <?php endif; // $show_image_step ?>

    <!-- EMAIL PROVIDER -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Email Provider</div>
        <h2>Email Your Customers Directly</h2>
        <p>Social posts get buried in feeds. Email lands in the inbox - and stays there. Add an email provider and AutoMarketer AI can send your content, promotions, and updates straight to the people who matter most.</p>
    </div>

    <?php if (empty($email_providers)): ?>
        <div class="am-empty">No email providers found.</div>
    <?php else: ?>
        <div id="amai-email-row">
        <div class="am-channel-group-badge" id="amai-email-badge">Free on all plans - even the free one</div>
        <div class="am-woo-row">
        <?php
        $active_email_id = '';
        $active_email_name = '';
        foreach ($email_providers as $_ep) {
            if (in_array($_ep->get_id(), $active_modules, true)) {
                $active_email_id   = $_ep->get_id();
                $active_email_name = $_ep->get_name();
                break;
            }
        }
        ?>
            <?php
            $email_provider_meta = [
                'email-elastic' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#3B3B98"/><line x1="38" y1="68" x2="52" y2="32" stroke="white" stroke-width="8" stroke-linecap="round"/><line x1="55" y1="68" x2="69" y2="32" stroke="white" stroke-width="8" stroke-linecap="round"/></svg>',
                    'icon_color'  => '#6366F1',
                    'tagline'     => 'Best for deliverability & value',
                    'recommended' => true,
                    'blurb'       => 'High-deliverability email for transactional and marketing sends. Pay-as-you-go pricing with no monthly minimums - fractions of a cent per email.',
                ],
                'email-sendgrid' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#1A82E2"/><path d="M30 50h40M50 30v40" stroke="white" stroke-width="8" stroke-linecap="round"/></svg>',
                    'icon_color'  => '#1A82E2',
                    'tagline'     => 'Best for scale & deliverability',
                    'recommended' => false,
                    'blurb'       => 'Industry-standard transactional and marketing email. Reliable delivery, detailed analytics, and a generous free tier to get started.',
                ],
                'email-brevo' => [
                    'icon_color'  => '#0B996E',
                    'tagline'     => 'Free tier with no daily sending cap',
                    'recommended' => false,
                    'blurb'       => 'All-in-one platform for transactional and marketing email. Generous free tier with no daily sending cap, plus SMS and automation built in.',
                ],
                'email-postmark' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#FFDE00"/><path d="M50 25l7 14 16 2-11.5 11 2.7 16L50 61l-14.2 7 2.7-16L27 41l16-2z" fill="#333"/></svg>',
                    'icon_color'  => '#FFDE00',
                    'tagline'     => 'Best for inbox delivery',
                    'recommended' => false,
                    'blurb'       => 'Built for transactional email that has to arrive. Postmark separates transactional and broadcast streams, giving your critical messages the best shot at the inbox every time.',
                ],
                'email-mailgun' => [
                    'icon_color'  => '#F06B26',
                    'tagline'     => 'Best for developer control & routing',
                ],
                'email-resend' => [
                    'icon_color'  => '#000000',
                    'tagline'     => 'Modern API with generous free tier',
                ],
                'email-mandrill' => [
                    'icon_color'  => '#FFE01B',
                    'tagline'     => 'Best for deliverability & reputation',
                ],
            ];
            foreach ($email_providers as $module):
                $id             = $module->get_id();
                $is_active      = in_array($id, $active_modules);
                $meta           = $email_provider_meta[$id] ?? [];
                $icon_color     = $meta['icon_color'] ?? '#6366F1';
                $is_recommended = !empty($meta['recommended']) && !$is_active;
            ?>
                <div class="am-card <?php echo $is_active ? 'is-active' : ($is_recommended ? 'is-recommended' : ''); ?>" data-email-provider-id="<?php echo esc_attr($id); ?>">
                    <?php if ($is_active): ?>
                        <div class="am-ribbon am-ribbon--active">Active</div>
                    <?php elseif ($is_recommended): ?>
                        <div class="am-ribbon am-ribbon--recommended">&#11088; Recommended</div>
                    <?php endif; ?>
                    <div class="am-card-icon" style="background:<?php echo esc_attr($icon_color); ?>1a;color:<?php echo esc_attr($icon_color); ?>;">
                        <?php echo $meta['icon'] ?? esc_html(substr($module->get_name(), 0, 1)); ?>
                    </div>
                    <div class="am-card-tagline"><?php echo esc_html($meta['tagline'] ?? ''); ?></div>
                    <h3 class="am-card-name"><?php echo esc_html($module->get_name()); ?></h3>
                    <p class="am-card-desc"><?php echo esc_html($meta['blurb'] ?? $module->get_description()); ?></p>
                    <div class="am-card-actions">
                        <?php if ($is_active): ?>
                            <div class="am-email-sender-info" style="margin-bottom:12px;font-size:13px;color:#555;">
                                <span style="font-weight:600;">Sending as:</span>
                                <?php echo esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()); ?>
                                &lt;<?php echo esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()); ?>&gt;
                            </div>
                            <div class="am-card-actions">
                                <button type="button" class="am-btn-change amai-activate-modal-btn" data-provider-id="<?php echo esc_attr($id); ?>" data-provider-name="<?php echo esc_attr($module->get_name()); ?>" data-email-provider="1">
                                    Update Key
                                </button>
                                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                                    <input type="hidden" name="action"        value="amai_module_toggle">
                                    <input type="hidden" name="module_action" value="deactivate">
                                    <input type="hidden" name="module_id"     value="<?php echo esc_attr($id); ?>">
                                    <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                                    <button type="submit" class="am-btn-deactivate">Deactivate</button>
                                </form>
                            </div>
                        <?php else: ?>
                        <?php if ($active_email_id !== '' && $active_email_id !== $id): ?>
                            <div class="am-locked">
                                <button type="button" class="am-locked-btn" disabled>Switch to <?php echo esc_html($module->get_name()); ?></button>
                                <p class="am-locked-hint">Deactivate <?php echo esc_html($active_email_name); ?> first</p>
                            </div>
                        <?php else: ?>
                            <button type="button" class="am-btn-activate amai-activate-modal-btn"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>"
                                    data-email-provider="1">
                                Activate <?php echo esc_html($module->get_name()); ?>
                            </button>
                            <button type="button" class="am-act-help-link amai-card-help-trigger"
                                    data-provider-id="<?php echo esc_attr($id); ?>"
                                    data-provider-name="<?php echo esc_attr($module->get_name()); ?>">
                                <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                                    <circle cx="6.5" cy="6.5" r="5.5" stroke="currentColor" stroke-width="1.3"/>
                                    <path d="M6.5 7.3V7c0-.6.35-.95.78-1.3.35-.27.52-.52.52-.87C7.8 4.13 7.28 3.7 6.5 3.7c-.7 0-1.2.43-1.3 1.04" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
                                    <circle cx="6.5" cy="9.1" r="0.65" fill="currentColor"/>
                                </svg>
                                What you'll need &rarr;
                            </button>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        </div><!-- /#amai-email-row -->
    <?php endif; ?>

    <!-- SMS PROVIDER -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">SMS Provider</div>
        <h2>Send Texts That Get Read</h2>
        <p>Text messages get opened. Connect an SMS provider and AutoMarketer AI can send cart recovery nudges, promotions, and time-sensitive updates straight to your customers' phones.</p>
    </div>

    <?php if (empty($sms_providers)): ?>
        <div class="am-empty">No SMS providers found.</div>
    <?php else: ?>
        <div class="am-woo-row">
            <?php
            $sms_provider_meta = [
                'sms-twilio' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#F22F46"/><path d="M50 28a22 22 0 100 44 22 22 0 000-44zm-8 16a6 6 0 110 12 6 6 0 010-12zm16 0a6 6 0 110 12 6 6 0 010-12z" fill="white"/></svg>',
                    'icon_color'  => '#F22F46',
                    'tagline'     => 'Best for reliability & reach',
                    'recommended' => true,
                    'blurb'       => 'Twilio sends your text messages. Trusted by thousands of businesses worldwide, it\'s simple to set up and charges only for what you send - no monthly fees.',
                ],
                'sms-plivo' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#0D6EFD"/><path d="M32 35h36v8H32zm0 14h24v8H32zm0 14h30v8H32z" fill="white"/></svg>',
                    'icon_color'  => '#0D6EFD',
                    'tagline'     => 'Best for cost-conscious senders',
                    'recommended' => false,
                    'blurb'       => 'Affordable SMS delivery with straightforward pricing and solid deliverability. No monthly fees - pay only for what you send.',
                ],
                'sms-vonage' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#7C3AED"/><path d="M25 30l25 40 25-40H60L50 50 40 30z" fill="white"/></svg>',
                    'icon_color'  => '#7C3AED',
                    'tagline'     => 'Best for scale & Canadian reach',
                    'recommended' => false,
                    'blurb'       => 'Enterprise-grade SMS with global reach and full Canadian support. Ideal for growing businesses that need reliable delivery at scale.',
                ],
                'sms-sinch' => [
                    'icon'        => '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="100" height="100" rx="18" fill="#1C1C1C"/><path d="M30 38h40v8H30zm0 16h28v8H30z" fill="white"/></svg>',
                    'icon_color'  => '#1C1C1C',
                    'tagline'     => 'Best for global reach & simple pricing',
                    'recommended' => false,
                    'blurb'       => 'Global SMS delivery with competitive rates and strong North American coverage. Simple REST API with pay-as-you-go pricing and no monthly fees.',
                ],
            ];
            $active_sms_name = '';
            foreach ($sms_providers as $_sp) { if (in_array($_sp->get_id(), $active_modules)) { $active_sms_name = $_sp->get_name(); break; } }
            foreach ($sms_providers as $module):
                $id             = $module->get_id();
                $is_active      = in_array($id, $active_modules);
                $meta           = $sms_provider_meta[$id] ?? [];
                $icon_color     = $meta['icon_color'] ?? '#F22F46';
                $is_recommended = !empty($meta['recommended']) && !$is_active;
                $has_creds      = $module->is_ready();
            ?>
                <div class="am-card <?php echo $is_active ? 'is-active' : ($is_recommended ? 'is-recommended' : ''); ?>" data-sms-provider-id="<?php echo esc_attr($id); ?>">
                    <?php if ($is_active): ?>
                        <div class="am-ribbon am-ribbon--active">Active</div>
                    <?php elseif ($is_recommended): ?>
                        <div class="am-ribbon am-ribbon--recommended">&#11088; Recommended</div>
                    <?php endif; ?>
                    <div class="am-card-icon" style="background:<?php echo esc_attr($icon_color); ?>1a;color:<?php echo esc_attr($icon_color); ?>;">
                        <?php echo $meta['icon'] ?? esc_html(substr($module->get_name(), 0, 1)); ?>
                    </div>
                    <div class="am-card-tagline"><?php echo esc_html($meta['tagline'] ?? ''); ?></div>
                    <h3 class="am-card-name"><?php echo esc_html($module->get_name()); ?></h3>
                    <p class="am-card-desc"><?php echo esc_html($meta['blurb'] ?? $module->get_description()); ?></p>
                    <div class="am-card-actions">
                        <?php if ($is_active): ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                                <input type="hidden" name="action"        value="amai_module_toggle">
                                <input type="hidden" name="module_action" value="deactivate">
                                <input type="hidden" name="module_id"     value="<?php echo esc_attr($id); ?>">
                                <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                                <button type="submit" class="am-btn-deactivate">Deactivate</button>
                            </form>
                            <?php if ($id === 'sms-twilio'): ?>
                            <a href="https://console.twilio.com/us1/billing/manage-billing/billing-overview" target="_blank" rel="noopener noreferrer" class="am-card-note am-card-note--link">Top up Twilio credits</a>
                            <?php endif; ?>
                        <?php elseif ($active_sms_name !== ''): ?>
                            <div class="am-locked">
                                <button type="button" class="am-locked-btn" disabled>Switch to <?php echo esc_html($module->get_name()); ?></button>
                                <p class="am-locked-hint">Deactivate <?php echo esc_html($active_sms_name); ?> first</p>
                            </div>
                        <?php elseif (!$has_creds): ?>
                            <button type="button" class="am-btn-activate amai-sms-connect-btn"
                                    data-sms-provider-id="<?php echo esc_attr($id); ?>"
                                    data-sms-provider-name="<?php echo esc_html($module->get_name()); ?>">
                                Connect <?php echo esc_html($module->get_name()); ?>
                            </button>
                        <?php else: ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                                <input type="hidden" name="action"        value="amai_module_toggle">
                                <input type="hidden" name="module_action" value="activate">
                                <input type="hidden" name="module_id"     value="<?php echo esc_attr($id); ?>">
                                <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                                <button type="submit" class="am-btn-activate">Connect <?php echo esc_html($module->get_name()); ?></button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- SOCIAL CHANNELS -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Social Channels</div>
        <h2>Social Channels</h2>
        <p>Connect your accounts and AutoMarketer AI will start generating and scheduling posts for you.</p>
    </div>

    <div class="am-channels-row" id="amai-channels-row">
        <div class="am-channel-free-border" id="amai-free-border"></div>
        <div class="am-channel-group-badge" id="amai-free-badge">Free on all plans - even the free one</div>

        <!-- Facebook -->
        <div class="am-card am-card--facebook <?php echo $fb_connected ? 'is-active' : ''; ?>" data-free-channel="1">
            <?php if ($fb_connected): ?>
                <div class="am-ribbon am-ribbon--connected">Connected</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#1877F21a;color:#1877F2;">
                <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon">
                    <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" fill="currentColor"/>
                </svg>
            </div>
            <h3 class="am-card-name">Facebook</h3>
            <p class="am-card-desc">
                <?php if ($fb_connected): ?>
                    Connected to <strong><?php echo esc_html((string) ($fb_connection['page_name'] ?? 'your page')); ?></strong>. AutoMarketer AI is writing and scheduling your posts.
                <?php else: ?>
                    Connect your Facebook page and let AutoMarketer AI write, schedule, and publish posts for you - automatically.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>" class="am-btn-activate">
                    <?php echo $fb_connected ? 'Go to Facebook &rarr;' : 'Connect Facebook &rarr;'; ?>
                </a>
            </div>
        </div>

        <!-- Instagram -->
        <div class="am-card am-card--instagram <?php echo $ig_connected ? 'is-active' : ''; ?>" data-free-channel="1">
            <?php if ($ig_connected): ?>
                <div class="am-ribbon am-ribbon--connected">Connected</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#E1306C1a;color:#E1306C;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon">
                    <rect x="2" y="2" width="20" height="20" rx="5" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="17.5" cy="6.5" r="0.75" fill="currentColor"/>
                </svg>
            </div>
            <h3 class="am-card-name">Instagram</h3>
            <p class="am-card-desc">
                <?php if ($ig_connected): ?>
                    Connected via Facebook. AutoMarketer AI is writing and scheduling your Instagram posts.
                <?php else: ?>
                    Connect your Facebook page first - Instagram links automatically via your Meta Business account.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($ig_connected): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=instagram')); ?>" class="am-btn-activate">Go to Instagram &rarr;</a>
                <?php elseif ($fb_connected): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=instagram')); ?>" class="am-btn-activate">Connect Instagram &rarr;</a>
                <?php else: ?>
                    <span class="am-btn-coming-soon">Connect Facebook First</span>
                <?php endif; ?>
            </div>
        </div>

        <!-- X -->
        <div class="am-card am-card--x <?php echo $x_connected ? 'is-active' : ''; ?>">
            <?php if ($x_connected): ?>
                <div class="am-ribbon am-ribbon--connected">Connected</div>
            <?php elseif ($current_plan === 'free'): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#1C19171a;color:#1C1917;">
                <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="am-svg-icon"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.73-8.835L1.254 2.25H8.08l4.253 5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z" fill="currentColor"/></svg>
            </div>
            <h3 class="am-card-name">X</h3>
            <p class="am-card-desc">
                <?php if ($x_connected): ?>
                    Connected to <strong><?php echo esc_html('@' . (string) ($x_connection['username'] ?? '')); ?></strong>. AutoMarketer AI is writing and scheduling your posts.
                <?php else: ?>
                    Connect your X account and let AutoMarketer AI write, schedule, and publish posts for you - automatically.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=x')); ?>" class="am-btn-activate">
                    <?php echo $x_connected ? 'Go to X &rarr;' : 'Connect X &rarr;'; ?>
                </a>
            </div>
        </div>

        <!-- TikTok -->
        <div class="am-card am-card--tiktok">
            <div class="am-ribbon am-ribbon--coming-soon">Pending Verification</div>
            <div class="am-card-icon" style="background:#0000001a;color:#000000;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon">
                    <path d="M16.6 2h-2.4v9.9a2.9 2.9 0 1 1-2-2.7V6a5.2 5.2 0 1 0 4.4 5.2V7c.9.5 1.9.8 2.9.8V5.1c-1.6-.2-2.9-1.3-2.9-3V2z" fill="currentColor"/>
                </svg>
            </div>
            <h3 class="am-card-name">TikTok</h3>
            <p class="am-card-desc">Connect your TikTok account and let AutoMarketer AI create photo carousel posts for you - automatically.</p>
            <div class="am-card-actions">
                <span class="am-btn-coming-soon">Pending Verification</span>
            </div>
        </div>

        <!-- LinkedIn -->
        <div class="am-card am-card--linkedin">
            <div class="am-ribbon am-ribbon--coming-soon">Pending Verification</div>
            <div class="am-card-icon" style="background:#0A66C21a;color:#0A66C2;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6zM2 9h4v12H2z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="4" cy="4" r="2" stroke="currentColor" stroke-width="1.5"/></svg>
            </div>
            <h3 class="am-card-name">LinkedIn</h3>
            <p class="am-card-desc">Publish AI-written posts to your LinkedIn company page and keep your professional presence active.</p>
            <div class="am-card-actions">
                <span class="am-btn-coming-soon">Pending Verification</span>
            </div>
        </div>
    </div>

    <!-- LOCAL & LISTINGS -->
    <div class="am-section-divider"></div>
    <div class="am-section-head">
        <div class="am-section-step">Local &amp; Listings</div>
        <h2>Show Up Where Locals Are Looking</h2>
        <p>Connect your local listings once. AutoMarketer AI keeps them fresh with updates, offers, and news.</p>
    </div>
    <div class="am-channels-row am-channels-row--local">
        <div class="am-card am-card--google<?php echo $google_connected ? ' am-card--connected' : ''; ?>">
            <div class="am-card-icon" style="background:#4285F41a;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21.805 10.023H12v3.954h5.618c-.242 1.354-1.012 2.5-2.156 3.267v2.717h3.49c2.043-1.882 3.222-4.654 3.222-7.938 0-.664-.057-1.305-.17-1.999z" fill="#4285F4"/>
                    <path d="M12 22c2.97 0 5.46-.984 7.284-2.66l-3.49-2.717c-.984.66-2.244 1.05-3.794 1.05-2.917 0-5.386-1.97-6.268-4.617H2.122v2.806A10.997 10.997 0 0 0 12 22z" fill="#34A853"/>
                    <path d="M5.732 13.056A6.6 6.6 0 0 1 5.386 11c0-.713.122-1.405.346-2.056V6.138H2.122A11.003 11.003 0 0 0 1 11c0 1.775.426 3.454 1.122 4.862l3.61-2.806z" fill="#FBBC05"/>
                    <path d="M12 5.327c1.643 0 3.117.565 4.276 1.674l3.205-3.205C17.454 1.986 14.965 1 12 1A10.997 10.997 0 0 0 2.122 6.138l3.61 2.806C6.614 7.297 9.083 5.327 12 5.327z" fill="#EA4335"/>
                </svg>
            </div>
            <h3 class="am-card-name">Google Business</h3>
            <p class="am-card-desc">Post updates and offers directly to your Google Business Profile - great for local search visibility.</p>
            <div class="am-card-actions">
                <?php if ($google_connected): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=google')); ?>" class="am-btn am-btn--primary">Manage</a>
                <?php else: ?>
                    <a href="<?php echo esc_url(\AutoMarketerAI\GoogleAuth::getAuthUrl()); ?>" class="am-btn-activate">Connect</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

<script>
(function () {
    var row    = document.getElementById("amai-channels-row");
    var border = document.getElementById("amai-free-border");
    var badge  = document.getElementById("amai-free-badge");
    if (!row || !border || !badge) return;
    function sizeBorder() {
        var cards = row.querySelectorAll("[data-free-channel]");
        if (cards.length === 0) return;
        var rowRect = row.getBoundingClientRect();
        var first   = cards[0].getBoundingClientRect();
        var last    = cards[cards.length - 1].getBoundingClientRect();
        var left    = first.left - rowRect.left - 16;
        var right   = last.right - rowRect.left + 10;
        var top     = first.top - rowRect.top - 28;
        var bottom  = last.bottom - rowRect.top + 16;
        border.style.left   = left + "px";
        border.style.top    = top + "px";
        border.style.width  = (right - left) + "px";
        border.style.height = (bottom - top) + "px";
        badge.style.position  = "absolute";
        badge.style.left      = (left + (right - left) / 2) + "px";
        badge.style.top       = (top - 1) + "px";
        badge.style.transform = "translate(-50%, -50%)";
    }
    sizeBorder();
    window.addEventListener("resize", sizeBorder);
}());
</script>

    <!-- EMAIL MARKETING -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Email</div>
        <h2>Email Marketing</h2>
        <p>AI-written emails that go out automatically - from first hello to win-back campaigns. No copywriter required.</p>
    </div>

    <div class="am-coming-grid">
        <div class="am-coming-card">
            <div class="am-coming-icon" style="background:#6366F11a;color:#6366F1;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 6l-10 7L2 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-coming-name">Email Campaigns</div>
            <div class="am-coming-desc">Write and schedule entire email campaigns with AI - from welcome sequences to promotional blasts.</div>
            <span class="am-btn-coming-soon">Coming Soon</span>
        </div>
        <div class="am-coming-card">
            <div class="am-coming-icon" style="background:#6366F11a;color:#6366F1;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" stroke="currentColor" stroke-width="1.5"/><path d="M12 6v6l4 2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
            </div>
            <div class="am-coming-name">Welcome Sequence</div>
            <div class="am-coming-desc">Automatically send a series of onboarding emails when a new customer signs up or makes a purchase.</div>
            <span class="am-btn-coming-soon">Coming Soon</span>
        </div>
        <div class="am-coming-card">
            <div class="am-coming-icon" style="background:#6366F11a;color:#6366F1;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-coming-name">Re-engagement</div>
            <div class="am-coming-desc">Win back customers who have gone quiet with AI-written re-engagement emails sent at the right moment.</div>
            <span class="am-btn-coming-soon">Coming Soon</span>
        </div>
    </div>

    <!-- WOOCOMMERCE -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">WooCommerce</div>
        <h2>WooCommerce Tools</h2>
        <p>Marketing copy and automated emails built specifically for your WooCommerce store - product descriptions, cart recovery, and more.</p>
    </div>
    <div class="am-woo-row">

    <?php
    $store_integration_active = in_array('store-integration', $active_modules, true);
    $store_woo_active         = in_array('store-woocommerce', $active_modules, true);
    $woo_available            = class_exists('WooCommerce');
    ?>
        <div class="am-card <?php echo $store_woo_active ? 'is-active' : ''; ?>">
            <?php if ($store_woo_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#7F54B31a;color:#7F54B3;">
                <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;"><rect width="32" height="32" rx="8" fill="#7F54B3"/><path d="M5 9.5C5 8.4 5.9 7.5 7 7.5h18c1.1 0 2 .9 2 2v9c0 1.1-.9 2-2 2h-7l-4 4v-4H7c-1.1 0-2-.9-2-2v-9z" fill="white"/><path d="M8 13h2.5l1 4.5 2-4.5h1.5l2 4.5 1-4.5H20" stroke="#7F54B3" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-card-tagline">Your store, on autopilot</div>
            <h3 class="am-card-name">Store Promotion</h3>
            <p class="am-card-desc">AutoMarketer AI reads your product catalog, tracks sale events, and automatically writes promotional posts three times a week. New arrivals, sale items, and your full catalog all get their turn - no extra work from you.</p>
            <?php if ($store_integration_active): ?>
            <div class="amai-store-module-toggle">
                <p class="amai-store-module-note">Store Integration is active. Product posts go out Mon, Wed, Fri automatically.
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=store')); ?>">View store dashboard &rarr;</a></p>
            </div>
            <?php endif; ?>
            <div class="am-card-actions">
                <?php if ($store_woo_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="amai_module_toggle">
                        <input type="hidden" name="module_id" value="store-woocommerce">
                        <input type="hidden" name="module_action" value="deactivate">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Disconnect</button>
                    </form>
                <?php elseif (!$woo_available): ?>
                    <div class="am-locked">WooCommerce must be installed and active.</div>
                <?php elseif (!in_array($current_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true)): ?>
                    <div class="am-locked">Upgrade to Starter or above to unlock Store Promotion.</div>
                <?php else: ?>
                    <button type="button" class="am-btn-activate amai-store-connect-btn" data-provider="store-woocommerce" data-name="WooCommerce" data-is-woo="1">
                        Connect WooCommerce
                    </button>
                <?php endif; ?>
            </div>
        </div>

        <?php
        $cart_active = get_option('amai_abandoned_cart_active', '0') === '1';
        $cart_stats  = ($cart_active && class_exists('AutoMarketerAI\\AbandonedCart')) ? AutoMarketerAI\AbandonedCart::getStats() : null;
        ?>
        <div class="am-card <?php echo $cart_active ? 'is-active' : ''; ?>">
            <?php if ($cart_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#7C3AED1a;color:#7C3AED;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" class="am-svg-icon"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>
            </div>
            <h3 class="am-card-name">Abandoned Cart Emails</h3>
            <p class="am-card-desc">Three perfectly timed nudges after they walk away - gentle, effective, and never annoying.</p>
            <?php if ($cart_active): ?>
            <div class="am-cart-stats-link">
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-cart-stats')); ?>" class="am-btn-stats-link">View Stats &rarr;</a>
            </div>
            <?php endif; ?>
            <div class="am-card-actions">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <input type="hidden" name="action" value="amai_abandoned_cart_toggle">
                    <?php wp_nonce_field('amai_abandoned_cart_toggle', '_wpnonce'); ?>
                    <?php if (!class_exists('WooCommerce')): ?>
                        <div class="am-locked">WooCommerce is required for this module.</div>
                    <?php elseif ($cart_active): ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    <?php elseif ($starter_slots_full): ?>
                        <div class="am-locked">All 5 module slots are in use. Deactivate a module to make room.</div>
                    <?php elseif (!in_array($current_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true)): ?>
                        <div class="am-locked">Upgrade to Starter or above to unlock Abandoned Cart Emails.</div>
                    <?php else: ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <?php
        $sms_active   = in_array('abandoned-cart-sms', $active_modules, true);
        $sms_eligible = in_array($current_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true);
        ?>
        <div class="am-card <?php echo $sms_active ? 'is-active' : ''; ?>">
            <?php if ($sms_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$sms_eligible): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#7C3AED1a;color:#7C3AED;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" class="am-svg-icon"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>
            </div>
            <h3 class="am-card-name">Abandoned Cart SMS</h3>
            <p class="am-card-desc">Reach shoppers where they actually look - their texts. When someone abandons their cart, we send them a quick SMS nudge alongside the email.</p>
            <div class="am-card-actions">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <input type="hidden" name="action" value="amai_abandoned_cart_sms_toggle">
                    <?php wp_nonce_field('amai_abandoned_cart_sms_toggle', '_wpnonce'); ?>
                    <?php if (!class_exists('WooCommerce')): ?>
                        <div class="am-locked">WooCommerce is required for this module.</div>
                    <?php elseif (!\AutoMarketerAI\SmsProvider::is_ready()): ?>
                        <div class="am-locked">Activate an SMS provider above to enable SMS nudges.</div>
                    <?php elseif ($sms_active): ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    <?php elseif (!$sms_eligible): ?>
                        <div class="am-locked">Upgrade to Starter or above to unlock this module.</div>
                    <?php elseif ($starter_slots_full): ?>
                        <div class="am-locked">All 5 module slots are in use. Deactivate a module to make room.</div>
                    <?php else: ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <?php
        $reeng_active   = in_array('re-engagement', $active_modules, true);
        $reeng_eligible = in_array($current_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true);
        ?>
        <div class="am-card <?php echo $reeng_active ? 'is-active' : ''; ?>">
            <?php if ($reeng_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$reeng_eligible): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#7C3AED1a;color:#7C3AED;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" class="am-svg-icon"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            </div>
            <h3 class="am-card-name">Re-engagement Emails</h3>
            <p class="am-card-desc">Win back browsers who didn't buy. Tracks products visitors viewed but never purchased, then sends a friendly follow-up 48 hours later - automatically.</p>
            <div class="am-card-actions">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <input type="hidden" name="action" value="amai_re_engagement_toggle">
                    <?php wp_nonce_field('amai_re_engagement_toggle', '_wpnonce'); ?>
                    <?php if (!class_exists('WooCommerce')): ?>
                        <div class="am-locked">WooCommerce is required for this module.</div>
                    <?php elseif ($reeng_active): ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    <?php elseif (!$reeng_eligible): ?>
                        <div class="am-locked">Upgrade to Starter or above to unlock this module.</div>
                    <?php elseif ($starter_slots_full): ?>
                        <div class="am-locked">All 5 module slots are in use. Deactivate a module to make room.</div>
                    <?php else: ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <div class="am-coming-grid">
            <div class="am-coming-card">
                <div class="am-coming-icon" style="background:#7C3AED1a;color:#7C3AED;">
                    <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
                </div>
                <div class="am-coming-name">Product Description Writer</div>
                <div class="am-coming-desc">Knock out a perfectly optimized product description in minutes - one at a time, done right.</div>
                <span class="am-btn-coming-soon">Coming Soon</span>
            </div>
            <div class="am-coming-card">
                <div class="am-coming-icon" style="background:#7C3AED1a;color:#7C3AED;">
                    <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
                </div>
                <div class="am-coming-name">Sale Announcement Generator</div>
                <div class="am-coming-desc">Turn your WooCommerce sale events into ready-to-send emails and social posts automatically.</div>
                <span class="am-btn-coming-soon">Coming Soon</span>
            </div>
            <div class="am-coming-card">
                <div class="am-coming-icon" style="background:#7C3AED1a;color:#7C3AED;">
                    <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
                </div>
                <div class="am-coming-name">Review Request</div>
                <div class="am-coming-desc">Ask for reviews at exactly the right moment - when customers are happiest.</div>
                <span class="am-btn-coming-soon">Coming Soon</span>
            </div>
        </div>
    </div>

    <!-- ADVERTISING -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Advertising</div>
        <h2>Ad Copy</h2>
        <p>Stop staring at a blank ad editor. Let AI write your headlines, descriptions, and CTAs - ready to paste into Google or Meta.</p>
    </div>

    <div class="am-coming-grid">
        <div class="am-coming-card">
            <div class="am-coming-icon" style="background:#0EA5E91a;color:#0EA5E9;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4M10 17l5-5-5-5M13 12H3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-coming-name">Ad Copy Generator</div>
            <div class="am-coming-desc">Generate headlines, descriptions, and calls-to-action for Google Ads and Meta campaigns in seconds.</div>
            <span class="am-btn-coming-soon">Coming Soon</span>
        </div>
    </div>

    <!-- SEO & CONTENT -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">SEO &amp; Content</div>
        <h2>SEO &amp; Blog Content</h2>
        <p>Rank higher and stay top of mind with AI-written blog posts built around your keywords and your business.</p>
    </div>

<?php
    $co_active   = in_array('content-optimizer', (array) get_option('amai_active_modules', []), true);
    $co_plan     = (string) get_option('automarketer_ai_plan_id', 'free');
    $co_eligible = in_array($co_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true);
?>
    <div class="am-woo-row">

        <div class="am-card <?php echo $co_active ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($co_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$co_eligible): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#10B9811a;color:#10B981;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-card-tagline">Score and improve every post</div>
            <h3 class="am-card-name">Content Optimizer</h3>
            <p class="am-card-desc">
                <?php if ($co_active): ?>
                    SEO scoring, one-click fixes, and Google snippet previews for every post.
                <?php else: ?>
                    Score your content for SEO, fix issues with one click, and preview exactly how Google will show your page.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($co_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="deactivate">
                        <input type="hidden" name="module_id"     value="content-optimizer">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    </form>
                <?php elseif ($co_eligible && !$starter_slots_full): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="activate">
                        <input type="hidden" name="module_id"     value="content-optimizer">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    </form>
                <?php elseif ($co_eligible && $starter_slots_full): ?>
                    <div class="am-locked">All 5 module slots are in use. Deactivate a module to make room.</div>
                <?php else: ?>
                    <div class="am-locked">Upgrade to Starter or above to unlock this module.</div>
                <?php endif; ?>
            </div>
        </div>

<?php
    $bg_active   = in_array('blog-generator', (array) get_option('amai_active_modules', []), true);
    $bg_plan     = (string) get_option('automarketer_ai_plan_id', 'free');
    $bg_eligible = in_array($bg_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true);
?>
        <div class="am-card <?php echo $bg_active ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($bg_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$bg_eligible): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#10B9811a;color:#10B981;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-card-tagline">AI-written posts, published instantly</div>
            <h3 class="am-card-name">Blog Post Generator</h3>
            <p class="am-card-desc">
                <?php if ($bg_active): ?>
                    Active. Use Write with AI on any post to generate titles and full content from your business profile.
                <?php else: ?>
                    Generate complete blog posts on any topic - published directly to WordPress or saved as drafts.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($bg_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="deactivate">
                        <input type="hidden" name="module_id"     value="blog-generator">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    </form>
                <?php elseif ($bg_eligible && !$starter_slots_full): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="activate">
                        <input type="hidden" name="module_id"     value="blog-generator">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    </form>
                <?php elseif ($bg_eligible && $starter_slots_full): ?>
                    <div class="am-locked">All 5 module slots are in use. Deactivate a module to make room.</div>
                <?php else: ?>
                    <div class="am-locked">Upgrade to Starter or above to unlock this module.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- REPUTATION -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Reputation</div>
        <h2>Reputation Management</h2>
        <p>Manage every comment, reply, and review from one inbox. AI drafts responses, you stay in control.</p>
    </div>

<?php
    $cm_active   = in_array('comment-manager', (array) get_option('amai_active_modules', []), true);
    $cm_plan     = (string) get_option('automarketer_ai_plan_id', 'free');
    $cm_eligible = in_array($cm_plan, ['unlimited_ai', 'agency'], true);
?>
    <div class="am-woo-row">

        <div class="am-card <?php echo $cm_active ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($cm_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php else: ?>
                <div class="am-ribbon am-ribbon--premium">Premium</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#7C3AED1a;color:#7C3AED;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-card-tagline">One inbox for every conversation</div>
            <h3 class="am-card-name">Comment Manager</h3>
            <p class="am-card-desc">
                <?php if ($cm_active): ?>
                    Active. Social comments, blog replies, and product reviews all in one inbox - with AI reply drafts and automatic sentiment scoring on every comment.
                <?php else: ?>
                    Manage comments from Facebook, Instagram, X, your blog, and product reviews - all in one place with AI reply drafts and sentiment scoring.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($cm_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="deactivate">
                        <input type="hidden" name="module_id"     value="comment-manager">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    </form>
                <?php elseif ($cm_eligible): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="activate">
                        <input type="hidden" name="module_id"     value="comment-manager">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    </form>
                <?php else: ?>
                    <div class="am-locked">Upgrade to Unlimited AI or above to unlock this module.</div>
                <?php endif; ?>
            </div>
        </div>

        <?php
        $rr_active   = in_array('review-responder', $active_modules, true);
        $rr_eligible = in_array($current_plan, ['unlimited_ai', 'agency'], true);
        ?>
        <div class="am-card <?php echo $rr_active ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($rr_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php else: ?>
                <div class="am-ribbon am-ribbon--premium">Premium</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#F59E0B1a;color:#F59E0B;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon"><path d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="am-card-tagline">Never let a review go unanswered</div>
            <h3 class="am-card-name">Review Responder</h3>
            <p class="am-card-desc">
                <?php if ($rr_active): ?>
                    Active. Google, Facebook, and more - every review gets an AI-drafted response ready for your approval or sent automatically.
                <?php else: ?>
                    Monitor reviews across Google, Facebook, and more. AI drafts responses automatically - you approve, edit, or let autopilot handle it.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($rr_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="amai_review_responder_toggle">
                        <input type="hidden" name="module_action" value="deactivate">
                        <?php wp_nonce_field('amai_review_responder_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Deactivate</button>
                    </form>
                <?php elseif ($rr_eligible): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="amai_review_responder_toggle">
                        <input type="hidden" name="module_action" value="activate">
                        <?php wp_nonce_field('amai_review_responder_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    </form>
                <?php else: ?>
                    <div class="am-locked">Upgrade to Unlimited AI or above to unlock this module.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- ANALYTICS -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Analytics</div>
        <h2>Analytics</h2>
        <p>Connect your analytics platform to see real traffic data for every post and unlock content performance insights.</p>
    </div>

    <div class="am-woo-row">
    <?php
    $ga4_eligible  = in_array($current_plan, ['starter', 'starter_pro', 'unlimited_ai', 'agency'], true);
    $ga4_connected = AutoMarketerAI\Ga4Auth::isConnected();
    $ga4_conn      = $ga4_connected ? AutoMarketerAI\Ga4Auth::getConnection() : null;
    $ga4_active    = in_array('analytics-ga4', $active_modules, true);
    $ga4_auth_url  = $ga4_eligible ? esc_url(AutoMarketerAI\Ga4Auth::getAuthUrl()) : '';
    ?>
        <div class="am-card <?php echo $ga4_connected ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($ga4_connected): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$ga4_eligible): ?>
                <div class="am-ribbon am-ribbon--starter">Starter and above</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#E8F0FE;color:#4285F4;">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" fill="#4285F4" opacity=".15"/>
                    <path d="M7 17V10" stroke="#4285F4" stroke-width="2" stroke-linecap="round"/>
                    <path d="M12 17V7" stroke="#EA4335" stroke-width="2" stroke-linecap="round"/>
                    <path d="M17 17v-5" stroke="#34A853" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </div>
            <div class="am-card-tagline">Know what is working</div>
            <h3 class="am-card-name">Google Analytics 4</h3>
            <p class="am-card-desc">Connect your GA4 property to see real traffic data for every post - sessions, pageviews, and trending direction. Powers content decay alerts and post performance insights.</p>
            <?php if ($ga4_connected && $ga4_conn): ?>
                <div class="amai-store-module-toggle">
                    <p class="amai-store-module-note">
                        Connected<?php if (!empty($ga4_conn['property_name'])): ?>: <?php echo esc_html($ga4_conn['property_name']); ?><?php endif; ?>.
                        <?php if (!empty($ga4_conn['last_synced_at'])): ?>
                            Last synced <?php echo esc_html(human_time_diff(strtotime($ga4_conn['last_synced_at']), time())); ?> ago.
                        <?php else: ?>
                            Not yet synced.
                        <?php endif; ?>
                    </p>
                </div>
                <div class="am-card-actions">
                    <button type="button" class="am-btn-deactivate" id="ga4-disconnect-btn" data-nonce="<?php echo esc_attr(wp_create_nonce('amai_ga4_disconnect')); ?>">
                        Disconnect
                    </button>
                </div>
                <p class="am-card-note">Traffic data syncs automatically once per day.</p>
            <?php elseif (!$ga4_eligible): ?>
                <div class="am-card-actions">
                    <div class="am-locked">Upgrade to Starter or above to unlock this module.</div>
                </div>
            <?php else: ?>
                <div class="am-card-actions">
                    <a href="<?php echo $ga4_auth_url; ?>" class="am-btn-activate">Connect GA4</a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- CONTENT INTELLIGENCE -->
    <div class="am-section-divider"></div>

    <div class="am-section-head">
        <div class="am-section-step">Content</div>
        <h2>Content Intelligence</h2>
        <p>Build topical authority automatically. AI generates interconnected clusters of posts that Google rewards with higher rankings.</p>
    </div>

    <div class="am-woo-row">
    <?php
    $cluster_eligible = in_array($current_plan, ['unlimited_ai', 'agency'], true);
    $cluster_active   = in_array('content-cluster-builder', $active_modules, true);
    $cluster_url      = admin_url('admin.php?page=automarketer-ai-content&tab=cluster');
    ?>
        <div class="am-card <?php echo $cluster_active ? 'is-active' : ''; ?>" style="width:230px;min-width:230px;flex-shrink:0;">
            <?php if ($cluster_active): ?>
                <div class="am-ribbon am-ribbon--active">Active</div>
            <?php elseif (!$cluster_eligible): ?>
                <div class="am-ribbon am-ribbon--premium">Unlimited AI</div>
            <?php endif; ?>
            <div class="am-card-icon" style="background:#FFF7ED;color:#D97757;">
                <svg viewBox="0 0 24 24" fill="none" class="am-svg-icon">
                    <circle cx="12" cy="5"  r="2" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="5"  cy="19" r="2" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="19" cy="19" r="2" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="12" cy="13" r="2" stroke="currentColor" stroke-width="1.5"/>
                    <line x1="12" y1="7"  x2="12" y2="11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
                    <line x1="12" y1="15" x2="6"  y2="18" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
                    <line x1="12" y1="15" x2="18" y2="18" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
                </svg>
            </div>
            <div class="am-card-tagline">Build topical authority on autopilot</div>
            <h3 class="am-card-name">Content Cluster Builder</h3>
            <p class="am-card-desc">
                <?php if ($cluster_active): ?>
                    Active. AI is writing and scheduling interconnected blog posts automatically - building your search rankings on autopilot.
                <?php else: ?>
                    Pick a topic and AI writes a full set of interconnected blog posts, schedules them automatically, and builds your Google rankings over time.
                <?php endif; ?>
            </p>
            <div class="am-card-actions">
                <?php if ($cluster_active): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="deactivate">
                        <input type="hidden" name="module_id"     value="content-cluster-builder">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-deactivate">Disconnect</button>
                    </form>
                    <a href="<?php echo esc_url($cluster_url); ?>" class="am-card-note am-card-note--link">Open Cluster Builder</a>
                <?php elseif ($cluster_eligible): ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action"        value="amai_module_toggle">
                        <input type="hidden" name="module_action" value="activate">
                        <input type="hidden" name="module_id"     value="content-cluster-builder">
                        <?php wp_nonce_field('amai_module_toggle', '_wpnonce'); ?>
                        <button type="submit" class="am-btn-activate">Activate</button>
                    </form>
                <?php else: ?>
                    <div class="am-locked">Upgrade to Unlimited AI or above to unlock this module.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

</div><!-- /#amai-root -->

<?php endif; // license check ?>

<!-- ACTIVATION MODAL -->
<div id="amai-act-modal">
    <div class="am-act-wrap">
        <div class="am-act-header">
            <div>
                <div class="am-act-eyebrow" id="act-modal-eyebrow">AI Providers</div>
                <div class="am-act-title" id="act-modal-title">Activate Provider</div>
            </div>
            <button class="am-act-close" id="act-close-btn">&#10005;</button>
        </div>
        <div class="am-act-body">
            <div class="am-act-error" id="act-error"></div>
            <div id="act-key-wrapper">
                <label class="am-act-label" for="act-api-key">Your API Key</label>
                <input type="text" id="act-api-key" class="am-act-input" placeholder="Paste your key here...">
            </div>
            <div id="act-model-wrapper">
                <label class="am-act-label" for="act-model">Model</label>
                <select id="act-model" class="am-act-select" disabled>
                    <option value="">Enter API key first</option>
                </select>
            </div>
            <button type="button" class="am-act-help-link" id="act-help-trigger">
                <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                    <circle cx="6.5" cy="6.5" r="5.5" stroke="currentColor" stroke-width="1.3"/>
                    <path d="M6.5 7.3V7c0-.6.35-.95.78-1.3.35-.27.52-.52.52-.87C7.8 4.13 7.28 3.7 6.5 3.7c-.7 0-1.2.43-1.3 1.04" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
                    <circle cx="6.5" cy="9.1" r="0.65" fill="currentColor"/>
                </svg>
                Don't have a key yet? Here's how to get one - takes about 5 minutes.
            </button>
        </div>
        <div class="am-act-footer">
            <div class="am-act-btns">
                <button type="button" id="act-cancel-btn" class="am-act-btn-cancel">Cancel</button>
                <button type="button" id="act-save-btn"   class="am-act-btn-save">Save &amp; Activate</button>
            </div>
        </div>
    </div>
</div>

<!-- HELP MODAL -->
<div id="amai-help-modal">
    <div class="am-hlp-wrap">
        <div class="am-hlp-header">
            <div>
                <div class="am-hlp-eyebrow" id="hlp-eyebrow">Getting Your API Key</div>
                <div class="am-hlp-title"   id="hlp-title">How to Get Your Key</div>
            </div>
            <button class="am-hlp-close" id="hlp-close">&#10005;</button>
        </div>
        <div class="am-hlp-progress">
            <div class="am-hlp-labels" id="hlp-labels"></div>
            <div class="am-hlp-track"><div class="am-hlp-fill" id="hlp-fill"></div></div>
        </div>
        <div class="am-hlp-counter" id="hlp-counter">Step 1 of 5</div>
        <div class="am-hlp-body"    id="hlp-body"></div>
        <div class="am-hlp-footer">
            <div class="am-hlp-nav">
                <button class="am-hlp-btn-back" id="hlp-back" disabled>&larr; Back</button>
                <button class="am-hlp-btn-next" id="hlp-next">Next &rarr;</button>
                <button class="am-hlp-btn-done" id="hlp-done">Got It - Back to Setup</button>
            </div>
            <div class="am-hlp-tip" id="hlp-tip">Takes about 5 minutes total</div>
        </div>
    </div>
</div>

<!-- SMS PROVIDER MODAL -->
<div id="amai-sms-modal">
    <div class="am-act-wrap">
        <div class="am-act-header">
            <div>
                <div class="am-act-eyebrow" id="sms-modal-eyebrow">SMS Providers</div>
                <div class="am-act-title" id="sms-modal-title">Connect Provider</div>
            </div>
            <button class="am-act-close" id="sms-close-btn">&#10005;</button>
        </div>
        <div class="am-act-body">
            <div class="am-act-error" id="sms-error"></div>
            <div id="sms-fields-twilio" class="sms-provider-fields" style="display:none;">
                <label class="am-act-label" for="sms-twilio-sid">Account SID</label>
                <input type="text" id="sms-twilio-sid" class="am-act-input" placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                <label class="am-act-label" for="sms-twilio-token" style="margin-top:12px;">Auth Token</label>
                <input type="password" id="sms-twilio-token" class="am-act-input" placeholder="Your auth token">
                <label class="am-act-label" for="sms-twilio-from" style="margin-top:12px;">From Number</label>
                <input type="text" id="sms-twilio-from" class="am-act-input" placeholder="+15551234567">
                <p class="am-act-hint">Get your credentials from the <a href="https://console.twilio.com" target="_blank" rel="noopener noreferrer">Twilio Console</a>. The From Number must be a Twilio-provisioned number.</p>
            </div>
            <div id="sms-fields-plivo" class="sms-provider-fields" style="display:none;">
                <label class="am-act-label" for="sms-plivo-authid">Auth ID</label>
                <input type="text" id="sms-plivo-authid" class="am-act-input" placeholder="MAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                <label class="am-act-label" for="sms-plivo-token" style="margin-top:12px;">Auth Token</label>
                <input type="password" id="sms-plivo-token" class="am-act-input" placeholder="Your auth token">
                <label class="am-act-label" for="sms-plivo-from" style="margin-top:12px;">From Number</label>
                <input type="text" id="sms-plivo-from" class="am-act-input" placeholder="+15551234567">
                <p class="am-act-hint">Get your credentials from the <a href="https://console.plivo.com" target="_blank" rel="noopener noreferrer">Plivo Console</a>. Note: Plivo signup is not available in Canada - use Twilio or Vonage instead.</p>
            </div>
            <div id="sms-fields-vonage" class="sms-provider-fields" style="display:none;">
                <label class="am-act-label" for="sms-vonage-key">API Key</label>
                <input type="text" id="sms-vonage-key" class="am-act-input" placeholder="xxxxxxxx">
                <label class="am-act-label" for="sms-vonage-secret" style="margin-top:12px;">API Secret</label>
                <input type="password" id="sms-vonage-secret" class="am-act-input" placeholder="Your API secret">
                <label class="am-act-label" for="sms-vonage-from" style="margin-top:12px;">From Number</label>
                <input type="text" id="sms-vonage-from" class="am-act-input" placeholder="+15551234567">
                <p class="am-act-hint">Get your credentials from the <a href="https://dashboard.nexmo.com" target="_blank" rel="noopener noreferrer">Vonage Dashboard</a>. Enter the From Number in E.164 format.</p>
            </div>
            <div id="sms-fields-sinch" class="sms-provider-fields" style="display:none;">
                <label class="am-act-label" for="sms-sinch-plan">Service Plan ID</label>
                <input type="text" id="sms-sinch-plan" class="am-act-input" placeholder="Your Service Plan ID">
                <label class="am-act-label" for="sms-sinch-token" style="margin-top:12px;">API Token</label>
                <input type="password" id="sms-sinch-token" class="am-act-input" placeholder="Your API token">
                <label class="am-act-label" for="sms-sinch-from" style="margin-top:12px;">From Number</label>
                <input type="text" id="sms-sinch-from" class="am-act-input" placeholder="+15551234567">
                <p class="am-act-hint">Get your credentials from the <a href="https://dashboard.sinch.com" target="_blank" rel="noopener noreferrer">Sinch Dashboard</a>. The Service Plan ID and API Token are under SMS &gt; REST configuration.</p>
            </div>
        </div>
        <div class="am-act-footer">
            <div class="am-act-btns">
                <button type="button" id="sms-cancel-btn" class="am-act-btn-cancel">Cancel</button>
                <button type="button" id="sms-save-btn" class="am-act-btn-save">Save &amp; Activate</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var disconnectBtn = document.getElementById('ga4-disconnect-btn');
    disconnectBtn.addEventListener('click', function () {
        var modal = document.getElementById('amai-ga4-dc-modal');
        if (modal) modal.classList.add('show');
    });

    var dcConfirm = document.getElementById('amai-ga4-dc-confirm');
    var dcCancel  = document.getElementById('amai-ga4-dc-cancel');
    var dcClose   = document.getElementById('amai-ga4-dc-close');
    var dcModal   = document.getElementById('amai-ga4-dc-modal');

    function closeGa4Modal() {
        if (dcModal) dcModal.classList.remove('show');
    }

    if (dcCancel) dcCancel.addEventListener('click', closeGa4Modal);
    if (dcClose)  dcClose.addEventListener('click', closeGa4Modal);
    if (dcModal)  dcModal.addEventListener('click', function (e) {
        if (e.target === dcModal) closeGa4Modal();
    });

    if (dcConfirm) {
        dcConfirm.addEventListener('click', function () {
            var nonce = disconnectBtn.dataset.nonce;
            dcConfirm.disabled = true;
            dcConfirm.textContent = 'Disconnecting...';
            var fd = new FormData();
            fd.append('action', 'amai_ga4_disconnect');
            fd.append('nonce', nonce);
            fetch(ajaxurl, { method: 'POST', body: fd })
                .then(function (r) { return r.json(); })
                .then(function (d) {
                    if (d.success) {
                        location.reload();
                    } else {
                        closeGa4Modal();
                        dcConfirm.disabled = false;
                        dcConfirm.textContent = 'Yes, disconnect';
                        var notice = document.getElementById('ga4-disconnect-btn').closest('.am-card').querySelector('.am-card-note');
                        if (notice) { notice.style.color = '#DC2626'; notice.textContent = 'Disconnect failed. Please try again.'; }
                    }
                })
                .catch(function () {
                    closeGa4Modal();
                    dcConfirm.disabled = false;
                    dcConfirm.textContent = 'Yes, disconnect';
                });
        });
    }
});
</script>

<!-- STORE PROVIDER MODAL -->
<!-- GA4 DISCONNECT MODAL -->
<div id="amai-ga4-dc-modal" class="amai-dc-modal">
    <div class="amai-dc-wrap">
        <div class="amai-dc-header">
            <div>
                <div class="amai-dc-eyebrow">Are you sure?</div>
                <div class="amai-dc-title">Disconnect Google Analytics 4?</div>
            </div>
            <button type="button" class="amai-dc-close" id="amai-ga4-dc-close">&#10005;</button>
        </div>
        <div class="amai-dc-body">
            <p class="amai-dc-warning-text">This will remove your GA4 connection. Traffic data will stop syncing and content decay alerts will be disabled.</p>
            <p class="amai-dc-warning-sub">You can reconnect at any time.</p>
        </div>
        <div class="amai-dc-footer">
            <button type="button" class="amai-dc-btn-cancel" id="amai-ga4-dc-cancel">Keep it connected</button>
            <button type="button" class="amai-dc-btn-disconnect" id="amai-ga4-dc-confirm">Yes, disconnect</button>
        </div>
    </div>
</div>

<div id="amai-store-modal">
    <div class="am-act-wrap">
        <div class="am-act-header">
            <div>
                <div class="am-act-eyebrow">Store Integration</div>
                <div class="am-act-title">Connect WooCommerce</div>
            </div>
            <button class="am-act-close" id="store-close-btn">&#10005;</button>
        </div>
        <div class="am-act-body">
            <div class="am-act-error" id="store-error"></div>
            <p class="am-act-hint" style="margin:0;">WooCommerce is detected on this site. No API keys needed - AutoMarketer AI reads your product catalog directly. Click Connect to activate.</p>
        </div>
        <div class="am-act-footer">
            <div class="am-act-btns">
                <button type="button" id="store-cancel-btn" class="am-act-btn-cancel">Cancel</button>
                <button type="button" id="store-save-btn" class="am-act-btn-save">Connect WooCommerce</button>
            </div>
        </div>
    </div>
</div>