<?php

namespace BricksExtras;

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

if ( class_exists( 'BricksExtrasMain' ) ) {
	return;
}

// Define required classes
$required_classes = array(
    'BricksExtrasInteractive'    => 'BricksExtrasInteractive.php',
    'BricksExtrasInteractions'   => 'BricksExtrasInteractions.php',
    'BricksExtrasHeaderExtras'   => 'BricksExtrasHeaderExtras.php',
    'BricksExtrasHelpers'        => 'BricksExtrasHelpers.php',
    'BricksExtrasFavorite'       => 'BricksExtrasFavorite.php',
    'BricksExtrasVideo'          => 'BricksExtrasVideo.php',
    'BricksExtrasBunnyStream'    => 'BricksExtrasBunnyStream.php',
);

// Load required classes
foreach ( $required_classes as $class_name => $file_path ) {
    if ( ! class_exists( $class_name ) ) {
        require_once dirname( __FILE__ ) . '/' . $file_path;
    }
}

// Load provider classes
if ( ! class_exists( 'BricksExtrasProviders' ) ) {
    require_once dirname( __FILE__ ) . '/Providers/BricksExtrasProviders.php';
    require_once dirname( __FILE__ ) . '/Providers/Provider_Extras.php';
}

global $bricksExtrasElementCSSAdded;
$bricksExtrasElementCSSAdded = [];

class BricksExtrasMain {
	public $elements = array();
	public $prefix = '';
	public $version= '';
	public $conditions = '';
	public $memberConditions = '';
	public $wcConditions = '';
	public $miscOptions = '';

	/**
	 * Main class constructor
	 */
	public function __construct( $prefix, $version ) {
		

		$this->prefix = $prefix;
		$this->version = $version;

		$this->set_files();
		$this->set_member_conditions();
		$this->set_wc_conditions();
		$this->set_misc_options();
		$this->set_conditions();

		add_action( 'admin_init', array( $this, 'register_options' ) );

		add_action( $this->prefix . 'form_options', array( $this, 'options_form' ) );
		add_action( $this->prefix . 'conditions_form_options', array( $this, 'conditions_form_options' ) );
		add_action( $this->prefix . 'member_conditions_form_options', array( $this, 'member_conditions_form_options' ) );
		add_action( $this->prefix . 'wc_conditions_form_options', array( $this, 'wc_conditions_form_options' ) );
		add_action( $this->prefix . 'misc_form_options', array( $this, 'misc_form_options' ) );
		
		// Add Gutenberg support
		if ( apply_filters( 'bricksextras/load_gutenberg_css', true ) ) {
			add_action( 'enqueue_block_assets', array( $this, 'load_gutenberg_css' ) );
		}


		if ( !class_exists("\Bricks\Elements") ) { 
			return;
		}
			
		$this->load_files();

		
		$media_player_active = get_option( $this->prefix . 'media_player');
		$media_player_audio_active = get_option( $this->prefix . 'media_player_audio');
		
		
		if ($media_player_active || $media_player_audio_active) {

			require_once 'BricksExtrasMedia.php';
			$media_handler = new \BricksExtras\BricksExtrasMedia();
			
			if ($media_player_active) {
				
				// Initialize Bunny Stream integration for captions
				if (class_exists('\BricksExtras\BricksExtrasBunnyStream')) {
					$bunny_stream = new \BricksExtras\BricksExtrasBunnyStream();
					if (method_exists($bunny_stream, 'init')) {
						$bunny_stream->init();
					}
				}
			}
			
			// Initialize waveform handler if enabled
			if ($media_player_audio_active) {
				$media_handler->init_waveform_handler();
			}
		}

		if ( bricks_is_frontend() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'conditional_default_CSS' ) );

			add_action( 'wp_enqueue_scripts', array( $this, 'global_scripts' ), 1 );

			// Interactions
			if ( get_option( $this->prefix . 'interactions') ) {
				add_action( 'wp_enqueue_scripts', array( $this, 'interactions_script' ), 1 );
			}

