<?php
/**
 * VoidPulse admin shell.
 *
 * @package VoidPulse
 */

namespace VoidPulse\Admin;

use VoidPulse\Core\Plugin;
use VoidPulse\Notifications\Analytics;
use VoidPulse\Shared\Asset;

defined( 'ABSPATH' ) || exit;

final class Admin {
	/**
	 * Register admin hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'admin_menu', array( $this, 'menu' ), 60 );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
		add_action( 'wp_dashboard_setup', array( $this, 'dashboard_widget' ) );
		add_action( 'rest_api_init', array( new RestController(), 'register' ) );
		add_action( 'admin_notices', array( $this, 'dependency_notice' ) );
		add_filter( 'plugin_action_links_' . VOIDPULSE_BASENAME, array( $this, 'plugin_action_links' ) );
	}

	/**
	 * Add a direct link from the Plugins screen to the plugin dashboard.
	 *
	 * @param array<string,string> $links Existing plugin-row actions.
	 * @return array<string,string>
	 */
	public function plugin_action_links( $links ) {
		$settings = sprintf(
			'<a href="%1$s" aria-label="%2$s">%3$s</a>',
			esc_url( admin_url( 'admin.php?page=voidpulse' ) ),
			esc_attr__( 'Open the Social Proof Notifications dashboard', 'voidpulse-social-proof-for-woocommerce' ),
			esc_html__( 'Settings', 'voidpulse-social-proof-for-woocommerce' )
		);
		array_unshift( $links, $settings );
		return $links;
	}

