<?php
/**
 * Comparison Bar widget — sticky bar showing vehicles queued for comparison.
 *
 * Free tier: thin wrapper around Frontend\CompareHandler::renderPage(), which
 * renders the full comparison view + clears button. Compare state lives in
 * sessionStorage on the client (per ADR-29 — anonymous, no logging) so this
 * widget produces a JS-hydrated shell.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Frontend\CompareHandler;

class ComparisonBarWidget extends Widget_Base {

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

	public function get_title(): string {
		return __( 'Comparison Bar', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		return 'eicon-table-of-contents';
	}

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

	public function get_keywords(): array {
		return array( 'compare', 'comparison', 'bar' );
	}

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

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

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_content',
			array(
				'label' => __( 'Content', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'heading',
			array(
				'label'   => __( 'Heading', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::TEXT,
				'default' => __( 'Compare Vehicles', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'empty_message',
			array(
				'label'   => __( 'Empty State Message', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::TEXT,
				'default' => __( 'Add vehicles to compare from the listings.', 'trx-auto-dealer' ),
			)
		);

		$this->end_controls_section();

		// ----------------------------------------------------------------
		// Comparison fields — toggle which spec rows appear in the table
		// below the cards. Order in $fields_config drives row order.
		// ----------------------------------------------------------------
		$this->start_controls_section(
			'section_fields',
			array(
				'label' => __( 'Comparison Fields', 'trx-auto-dealer' ),
			)
		);

		$default_on    = array_flip( CompareHandler::defaultFields() );
		$fields_config = array(
			'price'            => __( 'Price', 'trx-auto-dealer' ),
			'sale_price'       => __( 'Sale Price', 'trx-auto-dealer' ),
			'year'             => __( 'Year', 'trx-auto-dealer' ),
			'mileage'          => __( 'Mileage', 'trx-auto-dealer' ),
			'body_style'       => __( 'Body Style', 'trx-auto-dealer' ),
			'fuel_type'        => __( 'Fuel Type', 'trx-auto-dealer' ),
			'transmission'     => __( 'Transmission', 'trx-auto-dealer' ),
			'drivetrain'       => __( 'Drivetrain', 'trx-auto-dealer' ),
			'condition_type'   => __( 'Condition', 'trx-auto-dealer' ),
			'doors'            => __( 'Doors', 'trx-auto-dealer' ),
			'seats'            => __( 'Seats', 'trx-auto-dealer' ),
			'color_ext'        => __( 'Exterior Color', 'trx-auto-dealer' ),
			'color_int'        => __( 'Interior Color', 'trx-auto-dealer' ),
			'engine'           => __( 'Engine', 'trx-auto-dealer' ),
			'horsepower'       => __( 'Horsepower', 'trx-auto-dealer' ),
			'torque'           => __( 'Torque', 'trx-auto-dealer' ),
			'weight'           => __( 'Weight', 'trx-auto-dealer' ),
			'mpg_combined'     => __( 'Combined Fuel Economy', 'trx-auto-dealer' ),
			'mpg_city'         => __( 'City Fuel Economy', 'trx-auto-dealer' ),
			'mpg_highway'      => __( 'Highway Fuel Economy', 'trx-auto-dealer' ),
			'co2_emissions'    => __( 'CO₂ Emissions', 'trx-auto-dealer' ),
			'battery_capacity' => __( 'Battery Capacity (EV)', 'trx-auto-dealer' ),
			'electric_range'   => __( 'Electric Range (EV)', 'trx-auto-dealer' ),
			'charge_time'      => __( 'Charge Time (EV)', 'trx-auto-dealer' ),
			'accident_free'    => __( 'Accident Free', 'trx-auto-dealer' ),
			'vin'              => __( 'VIN', 'trx-auto-dealer' ),
			'stock_number'     => __( 'Stock Number', 'trx-auto-dealer' ),
		);

		foreach ( $fields_config as $key => $label ) {
			$this->add_control(
				'show_' . $key,
				array(
					'label'        => $label,
					'type'         => Controls_Manager::SWITCHER,
					'default'      => isset( $default_on[ $key ] ) ? 'yes' : '',
					'return_value' => 'yes',
				)
			);
		}

		$this->end_controls_section();

		$this->start_controls_section(
			'section_style',
			array(
				'label' => __( 'Style', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'heading_color',
			array(
				'label'     => __( 'Heading Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-compare-page__heading' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'heading_typography',
				'selector' => '{{WRAPPER}} .trx-ad-compare-page__heading',
			)
		);

		$this->add_control(
			'box_bg',
			array(
				'label'     => __( 'Box Background', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-compare-page' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'table_label_color',
			array(
				'label'     => __( 'Table Label Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-compare-page__specs th' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'table_value_color',
			array(
				'label'     => __( 'Table Value Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-compare-page__specs td' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'table_border_color',
			array(
				'label'     => __( 'Table Border Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-compare-page__specs th, {{WRAPPER}} .trx-ad-compare-page__specs td' => 'border-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();
		$heading  = (string) ( $settings['heading'] ?? '' );
		$empty    = (string) ( $settings['empty_message'] ?? '' );

		// Collect enabled spec fields (preserves widget control order so the
		// admin's order in the inspector matches the row order in the table).
		$all_keys = array_keys( CompareHandler::compareFieldConfigKeys() );
		$enabled  = array();
		foreach ( $all_keys as $key ) {
			if ( 'yes' === ( $settings[ 'show_' . $key ] ?? '' ) ) {
				$enabled[] = $key;
			}
		}

		// CompareHandler::renderPage() emits the section + optional heading +
		// grid + spec-table slots that frontend.js' hydrateComparePage
		// targets. The widget's Heading control (defaults to "Compare
		// Vehicles", clearable) passes straight through; empty text is still
		// a post-process replacement so the data-* selectors the JS hooks
		// onto stay intact.
		$html = CompareHandler::renderPage( $enabled, $heading );
		if ( '' !== $empty ) {
			$html = preg_replace(
				'/(<p[^>]*data-trx-ad-compare-empty[^>]*>)[^<]*(<\\/p>)/',
				'$1' . esc_html( $empty ) . '$2',
				$html,
				1
			);
		}

		echo wp_kses( $html, \ThemeREX\AutoDealer\allowedHtml() );
	}
}
