<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_DMM_Badges extends AIEO_DMM_Module_Base {

    const OPTION_KEY        = 'aieo_dmm_badges_settings';
    const SETTINGS_VERSION  = 1;

    public function get_id()       { return 'badges'; }
    public function get_label()    { return __('Badges', 'ai-eshop-optimizer'); }
    public function get_priority() { return 25; } 
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_badges_save', array($this, 'ajax_save'));
        
        
        
        add_action('admin_init', array(__CLASS__, 'maybe_migrate'));
        
        
        
        add_filter('body_class', array(__CLASS__, 'body_class_filter'));
    }

    
    public static function body_class_filter($classes) {
        $s          = self::get_settings();
        $placements = isset($s['placements']) && is_array($s['placements']) ? $s['placements'] : array();
        foreach (array('archive', 'pdp', 'recos', 'side_cart') as $surface) {
            $pl = isset($placements[$surface]) ? $placements[$surface] : array();
            if (is_string($pl)) {
                $migrated = self::migrate_legacy_placement($pl);
                if ($migrated) { $pl = $migrated; }
            }
            if (is_array($pl)) {
                if (!empty($pl['location'])) {
                    $classes[] = 'aieo-bp-' . $surface . '--' . sanitize_html_class($pl['location']);
                }
                if (!empty($pl['shape'])) {
                    $classes[] = 'aieo-bs-' . $surface . '--' . sanitize_html_class($pl['shape']);
                }
            }
        }
        
        
        if (isset($placements['archive']['location']) && $placements['archive']['location'] === 'below_favourite') {
            $classes[] = 'aieo-badges-below-fav';
        }
        return (array) $classes;
    }

    
    public static function location_options() {
        return array(
            'archive' => array(
                'below_favourite' => __('Below favourite (right column)', 'ai-eshop-optimizer'),
                'top_left'        => __('Top-left over image', 'ai-eshop-optimizer'),
                'top_right'       => __('Top-right over image', 'ai-eshop-optimizer'),
                'inline'          => __('Inline above title', 'ai-eshop-optimizer'),
            ),
            'pdp' => array(
                'top_left'  => __('Top-left over gallery', 'ai-eshop-optimizer'),
                'top_right' => __('Top-right over gallery', 'ai-eshop-optimizer'),
                'inline'    => __('Inline above title (right column)', 'ai-eshop-optimizer'),
            ),
            'recos' => array(
                'inline'    => __('Inline above title', 'ai-eshop-optimizer'),
                'top_left'  => __('Top-left over image', 'ai-eshop-optimizer'),
                'top_right' => __('Top-right over image', 'ai-eshop-optimizer'),
            ),
            'side_cart' => array(
                'inline'   => __('Inline above title', 'ai-eshop-optimizer'),
                'top_left' => __('Top-left over thumb', 'ai-eshop-optimizer'),
            ),
        );
    }

    
    public static function shape_options() {
        return array(
            'chip'   => __('Chip (rounded rectangle)', 'ai-eshop-optimizer'),
            'circle' => __('Circle (round, icon-only friendly)', 'ai-eshop-optimizer'),
        );
    }

    
    public static function default_location($surface) {
        $opts = self::location_options();
        if (!isset($opts[$surface]) || empty($opts[$surface])) { return ''; }
        return (string) array_key_first($opts[$surface]);
    }
    public static function default_shape() {
        $opts = self::shape_options();
        return $opts ? (string) array_key_first($opts) : 'chip';
    }

    
    public static function migrate_legacy_placement($legacy) {
        $legacy = (string) $legacy;
        if ($legacy === '') { return null; }
        
        if ($legacy === 'below_favourite') {
            return array('location' => 'below_favourite', 'shape' => 'circle');
        }
        
        if (strpos($legacy, 'top_left_') === 0)  { return array('location' => 'top_left',  'shape' => 'chip'); }
        if (strpos($legacy, 'top_right_') === 0) { return array('location' => 'top_right', 'shape' => 'chip'); }
        
        if (strpos($legacy, 'inline') === 0)     { return array('location' => 'inline',    'shape' => 'chip'); }
        return null;
    }

    
    
    

    
    public static function defaults() {
        return array(
            'version'         => self::SETTINGS_VERSION,
            'hide_wc_onsale'  => true,
            
            
            
            
            
            
            
            
            'sizes' => array(
                'archive'   => array('desktop' => 11, 'mobile' => 10),
                'pdp'       => array('desktop' => 13, 'mobile' => 11),
                'recos'     => array('desktop' => 10, 'mobile' => 9),
                'side_cart' => array('desktop' => 10, 'mobile' => 9),
            ),
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            'placements' => array(
                'archive'   => array('location' => 'below_favourite', 'shape' => 'circle'),
                'pdp'       => array('location' => 'top_left',         'shape' => 'chip'),
                'recos'     => array('location' => 'inline',           'shape' => 'chip'),
                'side_cart' => array('location' => 'inline',           'shape' => 'chip'),
            ),
            'families' => array(
                'sale'          => self::default_family('SALE',                '#dc2626', '#ffffff', 10),
                'monthly_offer' => self::default_family('ΠΡΟΣΦΟΡΑ ΤΟΥ ΜΗΝΑ',   '#F46767', '#ffffff', 15),
                'pro'           => self::default_family('PRO',                 '#1f3b8b', '#ffffff', 20, '★'),
                'new'           => self::default_family('NEW',                 '#1a1a1a', '#ffffff', 30),
                'gift'          => self::default_family('+ Free gift',         '#0a7d3a', '#ffffff', 40, '🎁'),
            ),
        );
    }

    private static function default_family($label, $bg, $fg, $order, $icon = '') {
        return array(
            'enabled'        => true,
            'label'          => (string) $label,
            'icon'           => (string) $icon,
            
            
            
            
            'icon_image'     => 0,    
            'icon_image_url' => '',   
            'order'          => (int) $order,
            'bg'             => (string) $bg,
            'fg'             => (string) $fg,
            'surfaces' => array(
                'archive'   => true,
                'pdp'       => true,
                'recos'     => true,
                'side_cart' => false,
            ),
        );
    }

    
    public static function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $defaults = self::defaults();

        $out = array_merge($defaults, $stored);

        
        
        
        
        $out['sizes'] = array();
        foreach ($defaults['sizes'] as $surface => $def) {
            $stored_val = isset($stored['sizes'][$surface]) ? $stored['sizes'][$surface] : null;
            if (is_int($stored_val) || (is_string($stored_val) && ctype_digit($stored_val))) {
                
                $out['sizes'][$surface] = array(
                    'desktop' => (int) $stored_val,
                    'mobile'  => max(8, (int) round((int) $stored_val * 0.9)),
                );
            } elseif (is_array($stored_val)) {
                $out['sizes'][$surface] = array(
                    'desktop' => isset($stored_val['desktop']) ? (int) $stored_val['desktop'] : (int) $def['desktop'],
                    'mobile'  => isset($stored_val['mobile'])  ? (int) $stored_val['mobile']  : (int) $def['mobile'],
                );
            } else {
                $out['sizes'][$surface] = $def;
            }
        }

        
        
        
        $out['placements'] = $defaults['placements'];
        $stored_placements = isset($stored['placements']) && is_array($stored['placements']) ? $stored['placements'] : array();
        foreach ($defaults['placements'] as $surface => $def_pl) {
            $sp = isset($stored_placements[$surface]) ? $stored_placements[$surface] : null;
            if (is_string($sp)) {
                
                $migrated = self::migrate_legacy_placement($sp);
                $out['placements'][$surface] = $migrated ? $migrated : $def_pl;
            } elseif (is_array($sp)) {
                $out['placements'][$surface] = array(
                    'location' => isset($sp['location']) ? (string) $sp['location'] : $def_pl['location'],
                    'shape'    => isset($sp['shape'])    ? (string) $sp['shape']    : $def_pl['shape'],
                );
            }
        }
        
        if (!isset($stored_placements['archive']) && isset($stored['archive_layout']) && is_string($stored['archive_layout'])) {
            $migrated = self::migrate_legacy_placement($stored['archive_layout']);
            if ($migrated) { $out['placements']['archive'] = $migrated; }
        }
        
        
        $valid_locations = self::location_options();
        $valid_shapes    = self::shape_options();
        foreach ($out['placements'] as $surface => $pl) {
            if (!isset($valid_locations[$surface][$pl['location']])) {
                $out['placements'][$surface]['location'] = self::default_location($surface);
            }
            if (!isset($valid_shapes[$pl['shape']])) {
                $out['placements'][$surface]['shape'] = self::default_shape();
            }
        }
        $out['families'] = isset($stored['families']) && is_array($stored['families'])
            ? $stored['families'] : array();
        foreach ($defaults['families'] as $key => $family_default) {
            $stored_family = isset($out['families'][$key]) && is_array($out['families'][$key])
                ? $out['families'][$key] : array();
            $merged = array_merge($family_default, $stored_family);
            
            $merged['surfaces'] = array_merge(
                $family_default['surfaces'],
                is_array($stored_family['surfaces'] ?? null) ? $stored_family['surfaces'] : array()
            );
            $out['families'][$key] = $merged;
        }
        return $out;
    }

    public static function get_family($key) {
        $s = self::get_settings();
        return isset($s['families'][$key]) ? $s['families'][$key] : null;
    }

    public static function family_enabled_for_surface($key, $surface) {
        $f = self::get_family($key);
        if (!$f || empty($f['enabled'])) { return false; }
        return !empty($f['surfaces'][$surface]);
    }

    
    
    

    public static function maybe_migrate() {
        $existing = get_option(self::OPTION_KEY, null);
        if (is_array($existing) && isset($existing['version']) && (int) $existing['version'] >= self::SETTINGS_VERSION) {
            return;
        }
        $unified = self::build_from_legacy();
        update_option(self::OPTION_KEY, $unified, false);
    }

    
    public static function build_from_legacy() {
        $unified = self::defaults();

        
        $pls = get_option('aieo_dmm_product_labels_settings', array());
        if (!is_array($pls)) { $pls = array(); }
        $legacy_pls = get_option('om_ppe_product-labels', array());
        if (!is_array($legacy_pls)) { $legacy_pls = array(); }
        $pls = array_merge($legacy_pls, $pls);

        if (!empty($pls)) {
            $rule = isset($pls['display_rules']) ? $pls['display_rules'] : 'products_on_sale';
            
            $family_key = ($rule === 'new_products') ? 'new' : 'sale';
            $unified['families'][$family_key]['enabled'] = !empty($pls['enabled']);
            if (!empty($pls['label_text'])) {
                $unified['families'][$family_key]['label'] = (string) $pls['label_text'];
            }
            if (!empty($pls['background_color'])) {
                $unified['families'][$family_key]['bg'] = (string) $pls['background_color'];
            }
            if (!empty($pls['text_color'])) {
                $unified['families'][$family_key]['fg'] = (string) $pls['text_color'];
            }
        }

        
        if (class_exists('AIEO_DMM_Settings')) {
            $ml = (string) AIEO_DMM_Settings::get('monthly_offer_label', '');
            if ($ml !== '') { $unified['families']['monthly_offer']['label'] = $ml; }
            $nl = (string) AIEO_DMM_Settings::get('new_product_label', '');
            if ($nl !== '') { $unified['families']['new']['label'] = $nl; }
        }

        
        $rp = get_option('aieo_dmm_role_pricing_settings', array());
        if (is_array($rp)) {
            if (!empty($rp['pro_badge_label']))      { $unified['families']['pro']['label'] = (string) $rp['pro_badge_label']; }
            if (!empty($rp['pro_badge_bg_color']))   { $unified['families']['pro']['bg']    = (string) $rp['pro_badge_bg_color']; }
            if (!empty($rp['pro_badge_text_color'])) { $unified['families']['pro']['fg']    = (string) $rp['pro_badge_text_color']; }
            if (!empty($rp['pro_badge_tooltip']))    { $unified['families']['pro']['tooltip'] = (string) $rp['pro_badge_tooltip']; }
        }

        
        
        
        

        
        
        
        
        $arch_pos = class_exists('AIEO_DMM_Settings')
            ? (string) AIEO_DMM_Settings::get('archive_badge_position', 'image_top_left')
            : 'image_top_left';
        $arch_placement = ($arch_pos === 'below_favourite') ? 'below_favourite' : 'top_left_over_image';
        $unified['placements']['archive'] = $arch_placement;

        return $unified;
    }

    
    
    

    public static function sanitize(array $input) {
        $defaults = self::defaults();
        $out = $defaults;

        $out['version']        = self::SETTINGS_VERSION;
        $out['hide_wc_onsale'] = !empty($input['hide_wc_onsale']);

        $valid_families   = array_keys($defaults['families']);
        $valid_surfaces   = array('archive', 'pdp', 'recos', 'side_cart');
        $location_opts    = self::location_options();
        $shape_opts       = self::shape_options();

        
        
        
        
        $out['sizes'] = array();
        foreach ($valid_surfaces as $s) {
            $def_d = (int) $defaults['sizes'][$s]['desktop'];
            $def_m = (int) $defaults['sizes'][$s]['mobile'];
            $raw   = isset($input['sizes'][$s]) ? $input['sizes'][$s] : array();
            if (is_int($raw) || (is_string($raw) && ctype_digit($raw))) {
                
                $d = max(8, min(24, (int) $raw));
                $m = max(8, min(24, (int) round($d * 0.9)));
            } else {
                $d = isset($raw['desktop']) ? max(8, min(24, (int) $raw['desktop'])) : $def_d;
                $m = isset($raw['mobile'])  ? max(8, min(24, (int) $raw['mobile']))  : $def_m;
            }
            $out['sizes'][$s] = array('desktop' => $d, 'mobile' => $m);
        }

        
        
        
        $out['placements'] = array();
        foreach ($valid_surfaces as $s) {
            $raw_loc   = isset($input['placements'][$s]['location']) ? (string) $input['placements'][$s]['location'] : '';
            $raw_shape = isset($input['placements'][$s]['shape'])    ? (string) $input['placements'][$s]['shape']    : '';
            $out['placements'][$s] = array(
                'location' => isset($location_opts[$s][$raw_loc]) ? $raw_loc : self::default_location($s),
                'shape'    => isset($shape_opts[$raw_shape])      ? $raw_shape : self::default_shape(),
            );
        }

        $out['families'] = array();
        foreach ($valid_families as $key) {
            $src = isset($input['families'][$key]) && is_array($input['families'][$key])
                ? $input['families'][$key] : array();
            $def = $defaults['families'][$key];

            
            
            
            
            
            $img_id = isset($src['icon_image']) ? (int) $src['icon_image'] : 0;
            if ($img_id > 0) {
                $img_url = wp_get_attachment_url($img_id);
                $img_url = $img_url ? esc_url_raw($img_url) : '';
            } else {
                $img_id  = 0;
                $img_url = '';
            }

            $f = array(
                'enabled'        => !empty($src['enabled']),
                'label'          => isset($src['label']) ? sanitize_text_field((string) $src['label']) : $def['label'],
                'icon'           => isset($src['icon'])  ? sanitize_text_field((string) $src['icon'])  : $def['icon'],
                'icon_image'     => $img_id,
                'icon_image_url' => $img_url,
                'order'          => isset($src['order']) ? max(0, min(999, (int) $src['order'])) : $def['order'],
                'bg'             => isset($src['bg']) ? (sanitize_hex_color((string) $src['bg']) ?: $def['bg']) : $def['bg'],
                'fg'             => isset($src['fg']) ? (sanitize_hex_color((string) $src['fg']) ?: $def['fg']) : $def['fg'],
            );
            $f['surfaces'] = array();
            foreach ($valid_surfaces as $s) {
                $f['surfaces'][$s] = isset($src['surfaces'][$s]) ? !empty($src['surfaces'][$s]) : !empty($def['surfaces'][$s]);
            }
            
            if (isset($src['tooltip'])) {
                $f['tooltip'] = sanitize_text_field((string) $src['tooltip']);
            }
            $out['families'][$key] = $f;
        }
        return $out;
    }

    
    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $raw = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : array();
        if (!is_array($raw)) {
            
            $decoded = json_decode((string) $raw, true);
            $raw = is_array($decoded) ? $decoded : array();
        }
        $clean = self::sanitize($raw);
        update_option(self::OPTION_KEY, $clean, false);
        
        
        
        
        wp_send_json_success(array(
            'message'  => __('Badge settings saved.', 'ai-eshop-optimizer'),
            'settings' => $clean,
        ));
    }

    
    
    

    public function render_subtab() {
        $s     = self::get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');

        
        
        
        
        if (function_exists('wp_enqueue_media')) { wp_enqueue_media(); }

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Badges', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Single-source-of-truth admin for the SALE, monthly-offer, PRO (role), NEW, and free-gift badges. Drives the unified renderer and the storefront badge stacks.', 'ai-eshop-optimizer') . '</p>';

        echo '<div class="aieo-badges-form aieo-dmm-card" id="aieo-badges-form">';

        
        $surface_labels = array(
            'archive'   => __('Archive (shop loop)', 'ai-eshop-optimizer'),
            'pdp'       => __('PDP (single product)', 'ai-eshop-optimizer'),
            'recos'     => __('Recos (recommendation rails)', 'ai-eshop-optimizer'),
            'side_cart' => __('Side cart', 'ai-eshop-optimizer'),
        );

        
        echo '<table class="form-table">';

        
        
        
        
        
        
        
        $shape_opts = self::shape_options();
        echo '<tr><th>' . esc_html__('Placement per surface', 'ai-eshop-optimizer') . '</th><td>';
        echo '<table class="aieo-badges-placements" style="border-collapse:collapse;">';
        echo '<thead><tr style="text-align:left;font-size:11px;color:#646970;text-transform:uppercase;letter-spacing:0.04em;">';
        echo '<th style="padding:0 14px 4px 0;width:200px;font-weight:600;">' . esc_html__('Surface', 'ai-eshop-optimizer') . '</th>';
        echo '<th style="padding:0 14px 4px 0;font-weight:600;">' . esc_html__('Location', 'ai-eshop-optimizer') . '</th>';
        echo '<th style="padding:0 0 4px 0;font-weight:600;">' . esc_html__('Shape', 'ai-eshop-optimizer') . '</th>';
        echo '</tr></thead><tbody>';
        foreach (self::location_options() as $sk => $loc_opts) {
            $cur_loc   = isset($s['placements'][$sk]['location']) ? (string) $s['placements'][$sk]['location'] : self::default_location($sk);
            $cur_shape = isset($s['placements'][$sk]['shape'])    ? (string) $s['placements'][$sk]['shape']    : self::default_shape();
            echo '<tr style="border-bottom:1px solid #f0f0f1;">';
            echo '<td style="padding:6px 14px 6px 0;font-size:13px;color:#1d2327;">' . esc_html($surface_labels[$sk]) . '</td>';
            echo '<td style="padding:6px 14px 6px 0;">';
            echo '<select data-placement-surface="' . esc_attr($sk) . '" data-placement-field="location" class="aieo-badges-placement-location">';
            foreach ($loc_opts as $slug => $label) {
                echo '<option value="' . esc_attr($slug) . '"' . selected($cur_loc, $slug, false) . '>' . esc_html($label) . '</option>';
            }
            echo '</select>';
            echo '</td>';
            echo '<td style="padding:6px 0;">';
            echo '<select data-placement-surface="' . esc_attr($sk) . '" data-placement-field="shape" class="aieo-badges-placement-shape">';
            foreach ($shape_opts as $slug => $label) {
                echo '<option value="' . esc_attr($slug) . '"' . selected($cur_shape, $slug, false) . '>' . esc_html($label) . '</option>';
            }
            echo '</select>';
            echo '</td></tr>';
        }
        echo '</tbody></table>';
        echo '<p class="description">' . esc_html__('Location is where the stack sits on each surface; Shape is the visual style of each chip. Combinations like "below favourite + chip" or "inline + circle" are supported. See the design-ownership doc for the CSS hooks.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Hide WooCommerce native sale flash', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="hide_wc_onsale" ' . checked(!empty($s['hide_wc_onsale']), true, false) . '> ' . esc_html__('Replace WooCommerce\'s built-in .onsale badge with our SALE family', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';

        
        
        
        
        
        echo '<tr><th>' . esc_html__('Badge size per surface (px)', 'ai-eshop-optimizer') . '</th><td>';
        echo '<table class="aieo-badges-sizes" style="border-collapse:collapse;">';
        echo '<thead><tr style="text-align:left;font-size:11px;color:#646970;text-transform:uppercase;letter-spacing:0.04em;">';
        echo '<th style="padding:0 14px 4px 0;width:200px;font-weight:600;">' . esc_html__('Surface', 'ai-eshop-optimizer') . '</th>';
        echo '<th style="padding:0 14px 4px 0;font-weight:600;">' . esc_html__('Desktop', 'ai-eshop-optimizer') . '</th>';
        echo '<th style="padding:0 0 4px 0;font-weight:600;">' . esc_html__('Mobile (≤600px)', 'ai-eshop-optimizer') . '</th>';
        echo '</tr></thead><tbody>';
        foreach ($surface_labels as $sk => $sl) {
            $d = isset($s['sizes'][$sk]['desktop']) ? (int) $s['sizes'][$sk]['desktop'] : 11;
            $m = isset($s['sizes'][$sk]['mobile'])  ? (int) $s['sizes'][$sk]['mobile']  : 10;
            echo '<tr style="border-bottom:1px solid #f0f0f1;">';
            echo '<td style="padding:6px 14px 6px 0;font-size:13px;color:#1d2327;">' . esc_html($sl) . '</td>';
            echo '<td style="padding:6px 14px 6px 0;">';
            echo '<input type="number" min="8" max="24" step="1" value="' . esc_attr($d) . '" data-size-surface="' . esc_attr($sk) . '" data-size-bp="desktop" class="aieo-badges-size small-text" style="width:64px;">';
            echo '</td>';
            echo '<td style="padding:6px 0;">';
            echo '<input type="number" min="8" max="24" step="1" value="' . esc_attr($m) . '" data-size-surface="' . esc_attr($sk) . '" data-size-bp="mobile" class="aieo-badges-size small-text" style="width:64px;">';
            echo '</td></tr>';
        }
        echo '</tbody></table>';
        echo '<p class="description">' . esc_html__('Mobile sizes apply at viewport width ≤ 600px; desktop sizes apply above. Padding/border-radius scale with the active size.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';

        echo '</table>';

        echo '<h3>' . esc_html__('Badge families', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="widefat striped aieo-badges-families">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Family', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Enabled', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Icon', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Image (overrides icon + label)', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Label', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Tooltip', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('BG', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('FG', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Order', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Surfaces', 'ai-eshop-optimizer') . '</th>';
        echo '</tr></thead><tbody>';

        $family_labels = array(
            'sale'          => __('SALE', 'ai-eshop-optimizer'),
            'monthly_offer' => __('Monthly offer', 'ai-eshop-optimizer'),
            'pro'           => __('PRO (role price)', 'ai-eshop-optimizer'),
            'new'           => __('NEW', 'ai-eshop-optimizer'),
            'gift'          => __('Free gift', 'ai-eshop-optimizer'),
        );
        foreach ($s['families'] as $key => $f) {
            $name_prefix  = "families[{$key}]";
            $css_class    = '.aieo-badge--' . $key;
            $surfaces_html = '';
            foreach (array('archive', 'pdp', 'recos', 'side_cart') as $surface) {
                $surfaces_html .= '<label style="margin-right:10px;font-size:12px;"><input type="checkbox" data-family="' . esc_attr($key) . '" data-surface="' . esc_attr($surface) . '" ' . checked(!empty($f['surfaces'][$surface]), true, false) . '> ' . esc_html(ucwords(str_replace('_', ' ', $surface))) . '</label>';
            }
            echo '<tr data-family="' . esc_attr($key) . '">';
            echo '<td><strong>' . esc_html(isset($family_labels[$key]) ? $family_labels[$key] : $key) . '</strong>'
               . '<br><code style="font-size:11px;color:#646970;">' . esc_html($css_class) . '</code></td>';
            echo '<td><input type="checkbox" class="aieo-badges-enabled" ' . checked(!empty($f['enabled']), true, false) . '></td>';
            echo '<td><input type="text" class="aieo-badges-icon" value="' . esc_attr((string) ($f['icon'] ?? '')) . '" maxlength="8" style="width:60px;text-align:center;font-size:16px;"></td>';
            
            $img_id  = (int) ($f['icon_image'] ?? 0);
            $img_url = (string) ($f['icon_image_url'] ?? '');
            echo '<td>';
            echo '<div class="aieo-badges-image-cell" style="display:flex;align-items:center;gap:6px;">';
            echo '<span class="aieo-badges-image-preview" style="display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border:1px solid #dcdcde;border-radius:4px;background:#f6f7f7;overflow:hidden;">';
            if ($img_url !== '') {
                echo '<img src="' . esc_url($img_url) . '" alt="" style="max-width:100%;max-height:100%;display:block;">';
            } else {
                echo '<span style="color:#a7aaad;font-size:18px;line-height:1;">∅</span>';
            }
            echo '</span>';
            echo '<input type="hidden" class="aieo-badges-image-id"  value="' . esc_attr((string) $img_id)  . '">';
            echo '<input type="hidden" class="aieo-badges-image-url" value="' . esc_attr($img_url)         . '">';
            echo '<button type="button" class="button button-small aieo-badges-image-pick">' . esc_html__('Pick', 'ai-eshop-optimizer') . '</button>';
            echo '<button type="button" class="button-link aieo-badges-image-clear" style="color:#b91c1c;font-size:11px;' . ($img_id ? '' : 'display:none;') . '">' . esc_html__('Remove', 'ai-eshop-optimizer') . '</button>';
            echo '</div>';
            echo '</td>';
            echo '<td><input type="text" class="aieo-badges-label regular-text" value="' . esc_attr((string) $f['label']) . '"></td>';
            echo '<td><input type="text" class="aieo-badges-tooltip regular-text" value="' . esc_attr((string) ($f['tooltip'] ?? '')) . '"></td>';
            echo '<td><input type="color" class="aieo-badges-bg" value="' . esc_attr((string) $f['bg']) . '"></td>';
            echo '<td><input type="color" class="aieo-badges-fg" value="' . esc_attr((string) $f['fg']) . '"></td>';
            echo '<td><input type="number" class="aieo-badges-order small-text" value="' . (int) $f['order'] . '"></td>';
            echo '<td>' . $surfaces_html . '</td>'; 
            echo '</tr>';
        }
        echo '</tbody></table>';

        
        
        echo '<details style="margin-top:12px;background:#f6f7f7;border:1px solid #dcdcde;border-radius:4px;padding:10px 14px;">';
        echo '<summary style="cursor:pointer;font-weight:600;">' . esc_html__('CSS classes for theme customisation', 'ai-eshop-optimizer') . '</summary>';
        echo '<p class="description" style="margin-top:8px;">' . esc_html__('Each badge emits these classes — drop overrides into your theme stylesheet to fine-tune fonts, sizing, shadows, etc.', 'ai-eshop-optimizer') . '</p>';
        echo '<pre style="font-size:12px;background:#fff;padding:10px;border-radius:3px;">';
        echo "/* Container — surface targeting */\n";
        echo ".aieo-badge-stack { /* all surfaces */ }\n";
        echo ".aieo-badge-stack[data-surface=\"archive\"]   { /* shop loop */ }\n";
        echo ".aieo-badge-stack[data-surface=\"pdp\"]       { /* single product */ }\n";
        echo ".aieo-badge-stack[data-surface=\"recos\"]     { /* recommendation rails */ }\n";
        echo ".aieo-badge-stack[data-surface=\"side_cart\"] { /* side-cart cards */ }\n";
        echo "\n/* Individual badges */\n";
        echo ".aieo-badge { /* base styling for every badge */ }\n";
        echo ".aieo-badge--sale, .aieo-badge--monthly_offer,\n";
        echo ".aieo-badge--pro, .aieo-badge--new, .aieo-badge--gift { /* per-family */ }\n";
        echo ".aieo-badge__icon  { /* the icon span */ }\n";
        echo ".aieo-badge__label { /* the label span */ }\n";
        echo '</pre></details>';

        echo '<p style="margin-top:16px;">';
        echo '<button type="button" class="button button-primary" id="aieo-badges-save">' . esc_html__('Save badge settings', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-badges-status" style="margin-left:10px;color:#646970;font-size:13px;"></span>';
        echo '</p>';

        echo '</div>'; 

        
        
        
        ?>
        <script>(function(){
            var form = document.getElementById('aieo-badges-form');
            var btn = document.getElementById('aieo-badges-save');
            var status = document.getElementById('aieo-badges-status');
            if (!btn) return;

            // ── Image picker — wp.media() per family row ─────────────
            // Single shared frame per row so re-opens reuse the same
            // dialog state. Selecting an image copies attachment.id +
            // attachment.url back into the row's hidden inputs and
            // refreshes the inline preview.
            form.querySelectorAll('tr[data-family]').forEach(function(tr){
                var pickBtn   = tr.querySelector('.aieo-badges-image-pick');
                var clearBtn  = tr.querySelector('.aieo-badges-image-clear');
                var idInput   = tr.querySelector('.aieo-badges-image-id');
                var urlInput  = tr.querySelector('.aieo-badges-image-url');
                var preview   = tr.querySelector('.aieo-badges-image-preview');
                if (!pickBtn || !idInput || !urlInput || !preview) return;
                var frame = null;
                pickBtn.addEventListener('click', function(){
                    if (!window.wp || !window.wp.media) return;
                    if (!frame) {
                        frame = wp.media({
                            title: '<?php echo esc_js(__('Pick badge image', 'ai-eshop-optimizer')); ?>',
                            button: { text: '<?php echo esc_js(__('Use this image', 'ai-eshop-optimizer')); ?>' },
                            multiple: false,
                            library: { type: ['image'] }
                        });
                        frame.on('select', function(){
                            var att = frame.state().get('selection').first().toJSON();
                            idInput.value  = att.id || 0;
                            urlInput.value = att.url || '';
                            preview.innerHTML = '<img src="' + att.url + '" alt="" style="max-width:100%;max-height:100%;display:block;">';
                            if (clearBtn) clearBtn.style.display = '';
                        });
                    }
                    frame.open();
                });
                if (clearBtn) {
                    clearBtn.addEventListener('click', function(){
                        idInput.value  = '';
                        urlInput.value = '';
                        preview.innerHTML = '<span style="color:#a7aaad;font-size:18px;line-height:1;">∅</span>';
                        clearBtn.style.display = 'none';
                    });
                }
            });

            function collect() {
                // Sizes are nested per surface × breakpoint.
                var sizes = {};
                form.querySelectorAll('input[data-size-surface]').forEach(function(inp){
                    var surface = inp.getAttribute('data-size-surface');
                    var bp      = inp.getAttribute('data-size-bp') || 'desktop';
                    if (!sizes[surface]) { sizes[surface] = {}; }
                    sizes[surface][bp] = parseInt(inp.value, 10) || 0;
                });
                // Placements are nested per surface × {location, shape}.
                var placements = {};
                form.querySelectorAll('select[data-placement-surface]').forEach(function(sel){
                    var surface = sel.getAttribute('data-placement-surface');
                    var field   = sel.getAttribute('data-placement-field') || 'location';
                    if (!placements[surface]) { placements[surface] = {}; }
                    placements[surface][field] = sel.value;
                });
                var out = {
                    placements:     placements,
                    hide_wc_onsale: form.querySelector('input[name="hide_wc_onsale"]').checked,
                    sizes:          sizes,
                    families:       {}
                };
                form.querySelectorAll('tr[data-family]').forEach(function(tr){
                    var key = tr.getAttribute('data-family');
                    var surfaces = {};
                    tr.querySelectorAll('input[data-surface]').forEach(function(cb){
                        surfaces[cb.getAttribute('data-surface')] = cb.checked;
                    });
                    var iconEl    = tr.querySelector('.aieo-badges-icon');
                    var tooltipEl = tr.querySelector('.aieo-badges-tooltip');
                    var imgIdEl   = tr.querySelector('.aieo-badges-image-id');
                    var imgUrlEl  = tr.querySelector('.aieo-badges-image-url');
                    out.families[key] = {
                        enabled:        tr.querySelector('.aieo-badges-enabled').checked,
                        icon:           iconEl ? iconEl.value : '',
                        icon_image:     imgIdEl  ? (parseInt(imgIdEl.value, 10) || 0) : 0,
                        icon_image_url: imgUrlEl ? (imgUrlEl.value || '') : '',
                        label:          tr.querySelector('.aieo-badges-label').value,
                        tooltip:        tooltipEl ? tooltipEl.value : '',
                        bg:             tr.querySelector('.aieo-badges-bg').value,
                        fg:             tr.querySelector('.aieo-badges-fg').value,
                        order:          parseInt(tr.querySelector('.aieo-badges-order').value, 10) || 0,
                        surfaces:       surfaces
                    };
                });
                return out;
            }

            btn.addEventListener('click', function(){
                status.style.color = '#646970';
                status.textContent = '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                var fd = new FormData();
                fd.set('action', 'aieo_dmm_badges_save');
                fd.set('nonce',  '<?php echo esc_js($nonce); ?>');
                fd.set('settings', JSON.stringify(collect()));
                fetch('<?php echo esc_js($ajax); ?>', {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: fd
                }).then(function(r){return r.json();}).then(function(j){
                    if (j && j.success) {
                        status.style.color = '#15803d';
                        status.textContent = j.data.message;
                    } else {
                        status.style.color = '#b91c1c';
                        status.textContent = (j && j.data && j.data.message) || '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';
                    }
                }).catch(function(){
                    status.style.color = '#b91c1c';
                    status.textContent = '<?php echo esc_js(__('Network error.', 'ai-eshop-optimizer')); ?>';
                });
            });
        })();</script>
        <?php

        echo '</div>'; 
    }
}
