<?php
/**
 * AnchorKit Elementor Widget
 *
 * Provides a drag-and-drop Table of Contents widget for Elementor page builder
 * with full customization options and per-instance settings.
 *
 * @package AnchorKit_TOC
 * @since 1.0.0
 */

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

/**
 * Check if Elementor is active and initialize widget.
 *
 * @return void
 */
function anchorkit_elementor_init() {
	// Check if Elementor is installed and activated.
	if ( ! did_action( 'elementor/loaded' ) ) {
		return;
	}

	// Register the widget (Pro feature - only available to pro users).
	// This block is stripped from the free version by Freemius.
	if ( anchorkit_fs() && anchorkit_fs()->is__premium_only() ) {
		if ( anchorkit_fs()->can_use_premium_code() ) {
			add_action( 'elementor/widgets/register', 'anchorkit_register_elementor_widget' );
			add_action( 'elementor/elements/categories_registered', 'anchorkit_add_elementor_widget_category' );
			add_action( 'elementor/editor/after_enqueue_styles', 'anchorkit_elementor_editor_styles' );
			add_action( 'elementor/editor/after_enqueue_scripts', 'anchorkit_elementor_editor_scripts' );

			// Ensure frontend assets are available on Elementor editor and preview.
			add_action(
				'elementor/frontend/after_register_scripts',
				function () {
					// Enqueue frontend assets so interactions work inside Elementor.
					$css_url = plugin_dir_url( __FILE__ ) . '../css/anchorkit-frontend.css';
					wp_enqueue_style( 'anchorkit-toc-css', $css_url, array(), ANCHORKIT_PLUGIN_VERSION );

					$script_url = plugin_dir_url( __FILE__ ) . '../js/table-of-contents.js';
					wp_enqueue_script( 'anchorkit-toc-js', $script_url, array(), ANCHORKIT_PLUGIN_VERSION, true );

					// Provide minimal defaults so JS runs in the editor/preview context.
					if ( ! wp_script_is( 'anchorkit-toc-js', 'enqueued' ) ) {
						return;
					}
					if ( ! isset( $GLOBALS['anchorkit_elementor_settings_localized'] ) ) {
						$GLOBALS['anchorkit_elementor_settings_localized'] = true;
						wp_localize_script(
							'anchorkit-toc-js',
							'anchorkitTocSettings',
							array(
								'smooth_scroll'      => true,
								'scroll_offset'      => 0,
								'collapsible'        => true,
								'initial_state'      => 'expanded',
								'hierarchical'       => true,
								'scroll_spy'         => true,
								'sticky'             => false,
								'sticky_position'    => 'content',
								'sticky_offset'      => 20,
								'entrance_animation' => false,
								'animation_type'     => 'fade',
							)
						);
					}
				}
			);
		}
	}
}
add_action( 'plugins_loaded', 'anchorkit_elementor_init' );

/**
 * Add AnchorKit category to Elementor panel.
 *
 * @param \Elementor\Elements_Manager $elements_manager Elementor elements manager.
 * @return void
 */
function anchorkit_add_elementor_widget_category( $elements_manager ) {
	$elements_manager->add_category(
		'anchorkit',
		array(
			'title' => __( 'AnchorKit', 'anchorkit-table-of-contents' ),
			'icon'  => 'fa fa-anchor',
		)
	);
}

/**
 * Register the Elementor widget.
 *
 * @param \Elementor\Widgets_Manager $widgets_manager Elementor widgets manager.
 * @return void
 */
function anchorkit_register_elementor_widget( $widgets_manager ) {
	require_once __DIR__ . '/elementor-widget-class.php';
	$widgets_manager->register( new \AnchorKit_Elementor_Widget() );
}

/**
 * Enqueue editor styles.
 *
 * @return void
 */
function anchorkit_elementor_editor_styles() {
	wp_enqueue_style(
		'anchorkit-elementor-editor',
		plugin_dir_url( __FILE__ ) . '../css/anchorkit-elementor-editor.css',
		array(),
		ANCHORKIT_PLUGIN_VERSION
	);
}

/**
 * Enqueue editor scripts.
 *
 * @return void
 */
function anchorkit_elementor_editor_scripts() {
	wp_enqueue_script(
		'anchorkit-elementor-editor',
		plugin_dir_url( __FILE__ ) . '../js/anchorkit-elementor-editor.js',
		array( 'jquery' ), // Removed elementor-frontend dependency as it may not be available in editor context.
		ANCHORKIT_PLUGIN_VERSION,
		true
	);

	if ( ! isset( $GLOBALS['anchorkit_elementor_reset_localized'] ) ) {
		if ( ! class_exists( 'AnchorKit_Elementor_Widget' ) ) {
			require_once __DIR__ . '/elementor-widget-class.php';
		}

		$reset_config = method_exists( 'AnchorKit_Elementor_Widget', 'get_reset_schema_static' )
			? AnchorKit_Elementor_Widget::get_reset_schema_static()
			: array(
				'sections'     => array(),
				'all_controls' => array(),
			);

		wp_localize_script(
			'anchorkit-elementor-editor',
			'anchorkitElementorResetConfig',
			array(
				'sections'     => $reset_config['sections'] ?? array(),
				'all_controls' => $reset_config['all_controls'] ?? array(),
				'strings'      => array(
					// translators: %s is the section name being reset (e.g., "Title", "Container").
					'sectionConfirm' => __( 'Reset %s settings to defaults?', 'anchorkit-table-of-contents' ),
					'allConfirm'     => __( 'Reset ALL AnchorKit settings in this widget? This cannot be undone.', 'anchorkit-table-of-contents' ),
					// translators: %s is the section name that was reset (e.g., "Title", "Container").
					'sectionSuccess' => __( '%s settings reset to defaults.', 'anchorkit-table-of-contents' ),
					'allSuccess'     => __( 'Widget reset to defaults.', 'anchorkit-table-of-contents' ),
					'noWidget'       => __( 'Open the AnchorKit TOC widget panel before resetting.', 'anchorkit-table-of-contents' ),
				),
			)
		);

		$GLOBALS['anchorkit_elementor_reset_localized'] = true;
	}
}
