<?php

namespace DiviBooster\GalleryBooster\LighboxBackground;

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_lightbox_background_color';
const DIVI5_SETTING_SLUG = 'diviboosterLightboxBackgroundColor';
const DIVI4_LIGHTBOX_TOGGLE = 'dbdb_lightbox';
const DIVI4_ENABLE_LIGHTBOX_SLUG = 'dbdb_show_in_lightbox';
const DIVI5_ENABLE_LIGHTBOX_SLUG = 'diviboosterShowInLightbox';

// === Hooks Registration ===
if (function_exists('add_filter')) {
    // Divi 4: Register field directly on Gallery module
    \add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_field');
    // Divi 4: Advanced fields group for Lightbox
    \add_filter('et_pb_gallery_advanced_fields', __NAMESPACE__ . '\\add_advanced_fields', 10, 3);
    // Divi 4: Output processing
    \add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\divi4_output', 10, 3);

    // Divi 5: Output processing
    \add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__ . '\\divi5_output', 10, 3);

    // Divi 5: PHP attribute registration
    \add_filter('divi_module_library_register_module_attrs', __NAMESPACE__ . '\\register_divi5_attribute', 10, 2);

    // Divi 5: PHP conversion outline registration
    \add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_lightbox_bgcolor_conversion', 10, 2);
}

if (function_exists('add_action')) {
    // Divi 5: Enqueue VB-only JS for attribute + conversion + group
    \add_action('divi_visual_builder_assets_before_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_js');
}

// === Divi 4 Field Registration ===
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'           => esc_html__('Lightbox Background Color', 'divi-gallery-booster'),
        'type'            => 'color-alpha',
        'option_category' => 'configuration',
        'default'         => '',
        'tab_slug'        => 'advanced',
        'toggle_slug'     => DIVI4_LIGHTBOX_TOGGLE,
        'description'     => esc_html__('Choose the background color for lightbox.', 'divi-gallery-booster'),
        'show_if'         => array(
            DIVI4_ENABLE_LIGHTBOX_SLUG => 'on',
        ),
    );
    return $fields;
}

// === Divi 4 Advanced Fields Group (Lightbox) ===
function add_advanced_fields($fields, $slug, $main_css_element) {
    if (!is_array($fields)) {
        return $fields;
    }
    if (!isset($fields['fonts'])) {
        $fields['fonts'] = array();
    }
    // Create an empty font toggle to hold our fields (as per original implementation)
    $fields['fonts'][DIVI4_LIGHTBOX_TOGGLE] = array(
        'label'               => esc_html__('Lightbox', 'divi-booster'),
        'hide_text_color'     => true,
        'hide_font_size'      => true,
        'hide_text_shadow'    => true,
        'hide_text_align'     => true,
        'hide_font'           => true,
        'hide_line_height'    => true,
        'hide_letter_spacing' => true,
    );
    return $fields;
}

// === Divi 5: Attribute Registration (PHP) ===
function register_divi5_attribute($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }
    $module_attrs[DIVI5_SETTING_SLUG] = get_divi5_attribute_definition();
    return $module_attrs;
}

// === Divi 5: Conversion outline mapping (PHP) ===
function dbdb_register_divi5_lightbox_bgcolor_conversion($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();
    }
    $conversion_outline['module'][DIVI4_SETTING_SLUG] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}

// === Divi 5: Attribute definition ===
function get_divi5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'lightboxBgColor' => [
                        'groupSlug'   => 'designLightbox',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Lightbox Background Color', 'divi-gallery-booster'),
                        'description' => __('Choose the background color for lightbox.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'design',
                        ],
                        'render'      => true,
                        'priority'    => 99,
                        'component'   => [
                            'type'  => 'field',
                            'name'  => 'divi/color-picker',
                            'props' => [ 'isAlpha' => true ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: JS Attribute Registration + Conversion + Group ===
function enqueue_divi5_js() {
    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_SETTING_SLUG);
    wp_register_script($handle, '', ['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());
    $d4slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $d5key = wp_json_encode(DIVI5_SETTING_SLUG);
    $d4key = wp_json_encode(DIVI4_SETTING_SLUG);
    return <<<JS
// Adds the custom attribute to the Gallery module.
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.gallery', 'divi', (attributes) => {
  attributes[{$d5key}] = {$attr};
  return attributes;
});

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

// Register Design group for Lightbox
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleSettings.groups.divi.gallery', 'divi', (groups) => {
  groups.designLightbox = {
    groupName: 'designLightbox',
    panel: 'design',
    priority: 20,
    multiElements: true,
    component: {
      name: 'divi/composite',
      props: {
        groupLabel: 'Lightbox',
        visible: ({ attrs }) => {
          const v = attrs?.diviboosterShowInLightbox;
          if (!v) return true; // default on
          return (v?.desktop?.value ?? v?.value ?? 'on') !== 'off';
        },
      }
    }
  };
  return groups;
});
JS;
}

// === Common Helpers ===
function sanitize_color($color) {
    if (!is_string($color)) return '';
    $color = trim($color);
    if ($color === '') return '';

    // Hex (#rgb, #rgba, #rrggbb, #rrggbbaa)
    if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $color)) {
        return $color;
    }
    // rgb/rgba/hsl/hsla functions
    if (preg_match('/^(rgb|rgba|hsl|hsla)\(\s*[-0-9.,%\s]+\)$/i', $color)) {
        return $color;
    }
    return '';
}

