<?php
/**
 * Shader Overlay Widget
 *
 * @package Sifency_Addons
 * @since   1.0.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Sifency\Traits\Sifency_Addons_Help_Controls;

/**
 * Class Sifency_Addons_Widget_Shader_Overlay
 *
 * Renders an animated WebGL shader canvas behind any Elementor content.
 * All shader parameters are driven by Elementor controls and forwarded
 * to the frontend via a single JSON data attribute.
 */
class Sifency_Addons_Widget_Shader_Overlay extends Widget_Base {
	use Sifency_Addons_Help_Controls;
	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-shader-overlay',
			'title'          => esc_html__( 'Sifency Shader Overlay', 'sifency-addons' ),
			'icon'           => 'eicon-animation',
			'category'       => array( 'sifency-creative-widgets' ),
			'script_depends' => array( 'sifency-shader-overlay-script' ),
			'style_depends'  => array( 'sifency-shader-overlay-style' ),
			'keywords'       => array( 'shader', 'webgl', 'animation', 'overlay', 'background', 'canvas', 'sifency' ),
		);
	}

	/**
	 * Controls
	 */
	protected function register_controls() {

		$this->start_controls_section(
			'section_colours',
			array(
				'label' => esc_html__( 'Colours', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'color_base',
			array(
				'label'   => esc_html__( 'Base Colour', 'sifency-addons' ),
				'type'    => Controls_Manager::COLOR,
				'default' => '#F4793A',
			)
		);

		$this->add_control(
			'color_light',
			array(
				'label'   => esc_html__( 'Highlight Colour', 'sifency-addons' ),
				'type'    => Controls_Manager::COLOR,
				'default' => '#F1E6D0',
			)
		);

		$this->end_controls_section();

		// ── Section: Animation ───────────────────────
		$this->start_controls_section(
			'section_animation',
			array(
				'label' => esc_html__( 'Animation', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'speed',
			array(
				'label'   => esc_html__( 'Speed', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.1,
						'max'  => 3.0,
						'step' => 0.05,
					),
				),
				'default' => array( 'size' => 1.0 ),
			)
		);

		$this->add_control(
			'warp',
			array(
				'label'       => esc_html__( 'Flow Warp', 'sifency-addons' ),
				'description' => esc_html__( 'Flow-field distortion strength.', 'sifency-addons' ),
				'type'        => Controls_Manager::SLIDER,
				'range'       => array(
					'px' => array(
						'min'  => 0.0,
						'max'  => 0.5,
						'step' => 0.01,
					),
				),
				'default'     => array( 'size' => 0.12 ),
			)
		);

		$this->add_control(
			'octaves',
			array(
				'label'   => esc_html__( 'Noise Detail (Octaves)', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 1,
						'max'  => 8,
						'step' => 1,
					),
				),
				'default' => array( 'size' => 5 ),
			)
		);

		$this->add_control(
			'pause_offscreen',
			array(
				'label'        => esc_html__( 'Pause When Off-Screen', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'sifency-addons' ),
				'label_off'    => esc_html__( 'No', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->end_controls_section();

		// ── Section: Post-Processing ─────────────────
		$this->start_controls_section(
			'section_postprocess',
			array(
				'label' => esc_html__( 'Post-Processing', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'grain',
			array(
				'label'   => esc_html__( 'Film Grain', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.0,
						'max'  => 0.15,
						'step' => 0.005,
					),
				),
				'default' => array( 'size' => 0.035 ),
			)
		);

		$this->add_control(
			'vignette',
			array(
				'label'   => esc_html__( 'Vignette Darkness', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.0,
						'max'  => 1.0,
						'step' => 0.01,
					),
				),
				'default' => array( 'size' => 0.75 ),
			)
		);

		$this->add_control(
			'scan',
			array(
				'label'   => esc_html__( 'Scan-Line Intensity', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.0,
						'max'  => 0.1,
						'step' => 0.001,
					),
				),
				'default' => array( 'size' => 0.015 ),
			)
		);

		$this->end_controls_section();

		// ── Section: Layout ──────────────────────────
		$this->start_controls_section(
			'section_layout',
			array(
				'label' => esc_html__( 'Layout', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_responsive_control(
			'canvas_height',
			array(
				'label'      => esc_html__( 'Height (px)', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vh' ),
				'range'      => array(
					'px' => array(
						'min'  => 100,
						'max'  => 1200,
						'step' => 10,
					),
					'vh' => array(
						'min'  => 10,
						'max'  => 100,
						'step' => 1,
					),
				),
				'default'    => array(
					'size' => 500,
					'unit' => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-shader-canvas' => 'height: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .sifency-shader-wrap'   => 'min-height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'content_align_h',
			array(
				'label'     => esc_html__( 'Content Horizontal Align', 'sifency-addons' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'flex-start' => array(
						'title' => esc_html__( 'Left', 'sifency-addons' ),
						'icon'  => 'eicon-h-align-left',
					),
					'center'     => array(
						'title' => esc_html__( 'Center', 'sifency-addons' ),
						'icon'  => 'eicon-h-align-center',
					),
					'flex-end'   => array(
						'title' => esc_html__( 'Right', 'sifency-addons' ),
						'icon'  => 'eicon-h-align-right',
					),
				),
				'default'   => 'center',
				'selectors' => array(
					'{{WRAPPER}} .sifency-shader-content' => 'align-items: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'content_align_v',
			array(
				'label'     => esc_html__( 'Content Vertical Align', 'sifency-addons' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'flex-start' => array(
						'title' => esc_html__( 'Top', 'sifency-addons' ),
						'icon'  => 'eicon-v-align-top',
					),
					'center'     => array(
						'title' => esc_html__( 'Middle', 'sifency-addons' ),
						'icon'  => 'eicon-v-align-middle',
					),
					'flex-end'   => array(
						'title' => esc_html__( 'Bottom', 'sifency-addons' ),
						'icon'  => 'eicon-v-align-bottom',
					),
				),
				'default'   => 'center',
				'selectors' => array(
					'{{WRAPPER}} .sifency-shader-content' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Section: Overlay Content ─────────────────
		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Overlay Content', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'heading',
			array(
				'label'       => esc_html__( 'Heading', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Shader Overlay', 'sifency-addons' ),
				'placeholder' => esc_html__( 'Enter heading…', 'sifency-addons' ),
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_control(
			'subheading',
			array(
				'label'       => esc_html__( 'Subheading', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXTAREA,
				'default'     => '',
				'placeholder' => esc_html__( 'Enter subheading…', 'sifency-addons' ),
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_control(
			'heading_tag',
			array(
				'label'   => esc_html__( 'Heading Tag', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'h1' => 'H1',
					'h2' => 'H2',
					'h3' => 'H3',
					'h4' => 'H4',
					'h5' => 'H5',
					'h6' => 'H6',
					'p'  => 'p',
				),
				'default' => 'h2',
			)
		);

		$this->end_controls_section();

		/*
		 ══════════════════════════════════════════
		 *  TAB STYLE
		 * ══════════════════════════════════════════ */

		// ── Style: Wrapper ───────────────────────────
		$this->start_controls_section(
			'style_wrapper',
			array(
				'label' => esc_html__( 'Wrapper', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'sifency-addons' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-shader-wrap'   => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}; overflow: hidden;',
					'{{WRAPPER}} .sifency-shader-canvas' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'wrapper_shadow',
				'selector' => '{{WRAPPER}} .sifency-shader-wrap',
			)
		);

		$this->end_controls_section();

		// ── Style: Heading ───────────────────────────
		$this->start_controls_section(
			'style_heading',
			array(
				'label'     => esc_html__( 'Heading', 'sifency-addons' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'heading!' => '' ),
			)
		);

		$this->add_control(
			'heading_color',
			array(
				'label'     => esc_html__( 'Colour', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#F1E6D0',
				'selectors' => array(
					'{{WRAPPER}} .sifency-shader-heading' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'heading_typography',
				'selector' => '{{WRAPPER}} .sifency-shader-heading',
			)
		);

		$this->add_responsive_control(
			'heading_margin',
			array(
				'label'      => esc_html__( 'Margin', 'sifency-addons' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-shader-heading' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Style: Subheading ────────────────────────
		$this->start_controls_section(
			'style_subheading',
			array(
				'label'     => esc_html__( 'Subheading', 'sifency-addons' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'subheading!' => '' ),
			)
		);

		$this->add_control(
			'subheading_color',
			array(
				'label'     => esc_html__( 'Colour', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => 'rgba(241,230,208,0.75)',
				'selectors' => array(
					'{{WRAPPER}} .sifency-shader-subheading' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'subheading_typography',
				'selector' => '{{WRAPPER}} .sifency-shader-subheading',
			)
		);

		$this->add_responsive_control(
			'subheading_margin',
			array(
				'label'      => esc_html__( 'Margin', 'sifency-addons' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-shader-subheading' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Style: Content Padding ───────────────────
		$this->start_controls_section(
			'style_content',
			array(
				'label' => esc_html__( 'Content Area', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'content_padding',
			array(
				'label'      => esc_html__( 'Padding', 'sifency-addons' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'default'    => array(
					'top'    => 40,
					'right'  => 40,
					'bottom' => 40,
					'left'   => 40,
					'unit'   => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-shader-content' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/*
	 ─────────────────────────────────────────────
	 *  Render
	 * ───────────────────────────────────────────── */

	protected function render() {
		$settings = $this->get_settings_for_display();

		// Build the config array forwarded to JS.
		$config = array(
			'colorBase'      => sanitize_hex_color( $settings['color_base'] ?? '#F4793A' ) ?: '#F4793A',
			'colorLight'     => sanitize_hex_color( $settings['color_light'] ?? '#F1E6D0' ) ?: '#F1E6D0',
			'speed'          => floatval( $settings['speed']['size'] ?? 1.0 ),
			'warp'           => floatval( $settings['warp']['size'] ?? 0.12 ),
			'octaves'        => absint( $settings['octaves']['size'] ?? 5 ),
			'grain'          => floatval( $settings['grain']['size'] ?? 0.035 ),
			'vignette'       => floatval( $settings['vignette']['size'] ?? 0.75 ),
			'scan'           => floatval( $settings['scan']['size'] ?? 0.015 ),
			'pauseOffscreen' => ( 'yes' === ( $settings['pause_offscreen'] ?? 'yes' ) ),
		);

		$heading    = $settings['heading'] ?? '';
		$subheading = $settings['subheading'] ?? '';
		$tag        = in_array( $settings['heading_tag'] ?? 'h2', array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p' ), true )
			? $settings['heading_tag']
			: 'h2';
		?>
		<div
			class="sifency-shader-wrap"
			data-shader-config="<?php echo esc_attr( wp_json_encode( $config ) ); ?>"
		>
			<canvas class="sifency-shader-canvas"></canvas>

			<div class="sifency-shader-content">
				<?php if ( ! empty( $heading ) ) : ?>
					<<?php echo esc_attr( $tag ); ?> class="sifency-shader-heading">
						<?php echo esc_html( $heading ); ?>
					</<?php echo esc_attr( $tag ); ?>>
				<?php endif; ?>

				<?php if ( ! empty( $subheading ) ) : ?>
					<p class="sifency-shader-subheading">
						<?php echo wp_kses_post( $subheading ); ?>
					</p>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/*
	 ─────────────────────────────────────────────
	 *  Editor / Live Preview (JS template)
	 * ───────────────────────────────────────────── */

	protected function content_template() {
		?>
		<#
		var config = {
			colorBase:     settings.color_base  || '#F4793A',
			colorLight:    settings.color_light || '#F1E6D0',
			speed:         parseFloat( settings.speed.size    ) || 1.0,
			warp:          parseFloat( settings.warp.size     ) || 0.12,
			octaves:       parseInt(   settings.octaves.size  ) || 5,
			grain:         parseFloat( settings.grain.size    ) || 0.035,
			vignette:      parseFloat( settings.vignette.size ) || 0.75,
			scan:          parseFloat( settings.scan.size     ) || 0.015,
			pauseOffscreen: ( settings.pause_offscreen === 'yes' ),
		};

		var allowedTags = ['h1','h2','h3','h4','h5','h6','p'];
		var tag = allowedTags.includes( settings.heading_tag ) ? settings.heading_tag : 'h2';
		#>
		<div
			class="sifency-shader-wrap"
			data-shader-config="{{ JSON.stringify( config ) }}"
		>
			<canvas class="sifency-shader-canvas"></canvas>
			<div class="sifency-shader-content">
				<# if ( settings.heading ) { #>
					<{{{ tag }}} class="sifency-shader-heading">{{{ settings.heading }}}</{{{ tag }}}>
				<# } #>
				<# if ( settings.subheading ) { #>
					<p class="sifency-shader-subheading">{{{ settings.subheading }}}</p>
				<# } #>
			</div>
		</div>
		<?php
	}
}
