<?php 

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

class X_Toast_Notification extends \Bricks\Element {

  // Element properties
  public $category     = 'extras';
	public $name         = 'xtoastnotification';
	public $icon         = 'ti-announcement';
	public $css_selector = '';
	public $scripts      = [];
  public $nestable = true;

  
  public function get_label() {
	  return esc_html__( 'Toast Notification', 'bricksextras' );
  }

  public function get_keywords() {
		return [ 'toast', 'notification', 'message', 'alert' ];
	}

  public function get_nestable_item() {
		return array(
        'name'     => 'text-basic',
        'label'    => esc_html__( 'Notification text', 'bricks' ),
        'settings' => array(
          'text' => esc_html__( 'Notification text here', 'bricks' ),
        ),
		);
	}

	public function get_nestable_children() {
		$children = array();

		for ( $i = 0; $i < 1; $i++ ) {
			$item = $this->get_nestable_item();

			// Replace {item_index} with $index
			$item       = json_encode( $item );
			$item       = str_replace( '{item_index}', $i + 1, $item );
			$item       = json_decode( $item, true );
			$children[] = $item;
		}

		return $children;
	}

  public function set_control_groups() {

    $this->control_groups['triggers'] = [
      'title' => esc_html__( 'Triggers', 'bricksextras' ),
      'tab'   => 'content',
    ];

    $this->control_groups['icon'] = [
      'title' => esc_html__( 'Dismiss Button', 'bricks' ),
      'tab'   => 'content',
    ];

    $this->control_groups['contextIcon'] = [
      'title' => esc_html__( 'Context Icon', 'bricks' ),
      'tab'   => 'content',
    ];

  }

