<?php
/**
 * Enqueue admin and frontend assets. Each builder app loads only on its own page.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Admin;

use SuiteMkt3k\Modules\Settings\Settings_Manager;
use SuiteMkt3k\Security\Capabilities;
use SuiteMkt3k\Security\Nonces;
use SuiteMkt3k\Utils\I18n;
use SuiteMkt3k\Utils\Sanitizer;

defined( 'ABSPATH' ) || exit;

final class Assets {

	public static function register(): void {
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin' ) );
	}

	public static function enqueue_admin( string $hook ): void {
		if ( ! self::is_suitemkt3k_screen( $hook ) ) {
			return;
		}

		I18n::ensure_textdomain();

		$page = Sanitizer::get( 'page', 'key' );
		$view = Sanitizer::get( 'view', 'key' );

		// Media library must be available BEFORE the admin script runs so the
		// `wp.media` global exists when Alpine.js triggers `pickImage()`.
		self::maybe_enqueue_media( $page );

		wp_enqueue_style(
			'suitemkt3k-admin',
			SUITEMKT3K_URL . 'assets/admin/css/suitemkt3k.css',
			array(),
			SUITEMKT3K_VERSION
		);

		wp_enqueue_script(
			'suitemkt3k-alpine',
			SUITEMKT3K_URL . 'assets/admin/js/alpine.min.js',
			array(),
			'3.14.9',
			true
		);

		wp_add_inline_script(
			'suitemkt3k-alpine',
			'window.deferLoadingAlpine=function(callback){window.__wmkAlpineStart=callback;};',
			'before'
		);

		wp_enqueue_script(
			'suitemkt3k-color-input',
			SUITEMKT3K_URL . 'assets/admin/js/wmk-color-input.js',
			array(),
			SUITEMKT3K_VERSION,
			true
		);

		$admin_deps = array( 'suitemkt3k-alpine', 'suitemkt3k-color-input', 'wp-element' );
		if ( in_array( $page, array( 'suitemkt3k-settings', 'suitemkt3k-coupons', 'suitemkt3k-newsletter', 'suitemkt3k-cart-recovery' ), true ) ) {
			$admin_deps[] = 'media-editor';
		}
		$admin_deps = array_merge( $admin_deps, self::maybe_enqueue_coupon_calendar( $page, $view ) );

		if ( in_array( 'suitemkt3k-fullcalendar', $admin_deps, true ) ) {
			wp_add_inline_style( 'suitemkt3k-admin', self::coupon_calendar_theme_css() );
		}

		wp_enqueue_script(
			'suitemkt3k-admin',
			SUITEMKT3K_URL . 'assets/admin/js/suitemkt3k-admin.js',
			$admin_deps,
			SUITEMKT3K_VERSION,
			true
		);

		wp_localize_script(
			'suitemkt3k-admin',
			'SuiteMkt3k',
			array(
				'restUrl'   => esc_url_raw( rest_url( SUITEMKT3K_REST_NAMESPACE . '/' ) ),
				'ajaxUrl'   => esc_url_raw( admin_url( 'admin-ajax.php' ) ),
				'nonce'     => Nonces::create( Nonces::REST_ACTION ),
				'adminNonce'=> Nonces::create( Nonces::ADMIN_ACTION ),
				'page'      => $page,
				'locale'    => I18n::get_active_locale(),
				'locales'   => I18n::available_locales(),
				'can'       => array(
					'manage'   => current_user_can( Capabilities::MANAGE ),
					'edit'     => current_user_can( Capabilities::EDIT_CAMPAIGN ),
					'stats'    => current_user_can( Capabilities::VIEW_STATS ),
					'settings' => current_user_can( Capabilities::EDIT_SETTINGS ),
				),
				'i18n'      => self::js_strings(),
				'currency'  => self::currency_meta(),
				'pluginUrl' => esc_url_raw( SUITEMKT3K_URL ),
				'newsletterTemplates' => \SuiteMkt3k\Email\Email_Renderer::newsletter_presets(),
			)
		);

		self::maybe_enqueue_builder( $page );
		self::maybe_enqueue_chartjs( $page, $view );
		self::maybe_enqueue_email_preview( $page, $view );
	}

	/**
	 * Server-rendered email preview sync (newsletter + cart recovery designers).
	 */
	private static function maybe_enqueue_email_preview( string $page, string $view ): void {
		$map = array(
			'suitemkt3k-newsletter'    => 'edit',
			'suitemkt3k-cart-recovery' => 'template',
			'suitemkt3k-coupons'       => 'email_template',
		);
		if ( ! isset( $map[ $page ] ) || $map[ $page ] !== $view ) {
			return;
		}

		wp_enqueue_script(
			'suitemkt3k-email-preview',
			SUITEMKT3K_URL . 'assets/admin/js/wmk-email-preview.js',
			array( 'suitemkt3k-admin' ),
			SUITEMKT3K_VERSION,
			true
		);

		$company     = (array) Settings_Manager::get( 'company', '', array() );
		$logo_id     = isset( $company['logo_id'] ) ? (int) $company['logo_id'] : 0;
		$logo_url    = $logo_id ? (string) ( wp_get_attachment_image_url( $logo_id, 'medium' ) ?: '' ) : '';
		$footer_ctx  = \SuiteMkt3k\Email\Email_Renderer::footer_context();

		wp_localize_script(
			'suitemkt3k-email-preview',
			'suitemkt3kEmailPreview',
			array(
				'previewName'          => __( 'there', 'suitemkt3k' ),
				'headingFallback'      => __( 'Big news from us', 'suitemkt3k' ),
				'bodyFallback'         => __( 'Your email body will appear here.', 'suitemkt3k' ),
				'ctaFallback'          => __( 'Discover more', 'suitemkt3k' ),
				'unsubscribeFallback'  => __( 'Unsubscribe', 'suitemkt3k' ),
				'defaultAccent'        => '#2AB2E5',
				'logoUrl'              => esc_url_raw( $logo_url ),
				'brand'                => (string) ( $company['name'] ?? get_bloginfo( 'name' ) ),
				'footerText'           => (string) $footer_ctx['footer_text'],
				'footerAddress'        => (string) $footer_ctx['address'],
				'validityTemplate'     => __( 'This discount is valid for {{hours}} hours after the email is sent.', 'suitemkt3k' ),
				'sampleCampaign'       => __( 'Sample campaign', 'suitemkt3k' ),
				'sampleMarketing'      => __( 'Thanks for signing up! Here is your exclusive discount.', 'suitemkt3k' ),
				'sampleCode'           => 'SAMPLE10',
			)
		);
	}

	private static function maybe_enqueue_media( string $page ): void {
		$pages = array( 'suitemkt3k-settings', 'suitemkt3k-coupons', 'suitemkt3k-newsletter', 'suitemkt3k-cart-recovery' );
		if ( in_array( $page, $pages, true ) ) {
			wp_enqueue_media();
		}
	}

	private static function maybe_enqueue_builder( string $page ): void {
		// Newsletter + cart recovery use Alpine.js in PHP views — not the legacy React bundle.
		$map = array(
			'suitemkt3k-coupons' => 'coupon-designer',
		);
		if ( ! isset( $map[ $page ] ) ) {
			return;
		}
		$view = Sanitizer::get( 'view', 'key' );
		if ( 'edit' !== $view && 'template' !== $view ) {
			return;
		}
		$bundle = $map[ $page ];
		$asset_file = SUITEMKT3K_PATH . 'assets/dist/' . $bundle . '.asset.php';
		$deps    = array( 'wp-element', 'wp-i18n', 'wp-components' );
		$version = SUITEMKT3K_VERSION;
		if ( file_exists( $asset_file ) ) {
			$asset   = include $asset_file;
			$deps    = isset( $asset['dependencies'] ) ? (array) $asset['dependencies'] : $deps;
			$version = isset( $asset['version'] ) ? (string) $asset['version'] : $version;
		}
		wp_enqueue_script(
			'suitemkt3k-' . $bundle,
			SUITEMKT3K_URL . 'assets/dist/' . $bundle . '.js',
			$deps,
			$version,
			true
		);
		if ( 'es_ES' === I18n::get_active_locale() && function_exists( 'wp_set_script_translations' ) ) {
			wp_set_script_translations(
				'suitemkt3k-' . $bundle,
				'suitemkt3k',
				SUITEMKT3K_PATH . 'languages'
			);
		}
		if ( file_exists( SUITEMKT3K_PATH . 'assets/dist/' . $bundle . '.css' ) ) {
			wp_enqueue_style(
				'suitemkt3k-' . $bundle,
				SUITEMKT3K_URL . 'assets/dist/' . $bundle . '.css',
				array( 'suitemkt3k-admin' ),
				$version
			);
		}
	}

	/**
	 * @return string[] Script handles to add as dependencies for suitemkt3k-admin.
	 */
	private static function maybe_enqueue_coupon_calendar( string $page, string $view ): array {
		if ( 'suitemkt3k-coupons' !== $page || 'calendar' !== $view ) {
			return array();
		}
		$cal_js = SUITEMKT3K_PATH . 'assets/admin/js/fullcalendar.min.js';
		if ( ! file_exists( $cal_js ) ) {
			return array();
		}

		wp_enqueue_script(
			'suitemkt3k-fullcalendar',
			SUITEMKT3K_URL . 'assets/admin/js/fullcalendar.min.js',
			array(),
			'6.1.17',
			true
		);

		$deps = array( 'suitemkt3k-fullcalendar' );

		if ( 'es_ES' === I18n::get_active_locale() ) {
			$locale_js = SUITEMKT3K_PATH . 'assets/admin/js/fullcalendar-locale-es.global.min.js';
			if ( file_exists( $locale_js ) ) {
				wp_enqueue_script(
					'suitemkt3k-fullcalendar-es',
					SUITEMKT3K_URL . 'assets/admin/js/fullcalendar-locale-es.global.min.js',
					array( 'suitemkt3k-fullcalendar' ),
					'6.1.17',
					true
				);
				$deps[] = 'suitemkt3k-fullcalendar-es';
			}
		}

		return $deps;
	}

	/**
	 * FullCalendar injects dark :root variables when its script loads.
	 * These overrides use fixed colors and load after the main admin stylesheet.
	 */
	private static function coupon_calendar_theme_css(): string {
		return '
.wmk-wrap #wmk-coupon-calendar,
.wmk-wrap #wmk-coupon-calendar .fc {
	--fc-button-bg-color: #ffffff;
	--fc-button-border-color: #E2E8F0;
	--fc-button-text-color: #475569;
	--fc-button-hover-bg-color: rgba(42, 178, 229, 0.08);
	--fc-button-hover-border-color: #2ab2e5;
	--fc-button-active-bg-color: rgba(42, 178, 229, 0.14);
	--fc-button-active-border-color: #2ab2e5;
}
.wmk-wrap #wmk-coupon-calendar .fc .fc-button,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button {
	background: #ffffff !important;
	background-color: #ffffff !important;
	border: 1px solid #E2E8F0 !important;
	color: #475569 !important;
	border-radius: 10px !important;
	box-shadow: none !important;
	font-weight: 600 !important;
}
.wmk-wrap #wmk-coupon-calendar .fc .fc-button:hover,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:hover,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button:hover {
	background: rgba(42, 178, 229, 0.08) !important;
	background-color: rgba(42, 178, 229, 0.08) !important;
	border-color: #2ab2e5 !important;
	color: #2ab2e5 !important;
}
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:not(:disabled).fc-button-active,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:not(:disabled):active,
.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button.fc-button-active {
	background: rgba(42, 178, 229, 0.14) !important;
	background-color: rgba(42, 178, 229, 0.14) !important;
	border-color: #2ab2e5 !important;
	color: #2ab2e5 !important;
}
.wmk-wrap #wmk-coupon-calendar .fc .fc-direction-ltr .fc-button-group > .fc-button:not(:first-child) {
	margin-left: 6px !important;
	border-top-left-radius: 10px !important;
	border-bottom-left-radius: 10px !important;
}
.wmk-wrap #wmk-coupon-calendar .fc .fc-direction-ltr .fc-button-group > .fc-button:not(:last-child) {
	border-top-right-radius: 10px !important;
	border-bottom-right-radius: 10px !important;
}';
	}

	private static function maybe_enqueue_chartjs( string $page, string $view = '' ): void {
		if ( ! in_array( $page, array( 'suitemkt3k', 'suitemkt3k-statistics' ), true ) ) {
			return;
		}
		wp_enqueue_script(
			'suitemkt3k-chartjs',
			SUITEMKT3K_URL . 'assets/admin/js/chart.umd.min.js',
			array(),
			'4.5.0',
			true
		);
		wp_enqueue_script(
			'suitemkt3k-admin-charts',
			SUITEMKT3K_URL . 'assets/admin/js/wmk-admin-charts.js',
			array( 'suitemkt3k-chartjs', 'suitemkt3k-admin' ),
			SUITEMKT3K_VERSION,
			true
		);
	}

	private static function is_suitemkt3k_screen( string $hook ): bool {
		if ( false !== strpos( $hook, 'suitemkt3k' ) ) {
			return true;
		}
		$page = Sanitizer::get( 'page', 'key' );
		return 0 === strpos( $page, 'suitemkt3k' );
	}

	private static function js_strings(): array {
		return array(
			'saving'       => __( 'Saving…', 'suitemkt3k' ),
			'saved'        => __( 'Saved', 'suitemkt3k' ),
			'error'        => __( 'Something went wrong', 'suitemkt3k' ),
			'confirmDelete'=> __( 'Are you sure you want to delete this item? This action cannot be undone.', 'suitemkt3k' ),
			'sending'      => __( 'Sending…', 'suitemkt3k' ),
			'sent'         => __( 'Email sent successfully', 'suitemkt3k' ),
			'testEmail'    => __( 'Send test email', 'suitemkt3k' ),
			'preview'      => __( 'Preview', 'suitemkt3k' ),
			'requiredField'=> __( 'This field is required', 'suitemkt3k' ),
			'invalidEmail' => __( 'Please enter a valid email address', 'suitemkt3k' ),
			'selectLogo'        => __( 'Select logo', 'suitemkt3k' ),
			'selectImage'       => __( 'Select image', 'suitemkt3k' ),
			'mediaUnavailable'  => __( 'Media library is unavailable on this screen.', 'suitemkt3k' ),
			'previewName'       => __( 'there', 'suitemkt3k' ),
			'previewBodyPlaceholder' => __( 'Your email body will appear here.', 'suitemkt3k' ),
			'selectBlogPost'         => __( '— Select a post —', 'suitemkt3k' ),
			'postsLoadFailed'        => __( 'Could not load blog posts.', 'suitemkt3k' ),
			'importSuccess'          => __( 'Post imported into the campaign.', 'suitemkt3k' ),
			'importFailed'           => __( 'Could not import this post.', 'suitemkt3k' ),
			'selectPostFirst'        => __( 'Select a post first.', 'suitemkt3k' ),
		);
	}

	private static function currency_meta(): array {
		if ( function_exists( 'get_woocommerce_currency' ) ) {
			return array(
				'code'   => get_woocommerce_currency(),
				'symbol' => html_entity_decode( get_woocommerce_currency_symbol() ),
			);
		}
		return array( 'code' => 'EUR', 'symbol' => '€' );
	}
}