function lightbox_enabled($props) {
    // Divi 4
    if (isset($props[DIVI4_ENABLE_LIGHTBOX_SLUG])) {
        return ($props[DIVI4_ENABLE_LIGHTBOX_SLUG] === 'on');
    }
    // Divi 5
    if (isset($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['desktop']['value'])) {
        return ($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['desktop']['value'] === 'on');
    }
    if (isset($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['value'])) {
        return ($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['value'] === 'on');
    }
    // Default: enabled
    return true;
}

function resolve_color_from_props($props) {
    // Divi 4 flat
    if (isset($props[DIVI4_SETTING_SLUG])) {
        $c = sanitize_color($props[DIVI4_SETTING_SLUG]);
        if ($c !== '') return $c;
    }
    // Divi 5 structured
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value'])) {
        $c = sanitize_color($props[DIVI5_SETTING_SLUG]['desktop']['value']);
        if ($c !== '') return $c;
    }
    if (isset($props[DIVI5_SETTING_SLUG]['value'])) {
        $c = sanitize_color($props[DIVI5_SETTING_SLUG]['value']);
        if ($c !== '') return $c;
    }
    return '';
}

function inject_data_attr_into_gallery($content, $attr_name, $attr_value) {
    if (!is_string($content) || $content === '') return $content;
    $attr_value_esc = esc_attr($attr_value);
    return preg_replace_callback(
        '/<div([^>]*)class=\"([^\"]*\\bet_pb_gallery\\b[^\"]*)\"/i',
        function($m) use ($attr_name, $attr_value_esc) {
            $before = $m[1];
            $classes = $m[2];
            if (strpos($before, $attr_name) === false) {
                $before .= ' ' . $attr_name . '="' . $attr_value_esc . '"';
            } else {
                $before = preg_replace('/' . preg_quote($attr_name, '/') . '\\s*=\\s*\"[^\"]*\"/i', $attr_name . '="' . $attr_value_esc . '"', $before);
            }
            return '<div' . $before . 'class="' . $classes . '"';
        },
        $content,
        1 // first gallery wrapper only
    );
}

function output_script_and_styles_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    ?>
    <script>
    jQuery(document).ready(function($) {
        function clearDbdbLightboxBg() {
            // Remove our per-instance classes
            $('body').removeClass(function(idx, className) {
                return (className.match(/(^|\s)et_pb_gallery_\d+(?:_[^\s]+)?_dbdb_lightbox_(?:open|bgcolor)\b/g) || []).join(' ');
            });
            // Clear CSS variable
            if (document.body && document.body.style) {
                document.body.style.removeProperty('--dbdb-gb-lbbox-color');
            }
        }

        // Click handler: when a gallery image is clicked
        $(document).on('click', '.et_pb_gallery .et_pb_gallery_image a', function() {
            clearDbdbLightboxBg();
            var $gallery = $(this).closest('.et_pb_gallery');
            if (!$gallery.length) return;
            var classMatches = ($gallery.attr('class') || '').match(/et_pb_gallery_\d+(?:_[^\s]+)?/);
            if (!classMatches) return;
            var orderClass = classMatches[0];
            var color = $gallery.attr('data-dbdb-lightbox-bg-color');
            if (color) {
                // Add per-instance body classes
                $('body').addClass(orderClass + '_dbdb_lightbox_open');
                $('body').addClass(orderClass + '_dbdb_lightbox_bgcolor');
                if (document.body && document.body.style) {
                    document.body.style.setProperty('--dbdb-gb-lbbox-color', color);
                }
            }
        });

        // Clear when popup closes
        $(document).on('click', '.mfp-close, .mfp-bg', function() { clearDbdbLightboxBg(); });
        $(document).on('keyup', function(e) { if (e.key === 'Escape') { clearDbdbLightboxBg(); } });
    });
    </script>
    <style>
    [class*="_dbdb_lightbox_bgcolor"] .mfp-bg {
        background-color: var(--dbdb-gb-lbbox-color) !important;
    }
    </style>
    <?php
}

// === Divi 4 Output ===
function divi4_output($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props) || !is_array($module->props)) {
        return $output;
    }
    $props = $module->props;
    if (!lightbox_enabled($props)) {
        return $output;
    }
    $color = resolve_color_from_props($props);
    if ($color === '') {
        // No color set by user; do not inject or override anything, let Divi handle it
        return $output;
    }

    // Inject data attribute with color on the gallery wrapper (for unified JS/CSS approach and Divi 5 parity)
    $output = inject_data_attr_into_gallery($output, 'data-dbdb-lightbox-bg-color', $color);

    if (!has_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once');
    }

    return $output;
}

// === Divi 5 Output ===
function divi5_output($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? array();
    if (!lightbox_enabled($attrs)) {
        return $block_content;
    }
    $color = resolve_color_from_props($attrs);
    if ($color === '') {
        // No color set by user; do not inject or override anything, let Divi handle it
        return $block_content;
    }

    // Inject data attribute with color on the gallery wrapper
    $block_content = inject_data_attr_into_gallery($block_content, 'data-dbdb-lightbox-bg-color', $color);

    if (!has_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once');
    }

    return $block_content;
}

// Created at 1756263607.