  public function set_controls() {

    // Apply all display/layout controls to the inner container
    $this->controls['_display']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_margin']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_padding']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_aspectRatio']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_position']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_top']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_right']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_bottom']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_left']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_visibility']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_overflow']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_opacity']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_cursor']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_isolation']['css'][0]['selector'] = '.x-toast-notification-inner'; 
    $this->controls['_mixBlendMode']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_pointerEvents']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_alignSelf']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_justifyContent']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_alignItems']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_gap']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_flexDirection']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_flexGrow']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_flexShrink']['css'][0]['selector'] = '.x-toast-notification-inner';
    $this->controls['_flexBasis']['css'][0]['selector'] = '.x-toast-notification-inner';

    $this->controls['info'] = [
      'tab' => 'content',
      'type' => 'separator',
      'description' => esc_html__( 'This element must be placed inside of a Toast element.', 'bricksextras' ),
    ];

    $this->controls['builderHidden'] = [
      'tab' => 'content',
      'inline' => true,
      'small' => true,
      'label' => esc_html__( 'Hide in builder', 'bricksextras' ),
      'type' => 'checkbox',
    ];

    $this->controls['builderHidden_sep'] = [
      'tab' => 'content',
      'type' => 'separator',
    ];

    // Duration
    $this->controls['duration'] = [
      'tab' => 'content',
      'label' => esc_html__( 'Duration', 'bricksextras' ) . ' (ms)',
      'type' => 'number',
      'unit' => 'ms',
      'inline' => true,
      'default' => 5000,
      'placeholder' => '5000',
      'description' => esc_html__( 'Set to 0 to disable auto-dismiss.', 'bricksextras' ),
    ];

    // Dismissible
    $this->controls['dismissible'] = [
      'tab' => 'content',
      'label' => esc_html__( 'Dismissible', 'bricksextras' ),
      'type' => 'select',
      'options' => [
        'enable' => esc_html__( 'Enable', 'bricksextras' ),
        'disable' => esc_html__( 'Disable', 'bricksextras' ),
      ],
      'placeholder' => esc_html__( 'Enable', 'bricksextras' ),
      'inline' => true,
      'description' => esc_html__( 'Can be swiped away', 'bricksextras' ),
    ];

    // Close Button
    $this->controls['closeButton'] = [
      'tab' => 'content',
      'label' => esc_html__( 'Dismiss Button', 'bricksextras' ),
      'type' => 'checkbox',
      'group' => 'icon',
      'inline' => true,
      'default' => false,
    ];

    // Close Button Icon
    $this->controls['closeButtonIcon'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Icon', 'bricksextras' ),
      'type' => 'icon',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'selector' => '.x-toast-close-icon svg',
        ],
      ],
    ];

    // Context Icon
    $this->controls['contextIcon'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Context Icon', 'bricksextras' ),
      'type' => 'checkbox',
      'inline' => true,
      'default' => false,
      'description' => esc_html__( 'Show icon on the left side of notification', 'bricksextras' ),
    ];

    // Context Icon Icon
    $this->controls['contextIconIcon'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Icon', 'bricksextras' ),
      'type' => 'icon',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'selector' => '.x-toast-context-icon svg',
        ],
      ],
    ];

    $icon_selector = '.x-toast-close';

    // Typography
    $this->controls['closeButtonTypography'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Typography', 'bricksextras' ),
      'type' => 'typography',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'font',
          'selector' => $icon_selector,
        ],
      ],
    ];

    // Background Color
    $this->controls['closeButtonBackgroundColor'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Background color', 'bricksextras' ),
      'type' => 'color',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'background-color',
          'selector' => $icon_selector,
        ],
      ],
    ];

    // Border
    $this->controls['closeButtonBorder'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Border', 'bricksextras' ),
      'type' => 'border',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'border',
          'selector' => $icon_selector,
        ],
      ],
    ];

    // Box Shadow
    $this->controls['closeButtonBoxShadow'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Box shadow', 'bricksextras' ),
      'type' => 'box-shadow',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'box-shadow',
          'selector' => $icon_selector,
        ],
      ],
    ];

    // Padding
    $this->controls['closeButtonPadding'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Padding', 'bricksextras' ),
      'type' => 'spacing',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'padding',
          'selector' => $icon_selector,
        ],
      ],
      'placeholder' => [
        'top' => '4px',
        'right' => '4px',
        'bottom' => '4px',
        'left' => '4px',
      ],
    ];

    // Margin
    $this->controls['closeButtonMargin'] = [
      'tab' => 'content',
      'group' => 'icon',
      'label' => esc_html__( 'Margin', 'bricksextras' ),
      'type' => 'spacing',
      'required' => [ 'closeButton', '!=', '' ],
      'css' => [
        [
          'property' => 'margin',
          'selector' => $icon_selector,
        ],
      ],
    ];

    // Context Icon Typography
    $context_icon_selector = '.x-toast-context-icon';
    
    $this->controls['contextIconTypography'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Typography', 'bricksextras' ),
      'type' => 'typography',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'font',
          'selector' => $context_icon_selector,
        ],
      ],
    ];

    // Context Icon Background Color
    $this->controls['contextIconBackgroundColor'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Background color', 'bricksextras' ),
      'type' => 'color',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'background-color',
          'selector' => $context_icon_selector,
        ],
      ],
    ];

    // Context Icon Border
    $this->controls['contextIconBorder'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Border', 'bricksextras' ),
      'type' => 'border',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'border',
          'selector' => $context_icon_selector,
        ],
      ],
    ];

    // Context Icon Box Shadow
    $this->controls['contextIconBoxShadow'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Box shadow', 'bricksextras' ),
      'type' => 'box-shadow',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'box-shadow',
          'selector' => $context_icon_selector,
        ],
      ],
    ];

    // Context Icon Padding
    $this->controls['contextIconPadding'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Padding', 'bricksextras' ),
      'type' => 'spacing',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'padding',
          'selector' => $context_icon_selector,
        ],
      ],
      'placeholder' => [
        'top' => '4px',
        'right' => '4px',
        'bottom' => '4px',
        'left' => '4px',
      ],
    ];

    // Context Icon Margin
    $this->controls['contextIconMargin'] = [
      'tab' => 'content',
      'group' => 'contextIcon',
      'label' => esc_html__( 'Margin', 'bricksextras' ),
      'type' => 'spacing',
      'required' => [ 'contextIcon', '!=', '' ],
      'css' => [
        [
          'property' => 'margin',
          'selector' => $context_icon_selector,
        ],
      ],
    ];

    // Screen Reader Announcement
    $this->controls['ariaLive'] = [
      'tab' => 'content',
      'label' => esc_html__( 'Screen Reader Announcement', 'bricksextras' ),
      'type' => 'select',
      'options' => [
        'polite' => esc_html__( 'Polite - Announce when convenient', 'bricksextras' ),
        'assertive' => esc_html__( 'Assertive - Interrupt to announce immediately', 'bricksextras' ),
        'off' => esc_html__( 'Off - Do not announce', 'bricksextras' ),
      ],
      'placeholder' => esc_html__( 'Polite - Announce when convenient', 'bricksextras' )
    ];

    $this->controls['triggersSep'] = [
      'tab' => 'content',
      'type' => 'separator',
      'group' => 'triggers',
      'description' => esc_html__( 'Notifications can be triggered via interactions, via code or via these options', 'bricksextras' ),
    ];

    // Triggers
    $this->controls['triggers'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'label' => esc_html__( 'Triggers to show notification', 'bricksextras' ),
      'type' => 'repeater',
      'titleProperty' => 'label',
      'placeholder' => esc_html__( 'Trigger', 'bricks' ),
      'fields' => [
        'label' => [
          'type' => 'text',
          'label' => esc_html__( 'Name', 'bricks' ) . ' (' . esc_html__( 'Optional', 'bricks' ) . ')',
          'inline' => true,
        ],
        'type' => [
          'label' => esc_html__( 'Type', 'bricks' ),
          'type' => 'select',
          'inline' => true,
          'options' => [
            'pageLoad' => esc_html__( 'On page load', 'bricksextras' ) . ' (ms)',
            'pageLoadURLParameter' => esc_html__( 'On page load', 'bricksextras' ) . ' (' . esc_html__( 'URL parameter', 'bricks' ) . ')',
            'scroll' => esc_html__( 'Scroll distance', 'bricksextras' ) . ' (px / %)',
            'scrolledToElement' => esc_html__( 'Scroll to element', 'bricksextras' ),
            'exitIntent' => esc_html__( 'Page exit intent', 'bricksextras' ),
            'pageViews' => esc_html__( 'Number of page views', 'bricksextras' ),
            'elementClick' => esc_html__( 'Click element', 'bricks' ),
            'elementHover' => esc_html__( 'Hover element', 'bricksextras' ),
            'intervals' => esc_html__( 'Looped intervals', 'bricksextras' ) . ' (s)',
          ],
        ],
        'delay' => [
          'label' => esc_html__( 'Delay', 'bricksextras' ) . ' (ms)',
          'type' => 'number',
          'inline' => true,
          'placeholder' => '1000',
          'required' => ['type', '=', ['pageLoad', 'pageLoadURLParameter']],
        ],
        'urlParameter' => [
          'label' => esc_html__( 'URL Parameter', 'bricks' ),
          'type' => 'text',
          'inline' => true,
          'placeholder' => 'success=true',
          'required' => ['type', '=', 'pageLoadURLParameter'],
        ],
        'scrollDistance' => [
          'label' => esc_html__( 'Scroll Distance', 'bricksextras' ),
          'type' => 'text',
          'inline' => true,
          'placeholder' => '500px or 50%',
          'required' => ['type', '=', 'scroll'],
        ],
        'pageViews' => [
          'label' => esc_html__( 'Number of Page Views', 'bricksextras' ),
          'type' => 'number',
          'inline' => true,
          'placeholder' => '3',
          'required' => ['type', '=', 'pageViews'],
        ],
        'intervalSeconds' => [
          'label' => esc_html__( 'Interval', 'bricksextras' ) . ' (s)',
          'type' => 'number',
          'inline' => true,
          'placeholder' => '20',
          'description' => esc_html__( 'Seconds between each notification rotation', 'bricksextras' ),
          'required' => ['type', '=', 'intervals'],
        ],
        'intervalLoop' => [
          'label' => esc_html__( 'Loop', 'bricks' ),
          'type' => 'checkbox',
          'inline' => true,
          'required' => ['type', '=', 'intervals'],
        ],
        'selector' => [
          'label' => esc_html__( 'Selector', 'bricks' ) . ' (' . esc_html__( 'Element', 'bricks' ) . ')',
          'type' => 'text',
          'hasDynamicData' => false,
          'inline' => true,
          'placeholder' => '.your-class',
          'required' => ['type', '=', [
            'scrolledToElement',
            'elementClick',
            'elementHover'
          ]],
        ],
      ],
    ];

    // Show Again Options
    $this->controls['show_again'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'label' => esc_html__( 'Reshow', 'bricksextras' ),
      'type' => 'select',
      'options' => [
        'page_load' => esc_html__( 'Show again on next visit', 'bricksextras' ),
        'never' => esc_html__( 'Never show again', 'bricksextras' ),
        'after' => esc_html__( 'Only allow to show after:', 'bricksextras' ),
      ],
      'placeholder' => esc_html__( 'Show again on next visit', 'bricksextras' ),
    ];

    $this->controls['show_again_days'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'label' => esc_html__( 'Days', 'bricksextras' ),
      'type' => 'number',
      'inline' => true,
      'required' => ['show_again', '=', ['after']],
    ];

    $this->controls['show_again_hours'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'label' => esc_html__( 'Hours', 'bricksextras' ),
      'type' => 'number',
      'inline' => true,
      'required' => ['show_again', '=', ['after']],
    ];

    $this->controls['show_once'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'small' => true,
      'label' => esc_html__( 'Only show once per page visit', 'bricksextras' ),
      'type' => 'checkbox',
      'required' => ['show_once_session', '!=', true],
    ];

    $this->controls['show_once_session'] = [
      'tab' => 'content',
      'group' => 'triggers',
      'small' => true,
      'label' => esc_html__( 'Only show once per session', 'bricksextras' ),
      'type' => 'checkbox',
      'required' => ['show_once', '!=', true],
    ];

  }
  
  public function render() {

    $settings = $this->settings;

    // Generate a unique identifier for this notification
    $identifier = \BricksExtras\Helpers::set_identifier_attribute( $this );

    // Get settings with defaults
    $duration = isset( $settings['duration'] ) ? intval( $settings['duration'] ) : 5000;
    $dismissible = !isset( $settings['dismissible'] ) || $settings['dismissible'] !== 'disable';
    $closeButton = !empty( $settings['closeButton'] );
    $ariaLive = isset( $settings['ariaLive'] ) ? esc_attr( $settings['ariaLive'] ) : 'polite';
    $triggers = isset( $settings['triggers'] ) ? $settings['triggers'] : [];

    // Build config for notification
    $config = [
      'duration' => $duration === 0 ? 'Infinity' : $duration,
      'dismissible' => $dismissible,
      'closeButton' => $closeButton,
      'ariaLive' => $ariaLive,
      'triggers' => $triggers,
      'show_once' => isset( $settings['show_once'] ) ? $settings['show_once'] : false,
      'show_once_session' => isset( $settings['show_once_session'] ) ? $settings['show_once_session'] : false,
      'show_again' => [
        'type' => isset( $settings['show_again'] ) ? $settings['show_again'] : '',
        'options' => [
          'days' => isset( $settings['show_again_days'] ) ? $settings['show_again_days'] : 0,
          'hours' => isset( $settings['show_again_hours'] ) ? $settings['show_again_hours'] : 0,
        ],
      ],
    ];

    $this->set_attribute( '_root', 'data-x-notification', wp_json_encode( $config ) );
    $this->set_attribute( '_root', 'class', 'x-toast-notification' );
    $this->set_attribute( 'content', 'class', 'x-toast-notification-content' );
    $this->set_attribute( 'inner', 'class', 'x-toast-notification-inner' );

    echo "<div {$this->render_attributes( '_root' )}>";
    echo "<div {$this->render_attributes( 'content' )}>";

    // Add context icon if enabled (outside inner div)
    if ( ! empty( $settings['contextIcon'] ) ) {
      // Use custom icon if set, otherwise use default SVG
      if ( ! empty( $settings['contextIconIcon'] ) ) {
        $contextIcon = self::render_icon( $settings['contextIconIcon'] );
      } else {
        $contextIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>';
      }
      
      $this->set_attribute( 'context-icon', 'class', 'x-toast-context-icon' );
      $this->set_attribute( 'context-icon', 'aria-hidden', 'true' );
      
      echo "<span {$this->render_attributes( 'context-icon' )}>" . $contextIcon . "</span>";
    }

    echo "<div {$this->render_attributes( 'inner' )}>";

    // Render nested children (any Bricks elements)
    if ( method_exists('\Bricks\Frontend','render_children') ) {
      echo \Bricks\Frontend::render_children( $this );
    }

    echo "</div>"; // Close inner wrapper

    // Add close button if enabled
    if ( $closeButton ) {
      // Use custom icon if set, otherwise use default SVG
      if ( ! empty( $settings['closeButtonIcon'] ) ) {
        $closeButtonIcon = self::render_icon( $settings['closeButtonIcon'] );
      } else {
        $closeButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>';
      }
      
      
      $this->set_attribute( 'close-button', 'class', 'x-toast-close' );
      $this->set_attribute( 'close-button', 'aria-hidden', 'true' );
      $this->set_attribute( 'close-button', 'data-x-toast-close', '' );
      $this->set_attribute( 'close-button-icon', 'class', 'x-toast-close-icon' );
      
      echo "<button {$this->render_attributes( 'close-button' )}>";
      echo "<span {$this->render_attributes( 'close-button-icon' )}>" . $closeButtonIcon . "</span>";
      echo "</button>";
    }

    echo "</div>"; // Close content wrapper

    

    echo "</div>";
  }

  public static function render_builder() { ?>

		<script type="text/x-template" id="tmpl-bricks-element-xtoastnotification">
      <component 
        v-if="!settings.builderHidden"
        is="div" 
        class="x-toast-notification"
        :data-x-notification="JSON.stringify({ 
          duration: settings.duration === 0 ? 'Infinity' : (settings.duration || 5000),
          dismissible: settings.dismissible !== false,
          closeButton: settings.closeButton || false
        })"
      >
        <div class="x-toast-notification-content">
          <span 
            v-if="settings.contextIcon"
            class="x-toast-context-icon"
            aria-hidden="true"
          >
            <icon-svg v-if="settings.contextIconIcon" :iconSettings="settings.contextIconIcon"/>
            <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
          </span>
          <div class="x-toast-notification-inner">
            <bricks-element-children :element="element"/>
          </div>
          <button 
          v-if="settings.closeButton"
          class="x-toast-close"
          aria-hidden="true"
        >
          <span class="x-toast-close-icon">
            <icon-svg v-if="settings.closeButtonIcon" :iconSettings="settings.closeButtonIcon"/>
            <svg v-else xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
          </span>
        </button>
        </div>
        
      </component>
	</script>

	<?php }

}
