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

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_menu';
const DIVI5_MODULE_SLUG = 'divi/menu';
const DIVI4_SEPARATOR_SLUG = 'db_separators';
const DIVI5_SEPARATOR_SLUG = 'dbSeparators';
const DIVI4_SPACING_SLUG = 'db_link_spacing';
const DIVI5_SPACING_SLUG = 'dbLinkSpacing';

// === Divi 4 Classic: Register admin field ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__.'\\register_divi4_separator_field');

function register_divi4_separator_field($fields) {
    if (!is_array($fields)) return $fields;
    $fields = [
        DIVI4_SEPARATOR_SLUG => [
            'label' => 'Vertical Separator Bars',
            'type' => 'yes_no_button',
            'options' => [
                'off' => esc_html__('No', 'et_builder'),
                'on'  => esc_html__('yes', 'et_builder'),
            ],
            'option_category' => 'basic_option',
            'description' => 'Show vertical separator bars between the menu links.',
            'default' => 'off',
            'tab_slug'          => 'advanced',
            'toggle_slug'       => 'layout',
        ],
    ] + $fields;
    return $fields;
}

// === Divi 4 Classic: Add separators CSS on frontend ===
add_filter('et_module_shortcode_output', function($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props)) {
        return $output;
    }
    $separators = $module->props[DIVI4_SEPARATOR_SLUG] ?? 'off';
    $spacing = $module->props[DIVI4_SPACING_SLUG] ?? '22px';
    return add_separator_css_to_content($output, $separators, $spacing);
}, 10, 3);

// === Helper: Extract order class from content ===
function get_order_class_from_content($content) {
    if (preg_match('/(et_pb_menu_\d+(?:_[a-z0-9_]+)?)/i', $content, $m)) {
        return $m[1];
    }
    return '';
}

function add_separator_css_to_content($content, $separators, $spacing) {
    $order_class = get_order_class_from_content($content);
    if (!$order_class || $separators !== 'on') return $content;
    $padding = (!empty($spacing) && $spacing !== '22px') ? esc_html(intval($spacing)/2) : '11';
    $content .= <<<END
<style>
.{$order_class} .et-menu.nav > li + li > a:before {
    position: absolute;
    left:-{$padding}px;
    transform: translateX(-50%);
    content: '|';
    font-size: smaller;
}
</style>
END;
    return $content;
}

// === Divi 5 Attribute Registration & Conversion ===
add_action('wp_enqueue_scripts', __NAMESPACE__.'\\enqueue_script');
function enqueue_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 . '-' . DIVI5_SEPARATOR_SLUG);
    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() {
    $attribute_json = wp_json_encode(get_attribute_definition());
    $divi5_slug = wp_json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $divi5_setting_slug = wp_json_encode(DIVI5_SEPARATOR_SLUG);
    $divi4_setting_slug = wp_json_encode(DIVI4_SEPARATOR_SLUG);
    return <<<END
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleMapping', 'divi', modules => {
    const path = [{$divi5_slug}, 'metadata', 'attributes'];
    const { set, get, has } = window.lodash;
    const target = get(modules, path) ? get(modules, path) : set(modules, path, {});
    if (has(modules, path)) {
        target[{$divi5_setting_slug}] = $attribute_json;
    }
    return modules;
});
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug}) return conversionOutline;
    conversionOutline.module[{$divi4_setting_slug}] = {$divi5_setting_slug} + '.*';
    return conversionOutline;
});
END;
}

add_filter('divi_module_library_register_module_attrs', function($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }
    $module_attrs[DIVI5_SEPARATOR_SLUG] = get_attribute_definition();
    return $module_attrs;
}, 10, 2);

// === Divi 5: Attribute definition ===
function get_attribute_definition() {
    return [
        'type' => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items' => [
                    'separatorToggle' => [
                        'groupSlug' => 'designLayout',
                        'attrName' => DIVI5_SEPARATOR_SLUG,
                        'label' => 'Vertical Separator Bars',
                        'description' => 'Show vertical separator bars between the menu links.',
                        'features' => [
                            'hover' => false,
                            'sticky' => false,
                            'responsive' => false,
                            'preset' => 'advanced',
                        ],
                        'render' => true,
                        'priority' => 25,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                            'props' => [],
                        ],
                        'defaultAttr' => ['desktop' => ['value' => 'off']],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5 Frontend: Render block filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $separators = $parsed_block['attrs'][DIVI5_SEPARATOR_SLUG]['desktop']['value'] ?? 'off';
    // Get spacing from companion feature if set (as in Divi 4 conversion)
    $spacing = $parsed_block['attrs'][DIVI5_SPACING_SLUG]['desktop']['value'] ?? '22px';
    return add_separator_css_to_content($block_content, $separators, $spacing);
}, 10, 3);
