<?php
/**
 * Admin-side bootstrap: menu pages and React asset enqueues.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class Admin {

	const MENU_SLUG          = 'catalogpilot-ai-studio-for-woocommerce';
	const BULK_SLUG          = 'catalogpilot-ai-studio-for-woocommerce-bulk';
	const HANDLE_SETTINGS    = 'cpais-settings';
	const HANDLE_PRODUCT     = 'cpais-product-panel';
	const HANDLE_BULK        = 'cpais-bulk';
	const HANDLE_TAXONOMY    = 'cpais-taxonomy';

	private static $instance = null;
	private $hook_settings   = '';
	private $hook_bulk       = '';

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'add_meta_boxes', array( $this, 'register_meta_box' ) );
		add_filter( 'plugin_action_links_' . CPAIS_BASENAME, array( $this, 'plugin_action_links' ) );

		add_filter( 'bulk_actions-edit-product', array( $this, 'register_bulk_action' ) );
		add_filter( 'handle_bulk_actions-edit-product', array( $this, 'handle_bulk_action' ), 10, 3 );
		add_action( 'admin_notices', array( $this, 'bulk_action_notice' ) );

		add_action( 'product_cat_edit_form', array( $this, 'render_taxonomy_mount' ), 10, 2 );
		add_action( 'product_tag_edit_form', array( $this, 'render_taxonomy_mount' ), 10, 2 );

		add_action( 'wp_dashboard_setup', array( $this, 'register_dashboard_widget' ) );
	}

	public function register_dashboard_widget() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'cpais_missing_content',
			__( 'CatalogPilot AI Studio for WooCommerce — Missing Content', 'catalogpilot-ai-studio-for-woocommerce' ),
			array( $this, 'render_dashboard_widget' )
		);

		$handle = 'cpais-dashboard-widget';
		wp_register_style( $handle, false, array(), CPAIS_VERSION );
		wp_enqueue_style( $handle );
		wp_add_inline_style(
			$handle,
			'.cpais-dash-widget{margin:0;padding:0;list-style:none}'
			. '.cpais-dash-widget__row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f0f0f1}'
			. '.cpais-dash-widget__row:last-child{border-bottom:0}'
			. '.cpais-dash-widget__label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
			. '.cpais-dash-widget__count{text-decoration:none;color:#50575e}'
			. '.cpais-dash-widget__count--has strong{color:#d63638}'
			. '.cpais-dash-widget .cpais-muted{color:#646970}'
			. '.cpais-dash-widget .cpais-small{font-size:11px}'
		);
	}

	public function render_dashboard_widget() {
		$data = Scanner::scan( 1 ); // Only need counts here, so keep sample tiny.
		$p    = $data['products'];
		$c    = $data['categories'];
		$bulk = admin_url( 'admin.php?page=' . self::BULK_SLUG );

		echo '<p class="cpais-muted">';
		esc_html_e( 'Products or categories missing content — click to open the bulk generator.', 'catalogpilot-ai-studio-for-woocommerce' );
		echo '</p>';

		echo '<ul class="cpais-dash-widget">';
		$this->render_widget_row( __( 'Short descriptions missing', 'catalogpilot-ai-studio-for-woocommerce' ), (int) $p['missing_short_desc'], (int) $p['total'], $bulk );
		$this->render_widget_row( __( 'Long descriptions missing', 'catalogpilot-ai-studio-for-woocommerce' ),  (int) $p['missing_long_desc'],  (int) $p['total'], $bulk );
		$this->render_widget_row( __( 'Featured images missing', 'catalogpilot-ai-studio-for-woocommerce' ),    (int) $p['missing_image'],      (int) $p['total'], $bulk );
		$this->render_widget_row( __( 'Image alt texts missing', 'catalogpilot-ai-studio-for-woocommerce' ),    (int) $p['missing_alt'],        (int) $p['total'], '' );
		$this->render_widget_row( __( 'SEO meta missing', 'catalogpilot-ai-studio-for-woocommerce' ),           (int) $p['missing_seo'],        (int) $p['total'], $bulk );
		$this->render_widget_row( __( 'Category descriptions missing', 'catalogpilot-ai-studio-for-woocommerce' ), (int) $c['missing_cat_desc'], (int) $c['total'], '' );
		echo '</ul>';

		printf(
			'<p><a class="button button-primary" href="%s">%s</a></p>',
			esc_url( $bulk ),
			esc_html__( 'Open Bulk Generator →', 'catalogpilot-ai-studio-for-woocommerce' )
		);
	}

	private function render_widget_row( $label, $count, $total, $link ) {
		$cls      = $count > 0 ? 'cpais-dash-widget__count--has' : '';
		$has_link = $count > 0 && ! empty( $link );
		echo '<li class="cpais-dash-widget__row">';
		echo '<span class="cpais-dash-widget__label">' . esc_html( $label ) . '</span>';
		if ( $has_link ) {
			printf(
				'<a href="%s" class="cpais-dash-widget__count %s"><strong>%d</strong></a>',
				esc_url( $link ),
				esc_attr( $cls ),
				(int) $count
			);
		} else {
			printf(
				'<span class="cpais-dash-widget__count %s"><strong>%d</strong></span>',
				esc_attr( $cls ),
				(int) $count
			);
		}
		if ( $total > 0 ) {
			printf( ' <span class="cpais-muted cpais-small">/ %d</span>', (int) $total );
		}
		echo '</li>';
	}

	public function render_taxonomy_mount( $tag, $taxonomy ) {
		printf(
			'<div id="cpais-taxonomy-root" data-term-id="%d" data-taxonomy="%s"></div>',
			(int) ( is_object( $tag ) ? $tag->term_id : 0 ),
			esc_attr( $taxonomy )
		);
	}

	public function register_menu() {
		$this->hook_settings = add_menu_page(
			__( 'CatalogPilot AI Studio for WooCommerce', 'catalogpilot-ai-studio-for-woocommerce' ),
			__( 'CatalogPilot AI Studio for WooCommerce', 'catalogpilot-ai-studio-for-woocommerce' ),
			'manage_woocommerce',
			self::MENU_SLUG,
			array( $this, 'render_settings_page' ),
			'dashicons-edit-large',
			58
		);

		add_submenu_page(
			self::MENU_SLUG,
			__( 'Settings', 'catalogpilot-ai-studio-for-woocommerce' ),
			__( 'Settings', 'catalogpilot-ai-studio-for-woocommerce' ),
			'manage_woocommerce',
			self::MENU_SLUG,
			array( $this, 'render_settings_page' )
		);

		$this->hook_bulk = add_submenu_page(
			self::MENU_SLUG,
			__( 'Bulk Generate', 'catalogpilot-ai-studio-for-woocommerce' ),
			__( 'Bulk Generate', 'catalogpilot-ai-studio-for-woocommerce' ),
			'manage_woocommerce',
			self::BULK_SLUG,
			array( $this, 'render_bulk_page' )
		);
	}

	public function render_settings_page() {
		echo '<div class="wrap">';
		$this->render_quota_panel();
		echo '<div id="cpais-settings-root"></div></div>';
	}

	private function render_quota_panel() {
		if ( ! Gateway::is_connected() ) {
			return;
		}
		$q = Gateway::quota_cached();
		if ( empty( $q ) || empty( $q['plan'] ) ) {
			return;
		}
		$bar = function ( $used, $limit ) {
			$pct = $limit > 0 ? min( 100, (int) round( ( $used / max( 1, $limit ) ) * 100 ) ) : 0;
			echo '<div style="background:#e2e8f0;border-radius:6px;height:9px;overflow:hidden;margin:0 0 8px"><div style="background:' . ( $pct >= 90 ? '#b42318' : '#2563eb' ) . ';height:100%;width:' . (int) $pct . '%"></div></div>';
		};
		echo '<div class="cpais-quota-panel" style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:16px;margin:12px 0;max-width:520px">';
		echo '<h2 style="margin-top:0;font-size:15px">' . esc_html__( 'Managed AI — usage this cycle', 'catalogpilot-ai-studio-for-woocommerce' );
		echo ' <span style="font-weight:400;color:#64748b;font-size:13px">(' . esc_html( ucfirst( (string) $q['plan'] ) ) . ')</span></h2>';

		if ( ! empty( $q['is_free'] ) ) {
			$used  = (int) ( $q['free_used'] ?? 0 );
			$limit = (int) ( $q['free_limit'] ?? 0 );
			echo '<p style="margin:8px 0 4px;font-size:13px"><strong>' . esc_html__( 'Free trial:', 'catalogpilot-ai-studio-for-woocommerce' ) . '</strong> ' . esc_html( sprintf(
				/* translators: 1: used, 2: limit, 3: remaining */
				__( '%1$d of %2$d uses — %3$d left', 'catalogpilot-ai-studio-for-woocommerce' ),
				$used, $limit, max( 0, $limit - $used )
			) ) . '</p>';
			$bar( $used, $limit );
		} else {
			$used  = (int) ( $q['credits_used'] ?? 0 );
			$limit = (int) ( $q['credits_limit'] ?? 0 );
			echo '<p style="margin:8px 0 4px;font-size:13px"><strong>' . esc_html__( 'AI credits:', 'catalogpilot-ai-studio-for-woocommerce' ) . '</strong> ' . esc_html( sprintf(
				/* translators: 1: used, 2: limit, 3: remaining */
				__( '%1$s of %2$s used — %3$s left', 'catalogpilot-ai-studio-for-woocommerce' ),
				number_format_i18n( $used ), number_format_i18n( $limit ), number_format_i18n( (int) ( $q['credits_left'] ?? 0 ) )
			) ) . '</p>';
			$bar( $used, $limit );
			if ( ! empty( $q['images_limit'] ) ) {
				echo '<p style="margin:8px 0 4px;font-size:13px"><strong>' . esc_html__( 'Images:', 'catalogpilot-ai-studio-for-woocommerce' ) . '</strong> ' . esc_html( sprintf(
					/* translators: 1: used, 2: limit */
					__( '%1$d of %2$d used', 'catalogpilot-ai-studio-for-woocommerce' ),
					(int) ( $q['images_used'] ?? 0 ), (int) $q['images_limit']
				) ) . '</p>';
				$bar( (int) ( $q['images_used'] ?? 0 ), (int) $q['images_limit'] );
			}
		}
		if ( isset( $q['tokens_spent'] ) ) {
			echo '<p style="margin:6px 0 0;font-size:12px;color:#64748b">' . esc_html( sprintf(
				/* translators: %s: token count */
				__( '%s AI tokens used this cycle.', 'catalogpilot-ai-studio-for-woocommerce' ),
				number_format_i18n( (int) $q['tokens_spent'] )
			) ) . '</p>';
		}
		if ( ! empty( $q['resets'] ) ) {
			echo '<p style="margin:4px 0 0;font-size:12px;color:#64748b">' . esc_html( sprintf( /* translators: %s: reset date */ __( 'Resets on %s.', 'catalogpilot-ai-studio-for-woocommerce' ), $q['resets'] ) ) . '</p>';
		}
		echo '</div>';
	}

	public function render_bulk_page() {
		echo '<div class="wrap"><div id="cpais-bulk-root"></div></div>';
	}

	public function register_meta_box() {
		add_meta_box(
			'catalogpilot-ai-studio-for-woocommerce-panel',
			__( 'CatalogPilot AI Studio for WooCommerce', 'catalogpilot-ai-studio-for-woocommerce' ),
			array( $this, 'render_meta_box' ),
			'product',
			'side',
			'high'
		);
	}

	public function render_meta_box( $post ) {
		printf( '<div id="cpais-product-panel-root" data-product-id="%d"></div>', (int) $post->ID );
	}

	public function enqueue_assets( $hook ) {
		$is_settings = ( $hook === $this->hook_settings );
		$is_bulk     = ( $hook === $this->hook_bulk );
		$is_product  = $this->is_product_edit_screen();
		$is_taxonomy = $this->is_taxonomy_edit_screen();

		if ( ! $is_settings && ! $is_bulk && ! $is_product && ! $is_taxonomy ) {
			return;
		}

		$build_dir = CPAIS_PATH . 'admin/build/';
		$build_url = CPAIS_URL . 'admin/build/';

		if ( $is_settings ) {
			$this->enqueue_bundle( self::HANDLE_SETTINGS, 'settings', $build_dir, $build_url );
		}
		if ( $is_bulk ) {
			$this->enqueue_bundle( self::HANDLE_BULK, 'bulk', $build_dir, $build_url );
		}
		if ( $is_product ) {
			$this->enqueue_bundle( self::HANDLE_PRODUCT, 'product-panel', $build_dir, $build_url );
		}
		if ( $is_taxonomy ) {
			$this->enqueue_bundle( self::HANDLE_TAXONOMY, 'taxonomy', $build_dir, $build_url );
		}
	}

	private function is_taxonomy_edit_screen() {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}
		$screen = get_current_screen();
		return $screen
			&& 'edit-tags' === $screen->base
			&& in_array( $screen->taxonomy, array( 'product_cat', 'product_tag' ), true )
			&& ! empty( $_GET['tag_ID'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	}

	private function enqueue_bundle( $handle, $entry, $build_dir, $build_url ) {
		$asset_file = $build_dir . $entry . '.asset.php';
		$js_file    = $build_dir . $entry . '.js';

		if ( ! file_exists( $asset_file ) || ! file_exists( $js_file ) ) {
			add_action(
				'admin_notices',
				function () {
					echo '<div class="notice notice-warning"><p>';
					esc_html_e( 'CatalogPilot AI Studio for WooCommerce: admin assets are not built yet. Run `npm install && npm run build` in the plugin directory.', 'catalogpilot-ai-studio-for-woocommerce' );
					echo '</p></div>';
				}
			);
			return;
		}

		$asset = include $asset_file;

		wp_enqueue_script(
			$handle,
			$build_url . $entry . '.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		foreach ( array( 'style-' . $entry . '.css', $entry . '.css' ) as $css_name ) {
			$css_file = $build_dir . $css_name;
			if ( file_exists( $css_file ) ) {
				wp_enqueue_style(
					$handle,
					$build_url . $css_name,
					array( 'wp-components' ),
					$asset['version']
				);
				break;
			}
		}

		wp_set_script_translations( $handle, 'catalogpilot-ai-studio-for-woocommerce', CPAIS_PATH . 'languages' );

		wp_localize_script(
			$handle,
			'cpaisData',
			array(
				'restUrl'        => esc_url_raw( rest_url( REST_API::NAMESPACE_V1 . '/' ) ),
				'nonce'          => wp_create_nonce( 'wp_rest' ),
				'options'        => REST_API::option_definitions(),
				'adminUrl'       => esc_url_raw( admin_url( 'admin.php?page=' . self::MENU_SLUG ) ),
				'bulkUrl'        => esc_url_raw( admin_url( 'admin.php?page=' . self::BULK_SLUG ) ),
				'seo'            => SEO::integration_label(),
			)
		);
	}

	private function is_product_edit_screen() {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}
		$screen = get_current_screen();
		return $screen && 'product' === $screen->id;
	}

	public function plugin_action_links( $links ) {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=' . self::MENU_SLUG ) ),
			esc_html__( 'Settings', 'catalogpilot-ai-studio-for-woocommerce' )
		);
		array_unshift( $links, $settings_link );
		return $links;
	}

	public function register_bulk_action( $actions ) {
		$actions['cpais_bulk_generate'] = __( 'CatalogPilot AI Studio for WooCommerce: Bulk Generate', 'catalogpilot-ai-studio-for-woocommerce' );
		return $actions;
	}

	public function handle_bulk_action( $redirect_to, $action, $post_ids ) {
		if ( 'cpais_bulk_generate' !== $action ) {
			return $redirect_to;
		}
		$ids = implode( ',', array_map( 'absint', $post_ids ) );
		return add_query_arg(
			array(
				'page'      => self::BULK_SLUG,
				'preselect' => $ids,
			),
			admin_url( 'admin.php' )
		);
	}

	public function bulk_action_notice() {
		// Placeholder for any future flash message.
	}
}
