<?php
/**
 * Video Tab
 *
 * Surfaces the engagement data video-analytics.php collects for embedded
 * YouTube / Vimeo / self-hosted videos: plays, play rate, average watch time,
 * completion rate, per-video list.
 *
 * The retention/drop-off curve, rewatch heatmap, and conversion attribution
 * are the paid Kantan SEO layer (mirroring the Conversions split) — the free
 * tab shows a locked teaser in their place. The underlying engagement buckets
 * accrue here regardless, so the curves have history the moment SEO activates.
 */

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

/**
 * Register the Video tab, inserted just before Settings in the Analytics
 * group. Priority 6 — after Conversions (5), before companion-plugin tabs.
 */
function kantan_register_video_tab($tabs) {
    $entry = array(
        'video' => array(
            'label' => __('Video', 'kantan-analytics'),
            'group' => __('Analytics', 'kantan-analytics'),
            'icon'  => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>',
        ),
    );

    $pos = array_search('settings', array_keys($tabs), true);
    if ($pos === false) {
        return $tabs + $entry;
    }
    return array_slice($tabs, 0, $pos, true) + $entry + array_slice($tabs, $pos, null, true);
}
add_filter('kantan_analytics_dashboard_tabs', 'kantan_register_video_tab', 6);

/**
 * Render the Video tab body. Hooked to the dashboard's companion-tab render
 * action; bails for any other tab.
 */
function kantan_render_video_tab($tab, $days) {
    if ($tab !== 'video') {
        return;
    }

    $days = max(1, intval($days));

    $totals     = kantan_get_video_totals($days);
    $video_rows = kantan_get_video_rows($days);
    $settings   = kantan_video_get_settings();

    // Upsell visibility: only when SEO isn't already installed.
    $show_seo_upsell = !defined('KANTAN_SEO_VERSION');
    // Promotional intensity: full everywhere except the wp.org build.
    $channel = defined('KANTAN_ANALYTICS_CHANNEL') ? KANTAN_ANALYTICS_CHANNEL : 'trykantan';
    $upsell_full = ($channel !== 'wporg');

    include KANTAN_ANALYTICS_PLUGIN_DIR . 'templates/video-tab.php';
}
add_action('kantan_analytics_render_tab', 'kantan_render_video_tab', 10, 2);
