<?php

namespace DiviBooster\GalleryBooster\LightboxTitle;

// === Constants ===
const DIVI4_MODULE_SLUG  = 'et_pb_gallery';
const DIVI5_MODULE_SLUG  = 'divi/gallery';
const ADVANCED_FIELD_SLUG = 'dbdb_lightbox_title'; // Divi 4 advanced font slug (must not change)
const DIVI5_ATTR_SLUG     = 'diviboosterLightboxTitle'; // Divi 5 attribute slug

// === Divi 4: Advanced Fields ===
if (function_exists('add_filter')) {
    \add_filter('et_pb_gallery_advanced_fields', __NAMESPACE__ . '\\add_advanced_fields', 10, 3);
}
function add_advanced_fields($fields, $slug, $main_css_element) {
    if (!is_array($fields) || !isset($fields['fonts'])) {
        return $fields;
    }

    // Derive '%%order_class%%' from '%%order_class%%.et_pb_gallery'
    $order_class = preg_replace('/\\.[^\\.]+$/', '', $main_css_element);

    $fields['fonts'][ADVANCED_FIELD_SLUG] = array(
        'label'      => esc_html__('Lightbox Title', 'divi-booster'),
        'css'        => array(
            'main'        => "{$order_class}_dbdb_lightbox_open .mfp-gallery .mfp-title",
            'hover'       => "{$order_class}_dbdb_lightbox_open .mfp-gallery .mfp-title:hover",
            'text_shadow' => "{$order_class}_dbdb_lightbox_open .mfp-gallery .mfp-title",
            // Ensure front-end rules win over theme defaults
            'important'   => array('main', 'hover', 'text_shadow'),
        ),
        'font_size'       => array(
            'default' => '14px',
        ),
        // Hide when lightbox disabled (Divi 4 toggle provided by Disable Lightbox feature if present)
        'show_if' => array(
            'dbdb_show_in_lightbox' => 'on'
        ),
    );

    return $fields;
}

// === Divi 4: Output Padding Fix and Script Injection ===
if (function_exists('add_filter')) {
    \add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\d4_output_padding_fix', 10, 3);
}
function d4_output_padding_fix($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props) || !is_array($module->props)) {
        return $output;
    }

    if (class_exists('ET_Builder_Element') && is_callable(array('ET_Builder_Element', 'set_style'))) {
        \ET_Builder_Element::set_style(
            $render_slug,
            array(
                'selector'    => '%%order_class%%_dbdb_lightbox_open .mfp-gallery .mfp-title',
                'declaration' => 'padding-right: 0 !important;'
            )
        );
    }

    if (function_exists('add_action') && !has_action('wp_footer', __NAMESPACE__ . '\\output_body_class_script_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_body_class_script_once');
    }

    return $output;
}

// === Body Class Script (Shared D4/D5) ===
if (function_exists('add_action')) {
    add_action('wp_footer', __NAMESPACE__ . '\\output_body_class_script_once');
}
function output_body_class_script_once() {
    static $done = false;
    if ($done) return;
    $done = true;
?>
<script>
jQuery(document).ready(function($) {
    function clearDbdbLightboxOpen() {
        $('body').removeClass(function(index, className) {
            return (className.match(/(^|\s)et_pb_gallery_\d+(?:_[^\s]+)?_dbdb_lightbox_open/g) || []).join(' ');
        });
    }

    // Add per-instance body class when a gallery image is clicked
    $(document).on('click', '.et_pb_gallery .et_pb_gallery_image a', function() {
        clearDbdbLightboxOpen();
        var $gallery = $(this).closest('.et_pb_gallery');
        if (!$gallery.length) return;
        var classes = ($gallery.attr('class') || '').match(/et_pb_gallery_\d+(?:_[^\s]+)?/);
        if (!classes || !classes[0]) return;
        var orderClass = classes[0];
        $('body').addClass(orderClass + '_dbdb_lightbox_open');
    });

    // Remove class when popup closes
    $(document).on('click', '.mfp-close, .mfp-bg', function() { clearDbdbLightboxOpen(); });
    $(document).on('keyup', function(e) { if (e.key === 'Escape') { clearDbdbLightboxOpen(); } });
});
</script>
<?php
}


