<?php
namespace DiviBooster\DiviBooster\Modules\Menu\TitleAndTagline;

// Constants
const DIVI5_MODULE_SLUG = 'divi/menu';
const DIVI4_MODULE_SLUG = 'et_pb_menu';

// D4 field slugs (must not change)
const D4_FIELD_DB_TITLE = 'db_title';
const D4_FIELD_DB_TITLE_USE_LINK = 'db_title_use_link';
const D4_FIELD_DB_TAGLINE = 'db_tagline';
const D4_FIELD_DB_TAGLINE_BELOW_TITLE = 'db_tagline_below_title';
const D4_FIELD_DB_VALIGN = 'db_title_and_tagline_valign';
const D4_FIELD_DB_BELOW_LOGO = 'db_title_and_tagline_below_logo';

// D5 attribute slugs (camelCase)
const D5_ATTR_DB_TITLE = 'dbTitle';
const D5_ATTR_DB_TITLE_USE_LINK = 'dbTitleUseLink';
const D5_ATTR_DB_TAGLINE = 'dbTagline';
const D5_ATTR_DB_TAGLINE_BELOW_TITLE = 'dbTaglineBelowTitle';
const D5_ATTR_DB_VALIGN = 'dbTitleAndTaglineValign';
const D5_ATTR_DB_BELOW_LOGO = 'dbTitleAndTaglineBelowLogo';

