<?php

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Elementor\Widgets\Controls\SpecsHighlightsControls;
use ThemeREX\AutoDealer\Frontend\SpecsHighlightsRenderer;

/**
 * Specs Highlights widget — configurable specs bar with taxonomy icons.
 *
 * @package ThemeREX\AutoDealer
 */
// Bail if Elementor isn't loaded — prevents a fatal during PSR-4 autoload
// when this file is included on a site that doesn't have Elementor active.
if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

class SpecsHighlightsWidget extends Widget_Base {

	// Elementor control schema lives in this trait — 450L of declarative
	// `add_control()` / `add_responsive_control()` calls that pre-T2-2f
	// drowned out the render logic. Traits compile in as first-class
	// private members so `$this->add_control(...)` still resolves to
	// `Widget_Base`.
	use SpecsHighlightsControls;

	public function get_name(): string {
		return 'trx_ad_specs_highlights';
	}

	public function get_title(): string {
		return __( 'Listing Specs Highlights', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		return 'eicon-info-box';
	}

	public function get_categories(): array {
		return array( 'trx-auto-dealer' );
	}

	public function get_style_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-widget-specs-highlights' );
	}

	public function get_script_depends(): array {
		return array( 'trx-ad-frontend' );
	}

	// ------------------------------------------------------------------
	// Controls
	// ------------------------------------------------------------------

	protected function register_controls(): void {
		$this->registerContentControls();
		$this->registerStyleTitleControls();
		$this->registerStyleItemControls();
		$this->registerStyleIconControls();
		$this->registerStyleLabelControls();
		$this->registerStyleValueControls();
	}

	// ------------------------------------------------------------------
	// Render
	// ------------------------------------------------------------------

	protected function render(): void {
		$settings = $this->get_settings_for_display();
		$post_id  = (int) ( $settings['vehicle_id'] ?? 0 );
		if ( $post_id <= 0 ) {
			$post_id = (int) $this->getPreviewPostId();
		}

		$sources   = $settings['sources'] ?? array();
		$showIcons = ( $settings['show_icons'] ?? 'yes' ) === 'yes';
		$showTitle = ( $settings['show_title'] ?? 'yes' ) === 'yes';
		$title     = $settings['title'] ?? '';
		$layout    = $settings['layout'] ?? 'horizontal';
		$isEditor  = \Elementor\Plugin::$instance->editor->is_edit_mode() || \Elementor\Plugin::$instance->preview->is_preview_mode();

		$items = array();
		if ( $post_id ) {
			$items = SpecsHighlightsRenderer::buildItems( (int) $post_id, is_array( $sources ) ? $sources : array() );
		}

		// Show demo data in editor when no real data available.
		if ( empty( $items ) && $isEditor ) {
			$items = $this->getDemoItems( $sources, $showIcons );
		}

		if ( empty( $items ) ) {
			return;
		}

		$itemClass = 'trx-ad-specs-highlights__item';
		if ( 'vertical' === $layout ) {
			$itemClass .= ' trx-ad-specs-highlights__item--vertical';
		}
		?>
		<div class="trx-ad-specs-highlights">
			<?php if ( $showTitle && '' !== $title ) : ?>
				<h2 class="trx-ad-specs-highlights__title"><?php echo esc_html( $title ); ?></h2>
			<?php endif; ?>

			<div class="trx-ad-specs-highlights__grid">
				<?php foreach ( $items as $item ) : ?>
					<div class="<?php echo esc_attr( $itemClass ); ?>">
						<?php if ( $showIcons && ! empty( $item['icon'] ) ) : ?>
							<span class="trx-ad-specs-highlights__icon">
								<?php echo wp_kses( $item['icon'], \ThemeREX\AutoDealer\allowedHtml() ); ?>
							</span>
						<?php endif; ?>
						<span class="trx-ad-specs-highlights__text">
							<span class="trx-ad-specs-highlights__label"><?php echo esc_html( $item['label'] ); ?></span>
							<span class="trx-ad-specs-highlights__value"><?php echo esc_html( $item['value'] ); ?></span>
						</span>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Get the correct post ID for preview — uses Elementor's preview post if in editor.
	 *
	 * @return int|false
	 */
	private function getPreviewPostId() {
		// Frontend: normal post context.
		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() && ! \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
			return get_the_ID();
		}

		// Editor/Preview: try to get a real listing post for preview.
		// Check if Elementor has a preview post set.
		$preview_id = \Elementor\Plugin::$instance->documents->get_current()
			? \Elementor\Plugin::$instance->documents->get_current()->get_settings( 'preview_id' )
			: 0;

		if ( $preview_id && 'trx_ad_listing' === get_post_type( $preview_id ) ) {
			return (int) $preview_id;
		}

		// Fallback: get the most recent listing post.
		$posts = get_posts(
			array(
				'post_type'      => 'trx_ad_listing',
				'posts_per_page' => 1,
				'post_status'    => 'publish',
				'fields'         => 'ids',
			)
		);

		return ! empty( $posts ) ? (int) $posts[0] : false;
	}

	/**
	 * Generate demo items for the editor preview.
	 *
	 * @param array $sources   Selected sources.
	 * @param bool  $showIcons Whether icons are enabled.
	 * @return array<int, array{icon: string, label: string, value: string}>
	 */
	private function getDemoItems( array $sources, bool $showIcons ): array {
		$allOptions = SpecsHighlightsRenderer::getSourceOptions();
		$demoValues = array(
			'_year'               => '2024',
			'_mileage'            => '12,500 km',
			'trx_ad_make'         => 'Toyota',
			'trx_ad_model'        => 'Camry',
			'trx_ad_body_style'   => 'Sedan',
			'trx_ad_fuel_type'    => 'Petrol',
			'trx_ad_transmission' => 'Automatic',
			'trx_ad_drivetrain'   => 'FWD',
			'trx_ad_color'        => 'White',
			'trx_ad_vehicle_type' => 'Car',
			'trx_ad_condition'    => 'Used',
			'trx_ad_feature'      => 'Bluetooth',
		);

		$keys  = ! empty( $sources ) ? $sources : array_keys( $allOptions );
		$items = array();

		foreach ( $keys as $key ) {
			if ( ! isset( $allOptions[ $key ] ) ) {
				continue;
			}
			$items[] = array(
				'icon'  => $showIcons ? \ThemeREX\AutoDealer\Admin\TaxonomyIconFields::getTaxonomyIconHtml( $key ) : '',
				'label' => $allOptions[ $key ],
				'value' => $demoValues[ $key ] ?? 'Sample',
			);
		}

		return $items;
	}
}
