<?php
/**
 * Leave Stoper Admin Page
 *
 * Renders the dedicated settings submenu for the Leave Stoper feature.
 *
 * @package Niwa_AI
 * @since   0.10.0
 */

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

class Niwa_AI_Leave_Stoper_Settings {

	const OPTION_KEY = Niwa_AI_Constants::OPT_UI_SETTINGS;

	/**
	 * Register hooks.
	 */
	public function register_hooks() {
		add_action( 'admin_menu', array( $this, 'add_submenu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
	}

	/**
	 * Enqueue assets for the Leave Stoper settings page.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 * @return void
	 */
	public function enqueue_admin_assets( $hook_suffix ) {
		if ( 'niwa-ai_page_niwa-ai-leave-stoper' !== $hook_suffix ) {
			return;
		}

		wp_enqueue_media();
	}

	/**
	 * Add submenu page under Niwa AI.
	 */
	public function add_submenu() {
		add_submenu_page(
			'niwa-ai',
			__( 'Leave Stoper', 'niwa-ai' ),
			__( 'Leave Stoper', 'niwa-ai' ),
			'manage_options',
			'niwa-ai-leave-stoper',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Render the Leave Stoper settings page.
	 */
	public function render_page() {
		$stored = get_option( self::OPTION_KEY, array() );
		$opts   = wp_parse_args(
			is_array( $stored ) ? $stored : array(),
			Niwa_AI_UI_Settings::get_leave_stoper_defaults()
		);
		$n      = self::OPTION_KEY;

		echo '<div class="wrap niwa-wrap">';

		echo '<div class="niwa-page-header">';
		echo '<div class="niwa-page-header__icon">';
		echo '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>';
		echo '</div>';
		echo '<div class="niwa-page-header__text">';
		echo '<h1 class="niwa-page-header__title">' . esc_html__( 'Leave Stoper', 'niwa-ai' ) . '</h1>';
		echo '<p class="niwa-page-header__subtitle">' . esc_html__( 'Exit intent and inactivity message settings.', 'niwa-ai' ) . '</p>';
		echo '</div>';
		echo '</div>';

		echo '<form method="post" action="options.php">';
		settings_fields( 'niwa_ai_ui_group' );
		echo '<input type="hidden" name="' . esc_attr( $n . '[' . Niwa_AI_UI_Settings::FORM_FIELD . ']' ) . '" value="' . esc_attr( Niwa_AI_UI_Settings::FORM_LEAVE_STOPER ) . '" />';

		echo '<div class="niwa-card">';
		echo '<details class="niwa-collapsible" open>';
		echo '<summary>';
		echo '<div class="niwa-card__header">';
		echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg></div>';
		echo '<h2 class="niwa-card__title">' . esc_html__( 'Trigger & Timing', 'niwa-ai' ) . '</h2>';
		echo '</div>';
		echo '</summary>';
		echo '<div class="niwa-card__body">';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-toggle">';
		echo '<input type="checkbox" name="' . esc_attr( $n . '[leave_stoper_enabled]' ) . '" value="1" ' . checked( $opts['leave_stoper_enabled'], 1, false ) . ' />';
		echo esc_html__( 'Enable Leave Stoper', 'niwa-ai' );
		echo '</label>';
		echo '<span class="niwa-field__hint">' . esc_html__( 'Detect exit intent or inactivity and show a message.', 'niwa-ai' ) . '</span>';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Trigger Type', 'niwa-ai' ) . '</label>';
		echo '<select name="' . esc_attr( $n . '[leave_stoper_trigger_type]' ) . '">';
		$trigger_options = array(
			'exit_intent' => __( 'Exit Intent (mouse leaves page)', 'niwa-ai' ),
			'inactivity'  => __( 'Inactivity Timeout', 'niwa-ai' ),
			'both'        => __( 'Both', 'niwa-ai' ),
		);
		foreach ( $trigger_options as $val => $lbl ) {
			echo '<option value="' . esc_attr( $val ) . '"' . selected( $opts['leave_stoper_trigger_type'], $val, false ) . '>' . esc_html( $lbl ) . '</option>';
		}
		echo '</select>';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Inactivity Timeout (sec)', 'niwa-ai' ) . '</label>';
		echo '<input type="number" name="' . esc_attr( $n . '[leave_stoper_inactivity_timeout]' ) . '" value="' . esc_attr( $opts['leave_stoper_inactivity_timeout'] ) . '" min="10" max="300" />';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Open Delay (ms)', 'niwa-ai' ) . '</label>';
		echo '<input type="number" name="' . esc_attr( $n . '[leave_stoper_open_delay]' ) . '" value="' . esc_attr( $opts['leave_stoper_open_delay'] ) . '" min="100" max="2000" />';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Session Cooldown (min)', 'niwa-ai' ) . '</label>';
		echo '<input type="number" name="' . esc_attr( $n . '[leave_stoper_session_cooldown]' ) . '" value="' . esc_attr( $opts['leave_stoper_session_cooldown'] ) . '" min="1" max="120" />';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-toggle">';
		echo '<input type="checkbox" name="' . esc_attr( $n . '[leave_stoper_disable_on_mobile]' ) . '" value="1" ' . checked( $opts['leave_stoper_disable_on_mobile'], 1, false ) . ' />';
		echo esc_html__( 'Disable on Mobile', 'niwa-ai' );
		echo '</label>';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-toggle">';
		echo '<input type="checkbox" name="' . esc_attr( $n . '[leave_stoper_test_mode]' ) . '" value="1" ' . checked( $opts['leave_stoper_test_mode'], 1, false ) . ' />';
		echo esc_html__( 'Test Mode', 'niwa-ai' );
		echo '</label>';
		echo '<span class="niwa-field__hint">' . esc_html__( 'Triggers every time (no cooldown).', 'niwa-ai' ) . '</span>';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-toggle">';
		echo '<input type="checkbox" name="' . esc_attr( $n . '[leave_stoper_reset_on_page_load]' ) . '" value="1" ' . checked( $opts['leave_stoper_reset_on_page_load'], 1, false ) . ' />';
		echo esc_html__( 'Reset on Page Load', 'niwa-ai' );
		echo '</label>';
		echo '</div>';

		echo '</div>';
		echo '</details>';
		echo '</div>';

		echo '<div class="niwa-card">';
		echo '<details class="niwa-collapsible" open>';
		echo '<summary>';
		echo '<div class="niwa-card__header">';
		echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>';
		echo '<h2 class="niwa-card__title">' . esc_html__( 'Message & Media', 'niwa-ai' ) . '</h2>';
		echo '</div>';
		echo '</summary>';
		echo '<div class="niwa-card__body">';

		$this->media_row( $n, 'leave_stoper_media_id', __( 'Media (Image/GIF/Video)', 'niwa-ai' ), $opts );

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Message Text', 'niwa-ai' ) . '</label>';
		echo '<span class="niwa-field__hint">' . esc_html__( 'The message shown when Leave Stoper triggers.', 'niwa-ai' ) . '</span>';
		echo '<textarea name="' . esc_attr( $n . '[leave_stoper_message_text]' ) . '" rows="3" class="niwa-input--wide" style="max-width:100%;">' . esc_textarea( $opts['leave_stoper_message_text'] ) . '</textarea>';
		echo '</div>';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html__( 'Alt Text (optional)', 'niwa-ai' ) . '</label>';
		echo '<span class="niwa-field__hint">' . esc_html__( 'Alt text for accessibility. If empty, attachment alt text will be used.', 'niwa-ai' ) . '</span>';
		echo '<input type="text" name="' . esc_attr( $n . '[leave_stoper_alt_text]' ) . '" value="' . esc_attr( $opts['leave_stoper_alt_text'] ) . '" class="niwa-input--wide" />';
		echo '</div>';

		echo '</div>';
		echo '</details>';
		echo '</div>';

		echo '<div style="margin-top:16px;">';
		submit_button( __( 'Save Settings', 'niwa-ai' ), 'primary niwa-btn niwa-btn--primary', 'submit', false );
		echo '</div>';

		echo '</form>';
		echo '</div>';
	}

	/**
	 * Render media selector row for Leave Stoper.
	 *
	 * @param string $n     Option key namespace.
	 * @param string $key   Option field key.
	 * @param string $label Row label.
	 * @param array  $opts  Current options.
	 * @return void
	 */
	private function media_row( $n, $key, $label, $opts ) {
		$media_id   = isset( $opts[ $key ] ) ? absint( $opts[ $key ] ) : 0;
		$media_url  = $media_id ? wp_get_attachment_url( $media_id ) : '';
		$mime_type  = $media_id ? (string) get_post_mime_type( $media_id ) : '';
		$file_name  = $media_url ? basename( $media_url ) : '';
		$is_video   = $mime_type && strpos( $mime_type, 'video/' ) === 0;
		$is_image   = $mime_type && strpos( $mime_type, 'image/' ) === 0;
		$hide_style = $media_id ? '' : ' style="display:none;"';

		echo '<div class="niwa-field">';
		echo '<label class="niwa-field__label">' . esc_html( $label ) . '</label>';
		echo '<span class="niwa-field__hint">' . esc_html__( 'Choose an image, GIF, or video shown with the Leave Stoper message.', 'niwa-ai' ) . '</span>';
		echo '<input type="hidden" name="' . esc_attr( $n . '[' . $key . ']' ) . '" id="niwa_leave_stoper_media_id" value="' . esc_attr( $media_id ) . '" />';
		echo '<div style="display:flex;gap:8px;margin-bottom:8px;">';
		echo '<button type="button" class="button" id="niwa_leave_stoper_upload_btn">' . esc_html__( 'Choose Media', 'niwa-ai' ) . '</button>';
		echo '<button type="button" class="button" id="niwa_leave_stoper_remove_btn"' . $hide_style . '>' . esc_html__( 'Remove', 'niwa-ai' ) . '</button>';
		echo '</div>';
		echo '<div id="niwa_leave_stoper_preview" style="margin-top:4px;">';

		if ( $media_url ) {
			if ( $is_image ) {
				echo '<img src="' . esc_url( $media_url ) . '" alt="" style="max-width:200px;max-height:150px;display:block;border-radius:8px;" />';
			} elseif ( $is_video ) {
				echo '<video controls style="max-width:200px;max-height:150px;display:block;border-radius:8px;">';
				echo '<source src="' . esc_url( $media_url ) . '" type="' . esc_attr( $mime_type ) . '" />';
				echo '</video>';
			}

			if ( $file_name ) {
				echo '<p style="margin:6px 0 0;font-size:13px;"><strong>' . esc_html( $file_name ) . '</strong></p>';
			}
		}

		echo '</div>';
		echo '<script>
		jQuery(function($) {
			var frame = null;
			var $mediaId = $("#niwa_leave_stoper_media_id");
			var $preview = $("#niwa_leave_stoper_preview");
			var $remove = $("#niwa_leave_stoper_remove_btn");

			$("#niwa_leave_stoper_upload_btn").on("click", function(e) {
				e.preventDefault();

				if (frame) {
					frame.open();
					return;
				}

				frame = wp.media({
					title: "Choose Leave Stoper Media",
					button: { text: "Use this media" },
					multiple: false
				});

				frame.on("select", function() {
					var attachment = frame.state().get("selection").first().toJSON();
					var attachmentType = attachment.type || "";
					var attachmentMime = attachment.mime || "";
					var isImage = attachmentType === "image" || attachmentMime.indexOf("image/") === 0;
					var isVideo = attachmentType === "video" || attachmentMime.indexOf("video/") === 0;

					if (!isImage && !isVideo) {
						window.alert("Please choose an image, GIF, or video file.");
						return;
					}

					var preview = "";

					$mediaId.val(attachment.id);

					if (isImage) {
						preview = "<img src=\"" + attachment.url + "\" alt=\"\" style=\"max-width:200px;max-height:150px;display:block;border-radius:8px;\" />";
					} else if (isVideo) {
						var mime = attachment.mime || "video/mp4";
						preview = "<video controls style=\"max-width:200px;max-height:150px;display:block;border-radius:8px;\"><source src=\"" + attachment.url + "\" type=\"" + mime + "\" /></video>";
					}

					if (attachment.filename) {
						preview += "<p style=\"margin:6px 0 0;font-size:13px;\"><strong>" + attachment.filename + "</strong></p>";
					}

					$preview.html(preview);
					$remove.show();
				});

				frame.open();
			});

			$remove.on("click", function(e) {
				e.preventDefault();
				$mediaId.val("");
				$preview.empty();
				$remove.hide();
			});
		});
		</script>';
		echo '</div>';
	}
}
