<?php

if (!defined('ABSPATH')) {
	exit;
}

$output = (string) $content;

if ($output === '') {
	return;
}

if (
	!preg_match(
		'/^\s*(?P<opening><(?P<tag>[a-z][\w:-]*)\b[^>]*>)(?P<inner>.*)(?P<closing><\/(?P=tag)\s*>)\s*$/is',
		$output,
		$wrapperMatches
	)
) {
	echo $output;
	return;
}

$wrapperInnerHtml = (string) ($wrapperMatches['inner'] ?? '');

if (
	!preg_match(
		'/(?P<label><(?P<tag>[a-z][\w:-]*)\b[^>]*\bclass=(["\'])[^"\']*\buicore-menu-link\b[^"\']*\3[^>]*>.*?<\/(?P=tag)\s*>)/is',
		$wrapperInnerHtml,
		$labelMatches
	)
) {
	echo $output;
	return;
}

$savedLabelHtml = (string) $labelMatches['label'];

if (
	!preg_match(
		'/^(?P<opening><(?P<tag>[a-z][\w:-]*)\b[^>]*>)(?P<inner>.*)(?P<closing><\/(?P=tag)\s*>)$/is',
		$savedLabelHtml,
		$savedLabelMatches
	)
) {
	echo $output;
	return;
}

$labelOpening = (string) ($savedLabelMatches['opening'] ?? '');
$labelInnerHtml = (string) ($savedLabelMatches['inner'] ?? '');
$labelClosing = (string) ($savedLabelMatches['closing'] ?? '');
$labelTag = strtolower((string) ($savedLabelMatches['tag'] ?? 'span'));

$labelOpening = preg_replace(
	'/^<' . preg_quote($labelTag, '/') . '\b/i',
	'<a',
	$labelOpening,
	1
);
$labelClosing = '</a>';

$parsedInnerBlocks = is_array($block->parsed_block['innerBlocks'] ?? null)
	? $block->parsed_block['innerBlocks']
	: [];

$labelBlocksHtml = '';
$labelToggleHtml = '';
$submenuHtml = '';

foreach ($parsedInnerBlocks as $innerBlock) {
	if (!is_array($innerBlock)) {
		continue;
	}

	$innerBlockName = (string) ($innerBlock['blockName'] ?? '');
	$innerBlockHtml = render_block($innerBlock);

	if ($innerBlockName === 'uicore/a-menu-submenu') {
		$submenuHtml .= $innerBlockHtml;
		continue;
	}

	if ($innerBlockName === 'uicore/toggle-icon') {
		$labelToggleHtml .= $innerBlockHtml;
		continue;
	}

	$labelBlocksHtml .= $innerBlockHtml;
}

echo $wrapperMatches['opening'];
echo $labelOpening;
echo '<span class="uicore-menu-link-wrapper">';
echo $labelInnerHtml;
echo $labelBlocksHtml;
echo $labelToggleHtml;
echo '</span>';
echo $labelClosing;
echo $submenuHtml;
echo $wrapperMatches['closing'];
