<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/templates/cluster-builder.php
// Description: Content Cluster Builder tab template - NUCLEAR+++
// Last Edited: 2026-05-18
// ==================================================
namespace AutoMarketerAI;

defined('ABSPATH') || exit;
?>
<div class="amai-cluster-wrap">

    <div class="amai-cluster-intro">
        <div class="amai-cluster-intro-text">
            <h2 class="amai-cluster-heading">Content Cluster Builder</h2>
            <p class="amai-cluster-subtext">Build topical authority automatically. Enter a topic and we'll generate a comprehensive pillar post plus 5 supporting posts, all internally linked and scheduled across your Tue/Thu/Sat slots.</p>
        </div>
        <div class="amai-cluster-mode-badge">
            <span class="amai-cluster-mode-dot <?php echo esc_attr($approval_mode); ?>"></span>
            <?php echo esc_html($mode_label); ?>
        </div>
    </div>

    <?php if ($has_active) : ?>
    <div class="amai-cluster-notice amai-cluster-notice--warn">
        A cluster is currently being generated. The form will unlock when it completes.
    </div>
    <?php endif; ?>

    <div class="amai-cluster-card amai-cluster-generate-card">
        <div class="amai-cluster-card-header">
            <span class="amai-cluster-eyebrow">New Cluster</span>
            <h3 class="amai-cluster-card-title">What topic should we build authority around?</h3>
            <p class="amai-cluster-card-sub">Be specific. "Email marketing for restaurants" outperforms "email marketing" every time.</p>
        </div>
        <div class="amai-cluster-form">
            <input
                type="text"
                id="amai-cluster-topic"
                class="amai-cluster-topic-input"
                placeholder="e.g. Email marketing for small restaurants"
                maxlength="200"
                <?php echo $has_active ? 'disabled' : ''; ?>
            >
            <button
                type="button"
                id="amai-cluster-generate-btn"
                class="amai-cluster-btn-primary"
                <?php echo $has_active ? 'disabled' : ''; ?>
                data-nonce="<?php echo esc_attr($nonce); ?>"
            >
                <?php echo $has_active ? 'Generating...' : 'Generate Cluster'; ?>
            </button>
        </div>
        <div id="amai-cluster-feedback" class="amai-cluster-feedback" style="display:none;"></div>
        <div class="amai-cluster-what">
            <span class="amai-cluster-what-label">What you get:</span>
            <span class="amai-cluster-what-item">1 pillar post</span>
            <span class="amai-cluster-what-sep">+</span>
            <span class="amai-cluster-what-item">5 supporting posts</span>
            <span class="amai-cluster-what-sep">+</span>
            <span class="amai-cluster-what-item">Automatic internal linking</span>
            <span class="amai-cluster-what-sep">+</span>
            <span class="amai-cluster-what-item">Tue/Thu/Sat scheduling</span>
        </div>
    </div>

    <?php if (!empty($recent)) : ?>
    <div class="amai-cluster-history">
        <h3 class="amai-cluster-history-title">Recent Clusters</h3>
        <?php foreach ($recent as $cl) :
            $cl_status      = (string) ($cl['status'] ?? 'pending');
            $cl_topic       = (string) ($cl['topic'] ?? '');
            $cl_posts       = is_array($cl['posts'] ?? null) ? $cl['posts'] : [];
            $cl_created     = (string) ($cl['created_at'] ?? '');
            $cl_post_count  = (int) ($cl['post_count'] ?? 0);
            $cl_pub_count   = (int) ($cl['published_count'] ?? 0);
            $cl_draft_count = $cl_post_count - $cl_pub_count;
            $pillar         = null;
            $supporting     = [];
            foreach ($cl_posts as $cp) {
                if ($cp['post_role'] === 'pillar') {
                    $pillar = $cp;
                } else {
                    $supporting[] = $cp;
                }
            }
        ?>
        <div class="amai-cluster-history-card" data-cluster-id="<?php echo (int) $cl['id']; ?>">
            <div class="amai-cluster-history-head">
                <div class="amai-cluster-history-meta">
                    <span class="amai-cluster-status-pill amai-cluster-status-pill--<?php echo esc_attr($cl_status); ?>">
                        <?php echo esc_html(ucfirst($cl_status)); ?>
                    </span>
                    <span class="amai-cluster-history-topic"><?php echo esc_html($cl_topic); ?></span>
                </div>
                <div class="amai-cluster-history-stats">
                    <?php if ($cl_post_count > 0) : ?>
                    <span class="amai-cluster-stat">
                        <strong><?php echo $cl_post_count; ?></strong> posts
                    </span>
                    <?php if ($cl_pub_count > 0) : ?>
                    <span class="amai-cluster-stat amai-cluster-stat--pub">
                        <?php echo $cl_pub_count; ?> published
                    </span>
                    <?php endif; ?>
                    <?php if ($cl_draft_count > 0) : ?>
                    <span class="amai-cluster-stat amai-cluster-stat--draft">
                        <?php echo $cl_draft_count; ?> draft
                    </span>
                    <?php endif; ?>
                    <?php endif; ?>
                    <span class="amai-cluster-history-date"><?php echo esc_html(gmdate('M j, Y', strtotime($cl_created))); ?></span>
                </div>
            </div>

            <?php if ($pillar !== null) : ?>
            <div class="amai-cluster-pillar-row">
                <span class="amai-cluster-role-badge amai-cluster-role-badge--pillar">Pillar</span>
                <span class="amai-cluster-post-title">
                    <?php if ($pillar['edit_url'] !== '') : ?>
                    <a href="<?php echo esc_url($pillar['edit_url']); ?>" target="_blank"><?php echo esc_html($pillar['title']); ?></a>
                    <?php else : ?>
                    <?php echo esc_html($pillar['title']); ?>
                    <?php endif; ?>
                </span>
                <span class="amai-cluster-post-date"><?php echo esc_html(gmdate('M j', strtotime($pillar['slot_date']))); ?></span>
                <span class="amai-cluster-post-status amai-cluster-post-status--<?php echo esc_attr($pillar['wp_status']); ?>">
                    <?php echo esc_html(ucfirst($pillar['wp_status'])); ?>
                </span>
            </div>
            <?php endif; ?>

            <?php if (!empty($supporting)) : ?>
            <div class="amai-cluster-supporting-list">
                <?php foreach ($supporting as $sp) : ?>
                <div class="amai-cluster-supporting-row">
                    <span class="amai-cluster-role-badge amai-cluster-role-badge--supporting">Supporting</span>
                    <span class="amai-cluster-post-title">
                        <?php if ($sp['edit_url'] !== '') : ?>
                        <a href="<?php echo esc_url($sp['edit_url']); ?>" target="_blank"><?php echo esc_html($sp['title']); ?></a>
                        <?php else : ?>
                        <?php echo esc_html($sp['title']); ?>
                        <?php endif; ?>
                    </span>
                    <span class="amai-cluster-post-date"><?php echo esc_html(gmdate('M j', strtotime($sp['slot_date']))); ?></span>
                    <span class="amai-cluster-post-status amai-cluster-post-status--<?php echo esc_attr($sp['wp_status']); ?>">
                        <?php echo esc_html(ucfirst($sp['wp_status'])); ?>
                    </span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if (empty($cl_posts) && $cl_status === 'pending') : ?>
            <div class="amai-cluster-generating-indicator">
                <span class="amai-cluster-spinner"></span> Generating posts...
            </div>
            <?php endif; ?>

        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</div>

