<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables are scoped when required inside the block render callback.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once dirname( __DIR__, 3 ) . '/includes/block-css-generator.php';
require_once dirname( __DIR__, 3 ) . '/includes/render-helpers/list-item-css.php';

/**
 * Render callback for the AxcelersBlocks List Item block.
 *
 * Generic main/hover CSS for the <li> (.uniqueClass) comes from the shared
 * generator. The list-item-specific marker/icon CSS comes from
 * axcelersblocks_list_item_generate_icon_css().
 *
 * @package AxcelersBlocks
 */

// ─── Identity ───────────────────────────────────────────────────────────────

$anchor       = isset( $attributes['anchor'] ) ? sanitize_title( $attributes['anchor'] ) : '';
$unique_class = isset( $attributes['uniqueClass'] ) ? sanitize_html_class( $attributes['uniqueClass'] ) : '';
if ( empty( $unique_class ) ) {
	$unique_class = sanitize_html_class( 'axb-' . wp_unique_id() );
}

// ─── List context & marker resolution ─────────────────────────────────────────

$list_tag      = isset( $block->context['axcelersblocks/listTag'] ) ? sanitize_key( $block->context['axcelersblocks/listTag'] ) : 'ul';
$list_icon_svg = isset( $block->context['axcelersblocks/listIconSvg'] ) && is_string( $block->context['axcelersblocks/listIconSvg'] ) ? $block->context['axcelersblocks/listIconSvg'] : '';

// Per-item icon override: use the item's own iconSvg if set, otherwise fall back to the list-level context icon.
$item_icon_svg = isset( $attributes['iconSvg'] ) && is_string( $attributes['iconSvg'] ) && false !== strpos( $attributes['iconSvg'], '<svg' )
	? $attributes['iconSvg']
	: $list_icon_svg;

// Custom markers work for both ul and ol — the icon replaces the default bullet/counter.
$show_custom_marker = false !== strpos( $item_icon_svg, '<svg' );
$show_marker        = $show_custom_marker || 'ol' === $list_tag;

// ─── Wrapper attributes ───────────────────────────────────────────────────────

$extra_attrs = [
	'class' => trim( 'axcelersblocks-list-item ' . $unique_class ),
	'id'    => $anchor ?: null,
];
$wrapper_attrs = get_block_wrapper_attributes( $extra_attrs );

// ─── CSS generation & collection ──────────────────────────────────────────────
// has_icon is disabled on the shared generator because the list item owns its own
// .icon selectors (produced by the helper, which the shared .icon cannot express).

$devices    = axcelersblocks_get_responsive_devices();
$styles_css = axcelersblocks_generate_block_styles( $unique_class, $devices, $attributes, [ 'has_icon' => false ] );
$hover_css  = axcelersblocks_generate_block_styles_hover( $unique_class, $devices, $attributes, [ 'has_icon' => false ] );
$icon_css   = axcelersblocks_list_item_generate_icon_css( $unique_class, $devices, $attributes );
axcelersblocks_collect_block_styles( $unique_class, $block, array_merge( $styles_css, $hover_css, $icon_css ) );

// ─── Content assembly ─────────────────────────────────────────────────────────
// The saved content holds the item text (in a __text span) plus any nested blocks.
// Split the text out so it can be wrapped consistently and the markers/nesting
// rebuilt around it.

$allowed_html   = axcelersblocks_get_allowed_svg_html();
$content_html   = isset( $attributes['content'] ) ? wp_kses_post( $attributes['content'] ) : '';
$saved_content  = is_string( $content ) ? $content : '';
$nested_content = '';
$text_tag_name  = isset( $attributes['textTagName'] ) ? strtolower( (string) $attributes['textTagName'] ) : 'span';
$text_tag_name  = in_array( $text_tag_name, [ 'span', 'strong', 'em', 'a' ], true ) ? $text_tag_name : 'span';
$text_link_url  = isset( $attributes['textLinkUrl'] ) ? esc_url( $attributes['textLinkUrl'] ) : '';
$text_link_target = isset( $attributes['textLinkTarget'] ) ? sanitize_key( $attributes['textLinkTarget'] ) : '';
$text_link_rel    = isset( $attributes['textLinkRel'] ) ? sanitize_text_field( $attributes['textLinkRel'] ) : '';

if ( '' !== $saved_content ) {
	if (
		'' === $content_html &&
		preg_match(
			'/<(span|strong|em|a)\b[^>]*class=(["\'])[^"\']*axcelersblocks-list-item__text[^"\']*\2[^>]*>(.*?)<\/\1>/is',
			$saved_content,
			$matches
		)
	) {
		$content_html = wp_kses_post( $matches[3] );
		if ( empty( $attributes['textTagName'] ) ) {
			$text_tag_name = strtolower( $matches[1] );
		}
		if ( 'a' === strtolower( $matches[1] ) ) {
			if ( '' === $text_link_url && preg_match( '/\bhref=(["\'])(.*?)\1/i', $matches[0], $href_matches ) ) {
				$text_link_url = esc_url( $href_matches[2] );
			}
			if ( '' === $text_link_target && preg_match( '/\btarget=(["\'])(.*?)\1/i', $matches[0], $target_matches ) ) {
				$text_link_target = sanitize_key( $target_matches[2] );
			}
			if ( '' === $text_link_rel && preg_match( '/\brel=(["\'])(.*?)\1/i', $matches[0], $rel_matches ) ) {
				$text_link_rel = sanitize_text_field( $rel_matches[2] );
			}
		}
	}

	$nested_content = preg_replace(
		'/<(span|strong|em|a)\b[^>]*class=(["\'])[^"\']*axcelersblocks-list-item__text[^"\']*\2[^>]*>.*?<\/\1>/is',
		'',
		$saved_content,
		1
	);
	$nested_content = wp_kses( $nested_content, $allowed_html );
}

// ─── Marker ───────────────────────────────────────────────────────────────────

$marker_html = '';
if ( $show_marker ) {
	if ( $show_custom_marker ) {
		$sanitized_icon_svg = trim( wp_kses( $item_icon_svg, $allowed_html ) );
		if ( '' !== $sanitized_icon_svg ) {
			$marker_html = sprintf(
				'<span class="axcelersblocks-list-item__marker icon" aria-hidden="true">%s</span>',
				$sanitized_icon_svg
			);
		}
	} else {
		$marker_html = '<span class="axcelersblocks-list-item__marker icon" aria-hidden="true"></span>';
	}
}

// ─── Output ───────────────────────────────────────────────────────────────────

$text_attrs = 'class="axcelersblocks-list-item__text"';
if ( 'a' === $text_tag_name ) {
	if ( '' !== $text_link_url ) {
		$text_attrs .= ' href="' . esc_url( $text_link_url ) . '"';
	}
	if ( '' !== $text_link_target ) {
		$text_attrs .= ' target="' . esc_attr( $text_link_target ) . '"';
	}
	if ( '' !== $text_link_rel ) {
		$text_attrs .= ' rel="' . esc_attr( $text_link_rel ) . '"';
	}
}

// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- wrapper attrs are escaped by get_block_wrapper_attributes(); content is sanitized by wp_kses above.
printf(
	'<li %1$s>%2$s<div class="axcelersblocks-list-item__content">%3$s%4$s</div></li>',
	$wrapper_attrs,
	$marker_html,
	! empty( $content_html ) ? sprintf( '<%1$s %2$s>%3$s</%1$s>', tag_escape( $text_tag_name ), $text_attrs, $content_html ) : '',
	$nested_content
);
// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
