<?php
namespace DiviBooster\GalleryBooster\ArrowStyles;

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const ADVANCED_FIELD_SLUG = 'dbdb_arrows';

// === Divi 5 Attribute Registration & Conversion Mapping (JS) ===
add_action('divi_visual_builder_assets_before_enqueue_scripts', __NAMESPACE__ . '\enqueue_d5_booster_script');
function enqueue_d5_booster_script() {
    $handle = sanitize_title('divi-booster-' . DIVI5_MODULE_SLUG . '-' . ADVANCED_FIELD_SLUG);
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_d5_inline_js());
}
function get_d5_inline_js() {
    $attr = wp_json_encode(get_d5_attribute_definition());
    $d5slug = wp_json_encode(DIVI5_MODULE_SLUG);
    $d4slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $key = wp_json_encode(ADVANCED_FIELD_SLUG);
    return <<<JS
// Adds the custom attribute to the Gallery module.
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.gallery', 'divi', (attributes, metadata) => {
    attributes[{$key}] = {$attr};
    return attributes;
});

window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$d4slug}) return conversionOutline;
    // Print the conversion outline to the console
    if (!conversionOutline.advanced) conversionOutline.advanced = {};
    if (!conversionOutline.advanced.fonts) conversionOutline.advanced.fonts = {};
    conversionOutline.advanced.fonts[{$key}] = {$key} + '.decoration.font';
    return conversionOutline;
});

// Visual Builder: Render additional module styles for arrows (color and font size)
window.vendor.wp.hooks.addFilter('divi.module.wrapper.render', 'divi', (moduleWrapper, param) => {
  const {
    name:     moduleName,
    attrs:    moduleAttrs,
    elements: moduleElements,
    state:    moduleState,
  } = param;

  if ('divi/gallery' !== moduleName) {
    return moduleWrapper;
  }

  const { StyleContainer } = window.divi.module;
  const { isEdited } = moduleWrapper.props;

  // Additional module styles for the arrows
  const additionalModuleStyles = window.vendor.wp.element.createElement(
    StyleContainer,
    {
      key:        'additional-arrows-styles',
      mode:       'builder',
      state:      isEdited ? moduleState : '',
      noStyleTag: false,
    },
    moduleElements.style({
      attrName: 'dbdb_arrows'
    })
  );

  return window.vendor.wp.element.cloneElement(
    moduleWrapper,
    {},
    moduleWrapper.props.children,
    [
      additionalModuleStyles,
    ]
  );
});
JS;
}


/**
 * Register custom option field attributes for Divi 5 Gallery arrows.
 *
 * @param array $settings The module metadata settings.
 * @return array The modified module metadata settings.
 */
add_filter('block_type_metadata_settings', function($settings) {
    $module_name = $settings['name'] ?? '';
    $module_attributes = $settings['attributes'] ?? false;
    if ($module_name !== DIVI5_MODULE_SLUG) {
        return $settings;
    }
    if (!$module_attributes) {
        return $settings;
    }

    // Register the custom arrows attribute (same as JS registration)
    $settings['attributes'][ADVANCED_FIELD_SLUG] = get_d5_attribute_definition();
    return $settings;
});