// === Divi 4 Classic Builder Fields Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__.'\\register_d4_fields');
function register_d4_fields($fields) {
    if (!is_array($fields)) { return $fields; }

    $new_fields = [
        D4_FIELD_DB_TITLE => [
            'label' => 'Show Site Title',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Display the site title. This option is not previewable, but will show up on the front-end.',
            'default' => 'off',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
        ],
        D4_FIELD_DB_TITLE_USE_LINK => [
            'label' => 'Link Site Title to Homepage',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Make the site title into a link to the site homepage.',
            'default' => 'off',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
            'show_if' => [ D4_FIELD_DB_TITLE => 'on' ],
        ],
        D4_FIELD_DB_TAGLINE => [
            'label' => 'Show Site Tagline',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Display the site tagline. This option is not previewable, but will show up on the front-end.',
            'default' => 'off',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
        ],
        D4_FIELD_DB_TAGLINE_BELOW_TITLE => [
            'label' => 'Place Site Tagline Below Title',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Place the tagline below the title (if shown).',
            'default' => 'off',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
            'show_if' => [
                D4_FIELD_DB_TAGLINE => 'on',
                D4_FIELD_DB_TITLE   => 'on',
            ],
        ],
        D4_FIELD_DB_VALIGN => [
            'label' => 'Title & Tagline Vertical Align',
            'type' => 'select',
            'options' => [
                'top'    => esc_html__('Top', 'divi-booster'),
                'middle' => esc_html__('Middle', 'divi-booster'),
                'bottom' => esc_html__('Bottom', 'divi-booster'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Specify the vertical alignment for the site title / tagline.',
            'default' => 'top',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
        ],
        D4_FIELD_DB_BELOW_LOGO => [
            'label' => 'Place Title & Tagline Below Logo',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Place the title and tagline below the logo.',
            'default' => 'off',
            'tab_slug' => 'general',
            'toggle_slug' => 'elements',
        ],
    ];

    return $new_fields + $fields;

}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_title_and_tagline_conversion_outline( $conversion_outline, $module_name ) {
    if ( DIVI5_MODULE_SLUG !== $module_name ) {
        return $conversion_outline;
    }
    if ( ! isset( $conversion_outline['module'] ) || ! is_array( $conversion_outline['module'] ) ) {
        $conversion_outline['module'] = array();
    }
    // Map Divi 4 fields to Divi 5 attributes
    $conversion_outline['module'][D4_FIELD_DB_TITLE] = D5_ATTR_DB_TITLE . '.*';
    $conversion_outline['module'][D4_FIELD_DB_TITLE_USE_LINK] = D5_ATTR_DB_TITLE_USE_LINK . '.*';
    $conversion_outline['module'][D4_FIELD_DB_TAGLINE] = D5_ATTR_DB_TAGLINE . '.*';
    $conversion_outline['module'][D4_FIELD_DB_TAGLINE_BELOW_TITLE] = D5_ATTR_DB_TAGLINE_BELOW_TITLE . '.*';
    $conversion_outline['module'][D4_FIELD_DB_VALIGN] = D5_ATTR_DB_VALIGN . '.*';
    $conversion_outline['module'][D4_FIELD_DB_BELOW_LOGO] = D5_ATTR_DB_BELOW_LOGO . '.*';
    // Map custom CSS fields
    if ( ! isset( $conversion_outline['css'] ) || ! is_array( $conversion_outline['css'] ) ) {
        $conversion_outline['css'] = array();
    }
    $conversion_outline['css']['db_title'] = 'css.*.dbTitle';
    $conversion_outline['css']['db_tagline'] = 'css.*.dbTagline';
    return $conversion_outline;
}
add_filter( 'divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_title_and_tagline_conversion_outline', 10, 2 );

// D4 Advanced Fonts
add_filter('et_pb_menu_advanced_fields', __NAMESPACE__.'\\add_d4_font_groups', 10, 3);
function add_d4_font_groups($fields, $slug, $main_css_element) {
    if (!is_array($fields)) return $fields;
    if (!isset($fields['fonts']) || !is_array($fields['fonts'])) {
        $fields['fonts'] = [];
    }
    $fields['fonts'][D4_FIELD_DB_TITLE] = [
        'css'   => [
            'main' => "{$main_css_element} .db_title, {$main_css_element} .db_title a",
            'important' => 'all',
        ],
        'label' => esc_html__('Site Title', 'divi-booster'),
        'font_size' => [ 'default' => '14px' ],
    ];
    $fields['fonts'][D4_FIELD_DB_TAGLINE] = [
        'css'   => [ 'main' => "{$main_css_element} .db_tagline" ],
        'label' => esc_html__('Site Tagline', 'divi-booster'),
    ];
    return $fields;
}

// D4 Custom CSS Fields
add_filter('et_pb_menu_custom_css_fields', __NAMESPACE__.'\\add_d4_custom_css_fields', 10, 3);
function add_d4_custom_css_fields($fields, $slug, $main_css_element) {
    if (!is_array($fields)) return $fields;
    $fields[D4_FIELD_DB_TITLE] = [
        'label'    => esc_html__('Site Title', 'divi-booster'),
        'selector' => '%%order_class%% .db_title',
    ];
    $fields[D4_FIELD_DB_TAGLINE] = [
        'label'    => esc_html__('Site Tagline', 'divi-booster'),
        'selector' => '%%order_class%% .db_tagline',
    ];
    return $fields;
}

// === Divi 4 Output Filters ===
add_filter('et_module_shortcode_output', __NAMESPACE__.'\\filter_d4_output', 10, 3);
//add_filter('db_pb_menu_content', __NAMESPACE__.'\\filter_d4_custom_content', 10, 2);

function filter_d4_output($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props)) {
        return $output;
    }

    $settings = normalize_settings([
        D4_FIELD_DB_TITLE               => $module->props[D4_FIELD_DB_TITLE]               ?? 'off',
        D4_FIELD_DB_TITLE_USE_LINK      => $module->props[D4_FIELD_DB_TITLE_USE_LINK]      ?? 'off',
        D4_FIELD_DB_TAGLINE             => $module->props[D4_FIELD_DB_TAGLINE]             ?? 'off',
        D4_FIELD_DB_TAGLINE_BELOW_TITLE => $module->props[D4_FIELD_DB_TAGLINE_BELOW_TITLE] ?? 'off',
        D4_FIELD_DB_VALIGN              => $module->props[D4_FIELD_DB_VALIGN]              ?? 'top',
        D4_FIELD_DB_BELOW_LOGO          => $module->props[D4_FIELD_DB_BELOW_LOGO]          ?? 'off',
    ]);

    return apply_d4_modifications($output, $settings);
}