// === Divi 5: Register attribute in block metadata (front-end) ===
if (function_exists('add_filter')) {
    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 Lightbox Title attribute for Divi 5 front-end
        $settings['attributes'][DIVI5_ATTR_SLUG] = get_divi5_attribute_definition();
        return $settings;
    });
}


// === Divi 5: VB-only JS for Attribute, Conversion & UI Group ===
if (function_exists('add_action')) {
    add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_vb_js');
}
function enqueue_divi5_vb_js() {
    // Guard: only in Divi 5 builder
    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_ATTR_SLUG);
    wp_register_script($handle, '', array('lodash', 'divi-vendor-wp-hooks'), null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_divi5_inline_js());
}
function get_divi5_inline_js() {
    $attr = wp_json_encode(get_divi5_attribute_definition());
    $d5name = wp_json_encode(DIVI5_MODULE_SLUG);
    $d4slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $key    = wp_json_encode(DIVI5_ATTR_SLUG);
    $d4key  = wp_json_encode(ADVANCED_FIELD_SLUG);
    return <<<JS
// Register custom attribute for Lightbox Title styling
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.gallery', 'divi', (attributes) => {
    attributes[{$key}] = {$attr};
    // Ensure visibility follows lightbox enabled toggle if present
    if (attributes[{$key}]?.settings?.decoration?.font?.item) {
        const item = attributes[{$key}].settings.decoration.font.item;
        item.visible = function({ attrs }) {
            // Show if custom "Enable Lightbox" attribute is on, or if absent
            const v = attrs?.diviboosterShowInLightbox?.desktop?.value;
            return (typeof v === 'undefined') || v !== 'off';
        };
    }
    return attributes;
});

// Add a dedicated group in Design panel for Lightbox Title
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleSettings.groups.divi.gallery', 'divi', (groups) => {
  groups.designLightboxText = {
    groupName: 'designLightboxText',
    panel: 'design',
    priority: 29,
    multiElements: true,
    component: {
      name: 'divi/composite',
      props: {
        groupLabel: 'Lightbox Title',
        visible: ({ attrs }) => {
            const v = attrs?.diviboosterShowInLightbox?.desktop?.value;
            return (typeof v === 'undefined') || v !== 'off';
        },
      }
    }
  };
  return groups;
});

// Conversion (Divi 4 -> Divi 5)
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$d4slug}) return conversionOutline;
    if (!conversionOutline.advanced) conversionOutline.advanced = {};
    if (!conversionOutline.advanced.fonts) conversionOutline.advanced.fonts = {};
    conversionOutline.advanced.fonts[{$d4key}] = {$key} + '.decoration.font';
    return conversionOutline;
});

// VB style rendering for custom attribute
window.vendor.wp.hooks.addFilter('divi.module.wrapper.render', 'divi', (moduleWrapper, param) => {
  const { name: moduleName, elements: moduleElements, state: moduleState } = param;
  if ('divi/gallery' !== moduleName || !moduleElements) return moduleWrapper;
  const { StyleContainer } = window.divi.module;
  const { isEdited } = moduleWrapper.props;
  const additionalModuleStyles = window.vendor.wp.element.createElement(
    StyleContainer,
    { key: 'additional-lightbox-title-styles', mode: 'builder', state: isEdited ? moduleState : '', noStyleTag: false },
    moduleElements.style({ attrName: {$key} })
  );
  return window.vendor.wp.element.cloneElement(moduleWrapper, {}, moduleWrapper.props.children, [ additionalModuleStyles ]);
});
JS;
}

// === Divi 5: Conversion Outline (PHP Fallback) ===
if (function_exists('add_filter')) {
    add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\register_d5_conversion_outline', 10, 2);
}
function register_d5_conversion_outline($conversion_outline, $module_name) {
    if ($module_name !== DIVI5_MODULE_SLUG) {
        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] = DIVI5_ATTR_SLUG . '.decoration.font';
    return $conversion_outline;
}

