<?php
/**
 * Video tab body.
 *
 * Rendered via kantan_render_video_tab(). Available vars:
 *   $days, $totals (array: videos, impressions, plays, completes,
 *   watch_seconds, play_rate, completion_rate, avg_watch),
 *   $video_rows (objects: video_key, provider, video_title, duration,
 *   impressions, plays, completes, watch_seconds, last_seen),
 *   $settings (video settings array),
 *   $show_seo_upsell (bool), $upsell_full (bool)
 */
if (!defined('ABSPATH')) {
    exit;
}

// Provider presentation.
$provider_meta = array(
    'youtube' => array('label' => 'YouTube', 'pill' => 'bg-red-100 text-red-800'),
    'vimeo'   => array('label' => 'Vimeo',   'pill' => 'bg-cyan-100 text-cyan-800'),
    'html5'   => array('label' => __('Self-hosted', 'kantan-analytics'), 'pill' => 'bg-gray-100 text-gray-700'),
);

// m:ss / h:mm:ss formatter for watch times.
$kantan_video_fmt_time = function ($seconds) {
    $seconds = max(0, intval($seconds));
    if ($seconds >= 3600) {
        return sprintf('%d:%02d:%02d', floor($seconds / 3600), floor(($seconds % 3600) / 60), $seconds % 60);
    }
    return sprintf('%d:%02d', floor($seconds / 60), $seconds % 60);
};
?>

<!-- ==================== VIDEO TAB ==================== -->

<div class="flex justify-between items-center mb-6">
    <h1 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Video', 'kantan-analytics'); ?></h1>
    <?php /* translators: %d: number of days in the reporting period */ ?>
    <span class="text-sm text-gray-400"><?php printf(esc_html__('Last %d days', 'kantan-analytics'), (int) $days); ?></span>
</div>

<?php if (!$settings['enabled']): ?>

    <div class="bg-amber-50 border border-amber-200 rounded-xl p-4 mb-8 text-sm text-amber-800">
        <?php esc_html_e('Video tracking is currently turned off. Enable it in Settings to start measuring engagement for embedded videos.', 'kantan-analytics'); ?>
    </div>

<?php endif; ?>

<?php if ($totals['impressions'] <= 0): ?>

    <!-- Empty state -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <div class="text-center py-10">
            <svg class="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <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>
            </svg>
            <p class="text-gray-700 font-medium"><?php esc_html_e('No video activity yet', 'kantan-analytics'); ?></p>
            <p class="text-gray-500 text-sm mt-1 max-w-md mx-auto">
                <?php esc_html_e('When a visitor loads a page with an embedded YouTube, Vimeo, or self-hosted video, it will show up here — with plays, play rate, watch time, and completion rate. No setup needed: embeds are detected automatically.', 'kantan-analytics'); ?>
            </p>
        </div>
    </div>

