<?php
/**
 * Button HTML rendering.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Buttons_Render
 */
class Rsmspark_Buttons_Render {

	const REGISTRY_ID = 'buttons';

	/**
	 * @param array<string, mixed> $config Button config.
	 * @param int                  $button_id Optional saved button ID.
	 * @param bool                 $force     Skip widget-enabled check (admin preview).
	 * @return string
	 */
	public static function render( array $config, $button_id = 0, $force = false ) {
		if ( ! $force && ! self::can_render() ) {
			return '';
		}

		$config = Rsmspark_Buttons_Config::sanitize( $config );
		if ( '' === trim( (string) $config['text_line_1'] ) ) {
			return '';
		}

		Rsmspark_Content_Widgets_Render::mark_assets_needed( self::REGISTRY_ID );

		$url = self::resolve_url( $config );
		if ( '' === $url ) {
			$url = '#';
		}

		$classes = array(
			'rsmspark-btn',
			'rsmspark-btn--' . sanitize_html_class( (string) $config['shape'] ),
			'rsmspark-btn--' . sanitize_html_class( (string) $config['size'] ),
			'rsmspark-btn--shadow-' . sanitize_html_class( (string) $config['shadow'] ),
			'rsmspark-btn--hover-' . sanitize_html_class( (string) $config['hover_effect'] ),
		);

		if ( 'full' === $config['width'] ) {
			$classes[] = 'rsmspark-btn--full';
		} elseif ( 'custom_px' === $config['width'] ) {
			$classes[] = 'rsmspark-btn--custom-width';
		}

		if ( ! empty( $config['extra_class'] ) ) {
			foreach ( preg_split( '/\s+/', (string) $config['extra_class'] ) as $extra_class ) {
				$extra_class = sanitize_html_class( (string) $extra_class );
				if ( '' !== $extra_class ) {
					$classes[] = $extra_class;
				}
			}
		}

		$style = self::build_css_vars( $config );

		$attrs = array(
			'href'  => $url,
			'class' => implode( ' ', array_filter( $classes ) ),
			'style' => $style,
		);

		if ( ! empty( $config['button_id'] ) ) {
			$attrs['id'] = $config['button_id'];
		}

		if ( $button_id > 0 ) {
			$attrs['data-rsmspark-button-id'] = (string) absint( $button_id );
		}

		if ( ! empty( $config['target_blank'] ) ) {
			$attrs['target'] = '_blank';
		}

		if ( ! empty( $config['rel'] ) ) {
			$attrs['rel'] = $config['rel'];
		}

		$aria = trim( (string) $config['aria_label'] );
		if ( '' !== $aria ) {
			$attrs['aria-label'] = $aria;
		}

		$html  = '<a';
		foreach ( $attrs as $name => $value ) {
			$html .= sprintf( ' %s="%s"', esc_attr( $name ), esc_attr( (string) $value ) );
		}
		$html .= '><span class="rsmspark-btn__inner">';

		if ( self::has_icon( $config ) && 'left' === $config['icon_position'] ) {
			$html .= self::render_icon( $config );
		}

		$html .= '<span class="rsmspark-btn__text">';
		$html .= '<span class="rsmspark-btn__line1">' . esc_html( (string) $config['text_line_1'] ) . '</span>';
		if ( '' !== trim( (string) $config['text_line_2'] ) ) {
			$html .= '<span class="rsmspark-btn__line2">' . esc_html( (string) $config['text_line_2'] ) . '</span>';
		}
		$html .= '</span>';

		if ( self::has_icon( $config ) && 'right' === $config['icon_position'] ) {
			$html .= self::render_icon( $config );
		}

		$html .= '</span></a>';

		return (string) apply_filters( 'rsmspark_button_rendered_html', $html, $config, $button_id );
	}

	/**
	 * @param array<string, mixed> $config Config.
	 * @return bool
	 */
	private static function has_icon( array $config ) {
		if ( 'image' === ( $config['icon_type'] ?? 'sprite' ) && absint( $config['icon_image_id'] ?? 0 ) > 0 ) {
			return true;
		}

		return '' !== trim( (string) ( $config['icon'] ?? '' ) );
	}