// === Divi 5: Front-end Styles Printing ===
if (function_exists('add_filter')) {
    add_filter('divi_module_wrapper_render', __NAMESPACE__ . '\\d5_frontend_styles', 10, 2);
}
function d5_frontend_styles($module_wrapper, $args) {
    $module_name        = $args['name'] ?? '';
    $module_elements    = $args['elements'] ?? null;
    
    if ($module_name !== DIVI5_MODULE_SLUG || !$module_elements) {
        return $module_wrapper;
    }
    if (is_callable('\ET\Builder\FrontEnd\Module\Style::add')) {
        \ET\Builder\FrontEnd\Module\Style::add(array(
            'id'            => $args['id'] ?? '',
            'name'          => $module_name,
            'orderIndex'    => $args['orderIndex'] ?? 0,
            'storeInstance' => $args['storeInstance'] ?? 0,
            'styles'        => array(
                $module_elements->style(array('attrName' => DIVI5_ATTR_SLUG))
            ),
        ));
    }
    return $module_wrapper;
}

// === Divi 5: Padding Fix (per instance) and script injection guard ===
if (function_exists('add_filter')) {
    add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__ . '\\d5_output_padding_fix', 10, 3);
}
function d5_output_padding_fix($block_content, $parsed_block, $block) {
    if (!is_string($block_content)) {
        return $block_content;
    }
    // Append per-instance style for padding fix
    $order_class = extract_order_class_from_content($block_content);
    if ($order_class) {
        $style  = '<style>.' . esc_attr($order_class) . '_dbdb_lightbox_open .mfp-gallery .mfp-title{padding-right:0 !important;}</style>';
        $block_content .= $style;
    }
    if (function_exists('add_action') && !has_action('wp_footer', __NAMESPACE__ . '\\output_body_class_script_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_body_class_script_once');
    }
    return $block_content;
}

// === Helpers ===
function get_divi5_attribute_definition() {
    return array(
        'type'     => 'object',
        'selector' => '{{selector}}_dbdb_lightbox_open .mfp-gallery .mfp-title',
        'settings' => array(
            'decoration' => array(
                'font' => array(
                    'groupType' => 'group-item',
                    'item'      => array(
                        'groupSlug' => 'designLightboxText',
                        'render'    => true,
                        'priority'  => 52,
                        'component' => array(
                            'type'  => 'group',
                            'name'  => 'divi/font',
                            'props' => array(
                                'grouped'        => false,
                                'fieldLabel'     => __('Lightbox Title', 'divi-booster'),
                                'defaultGroupAttr' => array(
                                    'font' => array(
                                        'desktop' => array(
                                            'value' => array(
                                                'size' => '14px'
                                            )
                                        )
                                    )
                                ),
                            )
                        )
                    )
                )
            )
        ),
        'styleProps' => array(
            'font' => array(
                'important' => array(
                    'font' => array(
                        'desktop' => array(
                            'value' => array(
                                'color'  => true,
                                'family' => true,
                                'size'   => true,
                                'weight' => true,
                                'style'  => true
                            )
                        )
                    )
                ),
                'propertySelectors' => array(
                    'textShadow' => array(
                        'desktop' => array(
                            'value' => array(
                                'text-shadow' => '{{selector}}_dbdb_lightbox_open .mfp-gallery .mfp-title'
                            )
                        )
                    )
                )
            )
        ),

    );
}

function extract_order_class_from_content($content) {
    if (!is_string($content) || $content === '') return '';
    // Find the first gallery wrapper and extract its order class (supports optional suffix like _tb_header)
    if (preg_match('/<div[^>]*class=\"([^\"]*\bet_pb_gallery\b[^\"]*)\"/i', $content, $m)) {
        $classes = preg_split('/\s+/', $m[1], -1, PREG_SPLIT_NO_EMPTY);
        foreach ($classes as $c) {
            if (preg_match('/^et_pb_gallery_\d+(?:_[^\s]+)?$/', $c)) {
                return $c;
            }
        }
    }
    return '';
}



// Created at 1758001215.