function filter_d4_custom_content($content, $args) {
    $settings = normalize_settings([
        'db_title'                       => $args['db_title']                       ?? 'off',
        'db_title_use_link'              => $args['db_title_use_link']              ?? 'off',
        'db_tagline'                     => $args['db_tagline']                     ?? 'off',
        'db_tagline_below_title'         => $args['db_tagline_below_title']         ?? 'off',
        'db_title_and_tagline_valign'    => $args['db_title_and_tagline_valign']    ?? 'top',
        'db_title_and_tagline_below_logo' => $args['db_title_and_tagline_below_logo'] ?? 'off',
    ]);

    return apply_d4_modifications($content, $settings);
}

function apply_d4_modifications($output, $settings) {
    if ($settings['db_title'] !== 'on' && $settings['db_tagline'] !== 'on') {
        return $output;
    }

    $order_class = extract_order_class($output);
    if (!$order_class) {
        return $output;
    }

    // Inject state classes onto module element
    $output = inject_module_state_classes($output, [
        'db_title_' . $settings['db_title'],
        'db_title_use_link_' . $settings['db_title_use_link'],
        'db_tagline_' . $settings['db_tagline'],
        'db_tagline_below_title_' . $settings['db_tagline_below_title'],
        'db_title_and_tagline_valign_' . $settings['db_title_and_tagline_valign'],
        'db_title_and_tagline_below_logo_' . $settings['db_title_and_tagline_below_logo'],
    ]);

    // Inject markup
    $html = build_title_tagline_markup($settings);

    if ($html) {
        $output = insert_before_menu_wrap($output, $html);
    }

    // Add scoped per-instance styles
    $output .= "\n<style>\n" . build_scoped_css($order_class) . "\n</style>\n";

    return $output;
}

// === Divi 5: Attribute Registration (PHP) ===
add_filter('divi_module_library_register_module_attrs', __NAMESPACE__.'\\register_divi5_attrs', 10, 2);
function register_divi5_attrs($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }

    // Register six content attributes (toggles/select)
    $module_attrs[D5_ATTR_DB_TITLE] = ['type' => 'object'];
    $module_attrs[D5_ATTR_DB_TITLE_USE_LINK] = ['type' => 'object'];
    $module_attrs[D5_ATTR_DB_TAGLINE] = ['type' => 'object'];
    $module_attrs[D5_ATTR_DB_TAGLINE_BELOW_TITLE] = ['type' => 'object'];
    $module_attrs[D5_ATTR_DB_VALIGN] = ['type' => 'object'];
    $module_attrs[D5_ATTR_DB_BELOW_LOGO] = ['type' => 'object'];

    // Register font groups for Title and Tagline
    $module_attrs['dbTitleFont'] = [
        'type' => 'object',
        'selector' => '{{selector}} .db_title, {{selector}} .db_title a',
    ];
    $module_attrs['dbTaglineFont'] = [
        'type' => 'object',
        'selector' => '{{selector}} .db_tagline',
    ];

    return $module_attrs;
}

// === Divi 5: JS Module Mapping & Conversion Outline ===
add_action('wp_enqueue_scripts', __NAMESPACE__.'\\enqueue_mapping_script');
function enqueue_mapping_script() {
    if ((!function_exists('et_builder_d5_enabled') || !\et_builder_d5_enabled()) ||
        (!function_exists('et_core_is_fb_enabled') || !\et_core_is_fb_enabled())) {
        return;
    }
    $handle = sanitize_title('divi-booster-' . DIVI5_MODULE_SLUG . '-title-tagline');
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_inline_js());
}