<script>
(function() {
    var btn   = document.getElementById('amai-cluster-generate-btn');
    var input = document.getElementById('amai-cluster-topic');
    var fb    = document.getElementById('amai-cluster-feedback');
    if (!btn || !input || !fb) { return; }

    btn.addEventListener('click', function() {
        var topic = input.value.trim();
        if (topic === '') {
            fb.textContent = 'Please enter a topic before generating.';
            fb.className   = 'amai-cluster-feedback amai-cluster-feedback--error';
            fb.style.display = 'block';
            return;
        }

        btn.disabled    = true;
        btn.textContent = 'Starting...';
        fb.style.display = 'none';

        var data = new FormData();
        data.append('action', 'amai_generate_cluster');
        data.append('nonce',  btn.dataset.nonce);
        data.append('topic',  topic);

        fetch(ajaxurl, { method: 'POST', body: data })
            .then(function(r) { return r.json(); })
            .then(function(json) {
                if (json.success) {
                    fb.textContent   = json.data.message;
                    fb.className     = 'amai-cluster-feedback amai-cluster-feedback--success';
                    fb.style.display = 'block';
                    btn.textContent  = 'Generating...';
                    input.disabled   = true;
                    // Reload after 4 seconds to show the new cluster card
                    setTimeout(function() { window.location.reload(); }, 4000);
                } else {
                    fb.textContent   = json.data.message || 'Generation failed. Please try again.';
                    fb.className     = 'amai-cluster-feedback amai-cluster-feedback--error';
                    fb.style.display = 'block';
                    btn.disabled     = false;
                    btn.textContent  = 'Generate Cluster';
                }
            })
            .catch(function() {
                fb.textContent   = 'Request failed. Please try again.';
                fb.className     = 'amai-cluster-feedback amai-cluster-feedback--error';
                fb.style.display = 'block';
                btn.disabled     = false;
                btn.textContent  = 'Generate Cluster';
            });
    });
}());
</script>