<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-marketing-site.php
// Description: Virtual routing and public marketing pages for AutoMarketer AI - NUCLEAR+++
// Last Edited: 2026-04-29
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class MarketingSite
{
    private const QUERY_VAR         = 'amai_page';
    private const PAGE_PRICING      = 'pricing';
    private const PAGE_FEATURES     = 'features';
    private const PAGE_GET_STARTED  = 'get-started';
    private const PAGE_WELCOME         = 'welcome';
    private const PAGE_PLUGIN_DOWNLOAD = 'plugin-download';
    private const PAGE_RELEASES         = 'releases';
    private const PAGE_PRIVACY          = 'privacy';
    private const PAGE_TERMS            = 'terms';
    private const CORE_REGISTER_URL = 'https://core.automarketer-ai.com/v1/license/activate-free';

    private const PLANS = [
        'free' => [
            'label'      => 'Basic',
            'price_year' => 0,
            'price_mo'   => 0,
            'tagline'    => 'Start posting to social media with AI - no credit card needed',
            'features'   => [
                'Social media channels included - start posting immediately',
                'Email your customers directly - free on all plans [APIKEY]Use your own key[/APIKEY]',
                'AI-powered captions and scheduling [APIKEY]Use your own key[/APIKEY]',
                '1 AI image provider [APIKEY]Use your own key[/APIKEY]',
                'Unlimited posts - no caps, no throttling',
                'Full scheduling, approval workflow and monitoring',
                'No credit card required. Ever.',
            ],
        ],
        'starter' => [
            'label'         => 'Starter',
            'price_year'    => 290,
            'price_mo'      => 29,
            'tagline'       => 'Both social channels + 5 additional modules',
            'price_id_year' => 'price_1TAYfhJfH56oJEdkb03ncBO1',
            'price_id_mo'   => 'price_1TAYegJfH56oJEdkSgQPS5bx',
            'features'      => [
                'All Basic features',
                'Facebook and Instagram included, plus 5 additional module slots',
                '5 additional channel modules - LinkedIn, Pinterest, X and more as they ship',
                'Unlimited posts across every connected channel',
            ],
        ],
        'starter_pro' => [
            'label'         => 'Starter Pro',
            'price_year'    => 490,
            'price_mo'      => 49,
            'tagline'       => 'Every channel module - now and forever',
            'price_id_year' => 'price_1TAYhnJfH56oJEdkxKPnfbCR',
            'price_id_mo'   => 'price_1TAYgyJfH56oJEdkP9mcO8ni',
            'popular'       => true,
            'features'      => [
                'All Starter features',
                'Every channel module - unlimited access, no exceptions',
                'Every new channel we build ships to you automatically',
                'Premium AI modules not included',
            ],
        ],
        'unlimited' => [
            'label'         => 'Unlimited AI',
            'price_year'    => 990,
            'price_mo'      => 99,
            'tagline'       => 'Every channel + Premium AI modules',
            'price_id_year' => 'price_1TAYkYJfH56oJEdkCBvqRIFH',
            'price_id_mo'   => 'price_1TAYjAJfH56oJEdkt8jufrgM',
            'features'      => [
                'All Starter Pro features',
                'AI image generation for every post',
                '[COMING_SOON]Analytics hub - see what is working across all your channels',
                '[PREMIUM]Content repurposer - one post adapted for every channel',
                '[PREMIUM]Review responder - AI replies to Google and Facebook reviews',
            ],
        ],
        'agency' => [
            'label'        => 'Agency',
            'price_year'   => 1990,
            'price_mo'     => 199,
            'tagline'      => 'Everything + Multi-Client Dashboard',
            'coming_soon'  => true,
            'features'     => [
                'All Unlimited AI features',
                'Unlimited client accounts - manage everyone from one login',
                'Agency dashboard - monitor all clients, generate reports, white-label the UI',
                'White-glove onboarding and priority support',
            ],
        ],
    ];

    public static function init(): void
    {
        add_action('init', [self::class, 'registerRewriteRules']);
        add_filter('query_vars', [self::class, 'registerQueryVar']);
        add_action('template_redirect', [self::class, 'handleRequest']);
        add_action('wp_enqueue_scripts', [self::class, 'enqueueAssets']);
        add_action('wp_ajax_nopriv_amai_wizard_step',        [self::class, 'handleWizardStep']);
        add_action('wp_ajax_amai_wizard_step',               [self::class, 'handleWizardStep']);
        add_action('wp_ajax_nopriv_amai_wizard_validate_ai', [self::class, 'handleWizardValidateAi']);
        add_action('wp_ajax_amai_wizard_validate_ai',        [self::class, 'handleWizardValidateAi']);
        add_action('wp_ajax_nopriv_amai_wizard_validate_img',[self::class, 'handleWizardValidateImg']);
        add_action('wp_ajax_amai_wizard_validate_img',       [self::class, 'handleWizardValidateImg']);
        add_action('wp_ajax_nopriv_amai_wizard_nonces',      [self::class, 'handleWizardNonces']);
        add_action('wp_ajax_amai_wizard_nonces',             [self::class, 'handleWizardNonces']);
        add_action('wp_ajax_amai_wizard_checkout',           [self::class, 'handleWizardCheckout']);
        add_action('wp_ajax_nopriv_amai_wizard_checkout',    [self::class, 'handleWizardCheckout']);
    }

    public static function registerRewriteRules(): void
    {
        add_rewrite_rule('^pricing/?$', 'index.php?' . self::QUERY_VAR . '=pricing', 'top');
        add_rewrite_rule('^features/?$', 'index.php?' . self::QUERY_VAR . '=features', 'top');
        add_rewrite_rule('^get-started/?$', 'index.php?' . self::QUERY_VAR . '=get-started', 'top');
        add_rewrite_rule('^welcome/?$', 'index.php?' . self::QUERY_VAR . '=welcome', 'top');
        add_rewrite_rule('^plugin-download/?$', 'index.php?' . self::QUERY_VAR . '=plugin-download', 'top');
        add_rewrite_rule('^releases/?$', 'index.php?' . self::QUERY_VAR . '=releases', 'top');
        add_rewrite_rule('^privacy/?$', 'index.php?' . self::QUERY_VAR . '=privacy', 'top');
        add_rewrite_rule('^terms/?$', 'index.php?' . self::QUERY_VAR . '=terms', 'top');
    }

    // @param array<string> $vars
    // @return array<string>
    public static function registerQueryVar(array $vars): array
    {
        $vars[] = self::QUERY_VAR;
        return $vars;
    }

    // --------------------------------------------------
    // Resolve a plan slug + billing period to a Stripe price ID
    // --------------------------------------------------
    private static function resolvePriceId(string $plan, string $billing): string
    {
        $validSlugs = ['starter', 'starter_pro', 'unlimited'];
        if (!in_array($plan, $validSlugs, true)) {
            return '';
        }
        $planData = self::PLANS[$plan] ?? [];
        if ($billing === 'monthly') {
            return (string) ($planData['price_id_mo'] ?? '');
        }
        return (string) ($planData['price_id_year'] ?? '');
    }

    public static function enqueueAssets(): void
    {
        $page    = get_query_var(self::QUERY_VAR, '');
        $cssBase = AMAI_PLUGIN_URL . 'assets/public/css/';
        $cssDir  = AMAI_PLUGIN_DIR . 'assets/public/css/';
        $jsBase  = AMAI_PLUGIN_URL . 'assets/public/js/';
        $jsDir   = AMAI_PLUGIN_DIR . 'assets/public/js/';

        $isMarketing = in_array($page, [
            self::PAGE_PRICING,
            self::PAGE_FEATURES,
            self::PAGE_GET_STARTED,
            self::PAGE_WELCOME,
            self::PAGE_PRIVACY,
            self::PAGE_TERMS,
        ], true) || is_front_page();

        if (!$isMarketing) {
            return;
        }

        wp_enqueue_style(
            'amai-public-global',
            $cssBase . 'global.css',
            [],
            (string) filemtime($cssDir . 'global.css')
        );

        if ($page === self::PAGE_PRICING) {
            wp_enqueue_style(
                'amai-public-pricing',
                $cssBase . 'pricing.css',
                ['amai-public-global'],
                (string) filemtime($cssDir . 'pricing.css')
            );
            wp_enqueue_script(
                'amai-public-pricing',
                $jsBase . 'pricing.js',
                [],
                (string) filemtime($jsDir . 'pricing.js'),
                true
            );
            wp_enqueue_style(
                'amai-public-home',
                $cssBase . 'home.css',
                ['amai-public-global'],
                (string) filemtime($cssDir . 'home.css')
            );
            wp_enqueue_script(
                'amai-public-home',
                $jsBase . 'home.js',
                [],
                (string) filemtime($jsDir . 'home.js'),
                true
            );
        } elseif ($page === self::PAGE_FEATURES) {
            wp_enqueue_style(
                'amai-public-features',
                $cssBase . 'features.css',
                ['amai-public-global'],
                (string) filemtime($cssDir . 'features.css')
            );
            wp_enqueue_style(
                'amai-public-home',
                $cssBase . 'home.css',
                ['amai-public-global'],
                (string) filemtime($cssDir . 'home.css')
            );
            wp_enqueue_script(
                'amai-public-home',
                $jsBase . 'home.js',
                [],
                (string) filemtime($jsDir . 'home.js'),
                true
            );
        } elseif ($page === self::PAGE_GET_STARTED) {
            wp_enqueue_style(
                'amai-public-get-started',
                $cssBase . 'get-started.css',
                ['amai-public-global'],
                file_exists($cssDir . 'get-started.css') ? (string) filemtime($cssDir . 'get-started.css') : '1'
            );
            wp_enqueue_script(
                'amai-public-get-started',
                $jsBase . 'get-started.js',
                [],
                file_exists($jsDir . 'get-started.js') ? (string) filemtime($jsDir . 'get-started.js') : '1',
                true
            );

            $selectedPlan    = sanitize_key(wp_unslash($_GET['plan'] ?? ''));
            $selectedBilling = in_array($_GET['billing'] ?? '', ['yearly', 'monthly'], true)
                ? sanitize_key(wp_unslash($_GET['billing']))
                : 'yearly';

            wp_localize_script('amai-public-get-started', 'amaiWizard', [
                'ajaxUrl'          => admin_url('admin-ajax.php'),
                'setupUrl'         => admin_url('admin.php?page=automarketer-ai-setup'),
                'nonceStep'        => wp_create_nonce('amai_wizard_step'),
                'nonceValidateAi'  => wp_create_nonce('amai_wizard_validate_ai'),
                'nonceValidateImg' => wp_create_nonce('amai_wizard_validate_img'),
                'nonceCheckout'    => wp_create_nonce('amai_wizard_checkout'),
                'fbConnectUrl'     => admin_url('admin.php?page=automarketer-ai-social&channel=facebook'),
                'currentStep'      => (int) get_user_meta(get_current_user_id(), 'amai_setup_step', true) ?: 1,
                'selectedPlan'     => $selectedPlan,
                'selectedBilling'  => $selectedBilling,
            ]);
        } elseif ($page === self::PAGE_WELCOME) {
            wp_enqueue_style(
                'amai-public-welcome',
                $cssBase . 'welcome.css',
                ['amai-public-global'],
                file_exists($cssDir . 'welcome.css') ? (string) filemtime($cssDir . 'welcome.css') : '1'
            );
        } elseif ($page === self::PAGE_PRIVACY || $page === self::PAGE_TERMS) {
            wp_enqueue_style(
                'amai-public-legal',
                $cssBase . 'legal.css',
                ['amai-public-global'],
                file_exists($cssDir . 'legal.css') ? (string) filemtime($cssDir . 'legal.css') : '1'
            );
        } else {
            wp_enqueue_style(
                'amai-public-home',
                $cssBase . 'home.css',
                ['amai-public-global'],
                (string) filemtime($cssDir . 'home.css')
            );
            wp_enqueue_script(
                'amai-public-home',
                $jsBase . 'home.js',
                [],
                (string) filemtime($jsDir . 'home.js'),
                true
            );
        }
    }

    public static function handleRequest(): void
    {
        $page = get_query_var(self::QUERY_VAR, '');

        if ($page === self::PAGE_PRICING) {
            self::renderPricing();
            exit;
        }
        if ($page === self::PAGE_FEATURES) {
            self::renderFeatures();
            exit;
        }
        if ($page === self::PAGE_GET_STARTED) {
            self::renderGetStarted();
            exit;
        }
        if ($page === self::PAGE_WELCOME) {
            self::renderWelcome();
            exit;
        }
        if ($page === self::PAGE_PLUGIN_DOWNLOAD) {
            self::renderPluginDownload();
            exit;
        }
        if ($page === self::PAGE_RELEASES) {
            self::renderReleases();
            exit;
        }
        if ($page === self::PAGE_PRIVACY) {
            self::renderPrivacy();
            exit;
        }
        if ($page === self::PAGE_TERMS) {
            self::renderTerms();
            exit;
        }
        if (is_front_page()) {
            self::renderHome();
            exit;
        }
    }

    // --------------------------------------------------
    // Wizard AJAX: initiate Stripe checkout after step 2
    // --------------------------------------------------
    public static function handleWizardCheckout(): void
    {
        $nonce = isset($_POST['_ajax_nonce']) ? sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'amai_wizard_checkout')) {
            wp_send_json_error(['message' => 'Security check failed.']);
            return;
        }

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => 'Session expired. Please refresh and try again.']);
            return;
        }

        $plan    = sanitize_key(wp_unslash($_POST['plan'] ?? ''));
        $billing = in_array($_POST['billing'] ?? '', ['yearly', 'monthly'], true)
            ? sanitize_key(wp_unslash($_POST['billing']))
            : 'yearly';

        $priceId = self::resolvePriceId($plan, $billing);
        if ($priceId === '') {
            wp_send_json_error(['message' => 'Invalid plan selection.']);
            return;
        }

        $user     = wp_get_current_user();
        $tenantId = (string) get_option('amai_tenant_id', '');

        if ($tenantId === '' || $user->ID === 0) {
            wp_send_json_error(['message' => 'Account not fully set up. Please contact support.']);
            return;
        }

        $url = self::createStripeCheckout($priceId, $user->user_email, $tenantId, $user->ID);
        if ($url === '') {
            wp_send_json_error(['message' => 'Could not create checkout session. Please try again.']);
            return;
        }

        wp_send_json_success(['url' => $url]);
    }

    // --------------------------------------------------
    // Activation handler
    // --------------------------------------------------
    private static function handleActivation(): array
    {
        $nonce = isset($_POST['amai_activate_nonce']) ? sanitize_text_field(wp_unslash($_POST['amai_activate_nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'amai_activate')) {
            return ['error' => 'Security check failed. Please refresh and try again.'];
        }

        $currentUser = wp_get_current_user();
        if (!($currentUser instanceof \WP_User) || $currentUser->ID === 0) {
            return ['error' => 'You must be logged in to activate AutoMarketer AI.'];
        }

        $businessName = isset($_POST['business_name']) ? sanitize_text_field(wp_unslash($_POST['business_name'])) : '';
        $email        = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $website      = isset($_POST['website']) ? esc_url_raw(wp_unslash($_POST['website'])) : '';

        if (empty($businessName)) {
            return ['error' => 'Please enter your business name.'];
        }
        if (!is_email($email)) {
            return ['error' => 'Please enter a valid email address.'];
        }

        $coreResponse = wp_remote_post(self::CORE_REGISTER_URL, [
            'timeout' => 15,
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => (string) json_encode([
                'first_name' => $currentUser->first_name !== '' ? $currentUser->first_name : $currentUser->display_name,
                'email'      => $email,
                'wp_user_id' => $currentUser->ID,
                'site_url'   => $website,
            ]),
        ]);

        if (is_wp_error($coreResponse)) {
            return ['error' => 'Activation failed. Please try again.'];
        }

        $body = json_decode(wp_remote_retrieve_body($coreResponse), true);
        if (!is_array($body) || empty($body['license_key']) || empty($body['tenant_id'])) {
            if (!empty($body['error']) && $body['error'] === 'email_already_registered') {
                update_option('amai_primary_user_id', $currentUser->ID);
                return ['redirect' => admin_url('admin.php?page=automarketer-ai')];
            }
            return ['error' => 'Activation failed. Please try again.'];
        }

        $licenseKey = sanitize_text_field((string) $body['license_key']);
        $apiSecret  = sanitize_text_field((string) $body['api_secret']);
        $tenantId   = sanitize_text_field((string) $body['tenant_id']);

        update_user_meta($currentUser->ID, 'amai_license_key', $licenseKey);
        update_user_meta($currentUser->ID, 'amai_api_secret', $apiSecret);
        update_user_meta($currentUser->ID, 'amai_tenant_id', $tenantId);

        update_option('amai_tenant_id', $tenantId);
        update_option('automarketer_ai_plan_id', 'basic');
        update_option('automarketer_ai_license_status', 'active');
        update_option('amai_primary_user_id', $currentUser->ID);
        self::seedTenantOnCore($tenantId);

        $currentUser->add_cap('manage_automarketer_ai');

        self::sendWelcomeEmail($email, $currentUser->first_name !== '' ? $currentUser->first_name : $currentUser->display_name, $licenseKey);
        WebhookReceiver::notifyAdminFreeSignup($email);

        return ['redirect' => admin_url('admin.php?page=automarketer-ai')];
    }

    private static function seedTenantOnCore(string $tenantId): void
    {
        $hmacSecret = defined('AMAI_HMAC_SECRET') ? AMAI_HMAC_SECRET : '';
        if ($hmacSecret === '' || $tenantId === '') {
            return;
        }
        $coreUrl = defined('AMAI_CORE_URL') ? AMAI_CORE_URL : '';
        if ($coreUrl === '') {
            return;
        }
        // Generate a unique 64-char hex secret for this install
        $installSecret = bin2hex(random_bytes(32));
        $timestamp     = (string) time();
        $nonce         = bin2hex(random_bytes(16));
        $keyId         = 'WP_PROXY';
        $tenant        = amai_tenant_id();
        $body          = (string) json_encode([
            'tenant_id'   => $tenantId,
            'hmac_secret' => $installSecret,
        ]);
        $bodyB64   = base64_encode(hash('sha256', $body, true));
        $canonical = implode('|', ['POST', '/api/tenant/provision', $timestamp, $nonce, $tenant, $keyId, $bodyB64]);
        $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, hex2bin($hmacSecret), true)), "\n");
        $response  = wp_remote_post($coreUrl . '/api/tenant/provision', [
            'timeout' => 15,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Amai-Tenant'      => $tenant,
                'X-Amai-Key-Id'      => $keyId,
                'X-Amai-Timestamp'   => $timestamp,
                'X-Amai-Nonce'       => $nonce,
                'X-Amai-Body-SHA256' => $bodyB64,
                'X-Amai-Signature'   => $signature,
            ],
            'body' => $body,
        ]);
        if (is_wp_error($response)) {
            return;
        }
        $decoded = json_decode(wp_remote_retrieve_body($response), true);
        if (is_array($decoded) && !empty($decoded['provisioned'])) {
            update_option('amai_hmac_secret', $installSecret);
        }
    }

    private static function createStripeCheckout(string $priceId, string $email, string $tenantId, int $wpUserId): string
    {
        $hmacSecret = defined('AMAI_HMAC_SECRET') ? AMAI_HMAC_SECRET : '';
        if ($hmacSecret === '') {
            return '';
        }
        $timestamp = (string) time();
        $nonce     = bin2hex(random_bytes(16));
        $keyId     = 'WP_PROXY';
        $tenant    = amai_tenant_id();
        $body      = (string) json_encode([
            'plan_id' => $priceId,
            'user_id' => $wpUserId,
            'email'   => $email,
        ]);
        $bodyB64   = base64_encode(hash('sha256', $body, true));
        $canonical = implode('|', ['POST', '/api/stripe/create-checkout', $timestamp, $nonce, $tenant, $keyId, $bodyB64]);
        $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, hex2bin($hmacSecret), true)), "\n");
        $response = wp_remote_post('https://core.automarketer-ai.com/api/stripe/create-checkout', [
            'timeout' => 45,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Amai-Tenant'      => $tenant,
                'X-Amai-Key-Id'      => $keyId,
                'X-Amai-Timestamp'   => $timestamp,
                'X-Amai-Nonce'       => $nonce,
                'X-Amai-Body-SHA256' => $bodyB64,
                'X-Amai-Signature'   => $signature,
            ],
            'body' => $body,
        ]);
        if (is_wp_error($response)) {
            return '';
        }
        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (is_array($data) && !empty($data['url'])) {
            return (string) $data['url'];
        }
        if (is_array($data) && !empty($data['session_id'])) {
            return 'https://checkout.stripe.com/pay/' . (string) $data['session_id'];
        }
        return '';
    }

    // ── Public test entry point for SettingsPage ───────────────────────
    public static function sendTestWelcomeEmail(string $to, string $firstName, string $licenseKey): void
    {
        self::sendWelcomeEmail($to, $firstName, $licenseKey);
    }

    public static function sendWelcomeEmail(string $email, string $firstName, string $licenseKey = ''): void
    {
        $subject      = 'Welcome to ' . get_bloginfo('name');
        $loginUrl     = home_url('/get-started');
        $keyDisplay   = $licenseKey !== '' ? $licenseKey : '(see your dashboard)';
        $html = self::buildWelcomeEmailHtml($firstName, $keyDisplay, $loginUrl);
        $headers = [
            'From: ' . \AutoMarketerAI\AbstractEmailProvider::get_sender_name() . ' <' . \AutoMarketerAI\AbstractEmailProvider::get_sender_email() . '>',
            'Reply-To: ' . \AutoMarketerAI\AbstractEmailProvider::get_sender_email(),
            'Content-Type: text/html; charset=UTF-8',
        ];
        wp_mail($email, $subject, $html, $headers);
    }

    // --------------------------------------------------
    // HTML shell
    // --------------------------------------------------
    private static function htmlOpen(string $title): void
    {
        echo '<!DOCTYPE html>';
        echo '<html ' . get_language_attributes() . '>';
        echo '<head>';
        echo '<meta charset="' . esc_attr(get_bloginfo('charset')) . '">';
        echo '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        echo '<title>' . esc_html($title) . ' - AutoMarketer AI</title>';
        wp_head();
        echo '</head>';
        echo '<body class="amai-marketing">';
        self::renderNav();
    }

    private static function htmlClose(): void
    {
        self::renderFooter();
        wp_footer();
        echo '</body></html>';
    }

    public static function renderNav(): void
    {
        $getStartedUrl = home_url('/get-started');
        $loginUrl      = wp_login_url(admin_url('admin.php?page=automarketer-ai'));
        echo '<nav class="amai-nav">';
        echo '<div class="amai-container amai-nav__inner">';
        echo '<a href="/" class="amai-nav__logo"><img src="https://automarketer-ai.com/wp-content/uploads/cropped-AutoMarketer-AI-Logo-Rect.png" alt="AutoMarketer AI" class="amai-nav__logo-img"></a>';
        echo '<div class="amai-nav__links">';
        echo '<a href="/features" class="amai-nav__link">Features</a>';
        echo '<a href="/pricing" class="amai-nav__link">Plans</a>';
        echo '<a href="/blog" class="amai-nav__link">Blog</a>';
        echo '<a href="/releases" class="amai-nav__link">Download</a>';
        if (is_user_logged_in()) {
            $logoutUrl = wp_logout_url(home_url());
            echo '<a href="' . esc_url($logoutUrl) . '" class="amai-nav__link">Log out</a>';
        } else {
            echo '<a href="' . esc_url($loginUrl) . '" class="amai-nav__link">Log in</a>';
        }
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--primary amai-btn--sm">Get Started Free</a>';
        echo '</div>';
        echo '</div>';
        echo '</nav>';
    }

    public static function renderFooter(): void
    {
        $year          = gmdate('Y');
        $getStartedUrl = home_url('/get-started');
        echo '<footer class="amai-footer">';
        echo '<div class="amai-container">';
        echo '<div class="amai-footer__grid">';
        echo '<div class="amai-footer__brand">';
        echo '<a href="/" class="amai-footer__logo-link"><img src="https://automarketer-ai.com/wp-content/uploads/cropped-AutoMarketer-AI-Logo-Rect.png" alt="AutoMarketer AI" class="amai-footer__logo-img"></a>';
        echo '<p class="amai-footer__tagline">Your always-on marketing team. AI-powered content, automated posting, and growing your online presence on autopilot.</p>';
        echo '</div>';
        echo '<div class="amai-footer__col">';
        echo '<div class="amai-footer__heading">Product</div>';
        echo '<a href="/features" class="amai-footer__link">Features</a>';
        echo '<a href="/pricing" class="amai-footer__link">Plans</a>';
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-footer__link">Get Started</a>';
        echo '</div>';
        echo '<div class="amai-footer__col">';
        echo '<div class="amai-footer__heading">Company</div>';
        echo '<a href="#" class="amai-footer__link">About</a>';
        echo '<a href="mailto:support@automarketer-ai.com" class="amai-footer__link">Contact</a>';
        echo '</div>';
        echo '<div class="amai-footer__col">';
        echo '<div class="amai-footer__heading">Legal</div>';
        echo '<a href="/privacy" class="amai-footer__link">Privacy Policy</a>';
        echo '<a href="/terms" class="amai-footer__link">Terms of Service</a>';
        echo '</div>';
        echo '</div>';
        echo '<div class="amai-footer__bottom">';
        echo '<span>&#169; ' . esc_html($year) . ' AutoMarketer AI. All rights reserved.</span>';
        echo '<span>Built for small businesses and agencies.</span>';
        echo '</div>';
        echo '</div>';
        echo '</footer>';
    }

    // --------------------------------------------------
    // SVG illustrations for feature blocks
    // --------------------------------------------------
    private static function svgAiContent(): string
    {
        return '<svg viewBox="0 0 420 315" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
            . '<rect x="40" y="40" width="340" height="235" rx="14" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="64" y="68" width="200" height="12" rx="6" fill="#E7DDD5"/>'
            . '<rect x="64" y="90" width="160" height="10" rx="5" fill="#EDE8E4"/>'
            . '<rect x="64" y="116" width="292" height="9" rx="4.5" fill="#EDE8E4"/>'
            . '<rect x="64" y="132" width="260" height="9" rx="4.5" fill="#EDE8E4"/>'
            . '<rect x="64" y="148" width="280" height="9" rx="4.5" fill="#EDE8E4"/>'
            . '<rect x="64" y="164" width="220" height="9" rx="4.5" fill="#EDE8E4"/>'
            . '<rect x="64" y="192" width="80" height="32" rx="8" fill="#D97757"/>'
            . '<rect x="154" y="192" width="80" height="32" rx="8" fill="#F5EDE8" stroke="#D97757" stroke-width="1.5"/>'
            . '<circle cx="330" cy="84" r="22" fill="#FDF0EB" stroke="#D97757" stroke-width="1.5"/>'
            . '<path d="M322 84 L328 90 L338 78" stroke="#D97757" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
            . '<circle cx="64" cy="248" r="6" fill="#D97757"/>'
            . '<circle cx="84" cy="248" r="6" fill="#E7DDD5"/>'
            . '<circle cx="104" cy="248" r="6" fill="#E7DDD5"/>'
            . '<text x="208" y="202" font-size="11" fill="#D97757" font-family="sans-serif" font-weight="600" text-anchor="middle">Approve</text>'
            . '<text x="120" y="212" font-size="11" fill="#D97757" font-family="sans-serif" font-weight="600" text-anchor="middle">Post</text>'
            . '</svg>';
    }

    private static function svgMultiChannel(): string
    {
        return '<svg viewBox="0 0 420 315" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
            . '<rect x="40" y="30" width="340" height="255" rx="14" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="64" y="56" width="292" height="40" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<circle cx="88" cy="76" r="12" fill="#1877F2" opacity="0.9"/>'
            . '<text x="88" y="81" font-size="13" fill="white" font-family="sans-serif" font-weight="700" text-anchor="middle">f</text>'
            . '<rect x="110" y="69" width="100" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="110" y="80" width="70" height="6" rx="3" fill="#EDE8E4"/>'
            . '<circle cx="336" cy="76" r="8" fill="#D97757" opacity="0.2"/>'
            . '<path d="M332 76 L336 80 L342 70" stroke="#D97757" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>'
            . '<rect x="64" y="106" width="292" height="40" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<circle cx="88" cy="126" r="12" fill="url(#ig-grad)" opacity="0.9"/>'
            . '<rect x="83" y="121" width="10" height="10" rx="3" fill="none" stroke="white" stroke-width="1.5"/>'
            . '<circle cx="88" cy="126" r="3" fill="none" stroke="white" stroke-width="1.2"/>'
            . '<circle cx="93" cy="122" r="1" fill="white"/>'
            . '<rect x="110" y="119" width="110" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="110" y="130" width="75" height="6" rx="3" fill="#EDE8E4"/>'
            . '<circle cx="336" cy="126" r="8" fill="#D97757" opacity="0.2"/>'
            . '<path d="M332 126 L336 130 L342 120" stroke="#D97757" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>'
            . '<rect x="64" y="156" width="292" height="40" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<circle cx="88" cy="176" r="12" fill="#0A66C2" opacity="0.9"/>'
            . '<text x="88" y="181" font-size="11" fill="white" font-family="sans-serif" font-weight="700" text-anchor="middle">in</text>'
            . '<rect x="110" y="169" width="90" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="110" y="180" width="60" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="316" y="166" width="44" height="20" rx="6" fill="#EDE8E4"/>'
            . '<text x="338" y="180" font-size="9" fill="#888" font-family="sans-serif" font-weight="500" text-anchor="middle">Soon</text>'
            . '<rect x="64" y="218" width="292" height="2" rx="1" fill="#E7DDD5"/>'
            . '<rect x="64" y="234" width="140" height="10" rx="5" fill="#D97757" opacity="0.15"/>'
            . '<rect x="216" y="234" width="140" height="10" rx="5" fill="#E7DDD5"/>'
            . '<defs>'
            . '<linearGradient id="ig-grad" x1="76" y1="114" x2="100" y2="138" gradientUnits="userSpaceOnUse">'
            . '<stop stop-color="#f09433"/>'
            . '<stop offset="0.25" stop-color="#e6683c"/>'
            . '<stop offset="0.5" stop-color="#dc2743"/>'
            . '<stop offset="0.75" stop-color="#cc2366"/>'
            . '<stop offset="1" stop-color="#bc1888"/>'
            . '</linearGradient>'
            . '</defs>'
            . '</svg>';
    }

    private static function svgApprovalWorkflow(): string
    {
        return '<svg viewBox="0 0 420 315" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
            . '<rect x="40" y="30" width="340" height="255" rx="14" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="64" y="56" width="292" height="58" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<circle cx="82" cy="72" r="8" fill="#EDE8E4"/>'
            . '<rect x="98" y="67" width="120" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="98" y="79" width="180" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="98" y="90" width="150" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="252" y="62" width="56" height="22" rx="6" fill="#D97757"/>'
            . '<text x="280" y="77" font-size="9" fill="white" font-family="sans-serif" font-weight="600" text-anchor="middle">Approve</text>'
            . '<rect x="64" y="126" width="292" height="58" rx="8" fill="white" stroke="#D97757" stroke-width="1.5"/>'
            . '<circle cx="82" cy="142" r="8" fill="#FDF0EB"/>'
            . '<rect x="98" y="137" width="130" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="98" y="149" width="185" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="98" y="160" width="140" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="244" y="132" width="56" height="22" rx="6" fill="#D97757"/>'
            . '<text x="272" y="147" font-size="9" fill="white" font-family="sans-serif" font-weight="600" text-anchor="middle">Approve</text>'
            . '<rect x="304" y="132" width="36" height="22" rx="6" fill="#FDF0EB" stroke="#D97757" stroke-width="1"/>'
            . '<text x="322" y="147" font-size="9" fill="#D97757" font-family="sans-serif" font-weight="600" text-anchor="middle">Edit</text>'
            . '<rect x="64" y="196" width="292" height="58" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<circle cx="82" cy="212" r="8" fill="#EDE8E4"/>'
            . '<rect x="98" y="207" width="110" height="7" rx="3.5" fill="#E7DDD5"/>'
            . '<rect x="98" y="219" width="175" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="98" y="230" width="130" height="6" rx="3" fill="#EDE8E4"/>'
            . '<rect x="252" y="202" width="56" height="22" rx="6" fill="#D97757"/>'
            . '<text x="280" y="217" font-size="9" fill="white" font-family="sans-serif" font-weight="600" text-anchor="middle">Approve</text>'
            . '</svg>';
    }

    private static function svgImageGeneration(): string
    {
        return '<svg viewBox="0 0 420 315" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
            . '<rect x="40" y="30" width="160" height="120" rx="10" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="52" y="42" width="136" height="96" rx="6" fill="#EDE8E4"/>'
            . '<circle cx="80" cy="68" r="10" fill="#D97757" opacity="0.3"/>'
            . '<path d="M52 110 L80 85 L100 100 L120 78 L188 110" stroke="#D97757" stroke-width="1.5" fill="none" opacity="0.4"/>'
            . '<rect x="220" y="30" width="160" height="120" rx="10" fill="#FDF6F2" stroke="#D97757" stroke-width="2"/>'
            . '<rect x="232" y="42" width="136" height="96" rx="6" fill="#FDF0EB"/>'
            . '<circle cx="260" cy="68" r="10" fill="#D97757" opacity="0.5"/>'
            . '<path d="M232 110 L260 82 L282 98 L304 72 L368 110" stroke="#D97757" stroke-width="2" fill="none" opacity="0.7"/>'
            . '<circle cx="220" cy="30" r="12" fill="#D97757"/>'
            . '<path d="M215 30 L219 34 L226 26" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
            . '<rect x="40" y="170" width="160" height="115" rx="10" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="52" y="182" width="136" height="91" rx="6" fill="#EDE8E4"/>'
            . '<circle cx="80" cy="208" r="10" fill="#D97757" opacity="0.3"/>'
            . '<path d="M52 250 L82 222 L104 238 L124 214 L188 250" stroke="#D97757" stroke-width="1.5" fill="none" opacity="0.4"/>'
            . '<rect x="220" y="170" width="160" height="115" rx="10" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="232" y="182" width="136" height="91" rx="6" fill="#EDE8E4"/>'
            . '<circle cx="262" cy="208" r="10" fill="#D97757" opacity="0.3"/>'
            . '<path d="M232 250 L264 220 L288 236 L308 212 L368 250" stroke="#D97757" stroke-width="1.5" fill="none" opacity="0.4"/>'
            . '<rect x="188" y="148" width="44" height="20" rx="6" fill="#D97757"/>'
            . '<text x="210" y="162" font-size="9" fill="white" font-family="sans-serif" font-weight="600" text-anchor="middle">Generate</text>'
            . '</svg>';
    }

    private static function svgAnalytics(): string
    {
        return '<svg viewBox="0 0 420 315" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">'
            . '<rect x="40" y="30" width="340" height="255" rx="14" fill="#FDF6F2" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<rect x="64" y="56" width="96" height="70" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<text x="112" y="84" font-size="22" fill="#D97757" font-family="sans-serif" font-weight="800" text-anchor="middle">847</text>'
            . '<text x="112" y="100" font-size="9" fill="#999" font-family="sans-serif" text-anchor="middle">Likes this week</text>'
            . '<rect x="172" y="56" width="96" height="70" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<text x="220" y="84" font-size="22" fill="#D97757" font-family="sans-serif" font-weight="800" text-anchor="middle">12.4k</text>'
            . '<text x="220" y="100" font-size="9" fill="#999" font-family="sans-serif" text-anchor="middle">Reach this week</text>'
            . '<rect x="280" y="56" width="96" height="70" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<text x="328" y="84" font-size="22" fill="#D97757" font-family="sans-serif" font-weight="800" text-anchor="middle">94</text>'
            . '<text x="328" y="100" font-size="9" fill="#999" font-family="sans-serif" text-anchor="middle">Comments</text>'
            . '<rect x="64" y="144" width="312" height="120" rx="8" fill="white" stroke="#E7DDD5" stroke-width="1.5"/>'
            . '<line x1="88" y1="240" x2="88" y2="164" stroke="#EDE8E4" stroke-width="1"/>'
            . '<line x1="64" y1="240" x2="376" y2="240" stroke="#EDE8E4" stroke-width="1"/>'
            . '<polyline points="88,220 130,200 172,210 214,185 256,175 298,160 340,150 360,148" stroke="#D97757" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>'
            . '<polyline points="88,228 130,222 172,225 214,218 256,215 298,210 340,205 360,202" stroke="#D97757" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4 3" opacity="0.5"/>'
            . '<circle cx="340" cy="150" r="4" fill="#D97757"/>'
            . '<circle cx="360" cy="148" r="4" fill="#D97757"/>'
            . '</svg>';
    }

    // --------------------------------------------------
    // Home page
    // --------------------------------------------------
    private static function renderHome(): void
    {
        $getStartedUrl = home_url('/get-started');
        self::htmlOpen('AI Marketing Automation for Small Business');
        echo '<main class="amai-main">';

        echo '<section class="amai-hero">';
        echo '<div class="amai-container">';
        echo '<h1 class="amai-hero__headline">Your always-on marketing team,<br><span class="amai-clay">minus the agency bills.</span></h1>';
        echo '<p class="amai-hero__sub">AutoMarketer AI writes, schedules, and posts your social content automatically - so you can run your business, not your feed.</p>';
        echo '<div class="amai-hero__ctas">';
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--primary amai-btn--lg">Get Started Free</a>';
        echo '<a href="/pricing" class="amai-btn amai-btn--secondary amai-btn--lg">See plans</a>';
        echo '</div>';
        echo '<p class="amai-hero__note">Free forever. No credit card required.</p>';
        echo '</div>';
        echo '</section>';

        echo '<section class="amai-section amai-section--white">';
        echo '<div class="amai-container amai-centered">';
        echo '<h2 class="amai-section__title">You know you should be posting.<br>You just never have time.</h2>';
        echo '<p class="amai-section__sub">Running a business leaves no room for consistent marketing. AutoMarketer AI handles all of it.</p>';
        echo '<div class="amai-cards-3">';
        echo self::problemCard('&#9200;', 'No time to post', 'Between running your business and everything else, social media always falls to the bottom of the list.');
        echo self::problemCard('&#128173;', 'No ideas', 'Staring at a blank screen wondering what to write is exhausting. AutoMarketer AI generates fresh content every week.');
        echo self::problemCard('&#128176;', 'Can\'t afford an agency', 'Agencies charge thousands per month for what AutoMarketer AI does automatically, for a fraction of the cost.');
        echo '</div>';
        echo '</div>';
        echo '</section>';

        echo '<section class="amai-section">';
        echo '<div class="amai-container">';
        echo '<div class="amai-centered">';
        echo '<div class="amai-tag">How it works</div>';
        echo '<h2 class="amai-section__title">Three steps to automated marketing</h2>';
        echo '</div>';
        echo '<div class="amai-steps">';
        echo self::stepCard('1', 'Connect your channels', 'Link your Facebook, Instagram, LinkedIn, and more. Takes less than two minutes.');
        echo self::stepCard('2', 'AI writes your content', 'Every week, AutoMarketer AI generates a full set of posts for your business. Review, edit, or approve with one click.');
        echo self::stepCard('3', 'Posts go out automatically', 'Approved posts are scheduled and published at the best times. Your channels stay active without you lifting a finger.');
        echo '</div>';
        echo '</div>';
        echo '</section>';

        echo '<section class="amai-section amai-section--white">';
        echo '<div class="amai-container">';
        echo '<div class="amai-centered">';
        echo '<div class="amai-tag">Built to grow with you</div>';
        echo '<h2 class="amai-section__title">Everything your marketing needs</h2>';
        echo '<p class="amai-section__sub">One platform. Multiple channels. All on autopilot.</p>';
        echo '</div>';
        echo '<div class="amai-cards-3">';
        echo self::featureCard('AI Content Generation', 'Powered by Claude, GPT-4, Gemini, Grok, and more. Fresh, relevant posts written specifically for your business every week.', '&#127775;');
        echo self::featureCard('Multi-Channel Posting', 'Facebook, Instagram, LinkedIn, and more. Manage all your channels from a single dashboard.', '&#128279;');
        echo self::featureCard('Review and Approve', 'Stay in control. Review every post before it goes out, or enable Autopilot and let it run completely hands-free.', '&#10003;');
        echo self::featureCard('AI Image Generation', 'Beautiful images generated for every post automatically, or pull from the Unsplash library of millions of free photos.', '&#128247;');
        echo self::featureCard('Analytics Hub', 'See what is working. Track likes, comments, reach, and engagement across all your channels in one place.', '&#128200;');
        echo self::featureCard('Always Improving', 'New channels, new AI providers, and new features ship regularly. Every plan automatically gets what we build next.', '&#128640;');
        echo '</div>';
        echo '<div class="amai-section__cta">';
        echo '<a href="/features" class="amai-btn amai-btn--secondary">See all features</a>';
        echo '</div>';
        echo '</div>';
        echo '</section>';

        echo '<section class="amai-section">';
        echo '<div class="amai-container amai-centered">';
        echo '<div class="amai-tag">Simple pricing</div>';
        echo '<h2 class="amai-section__title">Start free. Upgrade when you\'re ready.</h2>';
        echo '<p class="amai-section__sub">Plans starting at $290/year. No monthly contracts on yearly plans.</p>';
        echo '<div class="amai-hero__ctas">';
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--primary amai-btn--lg">Get Started Free</a>';
        echo '<a href="/pricing" class="amai-btn amai-btn--secondary amai-btn--lg">View all plans</a>';
        echo '</div>';
        echo '</div>';
        echo '</section>';

        echo '</main>';
        self::htmlClose();
    }

    private static function problemCard(string $icon, string $title, string $desc): string
    {
        return '<div class="amai-card">'
            . '<div class="amai-card__icon">' . $icon . '</div>'
            . '<h3 class="amai-card__title">' . esc_html($title) . '</h3>'
            . '<p class="amai-card__desc">' . esc_html($desc) . '</p>'
            . '</div>';
    }

    private static function featureCard(string $title, string $desc, string $icon): string
    {
        return '<div class="amai-card amai-card--feature">'
            . '<div class="amai-card__icon">' . $icon . '</div>'
            . '<h3 class="amai-card__title">' . esc_html($title) . '</h3>'
            . '<p class="amai-card__desc">' . esc_html($desc) . '</p>'
            . '</div>';
    }

    private static function stepCard(string $number, string $title, string $desc): string
    {
        return '<div class="amai-step">'
            . '<div class="amai-step__number">' . esc_html($number) . '</div>'
            . '<h3 class="amai-step__title">' . esc_html($title) . '</h3>'
            . '<p class="amai-step__desc">' . esc_html($desc) . '</p>'
            . '</div>';
    }

    // --------------------------------------------------
    // Plans page
    // --------------------------------------------------
    private static function renderPricing(): void
    {
        $getStartedUrl = home_url('/get-started');
        self::htmlOpen('Plans');
        echo '<main class="amai-main">';
        echo '<div class="amai-container">';

        echo '<div class="amai-page-header">';
        echo '<div class="amai-tag">Plans</div>';
        echo '<h1 class="amai-page-header__title">Simple, transparent plans</h1>';
        echo '<p class="amai-page-header__sub">Start free. Upgrade anytime. No surprises.</p>';
        echo '<div class="amai-billing-toggle" id="amai-billing-toggle">';
        echo '<button class="amai-billing-toggle__btn is-active" data-billing="yearly">Yearly <span class="amai-billing-save">Save 20%</span></button>';
        echo '<button class="amai-billing-toggle__btn" data-billing="monthly">Monthly</button>';
        echo '</div>';
        echo '</div>';

        echo '<div class="amai-plan-grid">';
        foreach (self::PLANS as $slug => $plan) {
            $isPopular    = !empty($plan['popular']);
            $isComingSoon = !empty($plan['coming_soon']);
            $isFree       = $slug === 'free';
            $savingsAmt   = $isFree ? 0 : (int) ($plan['price_mo'] * 2);
            $planLabel    = (string) $plan['label'];

            echo '<div class="amai-plan' . ($isPopular ? ' amai-plan--popular' : ($isFree ? ' amai-plan--free' : '')) . '" data-plan-slug="' . esc_attr($slug) . '">';
            if ($isPopular) {
                echo '<div class="amai-plan__badge">Most Popular</div>';
            } elseif ($isFree) {
                echo '<div class="amai-plan__badge">Free Forever</div>';
            }

            if ($isFree) {
                echo '<div class="amai-plan__price-block">';
                echo '<div class="amai-plan__price" data-price-year="0" data-price-mo="0">$0<span class="amai-plan__price-period">/yr</span></div>';
                echo '<div class="amai-plan__period">Always free, no card needed</div>';
                echo '</div>';
            } else {
                echo '<div class="amai-plan__price-block">';
                echo '<div class="amai-plan__price" data-price-year="' . esc_attr((string) $plan['price_year']) . '" data-price-mo="' . esc_attr((string) $plan['price_mo']) . '">$' . esc_html((string) $plan['price_year']) . '<span class="amai-plan__price-period">/yr</span></div>';
                echo '<div class="amai-plan__period" data-savings="' . esc_attr((string) $savingsAmt) . '">2 months free - save $' . esc_html((string) $savingsAmt) . '/yr</div>';
                echo '</div>';
            }

            echo '<ul class="amai-plan__features">';
            foreach ($plan['features'] as $feature) {
                $featureText = (string) $feature;
                $isPremium   = str_starts_with($featureText, '[PREMIUM]');
                $isComingSoonFeature = str_starts_with($featureText, '[COMING_SOON]');
                if ($isPremium) {
                    $featureText = substr($featureText, 9);
                }
                if ($isComingSoonFeature) {
                    $featureText = substr($featureText, 13);
                }
                $featureText = preg_replace_callback(
                    '/\[APIKEY\](.*?)\[\/APIKEY\]/',
                    function (array $m): string {
                        return '<button class="amai-apikey-trigger" type="button"><span class="amai-apikey-pill">&#128273; Use your own key</span></button>';
                    },
                    $featureText
                );
                $hasApiKey = str_contains((string) $feature, '[APIKEY]');
                echo '<li class="amai-plan__feature' . ($hasApiKey ? ' amai-plan__feature--block' : '') . '">';
                echo '<span class="amai-check">&#10003;</span>';
                if ($hasApiKey) {
                    echo '<span class="amai-plan__feature-text">' . $featureText . '</span>';
                } else {
                    echo $featureText;
                }
                if ($isPremium) {
                    echo '<span class="amai-feature-pill amai-feature-pill--premium">Premium</span>';
                }
                if ($isComingSoonFeature) {
                    echo '<span class="amai-feature-pill amai-feature-pill--soon">Soon</span>';
                }
                echo '</li>';
            }
            echo '</ul>';

            echo '<div class="amai-plan__cta">';
            if ($isComingSoon) {
                echo '<div class="amai-plan__coming-soon">Coming Soon</div>';
            } elseif ($isFree) {
                echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--secondary amai-btn--full">Get Started Free</a>';
            } else {
                // Paid plan -- default yearly href; pricing.js updates on billing toggle
                $defaultUrl = esc_url(home_url('/get-started?plan=' . $slug . '&billing=yearly'));
                echo '<a href="' . $defaultUrl . '" class="amai-btn amai-btn--primary amai-btn--full" data-plan-slug="' . esc_attr($slug) . '">Choose ' . esc_html($planLabel) . '</a>';
            }
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';

        echo '<div class="amai-plan-faq-sep"></div>';

        echo '<div class="amai-faq">';
        echo '<h2 class="amai-faq__title">Frequently asked questions</h2>';
        $faqs = [
            ['Can I cancel anytime?', 'Yes. Cancel any time from inside the plugin. We automatically refund whatever time you have left on your billing period - no questions asked. Your account drops to the free plan so you can keep using Facebook and Instagram as long as you like.'],
            ['What happens at the end of my free plan?', 'Your account stays active on the free plan indefinitely. You can upgrade to a paid plan whenever you are ready.'],
            ['Do I need a WordPress site?', 'Yes. AutoMarketer AI is a WordPress plugin. You install it on your existing WordPress site and it handles your marketing from there.'],
            ['Which social channels are supported?', 'Multiple social channels are live now, with more added regularly. Check the Modules page to see the full list.'],
            ['What AI providers do you use?', 'AutoMarketer AI supports Claude, GPT-4, Gemini, Grok, and more. You choose which one writes your content.'],
            ['Is there a long-term contract?', 'No. Yearly plans are billed once per year with no long-term commitment. Monthly plans can be cancelled anytime.'],
        ];
        foreach ($faqs as $faq) {
            echo '<div class="amai-faq__item">';
            echo '<div class="amai-faq__q">' . esc_html($faq[0]) . '</div>';
            echo '<div class="amai-faq__a">' . esc_html($faq[1]) . '</div>';
            echo '</div>';
        }
        echo '</div>';

        echo '<div class="amai-pricing-cta amai-pricing-cta--warm">';
        echo '<h2 class="amai-pricing-cta__title">Ready to put your marketing on autopilot?</h2>';
        echo '<p class="amai-pricing-cta__sub">Free forever. No credit card required.</p>';
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--primary amai-btn--lg">Get Started Free</a>';
        echo '</div>';

        echo '</div>';
        echo '</main>';
        self::htmlClose();
    }

    // --------------------------------------------------
    // Features page
    // --------------------------------------------------
    private static function renderFeatures(): void
    {
        $getStartedUrl = home_url('/get-started');
        self::htmlOpen('Features');
        echo '<main class="amai-main">';
        echo '<div class="amai-container">';

        echo '<div class="amai-page-header">';
        echo '<div class="amai-tag">Features</div>';
        echo '<h1 class="amai-page-header__title">Everything your marketing needs</h1>';
        echo '<p class="amai-page-header__sub">One platform for AI content, multi-channel posting, and growing your online presence.</p>';
        echo '</div>';

        $features = [
            [
                'title'   => 'AI Content Generation',
                'desc'    => 'AutoMarketer AI connects to leading AI providers - Claude, GPT-4, Gemini, Grok, and more - to write posts specifically for your business. Every week you get a full set of fresh, relevant drafts ready to review and approve.',
                'svg'     => self::svgAiContent(),
                'bullets' => [
                    'Choose your AI provider',
                    'Posts written for your specific business',
                    'Fresh content every week',
                    'Full control or fully hands-free - your choice',
                ],
            ],
            [
                'title'   => 'Multi-Channel Social Posting',
                'desc'    => 'Connect your social channels and manage everything from one clean dashboard. Posts are scheduled at the best times for each channel and published automatically.',
                'svg'     => self::svgMultiChannel(),
                'bullets' => [
                    'Multiple channels live now, more shipping regularly',
                    'Per-channel scheduling and timing',
                    'One dashboard for all channels',
                    'More integrations added regularly',
                ],
            ],
            [
                'title'   => 'Review and Approve Workflow',
                'desc'    => 'Stay in control of every post before it goes out. Review, edit, or reject drafts from a clean approval feed. Or enable Autopilot and let posts go out automatically without any intervention.',
                'svg'     => self::svgApprovalWorkflow(),
                'bullets' => [
                    'Weekly approval feed',
                    'Edit post content inline',
                    'Approve or reject individual posts',
                    'Autopilot mode for hands-free operation',
                ],
            ],
            [
                'title'   => 'AI Image Generation',
                'desc'    => 'Every post can have a beautiful image. AutoMarketer AI generates images automatically using AI, or pulls from the Unsplash library of millions of free photos. No design skills needed.',
                'svg'     => self::svgImageGeneration(),
                'bullets' => [
                    'AI image generation built in',
                    'Unsplash library access',
                    'Images matched to post content',
                    'No design skills required',
                ],
            ],
            [
                'title'   => 'Analytics and Insights (Coming Soon)',
                'desc'    => 'Post performance tracking is on the way. See likes, comments, reach, and engagement across all your channels in one place - so you always know what is working.',
                'svg'     => self::svgAnalytics(),
                'bullets' => [
                    'Per-post performance stats',
                    'Reach, likes, and comment tracking',
                    'Cross-channel reporting in one dashboard',
                    'Trend tracking over time',
                ],
            ],
        ];

        foreach ($features as $i => $f) {
            $even = ($i % 2 === 1);
            echo '<div class="amai-feature-block' . ($even ? ' amai-feature-block--flip' : '') . '">';
            echo '<div class="amai-feature-block__content">';
            echo '<h2 class="amai-feature-block__title">' . esc_html($f['title']) . '</h2>';
            echo '<p class="amai-feature-block__desc">' . esc_html($f['desc']) . '</p>';
            echo '<ul class="amai-feature-block__bullets">';
            foreach ($f['bullets'] as $bullet) {
                echo '<li class="amai-feature-block__bullet">'
                    . '<span class="amai-feature-block__check" aria-hidden="true">'
                    . '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="7.25" stroke="#D97757" stroke-width="1.5"/><path d="M5 8.5L7 10.5L11 6" stroke="#D97757" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>'
                    . '</span>'
                    . esc_html($bullet)
                    . '</li>';
            }
            echo '</ul>';
            echo '</div>';
            echo '<div class="amai-feature-block__visual">' . $f['svg'] . '</div>';
            echo '</div>';
        }

        echo '<div class="amai-features-cta">';
        echo '<div class="amai-features-cta__inner">';
        echo '<h2 class="amai-features-cta__title">Your marketing runs itself from here.</h2>';
        echo '<p class="amai-features-cta__sub">Connect your channels, let AI do the writing, and watch your online presence grow - without lifting a finger.</p>';
        echo '<a href="' . esc_url($getStartedUrl) . '" class="amai-btn amai-btn--primary amai-btn--lg">Get Started Free</a>';
        echo '<p class="amai-features-cta__note">Free forever. No credit card required.</p>';
        echo '</div>';
        echo '</div>';

        echo '</div>';
        echo '</main>';
        self::htmlClose();
    }

    // --------------------------------------------------
    // Welcome page -- shown after Stripe success
    // --------------------------------------------------
    private static function renderWelcome(): void
    {
        if (!is_user_logged_in() || !current_user_can('manage_automarketer_ai')) {
            wp_redirect(home_url('/'));
            exit;
        }

        $licenseKey  = (string) get_option('automarketer_ai_license_key', '');
        $plan        = (string) get_option('automarketer_ai_plan_id', 'free');
        $downloadUrl = 'https://automarketer-ai.com/plugin-download';
        $dashUrl     = admin_url('admin.php?page=automarketer-ai');

        $planLabels = [
            'basic'        => 'Basic',
            'starter'      => 'Starter',
            'starter_pro'  => 'Starter Pro',
            'unlimited_ai' => 'Unlimited AI',
            'agency'       => 'Agency',
        ];
        $planLabel = $planLabels[$plan] ?? ucfirst($plan);

        self::htmlOpen('Welcome to AutoMarketer AI');
        echo '<main class="amai-welcome">';
        echo '<div class="amai-container amai-welcome__inner">';
        echo '<div class="amai-welcome__card">';
        echo '<div class="amai-welcome__eyebrow">Welcome aboard</div>';
        echo '<h1 class="amai-welcome__title">Welcome to AutoMarketer AI</h1>';
        echo '<p class="amai-welcome__plan">Plan: <strong>' . esc_html($planLabel) . '</strong></p>';

        echo '<div class="amai-welcome__section">';
        echo '<h2 class="amai-welcome__section-title">Your License Key</h2>';
        echo '<p class="amai-welcome__hint">Keep this safe. You will need it to activate the plugin on your site.</p>';
        if ($licenseKey !== '') {
            echo '<div class="amai-welcome__key-wrap">';
            echo '<code class="amai-welcome__key" id="amai-license-key">' . esc_html($licenseKey) . '</code>';
            echo '<button type="button" class="amai-btn amai-btn--secondary amai-welcome__copy" data-target="amai-license-key">Copy</button>';
            echo '</div>';
        } else {
            echo '<p class="amai-welcome__key-missing">Your license key will be emailed to you shortly.</p>';
        }
        echo '</div>';

        echo '<div class="amai-welcome__section">';
        echo '<h2 class="amai-welcome__section-title">Download the Plugin</h2>';
        echo '<p class="amai-welcome__hint">Install the plugin on your WordPress site to get started.</p>';
        echo '<a href="' . esc_url($downloadUrl) . '" class="amai-btn amai-btn--primary amai-welcome__download" target="_blank" rel="noopener">Download AutoMarketer AI</a>';
        echo '</div>';

        echo '<div class="amai-welcome__section">';
        echo '<h2 class="amai-welcome__section-title">Next steps</h2>';
        echo '<ol class="amai-welcome__steps">';
        echo '<li>Download and install the plugin on your WordPress site - <button type="button" class="amai-welcome__install-link" id="amai-install-help">How to install</button></li>';
        echo '<li>Go to AutoMarketer AI &gt; Overview and enter your license key to activate</li>';
        echo '<li>Connect your first AI copy provider to enable content generation</li>';
        echo '<li>Connect your first AI image provider to add visuals to your posts</li>';
        echo '<li>Connect your social channels and schedule your first posts</li>';
        echo '</ol>';
        echo '</div>';

        echo '<div class="amai-welcome__actions">';
        echo '<a href="' . esc_url($dashUrl) . '" class="amai-btn amai-btn--secondary" style="border:2px solid #D97757;color:#D97757;font-weight:700;">Go to Dashboard</a>';
        echo '</div>';

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

        echo '<style>';
        echo '.amai-welcome__install-link{background:none;border:none;padding:0;color:#D97757;font-family:inherit;font-size:inherit;cursor:pointer;text-decoration:underline;}';
        echo '.amai-install-modal{display:none;position:fixed;inset:0;z-index:9999;align-items:center;justify-content:center;}';
        echo '.amai-install-modal.is-open{display:flex;}';
        echo '.amai-install-modal__backdrop{position:absolute;inset:0;background:rgba(0,0,0,0.5);backdrop-filter:blur(2px);}';
        echo '.amai-install-modal__box{position:relative;z-index:1;background:#fff;border-radius:16px;padding:40px;max-width:520px;width:90%;box-shadow:0 8px 40px rgba(0,0,0,0.15);}';
        echo '.amai-install-modal__eyebrow{font-family:Nunito,sans-serif;font-size:11px;font-weight:800;letter-spacing:0.1em;text-transform:uppercase;color:#D97757;margin-bottom:10px;}';
        echo '.amai-install-modal__title{font-family:Nunito,sans-serif;font-size:22px;font-weight:900;color:#1a1a1a;margin:0 0 24px;}';
        echo '.amai-install-modal__steps{list-style:none;padding:0;margin:0;counter-reset:install-step;}';
        echo '.amai-install-modal__steps li{counter-increment:install-step;display:flex;gap:14px;align-items:flex-start;padding:14px 0;border-bottom:1px solid #F3EDE9;font-family:DM Sans,sans-serif;font-size:15px;color:#374151;line-height:1.5;}';
        echo '.amai-install-modal__steps li:last-child{border-bottom:none;}';
        echo '.amai-install-modal__steps li::before{content:counter(install-step);min-width:26px;height:26px;background:#D97757;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-family:Nunito,sans-serif;font-size:12px;font-weight:800;flex-shrink:0;}';
        echo '.amai-install-modal__steps strong{color:#1a1a1a;}';
        echo '.amai-install-modal__close{position:absolute;top:16px;right:16px;background:none;border:none;cursor:pointer;font-size:20px;color:#9CA3AF;line-height:1;padding:4px;}';
        echo '.amai-install-modal__close:hover{color:#1a1a1a;}';
        echo '.amai-login-helper{margin-bottom:24px;border:1.5px solid #E7DDD5;border-radius:10px;overflow:hidden;}';
        echo '.amai-login-helper__toggle{width:100%;background:#FDF8F6;border:none;padding:12px 16px;text-align:left;cursor:pointer;font-family:DM Sans,sans-serif;font-size:14px;font-weight:600;color:#D97757;display:flex;justify-content:space-between;align-items:center;}';
        echo '.amai-login-helper__toggle:hover{background:#FAF0EB;}';
        echo '.amai-login-helper__body{display:none;padding:16px;background:#fff;border-top:1px solid #F3EDE9;}';
        echo '.amai-login-helper__body.is-open{display:block;}';
        echo '.amai-login-helper__label{font-family:DM Sans,sans-serif;font-size:13px;color:#6B7280;margin-bottom:8px;}';
        echo '.amai-login-helper__input-row{display:flex;gap:8px;margin-bottom:12px;}';
        echo '.amai-login-helper__input{flex:1;border:1.5px solid #E7DDD5;border-radius:6px;padding:8px 12px;font-family:DM Mono,monospace;font-size:13px;color:#1a1a1a;outline:none;}';
        echo '.amai-login-helper__input:focus{border-color:#D97757;}';
        echo '.amai-login-helper__go{background:#D97757;color:#fff;border:none;border-radius:6px;padding:8px 16px;font-family:Nunito,sans-serif;font-size:13px;font-weight:800;cursor:pointer;white-space:nowrap;}';
        echo '.amai-login-helper__go:hover{background:#c46440;}';
        echo '.amai-login-helper__hint{font-family:DM Sans,sans-serif;font-size:12px;color:#9CA3AF;line-height:1.5;}';
        echo '</style>';

        echo '<div class="amai-install-modal" id="amai-install-modal" role="dialog" aria-modal="true" aria-labelledby="amai-install-modal-title">';
        echo '<div class="amai-install-modal__backdrop" id="amai-install-backdrop"></div>';
        echo '<div class="amai-install-modal__box">';
        echo '<button type="button" class="amai-install-modal__close" id="amai-install-close" aria-label="Close">&times;</button>';
        echo '<div class="amai-install-modal__eyebrow">Plugin installation</div>';
        echo '<h2 class="amai-install-modal__title" id="amai-install-modal-title">How to install AutoMarketer AI</h2>';
        echo '<div class="amai-login-helper">';
        echo '<button type="button" class="amai-login-helper__toggle" id="amai-login-toggle">';
        echo 'Don\'t have your WordPress admin login? <span id="amai-login-arrow">&#9660;</span>';
        echo '</button>';
        echo '<div class="amai-login-helper__body" id="amai-login-body">';
        echo '<p class="amai-login-helper__label">Enter your site URL and we will open your WordPress login page in a new tab:</p>';
        echo '<div class="amai-login-helper__input-row">';
        echo '<input type="text" class="amai-login-helper__input" id="amai-site-url" placeholder="https://yoursite.com" />';
        echo '<button type="button" class="amai-login-helper__go" id="amai-reset-go">Go</button>';
        echo '</div>';
        echo '<p class="amai-login-helper__hint">We will open your WordPress login page in a new tab. If your password is saved in your browser you are straight in. If not, click \'Lost your password?\' on that page and a reset link will be sent to your admin email.</p>';
        echo '</div>';
        echo '</div>';
        echo '<ol class="amai-install-modal__steps">';
        echo '<li>In your WordPress admin, go to <a href="' . esc_url(admin_url('plugin-install.php')) . '" target="_blank" rel="noopener" style="color:#D97757;font-weight:700;text-decoration:underline;">Plugins &gt; Add New Plugin</a></li>';
        echo '<li>Click <strong>Upload Plugin</strong> at the top of the page</li>';
        echo '<li>Click <strong>Choose File</strong> and select the ZIP you just downloaded</li>';
        echo '<li>Click <strong>Install Now</strong></li>';
        echo '<li>Click <strong>Activate Plugin</strong> - you are done</li>';
        echo '</ol>';
        echo '</div>';
        echo '</div>';

        echo '<script>';
        echo '(function() {';
        echo '    var modal   = document.getElementById("amai-install-modal");';
        echo '    var trigger = document.getElementById("amai-install-help");';
        echo '    var close   = document.getElementById("amai-install-close");';
        echo '    function openModal() { modal.classList.add("is-open"); }';
        echo '    function closeModal() { modal.classList.remove("is-open"); }';
        echo '    if (trigger) trigger.addEventListener("click", openModal);';
        echo '    if (close) close.addEventListener("click", closeModal);';
        echo '    document.addEventListener("keydown", function(e) { if (e.key === "Escape") closeModal(); });';
        echo '    var loginToggle  = document.getElementById("amai-login-toggle");';
        echo '    var loginBody    = document.getElementById("amai-login-body");';
        echo '    var loginArrow   = document.getElementById("amai-login-arrow");';
        echo '    var resetGo      = document.getElementById("amai-reset-go");';
        echo '    var siteUrlInput = document.getElementById("amai-site-url");';
        echo '    if (loginToggle) loginToggle.addEventListener("click", function() {';
        echo '        var isOpen = loginBody.classList.toggle("is-open");';
        echo '        loginArrow.innerHTML = isOpen ? "&#9650;" : "&#9660;";';
        echo '    });';
        echo '    if (resetGo) resetGo.addEventListener("click", function() {';
        echo '        var url = siteUrlInput.value.trim().replace(/\/+$/, "");';
        echo '        if (!url) { siteUrlInput.focus(); return; }';
        echo '        if (!/^https?:\/\//i.test(url)) url = "https://" + url;';
        echo '        window.open(url + "/wp-login.php", "_blank");';
        echo '    });';
        echo '    if (siteUrlInput) siteUrlInput.addEventListener("keydown", function(e) {';
        echo '        if (e.key === "Enter") resetGo.click();';
        echo '    });';
        echo '})();';
        echo 'document.querySelectorAll(".amai-welcome__copy").forEach(function(btn) {';
        echo '    btn.addEventListener("click", function() {';
        echo '        var el = document.getElementById(btn.dataset.target);';
        echo '        if (!el) return;';
        echo '        navigator.clipboard.writeText(el.textContent.trim()).then(function() {';
        echo '            btn.textContent = "Copied";';
        echo '            setTimeout(function() { btn.textContent = "Copy"; }, 2000);';
        echo '        });';
        echo '    });';
        echo '});';
        echo '</script>';

        self::htmlClose();
    }

    // --------------------------------------------------

    // --------------------------------------------------
    // Public releases page -- lists all releases with changelog, gated by license
    // --------------------------------------------------
    private static function renderReleases(): void
    {
        $releasesDir = '/home/ploi/releases';
        $files       = glob($releasesDir . '/automarketer-ai-v*.zip');
        if ($files === false) {
            $files = [];
        }
        usort($files, function (string $a, string $b): int {
            preg_match('/v(\d+\.\d+\.\d+)\.zip$/', $a, $ma);
            preg_match('/v(\d+\.\d+\.\d+)\.zip$/', $b, $mb);
            return version_compare($mb[1] ?? '0', $ma[1] ?? '0');
        });

        $currentZip = (string) get_option('amai_current_release', '');
        if ($currentZip === '' && !empty($files)) {
            $currentZip = basename((string) $files[0]);
        }

        $releases = [];
        foreach ($files as $f) {
            $base   = basename((string) $f);
            $ver    = '';
            if (preg_match('/^automarketer-ai-v(\d+\.\d+\.\d+)\.zip$/', $base, $m)) {
                $ver = $m[1];
            }
            $size   = filesize((string) $f);
            $sizeMb = $size !== false ? round($size / 1048576, 1) : 0;
            $mtime  = filemtime((string) $f);
            $date   = $mtime !== false ? gmdate('F j, Y', $mtime) : '';
            $log    = $ver !== '' ? (string) get_option('amai_release_changelog_' . $ver, '') : '';
            $current = ($base === $currentZip);
            $releases[] = compact('base', 'ver', 'sizeMb', 'date', 'log', 'current');
        }

        $fontBase    = esc_url(home_url('/wp-content/plugins/automarketer-ai/assets/fonts/'));
        $downloadUrl = home_url('/plugin-download');

        http_response_code(200);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Downloads - AutoMarketer AI</title>';
        echo '<style>';
        echo '*{box-sizing:border-box;margin:0;padding:0}';
        echo '@font-face{font-family:"Nunito";font-style:normal;font-weight:800;src:url(' . $fontBase . 'Nunito-ExtraBold.woff2) format("woff2")}';
        echo '@font-face{font-family:"DM Sans";font-style:normal;font-weight:400;src:url(' . $fontBase . 'DMSans-Regular.woff2) format("woff2")}';
        echo '@font-face{font-family:"DM Sans";font-style:normal;font-weight:500;src:url(' . $fontBase . 'DMSans-Medium.woff2) format("woff2")}';
        echo 'body{background:#F9FAFB;font-family:"DM Sans",system-ui,sans-serif;color:#1C1917;min-height:100vh}';
        echo '.wrap{max-width:760px;margin:0 auto;padding:56px 24px 80px}';
        echo '.back{font-size:13px;color:#78716C;text-decoration:none;display:inline-flex;align-items:center;gap:6px;margin-bottom:40px}';
        echo '.back:hover{color:#D97757}';
        echo '.eyebrow{font-size:11px;font-weight:500;letter-spacing:.1em;text-transform:uppercase;color:#D97757;margin-bottom:10px}';
        echo '.page-title{font-family:"Nunito",sans-serif;font-size:30px;font-weight:800;color:#1C1917;margin-bottom:8px;line-height:1.2}';
        echo '.page-sub{font-size:15px;color:#78716C;margin-bottom:40px;line-height:1.6}';
        echo '.rel-card{background:#fff;border:1.5px solid #E7DDD5;border-radius:16px;padding:24px 28px;margin-bottom:16px}';
        echo '.rel-card--current{border-left:4px solid #D97757}';
        echo '.rel-card--old{opacity:.65}';
        echo '.rel-top{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:4px}';
        echo '.rel-left{display:flex;align-items:center;gap:10px}';
        echo '.rel-ver{font-family:"Nunito",sans-serif;font-size:18px;font-weight:800;color:#1C1917}';
        echo '.rel-badge{font-size:11px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;padding:3px 9px;border-radius:20px;background:#EAF3DE;color:#3B6D11}';
        echo '.rel-meta{font-size:12.5px;color:#A8A29E;margin-top:2px}';
        echo '.rel-dl{display:inline-flex;align-items:center;gap:7px;font-size:13.5px;font-weight:600;color:#fff;background:#D97757;border-radius:8px;padding:9px 18px;text-decoration:none;white-space:nowrap}';
        echo '.rel-dl:hover{background:#C4633E}';
        echo '.rel-dl-old{display:inline-flex;align-items:center;gap:7px;font-size:13.5px;font-weight:500;color:#78716C;background:transparent;border:1.5px solid #E7DDD5;border-radius:8px;padding:8px 18px;text-decoration:none;white-space:nowrap}';
        echo '.rel-dl-old:hover{border-color:#D97757;color:#D97757}';
        echo '.rel-log{margin-top:16px;padding-top:16px;border-top:1px solid #F3EDE8}';
        echo '.rel-log-label{font-size:12px;font-weight:500;color:#A8A29E;text-transform:uppercase;letter-spacing:.07em;margin-bottom:8px}';
        echo '.rel-log ul{list-style:none;padding:0;margin:0}';
        echo '.rel-log li{font-size:13.5px;color:#44403C;line-height:1.7;padding:3px 0 3px 16px;position:relative}';
        echo '.rel-log li:before{content:"";position:absolute;left:0;top:11px;width:5px;height:5px;border-radius:50%;background:#D97757}';
        echo '.install-box{background:#fff;border:1.5px solid #E7DDD5;border-radius:16px;padding:24px 28px;margin-top:32px}';
        echo '.install-title{font-size:14px;font-weight:500;color:#1C1917;margin-bottom:12px}';
        echo '.install-steps{list-style:none;padding:0;margin:0;counter-reset:steps}';
        echo '.install-steps li{counter-increment:steps;font-size:13.5px;color:#44403C;line-height:1.7;padding:4px 0 4px 28px;position:relative}';
        echo '.install-steps li:before{content:counter(steps);position:absolute;left:0;top:4px;width:18px;height:18px;border-radius:50%;background:#FDF3EE;color:#D97757;font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;text-align:center;line-height:18px}';
        echo '.rel-empty{text-align:center;padding:60px 0;color:#A8A29E;font-size:15px}';
        echo '</style></head><body>';
        echo '<div class="wrap">';
        echo '<a href="' . esc_url(home_url('/')) . '" class="back">&larr; AutoMarketer AI</a>';
        echo '<div class="eyebrow">Downloads</div>';
        echo '<h1 class="page-title">Get the plugin</h1>';
        echo '<p class="page-sub">Download the latest version of AutoMarketer AI and install it on your WordPress site. You\'ll need a license key to activate it. Don\'t have one yet? <a href="' . esc_url(home_url('/pricing')) . '" style="color:#D97757;text-decoration:none;font-weight:500">You can get started for free</a> -- no credit card required.</p>';

        if (empty($releases)) {
            echo '<div class="rel-empty">No releases yet. Check back soon.</div>';
        } else {
            foreach ($releases as $rel) {
                $isCurrent = $rel['current'];
                $cardClass = $isCurrent ? 'rel-card rel-card--current' : 'rel-card rel-card--old';
                $dlClass   = $isCurrent ? 'rel-dl' : 'rel-dl-old';
                $dlUrl     = esc_url(add_query_arg(['zip' => rawurlencode($rel['base'])], $downloadUrl));
                echo '<div class="' . $cardClass . '">';
                echo '<div class="rel-top">';
                echo '<div class="rel-left"><div>';
                echo '<div style="display:flex;align-items:center;gap:8px">';
                echo '<span class="rel-ver">v' . esc_html($rel['ver']) . '</span>';
                if ($isCurrent) {
                    echo '<span class="rel-badge">Latest</span>';
                }
                echo '</div>';
                echo '<div class="rel-meta">' . esc_html($rel['date']) . ' &middot; ' . esc_html((string) $rel['sizeMb']) . ' MB</div>';
                echo '</div></div>';
                echo '<a href="' . $dlUrl . '" class="' . $dlClass . '">Download v' . esc_html($rel['ver']) . '</a>';
                echo '</div>';
                if ($rel['log'] !== '') {
                    $lines = array_filter(array_map('trim', explode("\n", $rel['log'])));
                    echo '<div class="rel-log">';
                    
                    echo '<ul>';
                    foreach ($lines as $line) {
                        $line = ltrim((string) $line, '-* ');
                        if ($line !== '') {
                            echo '<li>' . esc_html($line) . '</li>';
                        }
                    }
                    echo '</ul></div>';
                }
                echo '</div>';
            }
        }

        echo '<div class="install-box">';
        echo '<div class="install-title">How to install</div>';
        echo '<ol class="install-steps">';
        echo '<li>Download the ZIP above</li>';
        echo '<li>In your WordPress admin go to Plugins &gt; Add New &gt; Upload Plugin</li>';
        echo '<li>Upload the ZIP, install, and activate</li>';
        echo '<li>Paste your license key when prompted</li>';
        echo '</ol>';
        echo '</div>';
        echo '</div></body></html>';
        exit;
    }

    private static function renderPluginDownload(): void
    {
        $releasesDir = '/home/ploi/releases/';
        $requested   = isset($_GET['zip']) ? basename((string) $_GET['zip']) : '';
        if ($requested !== '' && preg_match('/^automarketer-ai-v[\d.]+\.zip$/', $requested)) {
            $currentZip = $requested;
        } else {
            $currentZip = (string) get_option('amai_current_release', '');
            if ($currentZip === '') {
                $files = glob($releasesDir . 'automarketer-ai-v*.zip');
                if ($files === false || count($files) === 0) {
                    wp_die('No release available. Please contact support@automarketer-ai.com.', 'Download Unavailable', ['response' => 503]);
                }
                sort($files);
                $last = end($files);
                $currentZip = is_string($last) ? basename($last) : '';
            }
        }
        if ($currentZip === '') {
            wp_die('No release available. Please contact support@automarketer-ai.com.', 'Download Unavailable', ['response' => 503]);
        }
        $zipPath  = $releasesDir . $currentZip;
        $realPath = realpath($zipPath);
        if ($realPath === false || !str_starts_with($realPath, rtrim($releasesDir, '/') . '/')) {
            wp_die('Download link is invalid. Please contact support.', 'Error', ['response' => 500]);
        }
        if (!is_file($realPath)) {
            wp_die('Release file not found. Please contact support@automarketer-ai.com.', 'Download Unavailable', ['response' => 503]);
        }
        $fileName = basename($realPath);
        $fileSize = filesize($realPath);
        if ($fileSize === false) {
            wp_die('Could not read release file.', 'Error', ['response' => 500]);
        }
        error_log('[AMAI] Plugin download: file=' . $fileName . ' time=' . gmdate('c'));
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Length: ' . $fileSize);
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
        $handle = fopen($realPath, 'rb');
        if ($handle === false) {
            wp_die('Could not open release file.', 'Error', ['response' => 500]);
        }
        while (!feof($handle)) {
            $chunk = fread($handle, 8192);
            if ($chunk !== false) {
                echo $chunk;
            }
        }
        fclose($handle);
        exit;
    }
    // --------------------------------------------------
    // Onboarding wizard
    // --------------------------------------------------
    private static function renderGetStarted(): void
    {
        $primaryUserId = (int) get_option('amai_primary_user_id', 0);
        if ($primaryUserId !== 0 && get_user_by('id', $primaryUserId) === false) {
            update_option('amai_primary_user_id', 0);
            update_user_meta(get_current_user_id(), 'amai_setup_step', 1);
            $primaryUserId = 0;
        }
        if ($primaryUserId !== 0 && is_user_logged_in()) {
            $step = (int) (get_user_meta((int) get_option('amai_primary_user_id', 0), 'amai_setup_step', true) ?: 6);
            if ($step >= 6) {
                $planParam    = sanitize_key(wp_unslash($_GET['plan'] ?? ''));
                $billingParam = in_array($_GET['billing'] ?? '', ['yearly', 'monthly'], true) ? sanitize_key(wp_unslash($_GET['billing'])) : 'yearly';
                $priceId      = self::resolvePriceId($planParam, $billingParam);
                if ($priceId !== '') {
                    $user     = wp_get_current_user();
                    $tenantId = (string) get_option('amai_tenant_id', '');
                    if ($tenantId !== '' && $user->ID !== 0) {
                        $sessionId = self::createStripeCheckout($priceId, $user->user_email, $tenantId, $user->ID);
                        if ($sessionId !== '') {
                            wp_redirect($sessionId);
                            exit;
                        }
                    }
                }
                wp_redirect(admin_url('admin.php?page=automarketer-ai'));
                exit;
            }
        }

        $primaryExists = (int) get_option('amai_primary_user_id', 0) !== 0;
        if (!$primaryExists) {
            update_user_meta(get_current_user_id(), 'amai_setup_step', 1);
        }

        $selectedPlan    = sanitize_key(wp_unslash($_GET['plan'] ?? ''));
        $selectedBilling = in_array($_GET['billing'] ?? '', ['yearly', 'monthly'], true)
            ? sanitize_key(wp_unslash($_GET['billing']))
            : 'yearly';

        self::htmlOpen('Get Started - AutoMarketer AI');
        echo '<main class="amai-wizard">';
        echo '<div class="amai-wizard__inner">';

        echo '<div class="amai-wizard__progress">';
        for ($i = 1; $i <= 2; $i++) {
            echo '<div class="amai-wizard__step-dot" data-step="' . $i . '"><span>' . $i . '</span></div>';
            if ($i < 2) {
                echo '<div class="amai-wizard__step-line"></div>';
            }
        }
        echo '</div>';

        echo '<div class="amai-wizard__card">';

        // Plan context banner for paid plans
        if ($selectedPlan !== '' && $selectedPlan !== 'free' && isset(self::PLANS[$selectedPlan])) {
            $planLabel    = (string) (self::PLANS[$selectedPlan]['label'] ?? $selectedPlan);
            $billingLabel = $selectedBilling === 'monthly' ? 'monthly' : 'yearly';
            echo '<div class="amai-wizard__plan-banner">';
            echo '<span class="amai-wizard__plan-banner-icon">&#10003;</span>';
            echo '<span>You\'re signing up for <strong>' . esc_html($planLabel) . '</strong> (' . esc_html($billingLabel) . '). Create your free account first, then complete billing.</span>';
            echo '</div>';
        }

        echo '<div id="amai-wizard-error" class="amai-wizard__error"></div>';
        echo '<form id="amai-wizard-form">';

        echo '<div class="amai-wizard__step" id="amai-step-1">';
        echo '<div class="amai-wizard__eyebrow">Step 1 of 2</div>';
        echo '<h1 class="amai-wizard__title">Create your account</h1>';
        echo '<p class="amai-wizard__subtitle">Free forever. No credit card required.</p>';
        echo '<div class="amai-wizard__group">';
        echo '<label class="amai-wizard__label" for="first_name">First name</label>';
        echo '<input type="text" id="first_name" name="first_name" class="amai-wizard__input" autocomplete="given-name" placeholder="Jane">';
        echo '</div>';
        echo '<div class="amai-wizard__group">';
        echo '<label class="amai-wizard__label" for="email">Email address</label>';
        echo '<input type="email" id="email" name="email" class="amai-wizard__input" autocomplete="email" placeholder="jane@example.com">';
        echo '</div>';
        echo '<p class="amai-wizard__hint">By continuing you agree to our <a href="https://automarketer-ai.com/terms" target="_blank" rel="noopener">Terms of Service</a> and <a href="https://automarketer-ai.com/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</p>';
        echo '</div>';

        echo '<div class="amai-wizard__step" id="amai-step-2">';
        echo '<div class="amai-wizard__eyebrow">Step 2 of 2</div>';
        echo '<h1 class="amai-wizard__title">Tell us about your business</h1>';
        echo '<p class="amai-wizard__subtitle">This helps AutoMarketer AI write content that sounds like you.</p>';
        echo '<div class="amai-wizard__group">';
        echo '<label class="amai-wizard__label" for="business_name">Business name</label>';
        echo '<input type="text" id="business_name" name="business_name" class="amai-wizard__input" autocomplete="organization" placeholder="Acme Co.">';
        echo '</div>';
        echo '<div class="amai-wizard__group">';
        echo '<label class="amai-wizard__label" for="website">Website</label>';
        echo '<input type="url" id="website" name="website" class="amai-wizard__input" autocomplete="url" placeholder="https://example.com">';
        echo '</div>';
        echo '<div class="amai-wizard__group">';
        echo '<label class="amai-wizard__label" for="business_desc">What does your business do? <span>2-3 sentences</span></label>';
        echo '<textarea id="business_desc" name="business_desc" class="amai-wizard__textarea" placeholder="We help small business owners automate their social media marketing using AI..."></textarea>';
        echo '</div>';
        echo '</div>';

        echo '</form>';

        echo '<div class="amai-wizard__nav">';
        echo '<button type="button" class="amai-wizard__back" id="amai-wizard-back" style="visibility:hidden;">';
        echo '<svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M8.5 2L4 7l4.5 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
        echo ' Back';
        echo '</button>';
        echo '<button type="button" class="amai-btn amai-btn--primary amai-wizard__next" id="amai-wizard-next">Continue</button>';
        echo '</div>';

        echo '</div>';
        echo '</div>';
        echo '</main>';
        self::htmlClose();
    }

    // --------------------------------------------------
    // Wizard AJAX: step save
    // --------------------------------------------------
    public static function handleWizardStep(): void
    {
        $nonce = isset($_POST['_ajax_nonce']) ? sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'amai_wizard_step')) {
            wp_send_json_error(['message' => 'Invalid nonce.']);
            return;
        }

        $step = (int) ($_POST['step'] ?? 0);

        if ($step === 1) {
            $firstName = sanitize_text_field(wp_unslash($_POST['first_name'] ?? ''));
            $email     = sanitize_email(wp_unslash($_POST['email'] ?? ''));

            if ($firstName === '' || !is_email($email)) {
                wp_send_json_error(['message' => 'Please enter your name and a valid email address.']);
                return;
            }

            $existingId = email_exists($email);
            if ($existingId !== false) {
                wp_set_auth_cookie((int) $existingId, false);
                wp_set_current_user((int) $existingId);
                $existingStep = (int) (get_user_meta((int) $existingId, 'amai_setup_step', true) ?: 1);
                wp_send_json_success(['message' => 'ok', 'step' => max(2, $existingStep)]);
                return;
            }

            $username = $email;
            $password = wp_generate_password(16, true, false);
            $userId   = wp_create_user($username, $password, $email);

            if (is_wp_error($userId)) {
                wp_send_json_error(['message' => 'Something went wrong creating your account. Please try again or contact support.']);
                return;
            }

            wp_update_user(['ID' => $userId, 'first_name' => $firstName, 'display_name' => $firstName, 'role' => 'administrator']);
            $user = get_user_by('id', $userId);
            if ($user instanceof WP_User) {
                $user->add_cap('manage_automarketer_ai');
            }
            wp_set_auth_cookie($userId, false);
            wp_set_current_user($userId);

            $coreResponse = wp_remote_post(self::CORE_REGISTER_URL, [
                'timeout' => 15,
                'headers' => ['Content-Type' => 'application/json'],
                'body'    => (string) json_encode([
                    'first_name' => $firstName,
                    'email'      => $email,
                    'wp_user_id' => $userId,
                    'site_url'   => get_bloginfo('url'),
                ]),
            ]);

            if (!is_wp_error($coreResponse)) {
                $body = json_decode(wp_remote_retrieve_body($coreResponse), true);
                if (is_array($body) && !empty($body['license_key'])) {
                    $licenseKey = sanitize_text_field((string) $body['license_key']);
                    $apiSecret  = sanitize_text_field((string) ($body['api_secret'] ?? ''));
                    $tenantId   = sanitize_text_field((string) ($body['tenant_id'] ?? ''));
                    update_user_meta($userId, 'amai_license_key', $licenseKey);
                    update_user_meta($userId, 'amai_api_secret', $apiSecret);
                    update_user_meta($userId, 'amai_tenant_id', $tenantId);
                    update_option('amai_tenant_id', $tenantId);
                    update_option('automarketer_ai_plan_id', 'basic');
                    update_option('automarketer_ai_license_status', 'active');
                    update_option('amai_primary_user_id', $userId);
                    self::seedTenantOnCore($tenantId);
                    self::sendWizardWelcomeEmail($email, $firstName, $licenseKey, $password);
                    WebhookReceiver::notifyAdminFreeSignup($email);
                }
            }

            update_user_meta(get_current_user_id(), 'amai_setup_step', 2);
            wp_send_json_success(['message' => 'ok']);
            return;
        }

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => 'Session expired. Please refresh and try again.']);
            return;
        }

        if ($step === 2) {
            $bizName = sanitize_text_field(wp_unslash($_POST['business_name'] ?? ''));
            $website = esc_url_raw(wp_unslash($_POST['website'] ?? ''));
            $desc    = sanitize_textarea_field(wp_unslash($_POST['business_desc'] ?? ''));

            if ($bizName === '' || $website === '' || $desc === '') {
                wp_send_json_error(['message' => 'Please fill in all fields.']);
                return;
            }

            update_option('amai_business_name', $bizName);
            update_option('blogname', $bizName);
            update_option('siteurl_display', $website);

            global $wpdb;
            $table    = $wpdb->prefix . 'amai_business_profile';
            $existing = $wpdb->get_var($wpdb->prepare('SELECT id FROM ' . $table . ' WHERE tenant_id = %s LIMIT 1', 'default'));
            if ($existing !== null) {
                $wpdb->update($table, ['business_name' => $bizName, 'website_url' => $website, 'description' => $desc], ['tenant_id' => 'default']);
            } else {
                $wpdb->insert($table, ['tenant_id' => 'default', 'business_name' => $bizName, 'website_url' => $website, 'description' => $desc]);
            }

            update_user_meta(get_current_user_id(), 'amai_setup_step', 6);
            wp_send_json_success(['message' => 'ok']);
            return;
        }

        wp_send_json_error(['message' => 'Unknown step.']);
    }

    // --------------------------------------------------
    // Wizard AJAX: validate AI writing key
    // --------------------------------------------------
    public static function handleWizardValidateAi(): void
    {
        $nonce = isset($_POST['_ajax_nonce']) ? sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'amai_wizard_validate_ai')) {
            wp_send_json_error(['message' => 'Invalid nonce.']);
            return;
        }
        $providerId = sanitize_text_field(wp_unslash($_POST['provider_id'] ?? ''));
        $apiKey     = sanitize_text_field(wp_unslash($_POST['api_key'] ?? ''));
        if ($providerId === '' || $apiKey === '') {
            wp_send_json_error(['message' => 'Missing provider or key.']);
            return;
        }
        $moduleFile = AMAI_PLUGIN_DIR . 'modules/' . $providerId . '.php';
        if (!is_file($moduleFile)) {
            wp_send_json_error(['message' => 'Unknown provider.']);
            return;
        }
        require_once $moduleFile;
        $classMap = [
            'ai-claude'  => 'AutoMarketerAI\Modules\Claude',
            'ai-openai'  => 'AutoMarketerAI\Modules\Openai',
            'ai-gemini'  => 'AutoMarketerAI\Modules\Gemini',
            'ai-grok'    => 'AutoMarketerAI\Modules\Grok',
            'ai-mistral' => 'AutoMarketerAI\Modules\Mistral',
        ];
        $className = $classMap[$providerId] ?? '';
        if ($className === '' || !class_exists($className)) {
            wp_send_json_error(['message' => 'Something went wrong. Please try again.']);
            return;
        }
        $module = new $className();
        if ($module->validate_api_key($apiKey)) {
            wp_send_json_success(['message' => 'Key validated.']);
        } else {
            wp_send_json_error(['message' => 'Invalid API key. Please check and try again.']);
        }
    }

    // --------------------------------------------------
    // Wizard AJAX: validate image key
    // --------------------------------------------------
    public static function handleWizardValidateImg(): void
    {
        $nonce = isset($_POST['_ajax_nonce']) ? sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'amai_wizard_validate_img')) {
            wp_send_json_error(['message' => 'Invalid nonce.']);
            return;
        }
        $providerId = sanitize_text_field(wp_unslash($_POST['provider_id'] ?? ''));
        $apiKey     = sanitize_text_field(wp_unslash($_POST['api_key'] ?? ''));
        if ($providerId === '' || $apiKey === '') {
            wp_send_json_error(['message' => 'Missing provider or key.']);
            return;
        }
        $moduleFile = AMAI_PLUGIN_DIR . 'modules/' . $providerId . '.php';
        if (!is_file($moduleFile)) {
            wp_send_json_error(['message' => 'Unknown provider.']);
            return;
        }
        require_once $moduleFile;
        $classMap = [
            'img-imagen' => 'AutoMarketerAI\Modules\ImgImagen',
            'img-dalle'  => 'AutoMarketerAI\Modules\ImgDalle',
            'img-aurora' => 'AutoMarketerAI\Modules\ImgAurora',
        ];
        $className = $classMap[$providerId] ?? '';
        if ($className === '' || !class_exists($className)) {
            wp_send_json_error(['message' => 'Something went wrong. Please try again.']);
            return;
        }
        $module = new $className();
        if (method_exists($module, 'validate_api_key') && $module->validate_api_key($apiKey)) {
            wp_send_json_success(['message' => 'Key validated.']);
        } else {
            wp_send_json_error(['message' => 'Invalid API key. Please check and try again.']);
        }
    }

    // --------------------------------------------------
    // Wizard nonce refresh -- called after step 1 login
    // --------------------------------------------------
    public static function handleWizardNonces(): void
    {
        wp_send_json_success([
            'nonceStep'        => wp_create_nonce('amai_wizard_step'),
            'nonceValidateAi'  => wp_create_nonce('amai_wizard_validate_ai'),
            'nonceValidateImg' => wp_create_nonce('amai_wizard_validate_img'),
        ]);
    }

    // --------------------------------------------------
    // Wizard welcome email (includes temp password)
    // --------------------------------------------------
    private static function sendWizardWelcomeEmail(string $email, string $firstName, string $licenseKey, string $tempPassword): void
    {
        $subject      = 'Welcome to ' . get_bloginfo('name');
        $loginUrl     = home_url('/get-started');
        $changePassUrl = wp_lostpassword_url();
        $keyDisplay   = $licenseKey !== '' ? $licenseKey : '(see your dashboard)';
        $html = self::buildWizardWelcomeEmailHtml($firstName, $email, $tempPassword, $keyDisplay, $loginUrl, $changePassUrl);
        $headers = [
            'From: ' . \AutoMarketerAI\AbstractEmailProvider::get_sender_name() . ' <' . \AutoMarketerAI\AbstractEmailProvider::get_sender_email() . '>',
            'Reply-To: ' . \AutoMarketerAI\AbstractEmailProvider::get_sender_email(),
            'Content-Type: text/html; charset=UTF-8',
        ];
        wp_mail($email, $subject, $html, $headers);
    }

    // HTML template for free signup welcome email
    public static function buildWelcomeEmailHtml(string $firstName, string $licenseKey, string $loginUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('welcome')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('welcome', [
                '{{first_name}}' => esc_html($firstName),
                '{{license_key}}' => esc_html($licenseKey),
                '{{login_url}}'  => esc_url($loginUrl),
            ]);
        }
        $fn  = esc_html($firstName);
        $key = esc_html($licenseKey);
        $url = esc_url($loginUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">' . esc_html(get_bloginfo('name')) . '</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Welcome, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">' . esc_html((string) get_option('amai_email_tagline', 'Automated marketing that sounds like you.')) . ' Here&rsquo;s how to get it live on your site.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="margin:0 0 32px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Your License Key</div>'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:8px;padding:18px 24px;font-family:Courier New,Courier,monospace;font-size:13px;color:#3D3330;letter-spacing:.04em;word-break:break-all">' . $key . '</div>'
            . '<div style="font-size:12px;color:#9E8D8A;margin-top:8px">Paste this into your WordPress site when prompted to activate ' . esc_html(get_bloginfo('name')) . '.</div>'
            . '</div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 32px"></div>'
            . '<div style="margin:0 0 32px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:20px">Get live in 4 steps</div>'
            . '<table cellpadding="0" cellspacing="0" border="0" width="100%">'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">1</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Download and install the plugin</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Grab the zip from <a href="' . esc_url(defined('AMAI_RELEASES_URL') ? AMAI_RELEASES_URL : 'https://automarketer-ai.com/releases') . '" style="color:#D97757;text-decoration:none">' . esc_html(defined('AMAI_RELEASES_URL') ? AMAI_RELEASES_URL : 'https://automarketer-ai.com/releases') . '</a>, then go to WordPress Admin &rarr; Plugins &rarr; Add New &rarr; Upload Plugin. Select the zip, install, and activate. When prompted, paste your license key above.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">2</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Connect your AI providers</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Go to Modules in your dashboard and activate an AI content provider &mdash; ChatGPT and Gemini are popular choices, with more options available. You&rsquo;ll also need an AI image provider &mdash; DALL-E and Imagen are both excellent. You bring the keys; we handle everything else. The AI costs are surprisingly low. $10 will go a long way.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">3</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Tell the AI about your business</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Fill in your business profile &mdash; what you do, who you serve, your tone. This is what the AI uses to write content that actually sounds like you.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">4</div></td>'
            . '<td style="vertical-align:top;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Connect a channel and watch the content roll in</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Link your Facebook or Instagram page. Every Wednesday, ' . esc_html(get_bloginfo('name')) . ' automatically generates a full week of posts written specifically for your business. Review each one and approve what you like &mdash; approved posts go out on schedule.</div></td></tr>'
            . '</table></div>'
            . '<table cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 32px"><tr><td style="background:#D97757;border-radius:100px;padding:16px 40px"><a href="' . $url . '" style="display:inline-block;color:#fff;font-size:14px;font-weight:600;text-decoration:none">Log in to your account &rarr;</a></td></tr></table>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Questions? Reply to this email and we&rsquo;ll help you out.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you signed up at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for wizard/paid signup welcome email
    public static function buildWizardWelcomeEmailHtml(string $firstName, string $email, string $tempPassword, string $licenseKey, string $loginUrl, string $changePassUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('paid_welcome')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('paid_welcome', [
                '{{first_name}}'          => esc_html($firstName),
                '{{email}}'               => esc_html($email),
                '{{temp_password}}'       => esc_html($tempPassword),
                '{{license_key}}'         => esc_html($licenseKey),
                '{{login_url}}'           => esc_url($loginUrl),
                '{{change_password_url}}' => esc_url($changePassUrl),
            ]);
        }
        $fn   = esc_html($firstName);
        $em   = esc_html($email);
        $pass = esc_html($tempPassword);
        $key  = esc_html($licenseKey);
        $url  = esc_url($loginUrl);
        $cpu  = esc_url($changePassUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">' . esc_html(get_bloginfo('name')) . '</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Welcome, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">' . esc_html((string) get_option('amai_email_tagline', 'Automated marketing that sounds like you.')) . ' Here&rsquo;s everything you need.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="margin:0 0 24px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Your Account</div>'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-radius:4px;padding:16px 18px">'
            . '<table cellpadding="0" cellspacing="0" border="0" width="100%">'
            . '<tr><td style="font-size:12px;color:#9E8D8A;padding-bottom:10px;width:110px">Email</td><td style="font-size:13px;color:#3D3330;font-weight:500;padding-bottom:10px">' . $em . '</td></tr>'
            . '<tr><td style="font-size:12px;color:#9E8D8A;width:110px">Temp password</td><td style="font-family:Courier New,Courier,monospace;font-size:13px;color:#3D3330;font-weight:500">' . $pass . '</td></tr>'
            . '</table></div>'
            . '<div style="font-size:12px;color:#9E8D8A;margin-top:8px"><a href="' . $cpu . '" style="color:#D97757;text-decoration:none">Change your password</a> after you log in.</div>'
            . '</div>'
            . '<div style="margin:0 0 32px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Your License Key</div>'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:8px;padding:18px 24px;font-family:Courier New,Courier,monospace;font-size:13px;color:#3D3330;letter-spacing:.04em;word-break:break-all">' . $key . '</div>'
            . '<div style="font-size:12px;color:#9E8D8A;margin-top:8px">Paste this into your WordPress site when prompted to activate ' . esc_html(get_bloginfo('name')) . '.</div>'
            . '</div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 32px"></div>'
            . '<div style="margin:0 0 32px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:20px">Get live in 4 steps</div>'
            . '<table cellpadding="0" cellspacing="0" border="0" width="100%">'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">1</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Download and install the plugin</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Grab the zip from <a href="' . esc_url(defined('AMAI_RELEASES_URL') ? AMAI_RELEASES_URL : 'https://automarketer-ai.com/releases') . '" style="color:#D97757;text-decoration:none">' . esc_html(defined('AMAI_RELEASES_URL') ? AMAI_RELEASES_URL : 'https://automarketer-ai.com/releases') . '</a>, then go to WordPress Admin &rarr; Plugins &rarr; Add New &rarr; Upload Plugin. Select the zip, install, and activate. When prompted, paste your license key above.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">2</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Connect your AI providers</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Go to Modules in your dashboard and activate an AI content provider &mdash; ChatGPT and Gemini are popular choices, with more options available. You&rsquo;ll also need an AI image provider &mdash; DALL-E and Imagen are both excellent. You bring the keys; we handle everything else. The AI costs are surprisingly low. $10 will go a long way.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top;padding-bottom:24px"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">3</div></td>'
            . '<td style="vertical-align:top;padding-bottom:24px;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Tell the AI about your business</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Fill in your business profile &mdash; what you do, who you serve, your tone. This is what the AI uses to write content that actually sounds like you.</div></td></tr>'
            . '<tr><td style="width:36px;vertical-align:top"><div style="width:24px;height:24px;border-radius:50%;background:#D97757;text-align:center;line-height:24px;font-size:11px;font-weight:700;color:#fff">4</div></td>'
            . '<td style="vertical-align:top;padding-left:16px"><div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px">Connect a channel and watch the content roll in</div><div style="font-size:13px;color:#6B6260;line-height:1.6">Link your Facebook or Instagram page. Every Wednesday, ' . esc_html(get_bloginfo('name')) . ' automatically generates a full week of posts written specifically for your business. Review each one and approve what you like &mdash; approved posts go out on schedule.</div></td></tr>'
            . '</table></div>'
            . '<table cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 32px"><tr><td style="background:#D97757;border-radius:100px;padding:16px 40px"><a href="' . $url . '" style="display:inline-block;color:#fff;font-size:14px;font-weight:600;text-decoration:none">Log in to your account &rarr;</a></td></tr></table>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Questions? Reply to this email and we&rsquo;ll help you out.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you signed up at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for upgrade email -- free to Starter

    // HTML template for upgrade email -- free to Starter
    public static function buildUpgradeEmailHtmlStarter(string $firstName, string $modulesUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('upgrade_starter')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('upgrade_starter', [
                '{{first_name}}'  => esc_html($firstName),
                '{{modules_url}}' => esc_url($modulesUrl),
            ]);
        }
        $fn  = esc_html($firstName);
        $url = esc_url($modulesUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">FREE &rarr; STARTER</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Nice move, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Here is what just opened up for you.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">What&rsquo;s now unlocked</div>'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Facebook, Instagram, plus 5 additional modules.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6">You already had Facebook and Instagram. Now you can activate 5 more modules - social channels, content tools, and more. Head to your Modules page and pick the ones that matter most for your business.</div>'
            . '</div>'
            . '<div style="background:#FAF7F5;border-left:3px solid #D97757;border-radius:4px;padding:14px 18px;margin-bottom:28px">'
            . '<div style="font-size:13px;color:#57534E;line-height:1.6">Not sure where to start? Every module has a <strong>step-by-step walkthrough built right in</strong> - just look for the help link on any module page.</div>'
            . '</div>'
            . '<p style="margin:0 0 28px;font-size:15px;color:#57534E;line-height:1.7">Everything is already live on your site. Head to your Modules page and start activating.</p>'
            . '<div style="text-align:center;margin:0 0 32px"><a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Go to Your Modules &rarr;</a></div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Questions? Reply to this email and we&rsquo;ll help you out.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you upgraded at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for upgrade email -- any plan to Starter Pro
    public static function buildUpgradeEmailHtmlStarterPro(string $firstName, string $modulesUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('upgrade_starter_pro')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('upgrade_starter_pro', [
                '{{first_name}}'  => esc_html($firstName),
                '{{modules_url}}' => esc_url($modulesUrl),
            ]);
        }
        $fn  = esc_html($firstName);
        $url = esc_url($modulesUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">STARTER &rarr; STARTER PRO</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">The module limit is gone, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Here is what just opened up for you.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">What&rsquo;s now unlocked</div>'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Every regular module - now and forever.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6">The 5-module cap is gone. Activate as many regular modules as you like - social channels, content tools, and every new module we ship, automatically.</div>'
            . '</div>'
            . '<div style="background:#FAF7F5;border-left:3px solid #D97757;border-radius:4px;padding:14px 18px;margin-bottom:28px">'
            . '<div style="font-size:13px;color:#57534E;line-height:1.6">Not sure where to start? Every module has a <strong>step-by-step walkthrough built right in</strong> - just look for the help link on any module page.</div>'
            . '</div>'
            . '<p style="margin:0 0 28px;font-size:15px;color:#57534E;line-height:1.7">Everything is already live on your site. Head to your Modules page and activate as many as you like.</p>'
            . '<div style="text-align:center;margin:0 0 32px"><a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Go to Your Modules &rarr;</a></div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Questions? Reply to this email and we&rsquo;ll help you out.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you upgraded at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for blog nudge email -- title picker
    public static function buildNudgeEmailHtml(string $firstName, string $siteName, array $titleLinks): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('blog_nudge')) {
            $title_links_html = \AutoMarketerAI\EmailTemplates::renderTitleLinks($titleLinks);
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('blog_nudge', [
                '{{first_name}}' => esc_html($firstName),
                '{{site_name}}'  => esc_html($siteName),
            ], ['{{title_links}}' => $title_links_html]);
        }
        $fn   = esc_html($firstName);
        $site = esc_html($siteName);
        $rows = '';
        foreach ($titleLinks as $idx => $item) {
            $border_top = $idx > 0 ? 'border-top:1px solid #F0EBE6;' : '';
            $rows .= '<div style="padding:12px 0;' . $border_top . '">'
                . '<a href="' . esc_url((string) ($item['url'] ?? '#')) . '" style="font-size:15px;font-weight:600;color:#D97757;text-decoration:none;line-height:1.5;">' . esc_html((string) ($item['title'] ?? '')) . '</a>'
                . '</div>';
        }
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">BLOG POST DUE</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Time to write a new post, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Pick a title below and we will write the full post, add an image, and optimize everything automatically.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:4px">Choose your topic for ' . $site . '</div>'
            . $rows
            . '</div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">If you&rsquo;d rather skip today, just ignore this email. We&rsquo;ll take care of it in a few hours.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because your blog is scheduled on ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for draft ready email
    // HTML template for draft ready email
    // HTML template for draft ready email
    public static function buildDraftReadyEmailHtml(string $firstName, string $title, string $editUrl, int $post_id = 0): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('blog_draft_ready')) {
            $score_html = '';
            if ($post_id > 0) {
                $analysis = SeoAnalyzer::analyze($post_id);
                $score    = (int) round(((int)($analysis['score_seo'] ?? 0) + (int)($analysis['score_readability'] ?? 0)) / 2);
                $score_html = \AutoMarketerAI\EmailTemplates::renderScoreCard($score);
            }
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('blog_draft_ready', [
                '{{first_name}}' => esc_html($firstName),
                '{{post_title}}' => esc_html($title),
                '{{edit_url}}'   => esc_url($editUrl),
            ], ['{{score_card}}' => $score_html]);
        }
        $fn  = esc_html($firstName);
        $url = esc_url($editUrl);

        // Score block -- only if we have a real post
        $score_block = '';
        if ($post_id > 0) {
            $analysis    = SeoAnalyzer::analyze($post_id);
            $seo         = (int) ($analysis['score_seo']        ?? 0);
            $readability = (int) ($analysis['score_readability'] ?? 0);
            $score       = (int) round(($seo + $readability) / 2);
            if ($score >= 80) {
                $bar_color = '#10B981';
                $label     = 'Looking great';
            } elseif ($score >= 50) {
                $bar_color = '#F59E0B';
                $label     = 'A few things to tidy up';
            } else {
                $bar_color = '#EF4444';
                $label     = 'Could use some attention';
            }
            $bar_pct   = min(100, max(0, $score));
            $bar_empty = 100 - $bar_pct;
            $score_block = '<div style="margin-bottom:28px;">'
                . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Content Score</div>'
                . '<table width="100%" cellpadding="0" cellspacing="0"><tr>'
                . '<td style="font-size:32px;font-weight:700;font-family:Georgia,serif;color:#1a1a1a;width:56px;vertical-align:middle">' . $score . '</td>'
                . '<td style="vertical-align:middle;padding-left:14px">'
                . '<table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:6px"><tr>'
                . '<td style="background:' . $bar_color . ';height:6px;border-radius:3px 0 0 3px;width:' . $bar_pct . '%"></td>'
                . '<td style="background:#E7DDD5;height:6px;border-radius:0 3px 3px 0;width:' . $bar_empty . '%"></td>'
                . '</tr></table>'
                . '<span style="font-size:12px;color:#9E8D8A">' . $label . ' &bull; out of 100</span>'
                . '</td></tr></table>'
                . '</div>';
        }

        $tip_card = '<div style="background:#FAF7F5;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">A quick tip</div>'
            . '<p style="margin:0;font-size:15px;color:#57534E;line-height:1.7">Before you make any changes, hit Auto-Optimize in the editor first. It will clean up most issues in under a minute. Then give it a read and make it your own.</p>'
            . '</div>';

        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">DRAFT READY</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">We wrote one for you, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">You didn&rsquo;t pick a title earlier, so we went ahead and wrote one. It&rsquo;s sitting in your drafts, ready for your eyes.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">Your new draft</div>'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:16px">&ldquo;' . esc_html($title) . '&rdquo;</div>'
            . '<a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:12px 28px;border-radius:4px">Review and approve &rarr;</a>'
            . '</div>'
            . $tip_card
            . $score_block
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Good luck with your post. If you need any help, just reply to this email.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because your blog is scheduled on ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for blog published email -- score + issues

    public static function buildBlogPublishedEmailHtml(string $firstName, string $title, int $post_id): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('blog_published')) {
            $analysis     = SeoAnalyzer::analyze($post_id);
            $score        = (int) round(((int)($analysis['score_seo'] ?? 0) + (int)($analysis['score_readability'] ?? 0)) / 2);
            $all_issues   = (array)($analysis['issues'] ?? []);
            $fixable      = array_slice(array_values(array_filter($all_issues, static fn(array $i): bool => ($i['fix_mode'] ?? '') !== '')), 0, 5);
            $optimize_url = esc_url(add_query_arg(['amai_autooptimize' => '1'], get_edit_post_link($post_id, 'raw')));
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('blog_published', [
                '{{first_name}}' => esc_html($firstName),
                '{{post_title}}' => esc_html($title),
                '{{post_url}}'   => esc_url((string) get_permalink($post_id)),
                '{{edit_url}}'   => esc_url((string) get_edit_post_link($post_id, 'raw')),
            ], [
                '{{score_card}}'    => \AutoMarketerAI\EmailTemplates::renderScoreCard($score),
                '{{optimize_card}}' => \AutoMarketerAI\EmailTemplates::renderOptimizeCard($optimize_url),
                '{{issues_list}}'   => \AutoMarketerAI\EmailTemplates::renderIssuesList($fixable),
            ]);
        }
        $fn          = esc_html($firstName);
        $post_url    = esc_url((string) get_permalink($post_id));
        $edit_url    = esc_url((string) get_edit_post_link($post_id, 'raw'));
        $optimize_url = esc_url(add_query_arg(['amai_autooptimize' => '1'], get_edit_post_link($post_id, 'raw')));

        $analysis    = SeoAnalyzer::analyze($post_id);
        $seo         = (int) ($analysis['score_seo']        ?? 0);
        $readability = (int) ($analysis['score_readability'] ?? 0);
        $score       = (int) round(($seo + $readability) / 2);
        $all_issues  = (array) ($analysis['issues']          ?? []);

        // Plain-English issue messages only -- no jargon, no buttons
        $fixable = array_values(array_filter($all_issues, static fn(array $i): bool => ($i['fix_mode'] ?? '') !== ''));
        $fixable = array_slice($fixable, 0, 5);

        if ($score >= 80) {
            $bar_color = '#10B981';
            $label     = 'Looking great';
        } elseif ($score >= 50) {
            $bar_color = '#F59E0B';
            $label     = 'A few things to tidy up';
        } else {
            $bar_color = '#EF4444';
            $label     = 'Could use some attention';
        }

        $bar_pct   = min(100, max(0, $score));
        $bar_empty = 100 - $bar_pct;

        // Auto-Optimize CTA card
        $optimize_card = '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Let AI clean it up for you.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6;margin-bottom:16px">One click and ' . esc_html(get_bloginfo('name')) . ' will automatically fix the most common issues - titles, descriptions, readability, and more. Most posts are sorted in under a minute.</div>'
            . '<a href="' . $optimize_url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:12px 28px;border-radius:4px">Auto-Optimize this post &rarr;</a>'
            . '</div>';

        // Score card
        $score_card = '<div style="margin-bottom:28px;">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Content Score</div>'
            . '<table width="100%" cellpadding="0" cellspacing="0"><tr>'
            . '<td style="font-size:32px;font-weight:700;font-family:Georgia,serif;color:#1a1a1a;width:56px;vertical-align:middle">' . $score . '</td>'
            . '<td style="vertical-align:middle;padding-left:14px">'
            . '<table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:6px"><tr>'
            . '<td style="background:' . $bar_color . ';height:6px;border-radius:3px 0 0 3px;width:' . $bar_pct . '%"></td>'
            . '<td style="background:#E7DDD5;height:6px;border-radius:0 3px 3px 0;width:' . $bar_empty . '%"></td>'
            . '</tr></table>'
            . '<span style="font-size:12px;color:#9E8D8A">' . $label . ' &bull; out of 100</span>'
            . '</td></tr></table>'
            . '</div>';

        // Issues list -- plain English, no buttons, no jargon
        $issues_html = '';
        if (!empty($fixable)) {
            $issues_html .= '<div style="background:#FAF7F5;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
                . '<div style="font-size:13px;font-weight:600;color:#57534E;margin-bottom:12px">Auto-Optimize will take care of these:</div>';
            foreach ($fixable as $idx => $issue) {
                $msg        = esc_html((string) ($issue['message'] ?? ''));
                $border_top = $idx > 0 ? 'border-top:1px solid #F0EBE6;' : '';
                $issues_html .= '<div style="font-size:13px;color:#78716C;padding:8px 0;' . $border_top . '">&ndash; ' . $msg . '</div>';
            }
            $issues_html .= '</div>';
        }

        // Footer links -- plain text, not buttons
        $cta = '<p style="margin:0 0 28px;font-size:13px;color:#9E8D8A;">'
            . '<a href="' . $post_url . '" style="color:#D97757;text-decoration:none;font-weight:600;" target="_blank">View post</a>'
            . ' &nbsp;&bull;&nbsp; '
            . '<a href="' . $edit_url . '" style="color:#D97757;text-decoration:none;font-weight:600;">Edit post</a>'
            . '</p>';

        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">NEW BLOG POST</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Another one, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">We just published &ldquo;' . esc_html($title) . '&rdquo; for you. Here is how it is looking.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . $optimize_card
            . $score_card
            . $issues_html
            . $cta
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Prefer to handle it yourself? Use the Edit post link above.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because ' . esc_html(get_bloginfo('name')) . ' published a post on your behalf.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for cancellation email
    public static function buildCancellationEmailHtml(string $firstName): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('cancellation')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('cancellation', [
                '{{first_name}}' => esc_html($firstName),
            ]);
        }
        $fn = esc_html($firstName);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">SUBSCRIPTION CANCELLED</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">Your subscription has been cancelled, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Your account has been moved to the free plan.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">Did you know?</div>'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Your data is still here.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6">Your posts, content history, and social connections are all saved. Premium modules have been deactivated on your free plan, but nothing is deleted - if you come back, reactivating them picks up right where you left off.</div>'
            . '</div>'
            . '<p style="margin:0 0 28px;font-size:15px;color:#57534E;line-height:1.7">If this was a mistake or you have any questions, just reply to this email and we&rsquo;ll sort it out.</p>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you had an active subscription at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // HTML template for upgrade email -- any plan to Unlimited AI
    public static function buildUpgradeEmailHtmlUnlimitedAi(string $firstName, string $modulesUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('upgrade_unlimited_ai')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('upgrade_unlimited_ai', [
                '{{first_name}}'  => esc_html($firstName),
                '{{modules_url}}' => esc_url($modulesUrl),
            ]);
        }
        $fn  = esc_html($firstName);
        $url = esc_url($modulesUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">UNLIMITED AI</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">The full arsenal is yours, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Here is what just opened up for you.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">What&rsquo;s now unlocked</div>'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Every module - including the full premium suite.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6">Every regular module plus the full premium suite - AI image generation, analytics, content tools, and automated review responses - all live on your site right now. Every premium module we build in the future is included automatically.</div>'
            . '</div>'
            . '<div style="background:#FAF7F5;border-left:3px solid #D97757;border-radius:4px;padding:14px 18px;margin-bottom:28px">'
            . '<div style="font-size:13px;color:#57534E;line-height:1.6">Not sure where to start? Every module has a <strong>step-by-step walkthrough built right in</strong> - just look for the help link on any module page.</div>'
            . '</div>'
            . '<p style="margin:0 0 28px;font-size:15px;color:#57534E;line-height:1.7">Head to your Modules page to activate everything and get started.</p>'
            . '<div style="text-align:center;margin:0 0 32px"><a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Go to Your Modules &rarr;</a></div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">Questions? Reply to this email and we&rsquo;ll help you out.<br>- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because you upgraded at ' . esc_html(home_url('/')) . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // --------------------------------------------------
    // Render: /privacy
    // --------------------------------------------------
    private static function renderPrivacy(): void
    {
        $content = (string) get_option('amai_legal_privacy', '');
        if ($content === '') {
            $content = '<h1>Privacy Policy</h1><p>Last updated: May 13, 2026</p><h2>Who we are</h2><p>AutoMarketer AI is a social media automation tool for small businesses. We are operated by Ron Seigel. You can reach us at ron@automarketer-ai.com.</p><h2>What we collect and why</h2><p>When you create an account we collect your email address, business name, and website so we can set up your account and personalize the content we generate for you.</p><p>When you subscribe to a paid plan, payments are processed by Stripe. We never see or store your card number.</p><p>When you connect a social media account (Facebook, Instagram, X, TikTok, LinkedIn) we store the access tokens that let us post on your behalf. We only use them to post content you have approved.</p><h2>What we do not do</h2><p>We do not sell your data. We do not share it with advertisers. We do not use it for anything beyond running your account and improving the product.</p><h2>Cookies</h2><p>We use only the cookies WordPress and Stripe require to keep you logged in and process payments. No tracking cookies. No ad pixels.</p><h2>How long we keep your data</h2><p>We keep your account data for as long as your account exists. There is no automatic account deletion - if you stop using a paid plan you drop to the free tier and your account and data stay intact. If you want your data removed entirely, email ron@automarketer-ai.com and we will take care of it. Stripe retains payment records as required by law.</p><h2>Your rights</h2><p>You can ask us to show you what data we hold, correct anything that is wrong, or delete your account entirely. Email ron@automarketer-ai.com and we will sort it out within 5 business days.</p><h2>Security</h2><p>Your data is stored on DigitalOcean servers in Toronto, Canada. All connections are encrypted with TLS. API keys are encrypted at rest. We do not log sensitive data.</p><h2>Changes to this policy</h2><p>If we make a meaningful change we will update the date at the top of this page. If the change affects how we use your data in a significant way, we will email you.</p><h2>Contact</h2><p>AutoMarketer AI &bull; ron@automarketer-ai.com</p>';
            update_option('amai_legal_privacy', $content, false);
        }
        self::htmlOpen('Privacy Policy');
        echo '<main class="amai-main">';
        echo '<div class="amai-container">';
        echo '<div class="amai-legal-page">';
        echo wp_kses_post($content);
        echo '</div>';
        echo '</div>';
        echo '</main>';
        self::htmlClose();
    }

    // --------------------------------------------------
    // Render: /terms
    // --------------------------------------------------
    private static function renderTerms(): void
    {        $content = (string) get_option('amai_legal_terms', '');
        if ($content === '') {
            $content = '<h1>Terms of Service</h1><p>Last updated: May 13, 2026</p><h2>The short version</h2><p>Use AutoMarketer AI to run your business. Do not use it to spam people, break laws, or do anything you would be embarrassed to explain to a judge. We will keep the product running and give you fair warning before making any big changes.</p><h2>Who these terms apply to</h2><p>These terms apply to anyone who uses AutoMarketer AI, including free accounts. By using the product you agree to them.</p><h2>Your account</h2><p>You are responsible for keeping your login credentials secure and for anything that happens under your account. If you think someone has accessed your account without permission, email us immediately at ron@automarketer-ai.com.</p><h2>What you can do</h2><p>You can use AutoMarketer AI to generate, schedule, and post content for your own business. You can connect your own social media accounts. You can drop to the free plan any time - no hoops, no cancellation fees.</p><h2>What you cannot do</h2><p>You cannot use AutoMarketer AI to post spam, harassing content, illegal content, or anything that violates the terms of the social platforms you connect. You cannot resell or sublicense access to the product without a written agreement with us. Agency and reseller arrangements are available - email ron@automarketer-ai.com if that is what you need. You cannot reverse-engineer or attempt to extract the underlying AI models or systems.</p><h2>Content you generate</h2><p>You own the content AutoMarketer AI helps you create. You are responsible for reviewing it before it goes out. We are a tool, not a publisher. If a post causes a problem, that is on you to fix.</p><h2>Payments and refunds</h2><p>Subscriptions are billed monthly or yearly depending on the plan you choose. You can cancel any time and your access continues until the end of the billing period. If you cancel a paid plan, Stripe automatically calculates and applies a prorated credit for any unused time. That credit goes toward your next invoice or is refunded to your original payment method.</p><h2>Uptime and reliability</h2><p>We work hard to keep AutoMarketer AI running smoothly but we cannot guarantee 100% uptime. Scheduled maintenance, platform outages, and things outside our control happen. We will not be liable for missed posts or lost business due to downtime.</p><h2>Termination</h2><p>We can suspend or close an account that is being used to violate these terms. We will give you notice and a chance to fix things unless the violation is serious enough that we cannot.</p><h2>Changes to these terms</h2><p>If we change these terms in a meaningful way we will email you at least 14 days before the change takes effect. Continuing to use the product after that means you accept the new terms.</p><h2>Contact</h2><p>AutoMarketer AI &bull; ron@automarketer-ai.com</p>';
            update_option('amai_legal_terms', $content, false);
        }

        self::htmlOpen('Terms of Service');
        echo '<main class="amai-main">';
        echo '<div class="amai-container">';
        echo '<div class="amai-legal-page">';
        echo wp_kses_post($content);
        echo '</div>';
        echo '</div>';
        echo '</main>';
        self::htmlClose();
    }

    // --------------------------------------------------
    // HTML template for setup nudge email.
    // --------------------------------------------------
    public static function buildSetupNudgeEmailHtml(string $firstName, array $nudge_items, string $dashboardUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('setup_nudge')) {
            $nudge_html = \AutoMarketerAI\EmailTemplates::renderNudgeItems($nudge_items);
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('setup_nudge', [
                '{{first_name}}'    => esc_html($firstName),
                '{{dashboard_url}}' => esc_url($dashboardUrl),
            ], ['{{nudge_items}}' => $nudge_html]);
        }
        $fn   = esc_html($firstName);
        $url  = esc_url($dashboardUrl);
        $rows = '';
        foreach ($nudge_items as $item) {
            $rows .= '<div style="padding:8px 0;border-top:1px solid #F0EBE6;font-size:14px;color:#57534E;line-height:1.6;">' . esc_html($item) . '</div>';
        }
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">ALMOST THERE</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">A few things left to set up, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">You are almost ready to start posting automatically. Here is what is left:</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . $rows
            . '</div>'
            . '<div style="text-align:center;margin:0 0 28px"><a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Pick up where you left off &rarr;</a></div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">- The ' . esc_html((string) get_option('amai_business_name', get_bloginfo('name'))) . ' Team</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name()) . ' &bull; ' . esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email()) . '<br>You&rsquo;re receiving this because your account has pending setup steps.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }

    // --------------------------------------------------
    // HTML template for re-engagement followup email.
    // --------------------------------------------------
    public static function buildReEngagementEmailHtml(string $firstName, string $storeName, string $storeUrl): string
    {
        if (\AutoMarketerAI\EmailTemplates::hasCustom('re_engagement')) {
            return \AutoMarketerAI\EmailTemplates::buildFromCustom('re_engagement', [
                '{{first_name}}'  => esc_html($firstName),
                '{{store_name}}'  => esc_html($storeName),
                '{{store_url}}'   => esc_url($storeUrl),
            ]);
        }
        $fn    = esc_html($firstName);
        $store = esc_html($storeName);
        $url   = esc_url($storeUrl);
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head><body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:48px 48px 32px;border-bottom:1px solid #F0EBE6">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">STILL INTERESTED?</div>'
            . '<h1 style="margin:0 0 12px;font-family:Georgia,serif;font-size:36px;font-weight:400;color:#1a1a1a;line-height:1.2">You left a few things behind, ' . $fn . '.</h1>'
            . '<p style="margin:0;font-size:16px;color:#6B6260;line-height:1.6">Still thinking it over? The items you were browsing are waiting for you.</p>'
            . '</div>'
            . '</td></tr></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:8px">Your items</div>'
            . '<div style="font-size:14px;color:#57534E;line-height:1.6;">Visit your cart to pick up where you left off at <a href="' . $url . '" style="color:#D97757;text-decoration:none;">' . $store . '</a>.</div>'
            . '</div>'
            . '<div style="text-align:center;margin:0 0 28px"><a href="' . $url . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Return to shop &rarr;</a></div>'
            . '<div style="height:1px;background:#F0EBE6;margin:0 0 28px"></div>'
            . '<p style="margin:0;font-size:13px;color:#9E8D8A;line-height:1.6">- The team at ' . $store . '</p>'
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">You are receiving this because you recently visited ' . $store . '.</p>'
            . '</td></tr></table></table></td></tr></table></body></html>';
    }
}