<?php else: ?>

    <!-- Headline stats -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <div class="bg-white rounded-xl shadow-md p-6">
            <p class="text-sm font-medium text-gray-500"><?php esc_html_e('Plays', 'kantan-analytics'); ?></p>
            <p class="text-3xl font-bold text-gray-900 mt-1"><?php echo number_format($totals['plays']); ?></p>
            <p class="text-xs text-gray-400 mt-1"><?php
                /* translators: %s: number of impressions (already formatted) */
                printf(esc_html__('%s impressions', 'kantan-analytics'), number_format($totals['impressions']));
            ?></p>
        </div>
        <div class="bg-white rounded-xl shadow-md p-6">
            <p class="text-sm font-medium text-gray-500"><?php esc_html_e('Play rate', 'kantan-analytics'); ?></p>
            <p class="text-3xl font-bold text-gray-900 mt-1"><?php echo esc_html($totals['play_rate']); ?>%</p>
            <p class="text-xs text-gray-400 mt-1"><?php esc_html_e('of impressions became plays', 'kantan-analytics'); ?></p>
        </div>
        <div class="bg-white rounded-xl shadow-md p-6">
            <p class="text-sm font-medium text-gray-500"><?php esc_html_e('Avg watch time', 'kantan-analytics'); ?></p>
            <p class="text-3xl font-bold text-gray-900 mt-1"><?php echo esc_html($kantan_video_fmt_time($totals['avg_watch'])); ?></p>
            <p class="text-xs text-gray-400 mt-1"><?php
                /* translators: %s: total watch time, e.g. "3:42:10" */
                printf(esc_html__('%s watched in total', 'kantan-analytics'), esc_html($kantan_video_fmt_time($totals['watch_seconds'])));
            ?></p>
        </div>
        <div class="bg-white rounded-xl shadow-md p-6">
            <p class="text-sm font-medium text-gray-500"><?php esc_html_e('Completion rate', 'kantan-analytics'); ?></p>
            <p class="text-3xl font-bold text-gray-900 mt-1"><?php echo esc_html($totals['completion_rate']); ?>%</p>
            <p class="text-xs text-gray-400 mt-1"><?php
                /* translators: %s: number of completed plays (already formatted) */
                printf(esc_html__('%s watched to the end', 'kantan-analytics'), number_format($totals['completes']));
            ?></p>
        </div>
    </div>

    <!-- Video list -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-2">
                <h2 class="text-2xl font-bold text-gray-900"><?php esc_html_e('Videos', 'kantan-analytics'); ?></h2>
                <?php kantan_ai_prompts('analytics-video'); ?>
            </div>
            <?php /* translators: %d: number of videos listed */ ?>
            <span class="text-sm text-gray-400"><?php printf(esc_html__('%d videos', 'kantan-analytics'), count($video_rows)); ?></span>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Video', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Provider', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Plays', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Play rate', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Avg watch', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Completion', 'kantan-analytics'); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e('Last viewed', 'kantan-analytics'); ?></th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($video_rows as $row):
                        $impressions = intval($row->impressions);
                        $plays       = intval($row->plays);
                        $completes   = intval($row->completes);
                        $play_rate   = $impressions > 0 ? round(($plays / $impressions) * 100, 1) : 0;
                        $completion  = $plays > 0 ? round(($completes / $plays) * 100, 1) : 0;
                        $avg_watch   = $plays > 0 ? intval(round(intval($row->watch_seconds) / $plays)) : 0;
                        $meta = isset($provider_meta[$row->provider]) ? $provider_meta[$row->provider] : $provider_meta['html5'];
                    ?>
                        <tr class="hover:bg-gray-50 cursor-pointer kantan-video-row" data-video-key="<?php echo esc_attr($row->video_key); ?>" data-provider="<?php echo esc_attr($row->provider); ?>" data-title="<?php echo esc_attr($row->video_title); ?>">
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-800 font-medium truncate" style="max-width: 340px;" title="<?php echo esc_attr($row->video_key); ?>"><?php echo esc_html($row->video_title); ?></div>
                                <?php if (intval($row->duration) > 0): ?>
                                    <div class="text-xs text-gray-400 mt-0.5"><?php echo esc_html($kantan_video_fmt_time($row->duration)); ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 py-0.5 inline-flex text-xs font-medium rounded <?php echo esc_attr($meta['pill']); ?>"><?php echo esc_html($meta['label']); ?></span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right">
                                <span class="text-gray-800 font-medium"><?php echo number_format($plays); ?></span>
                                <span class="text-xs text-gray-400">/ <?php echo number_format($impressions); ?></span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-gray-600"><?php echo esc_html($play_rate); ?>%</td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-gray-600"><?php echo esc_html($kantan_video_fmt_time($avg_watch)); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-gray-600"><?php echo esc_html($completion); ?>%</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php
                                /* translators: %s: human-readable time difference, e.g. "3 hours" */
                                printf(esc_html__('%s ago', 'kantan-analytics'), human_time_diff(strtotime($row->last_seen)));
                            ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

<?php endif; ?>

