<?php
namespace AIPT\Api\BulkGenerator\FAQ;

/**
 * Handles frontend rendering for FAQ display on WooCommerce product pages.
 *
 * Enqueues base CSS, outputs dynamic CSS custom properties, and renders
 * accordion HTML when accordion display is enabled.
 *
 * @package AIPT\Api\BulkGenerator\FAQ
 */
class FAQFrontendRenderer {

	/**
	 * SVG data URIs for toggle icon variants.
	 *
	 * @var array<string, string>
	 */
	private static $toggle_icons = [
		'chevron' => "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E\")",
		'plus'    => "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Cpath d='M12 5v14M5 12h14'/%3E%3C/svg%3E\")",
		'arrow'   => "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Cpath d='M5 12h14M12 5l7 7-7 7'/%3E%3C/svg%3E\")",
		'caret'   => "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'%3E%3Cpath d='M8 5v14l11-7z'/%3E%3C/svg%3E\")",
	];

	/**
	 * Get toggle icon SVG data URIs.
	 *
	 * Shared by FAQShortcode for inline CSS output.
	 *
	 * @return array<string, string>
	 */
	public static function get_toggle_icons(): array {
		return self::$toggle_icons;
	}

	/**
	 * Check if FAQ data exists for the current product page.
	 *
	 * @return bool True if on a product page with FAQ data stored.
	 */
	public static function should_render(): bool {
		if ( ! function_exists( 'is_product' ) || ! is_product() ) {
			return false;
		}

		$product_id = get_the_ID();
		if ( ! $product_id ) {
			return false;
		}

		$faq_data = get_post_meta( $product_id, '_aipt_faq_data', true );
		return ! empty( $faq_data );
	}

	/**
	 * Determine if FAQ CSS should be loaded on the current page.
	 *
	 * CSS is needed for both accordion and flat list modes when
	 * FAQ data exists on a product page and display_mode is 'auto'.
	 *
	 * @return bool
	 */
	private static function needs_faq_css(): bool {
		if ( ! self::should_render() ) {
			return false;
		}

		$settings = new FAQDisplaySettings();
		$all      = $settings->getAll();

		if ( ! empty( $all['display_mode'] ) && 'shortcode' === $all['display_mode'] ) {
			return false;
		}

		return true;
	}

	/**
	 * Enqueue base FAQ CSS.
	 * Hooked to wp_enqueue_scripts.
	 *
	 * @return void
	 */
	public static function enqueue_styles(): void {
		if ( ! self::needs_faq_css() ) {
			return;
		}

		wp_enqueue_style(
			'aipt-faq-display',
			AIPT_PLUGIN_URL . 'dist/css/faq-display.css',
			[],
			AIPT_VERSION
		);
	}

