<?php
/**
 * Comments form — native WordPress comment_form() for the current post/page.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class CommentsFormWidget extends WidgetBase {

	public function get_type(): string {
		return 'comments_form';
	}

	public function get_title(): string {
		return 'Formulário de comentários';
	}

	public function get_category(): string {
		return 'dynamic';
	}

	public function get_icon(): string {
		return 'comments';
	}

	public function get_defaults(): array {
		return array(
			'title'           => 'Deixe um comentário',
			'show_title'      => '1',
			'show_list'       => '1',
			'list_title'      => 'Comentários',
			'require_name'    => '1',
			'submit_label'    => 'Publicar comentário',
			'btn_bg'          => '',
			'btn_color'       => '',
			'btn_full_width'  => '0',
			'btn_radius'      => '8',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$flag = static function ( $v, string $d = '1' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		$color = static function ( $v ): string {
			$v = trim( (string) $v );
			if ( $v === '' ) {
				return '';
			}
			if ( preg_match( '/^#([0-9a-fA-F]{3,8})$/', $v ) ) {
				return $v;
			}
			if ( preg_match( '/^rgba?\([^)]+\)$/', $v ) || preg_match( '/^hsla?\([^)]+\)$/', $v ) ) {
				return $v;
			}
			return sanitize_hex_color( $v ) ?: '';
		};
		$radius = sanitize_text_field( (string) ( $settings['btn_radius'] ?? '8' ) );
		if ( $radius !== '' && ! preg_match( '/^\d+(\.\d+)?(px|rem|em|%)?$/', $radius ) ) {
			$radius = '8';
		}
		return array(
			'title'          => sanitize_text_field( (string) ( $settings['title'] ?? 'Deixe um comentário' ) ),
			'show_title'     => $flag( $settings['show_title'] ?? null, '1' ),
			'show_list'      => $flag( $settings['show_list'] ?? null, '1' ),
			'list_title'     => sanitize_text_field( (string) ( $settings['list_title'] ?? 'Comentários' ) ),
			'require_name'   => $flag( $settings['require_name'] ?? null, '1' ),
			'submit_label'   => sanitize_text_field( (string) ( $settings['submit_label'] ?? 'Publicar comentário' ) ),
			'btn_bg'         => $color( $settings['btn_bg'] ?? '' ),
			'btn_color'      => $color( $settings['btn_color'] ?? '' ),
			'btn_full_width' => $flag( $settings['btn_full_width'] ?? null, '0' ),
			'btn_radius'     => $radius,
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s      = $node->settings;
		$editor = ! empty( $context['editor'] );
		$post_id = (int) ( $context['postId'] ?? get_the_ID() );

		if ( $editor ) {
			return $this->render_editor_preview( $s );
		}

		if ( $post_id <= 0 ) {
			return '';
		}

		// Temporarily set global $post for comment_form / comments_template.
		$post = get_post( $post_id );
		if ( ! $post ) {
			return '';
		}

		ob_start();
		$wrap_style = $this->wrapper_css_vars( $s );
		echo '<div class="ab-comments-form" data-ab-comments="1"'
			. ( $wrap_style !== '' ? ' style="' . esc_attr( $wrap_style ) . '"' : '' )
			. '>';

		if ( ( $s['show_list'] ?? '1' ) === '1' ) {
			$comments = get_comments(
				array(
					'post_id' => $post_id,
					'status'  => 'approve',
					'order'   => 'ASC',
				)
			);
			if ( $comments ) {
				$list_title = (string) ( $s['list_title'] ?? 'Comentários' );
				if ( $list_title !== '' ) {
					echo '<h3 class="ab-comments-form__list-title">' . esc_html( $list_title ) . '</h3>';
				}
				echo '<ol class="ab-comments-form__list">';
				wp_list_comments(
					array(
						'style'       => 'ol',
						'short_ping'  => true,
						'avatar_size' => 48,
					),
					$comments
				);
				echo '</ol>';
			}
		}

		if ( comments_open( $post_id ) ) {
			$submit  = (string) ( $s['submit_label'] ?? 'Publicar comentário' );
			$title   = ( $s['show_title'] ?? '1' ) === '1'
				? (string) ( $s['title'] ?? 'Deixe um comentário' )
				: '';
			$btn_st  = $this->button_inline_style( $s, $node );
			$btn_cls = 'ab-btn ab-comment-form__submit submit'
				. ( ( $s['btn_full_width'] ?? '0' ) === '1' ? ' is-full' : '' );
			$btn_attr = $btn_st !== '' ? ' style="' . esc_attr( $btn_st ) . '"' : '';

			// Field markup styled like the editor fake form.
			$comment_field = '<p class="ab-comment-form__row ab-comment-form__row--comment comment-form-comment">'
				. '<label for="comment">' . esc_html__( 'Comentário', 'auranet-page-theme-builder' )
				. ' <span class="required" aria-hidden="true">*</span></label>'
				. '<textarea id="comment" name="comment" class="ab-comment-form__control ab-comment-form__textarea" '
				. 'cols="45" rows="6" maxlength="65525" required="required" '
				. 'placeholder="' . esc_attr__( 'Escreva seu comentário…', 'auranet-page-theme-builder' ) . '"></textarea>'
				. '</p>';

			$args = array(
				'title_reply'          => $title,
				'title_reply_to'       => __( 'Responder a %s', 'auranet-page-theme-builder' ),
				'title_reply_before'   => '<h3 class="ab-comments-form__title comment-reply-title">',
				'title_reply_after'    => '</h3>',
				'label_submit'         => $submit,
				'class_container'      => 'ab-comments-form__form comment-respond',
				'class_form'           => 'ab-comment-form comment-form',
				'class_submit'         => $btn_cls,
				'submit_button'        => '<button name="%1$s" type="submit" id="%2$s" class="%3$s"' . $btn_attr . '>%4$s</button>',
				'submit_field'         => '<p class="ab-comment-form__row ab-comment-form__row--submit form-submit">%1$s %2$s</p>',
				'comment_field'        => $comment_field,
				'comment_notes_before' => '',
				'comment_notes_after'  => '',
				'logged_in_as'         => $this->logged_in_as_html( $post_id ),
				'fields'               => $this->author_fields_html(),
			);
			// phpcs:ignore WordPress.FAKESECRET_s1t2u3v4w5x6y7z8a9b0
			comment_form( $args, $post_id );
		} else {
			echo '<p class="ab-comments-form__closed">' . esc_html__( 'Comentários fechados.', 'auranet-page-theme-builder' ) . '</p>';
		}

		echo '</div>';
		return (string) ob_get_clean();
	}

	/**
	 * Editor canvas preview — same visual language as the public form.
	 *
	 * @param array<string, mixed> $s Settings.
	 */
	private function render_editor_preview( array $s ): string {
		$title  = esc_html( (string) ( $s['title'] ?? 'Deixe um comentário' ) );
		$submit = esc_html( (string) ( $s['submit_label'] ?? 'Publicar comentário' ) );
		$vars   = $this->wrapper_css_vars( $s );
		$full   = ( $s['btn_full_width'] ?? '0' ) === '1' ? ' is-full' : '';
		$html   = '<div class="ab-comments-form ab-comments-form--editor" data-ab-comments="1"'
			. ( $vars !== '' ? ' style="' . esc_attr( $vars ) . '"' : '' ) . '>';
		if ( ( $s['show_title'] ?? '1' ) === '1' ) {
			$html .= '<h3 class="ab-comments-form__title">' . $title . '</h3>';
		}
		$html .= '<div class="ab-comments-form__form ab-comment-form ab-comment-form--preview">';
		$html .= '<p class="ab-comment-form__logged-in logged-in-as">'
			. 'Conectado como <strong>Visitante</strong>. '
			. '<span class="ab-comment-form__required-note">Campos obrigatórios são marcados com *</span></p>';
		$html .= '<p class="ab-comment-form__row ab-comment-form__row--comment">'
			. '<label>Comentário <span class="required">*</span></label>'
			. '<span class="ab-comment-form__control ab-comment-form__textarea ab-comment-form__control--fake"></span>'
			. '</p>';
		$html .= '<p class="ab-comment-form__row ab-comment-form__row--submit">'
			. '<button type="button" class="ab-btn ab-comment-form__submit' . $full . '" disabled>'
			. $submit . '</button>'
			. '</p>';
		$html .= '</div></div>';
		return $html;
	}

	/**
	 * CSS custom properties on the wrapper (button colors survive StyleEngine text color).
	 *
	 * @param array<string, mixed> $s Settings.
	 */
	private function wrapper_css_vars( array $s ): string {
		$parts = array();
		$bg    = trim( (string) ( $s['btn_bg'] ?? '' ) );
		$fg    = trim( (string) ( $s['btn_color'] ?? '' ) );
		$rad   = trim( (string) ( $s['btn_radius'] ?? '' ) );
		if ( $bg !== '' ) {
			$parts[] = '--ab-cf-btn-bg:' . $bg;
		}
		if ( $fg !== '' ) {
			$parts[] = '--ab-cf-btn-color:' . $fg;
		}
		if ( $rad !== '' ) {
			if ( preg_match( '/^\d+(\.\d+)?$/', $rad ) ) {
				$rad .= 'px';
			}
			$parts[] = '--ab-cf-btn-radius:' . $rad;
		}
		return implode( ';', $parts );
	}

	/**
	 * Inline style string for the submit button (belt-and-suspenders with CSS vars).
	 *
	 * @param array<string, mixed> $s Settings.
	 */
	private function button_inline_style( array $s, ?Node $node = null ): string {
		unset( $node );
		$parts = array();
		$bg    = trim( (string) ( $s['btn_bg'] ?? '' ) );
		$fg    = trim( (string) ( $s['btn_color'] ?? '' ) );
		$rad   = trim( (string) ( $s['btn_radius'] ?? '' ) );
		// Never fall back to text color (that made the button label red/pink).
		if ( $bg !== '' ) {
			$parts[] = 'background:' . $bg;
			$parts[] = 'background-color:' . $bg;
			$parts[] = 'background-image:none';
		}
		if ( $fg !== '' ) {
			$parts[] = 'color:' . $fg;
			$parts[] = '-webkit-text-fill-color:' . $fg;
		} else {
			$parts[] = 'color:#ffffff';
			$parts[] = '-webkit-text-fill-color:#ffffff';
		}
		if ( $rad !== '' ) {
			if ( preg_match( '/^\d+(\.\d+)?$/', $rad ) ) {
				$rad .= 'px';
			}
			$parts[] = 'border-radius:' . $rad;
		}
		if ( ( $s['btn_full_width'] ?? '0' ) === '1' ) {
			$parts[] = 'width:100%';
			$parts[] = 'display:flex';
		}
		return implode( ';', $parts );
	}

	/**
	 * Logged-in note with spacing that survives theme/kses.
	 */
	private function logged_in_as_html( int $post_id ): string {
		$user = wp_get_current_user();
		if ( ! $user || ! $user->exists() ) {
			return '';
		}
		$profile = get_edit_profile_url();
		$logout  = wp_logout_url( get_permalink( $post_id ) ?: home_url( '/' ) );
		return '<p class="ab-comment-form__logged-in logged-in-as">'
			. sprintf(
				/* translators: 1: user display name, 2: edit profile URL, 3: logout URL */
				__( 'Conectado como <strong>%1$s</strong>. <a href="%2$s">Edite seu perfil</a>. <a href="%3$s">Sair</a>?', 'auranet-page-theme-builder' ),
				esc_html( $user->display_name ),
				esc_url( $profile ),
				esc_url( $logout )
			)
			. ' <span class="ab-comment-form__required-note">'
			. esc_html__( 'Campos obrigatórios são marcados com *', 'auranet-page-theme-builder' )
			. '</span></p>';
	}

	/**
	 * Author / email / url fields for guests — styled like editor fields.
	 *
	 * @return array<string, string>
	 */
	private function author_fields_html(): array {
		$req      = get_option( 'require_name_email' );
		$aria_req = $req ? ' required="required"' : '';
		$star     = $req ? ' <span class="required" aria-hidden="true">*</span>' : '';
		$commenter = wp_get_current_commenter();
		$author   = isset( $commenter['comment_author'] ) ? $commenter['comment_author'] : '';
		$email    = isset( $commenter['comment_author_email'] ) ? $commenter['comment_author_email'] : '';
		$url      = isset( $commenter['comment_author_url'] ) ? $commenter['comment_author_url'] : '';

		return array(
			'author' => '<p class="ab-comment-form__row ab-comment-form__row--name comment-form-author">'
				. '<label for="author">' . esc_html__( 'Nome', 'auranet-page-theme-builder' ) . $star . '</label>'
				. '<input id="author" name="author" type="text" class="ab-comment-form__control" value="'
				. esc_attr( $author ) . '" size="30" maxlength="245" autocomplete="name"' . $aria_req . ' /></p>',
			'email'  => '<p class="ab-comment-form__row ab-comment-form__row--email comment-form-email">'
				. '<label for="email">' . esc_html__( 'E-mail', 'auranet-page-theme-builder' ) . $star . '</label>'
				. '<input id="email" name="email" type="email" class="ab-comment-form__control" value="'
				. esc_attr( $email ) . '" size="30" maxlength="100" autocomplete="email"' . $aria_req . ' /></p>',
			'url'    => '<p class="ab-comment-form__row ab-comment-form__row--url comment-form-url">'
				. '<label for="url">' . esc_html__( 'Site', 'auranet-page-theme-builder' ) . '</label>'
				. '<input id="url" name="url" type="url" class="ab-comment-form__control" value="'
				. esc_attr( $url ) . '" size="30" maxlength="200" autocomplete="url" /></p>',
		);
	}
}