<!-- Video detail modal -->
<div id="kantan-video-modal" class="fixed inset-0 z-[2147483547] hidden" style="margin:0!important;">
    <div class="absolute inset-0 bg-black/60" data-video-close></div>
    <div class="absolute top-1/2 left-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-3xl" style="transform:translate(-50%,-50%);max-height:90vh;overflow-y:auto;">
        <div class="flex items-start justify-between p-6 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl z-10">
            <div class="min-w-0 pr-4">
                <p id="kantan-video-modal-provider" class="text-xs font-semibold uppercase tracking-wide text-blue-600 mb-1"><?php esc_html_e('Video', 'kantan-analytics'); ?></p>
                <h3 id="kantan-video-modal-title" class="text-xl font-bold text-gray-900 truncate">&nbsp;</h3>
                <p id="kantan-video-modal-sub" class="text-sm text-gray-500 mt-0.5 truncate"></p>
            </div>
            <button type="button" data-video-close class="text-gray-400 hover:text-gray-600 p-1 flex-shrink-0" aria-label="<?php esc_attr_e('Close', '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="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        <div id="kantan-video-modal-body" class="p-6"></div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    'use strict';
    if (window.__kantanVideoModalInit) return;
    window.__kantanVideoModalInit = true;

    var restBase = '<?php echo esc_url(rest_url('kantan/v1')); ?>';
    var nonce    = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var days     = <?php echo (int) $days; ?>;
    var paidActive = <?php echo kantan_video_paid_active() ? 'true' : 'false'; ?>;
    var seoUrl   = 'https://trykantan.com/seo/';

    var I18N = {
        impressions: '<?php echo esc_js(__('Impressions', 'kantan-analytics')); ?>',
        plays: '<?php echo esc_js(__('Plays', 'kantan-analytics')); ?>',
        playRate: '<?php echo esc_js(__('Play rate', 'kantan-analytics')); ?>',
        avgWatch: '<?php echo esc_js(__('Avg watch', 'kantan-analytics')); ?>',
        completion: '<?php echo esc_js(__('Completion', 'kantan-analytics')); ?>',
        totalWatch: '<?php echo esc_js(__('Total watch time', 'kantan-analytics')); ?>',
        playsByDay: '<?php echo esc_js(__('Plays by day', 'kantan-analytics')); ?>',
        topPages: '<?php echo esc_js(__('Pages where it was watched', 'kantan-analytics')); ?>',
        retention: '<?php echo esc_js(__('Retention curve', 'kantan-analytics')); ?>',
        retentionSub: '<?php echo esc_js(__('% of viewers still watching at each point', 'kantan-analytics')); ?>',
        rewatch: '<?php echo esc_js(__('Rewatch heatmap', 'kantan-analytics')); ?>',
        rewatchSub: '<?php echo esc_js(__('Darker sections were played more often — intros, rewinds, and rewatched moments light up', 'kantan-analytics')); ?>',
        attribution: '<?php echo esc_js(__('Conversion attribution', 'kantan-analytics')); ?>',
        cohortViewers: '<?php echo esc_js(__('Played the video', 'kantan-analytics')); ?>',
        cohortEngaged: '<?php echo esc_js(__('Watched ≥ 50%', 'kantan-analytics')); ?>',
        cohortNonViewers: '<?php echo esc_js(__('Saw it, didn\'t play', 'kantan-analytics')); ?>',
        sessionsLbl: '<?php echo esc_js(__('%s sessions', 'kantan-analytics')); ?>',
        convRate: '<?php echo esc_js(__('conversion rate', 'kantan-analytics')); ?>',
        convValue: '<?php echo esc_js(__('value', 'kantan-analytics')); ?>',
        liftLine: '<?php echo esc_js(__('Sessions that played this video converted at %1$s× the rate of sessions that saw it and didn\'t.', 'kantan-analytics')); ?>',
        attributionEmpty: '<?php echo esc_js(__('Not enough session data yet for attribution — check back once more visitors have seen this video.', 'kantan-analytics')); ?>',
        lockedTitle: '<?php echo esc_js(__('Where do viewers drop off?', 'kantan-analytics')); ?>',
        lockedBody: '<?php echo esc_js(__('The retention curve and rewatch heatmap for this video are part of Kantan SEO. Engagement data is already being recorded, so the curve fills with history from today.', 'kantan-analytics')); ?>',
        lockedCta: '<?php echo esc_js(__('Upgrade to Kantan SEO', 'kantan-analytics')); ?>',
        autoplayNote: '<?php echo esc_js(__('%s of plays were autoplay', 'kantan-analytics')); ?>',
        allTime: '<?php echo esc_js(__('All time: %1$s plays · %2$s completes · first seen %3$s', 'kantan-analytics')); ?>',
        loading: '<?php echo esc_js(__('Loading…', 'kantan-analytics')); ?>',
        loadError: '<?php echo esc_js(__('Could not load video details.', 'kantan-analytics')); ?>',
        watched: '<?php echo esc_js(__('watched', 'kantan-analytics')); ?>',
        noPagesYet: '<?php echo esc_js(__('No page data in this period.', 'kantan-analytics')); ?>'
    };

    var modal = document.getElementById('kantan-video-modal');
    var titleEl = document.getElementById('kantan-video-modal-title');
    var providerEl = document.getElementById('kantan-video-modal-provider');
    var subEl = document.getElementById('kantan-video-modal-sub');
    var body = document.getElementById('kantan-video-modal-body');
    var chart = null;
    var curveChart = null;

    function esc(s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }
    function fmtTime(s) {
        s = parseInt(s, 10) || 0;
        var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60;
        function p(n) { return (n < 10 ? '0' : '') + n; }
        return h > 0 ? h + ':' + p(m) + ':' + p(r) : m + ':' + p(r);
    }
    function pathOf(url) {
        try { var u = new URL(url); return (u.pathname || '/') + (u.search || ''); }
        catch (e) { return url || '/'; }
    }
    function open() { modal.classList.remove('hidden'); }
    function close() {
        modal.classList.add('hidden');
        if (chart) { chart.destroy(); chart = null; }
        if (curveChart) { curveChart.destroy(); curveChart = null; }
    }
    modal.querySelectorAll('[data-video-close]').forEach(function(el) { el.addEventListener('click', close); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) close(); });

    function kpi(label, val) {
        return '<div class="bg-gray-50 rounded-lg p-3">' +
            '<p class="text-xs text-gray-500 uppercase tracking-wide">' + esc(label) + '</p>' +
            '<p class="text-xl font-bold text-gray-900 mt-1">' + val + '</p></div>';
    }

    function render(d) {
        var s = d.summary;
        var html = '<div class="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6">' +
            kpi(I18N.impressions, s.impressions.toLocaleString()) +
            kpi(I18N.plays, s.plays.toLocaleString()) +
            kpi(I18N.playRate, esc(s.play_rate) + '%') +
            kpi(I18N.avgWatch, fmtTime(s.avg_watch)) +
            kpi(I18N.completion, esc(s.completion_rate) + '%') +
            kpi(I18N.totalWatch, fmtTime(s.watch_seconds)) +
            '</div>';

        if (s.autoplay_plays > 0 && s.plays > 0) {
            html += '<p class="text-xs text-gray-400 -mt-3 mb-5">' +
                esc(I18N.autoplayNote.replace('%s', Math.round((s.autoplay_plays / s.plays) * 100) + '%')) + '</p>';
        }

        if (d.by_day && d.by_day.length) {
            html += '<div class="mb-6"><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">' + esc(I18N.playsByDay) + '</h4>' +
                '<div style="height:130px"><canvas id="kantan-video-modal-chart"></canvas></div></div>';
        }

        // Engagement curve + rewatch heatmap: real charts when the paid layer
        // supplies buckets, locked teaser otherwise.
        if (d.engagement && d.engagement.reached) {
            html += '<div class="mb-6"><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">' + esc(I18N.retention) + '</h4>' +
                '<p class="text-xs text-gray-400 mb-2">' + esc(I18N.retentionSub) + '</p>' +
                '<div style="height:150px"><canvas id="kantan-video-modal-curve"></canvas></div></div>';

            var maxPlays = Math.max.apply(null, d.engagement.plays.concat([1]));
            html += '<div class="mb-6"><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">' + esc(I18N.rewatch) + '</h4>' +
                '<p class="text-xs text-gray-400 mb-2">' + esc(I18N.rewatchSub) + '</p>' +
                '<div class="flex rounded overflow-hidden" style="height:26px">' +
                d.engagement.plays.map(function(v, i) {
                    var intensity = v > 0 ? 0.15 + 0.85 * (v / maxPlays) : 0.04;
                    return '<span class="flex-1" style="background:rgba(59,130,246,' + intensity.toFixed(2) + ')" title="' + i + '% — ' + v + '"></span>';
                }).join('') +
                '</div><div class="flex justify-between text-[10px] text-gray-400 mt-1"><span>0%</span><span>50%</span><span>100%</span></div></div>';
        } else if (!paidActive) {
            html += '<div class="mb-6 rounded-xl border border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50 p-4">' +
                '<div class="flex items-center gap-4">' +
                '<svg viewBox="0 0 100 36" class="w-32 flex-shrink-0 blur-[2px] select-none" aria-hidden="true">' +
                '<path d="M0,4 L10,6 20,10 30,13 40,15 50,20 60,22 70,28 80,30 90,31 100,33 L100,36 0,36 Z" fill="#bfdbfe"></path>' +
                '<path d="M0,4 L10,6 20,10 30,13 40,15 50,20 60,22 70,28 80,30 90,31 100,33" fill="none" stroke="#3b82f6" stroke-width="1.5"></path></svg>' +
                '<div class="min-w-0"><p class="text-sm font-semibold text-gray-900">' + esc(I18N.lockedTitle) + '</p>' +
                '<p class="text-xs text-gray-600 mt-0.5">' + esc(I18N.lockedBody) + '</p>' +
                '<a href="' + esc(seoUrl) + '" target="_blank" rel="noopener" class="inline-block text-xs font-medium text-blue-600 hover:underline mt-1.5">' + esc(I18N.lockedCta) + ' →</a></div>' +
                '</div></div>';
        }

        // Conversion attribution (attached by Kantan SEO when licensed).
        if (d.attribution) {
            var a = d.attribution;
            function cohortCard(label, c, highlight) {
                return '<div class="rounded-lg p-3 ' + (highlight ? 'bg-blue-50 border border-blue-200' : 'bg-gray-50') + '">' +
                    '<p class="text-xs text-gray-500 uppercase tracking-wide">' + esc(label) + '</p>' +
                    '<p class="text-xl font-bold text-gray-900 mt-1">' + esc(c.conv_rate) + '%</p>' +
                    '<p class="text-xs text-gray-500">' + esc(I18N.convRate) + '</p>' +
                    '<p class="text-xs text-gray-400 mt-1.5">' + esc(I18N.sessionsLbl.replace('%s', c.sessions.toLocaleString())) +
                    ' · $' + Number(c.value).toLocaleString() + ' ' + esc(I18N.convValue) + '</p></div>';
            }
            html += '<div class="mb-6"><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">' + esc(I18N.attribution) + '</h4>';
            if (a.viewers.sessions === 0 && a.non_viewers.sessions === 0) {
                html += '<p class="text-sm text-gray-400">' + esc(I18N.attributionEmpty) + '</p>';
            } else {
                html += '<div class="grid grid-cols-1 sm:grid-cols-3 gap-3">' +
                    cohortCard(I18N.cohortViewers, a.viewers, true) +
                    cohortCard(I18N.cohortEngaged, a.engaged, false) +
                    cohortCard(I18N.cohortNonViewers, a.non_viewers, false) +
                    '</div>';
                if (a.lift && a.lift > 1) {
                    html += '<p class="text-sm text-gray-700 mt-3 bg-green-50 border border-green-200 rounded-lg px-3 py-2">' +
                        esc(I18N.liftLine.replace('%1$s', a.lift)) + '</p>';
                }
            }
            html += '</div>';
        }

        html += '<div><h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">' + esc(I18N.topPages) + '</h4>';
        if (d.top_pages && d.top_pages.length) {
            html += '<div class="space-y-1">' + d.top_pages.map(function(p) {
                return '<div class="flex items-center justify-between gap-3 text-sm py-1.5 px-2 rounded hover:bg-gray-50">' +
                    '<span class="text-gray-700 truncate">' + esc(pathOf(p.page_url)) + '</span>' +
                    '<span class="text-gray-500 flex-shrink-0 text-xs">' + p.plays.toLocaleString() + ' × · ' + fmtTime(p.watch_seconds) + ' ' + esc(I18N.watched) + '</span></div>';
            }).join('') + '</div>';
        } else {
            html += '<p class="text-sm text-gray-400">' + esc(I18N.noPagesYet) + '</p>';
        }
        html += '</div>';

        if (d.all_time) {
            html += '<p class="text-xs text-gray-400 mt-5 pt-4 border-t border-gray-100">' +
                esc(I18N.allTime
                    .replace('%1$s', d.all_time.plays.toLocaleString())
                    .replace('%2$s', d.all_time.completes.toLocaleString())
                    .replace('%3$s', String(d.all_time.first_seen || '').split(' ')[0])) + '</p>';
        }

        body.innerHTML = html;

        if (d.by_day && d.by_day.length && typeof Chart !== 'undefined') {
            var ctx = document.getElementById('kantan-video-modal-chart');
            chart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: d.by_day.map(function(r) { return r.day.slice(5); }),
                    datasets: [{ data: d.by_day.map(function(r) { return r.plays; }), backgroundColor: '#3b82f6', borderRadius: 3 }]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 } }, x: { grid: { display: false } } }
                }
            });
        }

        if (d.engagement && d.engagement.reached && typeof Chart !== 'undefined') {
            var started = Math.max.apply(null, d.engagement.reached.concat([1]));
            var curveCtx = document.getElementById('kantan-video-modal-curve');
            if (curveCtx) {
                curveChart = new Chart(curveCtx, {
                    type: 'line',
                    data: {
                        labels: d.engagement.reached.map(function(_, i) { return i + '%'; }),
                        datasets: [{
                            data: d.engagement.reached.map(function(v) { return Math.round((v / started) * 100); }),
                            borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,.15)',
                            fill: true, pointRadius: 0, borderWidth: 2, tension: .3
                        }]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            y: { min: 0, max: 100, ticks: { callback: function(v) { return v + '%'; } } },
                            x: { grid: { display: false }, ticks: { maxTicksLimit: 11 } }
                        }
                    }
                });
            }
        }
    }

    document.querySelectorAll('.kantan-video-row').forEach(function(row) {
        row.addEventListener('click', function() {
            var key = row.getAttribute('data-video-key');
            providerEl.textContent = row.getAttribute('data-provider') || '';
            titleEl.textContent = row.getAttribute('data-title') || key;
            subEl.textContent = key;
            body.innerHTML = '<p class="text-sm text-gray-400">' + esc(I18N.loading) + '</p>';
            open();
            fetch(restBase + '/videos/detail?key=' + encodeURIComponent(key) + '&days=' + days, {
                credentials: 'same-origin',
                headers: { 'X-WP-Nonce': nonce }
            })
            .then(function(r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
            .then(render)
            .catch(function() { body.innerHTML = '<p class="text-sm text-red-500">' + esc(I18N.loadError) + '</p>'; });
        });
    });
})();
<?php kantan_admin_inline_js(ob_get_clean()); ?>

