<?php
if (!defined('ABSPATH')) die('Restricted Access');

/**
 * Free, local insight layer for AI Flash Tune.
 *
 * This class intentionally avoids external AI calls. It turns the tracking data that
 * the free plugin already collects into practical, immediately useful guidance.
 */
class AIFLT_Free_Insights_Logic {

    /**
     * Safely check whether a custom table exists.
     */
    private static function table_exists($table_name) {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name)) === $table_name;
    }

    /**
     * Convert numbers that may include percent signs into a float.
     */
    private static function to_float($value) {
        if (is_numeric($value)) {
            return (float) $value;
        }
        return (float) preg_replace('/[^0-9.\-]/', '', (string) $value);
    }

    /**
     * Return the most important data-confidence state for the dashboard.
     */
    public static function get_data_confidence($dashboard_metrics, $funnel_data) {
        $total_sessions = isset($dashboard_metrics['total_sessions']) ? (int) $dashboard_metrics['total_sessions'] : 0;
        $has_funnel_data = !empty($funnel_data) && empty($funnel_data['is_empty']);
        $min_sessions = 20;

        if (!aiflt_is_woocommerce_active()) {
            return [
                'level' => __('Blocked', 'ai-flash-tune'),
                'tone' => 'critical',
                'summary' => __('WooCommerce must be active before AI Flash Tune can measure your store funnel.', 'ai-flash-tune'),
                'is_ready' => false,
                'sessions' => $total_sessions,
                'min_sessions' => $min_sessions,
                'progress' => 0,
            ];
        }

        if ($total_sessions <= 0 && !$has_funnel_data) {
            return [
                'level' => __('Waiting for data', 'ai-flash-tune'),
                'tone' => 'notice',
                'summary' => __('No visitor funnel data has been recorded yet. Run a quick product-to-checkout test or wait for real shoppers before making conversion decisions.', 'ai-flash-tune'),
                'is_ready' => false,
                'sessions' => $total_sessions,
                'min_sessions' => $min_sessions,
                'progress' => 0,
            ];
        }

        if ($total_sessions < $min_sessions) {
            return [
                'level' => __('Low confidence', 'ai-flash-tune'),
                'tone' => 'warning',
                'summary' => sprintf(
                    /* translators: 1: current session count, 2: minimum recommended session count */
                    __('Only %1$d sessions are available. Use the checks as early signals, but wait for about %2$d+ sessions before making bigger decisions.', 'ai-flash-tune'),
                    $total_sessions,
                    $min_sessions
                ),
                'is_ready' => false,
                'sessions' => $total_sessions,
                'min_sessions' => $min_sessions,
                'progress' => min(100, (int) round(($total_sessions / $min_sessions) * 100)),
            ];
        }

        if ($total_sessions < 100) {
            return [
                'level' => __('Medium confidence', 'ai-flash-tune'),
                'tone' => 'good',
                'summary' => __('You have enough data for useful free diagnostics. Keep collecting traffic to make the score and priorities more reliable.', 'ai-flash-tune'),
                'is_ready' => true,
                'sessions' => $total_sessions,
                'min_sessions' => $min_sessions,
                'progress' => 100,
            ];
        }

        return [
            'level' => __('High confidence', 'ai-flash-tune'),
            'tone' => 'good',
            'summary' => __('You have a strong sample of recent visitor behavior. The priority checks are reliable enough for practical optimization work.', 'ai-flash-tune'),
            'is_ready' => true,
            'sessions' => $total_sessions,
            'min_sessions' => $min_sessions,
            'progress' => 100,
        ];
    }

    /**
     * Builds a simple, local Store Health Score for the free dashboard.
     */
    public static function get_store_health_score($dashboard_metrics, $funnel_data, $page_speed_data, $checkout_detector_data, $low_performing_products) {
        $confidence = self::get_data_confidence($dashboard_metrics, $funnel_data);
        $factors = [];

        if (!$confidence['is_ready']) {
            $factors[] = [
                'label' => $confidence['level'],
                'impact' => __('Data readiness', 'ai-flash-tune'),
                'tone' => $confidence['tone'],
            ];

            $tracking_enabled = get_option('aiflt_enable_tracking', 1) === '1' || get_option('aiflt_enable_tracking', 1) === 1;
            if (!$tracking_enabled) {
                $factors[] = [
                    'label' => __('Frontend tracking is disabled', 'ai-flash-tune'),
                    'impact' => __('Fix first', 'ai-flash-tune'),
                    'tone' => 'critical',
                ];
            }

            if (isset($checkout_detector_data['status']) && $checkout_detector_data['status'] === 'High Friction') {
                $factors[] = [
                    'label' => __('Checkout form may be too long', 'ai-flash-tune'),
                    'impact' => __('Early warning', 'ai-flash-tune'),
                    'tone' => 'warning',
                ];
            }

            return [
                'score' => null,
                'label' => __('Waiting for data', 'ai-flash-tune'),
                'tone' => $confidence['tone'],
                'summary' => __('Store Health Score will appear once enough real funnel activity has been recorded.', 'ai-flash-tune'),
                'factors' => $factors,
                'is_ready' => false,
                'confidence' => $confidence,
            ];
        }

        $score = 100;
        $tracking_enabled = get_option('aiflt_enable_tracking', 1) === '1' || get_option('aiflt_enable_tracking', 1) === 1;
        if (!$tracking_enabled) {
            $score -= 30;
            $factors[] = [
                'label' => __('Frontend tracking is disabled', 'ai-flash-tune'),
                'impact' => __('High impact', 'ai-flash-tune'),
                'tone' => 'critical',
            ];
        }

        $total_sessions = isset($dashboard_metrics['total_sessions']) ? (int) $dashboard_metrics['total_sessions'] : 0;
        $conversion_rate = isset($dashboard_metrics['conversion_rate']) ? self::to_float($dashboard_metrics['conversion_rate']) : 0;
        $abandoned_carts = isset($dashboard_metrics['abandoned_carts']) ? (int) $dashboard_metrics['abandoned_carts'] : 0;
        $avg_lcp = isset($dashboard_metrics['page_speed']) ? self::to_float($dashboard_metrics['page_speed']) : 0;

        if ($conversion_rate < 1) {
            $score -= 18;
            $factors[] = [
                'label' => __('Very low conversion rate', 'ai-flash-tune'),
                'impact' => __('High impact', 'ai-flash-tune'),
                'tone' => 'critical',
            ];
        } elseif ($conversion_rate < 2) {
            $score -= 10;
            $factors[] = [
                'label' => __('Conversion rate needs attention', 'ai-flash-tune'),
                'impact' => __('Medium impact', 'ai-flash-tune'),
                'tone' => 'warning',
            ];
        }

        if ($total_sessions > 0 && $abandoned_carts > 0) {
            $abandonment_ratio = $abandoned_carts / max(1, $total_sessions);
            if ($abandonment_ratio >= 0.40) {
                $score -= 18;
                $factors[] = [
                    'label' => __('High abandoned-cart pressure', 'ai-flash-tune'),
                    'impact' => __('High impact', 'ai-flash-tune'),
                    'tone' => 'critical',
                ];
            } elseif ($abandonment_ratio >= 0.20) {
                $score -= 10;
                $factors[] = [
                    'label' => __('Abandoned carts need monitoring', 'ai-flash-tune'),
                    'impact' => __('Medium impact', 'ai-flash-tune'),
                    'tone' => 'warning',
                ];
            }
        }

        if ($avg_lcp > 4) {
            $score -= 18;
            $factors[] = [
                'label' => __('Key pages are loading slowly', 'ai-flash-tune'),
                'impact' => __('High impact', 'ai-flash-tune'),
                'tone' => 'critical',
            ];
        } elseif ($avg_lcp > 2.5 || (isset($page_speed_data['status']) && $page_speed_data['status'] === 'warning')) {
            $score -= 10;
            $factors[] = [
                'label' => __('Page speed can hurt conversions', 'ai-flash-tune'),
                'impact' => __('Medium impact', 'ai-flash-tune'),
                'tone' => 'warning',
            ];
        }

        if (isset($checkout_detector_data['status']) && $checkout_detector_data['status'] === 'High Friction') {
            $score -= 15;
            $factors[] = [
                'label' => __('Checkout form may be too long', 'ai-flash-tune'),
                'impact' => __('High impact', 'ai-flash-tune'),
                'tone' => 'critical',
            ];
        }

        if (!empty($funnel_data) && empty($funnel_data['is_empty'])) {
            $highest_drop = max(
                isset($funnel_data['drop_off_product']) ? self::to_float($funnel_data['drop_off_product']) : 0,
                isset($funnel_data['drop_off_cart']) ? self::to_float($funnel_data['drop_off_cart']) : 0,
                isset($funnel_data['drop_off_checkout']) ? self::to_float($funnel_data['drop_off_checkout']) : 0
            );
            if ($highest_drop >= 80) {
                $score -= 20;
                $factors[] = [
                    'label' => __('A major funnel step is leaking visitors', 'ai-flash-tune'),
                    'impact' => __('High impact', 'ai-flash-tune'),
                    'tone' => 'critical',
                ];
            } elseif ($highest_drop >= 50) {
                $score -= 10;
                $factors[] = [
                    'label' => __('Funnel drop-off needs review', 'ai-flash-tune'),
                    'impact' => __('Medium impact', 'ai-flash-tune'),
                    'tone' => 'warning',
                ];
            }
        }

        if (!empty($low_performing_products)) {
            $score -= min(15, count($low_performing_products) * 5);
            $factors[] = [
                'label' => sprintf(
                    /* translators: %d: number of low-performing products */
                    _n('%d product needs review', '%d products need review', count($low_performing_products), 'ai-flash-tune'),
                    count($low_performing_products)
                ),
                'impact' => __('Medium impact', 'ai-flash-tune'),
                'tone' => 'warning',
            ];
        }

        $score = max(0, min(100, (int) round($score)));

        if ($score >= 85) {
            $label = __('Strong', 'ai-flash-tune');
            $tone = 'good';
            $summary = __('Your store looks healthy. Keep monitoring funnel movement as more data arrives.', 'ai-flash-tune');
        } elseif ($score >= 70) {
            $label = __('Good', 'ai-flash-tune');
            $tone = 'good';
            $summary = __('Your store is mostly healthy, with a few areas worth checking.', 'ai-flash-tune');
        } elseif ($score >= 50) {
            $label = __('Needs Attention', 'ai-flash-tune');
            $tone = 'warning';
            $summary = __('Your store has visible conversion leaks. Start with the priority checks below.', 'ai-flash-tune');
        } else {
            $label = __('Critical', 'ai-flash-tune');
            $tone = 'critical';
            $summary = __('Your store has serious conversion friction. Review the highest-impact issues first.', 'ai-flash-tune');
        }

        if (empty($factors)) {
            $factors[] = [
                'label' => __('No major free-scan issues detected', 'ai-flash-tune'),
                'impact' => __('Good sign', 'ai-flash-tune'),
                'tone' => 'good',
            ];
        }

        return [
            'score' => $score,
            'label' => $label,
            'tone' => $tone,
            'summary' => $summary,
            'factors' => $factors,
            'is_ready' => true,
            'confidence' => $confidence,
        ];
    }

    /**
     * Build the top practical checks for the free dashboard.
     */
    public static function get_priority_checks($dashboard_metrics, $funnel_data, $page_speed_data, $checkout_detector_data, $low_performing_products) {
        $checks = [];
        $admin_url = admin_url('admin.php');
        $confidence = self::get_data_confidence($dashboard_metrics, $funnel_data);
        $total_sessions = isset($dashboard_metrics['total_sessions']) ? (int) $dashboard_metrics['total_sessions'] : 0;
        $abandoned_carts = isset($dashboard_metrics['abandoned_carts']) ? (int) $dashboard_metrics['abandoned_carts'] : 0;
        $avg_lcp = isset($dashboard_metrics['page_speed']) ? self::to_float($dashboard_metrics['page_speed']) : 0;

        if (get_option('aiflt_enable_tracking', 1) !== '1' && get_option('aiflt_enable_tracking', 1) !== 1) {
            $checks[] = self::priority_item('critical', 'fas fa-toggle-off', __('Enable tracking first', 'ai-flash-tune'), __('Frontend tracking is disabled, so AI Flash Tune cannot collect funnel or cart data.', 'ai-flash-tune'), __('Open Settings', 'ai-flash-tune'), add_query_arg('page', 'aiflt_settings', $admin_url));
        }

        if ($total_sessions === 0) {
            $checks[] = self::priority_item('notice', 'fas fa-seedling', __('Collect your first visitor data', 'ai-flash-tune'), __('Visit a product page, add a product to cart, open checkout, then refresh this dashboard to confirm events are being recorded.', 'ai-flash-tune'), __('Open Products', 'ai-flash-tune'), admin_url('edit.php?post_type=product'));
            $checks[] = self::priority_item('notice', 'fas fa-user-shield', __('Exclude admin testing from real reports', 'ai-flash-tune'), __('Keep Administrator and Shop Manager roles excluded so your own testing does not pollute customer behavior data.', 'ai-flash-tune'), __('Open Settings', 'ai-flash-tune'), add_query_arg('page', 'aiflt_settings', $admin_url));
        } elseif (!$confidence['is_ready']) {
            $checks[] = self::priority_item('notice', 'fas fa-hourglass-half', __('Wait for more visitor data', 'ai-flash-tune'), sprintf(
                /* translators: 1: current sessions, 2: recommended sessions */
                __('You have %1$d sessions. Use current issues as early warnings, but review again around %2$d+ sessions.', 'ai-flash-tune'),
                $confidence['sessions'],
                $confidence['min_sessions']
            ), __('Refresh Dashboard', 'ai-flash-tune'), add_query_arg('page', 'ai_flash_tune', $admin_url));
        }

        if (!empty($funnel_data) && empty($funnel_data['is_empty'])) {
            $drop_map = [
                'checkout' => [__('Checkout Page', 'ai-flash-tune'), isset($funnel_data['drop_off_checkout']) ? self::to_float($funnel_data['drop_off_checkout']) : 0, __('Review checkout friction, payment trust, required fields, and unexpected costs.', 'ai-flash-tune')],
                'cart' => [__('Cart Page', 'ai-flash-tune'), isset($funnel_data['drop_off_cart']) ? self::to_float($funnel_data['drop_off_cart']) : 0, __('Review cart clarity, shipping or tax surprises, coupon distractions, and checkout button visibility.', 'ai-flash-tune')],
                'product' => [__('Product Page', 'ai-flash-tune'), isset($funnel_data['drop_off_product']) ? self::to_float($funnel_data['drop_off_product']) : 0, __('Review product titles, images, pricing clarity, benefits, CTA visibility, and trust signals.', 'ai-flash-tune')],
            ];
            uasort($drop_map, function($a, $b) { return $b[1] <=> $a[1]; });
            $top = reset($drop_map);
            if ($top && $top[1] >= 50) {
                $checks[] = self::priority_item($top[1] >= 80 ? 'critical' : 'warning', 'fas fa-route', sprintf(
                    /* translators: 1: funnel step name, 2: drop-off percent */
                    __('Fix the %1$s drop-off (%2$s%%)', 'ai-flash-tune'),
                    $top[0],
                    round($top[1], 2)
                ), $top[2], __('Open Funnel Analysis', 'ai-flash-tune'), add_query_arg('page', 'funnelanalysis', $admin_url));
            }
        }

        if ($avg_lcp > 2.5 || (isset($page_speed_data['status']) && $page_speed_data['status'] === 'warning')) {
            $checks[] = self::priority_item($avg_lcp > 4 ? 'critical' : 'warning', 'fas fa-tachometer-alt', __('Improve slow key pages', 'ai-flash-tune'), sprintf(
                /* translators: %s: LCP seconds */
                __('Average LCP is %ss. Slow pages can reduce product interest and checkout completion.', 'ai-flash-tune'),
                round($avg_lcp, 2)
            ), __('View Dashboard Alert', 'ai-flash-tune'), add_query_arg('page', 'ai_flash_tune', $admin_url));
        }

        if (isset($checkout_detector_data['status']) && $checkout_detector_data['status'] === 'High Friction') {
            $checks[] = self::priority_item('critical', 'fas fa-clipboard-list', __('Simplify checkout fields', 'ai-flash-tune'), $checkout_detector_data['message'] . ' ' . __('Long forms can create hesitation at the final step.', 'ai-flash-tune'), __('Open Settings', 'ai-flash-tune'), add_query_arg('page', 'aiflt_settings', $admin_url));
        }

        if ($abandoned_carts > 0) {
            $checks[] = self::priority_item('warning', 'fas fa-shopping-basket', sprintf(
                /* translators: %d: abandoned carts */
                _n('Review %d abandoned cart', 'Review %d abandoned carts', $abandoned_carts, 'ai-flash-tune'),
                $abandoned_carts
            ), __('Look for repeated products, guest-only patterns, or a checkout step that blocks buyers.', 'ai-flash-tune'), __('Open Abandoned Carts', 'ai-flash-tune'), add_query_arg('page', 'abandonedcarts', $admin_url));
        }

        if (!empty($low_performing_products)) {
            $first = reset($low_performing_products);
            $title = !empty($first['product_name']) ? $first['product_name'] : __('a product', 'ai-flash-tune');
            $checks[] = self::priority_item('warning', 'fas fa-search-dollar', __('Review low-performing product pages', 'ai-flash-tune'), sprintf(
                /* translators: %s: product name */
                __('Start with "%s". It has traffic but weak sales movement.', 'ai-flash-tune'),
                $title
            ), __('Open Products', 'ai-flash-tune'), add_query_arg('page', 'products', $admin_url));
        }

        if (empty($checks)) {
            $checks[] = self::priority_item('good', 'fas fa-check-circle', __('No urgent free-scan issues found', 'ai-flash-tune'), __('Your current data does not show a major leak. Keep collecting traffic and review again after more sessions.', 'ai-flash-tune'), __('Open Funnel Analysis', 'ai-flash-tune'), add_query_arg('page', 'funnelanalysis', $admin_url));
        }

        return array_slice($checks, 0, 5);
    }

    private static function priority_item($tone, $icon, $title, $description, $action_label, $action_url) {
        return compact('tone', 'icon', 'title', 'description', 'action_label', 'action_url');
    }

    /**
     * Tracking health checklist for free users and support debugging.
     */
    public static function get_tracking_health() {
        global $wpdb;
        $funnel_table = $wpdb->prefix . 'aiflt_funnel_data';
        $behavior_table = $wpdb->prefix . 'aiflt_behavior_data';
        $items = [];

        $wc_active = aiflt_is_woocommerce_active();
        $items[] = self::health_item(__('WooCommerce active', 'ai-flash-tune'), $wc_active, $wc_active ? __('Ready', 'ai-flash-tune') : __('Required', 'ai-flash-tune'));

        $tracking_enabled = get_option('aiflt_enable_tracking', 1) === '1' || get_option('aiflt_enable_tracking', 1) === 1;
        $items[] = self::health_item(__('Frontend tracking enabled', 'ai-flash-tune'), $tracking_enabled, $tracking_enabled ? __('Tracking script is allowed', 'ai-flash-tune') : __('Enable it in Settings', 'ai-flash-tune'));

        $funnel_exists = self::table_exists($funnel_table);
        $behavior_exists = self::table_exists($behavior_table);
        $items[] = self::health_item(__('Funnel table created', 'ai-flash-tune'), $funnel_exists, $funnel_exists ? __('Database ready', 'ai-flash-tune') : __('Reactivate plugin to create tables', 'ai-flash-tune'));
        $items[] = self::health_item(__('Behavior table created', 'ai-flash-tune'), $behavior_exists, $behavior_exists ? __('Database ready', 'ai-flash-tune') : __('Reactivate plugin to create tables', 'ai-flash-tune'));

        $since = gmdate('Y-m-d H:i:s', strtotime('-7 days'));
        $recent_funnel_events = $funnel_exists ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$funnel_table} WHERE timestamp >= %s", $since)) : 0;
        $recent_product_events = $funnel_exists ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$funnel_table} WHERE page_name = 'product' AND timestamp >= %s", $since)) : 0;
        $recent_cart_events = $behavior_exists ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$behavior_table} WHERE behavior_type = 'add_to_cart' AND timestamp >= %s", $since)) : 0;
        $recent_checkout_events = $funnel_exists ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$funnel_table} WHERE page_name IN ('checkout', 'checkout_attempt') AND timestamp >= %s", $since)) : 0;

        $items[] = self::health_item(__('Recent funnel events', 'ai-flash-tune'), $recent_funnel_events > 0, sprintf(
            /* translators: %d: event count */
            _n('%d event in last 7 days', '%d events in last 7 days', $recent_funnel_events, 'ai-flash-tune'),
            $recent_funnel_events
        ), $recent_funnel_events > 0 ? 'good' : 'notice');

        $items[] = self::health_item(__('Product page tracking', 'ai-flash-tune'), $recent_product_events > 0, sprintf(
            /* translators: %d: event count */
            _n('%d product view', '%d product views', $recent_product_events, 'ai-flash-tune'),
            $recent_product_events
        ), $recent_product_events > 0 ? 'good' : 'notice');

        $items[] = self::health_item(__('Add-to-cart tracking', 'ai-flash-tune'), $recent_cart_events > 0, sprintf(
            /* translators: %d: event count */
            _n('%d cart event', '%d cart events', $recent_cart_events, 'ai-flash-tune'),
            $recent_cart_events
        ), $recent_cart_events > 0 ? 'good' : 'notice');

        $items[] = self::health_item(__('Checkout tracking', 'ai-flash-tune'), $recent_checkout_events > 0, sprintf(
            /* translators: %d: event count */
            _n('%d checkout event', '%d checkout events', $recent_checkout_events, 'ai-flash-tune'),
            $recent_checkout_events
        ), $recent_checkout_events > 0 ? 'good' : 'notice');

        $ready_count = 0;
        foreach ($items as $item) {
            if ($item['ok']) {
                $ready_count++;
            }
        }

        return [
            'items' => $items,
            'ready_count' => $ready_count,
            'total_count' => count($items),
        ];
    }

    private static function health_item($label, $ok, $message, $tone = null) {
        return [
            'label' => $label,
            'ok' => (bool) $ok,
            'message' => $message,
            'tone' => $tone ? $tone : ((bool) $ok ? 'good' : 'critical'),
        ];
    }

    /**
     * Finds products most commonly left in abandoned carts.
     */
    public static function get_top_abandoned_products($limit = 5, $days = 30) {
        if (!class_exists('AIFLT_Abandoned_Carts_Logic')) {
            return [];
        }

        global $wpdb;
        $funnel_table = $wpdb->prefix . 'aiflt_funnel_data';
        if (!self::table_exists($funnel_table)) {
            return [];
        }

        $start_date = gmdate('Y-m-d', strtotime('-' . absint($days) . ' days'));
        $end_date = gmdate('Y-m-d');
        $session_ids = AIFLT_Abandoned_Carts_Logic::get_abandoned_session_ids($start_date, $end_date, 'all');
        if (empty($session_ids)) {
            return [];
        }

        $session_ids = array_slice($session_ids, 0, 500);
        $placeholders = implode(', ', array_fill(0, count($session_ids), '%s'));
        $cart_rows = $wpdb->get_results(
            $wpdb->prepare(
                "
                SELECT f.session_id, f.cart_data
                FROM {$funnel_table} f
                INNER JOIN (
                    SELECT session_id, MAX(timestamp) as max_ts
                    FROM {$funnel_table}
                    WHERE session_id IN ({$placeholders})
                      AND cart_data IS NOT NULL
                      AND cart_data != '[]'
                    GROUP BY session_id
                ) latest ON f.session_id = latest.session_id AND f.timestamp = latest.max_ts
                ",
                $session_ids
            ),
            ARRAY_A
        );

        $products = [];
        foreach ($cart_rows as $row) {
            $cart_data = maybe_unserialize($row['cart_data']);
            if (!is_array($cart_data) || empty($cart_data['contents']) || !is_array($cart_data['contents'])) {
                continue;
            }

            foreach ($cart_data['contents'] as $item) {
                $product_id = isset($item['product_id']) ? absint($item['product_id']) : 0;
                $name = isset($item['name']) ? sanitize_text_field($item['name']) : __('Unknown Product', 'ai-flash-tune');
                $quantity = isset($item['quantity']) ? max(1, absint($item['quantity'])) : 1;
                $price = isset($item['price']) ? self::to_float($item['price']) : 0;
                $key = $product_id > 0 ? 'p_' . $product_id : 'n_' . md5($name);

                if (!isset($products[$key])) {
                    $products[$key] = [
                        'product_id' => $product_id,
                        'name' => $name,
                        'cart_count' => 0,
                        'quantity' => 0,
                        'estimated_value' => 0,
                    ];
                }

                $products[$key]['cart_count']++;
                $products[$key]['quantity'] += $quantity;
                $products[$key]['estimated_value'] += ($price * $quantity);
            }
        }

        usort($products, function($a, $b) {
            if ($a['cart_count'] === $b['cart_count']) {
                return $b['estimated_value'] <=> $a['estimated_value'];
            }
            return $b['cart_count'] <=> $a['cart_count'];
        });

        return array_slice($products, 0, absint($limit));
    }

    /**
     * A local, free insight snapshot that does not require an API key.
     */
    public static function get_local_insight_snapshot($priority_checks, $dashboard_metrics = [], $funnel_data = []) {
        $confidence = self::get_data_confidence($dashboard_metrics, $funnel_data);
        if (!$confidence['is_ready'] && $confidence['sessions'] <= 0) {
            return __('Start with one clean tracking test: visit a product page, add a product to cart, open checkout, then refresh the dashboard. This confirms the free funnel is recording correctly.', 'ai-flash-tune');
        }

        if (empty($priority_checks)) {
            return __('Keep collecting data. AI Flash Tune will surface practical checks as soon as visitors move through your funnel.', 'ai-flash-tune');
        }

        $first = reset($priority_checks);
        if ($first['tone'] === 'good') {
            return __('No urgent leak is visible in the current free scan. Keep monitoring product movement, abandoned carts, checkout completion, and page speed as more data arrives.', 'ai-flash-tune');
        }

        return sprintf(
            /* translators: 1: issue title, 2: issue description */
            __('Start with this: %1$s. %2$s', 'ai-flash-tune'),
            $first['title'],
            $first['description']
        );
    }

    /**
     * Local weekly snapshot for the free dashboard.
     */
    public static function get_weekly_snapshot($dashboard_metrics, $funnel_data, $page_speed_data) {
        $sessions = isset($dashboard_metrics['total_sessions']) ? (int) $dashboard_metrics['total_sessions'] : 0;
        $conversion_rate = isset($dashboard_metrics['conversion_rate']) ? self::to_float($dashboard_metrics['conversion_rate']) : 0;
        $abandoned_carts = isset($dashboard_metrics['abandoned_carts']) ? (int) $dashboard_metrics['abandoned_carts'] : 0;
        $page_speed = isset($dashboard_metrics['page_speed']) ? self::to_float($dashboard_metrics['page_speed']) : 0;

        if ($sessions <= 0) {
            return [
                'title' => __('This week: waiting for activity', 'ai-flash-tune'),
                'text' => __('No visitor sessions have been recorded yet. Once shoppers visit products, add to cart, or reach checkout, this snapshot will summarize the week in plain language.', 'ai-flash-tune'),
                'tone' => 'notice',
            ];
        }

        $parts = [];
        $parts[] = sprintf(
            /* translators: %d: session count */
            _n('%d session was recorded', '%d sessions were recorded', $sessions, 'ai-flash-tune'),
            $sessions
        );

        $parts[] = sprintf(
            /* translators: %s: conversion rate */
            __('conversion rate is %s%%', 'ai-flash-tune'),
            round($conversion_rate, 2)
        );

        if ($abandoned_carts > 0) {
            $parts[] = sprintf(
                /* translators: %d: abandoned carts */
                _n('%d cart was abandoned', '%d carts were abandoned', $abandoned_carts, 'ai-flash-tune'),
                $abandoned_carts
            );
        }

        if (!empty($funnel_data) && empty($funnel_data['is_empty'])) {
            $drops = [
                __('product step', 'ai-flash-tune') => isset($funnel_data['drop_off_product']) ? self::to_float($funnel_data['drop_off_product']) : 0,
                __('cart step', 'ai-flash-tune') => isset($funnel_data['drop_off_cart']) ? self::to_float($funnel_data['drop_off_cart']) : 0,
                __('checkout step', 'ai-flash-tune') => isset($funnel_data['drop_off_checkout']) ? self::to_float($funnel_data['drop_off_checkout']) : 0,
            ];
            arsort($drops);
            $top_step = key($drops);
            $top_drop = current($drops);
            if ($top_drop > 0) {
                $parts[] = sprintf(
                    /* translators: 1: funnel step, 2: drop-off percent */
                    __('the largest drop-off is at the %1$s (%2$s%%)', 'ai-flash-tune'),
                    $top_step,
                    round($top_drop, 2)
                );
            }
        }

        if ($page_speed > 2.5 || (isset($page_speed_data['status']) && $page_speed_data['status'] === 'warning')) {
            $parts[] = __('page speed needs attention', 'ai-flash-tune');
        }

        return [
            'title' => __('This week in your store', 'ai-flash-tune'),
            'text' => ucfirst(implode(', ', $parts)) . '.',
            'tone' => ($conversion_rate > 0 || $abandoned_carts === 0) ? 'good' : 'warning',
        ];
    }

    /**
     * Manual tracking test steps shown in the free dashboard.
     */
    public static function get_tracking_test_steps() {
        return [
            __('Open your store in a private/incognito browser window.', 'ai-flash-tune'),
            __('Visit one product page as a normal shopper.', 'ai-flash-tune'),
            __('Add the product to cart and open the cart page.', 'ai-flash-tune'),
            __('Continue to checkout, then refresh this dashboard.', 'ai-flash-tune'),
        ];
    }
}