	/**
	 * Register the seven-day analytics dashboard widget.
	 *
	 * @return void
	 */
	public function dashboard_widget() {
		if ( ! current_user_can( 'view_voidpulse_analytics' ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'voidpulse_analytics',
			__( 'Social Proof Notifications performance', 'voidpulse-social-proof-for-woocommerce' ),
			array( $this, 'render_dashboard_widget' )
		);
	}

	/**
	 * Render the analytics summary without loading application JavaScript.
	 *
	 * @return void
	 */
	public function render_dashboard_widget() {
		$summary        = Analytics::summary( 7 );
		$days           = isset( $summary['days'] ) && is_array( $summary['days'] ) ? $summary['days'] : array();
		$maximum        = 0;
		$total_activity = absint( $summary['impressions'] ) + absint( $summary['clicks'] ) + absint( $summary['dismissals'] );
		foreach ( $days as $day ) {
			$maximum = max( $maximum, absint( $day['impressions'] ) );
		}
		$analytics_url = add_query_arg(
			array(
				'page' => 'voidpulse',
				'tab'  => 'analytics',
			),
			admin_url( 'admin.php' )
		);

		echo '<div class="voidpulse-dashboard-widget">';
		echo '<div class="voidpulse-widget-intro"><img class="voidpulse-widget-logo" src="' . esc_url( VOIDPULSE_URL . 'public/icon-128x128.png' ) . '" alt="" width="35" height="35"><div><strong>' . esc_html__( 'Last 7 days', 'voidpulse-social-proof-for-woocommerce' ) . '</strong><span>' . esc_html__( 'Live social-proof performance', 'voidpulse-social-proof-for-woocommerce' ) . '</span></div></div>';
		echo '<div class="voidpulse-widget-stats">';
		$this->render_widget_metric( __( 'Impressions', 'voidpulse-social-proof-for-woocommerce' ), number_format_i18n( absint( $summary['impressions'] ) ), 'eye' );
		$this->render_widget_metric( __( 'Clicks', 'voidpulse-social-proof-for-woocommerce' ), number_format_i18n( absint( $summary['clicks'] ) ), 'cursor' );
		$this->render_widget_metric( __( 'Click-through rate', 'voidpulse-social-proof-for-woocommerce' ), number_format_i18n( (float) $summary['ctr'], 2 ) . '%', 'trend' );
		$this->render_widget_metric( __( 'Dismissals', 'voidpulse-social-proof-for-woocommerce' ), number_format_i18n( absint( $summary['dismissals'] ) ), 'close' );
		echo '</div>';

		if ( $total_activity ) {
			echo '<div class="voidpulse-widget-chart"><div class="voidpulse-widget-chart-head"><strong>' . esc_html__( 'Notification views', 'voidpulse-social-proof-for-woocommerce' ) . '</strong><span>' . esc_html__( 'Daily', 'voidpulse-social-proof-for-woocommerce' ) . '</span></div>';
			echo '<div class="voidpulse-widget-bars" role="img" aria-label="' . esc_attr__( 'Daily notification impressions for the last seven days', 'voidpulse-social-proof-for-woocommerce' ) . '">';
			foreach ( $days as $day ) {
				$impressions = absint( $day['impressions'] );
				$height      = $maximum ? max( $impressions ? 7 : 2, round( 100 * $impressions / $maximum ) ) : 2;
				$day_label   = wp_date( 'D', strtotime( $day['date'] . ' 12:00:00 UTC' ) );
				$date_label  = wp_date( 'j M', strtotime( $day['date'] . ' 12:00:00 UTC' ) );
				$title       = sprintf(
					/* translators: 1: weekday label, 2: calendar date, 3: number of impressions. */
					__( '%1$s %2$s: %3$s impressions', 'voidpulse-social-proof-for-woocommerce' ),
					$day_label,
					$date_label,
					number_format_i18n( $impressions )
				);
				echo '<span class="voidpulse-widget-bar"><i style="height:' . esc_attr( $height ) . '%" title="' . esc_attr( $title ) . '"></i><small><strong>' . esc_html( $day_label ) . '</strong><time datetime="' . esc_attr( $day['date'] ) . '">' . esc_html( $date_label ) . '</time></small></span>';
			}
			echo '</div></div>';
		} else {
			echo '<div class="voidpulse-widget-empty"><span aria-hidden="true">↗</span><div><strong>' . esc_html__( 'Your analytics will appear here', 'voidpulse-social-proof-for-woocommerce' ) . '</strong><p>' . esc_html__( 'Publish a campaign to start measuring notification views and clicks.', 'voidpulse-social-proof-for-woocommerce' ) . '</p></div></div>';
		}

		echo '<div class="voidpulse-widget-footer"><span>' . esc_html__( 'Privacy-safe analytics', 'voidpulse-social-proof-for-woocommerce' ) . '</span><a href="' . esc_url( $analytics_url ) . '">' . esc_html__( 'View full analytics', 'voidpulse-social-proof-for-woocommerce' ) . ' <span aria-hidden="true">→</span></a></div>';
		echo '</div>';
	}

	/**
	 * Render one dashboard-widget statistic.
	 *
	 * @param string $label Metric label.
	 * @param string $value Formatted metric value.
	 * @param string $icon  Icon identifier.
	 * @return void
	 */
	private function render_widget_metric( $label, $value, $icon ) {
		$icons = array(
			'eye'    => '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"/><circle cx="12" cy="12" r="2.5"/>',
			'cursor' => '<path d="m5 3 14 9-6 2-3 6Z"/>',
			'trend'  => '<path d="m3 17 6-6 4 4 8-9"/><path d="M15 6h6v6"/>',
			'close'  => '<path d="m7 7 10 10M17 7 7 17"/>',
		);
		echo '<article><div class="voidpulse-widget-metric-head"><span>' . esc_html( $label ) . '</span><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' . wp_kses(
			$icons[ $icon ],
			array(
				'path'   => array( 'd' => true ),
				'circle' => array(
					'cx' => true,
					'cy' => true,
					'r'  => true,
				),
			)
		) . '</svg></div><strong>' . esc_html( $value ) . '</strong></article>';
	}

	/**
	 * Register a WooCommerce child menu.
	 *
	 * @return void
	 */
	public function menu() {
		add_submenu_page(
			'woocommerce',
			__( 'Social Proof Notifications', 'voidpulse-social-proof-for-woocommerce' ),
			__( 'Social Proof Notifications', 'voidpulse-social-proof-for-woocommerce' ),
			'edit_voidpulse_campaigns',
			'voidpulse',
			array( $this, 'render' )
		);
	}

	/**
	 * Render the application mount.
	 *
	 * @return void
	 */
	public function render() {
		echo '<div class="wrap voidpulse-admin"><div id="voidpulse-app">';
		echo '<div class="voidpulse-admin-skeleton" aria-busy="true" aria-label="' . esc_attr__( 'Preparing Social Proof Notifications', 'voidpulse-social-proof-for-woocommerce' ) . '"><div aria-hidden="true">';
		echo '<div class="voidpulse-skeleton-brand"><span class="voidpulse-skeleton-block voidpulse-skeleton-logo"></span><div class="voidpulse-skeleton-brand-copy"><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span></div></div>';
		echo '<div class="voidpulse-skeleton-tabs"><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span></div>';
		echo '<div class="voidpulse-skeleton-stats">';
		for ( $index = 0; $index < 4; $index++ ) {
			echo '<div class="voidpulse-skeleton-card voidpulse-skeleton-stat"><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span></div>';
		}
		echo '</div><div class="voidpulse-skeleton-dashboard"><div class="voidpulse-skeleton-card voidpulse-skeleton-setup"><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span></div><div class="voidpulse-skeleton-card voidpulse-skeleton-campaign"><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span><span class="voidpulse-skeleton-block"></span></div></div>';
		echo '</div></div>';
		echo '</div></div>';
	}

	/**
	 * Load assets only on VoidPulse.
	 *
	 * @param string $hook Hook suffix.
	 * @return void
	 */
	public function assets( $hook ) {
		$asset = Asset::metadata( 'admin' );
		if ( 'index.php' === $hook && current_user_can( 'view_voidpulse_analytics' ) ) {
			wp_enqueue_style( 'voidpulse-admin', VOIDPULSE_URL . 'public/admin.css', array(), $asset['version'] );
			wp_style_add_data( 'voidpulse-admin', 'rtl', 'replace' );
			return;
		}
		if ( 'woocommerce_page_voidpulse' !== $hook ) {
			return;
		}
		$fs             = function_exists( 'voidpulse_fs' ) ? voidpulse_fs() : null;
		$has_paid_plans = is_object( $fs ) && method_exists( $fs, 'has_paid_plan' ) && $fs->has_paid_plan();
		/*
		 * Freemius is_premium() describes the package build, not whether the
		 * licensed optional runtime successfully booted. Using it here makes
		 * an unlicensed premium-capable build render empty Pro mount points.
		 */
		$is_premium     = Plugin::instance()->optional_runtime_active();
		$upgrade_url    = is_object( $fs ) && method_exists( $fs, 'get_upgrade_url' ) ? $fs->get_upgrade_url() : '';
		$upgrade_url    = $upgrade_url ?: admin_url( 'admin.php?page=voidpulse-pricing' );
		wp_enqueue_style( 'voidpulse-admin', VOIDPULSE_URL . 'public/admin.css', array(), $asset['version'] );
		wp_style_add_data( 'voidpulse-admin', 'rtl', 'replace' );
		wp_enqueue_script( 'voidpulse-admin', VOIDPULSE_URL . 'public/admin.js', $asset['dependencies'], $asset['version'], true );
		wp_add_inline_script(
			'voidpulse-admin',
			'window.voidPulseAdmin=' . wp_json_encode(
				array(
					'nonce'       => wp_create_nonce( 'wp_rest' ),
					'root'        => esc_url_raw( rest_url( 'voidpulse/v1/' ) ),
					'woocommerce' => class_exists( 'WooCommerce' ),
					'canPublish'  => current_user_can( 'publish_voidpulse_campaigns' ),
					'canExportAnalytics' => current_user_can( 'export_voidpulse_analytics' ),
					'canManageSettings' => current_user_can( 'manage_voidpulse_settings' ),
					'canManageIntegrations' => current_user_can( 'manage_voidpulse_integrations' ),
					'canManageRoles' => current_user_can( 'manage_options' ),
					'hasPaidPlans' => $has_paid_plans,
					'isPremium'    => $is_premium,
					'pro'          => $is_premium,
					'upgradeUrl'   => esc_url_raw( $upgrade_url ),
					'iconUrl'      => esc_url_raw( VOIDPULSE_URL . 'public/icon-128x128.png' ),
					'preview'      => PreviewOrder::data(),
				),
				JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
			) . ';',
			'before'
		);
	}

	/**
	 * Explain missing WooCommerce only on relevant screens.
	 *
	 * @return void
	 */
	public function dependency_notice() {
		if ( class_exists( 'WooCommerce' ) || ! current_user_can( 'activate_plugins' ) ) {
			return;
		}
		$screen = get_current_screen();
		if ( ! $screen || ( 'plugins' !== $screen->base && 'woocommerce_page_voidpulse' !== $screen->id ) ) {
			return;
		}
		echo '<div class="notice notice-warning is-dismissible"><p>';
		echo esc_html__( 'VoidPulse is active, but WooCommerce is required before genuine store activity can be collected or displayed.', 'voidpulse-social-proof-for-woocommerce' );
		echo '</p></div>';
	}
}