	/**
	 * @param array<string, mixed> $config Config.
	 * @return string
	 */
	private static function render_icon( array $config ) {
		if ( 'image' === ( $config['icon_type'] ?? 'sprite' ) && absint( $config['icon_image_id'] ?? 0 ) > 0 ) {
			$image_id = absint( $config['icon_image_id'] );
			$src      = wp_get_attachment_image_url( $image_id, 'thumbnail' );
			if ( ! $src ) {
				return '';
			}

			return sprintf(
				'<img class="rsmspark-btn__icon rsmspark-btn__icon--img" src="%s" alt="" aria-hidden="true" />',
				esc_url( $src )
			);
		}

		$icon = Rsmspark_Buttons_Config::sanitize_icon( (string) ( $config['icon'] ?? '' ) );
		if ( '' === $icon ) {
			return '';
		}

		$icon_type = (string) ( $config['icon_type'] ?? 'sprite' );
		if ( 'dashicon' === $icon_type ) {
			$icon_class = sanitize_html_class( $icon );
			if ( false === strpos( $icon_class, 'dashicons-' ) ) {
				$icon_class = 'dashicons-' . $icon_class;
			}

			return '<span class="rsmspark-btn__icon dashicons ' . esc_attr( $icon_class ) . '" aria-hidden="true"></span>';
		}

		$icon_markup = Rsmspark_Buttons_Icons::render_use_markup( $icon );
		if ( '' === $icon_markup ) {
			return '';
		}

		if (
			class_exists( 'Rsmspark_Content_Widgets_Blocks', false )
			&& Rsmspark_Content_Widgets_Blocks::is_editor_preview_request()
		) {
			return Rsmspark_Buttons_Icons::get_sprite_markup() . $icon_markup;
		}

		return $icon_markup;
	}

	/**
	 * @param array<string, mixed> $config Config.
	 * @return string
	 */
	public static function build_css_vars( array $config ) {
		$radius = 'pill' === $config['shape'] ? '999px' : absint( $config['border_radius'] ) . 'px';
		$bg     = (string) $config['bg_color'];

		$vars = array(
			'--rsmspark-btn-bg'              => $bg,
			'--rsmspark-btn-bg-hover'        => (string) $config['bg_hover_color'],
			'--rsmspark-btn-text'            => (string) $config['text_color'],
			'--rsmspark-btn-text-hover'      => (string) $config['text_hover_color'],
			'--rsmspark-btn-border'          => (string) $config['border_color'],
			'--rsmspark-btn-border-hover'    => (string) $config['border_hover_color'],
			'--rsmspark-btn-border-width'    => absint( $config['border_width'] ) . 'px',
			'--rsmspark-btn-border-style'    => (string) $config['border_style'],
			'--rsmspark-btn-radius'          => $radius,
			'--rsmspark-btn-transition'      => (float) $config['transition_duration'] . 's',
			'--rsmspark-btn-font-weight'     => (string) $config['font_weight'],
			'--rsmspark-btn-text-transform'  => (string) $config['text_transform'],
		);

		if ( absint( $config['font_size'] ) > 0 ) {
			$vars['--rsmspark-btn-font-size'] = absint( $config['font_size'] ) . 'px';
		}

		if ( absint( $config['padding_x'] ) > 0 ) {
			$vars['--rsmspark-btn-padding-x'] = absint( $config['padding_x'] ) . 'px';
		}

		if ( absint( $config['padding_y'] ) > 0 ) {
			$vars['--rsmspark-btn-padding-y'] = absint( $config['padding_y'] ) . 'px';
		}

		if ( '' !== trim( (string) $config['icon_color'] ) && 'transparent' !== strtolower( (string) $config['icon_color'] ) ) {
			$vars['--rsmspark-btn-icon-color'] = (string) $config['icon_color'];
		}

		if ( 'custom_px' === $config['width'] ) {
			$vars['--rsmspark-btn-width'] = absint( $config['custom_width_px'] ) . 'px';
		}

		$parts = array();
		foreach ( $vars as $key => $value ) {
			$parts[] = $key . ':' . $value;
		}

		return implode( ';', $parts );
	}

	/**
	 * Buttons honor the shared widget enable gate and editor preview filter.
	 *
	 * @return bool
	 */
	public static function can_render() {
		if ( ! class_exists( 'Rsmspark_Content_Widgets_Render', false ) ) {
			return true;
		}

		return Rsmspark_Content_Widgets_Render::should_render( self::REGISTRY_ID );
	}

	/**
	 * @param array<string, mixed> $config Config.
	 * @return string
	 */
	private static function resolve_url( array $config ) {
		if ( 'post' === $config['link_type'] && $config['link_post_id'] > 0 ) {
			$permalink = get_permalink( absint( $config['link_post_id'] ) );
			return $permalink ? (string) $permalink : '';
		}

		return (string) $config['link_url'];
	}
}
