<?php
/**
 * Elementor Markdown article widget.
 *
 * @package MarkBlocks
 */

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

/**
 * Renders Markdown and provides the editor-only native-widget converter.
 */
final class MarkBlocks_Markdown_Article_Widget extends \Elementor\Widget_Base {
	/**
	 * Elementor widget identifier.
	 */
	public function get_name(): string {
		// Retained for compatibility with content created by pre-release builds.
		return 'emb_markdown_article';
	}

	/**
	 * Widget title shown in the Elementor panel.
	 */
	public function get_title(): string {
		return esc_html__( 'Markdown Article', 'markblocks' );
	}

	/**
	 * Elementor icon identifier.
	 */
	public function get_icon(): string {
		return 'eicon-editor-code';
	}

	/**
	 * Elementor categories containing this widget.
	 *
	 * @return string[]
	 */
	public function get_categories(): array {
		return [ 'markblocks-content' ];
	}

	/**
	 * Search keywords for the Elementor panel.
	 *
	 * @return string[]
	 */
	public function get_keywords(): array {
		return [ 'markdown', 'article', 'code', 'import', 'blog' ];
	}

	/**
	 * Conditional frontend script dependencies.
	 *
	 * @return string[]
	 */
	public function get_script_depends(): array {
		return [ 'markblocks-frontend' ];
	}

	/**
	 * Conditional frontend style dependencies.
	 *
	 * @return string[]
	 */
	public function get_style_depends(): array {
		return [ 'markblocks-frontend' ];
	}

	/**
	 * Avoid an unnecessary Elementor wrapper around the widget markup.
	 */
	public function has_widget_inner_wrapper(): bool {
		return false;
	}

	/**
	 * Register Elementor controls.
	 */
	protected function register_controls(): void {
		$this->start_controls_section(
			'content_section',
			[ 'label' => esc_html__( 'Markdown Source', 'markblocks' ) ]
		);

		$this->add_control(
			'markdown',
			[
				'label'       => esc_html__( 'Markdown', 'markblocks' ),
				'type'        => \Elementor\Controls_Manager::TEXTAREA,
				'rows'        => 24,
				'default'     => "## Example heading\n\nPaste your Markdown article here.\n\n```bash\nget system status\n```",
				'placeholder' => esc_html__( 'Paste the complete Markdown article…', 'markblocks' ),
			]
		);

		$this->add_control(
			'show_article',
			[
				'label'        => esc_html__( 'Render Markdown source', 'markblocks' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'markblocks' ),
				'label_off'    => esc_html__( 'Hide', 'markblocks' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__( 'The converter hides this source after creating native widgets, while preserving the Markdown for later updates.', 'markblocks' ),
			]
		);

		$this->add_control(
			'code_theme',
			[
				'label'   => esc_html__( 'Code theme', 'markblocks' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'default' => 'midnight',
				'options' => [
					'midnight' => esc_html__( 'Midnight', 'markblocks' ),
					'light'    => esc_html__( 'Light', 'markblocks' ),
				],
			]
		);

		$this->add_control(
			'show_copy',
			[
				'label'        => esc_html__( 'Code copy button', 'markblocks' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'conversion_section',
			[ 'label' => esc_html__( 'Convert to Elementor', 'markblocks' ) ]
		);

		$this->add_control(
			'replace_previous',
			[
				'label'        => esc_html__( 'Replace previous import', 'markblocks' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__( 'Creates the replacement first, then removes only the previously generated container that belongs to this source widget.', 'markblocks' ),
			]
		);

		$this->add_control(
			'generated_container_id',
			[
				'type'    => \Elementor\Controls_Manager::HIDDEN,
				'default' => '',
			]
		);

		$convert_button = '<button type="button" class="elementor-button elementor-button-success markblocks-convert-markdown"><i class="eicon-import-export" aria-hidden="true"></i> ' . esc_html__( 'Convert / Update Elementor Blocks', 'markblocks' ) . '</button>';
		$status         = '<div class="markblocks-convert-status" role="status" aria-live="polite" aria-atomic="true"></div>';
		$help           = '<p class="markblocks-convert-help">' . esc_html__( 'Creates a new container with native Heading, Text Editor, Divider and Image widgets, plus editable Markdown Code Block widgets.', 'markblocks' ) . '</p>';

		$this->add_control(
			'convert_action',
			[
				'type' => \Elementor\Controls_Manager::RAW_HTML,
				'raw'  => $convert_button . $status . $help,
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'style_section',
			[
				'label' => esc_html__( 'Article Style', 'markblocks' ),
				'tab'   => \Elementor\Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			\Elementor\Group_Control_Typography::get_type(),
			[
				'name'     => 'typography',
				'selector' => '{{WRAPPER}} .markblocks-markdown-body',
			]
		);

		$this->add_control(
			'text_color',
			[
				'label'     => esc_html__( 'Text color', 'markblocks' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .markblocks-markdown-body' => 'color: {{VALUE}};' ],
			]
		);

		$this->add_control(
			'link_color',
			[
				'label'     => esc_html__( 'Link color', 'markblocks' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .markblocks-markdown-body a' => 'color: {{VALUE}};' ],
			]
		);

		$this->add_control(
			'accent_color',
			[
				'label'     => esc_html__( 'Accent color', 'markblocks' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .markblocks-markdown-body blockquote' => 'border-inline-start-color: {{VALUE}};',
					'{{WRAPPER}} .markblocks-markdown-body th'         => 'border-bottom-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();
	}

	/**
	 * Render the Markdown source with a strict KSES allowlist.
	 */
	protected function render(): void {
		$settings    = $this->get_settings_for_display();
		$show_source = 'yes' === ( $settings['show_article'] ?? 'yes' );
		$is_editor   = isset( \Elementor\Plugin::$instance->editor ) && \Elementor\Plugin::$instance->editor->is_edit_mode();

		if ( ! $show_source ) {
			if ( $is_editor ) {
				echo '<div class="markblocks-source-hidden-note">' . esc_html__( 'Markdown source is preserved but hidden on the front end. Use the widget controls to edit or reconvert it.', 'markblocks' ) . '</div>';
			}
			return;
		}

		$parser = new MarkBlocks_Markdown_Parser(
			'yes' === ( $settings['show_copy'] ?? 'yes' ),
			(string) ( $settings['code_theme'] ?? 'midnight' )
		);

		$html = $parser->parse( (string) ( $settings['markdown'] ?? '' ) );

		echo '<div class="markblocks-markdown-body">';
		echo wp_kses( $html, MarkBlocks_Markdown_Parser::allowed_html(), [ 'http', 'https', 'mailto', 'tel' ] );
		echo '</div>';
	}
}