	/**
	 * Output dynamic CSS custom properties in wp_head.
	 * Hooked to wp_head.
	 *
	 * @return void
	 */
	public static function render_dynamic_css(): void {
		if ( ! self::needs_faq_css() ) {
			return;
		}

		$settings_obj = new FAQDisplaySettings();
		$settings     = $settings_obj->getAll();

		$css_vars = [];
		$map      = [
			'question_color'   => '--aipt-faq-question-color',
			'answer_color'     => '--aipt-faq-answer-color',
			'background_color' => '--aipt-faq-background-color',
			'border_color'     => '--aipt-faq-border-color',
			'font_family'      => '--aipt-faq-font-family',
			'font_size'        => '--aipt-faq-font-size',
			'font_weight'      => '--aipt-faq-font-weight',
			'padding_top'              => '--aipt-faq-padding-top',
			'padding_right'            => '--aipt-faq-padding-right',
			'padding_bottom'           => '--aipt-faq-padding-bottom',
			'padding_left'             => '--aipt-faq-padding-left',
			'margin_top'               => '--aipt-faq-margin-top',
			'margin_right'             => '--aipt-faq-margin-right',
			'margin_bottom'            => '--aipt-faq-margin-bottom',
			'margin_left'              => '--aipt-faq-margin-left',
			'gap'                      => '--aipt-faq-gap',
			'border_radius_top_left'   => '--aipt-faq-border-radius-tl',
			'border_radius_top_right'  => '--aipt-faq-border-radius-tr',
			'border_radius_bottom_right' => '--aipt-faq-border-radius-br',
			'border_radius_bottom_left'  => '--aipt-faq-border-radius-bl',
			'border_width_top'         => '--aipt-faq-border-width-top',
			'border_width_right'       => '--aipt-faq-border-width-right',
			'border_width_bottom'      => '--aipt-faq-border-width-bottom',
			'border_width_left'        => '--aipt-faq-border-width-left',
		];

		foreach ( $map as $setting_key => $css_var ) {
			if ( ! empty( $settings[ $setting_key ] ) ) {
				$css_vars[] = sprintf(
					'%s: %s;',
					esc_attr( $css_var ),
					esc_attr( $settings[ $setting_key ] )
				);
			}
		}

		$toggle_icon = isset( $settings['toggle_icon'] ) ? $settings['toggle_icon'] : 'chevron';
		if ( isset( self::$toggle_icons[ $toggle_icon ] ) ) {
			$css_vars[] = '--aipt-faq-toggle-icon: ' . self::$toggle_icons[ $toggle_icon ] . ';';
		}

		$output_parts = [];

		if ( ! empty( $css_vars ) ) {
			$output_parts[] = '.aipt-faq-accordion,.aipt-faq-flat{' . implode( '', $css_vars ) . '}';
		}

		$custom_css = isset( $settings['custom_css'] ) ? trim( (string) $settings['custom_css'] ) : '';
		if ( '' !== $custom_css ) {
			$safe_css       = preg_replace( '#<\s*/?\s*(style|script)\b[^>]*>#i', '', $custom_css );
			$output_parts[] = $safe_css;
		}

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

		$css = wp_strip_all_tags( implode( "\n", $output_parts ) );
		echo '<style id="aipt-faq-dynamic-css">' . $css . '</style>' . "\n"; 
	}

	/**
	 * Build the container CSS classes for the accordion.
	 *
	 * @param array<string, mixed> $settings Display settings.
	 * @return string Space-separated class string.
	 */
	public static function build_container_classes( array $settings ): string {
		$classes = [];

		$custom_class = isset( $settings['container_class_name'] ) ? trim( (string) $settings['container_class_name'] ) : '';
		if ( $custom_class !== '' ) {
			$tokens = preg_split( '/\s+/', $custom_class, -1, PREG_SPLIT_NO_EMPTY );
			if ( is_array( $tokens ) ) {
				foreach ( $tokens as $token ) {
					$sanitized_token = sanitize_html_class( $token );
					if ( $sanitized_token !== '' ) {
						$classes[] = $sanitized_token;
					}
				}
			}
		}

		$theme_preset = ! empty( $settings['theme_preset'] ) ? $settings['theme_preset'] : 'default';
		$classes[]    = 'aipt-faq-accordion--' . sanitize_html_class( $theme_preset );

		$animation = isset( $settings['animation'] ) ? $settings['animation'] : '';
		if ( ! empty( $animation ) && 'none' !== $animation ) {
			$classes[] = 'aipt-faq-accordion--' . sanitize_html_class( $animation );
		}

		return implode( ' ', $classes );
	}

	/**
	 * Render FAQ content after single product summary.
	 * Hooked to woocommerce_after_single_product_summary.
	 *
	 * Chooses between accordion and flat list output based on settings.
	 * Skips rendering when display_mode is 'shortcode' (user places manually).
	 *
	 * @return void
	 */
	public static function render_accordion_content(): void {
		if ( ! self::should_render() ) {
			return;
		}

		$settings_obj = new FAQDisplaySettings();
		$settings     = $settings_obj->getAll();

		if ( ! empty( $settings['display_mode'] ) && 'shortcode' === $settings['display_mode'] ) {
			return;
		}

		$product_id = get_the_ID();
		$faq_data   = get_post_meta( $product_id, '_aipt_faq_data', true );
		$faqs       = json_decode( $faq_data, true );

		if ( ! is_array( $faqs ) || empty( $faqs ) ) {
			return;
		}

		if ( ! empty( $settings['accordion_enabled'] ) ) {

			$render_settings = [
				'container_class_name' => self::build_container_classes( $settings ),
			];

			echo FAQTemplateRenderer::renderAccordion( $faqs, $render_settings );
		} else {

			echo FAQTemplateRenderer::renderFlat( $faqs, 'html', $settings );
		}
	}
}
