<?php
/**
 * Kantan — "Ask the agent" prompt affordance (shared across Analytics + SEO)
 *
 * A reusable icon button + modal that surfaces a few copy-paste, data-specific
 * agent prompts for any dashboard block. Lives in the base (Analytics) plugin so
 * both plugins can use it; Kantan SEO registers its prompt sets via the
 * `kantan_ai_prompt_sets` filter.
 *
 * Drop onto a block's header:
 *   <div class="flex items-center justify-between mb-6">
 *       <h2 ...>Block title</h2>
 *       <?php kantan_ai_prompts('analytics-overview-referrers'); ?>
 *   </div>
 *
 * Prompt sets are keyed by id and registered centrally (below + the filter), so
 * the per-block markup is a one-liner and all prompt copy lives in one place.
 *
 * @package Kantan_Analytics
 */

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

/**
 * All registered prompt sets, keyed by block id. Each set:
 *   array( 'title' => string, 'intro' => string,
 *          'agent' => 'analytics'|'seo',
 *          'prompts' => array( array('label' => string, 'prompt' => string), ... ) )
 *
 * @return array
 */
function kantan_ai_prompt_sets() {
    $sets = array(

        // ——— Analytics → Overview ———
        'analytics-overview-referrers' => array(
            'title' => __( 'Ask the agent about your referrers', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Group & qualify my referrers', 'kantan-analytics' ), 'prompt' => __( 'Group my referrers into themes (search, social, AI assistants, partner/link sites, email), tell me which send engaged versus bouncing traffic, and where the conversions come from.', 'kantan-analytics' )),
                array('label' => __( 'Follow the visitors from one referrer', 'kantan-analytics' ), 'prompt' => __( 'For my top referring domain, list the visitors who came from it and trace each journey — entry page, the path they took, and where they dropped off or converted.', 'kantan-analytics' )),
                array('label' => __( 'Find a referrer worth pursuing', 'kantan-analytics' ), 'prompt' => __( 'Which referrers punch above their weight (low volume but high engagement or conversions)? Name the 2-3 worth investing in and how to get more from each.', 'kantan-analytics' )),
            ),
        ),
        'analytics-overview-traffic-sources' => array(
            'title' => __( 'Ask the agent about your traffic sources', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Where should I focus?', 'kantan-analytics' ), 'prompt' => __( 'Break my traffic down by source, show which sources actually convert (not just which bring volume), and recommend where to invest next month.', 'kantan-analytics' )),
                array('label' => __( 'Am I over-dependent on one source?', 'kantan-analytics' ), 'prompt' => __( 'Is my traffic over-concentrated in a single source? Quantify the risk and suggest concrete ways to diversify.', 'kantan-analytics' )),
                array('label' => __( 'AI-assistant traffic trend', 'kantan-analytics' ), 'prompt' => __( 'Track my AI-assistant traffic over time, tell me which pages those visitors land on, and whether they engage or convert.', 'kantan-analytics' )),
            ),
        ),
        'analytics-overview-pages' => array(
            'title' => __( 'Ask the agent about your pages', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Best & worst content', 'kantan-analytics' ), 'prompt' => __( 'Rank my pages by engaged traffic and conversions, and flag the high-traffic pages that underperform on engagement so I know what to fix first.', 'kantan-analytics' )),
                array('label' => __( 'Quick wins', 'kantan-analytics' ), 'prompt' => __( 'Find my highest-traffic, lowest-engagement pages and give me specific, practical fixes to improve each one.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → Journeys ———
        'analytics-journeys-profiles' => array(
            'title' => __( 'Ask the agent about visitor journeys', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Common paths to conversion', 'kantan-analytics' ), 'prompt' => __( 'From my visitor journeys, show the most common paths that end in a conversion and the most common drop-off points before one.', 'kantan-analytics' )),
                array('label' => __( 'Profile my engaged visitors', 'kantan-analytics' ), 'prompt' => __( 'Profile my most engaged visitors — where they come from, what they read, and what they do — and tell me how to attract more like them.', 'kantan-analytics' )),
            ),
        ),
        'analytics-journeys-transitions' => array(
            'title' => __( 'Ask the agent about page flow', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Fix the leaky steps', 'kantan-analytics' ), 'prompt' => __( 'Show the page-to-page transitions where I lose the most people, and suggest internal links or CTAs to keep them moving toward a conversion.', 'kantan-analytics' )),
            ),
        ),
        'analytics-journeys-entryexit' => array(
            'title' => __( 'Ask the agent about entry & exit pages', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Entry & exit insight', 'kantan-analytics' ), 'prompt' => __( 'Tell me which entry pages start the best journeys and which exit pages are leaking visitors who looked likely to convert.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → Interactions ———
        'analytics-interactions-clicks' => array(
            'title' => __( 'Ask the agent about on-page interactions', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'What are people clicking?', 'kantan-analytics' ), 'prompt' => __( 'From my click data, tell me what visitors engage with most, what they ignore, and where I should add or move CTAs.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → Conversions ———
        'analytics-conversions' => array(
            'title' => __( 'Ask the agent about conversions', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'What drives conversions?', 'kantan-analytics' ), 'prompt' => __( 'Break my conversions down by type and traffic source, tell me which channels convert best, and where to focus to get more.', 'kantan-analytics' )),
                array('label' => __( 'Reduce conversion friction', 'kantan-analytics' ), 'prompt' => __( 'Trace how my converting visitors arrive and what they do right before converting, then suggest how to remove friction for everyone else.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → User Data ———
        'analytics-devices' => array(
            'title' => __( 'Ask the agent about devices', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Device experience gaps', 'kantan-analytics' ), 'prompt' => __( 'Compare engagement, duration, and bounce by device, flag any device where my site underperforms, and suggest likely causes.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → Realtime ———
        'analytics-realtime' => array(
            'title' => __( 'Ask the agent about live visitors', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( "Who's on my site now?", 'kantan-analytics' ), 'prompt' => __( 'Summarize my current live visitors — where they came from and what they are looking at — and flag anything notable about the moment.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → Video ———
        'analytics-video' => array(
            'title' => __( 'Ask the agent about video', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Which videos hold attention?', 'kantan-analytics' ), 'prompt' => __( 'Audit my video engagement: which videos actually get played, which hold attention to the end, and where do viewers drop off? Use plays, play-rate, completion rate and the per-video drop-off curve, and tell me which to trim, cut, or feature.', 'kantan-analytics' )),
                array('label' => __( 'Does video drive conversions?', 'kantan-analytics' ), 'prompt' => __( 'Compare pages that have video against pages that do not: do videos lift engagement and conversions, and which specific videos earn their place? Recommend where to add, keep, or remove video.', 'kantan-analytics' )),
            ),
        ),

        // ——— Analytics → AI Crawlers ———
        'analytics-crawlers' => array(
            'title' => __( 'Ask the agent about AI crawlers', 'kantan-analytics' ),
            'agent' => 'analytics',
            'prompts' => array(
                array('label' => __( 'Who is crawling my site?', 'kantan-analytics' ), 'prompt' => __( 'Summarize my AI-crawler activity: which AI bots hit my site, how often, how many pages each reaches, and the split between live fetches and training crawls. Flag any crawler I might want to allow or block.', 'kantan-analytics' )),
                array('label' => __( 'Crawled vs. cited', 'kantan-analytics' ), 'prompt' => __( 'Cross-reference the AI crawlers hitting my site with my AI-assistant referral traffic — are the assistants that crawl me actually sending visitors, and which pages should I make easier to cite?', 'kantan-analytics' )),
            ),
        ),
    );

    /**
     * Lets Kantan SEO (and anything else) register additional prompt sets.
     *
     * @param array $sets id => set config
     */
    return apply_filters('kantan_ai_prompt_sets', $sets);
}

/**
 * Render the "Ask the agent" icon button + modal for a registered block id.
 *
 * @param string $id Block id present in kantan_ai_prompt_sets().
 */
function kantan_ai_prompts($id) {
    $id   = sanitize_html_class($id);
    $sets = kantan_ai_prompt_sets();
    if (empty($sets[$id]) || empty($sets[$id]['prompts'])) {
        return;
    }
    $set     = $sets[$id];
    $title   = isset($set['title']) ? $set['title'] : __( 'Ask the agent', 'kantan-analytics' );
    $agent      = isset($set['agent']) && $set['agent'] === 'seo' ? 'seo' : 'analytics';
    $agent_name = $agent === 'seo' ? 'kantan-seo-agent' : 'kantan-analytics-agent';
    $prompts    = $set['prompts'];

    $footer = $agent === 'seo'
        ? __( 'Each copied prompt invokes your <strong>kantan-seo-agent</strong> — paste it into Claude Code, Gemini CLI, or any AI tool that supports agents. Don\'t have the agent yet? Download it under <strong>SEO → Settings</strong>.', 'kantan-analytics' )
        : __( 'Each copied prompt invokes your <strong>kantan-analytics-agent</strong> — paste it into Claude Code, Gemini CLI, or any AI tool that supports agents. Don\'t have the agent yet? Download it under <strong>Settings</strong>.', 'kantan-analytics' );
    ?>
    <button type="button" data-ai-open="<?php echo esc_attr($id); ?>"
            class="inline-flex items-center justify-center w-9 h-9 rounded-lg text-gray-400 hover:text-purple-600 hover:bg-purple-50 transition shrink-0"
            title="<?php esc_attr_e( 'Ask the agent about this data', 'kantan-analytics' ); ?>" aria-label="<?php esc_attr_e( 'Ask the agent about this data', 'kantan-analytics' ); ?>">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 3l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3zM6 17v4m-2-2h4M5 3v3M3.5 4.5h3"/></svg>
    </button>

    <div id="kantan-ai-modal-<?php echo esc_attr($id); ?>" data-ai-agent="<?php echo esc_attr($agent_name); ?>" class="kantan-ai-modal hidden fixed inset-0 z-[2147483547] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-black/60" data-ai-close></div>
        <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-start gap-3 px-6 pt-6 pb-4 border-b border-gray-100">
                <h3 class="text-lg font-semibold text-gray-900 flex items-center gap-2">
                    <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 3l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"/></svg>
                    <?php echo esc_html($title); ?>
                </h3>
                <button type="button" data-ai-close class="shrink-0 text-gray-400 hover:text-gray-700 text-2xl leading-none p-1" aria-label="<?php esc_attr_e( 'Close', 'kantan-analytics' ); ?>">&times;</button>
            </div>
            <div class="overflow-auto px-6 py-4 space-y-3">
                <?php foreach ($prompts as $p) : ?>
                    <div class="kantan-ai-row border border-gray-200 rounded-lg p-3 hover:border-purple-300 transition">
                        <div class="flex justify-between items-center gap-3 mb-1.5">
                            <p class="text-sm font-medium text-gray-800"><?php echo esc_html($p['label']); ?></p>
                            <button type="button" data-ai-copy class="shrink-0 text-xs font-medium text-purple-700 hover:text-purple-900"><?php esc_html_e( 'Copy', 'kantan-analytics' ); ?></button>
                        </div>
                        <p data-ai-prompt class="text-sm text-gray-600 leading-relaxed"><?php echo esc_html($p['prompt']); ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="px-6 py-3 border-t border-gray-100 text-xs text-gray-500"><?php echo wp_kses_post($footer); ?></div>
        </div>
    </div>
    <?php
    kantan_ai_prompts_assets();
}

/**
 * Output the shared modal JS once. Event-delegated, so it covers every instance.
 */
function kantan_ai_prompts_assets() {
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    // Enqueue the modal handler as a file (no inline <script>). Called during
    // admin render, before footer scripts print, so the footer enqueue lands.
    wp_enqueue_script(
        'kantan-ai-prompts',
        KANTAN_ANALYTICS_PLUGIN_URL . 'assets/js/ai-prompts.js',
        array(),
        KANTAN_ANALYTICS_VERSION,
        true
    );
    // Translatable strings used by the modal JS (static file, so pass them in).
    wp_localize_script('kantan-ai-prompts', 'kantanAiL10n', array(
        'copied' => __('Copied!', 'kantan-analytics'),
    ));
}
