<?php
/**
 * BW Separator Block
 *
 * Registers the bw/separator Gutenberg block.
 * Displays an SVG decorative separator with configurable alignment.
 */

add_action('init', function() {
    $registry = WP_Block_Type_Registry::get_instance();
    if ($registry->is_registered('bw/separator')) {
        return;
    }

    wp_register_script(
        'bw-separator-editor',
        get_stylesheet_directory_uri() . '/blocks/bw-separator/editor.js',
        array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-separator/editor.js')
    );

    wp_localize_script('bw-separator-editor', 'bwSeparatorData', array(
        'svgUrl' => content_url('/uploads/2026/02/Group.svg'),
    ));

    register_block_type('bw/separator', array(
        'editor_script'   => 'bw-separator-editor',
        'render_callback' => 'bw_render_separator_block',
        'attributes'      => array(
            'align' => array(
                'type'    => 'string',
                'default' => 'center',
            ),
        ),
    ));
});

/**
 * Server-side render callback for bw/separator block.
 */
function bw_render_separator_block($attributes) {
    $align = isset($attributes['align']) ? strtolower(trim($attributes['align'])) : 'center';
    if (!in_array($align, array('left', 'center', 'right'))) {
        $align = 'center';
    }

    $justify_map = array(
        'left'   => 'flex-start',
        'center' => 'center',
        'right'  => 'flex-end',
    );
    $justify = $justify_map[$align];

    $svg_url = esc_url(set_url_scheme(content_url('/uploads/2026/02/Group.svg')));

    return sprintf(
        '<figure class="wp-block-bw-separator wp-block-kadence-image kb-image-separator image-is-svg" style="display: flex; justify-content: %s;">' .
            '<img loading="lazy" decoding="async" width="150" height="19" src="%s" alt="" class="kb-img">' .
        '</figure>',
        esc_attr($justify),
        $svg_url
    );
}
