<?php
/**
 * Chief Insights payload for React admin (2.7).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_insights_registry_i18n' ) ) {
	function newsai_insights_registry_i18n() {
		return [
			'loading'           => __( 'Loading Chief Insights…', 'newsroom-ai-assistant' ),
			'error'             => __( 'Chief Insights could not load.', 'newsroom-ai-assistant' ),
			'title'             => __( 'Chief Insights', 'newsroom-ai-assistant' ),
			'subtitle'          => __( 'High-level overview of editorial & search performance.', 'newsroom-ai-assistant' ),
			'export'            => __( 'Export report', 'newsroom-ai-assistant' ),
			'ai_brief'          => __( 'AI daily brief', 'newsroom-ai-assistant' ),
			'search_perf'       => __( 'Search performance', 'newsroom-ai-assistant' ),
			'total_clicks'      => __( 'Total clicks', 'newsroom-ai-assistant' ),
			'published'         => __( 'Published articles', 'newsroom-ai-assistant' ),
			'avg_focus'         => __( 'Avg focus score', 'newsroom-ai-assistant' ),
			'avg_discover'      => __( 'Avg Discover %', 'newsroom-ai-assistant' ),
			'winning'           => __( 'Top winning posts', 'newsroom-ai-assistant' ),
			'losing'            => __( 'Top losing posts', 'newsroom-ai-assistant' ),
			'devices'           => __( 'Device breakdown', 'newsroom-ai-assistant' ),
			'channels'          => __( 'Channel clicks', 'newsroom-ai-assistant' ),
			'clicks'            => __( 'clicks', 'newsroom-ai-assistant' ),
			'pro_demo'          => __( 'Demo data — upgrade to Pro for live GSC metrics.', 'newsroom-ai-assistant' ),
			'channel_web'       => __( 'Web', 'newsroom-ai-assistant' ),
			'channel_discover'  => __( 'Discover', 'newsroom-ai-assistant' ),
			'channel_news'      => __( 'Google News', 'newsroom-ai-assistant' ),
			'morning'           => __( 'Morning', 'newsroom-ai-assistant' ),
			'evening'           => __( 'Evening', 'newsroom-ai-assistant' ),
			'brief_loading'     => __( 'Generating brief…', 'newsroom-ai-assistant' ),
			'brief_error'       => __( 'Could not generate brief.', 'newsroom-ai-assistant' ),
			'export_pdf'        => __( 'Export PDF', 'newsroom-ai-assistant' ),
			'days_label'        => __( 'Period', 'newsroom-ai-assistant' ),
			'ctr'               => __( 'CTR', 'newsroom-ai-assistant' ),
			'no_devices'        => __( 'No device data yet — run GSC sync.', 'newsroom-ai-assistant' ),
			'no_gsc'            => __( 'No Google Search Console data for this period yet. Connect GSC in Settings and run a sync.', 'newsroom-ai-assistant' ),
		];
	}
}

if ( ! function_exists( 'newsai_insights_registry_slim_posts' ) ) {
	function newsai_insights_registry_slim_posts( $rows, $limit = 8 ) {
		$out = [];
		foreach ( array_slice( (array) $rows, 0, $limit ) as $row ) {
			if ( ! is_array( $row ) ) {
				continue;
			}
			$clicks = (int) ( $row['clicks'] ?? 0 );
			$delta  = (int) ( $row['delta_clicks'] ?? 0 );
			$out[]  = [
				'title'  => (string) ( $row['title'] ?? '' ),
				'clicks' => $clicks,
				'delta'  => $delta,
				'trend'  => (string) ( $row['trend'] ?? ( $delta > 0 ? 'up' : ( $delta < 0 ? 'down' : 'flat' ) ) ),
				'editUrl' => ! empty( $row['post_id'] ) ? get_edit_post_link( (int) $row['post_id'], 'raw' ) : '',
			];
		}
		return $out;
	}
}

if ( ! function_exists( 'newsai_insights_registry_payload' ) ) {
	function newsai_insights_registry_payload( $days = 30 ) {
		$days    = max( 7, min( 90, (int) $days ) );
		$is_pro  = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
		$insights = [];
		if ( function_exists( 'newsai_chief_insights_get_cached_data' ) ) {
			try {
				$insights = newsai_chief_insights_get_cached_data( $days, $is_pro );
			} catch ( \Throwable $e ) {
				$insights = [];
			}
		}

		$gsc       = (array) ( $insights['gsc'] ?? [] );
		$series    = (array) ( $insights['chief_gsc_series'] ?? [] );
		$devices   = (array) ( $insights['chief_gsc_devices'] ?? [] );
		$gsc_kpis  = (array) ( $insights['gsc_kpis'] ?? [] );
		$movers    = (array) ( $insights['post_movers'] ?? [] );

		$win = [];
		$lose = [];
		foreach ( $movers as $m ) {
			if ( ! is_array( $m ) ) {
				continue;
			}
			$delta = (int) ( $m['delta_clicks'] ?? 0 );
			$item  = [
				'title'  => (string) ( $m['title'] ?? '' ),
				'clicks' => (int) ( $m['clicks'] ?? 0 ),
				'delta'  => $delta,
				'trend'  => $delta > 0 ? 'up' : ( $delta < 0 ? 'down' : 'flat' ),
			];
			if ( $delta >= 0 ) {
				$win[] = $item;
			} else {
				$lose[] = $item;
			}
		}
		if ( empty( $win ) && empty( $lose ) ) {
			$win  = newsai_insights_registry_slim_posts( $insights['top_articles'] ?? [], 5 );
			$lose = array_filter(
				newsai_insights_registry_slim_posts( $insights['top_discover'] ?? [], 5 ),
				static function ( $r ) {
					return ( $r['delta'] ?? 0 ) < 0;
				}
			);
		}

		$total_clicks = (int) ( $insights['total_clicks'] ?? 0 );
		if ( $total_clicks === 0 ) {
			foreach ( [ 'web', 'discover', 'googleNews' ] as $ch ) {
				$total_clicks += (int) ( $gsc[ $ch ]['clicks'] ?? 0 );
			}
		}

		$channel_bars = [];
		$ch_labels    = [
			'web'        => __( 'Web', 'newsroom-ai-assistant' ),
			'discover'   => __( 'Discover', 'newsroom-ai-assistant' ),
			'googleNews' => __( 'Google News', 'newsroom-ai-assistant' ),
		];
		$ch_max = 1;
		foreach ( $ch_labels as $key => $label ) {
			$clicks = (int) ( $gsc[ $key ]['clicks'] ?? 0 );
			$ch_max = max( $ch_max, $clicks );
			$channel_bars[] = [
				'key'    => $key,
				'label'  => $label,
				'clicks' => $clicks,
				'ctr'    => isset( $gsc[ $key ]['ctr'] ) ? round( (float) $gsc[ $key ]['ctr'] * 100, 1 ) : 0,
			];
		}
		foreach ( $channel_bars as $i => $row ) {
			$channel_bars[ $i ]['pct'] = round( ( $row['clicks'] / $ch_max ) * 100, 1 );
		}

		$device_breakdown = [];
		foreach ( (array) $devices as $dev ) {
			if ( ! is_array( $dev ) ) {
				continue;
			}
			$device_breakdown[] = [
				'device' => (string) ( $dev['device'] ?? '' ),
				'label'  => (string) ( $dev['label'] ?? '' ),
				'clicks' => (int) ( $dev['clicks'] ?? 0 ),
				'pct'    => (float) ( $dev['pct'] ?? 0 ),
				'color'  => (string) ( $dev['color'] ?? '#6366f1' ),
			];
		}

		$ai_ready = function_exists( 'newsai_ai_is_active' ) && newsai_ai_is_active();

		return [
			'version'    => defined( 'NEWSAI_VERSION' ) ? NEWSAI_VERSION : '1',
			'days'       => $days,
			'isPro'      => $is_pro,
			'isDemo'     => ! $is_pro,
			'gscReady'   => $is_pro && function_exists( 'newsai_gsc_data_available' ) && newsai_gsc_data_available(),
			'kpis'       => [
				'totalClicks' => $total_clicks,
				'published'   => (int) ( $insights['post_count'] ?? 0 ),
				'avgFocus'    => (int) ( $insights['avg_focus'] ?? 0 ),
				'avgDiscover' => (int) ( $insights['avg_discover'] ?? 0 ),
				'prevClicks'  => (int) ( $insights['prev_gsc_clicks'] ?? 0 ),
			],
			'channels'   => $gsc,
			'series'     => (array) ( $insights['chief_gsc_series'] ?? [] ),
			'devices'    => (array) ( $insights['chief_gsc_devices'] ?? [] ),
			'deviceBreakdown' => $device_breakdown,
			'channelBars'=> $channel_bars,
			'channelKpis'=> (array) ( $insights['gsc_kpis'] ?? [] ),
			'deviceChannels' => [
				[ 'id' => 'web', 'label' => __( 'Web', 'newsroom-ai-assistant' ) ],
				[ 'id' => 'discover', 'label' => __( 'Discover', 'newsroom-ai-assistant' ) ],
				[ 'id' => 'googleNews', 'label' => __( 'Google News', 'newsroom-ai-assistant' ) ],
			],
			'aiBriefReady' => $is_pro && $ai_ready && current_user_can( 'edit_others_posts' ),
			'canExport'    => current_user_can( 'edit_others_posts' ),
			'winning'    => array_slice( $win, 0, 8 ),
			'losing'     => array_slice( $lose, 0, 8 ),
			'urls'       => [
				'classic' => admin_url( 'admin.php?page=newsai-settings&tab=insights&ui=classic' ),
			],
			'i18n'       => newsai_insights_registry_i18n(),
		];
	}
}
