<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/partials/nudge-card.php
// Description: Profile completion nudge card partial - renders the active nudge - NUCLEAR+++
// Last Edited: 2026-04-29
// ==================================================

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

// $nudge_key must be set by the including template
if (!isset($nudge_key) || !is_string($nudge_key) || $nudge_key === '') {
    return;
}

$nonce = wp_create_nonce('amai_nudge_actions');

$nudge_config = [
    'profile' => [
        'eyebrow'    => 'Step 1 of 4',
        'title'      => 'Tell us about your business',
        'body'       => 'The more we know about what you do and what makes you different, the better your posts will sound. It takes about two minutes - or let AI do the heavy lifting.',
        'cta_label'  => 'Set up my profile',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-setup'),
        'has_rewrite' => true,
        'has_snooze'  => false,
    ],
    'ai_copy' => [
        'eyebrow'    => 'Step 2 of 4',
        'title'      => 'Pick your AI writer',
        'body'       => 'Your AI provider is what writes your posts. Connect it with your own API key - you stay in control of your data and costs. Not sure which to pick? Start with Claude.',
        'cta_label'  => 'Choose an AI provider',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-modules'),
        'has_rewrite' => false,
        'has_snooze'  => false,
    ],
    'ai_image' => [
        'eyebrow'    => 'Step 3 of 4',
        'title'      => 'Add an image provider',
        'body'       => 'Posts with images get more attention. Connect an image provider and your posts will come with visuals picked to match your content - automatically.',
        'cta_label'  => 'Add image provider',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-modules'),
        'has_rewrite' => false,
        'has_snooze'  => true,
    ],
    'channel' => [
        'eyebrow'    => 'Step 4 of 4',
        'title'      => 'Connect your first channel',
        'body'       => 'Connect Facebook or Instagram and your first week of posts will be generated and ready to review. It is the last step - you are almost there.',
        'cta_label'  => 'Connect a channel',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-social&channel=facebook'),
        'has_rewrite' => false,
        'has_snooze'  => false,
    ],
    'comments' => [
        'eyebrow'    => 'Action needed',
        'title'      => 'You have comments waiting for a reply',
        'body'       => 'People are engaging with your posts. Head to your comment inbox and keep the conversation going - it builds trust and keeps your audience coming back.',
        'cta_label'  => 'Open comment inbox',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-comments'),
        'has_rewrite' => false,
        'has_snooze'  => true,
    ],
    'legal' => [
        'eyebrow'    => 'Quick setup',
        'title'      => 'Add your privacy policy and terms',
        'body'       => 'Your site needs a privacy policy and terms of service. You can paste in URLs if you already have them elsewhere, or use the built-in editor to write them here.',
        'cta_label'  => 'Set up legal pages',
        'cta_url'    => admin_url('admin.php?page=automarketer-ai-settings#amai-legal-section'),
        'has_rewrite' => false,
        'has_snooze'  => false,
    ],
];

$config = $nudge_config[$nudge_key] ?? null;

if ($config === null) {
    return;
}
?>
<div class="amai-nudge-card" id="amai-nudge-card" data-nudge-key="<?php echo esc_attr($nudge_key); ?>">
    <div class="amai-nudge-inner">
        <div class="amai-nudge-eyebrow"><?php echo esc_html($config['eyebrow']); ?></div>
        <div class="amai-nudge-title"><?php echo esc_html($config['title']); ?></div>
        <p class="amai-nudge-body"><?php echo esc_html($config['body']); ?></p>
        <div class="amai-nudge-actions">
            <?php if (!isset($nudge_context) || $nudge_context !== 'modules'): ?>
            <a href="<?php echo esc_url($config['cta_url']); ?>" class="amai-nudge-btn-primary">
                <?php echo esc_html($config['cta_label']); ?> &rarr;
            </a>
            <?php endif; ?>
            <?php if ($config['has_rewrite']): ?>
                <button
                    type="button"
                    class="amai-nudge-btn-secondary"
                    id="amai-nudge-rewrite-btn"
                    data-nonce="<?php echo esc_attr($nonce); ?>"
                >
                    Spruce it up with AI
                </button>
            <?php endif; ?>
            <?php if ($config['has_snooze']): ?>
                <button
                    type="button"
                    class="amai-nudge-btn-ghost"
                    id="amai-nudge-snooze-btn"
                    data-nonce="<?php echo esc_attr($nonce); ?>"
                    data-nudge-key="<?php echo esc_attr($nudge_key); ?>"
                >
                    Remind me in a week
                </button>
            <?php endif; ?>
            <button
                type="button"
                class="amai-nudge-btn-dismiss"
                id="amai-nudge-dismiss-btn"
                data-nonce="<?php echo esc_attr($nonce); ?>"
                data-nudge-key="<?php echo esc_attr($nudge_key); ?>"
            >
                Don't show this again
            </button>
        </div>
        <div class="amai-nudge-rewrite-result" id="amai-nudge-rewrite-result" style="display:none;">
            <div class="amai-nudge-rewrite-label">Here is what your AI wrote:</div>
            <div class="amai-nudge-rewrite-text" id="amai-nudge-rewrite-text"></div>
            <div class="amai-nudge-rewrite-btns">
                <button type="button" class="amai-nudge-btn-primary" id="amai-nudge-rewrite-accept">Use this</button>
                <button type="button" class="amai-nudge-btn-ghost" id="amai-nudge-rewrite-retry">Try again</button>
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-setup')); ?>" class="amai-nudge-btn-ghost">Edit it myself</a>
            </div>
        </div>
        <div class="amai-nudge-progress">
            <?php foreach (['profile', 'ai_copy', 'ai_image', 'channel'] as $i => $k): ?>
                <span class="amai-nudge-dot <?php echo $k === $nudge_key ? 'is-active' : (array_search($k, ['profile', 'ai_copy', 'ai_image', 'channel'], true) < array_search($nudge_key, ['profile', 'ai_copy', 'ai_image', 'channel'], true) ? 'is-done' : ''); ?>"></span>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<script>