function get_inline_js() {
    $divi5_slug = wp_json_encode(DIVI5_MODULE_SLUG);
    $d4_slug = wp_json_encode(DIVI4_MODULE_SLUG);

    $attr_dbTitle = wp_json_encode(D5_ATTR_DB_TITLE);
    $attr_dbTitleUseLink = wp_json_encode(D5_ATTR_DB_TITLE_USE_LINK);
    $attr_dbTagline = wp_json_encode(D5_ATTR_DB_TAGLINE);
    $attr_dbTaglineBelowTitle = wp_json_encode(D5_ATTR_DB_TAGLINE_BELOW_TITLE);
    $attr_dbVAlign = wp_json_encode(D5_ATTR_DB_VALIGN);
    $attr_dbBelowLogo = wp_json_encode(D5_ATTR_DB_BELOW_LOGO);

    $d4_dbTitle = wp_json_encode(D4_FIELD_DB_TITLE);
    $d4_dbTitleUseLink = wp_json_encode(D4_FIELD_DB_TITLE_USE_LINK);
    $d4_dbTagline = wp_json_encode(D4_FIELD_DB_TAGLINE);
    $d4_dbTaglineBelowTitle = wp_json_encode(D4_FIELD_DB_TAGLINE_BELOW_TITLE);
    $d4_dbVAlign = wp_json_encode(D4_FIELD_DB_VALIGN);
    $d4_dbBelowLogo = wp_json_encode(D4_FIELD_DB_BELOW_LOGO);

    // Attribute definitions (settings & groups) for D5
    $attribute_def = [
        'type' => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items' => [
                    'dbTitleToggle' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_TITLE,
                        'label' => 'Show Site Title',
                        'description' => 'Display the site title. This option is not previewable, but will show up on the front-end.',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 10,
                        'component' => [ 'type' => 'field', 'name' => 'divi/toggle' ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                    'dbTitleUseLinkToggle' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_TITLE_USE_LINK,
                        'label' => 'Link Site Title to Homepage',
                        'description' => 'Make the site title into a link to the site homepage.',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 11,
                        'component' => [ 'type' => 'field', 'name' => 'divi/toggle' ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                    'dbTaglineToggle' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_TAGLINE,
                        'label' => 'Show Site Tagline',
                        'description' => 'Display the site tagline. This option is not previewable, but will show up on the front-end.',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 12,
                        'component' => [ 'type' => 'field', 'name' => 'divi/toggle' ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                    'dbTaglineBelowTitleToggle' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_TAGLINE_BELOW_TITLE,
                        'label' => 'Place Site Tagline Below Title',
                        'description' => 'Place the tagline below the title (if shown).',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 13,
                        'component' => [ 'type' => 'field', 'name' => 'divi/toggle' ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                    'dbVAlignSelect' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_VALIGN,
                        'label' => 'Title & Tagline Vertical Align',
                        'description' => 'Specify the vertical alignment for the site title / tagline.',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 14,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/select',
                            'props' => [ 'options' => [ 'top' => ['label'=>'Top'], 'middle' => ['label'=>'Middle'], 'bottom' => ['label'=>'Bottom'] ] ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'top' ] ],
                    ],
                    'dbBelowLogoToggle' => [
                        'groupSlug' => 'contentElements',
                        'attrName' => D5_ATTR_DB_BELOW_LOGO,
                        'label' => 'Place Title & Tagline Below Logo',
                        'description' => 'Place the title and tagline below the logo.',
                        'features' => [ 'hover' => false, 'sticky' => false, 'responsive' => false, 'preset' => 'content' ],
                        'render' => true,
                        'priority' => 15,
                        'component' => [ 'type' => 'field', 'name' => 'divi/toggle' ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                ],
            ],
        ],
    ];

    $title_font_attr = [
        'type' => 'object',
        'selector' => '{{selector}} .db_title, {{selector}} .db_title a',
        'settings' => [
            'decoration' => [
                'font' => [
                    'groupType' => 'group-item',
                    'item' => [
                        'groupSlug' => 'designMenuText',
                        'render' => true,
                        'priority' => 20,
                        'component' => [
                            'type' => 'group',
                            'name' => 'divi/font',
                            'props' => [ 'grouped' => false, 'fieldLabel' => 'Site Title' ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => [ 'size' => '14px' ] ] ],
                    ],
                ],
            ],
        ],
    ];

    $tagline_font_attr = [
        'type' => 'object',
        'selector' => '{{selector}} .db_tagline',
        'settings' => [
            'decoration' => [
                'font' => [
                    'groupType' => 'group-item',
                    'item' => [
                        'groupSlug' => 'designMenuText',
                        'render' => true,
                        'priority' => 21,
                        'component' => [
                            'type' => 'group',
                            'name' => 'divi/font',
                            'props' => [ 'grouped' => false, 'fieldLabel' => 'Site Tagline' ],
                        ],
                    ],
                ],
            ],
        ],
    ];

    $attribute_json = wp_json_encode($attribute_def);
    $title_font_json = wp_json_encode($title_font_attr);
    $tagline_font_json = wp_json_encode($tagline_font_attr);

    return <<<JS
(function(){
  var hooks = window.vendor && window.vendor.wp && window.vendor.wp.hooks; if(!hooks) return;
  var lodash = window.lodash;
  // Register attributes and custom CSS fields
  hooks.addFilter('divi.moduleLibrary.moduleMapping', 'divi', function(modules){
    var path = [{$divi5_slug}, 'metadata', 'attributes'];
    var get = lodash.get, set = lodash.set, has = lodash.has;
    var target = get(modules, path) ? get(modules, path) : set(modules, path, {});
    if (has(modules, path)) {
      target[{$attr_dbTitle}] = {$attribute_json};
      target[{$attr_dbTitleUseLink}] = {$attribute_json};
      target[{$attr_dbTagline}] = {$attribute_json};
      target[{$attr_dbTaglineBelowTitle}] = {$attribute_json};
      target[{$attr_dbVAlign}] = {$attribute_json};
      target[{$attr_dbBelowLogo}] = {$attribute_json};
      target['dbTitleFont'] = {$title_font_json};
      target['dbTaglineFont'] = {$tagline_font_json};
    }

    // Add visibility rules
    try {
      var itemsPath = [{$divi5_slug}, 'metadata', 'attributes', {$attr_dbTitleUseLink}, 'settings', 'innerContent', 'items', 'dbTitleUseLinkToggle'];
      var items = get(modules, itemsPath);
      if (items && typeof items === 'object') {
        items.visible = function(params){
          var attrs = params && params.attrs || {}; var v = attrs && attrs[{$attr_dbTitle}] && attrs[{$attr_dbTitle}].desktop && attrs[{$attr_dbTitle}].desktop.value; return v === 'on';
        };
      }
      var belowPath = [{$divi5_slug}, 'metadata', 'attributes', {$attr_dbTaglineBelowTitle}, 'settings', 'innerContent', 'items', 'dbTaglineBelowTitleToggle'];
      var belowItem = get(modules, belowPath);
      if (belowItem && typeof belowItem === 'object') {
        belowItem.visible = function(params){
          var attrs = params && params.attrs || {}; var t = attrs && attrs[{$attr_dbTitle}] && attrs[{$attr_dbTitle}].desktop && attrs[{$attr_dbTitle}].desktop.value; var g = attrs && attrs[{$attr_dbTagline}] && attrs[{$attr_dbTagline}].desktop && attrs[{$attr_dbTagline}].desktop.value; return t === 'on' && g === 'on';
        };
      }
    } catch(e) {}

    // Extend custom CSS fields
    var cssPath = [{$divi5_slug}, 'metadata', 'customCssFields'];
    var cssTarget = get(modules, cssPath) ? get(modules, cssPath) : set(modules, cssPath, {});
    cssTarget['dbTitle'] = { label: 'Site Title', subName: 'dbTitle', selector: '{{selector}}', selectorSuffix: ' .db_title' };
    cssTarget['dbTagline'] = { label: 'Site Tagline', subName: 'dbTagline', selector: '{{selector}}', selectorSuffix: ' .db_tagline' };

    return modules;
  });

  // Conversion outline mapping
  hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', function(conversionOutline, name){
    if (name !== {$d4_slug}) return conversionOutline;
    conversionOutline.module = conversionOutline.module || {};
    conversionOutline.css = conversionOutline.css || {};
    conversionOutline.module[{$d4_dbTitle}] = {$attr_dbTitle} + '.*';
    conversionOutline.module[{$d4_dbTitleUseLink}] = {$attr_dbTitleUseLink} + '.*';
    conversionOutline.module[{$d4_dbTagline}] = {$attr_dbTagline} + '.*';
    conversionOutline.module[{$d4_dbTaglineBelowTitle}] = {$attr_dbTaglineBelowTitle} + '.*';
    conversionOutline.module[{$d4_dbVAlign}] = {$attr_dbVAlign} + '.*';
    conversionOutline.module[{$d4_dbBelowLogo}] = {$attr_dbBelowLogo} + '.*';
    conversionOutline.css['db_title'] = 'css.*.dbTitle';
    conversionOutline.css['db_tagline'] = 'css.*.dbTagline';
    return conversionOutline;
  });
})();
JS;
}

