<?php

namespace Elementor\Modules\AtomicWidgets\Elements\Base;

use Elementor\Modules\AtomicWidgets\Elements\Loader\Frontend_Assets_Loader;
use Elementor\Modules\AtomicWidgets\PropDependencies\Manager as Dependency_Manager;
use Elementor\Modules\AtomicWidgets\PropTypes\Concerns\Has_Meta;
use Elementor\Widget_Base;

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

abstract class Atomic_Widget_Base extends Widget_Base {
	use Has_Atomic_Base;
	use Has_Meta;

	public static $widget_description = null;

	protected $version = '0.0';
	protected $styles = [];
	protected $interactions = [];
	protected $editor_settings = [];
	protected $origin_id = null;

	public function __construct( $data = [], $args = null ) {
		parent::__construct( $data, $args );

		$this->version = $data['version'] ?? '0.0';
		$this->styles = $data['styles'] ?? [];
		$this->interactions = $this->parse_atomic_interactions( $data['interactions'] ?? [] );
		$this->editor_settings = $data['editor_settings'] ?? [];
		if ( static::$widget_description ) {
			$this->description( static::$widget_description );
		}
		$this->origin_id = $data['origin_id'] ?? null;
	}

	private function parse_atomic_interactions( $interactions ) {
		if ( empty( $interactions ) ) {
			return [];
		}

		if ( is_string( $interactions ) ) {
			$decoded = json_decode( $interactions, true );
			if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
				$interactions = $decoded;
			}
		}

		if ( ! is_array( $interactions ) ) {
			return [];
		}

		return $interactions;
	}

	abstract protected function define_atomic_controls(): array;

	protected function define_atomic_pseudo_states(): array {
		return [];
	}

	public function get_global_scripts() {
		return [];
	}

	public function get_initial_config() {
		$config = parent::get_initial_config();
		$props_schema = static::get_props_schema();

		$config['atomic'] = true;
		$config['atomic_controls'] = $this->get_atomic_controls();
		$config['base_styles'] = $this->get_base_styles();
		$config['base_styles_dictionary'] = $this->get_base_styles_dictionary();
		$config['atomic_props_schema'] = $props_schema;
		$config['atomic_pseudo_states'] = $this->define_atomic_pseudo_states();
		$config['dependencies_per_target_mapping'] = Dependency_Manager::get_source_to_dependents( $props_schema );
		$config['version'] = $this->version;
		$config['meta'] = $this->get_meta();

		return $config;
	}

	public function get_categories(): array {
		return [ 'v4-elements' ];
	}

	public function before_render() {}

	public function after_render() {}

	abstract protected static function define_props_schema(): array;

	public static function generate() {
		return Widget_Builder::make( static::get_element_type() );
	}

	public function get_script_depends() {
		return [ Frontend_Assets_Loader::ATOMIC_WIDGETS_HANDLER ];
	}

	public function get_interaction_id() {
		return $this->origin_id ?? $this->get_id();
	}
}
