<?php

namespace ElementPack\Modules\Notation;

use Elementor\Controls_Manager;
use Elementor\Repeater;
use ElementPack\Base\Element_Pack_Module_Base;
use ElementPack\Modules\Notation\Atomic\Support as Atomic_Support;
use ElementPack\Modules\Notation\Normalizers\Settings_Normalizer;

if (!defined('ABSPATH')) {
    exit;
} // Exit if accessed directly

class Module extends Element_Pack_Module_Base {

    private $atomic_support = null;
    private $settings_normalizer = null;

    public function __construct() {
        parent::__construct();
        $this->add_actions();
    }

    public function get_name() {
        return 'bdt-notation';
    }

    public function register_section($element) {
        $pro_lock = bdt_get_widget_badge( str_replace( 'bdt-', '', $this->get_name() ) );
        $element->start_controls_section(
            'section_element_pack_notation_controls',
            [
                'label' => BDTEP_CP . esc_html__('Notation', 'bdthemes-element-pack') . $pro_lock,
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );
        $element->end_controls_section();
    }


    public function register_controls($widget, $args) {

        $widget->add_control(
            'ep_notation_active',
            [
                'label'              => esc_html__('Notation Effects', 'bdthemes-element-pack'),
                'type'               => Controls_Manager::SWITCHER,
                'render_type'        => 'template',
                'frontend_available' => true,
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'ep_notation_select_type',
            [
                'label'   => esc_html__('Element Type', 'bdthemes-element-pack'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'widget',
                'options' => [
                    'widget' => esc_html__('Widget', 'bdthemes-element-pack'),
                    'custom' => esc_html__('Widget > Custom Selector', 'bdthemes-element-pack'),
                ],
            ]
        );

        $repeater->add_control(
            'ep_notation_custom_selector',
            [
                'label'       => esc_html__('Custom Selector', 'bdthemes-element-pack'),
                'type'        => Controls_Manager::TEXT,
                'dynamic'     => [ 'active' => true ],
                'description' => esc_html__('Please use ID or Class to select your element/elements. ( Example - #select-id, .select-class)', 'bdthemes-element-pack'),
                'condition'   => [
                    'ep_notation_select_type' => 'custom',
                ],
            ]
        );
        $repeater->add_control(
            'ep_notation_type',
            [
                'label'   => esc_html__('Select Style', 'bdthemes-element-pack'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'underline',
                'options' => [
                    'underline'      => esc_html__('Underline', 'bdthemes-element-pack'),
                    'box'            => esc_html__('Box', 'bdthemes-element-pack'),
                    'circle'         => esc_html__('Circle', 'bdthemes-element-pack'),
                    'highlight'      => esc_html__('Highlight', 'bdthemes-element-pack'),
                    'strike-through' => esc_html__('Strike-through', 'bdthemes-element-pack'),
                    'crossed-off'    => esc_html__('Crossed-off', 'bdthemes-element-pack'),
                    'bracket'        => esc_html__('Bracket', 'bdthemes-element-pack'),
                    'soft-wave'      => esc_html__('Soft Wave', 'bdthemes-element-pack'),
                ],
                'render_type'        => 'template',
                'frontend_available' => true,
            ]
        );
        $repeater->add_control(
            'ep_notation_bracket_on',
            [
                'label'       => esc_html__('Bracket On', 'bdthemes-element-pack'),
                'type'        => Controls_Manager::TEXT,
                'dynamic'     => [ 'active' => true ],
                'description' => esc_html__('Value could be a string. Each string being one of these values: left, right, top, bottom. When drawing a bracket, this configures which side(s) of the element to bracket. Default value is left,right', 'bdthemes-element-pack'),
                'default'     => 'left,right',
                'condition'   => [
                    'ep_notation_type' => 'bracket',
                ],
            ]
        );
        $repeater->add_control(
            'ep_notation_color',
            [
                'label' => esc_html__('Color', 'bdthemes-element-pack'),
                'type'  => Controls_Manager::COLOR,
            ]
        );
        $repeater->add_control(
            'ep_notation_stroke_width',
            [
                'label'   => esc_html__('Stroke Width', 'bdthemes-element-pack'),
                'type'    => Controls_Manager::SLIDER,
                'range'   => [
                    'px' => [
                        'min' => 0,
                        'max' => 100,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 1,
                ],
            ]
        );
        
        $repeater->add_control(
            'ep_notation_infinity_loop',
            [
                'label'              => esc_html__('Infinity Loop', 'bdthemes-element-pack') . BDTEP_NC,
                'type'               => Controls_Manager::SWITCHER,
                'frontend_available' => true,
            ]
        );

        $repeater->add_control(
            'ep_notation_anim_duration',
            [
                'label'   => esc_html__('Animation Duration (ms)', 'bdthemes-element-pack'),
                'type'    => Controls_Manager::SLIDER,
                'range'   => [
                    'px' => [
                        'min'  => 0,
                        'max'  => 5000,
                        'step' => 10,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 800,
                ],
            ]
        );

        $repeater->add_control(
            'ep_notation_loop_delay',
            [
                'label'       => esc_html__('Loop Delay (ms)', 'bdthemes-element-pack'),
                'type'        => Controls_Manager::SLIDER,
                'range'       => [
                    'px' => [
                        'min'  => 500,
                        'max'  => 10000,
                        'step' => 100,
                    ],
                ],
                'default'     => [
                    'unit' => 'px',
                    'size' => 5000,
                ],
                'condition'   => [
                    'ep_notation_infinity_loop' => 'yes',
                ],
                'frontend_available' => true,
            ]
        );

        $repeater->add_control(
            'ep_notation_waypoint_offset',
            [
                'label'       => esc_html__('Waypoint Offset', 'bdthemes-element-pack') . BDTEP_NC,
                'description' => esc_html__('Example: bottom-in-view, 90%', 'bdthemes-element-pack'),
                'type'        => Controls_Manager::TEXT,
                'dynamic'     => [ 'active' => true ],
                'placeholder' => 'bottom-in-view',
                'separator'   => 'before',
                'frontend_available' => true,
            ]
        );

        $widget->add_control(
            'ep_notation_list',
            [
                'label'              => esc_html__('Notation Items', 'bdthemes-element-pack'),
                'type'               => Controls_Manager::REPEATER,
                'fields'             => $repeater->get_controls(),
                'prevent_empty'      => false,
                'title_field'        => '{{{ ep_notation_select_type }}}',
                'frontend_available' => true,
                'default'            => [
                    [
                        'ep_notation_select_type' => 'widget',
                    ],
                ],
                'condition'          => [
                    'ep_notation_active' => 'yes',
                ],
                'render_type' => 'template',
            ]
        );
    }


    public function enqueue_scripts() {
        wp_enqueue_script( 'ep-notation' );
    }

    /**
     * Notation boots on elementor/frontend/init — it must load after elementor-frontend.
     */
    public function ensure_frontend_script_deps() {
        $scripts = wp_scripts();

        if ( empty( $scripts->registered['ep-notation'] ) ) {
            return;
        }

        $deps = $scripts->registered['ep-notation']->deps;

        foreach ( [ 'elementor-frontend', 'elementor-frontend-modules' ] as $handle ) {
            if ( wp_script_is( $handle, 'registered' ) && ! in_array( $handle, $deps, true ) ) {
                $deps[] = $handle;
            }
        }

        $scripts->registered['ep-notation']->deps = $deps;
    }

    public function enqueue_editor_scripts() {
        wp_enqueue_script(
            'ep-notation-editor',
            BDTEP_ASSETS_URL . 'js/modules/ep-notation-editor.min.js',
            [ 'elementor-editor', 'elementor-common' ],
            BDTEP_VER,
            true
        );
    }

    public function should_script_enqueue( $widget ) {
        if ( $this->get_settings_normalizer()->normalize( $widget ) ) {
            $this->ensure_frontend_script_deps();
            $this->enqueue_scripts();
        }
    }

    private function is_atomic_widget( $widget ): bool {
        return is_object( $widget ) && method_exists( $widget, 'get_atomic_setting' );
    }

    public function register_atomic_schema( $schema ) {
        if ( ! class_exists( '\Elementor\Modules\AtomicWidgets\PropTypes\Primitives\Boolean_Prop_Type' ) ) {
            return $schema;
        }

        return $this->get_atomic_support()->register_schema( $schema );
    }

    public function register_atomic_controls( $controls, $element ) {
        if ( ! class_exists( '\Elementor\Modules\AtomicWidgets\Controls\Types\Switch_Control' ) ) {
            return $controls;
        }

        $schema = method_exists( $element, 'get_props_schema' ) ? $element::get_props_schema() : [];

        if ( ! isset( $schema[ Atomic_Support::ACTIVE_KEY ] ) ) {
            return $controls;
        }

        return $this->get_atomic_support()->register_controls( $controls );
    }

    public function inject_atomic_notation_data( $widget_content, $widget ) {
        if ( ! $this->is_atomic_widget( $widget ) ) {
            return $widget_content;
        }

        $settings = $this->get_settings_normalizer()->normalize( $widget );

        if ( ! $settings || ! is_string( $widget_content ) || '' === $widget_content ) {
            return $widget_content;
        }

        if ( false !== strpos( $widget_content, 'data-ep-notation=' ) ) {
            return $widget_content;
        }

        $encoded_settings = wp_json_encode( $settings );

        if ( class_exists( '\WP_HTML_Tag_Processor' ) ) {
            $processor = new \WP_HTML_Tag_Processor( $widget_content );

            if ( $processor->next_tag() ) {
                $processor->set_attribute( 'data-ep-notation', $encoded_settings );

                return $processor->get_updated_html();
            }
        }

        return preg_replace(
            '/<([a-zA-Z][^\\s>]*)([^>]*)>/',
            '<$1$2 data-ep-notation="' . esc_attr( $encoded_settings ) . '">',
            $widget_content,
            1
        ) ?: $widget_content;
    }

    public function render_atomic_notation_wrapper_attr( $widget ) {
        if ( ! $this->is_atomic_widget( $widget ) ) {
            return;
        }

        $settings = $this->get_settings_normalizer()->normalize( $widget );

        if ( ! $settings ) {
            return;
        }

        $widget->add_render_attribute( '_wrapper', 'data-ep-notation', wp_json_encode( $settings ) );
    }

    public function maybe_register_atomic_hooks() {
        if ( ! class_exists( '\Elementor\Plugin' ) ) {
            return;
        }

        if ( has_filter( 'elementor/atomic-widgets/props-schema', [ $this, 'register_atomic_schema' ] ) ) {
            return;
        }

        add_filter( 'elementor/atomic-widgets/props-schema', [ $this, 'register_atomic_schema' ], 20 );
        add_filter( 'elementor/atomic-widgets/controls', [ $this, 'register_atomic_controls' ], 30, 2 );
    }

    private function get_atomic_support() {
        if ( null === $this->atomic_support ) {
            $this->atomic_support = new Atomic_Support();
        }

        return $this->atomic_support;
    }

    private function get_settings_normalizer() {
        if ( null === $this->settings_normalizer ) {
            $this->settings_normalizer = new Settings_Normalizer();
        }

        return $this->settings_normalizer;
    }

    protected function add_actions() {

        add_action('elementor/element/common/_section_style/after_section_end', [$this, 'register_section']);
        add_action('elementor/element/common/section_element_pack_notation_controls/before_section_end', [$this, 'register_controls'], 10, 2);
        add_action('elementor/frontend/widget/before_render', [$this, 'should_script_enqueue']);
        add_action('elementor/frontend/widget/before_render', [$this, 'render_atomic_notation_wrapper_attr'], 15);
        add_action('elementor/preview/enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'enqueue_editor_scripts' ] );
        add_filter( 'elementor/widget/render_content', [ $this, 'inject_atomic_notation_data' ], 10, 2 );
        add_action( 'elementor/frontend/after_register_scripts', [ $this, 'ensure_frontend_script_deps' ] );

        if ( did_action( 'elementor/init' ) ) {
            $this->maybe_register_atomic_hooks();
        } else {
            add_action( 'elementor/init', [ $this, 'maybe_register_atomic_hooks' ] );
        }
    }
}
