<?php
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use UM_Elementor\Abstracts\UM_Profile_Base_Widget;
use UM_Elementor\Helpers\UM_Core_Pages;
use UM_Elementor\Helpers\UM_Logged_In_Login;

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

/**
 * UM Login / Register Form Styler
 *
 * Wraps any UM login or register form via [ultimatemember] shortcode and exposes
 * Elementor style controls targeting UM's real rendered HTML classes.
 */
class UM_Login_Register_Styler_Widget extends UM_Profile_Base_Widget {

	public function get_name(): string {
		return 'um-login-register-styler';
	}

	public function get_title(): string {
		return __( 'UM Login & Register Form', 'ultimate-member-widgets-for-elementor' );
	}

	public function get_icon(): string {
		return 'eicon-form-horizontal';
	}

	public function get_keywords(): array {
		return [ 'um', 'ultimate member', 'login', 'register', 'signup', 'form', 'styler' ];
	}

	public function get_script_depends(): array {
		return [ 'umep-styler-editor' ];
	}

	/**
	 * Override: Login/Register widgets are relevant on any page (no profile user required).
	 */
	public function show_in_panel(): bool {
		return true;
	}

	protected function register_controls(): void {

		// ── CONTENT TAB ───────────────────────────────────────────────────────

		$this->start_controls_section(
			'section_form_select',
			[ 'label' => __( 'Form', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->register_um_edit_form_notice();

		$login_hint = UM_Core_Pages::get_core_page_panel_hint_html( 'login', $this->get_title() );
		if ( $login_hint && ! UM_Core_Pages::is_on_core_page( 'login' ) ) {
			$this->add_control(
				'umwfe_login_page_panel_hint',
				[
					'type'            => Controls_Manager::RAW_HTML,
					'raw'             => $login_hint,
					'content_classes' => 'elementor-panel-alert elementor-panel-alert-warning',
					'condition'       => [ 'form_type' => 'login' ],
				]
			);
		}

		$register_hint = UM_Core_Pages::get_core_page_panel_hint_html( 'register', $this->get_title() );
		if ( $register_hint && ! UM_Core_Pages::is_on_core_page( 'register' ) ) {
			$this->add_control(
				'umwfe_register_page_panel_hint',
				[
					'type'            => Controls_Manager::RAW_HTML,
					'raw'             => $register_hint,
					'content_classes' => 'elementor-panel-alert elementor-panel-alert-warning',
					'condition'       => [ 'form_type' => 'register' ],
				]
			);
		}

		$this->add_control(
			'form_type',
			[
				'label'   => __( 'Form Type', 'ultimate-member-widgets-for-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'login',
				'options' => [
					'login'    => __( 'Login', 'ultimate-member-widgets-for-elementor' ),
					'register' => __( 'Registration', 'ultimate-member-widgets-for-elementor' ),
				],
			]
		);

		$this->add_control(
			'form_source',
			[
				'label'   => __( 'Form Selection', 'ultimate-member-widgets-for-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'default',
				'options' => [
					'default' => __( 'Site default form', 'ultimate-member-widgets-for-elementor' ),
					'pick'    => __( 'Choose a specific form…', 'ultimate-member-widgets-for-elementor' ),
				],
			]
		);

		$login_form_options    = self::get_um_form_options( 'login' );
		$register_form_options = self::get_um_form_options( 'register' );

		$this->add_control(
			'login_form_id',
			[
				'label'     => __( 'Login Form', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => $login_form_options,
				'default'   => (string) ( array_key_first( $login_form_options ) ?? '' ),
				'condition' => [
					'form_source' => 'pick',
					'form_type'   => 'login',
				],
			]
		);

		$this->add_control(
			'register_form_id',
			[
				'label'     => __( 'Register Form', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => $register_form_options,
				'default'   => (string) ( array_key_first( $register_form_options ) ?? '' ),
				'condition' => [
					'form_source' => 'pick',
					'form_type'   => 'register',
				],
			]
		);

		$this->add_control(
			'redirect_after_login',
			[
				'label'       => __( 'Redirect After Login (URL)', 'ultimate-member-widgets-for-elementor' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => home_url( '/' ),
				'description' => __( 'Leave empty to use UM\'s default redirect setting.', 'ultimate-member-widgets-for-elementor' ),
				'condition'   => [ 'form_type' => 'login' ],
			]
		);

		$this->add_control(
			'redirect_after_register',
			[
				'label'       => __( 'Redirect After Registration (URL)', 'ultimate-member-widgets-for-elementor' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => home_url( '/' ),
				'description' => __( 'Leave empty to use UM\'s default redirect setting.', 'ultimate-member-widgets-for-elementor' ),
				'condition'   => [ 'form_type' => 'register' ],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_logged_in_login',
			[
				'label'     => __( 'When Already Logged In', 'ultimate-member-widgets-for-elementor' ),
				'condition' => [ 'form_type' => 'login' ],
			]
		);

		$this->add_control(
			'logged_in_login_info',
			[
				'type'            => Controls_Manager::RAW_HTML,
				'raw'             => __( 'On the live site, Ultimate Member normally shows its default logout screen when a logged-in visitor opens the login page. Choose what they see instead when this widget is on the page.', 'ultimate-member-widgets-for-elementor' ),
				'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
			]
		);

		$this->add_control(
			'logged_in_login_mode',
			[
				'label'   => __( 'Display', 'ultimate-member-widgets-for-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'welcome',
				'options' => [
					'welcome'  => __( 'Welcome message & links', 'ultimate-member-widgets-for-elementor' ),
					'redirect' => __( 'Redirect to another page', 'ultimate-member-widgets-for-elementor' ),
					'message'  => __( 'Simple text message', 'ultimate-member-widgets-for-elementor' ),
				],
			]
		);

		$this->add_control(
			'logged_in_login_redirect',
			[
				'label'       => __( 'Redirect URL', 'ultimate-member-widgets-for-elementor' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => UM_Logged_In_Login::get_profile_url() ?: home_url( '/' ),
				'description' => __( 'Logged-in visitors are sent here. Falls back to Redirect After Login above, then the member profile page.', 'ultimate-member-widgets-for-elementor' ),
				'condition'   => [ 'logged_in_login_mode' => 'redirect' ],
			]
		);

		$this->add_control(
			'logged_in_show_avatar',
			[
				'label'     => __( 'Show Avatar', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => [ 'logged_in_login_mode' => 'welcome' ],
			]
		);

		$this->add_control(
			'logged_in_welcome_message',
			[
				'label'       => __( 'Welcome Message', 'ultimate-member-widgets-for-elementor' ),
				'type'        => Controls_Manager::TEXTAREA,
				'default'     => __( 'Welcome back, {display_name}!', 'ultimate-member-widgets-for-elementor' ),
				'description' => __( 'Use {display_name} for the member name.', 'ultimate-member-widgets-for-elementor' ),
				'condition'   => [ 'logged_in_login_mode' => 'welcome' ],
			]
		);

		$this->add_control(
			'logged_in_show_profile_link',
			[
				'label'     => __( 'Profile Link', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => [ 'logged_in_login_mode' => 'welcome' ],
			]
		);

		$this->add_control(
			'logged_in_profile_label',
			[
				'label'     => __( 'Profile Link Label', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => __( 'View profile', 'ultimate-member-widgets-for-elementor' ),
				'condition' => [
					'logged_in_login_mode' => 'welcome',
					'logged_in_show_profile_link' => 'yes',
				],
			]
		);

		$this->add_control(
			'logged_in_show_account_link',
			[
				'label'     => __( 'Account Link', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => [ 'logged_in_login_mode' => 'welcome' ],
			]
		);

		$this->add_control(
			'logged_in_account_label',
			[
				'label'     => __( 'Account Link Label', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => __( 'Manage account', 'ultimate-member-widgets-for-elementor' ),
				'condition' => [
					'logged_in_login_mode' => 'welcome',
					'logged_in_show_account_link' => 'yes',
				],
			]
		);

		$this->add_control(
			'logged_in_show_logout_link',
			[
				'label'     => __( 'Logout Link', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => [ 'logged_in_login_mode' => 'welcome' ],
			]
		);

		$this->add_control(
			'logged_in_logout_label',
			[
				'label'     => __( 'Logout Link Label', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => __( 'Logout', 'ultimate-member-widgets-for-elementor' ),
				'condition' => [
					'logged_in_login_mode' => 'welcome',
					'logged_in_show_logout_link' => 'yes',
				],
			]
		);

		$this->add_control(
			'logged_in_simple_message',
			[
				'label'     => __( 'Message', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::TEXTAREA,
				'default'   => __( 'You are already logged in.', 'ultimate-member-widgets-for-elementor' ),
				'condition' => [ 'logged_in_login_mode' => 'message' ],
			]
		);

		$this->end_controls_section();

		// ── STYLE TAB ─────────────────────────────────────────────────────────

		// ── 1. Form Wrapper ───────────────────────────────────────────────────
		$this->start_controls_section(
			'section_wrapper_style',
			[
				'label' => __( 'Form Wrapper', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_responsive_control(
			'form_max_width',
			[
				'label'      => __( 'Max Width', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%' ],
				'range'      => [
					'px' => [ 'min' => 280, 'max' => 1200 ],
					'%'  => [ 'min' => 20,  'max' => 100  ],
				],
				'selectors'  => [
					'{{WRAPPER}} .um' => 'max-width: {{SIZE}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Background::get_type(),
			[
				'name'     => 'form_background',
				'label'    => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'types'    => [ 'classic', 'gradient' ],
				'selector' => '{{WRAPPER}} .um',
			]
		);

		$this->add_responsive_control(
			'form_padding',
			[
				'label'      => __( 'Padding', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em', '%' ],
				'selectors'  => [
					'{{WRAPPER}} .um' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'form_border',
				'selector' => '{{WRAPPER}} .um',
			]
		);

		$this->add_responsive_control(
			'form_border_radius',
			[
				'label'      => __( 'Border Radius', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} .um' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			[
				'name'     => 'form_shadow',
				'selector' => '{{WRAPPER}} .um',
			]
		);

		$this->end_controls_section();

		// ── 2. Input Fields ───────────────────────────────────────────────────
		$this->start_controls_section(
			'section_inputs_style',
			[
				'label' => __( 'Input Fields', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'input_typography',
				'label'    => __( 'Typography', 'ultimate-member-widgets-for-elementor' ),
				'selector' => '{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
				               {{WRAPPER}} .um-field textarea,
				               {{WRAPPER}} .um-field select',
			]
		);

		$this->start_controls_tabs( 'tabs_input_state' );

		$this->start_controls_tab(
			'tab_input_normal',
			[ 'label' => __( 'Normal', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'input_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
					 {{WRAPPER}} .um-field textarea,
					 {{WRAPPER}} .um-field select' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'input_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
					 {{WRAPPER}} .um-field textarea,
					 {{WRAPPER}} .um-field select' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'input_placeholder_color',
			[
				'label'     => __( 'Placeholder Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input::placeholder'          => 'color: {{VALUE}};',
					'{{WRAPPER}} .um-field input::-webkit-input-placeholder' => 'color: {{VALUE}};',
					'{{WRAPPER}} .um-field input:-ms-input-placeholder'  => 'color: {{VALUE}};',
					'{{WRAPPER}} .um-field textarea::placeholder'        => 'color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'tab_input_focus',
			[ 'label' => __( 'Focus', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'input_focus_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input:focus,
					 {{WRAPPER}} .um-field textarea:focus,
					 {{WRAPPER}} .um-field select:focus' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'input_focus_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input:focus,
					 {{WRAPPER}} .um-field textarea:focus,
					 {{WRAPPER}} .um-field select:focus' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'input_focus_border_color',
			[
				'label'     => __( 'Border Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field input:focus,
					 {{WRAPPER}} .um-field textarea:focus,
					 {{WRAPPER}} .um-field select:focus' => 'border-color: {{VALUE}} !important; outline: none !important;',
				],
			]
		);

		$this->end_controls_tab();
		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'      => 'input_border',
				'separator' => 'before',
				'selector'  => '{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
				                {{WRAPPER}} .um-field textarea,
				                {{WRAPPER}} .um-field select',
			]
		);

		$this->add_responsive_control(
			'input_border_radius',
			[
				'label'      => __( 'Border Radius', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
					 {{WRAPPER}} .um-field textarea,
					 {{WRAPPER}} .um-field select' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'input_padding',
			[
				'label'      => __( 'Padding', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em' ],
				'selectors'  => [
					'{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
					 {{WRAPPER}} .um-field textarea,
					 {{WRAPPER}} .um-field select' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'input_height',
			[
				'label'      => __( 'Input Height', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', 'em' ],
				'range'      => [ 'px' => [ 'min' => 28, 'max' => 100 ] ],
				'selectors'  => [
					'{{WRAPPER}} .um-field input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]),
					 {{WRAPPER}} .um-field select' => 'height: {{SIZE}}{{UNIT}} !important;',
				],
			]
		);

		$this->end_controls_section();

		// ── 3. Field Labels ───────────────────────────────────────────────────
		$this->start_controls_section(
			'section_labels_style',
			[
				'label' => __( 'Field Labels', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'label_typography',
				'selector' => '{{WRAPPER}} .um .um-field .um-field-label > label',
				'fields_options' => [
					'font_size' => [
						'selector_value' => 'font-size: {{SIZE}}{{UNIT}} !important;',
					],
					'line_height' => [
						'selector_value' => 'line-height: {{SIZE}}{{UNIT}} !important;',
					],
				],
			]
		);

		$this->add_control(
			'label_color',
			[
				'label'     => __( 'Label Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um .um-field .um-field-label > label' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'label_icon_color',
			[
				'label'     => __( 'Label Icon Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field-label-icon i' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'label_spacing',
			[
				'label'      => __( 'Bottom Spacing', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [ 'px' => [ 'min' => 0, 'max' => 40 ] ],
				'selectors'  => [
					'{{WRAPPER}} .um .um-field .um-field-label' => 'margin-bottom: {{SIZE}}px !important;',
				],
			]
		);

		$this->add_responsive_control(
			'field_row_spacing',
			[
				'label'      => __( 'Row Spacing (between fields)', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [ 'px' => [ 'min' => 0, 'max' => 60 ] ],
				'selectors'  => [
					'{{WRAPPER}} .um-field' => 'margin-bottom: {{SIZE}}px !important;',
				],
			]
		);

		$this->add_control(
			'required_asterisk_color',
			[
				'label'     => __( 'Required Asterisk Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field-label .um-req' => 'color: {{VALUE}} !important;',
					'{{WRAPPER}} .um-field-label abbr'    => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_section();

		// ── 4. Primary button (submit) ─────────────────────────────────────────
		$this->start_controls_section(
			'section_button_style',
			[
				'label' => __( 'Primary Button (Submit)', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'button_typography',
				'selector' => '{{WRAPPER}} input.um-button[type="submit"],
				               {{WRAPPER}} input[name="um-submit"][type="submit"]',
			]
		);

		$this->start_controls_tabs( 'tabs_button_state' );

		$this->start_controls_tab(
			'tab_button_normal',
			[ 'label' => __( 'Normal', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'button_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} input.um-button[type="submit"],
					 {{WRAPPER}} input[name="um-submit"][type="submit"]' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'button_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} input.um-button[type="submit"],
					 {{WRAPPER}} input[name="um-submit"][type="submit"]' => 'background-color: {{VALUE}} !important; background: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'tab_button_hover',
			[ 'label' => __( 'Hover', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'button_hover_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} input.um-button[type="submit"]:hover,
					 {{WRAPPER}} input[name="um-submit"][type="submit"]:hover' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'button_hover_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} input.um-button[type="submit"]:hover,
					 {{WRAPPER}} input[name="um-submit"][type="submit"]:hover' => 'background-color: {{VALUE}} !important; background: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'button_hover_border_color',
			[
				'label'     => __( 'Border Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} input.um-button[type="submit"]:hover,
					 {{WRAPPER}} input[name="um-submit"][type="submit"]:hover' => 'border-color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_tab();
		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'      => 'button_border',
				'separator' => 'before',
				'selector'  => '{{WRAPPER}} input.um-button[type="submit"],
				                {{WRAPPER}} input[name="um-submit"][type="submit"]',
			]
		);

		$this->add_responsive_control(
			'button_border_radius',
			[
				'label'      => __( 'Border Radius', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} input.um-button[type="submit"],
					 {{WRAPPER}} input[name="um-submit"][type="submit"]' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'button_padding',
			[
				'label'      => __( 'Padding', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em' ],
				'selectors'  => [
					'{{WRAPPER}} input.um-button[type="submit"],
					 {{WRAPPER}} input[name="um-submit"][type="submit"]' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_control(
			'button_full_width',
			[
				'label'        => __( 'Full Width Button', 'ultimate-member-widgets-for-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'selectors'    => [
					'{{WRAPPER}} input.um-button[type="submit"],
					 {{WRAPPER}} input[name="um-submit"][type="submit"]' => 'width: 100% !important; display: block !important;',
				],
			]
		);

		$this->end_controls_section();

		// ── 4b. Secondary button (e.g. Login / Register link in .um-col-alt) ───
		$this->start_controls_section(
			'section_secondary_button_style',
			[
				'label' => __( 'Secondary Button (Outline)', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'secondary_button_typography',
				'selector' => '{{WRAPPER}} a.um-button.um-alt',
			]
		);

		$this->start_controls_tabs( 'tabs_secondary_button_state' );

		$this->start_controls_tab(
			'tab_secondary_button_normal',
			[ 'label' => __( 'Normal', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'secondary_button_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-button.um-alt' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'secondary_button_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-button.um-alt' => 'background-color: {{VALUE}} !important; background: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'tab_secondary_button_hover',
			[ 'label' => __( 'Hover', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->add_control(
			'secondary_button_hover_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-button.um-alt:hover' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'secondary_button_hover_bg_color',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-button.um-alt:hover' => 'background-color: {{VALUE}} !important; background: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'secondary_button_hover_border_color',
			[
				'label'     => __( 'Border Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-button.um-alt:hover' => 'border-color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_tab();
		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'      => 'secondary_button_border',
				'separator' => 'before',
				'selector'  => '{{WRAPPER}} a.um-button.um-alt',
			]
		);

		$this->add_responsive_control(
			'secondary_button_border_radius',
			[
				'label'      => __( 'Border Radius', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} a.um-button.um-alt' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'secondary_button_padding',
			[
				'label'      => __( 'Padding', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em' ],
				'selectors'  => [
					'{{WRAPPER}} a.um-button.um-alt' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->end_controls_section();

		// ── 5. Error & Notice Messages ────────────────────────────────────────
		$this->start_controls_section(
			'section_notices_style',
			[
				'label' => __( 'Error & Notice Messages', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'error_typography',
				'label'    => __( 'Typography', 'ultimate-member-widgets-for-elementor' ),
				'selector' => '{{WRAPPER}} .um-field-error,
				               {{WRAPPER}} .um-notice',
			]
		);

		$this->add_control(
			'field_error_color',
			[
				'label'     => __( 'Field Error Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-field-error' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'notice_error_bg',
			[
				'label'     => __( 'Notice Error Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => [
					'{{WRAPPER}} .um-notice.notice-error,
					 {{WRAPPER}} .um-notice.um-notice-error' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'notice_error_text',
			[
				'label'     => __( 'Notice Error Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-notice.notice-error,
					 {{WRAPPER}} .um-notice.um-notice-error' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'notice_success_bg',
			[
				'label'     => __( 'Notice Success Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-notice.notice-success,
					 {{WRAPPER}} .um-notice.um-notice-success' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'notice_success_text',
			[
				'label'     => __( 'Notice Success Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-notice.notice-success,
					 {{WRAPPER}} .um-notice.um-notice-success' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'notice_border',
				'selector' => '{{WRAPPER}} .um-notice',
			]
		);

		$this->add_responsive_control(
			'notice_border_radius',
			[
				'label'      => __( 'Notice Border Radius', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} .um-notice' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->end_controls_section();

		// ── 6. Footer Links ───────────────────────────────────────────────────
		$this->start_controls_section(
			'section_links_style',
			[
				'label' => __( 'Footer Links', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'link_typography',
				'selector' => '{{WRAPPER}} a.um-forgot-pass,
				               {{WRAPPER}} a.um-link-alt,
				               {{WRAPPER}} .um-login-fields .um-link,
				               {{WRAPPER}} .um-register-fields .um-link,
				               {{WRAPPER}} .um.um-login .um-link,
				               {{WRAPPER}} .um.um-register .um-link,
				               {{WRAPPER}} .um-col-1.um-remember-me label,
				               {{WRAPPER}} label.um-field-checkbox,
				               {{WRAPPER}} label.um-field-checkbox .um-field-checkbox-option',
			]
		);

		$this->add_control(
			'link_color',
			[
				'label'     => __( 'Link Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-forgot-pass,
					 {{WRAPPER}} a.um-link-alt,
					 {{WRAPPER}} .um-login-fields .um-link a,
					 {{WRAPPER}} .um-register-fields .um-link a,
					 {{WRAPPER}} .um.um-login .um-link a,
					 {{WRAPPER}} .um.um-register .um-link a' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'link_hover_color',
			[
				'label'     => __( 'Link Hover Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} a.um-forgot-pass:hover,
					 {{WRAPPER}} a.um-link-alt:hover,
					 {{WRAPPER}} .um-login-fields .um-link a:hover,
					 {{WRAPPER}} .um-register-fields .um-link a:hover,
					 {{WRAPPER}} .um.um-login .um-link a:hover,
					 {{WRAPPER}} .um.um-register .um-link a:hover' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'footer_text_color',
			[
				'label'     => __( 'Footer Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-login-fields .um-link,
					 {{WRAPPER}} .um-register-fields .um-link,
					 {{WRAPPER}} .um.um-login .um-link,
					 {{WRAPPER}} .um.um-register .um-link,
					 {{WRAPPER}} .um-col-alt-b' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_logged_in_welcome_style',
			[
				'label'     => __( 'Logged-in Welcome', 'ultimate-member-widgets-for-elementor' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => [
					'form_type'            => 'login',
					'logged_in_login_mode' => 'welcome',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'logged_in_welcome_typography',
				'selector' => '{{WRAPPER}} .umep-logged-in-welcome-message',
			]
		);

		$this->add_control(
			'logged_in_welcome_text_color',
			[
				'label'     => __( 'Text Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .umep-logged-in-welcome-message' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'logged_in_welcome_link_typography',
				'label'    => __( 'Links Typography', 'ultimate-member-widgets-for-elementor' ),
				'selector' => '{{WRAPPER}} .umep-logged-in-welcome-links a',
			]
		);

		$this->add_control(
			'logged_in_welcome_link_color',
			[
				'label'     => __( 'Link Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .umep-logged-in-welcome-links a' => 'color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();
	}

	/**
	 * Override: No profile user context needed for login/register forms.
	 */
	protected function render(): void {
		if ( ! function_exists( 'UM' ) ) {
			if ( current_user_can( 'edit_pages' ) ) {
				echo '<p>' . esc_html__( 'This widget requires Ultimate Member to be active.', 'ultimate-member-widgets-for-elementor' ) . '</p>';
			}
			return;
		}

		$this->render_profile_widget( 0 );
	}

	protected function render_profile_widget( int $user_id ): void {
		$settings  = $this->get_settings_for_display();
		$form_type = sanitize_key( (string) ( $settings['form_type'] ?? 'login' ) );
		$source    = sanitize_key( (string) ( $settings['form_source'] ?? 'default' ) );

		if ( 'pick' === $source ) {
			$form_id_key = 'login' === $form_type ? 'login_form_id' : 'register_form_id';
			$form_id     = (int) ( $settings[ $form_id_key ] ?? 0 );
		} else {
			$form_id = self::get_default_form_id( $form_type );
		}

		$is_elementor_context = \Elementor\Plugin::$instance->editor->is_edit_mode()
			|| (
				isset( \Elementor\Plugin::$instance->preview )
				&& \Elementor\Plugin::$instance->preview->is_preview_mode()
			);

		// Logged-in users: custom UX on real frontend only, not in editor or preview iframe.
		if ( is_user_logged_in() && ! $is_elementor_context ) {
			if ( 'login' === $form_type ) {
				UM_Logged_In_Login::handle_frontend( $settings );
				return;
			}

			$msg          = __( 'You are already registered and logged in.', 'ultimate-member-widgets-for-elementor' );
			$redirect_url = (string) ( $settings['redirect_after_register']['url'] ?? '' );

			if ( '' !== $redirect_url ) {
				wp_safe_redirect( esc_url_raw( $redirect_url ) );
				exit;
			}

			echo '<p class="umep-form-logged-in-notice">' . esc_html( $msg ) . '</p>';
			return;
		}

		if ( $form_id <= 0 ) {
			if ( $is_elementor_context ) {
				$type_label   = 'login' === $form_type ? __( 'Login', 'ultimate-member-widgets-for-elementor' ) : __( 'Register', 'ultimate-member-widgets-for-elementor' );
				$settings_url = \UM_Elementor\Helpers\UM_Core_Pages::get_um_pages_settings_url();
				if ( 'default' === $source ) {
					echo '<p class="umep-profile-body-empty">';
					echo wp_kses(
						sprintf(
							/* translators: 1: form type (Login/Register), 2: UM Pages settings URL */
							__( 'No default UM %1$s form is configured. Set it under <a href="%2$s" target="_blank" rel="noopener noreferrer">Ultimate Member → Settings → Pages</a>.', 'ultimate-member-widgets-for-elementor' ),
							esc_html( $type_label ),
							esc_url( $settings_url )
						),
						[
							'a' => [
								'href'   => [],
								'target' => [],
								'rel'    => [],
							],
						]
					);
					echo '</p>';
				} else {
					$forms_url = admin_url( 'edit.php?post_type=um_form' );
					echo '<p class="umep-profile-body-empty">';
					echo wp_kses(
						sprintf(
							/* translators: 1: form type, 2: link to UM forms list */
							__( 'No UM %1$s form selected. Choose a form in this widget, or create one in <a href="%2$s" target="_blank" rel="noopener noreferrer">Ultimate Member → Forms</a>.', 'ultimate-member-widgets-for-elementor' ),
							esc_html( $type_label ),
							esc_url( $forms_url )
						),
						[
							'a' => [
								'href'   => [],
								'target' => [],
								'rel'    => [],
							],
						]
					);
					echo '</p>';
				}
			}
			return;
		}

		if ( $is_elementor_context && is_user_logged_in() ) {
			$this->render_with_editor_preview( $form_id, $form_type );
			return;
		}

		echo do_shortcode( '[ultimatemember form_id="' . (int) $form_id . '"]' );
	}

	/**
	 * Render the login/register form inside Elementor editor/preview for a logged-in user.
	 */
	private function render_with_editor_preview( int $form_id, string $form_type ): void {
		echo '<div class="umep-editor-preview-notice" style="'
			. 'background:#1d2939;color:#93c5fd;font-size:11px;font-family:monospace;'
			. 'padding:6px 12px;border-radius:4px;margin-bottom:8px;border-left:3px solid #3b82f6;">'
			. esc_html__( 'Editor preview — this form is shown to guests on the live site.', 'ultimate-member-widgets-for-elementor' )
			. '</div>';

		if ( 'login' === $form_type ) {
			if ( function_exists( 'UM' ) && is_object( UM()->user() ) ) {
				$prev_preview = isset( UM()->user()->preview ) ? UM()->user()->preview : null;
				UM()->user()->preview = true;
				try {
					echo do_shortcode( '[ultimatemember form_id="' . (int) $form_id . '"]' );
				} finally {
					if ( null === $prev_preview ) {
						unset( UM()->user()->preview );
					} else {
						UM()->user()->preview = $prev_preview;
					}
				}
			} else {
				echo do_shortcode( '[ultimatemember form_id="' . (int) $form_id . '"]' );
			}
		} else {
			$allow_filter = static function () {
				return true;
			};
			add_filter( 'um_registration_for_loggedin_users', $allow_filter, PHP_INT_MAX );
			try {
				echo do_shortcode( '[ultimatemember form_id="' . (int) $form_id . '"]' );
			} finally {
				remove_filter( 'um_registration_for_loggedin_users', $allow_filter, PHP_INT_MAX );
			}
		}
	}

	/**
	 * @return array<string, string>
	 */
	public static function get_um_form_options( string $mode ): array {
		$mode = in_array( $mode, [ 'login', 'register' ], true ) ? $mode : 'login';

		$cache_key = 'umep_um_form_options_' . $mode;
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) ) {
			return $cached;
		}

		$forms = get_posts(
			[
				'post_type'      => 'um_form',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				'orderby'        => 'title',
				'order'          => 'ASC',
				'no_found_rows'  => true,
				'meta_query'     => [
					[
						'key'   => '_um_mode',
						'value' => $mode,
					],
				],
			]
		);

		if ( empty( $forms ) ) {
			$opts = [
				'' => 'login' === $mode
					? __( '— No login forms found —', 'ultimate-member-widgets-for-elementor' )
					: __( '— No registration forms found —', 'ultimate-member-widgets-for-elementor' ),
			];
		} else {
			$opts = [];
			foreach ( (array) $forms as $form ) {
				$opts[ (string) $form->ID ] = esc_html( $form->post_title );
			}
		}

		set_transient( $cache_key, $opts, 5 * MINUTE_IN_SECONDS );
		return $opts;
	}

	private static function get_default_form_id( string $mode ): int {
		global $wpdb;
		if ( ! isset( $wpdb ) ) {
			return 0;
		}
		$id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT pm.post_id
				FROM {$wpdb->postmeta} pm
				LEFT JOIN {$wpdb->postmeta} pm2
				  ON pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default'
				WHERE pm.meta_key   = '_um_mode'
				  AND pm.meta_value = %s
				  AND pm2.meta_value = '1'
				LIMIT 1",
				$mode
			)
		);
		if ( $id ) {
			return (int) $id;
		}
		// Fallback: first published form of this mode
		$id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT pm.post_id
				FROM {$wpdb->postmeta} pm
				INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
				WHERE pm.meta_key   = '_um_mode'
				  AND pm.meta_value = %s
				  AND p.post_status = 'publish'
				ORDER BY pm.post_id ASC
				LIMIT 1",
				$mode
			)
		);
		return (int) $id;
	}
}