(function() {
    var ajaxUrl = window.ajaxurl || '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';

    // Snooze
    var snoozeBtn = document.getElementById('amai-nudge-snooze-btn');
    if (snoozeBtn) {
        snoozeBtn.addEventListener('click', function() {
            var btn   = this;
            var nonce = btn.dataset.nonce;
            var key   = btn.dataset.nudgeKey;
            btn.disabled = true;
            btn.textContent = 'Snoozing...';
            var fd = new FormData();
            fd.append('action', 'amai_nudge_snooze');
            fd.append('nudge_key', key);
            fd.append('_ajax_nonce', nonce);
            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        var card = document.getElementById('amai-nudge-card');
                        if (card) {
                            card.style.transition = 'opacity 0.3s';
                            card.style.opacity = '0';
                            setTimeout(function() { card.remove(); }, 320);
                        }
                    } else {
                        btn.disabled = false;
                        btn.textContent = 'Remind me in a week';
                    }
                })
                .catch(function() {
                    btn.disabled = false;
                    btn.textContent = 'Remind me in a week';
                });
        });
    }

    // Dismiss
    var dismissBtn = document.getElementById('amai-nudge-dismiss-btn');
    if (dismissBtn) {
        dismissBtn.addEventListener('click', function() {
            var btn   = this;
            var nonce = btn.dataset.nonce;
            var key   = btn.dataset.nudgeKey;
            btn.disabled = true;
            btn.textContent = 'Dismissing...';
            var fd = new FormData();
            fd.append('action', 'amai_nudge_dismiss');
            fd.append('nudge_key', key);
            fd.append('_ajax_nonce', nonce);
            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        var card = document.getElementById('amai-nudge-card');
                        if (card) {
                            card.style.transition = 'opacity 0.3s';
                            card.style.opacity = '0';
                            setTimeout(function() { card.remove(); }, 320);
                        }
                    } else {
                        btn.disabled = false;
                        btn.textContent = "Don't show this again";
                    }
                })
                .catch(function() {
                    btn.disabled = false;
                    btn.textContent = "Don't show this again";
                });
        });
    }

    // AI rewrite
    var rewriteBtn = document.getElementById('amai-nudge-rewrite-btn');
    if (rewriteBtn) {
        function runRewrite() {
            var nonce       = rewriteBtn.dataset.nonce;
            var resultBox   = document.getElementById('amai-nudge-rewrite-result');
            var resultText  = document.getElementById('amai-nudge-rewrite-text');
            rewriteBtn.disabled    = true;
            rewriteBtn.textContent = 'Writing...';
            var fd = new FormData();
            fd.append('action', 'amai_nudge_profile_rewrite');
            fd.append('_ajax_nonce', nonce);
            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    rewriteBtn.disabled    = false;
                    rewriteBtn.textContent = 'Spruce it up with AI';
                    if (data.success && data.data && data.data.differentiator) {
                        resultText.textContent = data.data.differentiator;
                        resultBox.style.display = 'block';
                    } else {
                        var msg = (data.data && data.data.message) ? data.data.message : 'Something went wrong. Try again.';
                        alert(msg);
                    }
                })
                .catch(function() {
                    rewriteBtn.disabled    = false;
                    rewriteBtn.textContent = 'Spruce it up with AI';
                    alert('Connection error. Please try again.');
                });
        }

        rewriteBtn.addEventListener('click', runRewrite);

        var retryBtn = document.getElementById('amai-nudge-rewrite-retry');
        if (retryBtn) {
            retryBtn.addEventListener('click', runRewrite);
        }

        var acceptBtn = document.getElementById('amai-nudge-rewrite-accept');
        if (acceptBtn) {
            acceptBtn.addEventListener('click', function() {
                var card = document.getElementById('amai-nudge-card');
                if (card) {
                    card.style.transition = 'opacity 0.3s';
                    card.style.opacity = '0';
                    setTimeout(function() { card.remove(); }, 320);
                }
            });
        }
    }
})();
</script>