<?php
defined('ABSPATH') || exit;

if (! function_exists('reeid_gutenberg_encode_attrs_json')) {
    function reeid_gutenberg_encode_attrs_json(array $attrs): string
    {
        $json = wp_json_encode($attrs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return is_string($json) ? $json : '{}';
    }
}

if (! function_exists('reeid_gutenberg_serialize_one_block_preserve_attrs')) {
    function reeid_gutenberg_serialize_one_block_preserve_attrs(array $block, array $translated_map = []): string
    {
        $name  = isset($block['blockName']) ? (string) $block['blockName'] : null;
        $attrs = isset($block['attrs']) && is_array($block['attrs']) ? $block['attrs'] : [];
        $inner = isset($block['innerBlocks']) && is_array($block['innerBlocks']) ? $block['innerBlocks'] : [];
        $html  = isset($block['innerHTML']) ? (string) $block['innerHTML'] : '';

        if (! empty($inner)) {
            $rendered = '';
            foreach ($inner as $ib) {
                $rendered .= reeid_gutenberg_serialize_one_block_preserve_attrs($ib, $translated_map);
            }
            $html = $rendered;
        }

        if ($name === null) {
            return $html;
        }

        $open = '<!-- wp:' . $name;
        if (! empty($attrs)) {
            $open .= ' ' . reeid_gutenberg_encode_attrs_json($attrs);
        }
        $open .= ' -->';

        $close = '<!-- /wp:' . $name . ' -->';

        return $open . $html . $close;
    }
}

if (! function_exists('reeid_gutenberg_serialize_preserve_attrs')) {
    function reeid_gutenberg_serialize_preserve_attrs(array $blocks, array $translated_map = []): string
    {
        $out = '';
        foreach ($blocks as $b) {
            $out .= reeid_gutenberg_serialize_one_block_preserve_attrs($b, $translated_map);
        }
        return $out;
    }
}