// === Divi 5 Frontend: Render block filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__.'\\filter_d5_output', 10, 3);
function filter_d5_output($block_content, $parsed_block, $block) {
    // Extract settings with defaults
    $attrs = is_array($parsed_block['attrs'] ?? null) ? $parsed_block['attrs'] : [];
    $settings = [
        'db_title' => read_d5_toggle($attrs, D5_ATTR_DB_TITLE, 'off'),
        'db_title_use_link' => read_d5_toggle($attrs, D5_ATTR_DB_TITLE_USE_LINK, 'off'),
        'db_tagline' => read_d5_toggle($attrs, D5_ATTR_DB_TAGLINE, 'off'),
        'db_tagline_below_title' => read_d5_toggle($attrs, D5_ATTR_DB_TAGLINE_BELOW_TITLE, 'off'),
        'db_title_and_tagline_valign' => read_d5_value($attrs, D5_ATTR_DB_VALIGN, 'top'),
        'db_title_and_tagline_below_logo' => read_d5_toggle($attrs, D5_ATTR_DB_BELOW_LOGO, 'off'),
    ];
    $settings = normalize_settings($settings);

    if ($settings['db_title'] !== 'on' && $settings['db_tagline'] !== 'on') {
        return $block_content;
    }

    $order_class = extract_order_class($block_content);
    if (!$order_class) {
        return $block_content;
    }

    $block_content = inject_module_state_classes($block_content, [
        'db_title_' . $settings['db_title'],
        'db_title_use_link_' . $settings['db_title_use_link'],
        'db_tagline_' . $settings['db_tagline'],
        'db_tagline_below_title_' . $settings['db_tagline_below_title'],
        'db_title_and_tagline_valign_' . $settings['db_title_and_tagline_valign'],
        'db_title_and_tagline_below_logo_' . $settings['db_title_and_tagline_below_logo'],
    ]);

    $html = build_title_tagline_markup($settings);
    if ($html) {
        $block_content = insert_before_menu_wrap($block_content, $html);
    }

    $block_content .= "\n<style>\n" . build_scoped_css($order_class) . "\n</style>\n";

    return $block_content;
}