function get_d5_attribute_definition() {
    return [
        'type' => 'object',
        'selector' => '{{selector}} .et-pb-slider-arrows a',
        'settings' => [
            'decoration' => [
                'font' => [
                    'groupType' => 'group-item',
                    'item' => [
                        'groupSlug' => 'designSliderArrows',
                        'render' => true,
                        'component' => [
                            'name' => 'divi/font',
                            'type' => 'group',
                            'props' => [
                                'grouped' => false,
                                'fieldLabel' => __('Slider Arrows', 'divi-booster'),
                                'defaultGroupAttr' => [
                                    'font' => [
                                        'desktop' => [
                                            'value' => [
                                                'size' => '48px'
                                            ]
                                        ]
                                    ]
                                ],
                                'fields' => [
                                    'lineHeight' => [
                                        'render' => false
                                    ],
                                    'textAlign' => [
                                        'render' => false
                                    ],
                                    'family' => [
                                        'render' => false
                                    ],
                                    'weight' => [
                                        'render' => false
                                    ],
                                    'style' => [
                                        'render' => false
                                    ],
                                    'letterSpacing' => [
                                        'render' => false
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ],
        'styleProps' => [
            'font' => [
                'important' => [
                    'font' => [
                        'desktop' => [
                            'value' => [
                                'color' => true
                            ]
                        ]
                    ]
                ],
                'propertySelectors' => [
                    'textShadow' => [
                        'desktop' => [
                            'value' => [
                                'text-shadow' => '{{selector}} .et-pb-slider-arrows a:before'
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ];
}

// === Divi 4 Advanced Fields ===
add_filter('et_pb_gallery_advanced_fields', __NAMESPACE__ . '\add_advanced_fields', 10, 3);
// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_arrow_styles_conversion( $conversion_outline, $module_name ) {
    if ( DIVI5_MODULE_SLUG !== $module_name ) {
        return $conversion_outline;
    }
    if (!isset($conversion_outline['advanced']) || !is_array($conversion_outline['advanced'])) {
        $conversion_outline['advanced'] = array();
    }
    if (!isset($conversion_outline['advanced']['fonts']) || !is_array($conversion_outline['advanced']['fonts'])) {
        $conversion_outline['advanced']['fonts'] = array();
    }
    $conversion_outline['advanced']['fonts'][ADVANCED_FIELD_SLUG] = ADVANCED_FIELD_SLUG . '.decoration.font';
    return $conversion_outline;
}
add_filter( 'divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\dbdb_register_divi5_arrow_styles_conversion', 10, 2 );
function add_advanced_fields($fields, $slug, $main_css_element) {
    if (!is_array($fields) || !isset($fields['fonts'])) {
        return $fields;
    }
    $fields['fonts'][ADVANCED_FIELD_SLUG] = array(
        'label'      => esc_html__('Slider Arrows', 'divi-booster'),
        'css'        => array(
            'main'       => "{$main_css_element} .et-pb-slider-arrows a",
            'hover'      => "{$main_css_element} .et-pb-slider-arrows a:hover",
            'text_shadow' => "{$main_css_element} .et-pb-slider-arrows a:before",
            'important' => array('text_shadow')
        ),
        'hide_text_align'   => true,
        'hide_font'        => true,
        'hide_line_height' => true,
        'hide_letter_spacing' => true,
        'font_size'       => array('default' => '48px'),
    );
    return $fields;
}

// === Default Arrows CSS for Both Divi 4 and Divi 5 ===
add_action('wp_head', __NAMESPACE__ . '\add_default_styles');
function add_default_styles() {
?>
<style>
    .et_pb_gallery .et-pb-slider-arrows a {
        margin-top: 0;
        transform: translateY(-50%);
    }
</style>
<?php
}


// === Divi 5 Custom Group Registration for Slider Arrows ===
function get_d5_slider_arrows_group_js() {
    return <<<JS
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleSettings.groups.divi.gallery', 'divi', (groups, metadata) => {
  groups.designSliderArrows = {
    groupName: 'designSliderArrows',
    panel: 'design',
    priority: 20,
    multiElements: true,
    component: {
        name: 'divi/composite',
        props: {
        groupLabel: 'Slider Arrows',
            visible: ({ attrs }) => {
                return attrs?.module?.advanced?.fullwidth?.desktop?.value === 'on';
            },
        },
    },
  };
  return groups;
});
JS;
}

add_action('divi_visual_builder_assets_before_enqueue_scripts', __NAMESPACE__ . '\enqueue_d5_slider_arrows_group_script');
function enqueue_d5_slider_arrows_group_script() {
    $handle = sanitize_title('divi-booster-slider-arrows-group');
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_d5_slider_arrows_group_js());
}


// New Divi 5 front-end styles filter using Style::add
add_filter('divi_module_wrapper_render', function($module_wrapper, $args) {
    $module_id = $args['id'] ?? '';
    $module_name = $args['name'] ?? '';
    $module_order_index = $args['orderIndex'] ?? 0;
    $module_store_instance = $args['storeInstance'] ?? 0;
    $module_elements = $args['elements'] ?? null;
    if ($module_name !== DIVI5_MODULE_SLUG || !$module_elements) {
        return $module_wrapper;
    }

    // Advanced field: font size style
    if (is_callable('\ET\Builder\FrontEnd\Module\Style::add')) {
        \ET\Builder\FrontEnd\Module\Style::add([
            'id'            => $module_id,
            'name'          => $module_name,
            'orderIndex'    => $module_order_index,
            'storeInstance' => $module_store_instance,
            'styles'        => [
                $module_elements->style([
                    'attrName'   => ADVANCED_FIELD_SLUG
                ])
            ],
        ]);
    }

    return $module_wrapper;
}, 10, 2);