			// frontend Scripts
			add_action( 'bricks_after_footer', array( $this, 'frontend_scripts' ), 200 );
		}

		if ( bricks_is_builder_main() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'builder_scripts' ) );
		}

		if ( bricks_is_builder_iframe() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'iframe_scripts' ) );
			add_filter( 'bricks/body/attributes', array( $this, 'proslider_builder_init' ) );
		}
		
		if ( get_option( $this->prefix . 'header_row') ) {
			(new HeaderExtras())->init();
		}

		if ( ! class_exists( 'WPGridBuilderStyler' ) && get_option( $this->prefix . 'wpgb_facets') ) {
			require_once 'WPGridBuilderStyler.php';
			(new WPGridBuilderStyler())->init();
		}
		

		if ( get_option( $this->prefix . 'favorite') ) {
			(new Favorite())->init();
		}

		// Load Toast Queue helper
		if ( get_option( $this->prefix . 'toast') ) {
			if ( ! class_exists( '\BricksExtras\BricksExtrasToast' ) ) {
				require_once 'BricksExtrasToast.php';
				(new BricksExtrasToast())->init();
			}
		}

	}

	function sanitize_enable( $input ) {
		return ( $input == 1 ? 1 : 0 );
	}
	
	/**
	 * Sanitize API keys and preserve existing values when empty
	 *
	 * @param string $input The input value from the form
	 * @return string The sanitized value
	 */
	function sanitize_api_key( $input ) {
		// Get the option name from the filter
		$option_name = current_filter();
		$option_name = str_replace('sanitize_option_', '', $option_name);
		
		// If input is empty, keep the existing value
		if ( empty($input) ) {
			return get_option( $option_name, '' );
		}
		
		// Otherwise sanitize and return the new value
		return sanitize_text_field( $input );
	}

	function set_files() {
		$this->elements = [
			'back_to_top' => [
				'title' => esc_html__( 'Back to Top', 'bricksextras' ),
				'file_name' => 'x-back-to-top',
				'docs_slug' => 'back-to-top'
			],
			'before_after_image' => [
				'title' => esc_html__( 'Before / After Image', 'bricksextras' ),
				'file_name' => 'x-before-after-image',
				'docs_slug' => 'before-after-image'
			],
			'burger_trigger' => [
				'title' => esc_html__( 'Burger Trigger', 'bricksextras' ),
				'file_name' => 'x-burger-trigger',
				'docs_slug' => 'burger-trigger'
			],
			'content_switcher' =>[
				'title' => esc_html__( 'Content Switcher', 'bricksextras' ),
				'file_name' => 'x-content-switcher',
				'docs_slug' => 'content-switcher'
			],
			'content_timeline' => [
				'title' => esc_html__( 'Content Timeline', 'bricksextras' ),
				'file_name' => 'x-content-timeline',
				'docs_slug' => 'content-timeline'
			],
			'copy_to_clipboard' => [
				'title' => esc_html__( 'Copy to Clipboard', 'bricksextras' ),
				'file_name' => 'x-copy-to-clipboard',
				'docs_slug' => 'copy-to-clipboard'
			],
			'dynamic_chart' => [
				'title' => esc_html__( 'Dynamic Chart', 'bricksextras' ),
				'file_name' => 'x-dynamic-chart',
				'docs_slug' => 'dynamic-chart'
			],
			'dynamic_lightbox' => [
				'title' => esc_html__( 'Dynamic Lightbox', 'bricksextras' ),
				'file_name' => 'x-dynamic-lightbox',
				'docs_slug' => 'dynamic-lightbox'
			],
			
			'dynamic_table' => [
				'title' => esc_html__( 'Dynamic Table', 'bricksextras' ),
				'file_name' => 'x-dynamic-table',
				'docs_slug' => 'dynamic-table'
			],
			'favorite' =>[
				'title' => esc_html__( 'Favorites', 'bricksextras' ) . ' / ' . esc_html__( 'Wishlist', 'bricksextras' ),
				'file_name' => 'x-favorite',
				'docs_slug' => 'favorites-wishlist'
			],
			
			'fluent_form' => [
				'title' => esc_html( 'Fluent Form', 'bricksextras' ),
				'file_name' => 'x-fluent-form',
				'docs_slug' => 'fluent-form'
			],
			'header_row' => [
				'title' => esc_html__( 'Header Extras', 'bricksextras' ) . ' / ' . esc_html__( 'Rows', 'bricksextras' ),
				'file_name' => 'x-header-row',
				'docs_slug' => 'header-extras'
			],
			'notification_bar' =>[
				'title' => esc_html__( 'Header Notification Bar', 'bricksextras' ),
				'file_name' => 'x-notification-bar',
				'docs_slug' => 'header-notification-bar'
			],
			
			'header_search' => [
				'title' => esc_html__( 'Header Search', 'bricksextras' ),
				'file_name' => 'x-header-search',
				'docs_slug' => 'header-search'
			],
			'image_hotspots' => [
				'title' => esc_html__( 'Image Hotspots', 'bricksextras' ),
				'file_name' => 'x-image-hotspots',
				'docs_slug' => 'image-hotspots'
			],
			'image_hotspot_marker' => [
				'title' => esc_html__( 'Image Hotspot Marker', 'bricksextras' ),
				'file_name' => 'x-image-hotspot-marker',
				'docs_slug' => 'image-hotspot-marker',
				'stylesheet' => false
			],
			'interactive_cursor' => [
				'title' => esc_html__( 'Interactive Cursor', 'bricksextras' ),
				'file_name' => 'x-interactive-cursor',
				'docs_slug' => 'interactive-cursor'
			],
			'lottie' =>[
				'title' => esc_html__( 'Lottie', 'bricksextras' ),
				'file_name' => 'x-lottie',
				'docs_slug' => 'lottie',
			],
			'media_player' =>[
				'title' => esc_html__( 'Media Player', 'bricksextras' ),
				'file_name' => 'x-media-player',
				'docs_slug' => 'media-player',
			],
			'media_player_audio' =>[
				'title' => esc_html__( 'Media Player', 'bricksextras' ) . ' (' . esc_html__( 'Audio', 'bricksextras' ) . ')',
				'file_name' => 'x-media-player-audio',
				'docs_slug' => 'media-player-audio',
				'stylesheet' => 'mediaplayer'
			],
			'media_control' =>[
				'title' => esc_html__( 'Media Control', 'bricksextras' ),
				'file_name' => 'x-media-control',
				'docs_slug' => 'media-control',
				'stylesheet' => false,
			],
			'media_playlist' =>[
				'title' => esc_html__( 'Media Playlist', 'bricksextras' ),
				'file_name' => 'x-media-playlist',
				'docs_slug' => 'media-playlist',
			],
			'pro_modal' =>[
				'title' => esc_html__( 'Modal', 'bricksextras' ) . ' (' . esc_html__( 'Template', 'bricksextras' ) . ' - ' . esc_html__( 'Legacy', 'bricksextras' ) . ')',
				'file_name' => 'x-pro-modal',
				'docs_slug' => 'modal'
			],
			'pro_modal_nestable' =>[
				'title' => esc_html__( 'Modal', 'bricksextras' ),
				'file_name' => 'x-pro-modal-nestable',
				'docs_slug' => 'modal',
				'stylesheet' => 'promodal'
			],
			'nestable_table' =>[
				'title' => esc_html__( 'Nestable Table', 'bricksextras' ),
				'file_name' => 'x-nestable-table',
				'docs_slug' => 'nestable-table',
			],
			'offcanvas' =>[
				'title' => esc_html__( 'Offcanvas', 'bricksextras' ) . ' (' . esc_html__( 'Template', 'bricksextras' ) . ' - ' . esc_html__( 'Legacy', 'bricksextras' ) . ')',
				'file_name' => 'x-offcanvas',
				'docs_slug' => 'offcanvas'
			],
			'offcanvas_nestable' =>[
				'title' => esc_html__( 'Offcanvas', 'bricksextras' ),
				'file_name' => 'x-offcanvas-nestable',
				'docs_slug' => 'offcanvas',
				'stylesheet' => 'offcanvas'
			],
			'page_tour' =>[
				'title' => esc_html__( 'Page Tour', 'bricksextras' ),
				'file_name' => 'x-page-tour',
				'docs_slug' => 'page-tour',
			],
			'page_tour_step' =>[
				'title' => esc_html__( 'Page Tour Step', 'bricksextras' ),
				'file_name' => 'x-page-tour-step',
				'docs_slug' => 'page-tour', /* same as pagetour */
				'stylesheet' => 'pagetour' /* same as pagetour */
			],
			'panorama_viewer' =>[
				'title' => esc_html__( 'Panorama Viewer', 'bricksextras' ),
				'file_name' => 'x-panorama-viewer',
				'docs_slug' => 'panorama-viewer',
			],
			'panorama_scene' =>[
				'title' => esc_html__( 'Panorama Scene', 'bricksextras' ),
				'file_name' => 'x-panorama-scene',
				'docs_slug' => 'panorama-viewer',
				'stylesheet' => false
			],
			'popover' =>[
				'title' => esc_html__( 'Popover / Tooltips', 'bricksextras' ),
				'file_name' => 'x-popover',
				'docs_slug' => 'popovers-tooltips'
			],
			'pro_accordion' =>[
				'title' => esc_html__( 'Pro Accordion', 'bricksextras' ),
				'file_name' => 'x-pro-accordion',
				'docs_slug' => 'pro-accordion'
			],
			'pro_alert' =>[
				'title' => esc_html__( 'Pro Alert', 'bricksextras' ),
				'file_name' => 'x-pro-alert',
				'docs_slug' => 'pro-alert'
			],
			'countdown' =>[
				'title' => esc_html__( 'Pro Countdown', 'bricksextras' ),
				'file_name' => 'x-countdown',
				'docs_slug' => 'countdown'
			],
			'pro_slider' =>[
				'title' => esc_html__( 'Pro Slider', 'bricksextras' ),
				'file_name' => 'x-pro-slider',
				'docs_slug' => 'pro-slider'
			],
			'pro_slider_control' =>[
				'title' => esc_html__( 'Pro Slider Control', 'bricksextras' ),
				'file_name' => 'x-pro-slider-control',
				'docs_slug' => 'pro-slider',
			],
			'pro_slider_gallery' =>[
				'title' => esc_html__( 'Pro Slider Gallery', 'bricksextras' ),
				'file_name' => 'x-pro-slider-gallery',
				'docs_slug' => 'pro-slider',
				'stylesheet' => false
			],
			'pro_tabs' => [
				'title' => esc_html__( 'Pro Tabs', 'bricksextras' ),
				'file_name' => 'x-tabs',
				'docs_slug' => 'pro-tabs'
			],
			'qr_code' =>[
				'title' => esc_html__( 'QR Code', 'bricksextras' ),
				'file_name' => 'x-qr-code',
				'docs_slug' => 'qr-code',
			],
			'reading_progress_bar' =>[
				'title' => esc_html__( 'Reading Progress Bar', 'bricksextras' ),
				'file_name' => 'x-reading-progress-bar',
				'docs_slug' => 'reading-progress-bar'
			],
			'read_more_less' =>[
				'title' => esc_html__( 'Read More / Less', 'bricksextras' ),
				'file_name' => 'x-read-more-less',
				'docs_slug' => 'read-more-less'
			],
			'shortcode_wrapper' =>[
				'title' => esc_html__( 'Shortcode Wrapper', 'bricksextras' ),
				'file_name' => 'x-shortcode-wrapper',
				'docs_slug' => 'shortcode-wrapper',
				'stylesheet' => false
			],
			'breadcrumbs' => [
				'title' => esc_html__( 'Site Breadcrumbs', 'bricksextras' ),
				'file_name' => 'x-breadcrumbs',
				'docs_slug' => 'site-breadcrumbs'
			],
			'slide_menu' =>[
				'title' => esc_html__( 'Slide menu', 'bricksextras' ),
				'file_name' => 'x-slide-menu',
				'docs_slug' => 'slide-menu'
			],
			'social_share' =>[
				'title' => esc_html__( 'Social Share', 'bricksextras' ),
				'file_name' => 'x-social-share',
				'docs_slug' => 'social-share'
			],
			'star_rating' =>[
				'title' => esc_html__( 'Star Rating', 'bricksextras' ),
				'file_name' => 'x-star-rating',
				'docs_slug' => 'star-rating'
			],
			'table_of_contents' =>[
				'title' => esc_html__( 'Table of Contents', 'bricksextras' ),
				'file_name' => 'x-table-of-contents',
				'docs_slug' => 'table-of-contents'
			],
			'toast' =>[
				'title' => esc_html__( 'Toast', 'bricksextras' ) . ' (beta)',
				'file_name' => 'x-toast',
				'docs_slug' => 'toast'
			],
			'toast_notification' =>[
				'title' => esc_html__( 'Toast Notification', 'bricksextras' ) . ' (beta)',
				'file_name' => 'x-toast-notification',
				'docs_slug' => 'toast',
				'stylesheet' => false
			],
			'toggle_switch' =>[
				'title' => esc_html__( 'Toggle Switch', 'bricksextras' ),
				'file_name' => 'x-toggle-switch',
				'docs_slug' => 'toggle-switch'
			],
			'wpgb_facets' =>[
				'title' => 'WPGB ' . esc_html__( 'Facet Styler', 'bricksextras' ),
				'file_name' => 'x-wpgb-facet-styler',
				'docs_slug' => 'wpgb-facet-styler',
				'element' => false,
			],
			'ws_forms' =>[
				'title' => esc_html( 'WS Form', 'bricksextras' ),
				'file_name' => 'x-ws-forms',
				'docs_slug' => 'ws-forms'
			],
			
		];

		

	}

	function set_conditions() {
		$this->conditions = Helpers::getExtrasConditions('general');
	}

	function set_member_conditions() {
		$this->memberConditions = Helpers::getExtrasConditions('member');
	}
	
	function set_wc_conditions() {
		$this->wcConditions = Helpers::getExtrasConditions('wc');
	}

	function set_misc_options() {
		$this->miscOptions = Helpers::getExtrasMiscOptions();
	}

	function register_options() {

		/* elements/features  */
		foreach ( $this->elements as $key => $element ) {

				add_option( $this->prefix . $key, 0 );
				register_setting( $this->prefix . 'settings', $this->prefix . $key, array( $this, 'sanitize_enable' ) );
			
		}

		/* conditons */
		foreach ( $this->conditions as $key => $condition ) {

			add_option( $this->prefix . $key, 0 );
			register_setting( $this->prefix . 'conditions_settings', $this->prefix . $key, array( $this, 'sanitize_enable' ) );
		
		}

		/* member conditons */
		foreach ( $this->memberConditions as $key => $memberCondition ) {

			add_option( $this->prefix . $key, 0 );
			register_setting( $this->prefix . 'conditions_settings', $this->prefix . $key, array( $this, 'sanitize_enable' ) );
		
		}
		
		/* WooCommerce conditons */
		foreach ( $this->wcConditions as $key => $wcCondition ) {

			add_option( $this->prefix . $key, 0 );
			register_setting( $this->prefix . 'conditions_settings', $this->prefix . $key, array( $this, 'sanitize_enable' ) );
		
		}

		/* Misc features */
		foreach ( $this->miscOptions as $key => $miscOption ) {

			add_option( $this->prefix . $key, 0 );
			register_setting( $this->prefix . 'misc_options', $this->prefix . $key, array( $this, 'sanitize_enable' ) );
		
		}
		
		/* Video Provider settings */
		add_option( $this->prefix . 'bunny_token', '' );
		
		register_setting( $this->prefix . 'video_providers', $this->prefix . 'bunny_token', array( $this, 'sanitize_api_key' ) );
		
	}

	function options_form() {

		foreach ( $this->elements as $key => $element ) {  ?>
			
			<tr valign="top"<?php echo get_option( $this->prefix . $key ) === '1' ? ' class="active"' : ' class="inactive"'; ?>>
				<th class="check-column">
					<input id="<?php echo esc_attr( $this->prefix . $key ); ?>" name="<?php echo esc_attr( $this->prefix . $key ); ?>" type="checkbox" value="1" <?php checked( get_option( $this->prefix . $key ), 1 ); ?> />
				</th>
				<td class="plugin-title column-primary">
					<?php echo '<strong>' . esc_html( $element['title'] ) . '</strong>'; ?>
				</td>
				<th class="doc-link-th" style="text-align: end; padding-right: 10px;">
					<?php echo '<p class="doc-link"><a target="_blank" href="https://bricksextras.com/docs/' . esc_attr( $element['docs_slug'] ) . '">Doc</a></p>'; ?>
				</th>
			</tr>
			<?php 
		}

	}

	function conditions_form_options(): void {

		foreach ( $this->conditions as $key => $condition ) {  ?>
			
			<tr valign="top"<?php echo get_option( $this->prefix . $key ) === '1' ? ' class="active"' : ' class="inactive"'; ?>>
				<th class="check-column">
					<input id="<?php echo esc_attr( $this->prefix . $key ); ?>" name="<?php echo esc_attr( $this->prefix . $key ); ?>" type="checkbox" value="1" <?php checked( get_option( $this->prefix . $key ), 1 ); ?> />
				</th>
				<td class="plugin-title column-primary">
					<?php echo '<strong>' . esc_html( $condition['title'] ) . '</strong>'; ?>
				</td>
				<th class="doc-link-th" style="text-align: end; padding-right: 10px;">
					<?php echo '<p class="doc-link"><a target="_blank" href="https://bricksextras.com/docs/' . esc_attr( $condition['docs_slug'] ) . '">Doc</a></p>'; ?>
				</th>
			</tr>
			<?php 
		}

	}

	function member_conditions_form_options(): void {

		foreach ( $this->memberConditions as $key => $memberCondition ) {  ?>
			
			<tr valign="top"<?php echo get_option( $this->prefix . $key ) === '1' ? ' class="active"' : ' class="inactive"'; ?>>
				<th class="check-column">
					<input id="<?php echo esc_attr( $this->prefix . $key ); ?>" name="<?php echo esc_attr( $this->prefix . $key ); ?>" type="checkbox" value="1" <?php checked( get_option( $this->prefix . $key ), 1 ); ?> />
				</th>
				<td class="plugin-title column-primary">
					<?php echo '<strong>' . esc_html( $memberCondition['title'] ) . '</strong>'; ?>
				</td>
				<th class="doc-link-th" style="text-align: end; padding-right: 10px;">
					<?php echo '<p class="doc-link"><a target="_blank" href="https://bricksextras.com/docs/' . esc_attr( $memberCondition['docs_slug'] ) . '/">Doc</a></p>'; ?>
				</th>
			</tr>
			<?php 
		}

	}
	
	function wc_conditions_form_options(): void {

		foreach ( $this->wcConditions as $key => $wcCondition ) {  ?>
			
			<tr valign="top"<?php echo get_option( $this->prefix . $key ) === '1' ? ' class="active"' : ' class="inactive"'; ?>>
				<th class="check-column">
					<input id="<?php echo esc_attr( $this->prefix . $key ); ?>" name="<?php echo esc_attr( $this->prefix . $key ); ?>" type="checkbox" value="1" <?php checked( get_option( $this->prefix . $key ), 1 ); ?> />
				</th>
				<td class="plugin-title column-primary">
					<?php echo '<strong>' . esc_html( $wcCondition['title'] ) . '</strong>'; ?>
				</td>
				<th class="doc-link-th" style="text-align: end; padding-right: 10px;">
					<?php echo '<p class="doc-link"><a target="_blank" href="https://bricksextras.com/docs/' . esc_attr( $wcCondition['docs_slug'] ) . '">Doc</a></p>'; ?>
				</th>
			</tr>
			<?php 
		}

	}

	function misc_form_options() {

		foreach ( $this->miscOptions as $key => $miscOption ) {  ?>
			
			<tr valign="top"<?php echo get_option( $this->prefix . $key ) === '1' ? ' class="active"' : ' class="inactive"'; ?>>
				<th class="check-column">
					<input id="<?php echo esc_attr( $this->prefix . $key ); ?>" name="<?php echo esc_attr( $this->prefix . $key ); ?>" type="checkbox" value="1" <?php checked( get_option( $this->prefix . $key ), 1 ); ?> />
				</th>
				<td class="plugin-title column-primary">
					<?php echo '<strong>' . esc_html( $miscOption['title'] ) . '</strong>'; ?>
					<?php echo isset( $miscOption['description'] ) ? esc_html( $miscOption['description'] ) : '' ?>
				</td>
				<th class="doc-link-th" style="text-align: end; padding-right: 10px;">
					<?php echo '<p class="doc-link"><a target="_blank" href="https://bricksextras.com/docs/' . esc_attr( $miscOption['docs_slug'] ) . '">Doc</a></p>'; ?>
				</th>
			</tr>
			<?php 
		}

	}

	function load_files() {

		$element_dir = BRICKSEXTRAS_PATH . 'components/classes/';

		foreach ( $this->elements as $key => $element ) {
			
			if ( 0 === intval( get_option( $this->prefix . $key, 0 ) ) ) {
				continue;
			}

			if ( isset( $element['element'] ) ) {
				continue;
			}

			$file = $element_dir . $element['file_name'] . '.php';
			$name = str_replace( '-', '', $element['file_name'] );
			$class_name = str_replace( '-', '_', $element['file_name'] );
			$class_name = ucwords( $class_name, '_' );

			/* Example output for each element for Bricks' register_element() function ..

				$file = BRICKSEXTRAS_PATH . 'components/classes/x-burger-trigger.php';
				$name = xburgertrigger ( this is the $name from the element class, no dashes )
				$class_name = X_Burger_Trigger ( the Class of the element, always capitalized, underscore not dashes )

			*/

			// Register all elements in builder & frontend 
			\Bricks\Elements::register_element( $file, $name, $class_name );

			/* include styles in builder */
			if ( bricks_is_builder_iframe() ) {

				if ( !isset( $element['stylesheet'] ) ) {
					$element['stylesheet'] = true;
				}

				if ( true === $element['stylesheet'] ) {
					$stylesheet = ltrim( str_replace( '-', '', $element['file_name'] ) , "x");
				} else if ( false !== $element['stylesheet'] ) {
					$stylesheet = $element['stylesheet'];
				}

				if ( !!$element['stylesheet'] ) {

					if ('xmodalnestable' === $name) {
						$handle = 'x-modal';
					} else if ('xoffcanvasnestable' === $name) {
						$handle = 'x-offcanvas';
					} else if ('xmediaplayeraudio' === $name) {
						$handle = 'x-media-player';
					} else {
						$handle = $element['file_name'];
					}

					if ('xwsforms' === $name && method_exists('\WS_Form_Common','styler_enabled') && \WS_Form_Common::styler_enabled() ) {
						$stylesheet = 'wsforms-styler-enabled';
					}

					wp_enqueue_style( $handle, BRICKSEXTRAS_URL . 'components/assets/css/' . $stylesheet . '.css', [], $this->version );

				}

			}

		}

		BricksExtrasInteractive::init();

		if ( get_option( $this->prefix . 'interactions') ) {
			BricksExtrasInteractions::init($this->prefix);
		}

		if ( get_option( $this->prefix . 'query_loop_extras') ) {
			if ( ! class_exists( 'BricksExtrasQueryLoop' ) ) {
				require_once 'BricksExtrasQueryLoop.php';
			}
	
			(new BricksExtrasQueryLoop())->init($this->prefix);
		}

		

		$providers = [
			'extras'
		];

		if ( class_exists("\Bricks\Integrations\Dynamic_Data\Providers\Base") ) {
			BricksExtrasProviders::register($providers);
		}

		if ( ! class_exists( 'BricksExtrasHelpers' ) ) {
			require_once BRICKSEXTRAS_PATH . '/includes/BricksExtrasHelpers.php';
		}
		
	}


	function conditional_default_CSS( $version ) {	

			global $bricksExtrasElementCSSAdded;
			$bricksExtrasElementCSSAdded['version'] = $this->version;

			$elementsOnPageArray = \BricksExtras\Helpers::getElementsOnPage();

			$elementsOnPageNames = array_column($elementsOnPageArray, 'name');
				
				
					// find all the active elements
					foreach ( $this->elements as $key => $element ) {

						if ( 0 === intval( get_option( $this->prefix . $key, 0 ) ) ) {
							continue;
						}

						$name = str_replace( '-', '', $element['file_name'] );
		
						$bricksExtrasElementCSSAdded[$name] = false;

						// check if our elements are being used on the page
						if ( in_array( $name, $elementsOnPageNames ) )  {

							// enqueue neccessary styles in head for that page

							if ( !isset( $element['stylesheet'] ) ) {
								$element['stylesheet'] = true;
							}

							if ( true === $element['stylesheet'] ) {
								$stylesheet = ltrim( str_replace( '-', '', $element['file_name'] ) , "x");
							} else if ( false !== $element['stylesheet'] ) {
								$stylesheet = $element['stylesheet'];
							}

							if ( !!$element['stylesheet'] ) {

								$bricksExtrasElementCSSAdded[$name] = true;
						
								// make sure the new versions of modal/offcanvas use the same CSS as the older ones.
								if ('xpromodalnestable' === $name) {
									$handle = 'x-modal';
								} else if ('xoffcanvasnestable' === $name) {
									$handle = 'x-offcanvas';
								} else if ('xmediaplayeraudio' === $name) {
									$handle = 'x-media-player';
								} else {
									$handle = $element['file_name'];
								}

								if ('xproslider' === $name) {
									// Include Splide CSS
									wp_enqueue_style( 'bricks-splide' );
								}

								if ('xwsforms' === $name && method_exists('\WS_Form_Common','styler_enabled') && \WS_Form_Common::styler_enabled() ) {
									$stylesheet = 'wsforms-styler-enabled';
								}

								if ( \Bricks\Database::get_setting( 'cssLoading' ) === 'file' || 'xwsforms' === $name ) {
									wp_enqueue_style( $handle, BRICKSEXTRAS_URL . 'components/assets/css/' . $stylesheet . '.css', [], $this->version );
								} else {
									$minified_css = false;

									/* check for bricks v1.8.1 - Bricks changed helper function from get_file_contents to file_get_contents */
									if ( method_exists( '\Bricks\Helpers', 'get_file_contents' ) ) {
										$minified_css = \Bricks\Assets::minify_css( \Bricks\Helpers::get_file_contents( BRICKSEXTRAS_URL . 'components/assets/css/' . $stylesheet . '.css' ) );
									} else if ( method_exists( '\Bricks\Helpers', 'file_get_contents' ) ) {
										$minified_css = \Bricks\Assets::minify_css( \Bricks\Helpers::file_get_contents( BRICKSEXTRAS_PATH . 'components/assets/css/' . $stylesheet . '.css' ) );
									} 
									if ( $minified_css ) {
										wp_add_inline_style( 'bricks-frontend', $minified_css );
									} else {
										wp_enqueue_style( $handle, BRICKSEXTRAS_URL . 'components/assets/css/' . $stylesheet . '.css', [], $this->version );
									}
								}

							}

						}

				}

	}


	function interactions_script() {
		wp_enqueue_script( 'x-interactions', BRICKSEXTRAS_URL . 'includes/js/interactions.min.js', ['bricks-scripts'], $this->version, true );
	}

	function frontend_scripts() {

		/* WPGridbuilder facet support */
		if ( defined( 'WPGB_VERSION' ) ) {

			$elementsOnPageArray = \BricksExtras\Helpers::getElementsOnPage();
			$elementsOnPageNames = array_column($elementsOnPageArray, 'name');

			if ( in_array("wpgb-facet", $elementsOnPageNames) ) {

				if ( get_option( $this->prefix . 'wpgb_facets') ) {
					wp_enqueue_style(  'wpgb-facets-extras', BRICKSEXTRAS_URL . 'components/assets/css/wpgb-facets.css',['wpgb-facets'], $this->version );
				}

				wp_enqueue_script( 'wpgb-extras', BRICKSEXTRAS_URL . 'includes/js/wpgb-extras.js', ['wpgb-facets'], $this->version, true );
			}
		}

		/* Jet Smart Filters support */
		if ( class_exists( 'Jet_Smart_Filters' ) ) {
			wp_enqueue_script( 'jsf-extras', BRICKSEXTRAS_URL . 'includes/js/jsf-extras.js', ['jet-smart-filters'], $this->version, true );
		}

		/* Piotnet Grid Filters support */
		if ( class_exists( 'piotnetgrid' ) ) {
			wp_enqueue_script( 'piotnet-extras', BRICKSEXTRAS_URL . 'includes/js/piotnet-extras.js', ['piotnetgrid-script'], $this->version, true );
		}
		

	}

	function global_scripts() {
		wp_enqueue_script( 'x-frontend', BRICKSEXTRAS_URL . 'components/assets/js/' . \BricksExtras\Helpers::maybeMinifyScripts('frontend') . '.js', '', $this->version, true );
	} 

	function builder_scripts() {

		if ( get_option( $this->prefix . 'x_ray') ) {
			wp_enqueue_script( 'bricks-editor', BRICKSEXTRAS_URL . 'includes/js/editor.js', [], '1.0.0', true );
		}

	}

	function iframe_scripts() {

		if ( get_option( $this->prefix . 'wpgb_facets') ) {
			wp_enqueue_style(  'wpgb-facets-extras', BRICKSEXTRAS_URL . 'components/assets/css/wpgb-facets.css',[], $this->version );
		}

	}


	/**
	 * Load all element CSS files in the Gutenberg editor and preview iframe
	 */
	public function load_gutenberg_css() {

		// Only load in admin context (Gutenberg editor or preview)
		if (!is_admin()) {
			return;
		}

		// Include Splide CSS directly from our plugin
		wp_enqueue_style(
			'bricksextras-splide',
			BRICKSEXTRAS_URL . 'components/assets/css/splide-layer.min.css',
			array(),
			$this->version
		);

		wp_enqueue_script(
			'x-frontend',
			BRICKSEXTRAS_URL . 'components/assets/js/frontend.min.js',
			array(),
			$this->version,
			false
		);
		
		// Load CSS for all active elements
		foreach ( $this->elements as $element_key => $element_data ) {
			
			if ( isset( $element_data['element'] ) ) {
				continue;
			} 

			$option_name = $this->prefix . $element_key;
			
			if ( get_option( $option_name ) ) {
				$file_name = $element_data['file_name'];
				$file_name = str_replace('x-', '', $file_name);
				
				// Get stylesheet name - remove hyphens to match actual filenames
				if ( isset($element_data['stylesheet']) && $element_data['stylesheet'] !== true ) {
					$stylesheet = $element_data['stylesheet'];
				} else {
					$stylesheet = ltrim($file_name, 'x');
				}
				
				// Remove hyphens from stylesheet name to match actual filenames
				$stylesheet = str_replace('-', '', $stylesheet);
				
				// Special cases for certain elements
				if ('xpromodalnestable' === $file_name) {
					$handle = 'x-modal';
					$stylesheet = 'promodal'; // Use correct filename
				} else if ('xoffcanvasnestable' === $file_name) {
					$handle = 'x-offcanvas';
					$stylesheet = 'offcanvas'; // Use correct filename
				} else {
					$handle = $element_data['file_name'];
				}
				
				// Skip elements with no stylesheet
				if (empty($stylesheet)) {
					continue;
				}
				
				// Enqueue the CSS file
				$css_file = BRICKSEXTRAS_URL . 'components/assets/css/' . $stylesheet . '.css';
				
				wp_enqueue_style( 
					'bricksextras-gutenberg-' . $handle, 
					$css_file, 
					array(), 
					$this->version 
				);
			}
		}

		
	}

	function proslider_builder_init ( $attributes ) {

		$initProSlider = false;

		/* allow for init if prefered */
		$initProSlider = apply_filters( 'bricksextras/proslider/builderinit', $initProSlider );

		if ( $initProSlider ) {
			$attributes['data-x-proslider-init'] = 'true';
		}

		return $attributes;

	}



}