// === Helpers ===

function read_d5_toggle($attrs, $key, $default = 'off') {
    $v = $attrs[$key]['desktop']['value'] ?? $default;
    return in_array($v, ['on','off'], true) ? $v : $default;
}
function read_d5_value($attrs, $key, $default) {
    $v = $attrs[$key]['desktop']['value'] ?? $default;
    return is_string($v) ? $v : $default;
}

function normalize_settings($s) {
    return [
        'db_title' => ($s['db_title'] ?? 'off') === 'on' ? 'on' : 'off',
        'db_title_use_link' => ($s['db_title_use_link'] ?? 'off') === 'on' ? 'on' : 'off',
        'db_tagline' => ($s['db_tagline'] ?? 'off') === 'on' ? 'on' : 'off',
        'db_tagline_below_title' => ($s['db_tagline_below_title'] ?? 'off') === 'on' ? 'on' : 'off',
        'db_title_and_tagline_valign' => in_array(($s['db_title_and_tagline_valign'] ?? 'top'), ['top','middle','bottom'], true) ? $s['db_title_and_tagline_valign'] : 'top',
        'db_title_and_tagline_below_logo' => ($s['db_title_and_tagline_below_logo'] ?? 'off') === 'on' ? 'on' : 'off',
    ];
}

function extract_order_class($html) {
    if (preg_match('/\bet_pb_menu_(\d+(?:_[a-z0-9_]+)?)\b/i', $html, $m)) {
        return 'et_pb_menu_' . $m[1];
    }
    return '';
}