<?php if ($show_seo_upsell): ?>
    <?php if ($upsell_full): ?>

        <!-- SEO upsell — full (directly-distributed build) -->
        <div class="rounded-xl border border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50 p-6">
            <div class="flex flex-col lg:flex-row lg:items-center gap-6">
                <div class="flex-1">
                    <span class="inline-block text-xs font-semibold uppercase tracking-wider text-blue-700 bg-blue-100 rounded px-2 py-0.5 mb-3">Kantan SEO</span>
                    <h2 class="text-xl font-bold text-gray-900"><?php esc_html_e('See where viewers drop off — and what watching does to conversions', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-600 text-sm mt-2 max-w-xl"><?php
                        echo wp_kses_post(__('Kantan Analytics shows you <em>whether</em> videos get played. Kantan SEO shows you <em>which moment loses viewers</em> and <em>whether watching moves them to convert</em>.', 'kantan-analytics'));
                    ?></p>
                    <ul class="mt-4 space-y-2 text-sm text-gray-700">
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('<strong>Drop-off curve</strong> — the exact second viewers leave each video', 'kantan-analytics')); ?></li>
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('<strong>Rewatch heatmap</strong> — the sections viewers play again', 'kantan-analytics')); ?></li>
                        <li class="flex items-start gap-2"><svg class="w-5 h-5 text-blue-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><?php echo wp_kses_post(__('<strong>Conversion lift</strong> — conversion rate of viewers vs non-viewers, in dollars', 'kantan-analytics')); ?></li>
                    </ul>
                    <p class="text-xs text-gray-400 mt-3"><?php esc_html_e('Your engagement data is already being collected — the curves fill with history from today, not from purchase day.', 'kantan-analytics'); ?></p>
                </div>
                <div class="lg:w-64 flex-shrink-0">
                    <div class="bg-white rounded-lg border border-gray-200 p-4 mb-4">
                        <p class="text-xs text-gray-400 mb-2"><?php esc_html_e('Retention curve (with SEO)', 'kantan-analytics'); ?></p>
                        <svg viewBox="0 0 100 36" class="w-full blur-[2px] select-none" aria-hidden="true">
                            <path d="M0,4 L10,6 20,10 30,13 40,15 50,20 60,22 70,28 80,30 90,31 100,33 L100,36 0,36 Z" fill="#bfdbfe"></path>
                            <path d="M0,4 L10,6 20,10 30,13 40,15 50,20 60,22 70,28 80,30 90,31 100,33" fill="none" stroke="#3b82f6" stroke-width="1.5"></path>
                        </svg>
                    </div>
                    <a href="<?php echo esc_url('https://trykantan.com/seo/'); ?>" target="_blank" rel="noopener" class="block w-full text-center px-4 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition text-sm"><?php esc_html_e('Upgrade to Kantan SEO', 'kantan-analytics'); ?></a>
                </div>
            </div>
        </div>

    <?php else: ?>

        <!-- SEO upsell — restrained (wp.org build) -->
        <div class="rounded-xl border border-gray-200 bg-gray-50 p-6">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h2 class="text-base font-semibold text-gray-900"><?php esc_html_e('See where viewers drop off — and what watching does to conversions', 'kantan-analytics'); ?></h2>
                    <p class="text-gray-600 text-sm mt-1 max-w-2xl"><?php esc_html_e('Kantan SEO adds per-video retention curves, rewatch heatmaps, and conversion attribution to the engagement data this tab already collects.', 'kantan-analytics'); ?></p>
                </div>
                <a href="<?php echo esc_url('https://trykantan.com/seo/'); ?>" target="_blank" rel="noopener" class="flex-shrink-0 text-sm font-medium text-blue-600 hover:text-blue-700 hover:underline whitespace-nowrap"><?php esc_html_e('Learn more about Kantan SEO →', 'kantan-analytics'); ?></a>
            </div>
        </div>

    <?php endif; ?>
<?php endif; ?>