function build_title_tagline_markup($settings) {
    $title_html = '';
    if ($settings['db_title'] === 'on') {
        $title = (string) get_bloginfo('name');
        $title = esc_html($title);
        if ($title !== '') {
            if ($settings['db_title_use_link'] === 'on') {
                $title = '<a href="' . esc_attr(esc_url(home_url('/'))) . '">' . $title . '</a>';
            }
            $title_html = '<div class="db_title">' . $title . '</div>';
        }
    }

    $tagline_html = '';
    if ($settings['db_tagline'] === 'on') {
        $tag = (string) get_bloginfo('description');
        if ($tag !== '') {
            $tagline_html = '<div class="db_tagline">' . esc_html($tag) . '</div>';
        }
    }

    if ($title_html === '' && $tagline_html === '') {
        return '';
    }

    return '<div class="db_title_and_tagline">' . $title_html . $tagline_html . '</div>';
}

function insert_before_menu_wrap($content, $insertion) {
    $needle = '<div class="et_pb_menu__wrap';
    $pos = strpos($content, $needle);
    if ($pos !== false) {
        return substr($content, 0, $pos) . $insertion . substr($content, $pos);
    }
    return $content;
}

function inject_module_state_classes($html, $classes) {
    $classes = array_filter(array_map('sanitize_html_class', (array) $classes));
    if (!$classes) return $html;
    $class_str = implode(' ', $classes);
    // Inject into first Menu module container only
    $html = preg_replace(
        '#(<div\s+[^>]*class=\"[^\"]*?\bet_pb_menu\b[^\"]*?)\"#',
        '$1 ' . $class_str . '"',
        $html,
        1
    );
    return $html;
}

function build_scoped_css($order_class) {
    $oc = '.' . $order_class;
    $css = [];
    $css[] = "$oc .db_title, $oc .db_tagline{margin-right:30px;margin-top:0;line-height:1em;}";
    $css[] = "$oc .db_title_and_tagline{display:flex;align-items:flex-start;}";
    $css[] = "$oc.db_tagline_below_title_on .db_title_and_tagline{flex-direction:column;}";
    $css[] = "$oc.db_tagline_below_title_on .db_tagline{margin-top:8px;}";
    $css[] = "$oc.db_title_and_tagline_valign_middle .db_title_and_tagline{align-items:center;}";
    $css[] = "$oc.db_title_and_tagline_valign_bottom .db_title_and_tagline{align-items:flex-end;}";
    $css[] = "$oc.db_title_and_tagline_below_logo_on .db_title_and_tagline{position:absolute;bottom:0;left:0;transform:translateY(100%);}";
    return implode("\n", $css);
}

// Created at 1762228840
