<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) return;

$is_licensed = cdtv_is_licensed();

// All tables for the dropdown
$all_tables = get_posts( array(
    'post_type'      => 'cdtv_table',
    'posts_per_page' => -1,
    'post_status'    => 'publish',
    'orderby'        => 'title',
    'order'          => 'ASC',
) );

// Global design defaults
$design     = get_option( 'cdtv_global_design', array() );
$hdr_bg     = $design['hdr_bg']     ?? '#2271b1';
$hdr_color  = $design['hdr_color']  ?? '#ffffff';
$hdr_size   = (int) ( $design['hdr_size']  ?? 14 );
$hdr_bold   = ! empty( $design['hdr_bold'] );
$row_bg     = $design['row_bg']     ?? '#ffffff';
$row_color  = $design['row_color']  ?? '#333333';
$row_stripe = $design['row_stripe'] ?? '#f7f9fc';
$row_hover  = $design['row_hover']  ?? '#eaf3fb';
$row_height = (int) ( $design['row_height'] ?? 36 );
$bdr_style  = $design['bdr_style']  ?? 'all';
$bdr_color  = $design['bdr_color']  ?? '#dddddd';
$bdr_width  = (int) ( $design['bdr_width']  ?? 1 );
?>
<div class="wrap cdtv-wrap">
    <h1><?php esc_html_e( 'Design Generator', 'codede-table-viewer' ); ?></h1>

    <?php if ( ! $is_licensed ) : ?>
    <!-- ── LOCKED (Lite) ──────────────────────────────────────────────── -->
    <div class="cdtv-pro-notice">
        <span class="cdtv-pro-notice-icon">🔒</span>
        <div class="cdtv-pro-notice-text">
            <strong><?php esc_html_e( 'Pro Feature', 'codede-table-viewer' ); ?></strong> —
            <?php esc_html_e( 'The Design Generator is available in the Pro version.', 'codede-table-viewer' ); ?>
        </div>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=cdtv-upgrade' ) ); ?>" class="button button-primary cdtv-pro-notice-btn">
            ⭐ <?php esc_html_e( 'Get Pro', 'codede-table-viewer' ); ?>
        </a>
    </div>
    <div class="cdtv-design-locked-wrap">
        <div class="cdtv-design-overlay">
            <div class="cdtv-design-overlay-inner">
                <span class="cdtv-lock-icon">🔒</span>
                <h2><?php esc_html_e( 'Design Generator — Pro Feature', 'codede-table-viewer' ); ?></h2>
                <p><?php esc_html_e( 'Customize colors, fonts, borders and layout with a live preview. Available in the Pro version.', 'codede-table-viewer' ); ?></p>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=cdtv-upgrade' ) ); ?>" class="button button-primary button-hero">
                    ⭐ <?php esc_html_e( 'Upgrade to Pro', 'codede-table-viewer' ); ?>
                </a>
            </div>
        </div>
        <div class="cdtv-design-preview-ui" aria-hidden="true">
            <div class="cdtv-design-layout" style="filter:blur(3px);pointer-events:none;"></div>
        </div>
    </div>

    <?php else : ?>
    <!-- ── UNLOCKED (Pro) ─────────────────────────────────────────────── -->

    <!-- Mode Switcher -->
    <div class="cdtv-dg-mode-bar">
        <label class="cdtv-dg-mode-option">
            <input type="radio" name="cdtv_dg_mode" id="dg-mode-global" value="global" checked>
            <span><?php esc_html_e( '🌐 Global — all tables', 'codede-table-viewer' ); ?></span>
        </label>
        <label class="cdtv-dg-mode-option">
            <input type="radio" name="cdtv_dg_mode" id="dg-mode-table" value="table">
            <span><?php esc_html_e( '📋 Per table:', 'codede-table-viewer' ); ?></span>
        </label>
        <select id="dg-table-select" disabled>
            <option value=""><?php esc_html_e( '— Select a table —', 'codede-table-viewer' ); ?></option>
            <?php foreach ( $all_tables as $t ) : ?>
            <option value="<?php echo esc_attr( $t->ID ); ?>"><?php echo esc_html( $t->post_title ); ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <!-- Save feedback toast (shown by JS) -->
    <div id="cdtv-design-save-msg" style="display:none;" class="notice is-dismissible"><p></p></div>

    <!-- Per-table extra options (search / sort / filters / pagination) -->
    <div id="dg-table-options" style="display:none;" class="cdtv-dg-table-options">
        <h3><?php esc_html_e( 'Table Features', 'codede-table-viewer' ); ?></h3>
        <label class="cdtv-toggle-label">
            <input type="checkbox" id="dg-enable-search">
            <span><?php esc_html_e( 'Show live search field', 'codede-table-viewer' ); ?></span>
        </label>
        &nbsp;&nbsp;
        <label class="cdtv-toggle-label">
            <input type="checkbox" id="dg-enable-sort">
            <span><?php esc_html_e( 'Make columns sortable', 'codede-table-viewer' ); ?></span>
        </label>
        <div id="dg-sort-style-wrap" style="display:none;margin-top:10px;margin-left:2px;">
            <span style="font-weight:600;font-size:12px;"><?php esc_html_e( 'Sort indicator style:', 'codede-table-viewer' ); ?></span>
            <div style="display:flex;gap:8px;margin-top:6px;flex-wrap:wrap;">
                <?php
                // Previews render on a blue header swatch so they match the actual frontend appearance.
                $sort_styles = array(
                    'badge'   => array( 'label' => __( 'Badge',   'codede-table-viewer' ), 'preview' => '<span style="display:inline-block;background:#2271b1;padding:3px 6px;border-radius:3px;"><span style="display:inline-flex;align-items:center;justify-content:center;padding:1px 5px 2px;background:rgba(255,255,255,0.22);border:1px solid rgba(255,255,255,0.5);border-radius:3px;font-size:9px;color:#fff;line-height:1.2;">▲▼</span></span>' ),
                    'outline' => array( 'label' => __( 'Outline', 'codede-table-viewer' ), 'preview' => '<span style="display:inline-block;background:#2271b1;padding:3px 6px;border-radius:3px;"><span style="display:inline-flex;align-items:center;justify-content:center;padding:1px 5px 2px;background:transparent;border:1px solid rgba(255,255,255,0.5);border-radius:3px;font-size:9px;color:#fff;line-height:1.2;">▲▼</span></span>' ),
                    'text'    => array( 'label' => __( 'Text',    'codede-table-viewer' ), 'preview' => '<span style="display:inline-block;background:#2271b1;padding:3px 6px;border-radius:3px;"><span style="font-size:11px;color:rgba(255,255,255,0.75);">▲▼</span></span>' ),
                    'none'    => array( 'label' => __( 'None',    'codede-table-viewer' ), 'preview' => '<span style="display:inline-block;background:#2271b1;padding:3px 8px;border-radius:3px;font-size:11px;color:rgba(255,255,255,0.4);">—</span>' ),
                );
                foreach ( $sort_styles as $val => $info ) :
                ?>
                <label class="cdtv-ind-style-btn" style="display:flex;flex-direction:column;align-items:center;gap:4px;cursor:pointer;padding:6px 10px;border:2px solid #ddd;border-radius:6px;background:#fff;min-width:58px;text-align:center;transition:border-color 0.15s;">
                    <input type="radio" name="dg_sort_indicator_style" id="dg-sort-style-<?php echo esc_attr( $val ); ?>" value="<?php echo esc_attr( $val ); ?>" style="position:absolute;opacity:0;pointer-events:none;">
                    <span><?php echo $info['preview']; // phpcs:ignore -- trusted HTML ?></span>
                    <span style="font-size:11px;color:#444;"><?php echo esc_html( $info['label'] ); ?></span>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        &nbsp;&nbsp;
        <label class="cdtv-toggle-label">
            <input type="checkbox" id="dg-enable-excel-format">
            <span><?php esc_html_e( 'Apply Excel cell formatting (colors, fonts)', 'codede-table-viewer' ); ?></span>
        </label>
        <hr>
        <div style="margin-top:10px;">
            <label style="font-weight:600;"><?php esc_html_e( 'Rows per page', 'codede-table-viewer' ); ?></label>
            <select id="dg-rows-per-page" style="margin-left:10px;">
                <?php foreach ( array( 0 => __( 'Show all', 'codede-table-viewer' ), 5 => '5', 10 => '10', 15 => '15', 20 => '20', 25 => '25', 50 => '50', 100 => '100' ) as $val => $label ) : ?>
                <option value="<?php echo esc_attr( $val ); ?>"><?php echo esc_html( $label ); ?></option>
                <?php endforeach; ?>
            </select>
            <p class="description" style="margin-top:4px;"><?php esc_html_e( 'Show pagination when the table exceeds this number of rows. "Show all" disables pagination.', 'codede-table-viewer' ); ?></p>
        </div>
        <hr>
        <div id="dg-filter-section" style="margin-top:12px;">
            <strong><?php esc_html_e('Column Filters', 'codede-table-viewer'); ?></strong>
            <p class="description" style="margin:4px 0 8px;"><?php esc_html_e('Select which columns show a filter dropdown in the frontend.', 'codede-table-viewer'); ?></p>
            <div id="dg-filter-cols-wrap" class="cdtv-filter-col-picker">
                <em><?php esc_html_e('Select a table to configure column filters.', 'codede-table-viewer'); ?></em>
            </div>
        </div>
    </div>

    <!-- Design Layout -->
    <div class="cdtv-design-layout">

        <!-- Left: Controls -->
        <div class="cdtv-design-controls">
            <h3><?php esc_html_e( 'Header Row', 'codede-table-viewer' ); ?></h3>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Background', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-hdr-bg" value="<?php echo esc_attr( $hdr_bg ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Text Color', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-hdr-color" value="<?php echo esc_attr( $hdr_color ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Font Size (px)', 'codede-table-viewer' ); ?></label>
                <input type="number" id="dg-hdr-size" value="<?php echo esc_attr( $hdr_size ); ?>" min="8" max="36" style="width:64px;">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Bold', 'codede-table-viewer' ); ?></label>
                <input type="checkbox" id="dg-hdr-bold" <?php checked( $hdr_bold ); ?>>
            </div>
            <hr>
            <h3><?php esc_html_e( 'Data Rows', 'codede-table-viewer' ); ?></h3>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Background', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-row-bg" value="<?php echo esc_attr( $row_bg ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Text Color', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-row-color" value="<?php echo esc_attr( $row_color ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Stripe Color', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-row-stripe" value="<?php echo esc_attr( $row_stripe ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Hover Color', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-row-hover" value="<?php echo esc_attr( $row_hover ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Row Height (px)', 'codede-table-viewer' ); ?></label>
                <input type="number" id="dg-row-height" value="<?php echo esc_attr( $row_height ); ?>" min="20" max="120" style="width:64px;">
            </div>
            <hr>
            <h3><?php esc_html_e( 'Borders', 'codede-table-viewer' ); ?></h3>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Style', 'codede-table-viewer' ); ?></label>
                <select id="dg-bdr-style">
                    <option value="all"   <?php selected( $bdr_style, 'all' ); ?>><?php esc_html_e( 'All borders',  'codede-table-viewer' ); ?></option>
                    <option value="outer" <?php selected( $bdr_style, 'outer' ); ?>><?php esc_html_e( 'Outer only', 'codede-table-viewer' ); ?></option>
                    <option value="none"  <?php selected( $bdr_style, 'none' ); ?>><?php esc_html_e( 'None',        'codede-table-viewer' ); ?></option>
                </select>
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Color', 'codede-table-viewer' ); ?></label>
                <input type="color" id="dg-bdr-color" value="<?php echo esc_attr( $bdr_color ); ?>">
            </div>
            <div class="cdtv-design-row">
                <label><?php esc_html_e( 'Width (px)', 'codede-table-viewer' ); ?></label>
                <input type="number" id="dg-bdr-width" value="<?php echo esc_attr( $bdr_width ); ?>" min="1" max="5" style="width:64px;">
            </div>
            <hr>
            <div class="cdtv-design-actions">
                <button class="button button-primary" id="dg-save"><?php esc_html_e( 'Save Design', 'codede-table-viewer' ); ?></button>
                <button class="button" id="dg-reset"><?php esc_html_e( 'Reset to Default', 'codede-table-viewer' ); ?></button>
            </div>
        </div><!-- .cdtv-design-controls -->

        <!-- Right: Live Preview -->
        <div class="cdtv-design-preview-col">
            <h3><?php esc_html_e( 'Live Preview', 'codede-table-viewer' ); ?></h3>
            <style id="dg-preview-style"></style>
            <table class="cdtv-table cdtv-preview-table" id="dg-preview-table">
                <thead><tr>
                    <th><?php esc_html_e( 'Product',  'codede-table-viewer' ); ?></th>
                    <th><?php esc_html_e( 'Category', 'codede-table-viewer' ); ?></th>
                    <th><?php esc_html_e( 'Price',    'codede-table-viewer' ); ?></th>
                    <th><?php esc_html_e( 'Stock',    'codede-table-viewer' ); ?></th>
                </tr></thead>
                <tbody>
                    <tr><td>Widget A</td><td>Tools</td><td>€ 24.99</td><td>142</td></tr>
                    <tr><td>Widget B</td><td>Parts</td><td>€ 9.50</td><td>88</td></tr>
                    <tr><td>Widget C</td><td>Tools</td><td>€ 49.00</td><td>5</td></tr>
                    <tr><td>Widget D</td><td>Parts</td><td>€ 14.75</td><td>230</td></tr>
                    <tr><td>Widget E</td><td>Accessories</td><td>€ 3.99</td><td>512</td></tr>
                </tbody>
            </table>
        </div>

    </div><!-- .cdtv-design-layout -->

    <script>
    (function($){
        var nonce   = '<?php echo esc_js( wp_create_nonce( 'cdtv_admin_nonce' ) ); ?>';
        var DEFAULTS = {
            hdrBg:'#2271b1', hdrColor:'#ffffff', hdrSize:14, hdrBold:false,
            rowBg:'#ffffff', rowColor:'#333333', rowStripe:'#f7f9fc', rowHover:'#eaf3fb', rowHeight:36,
            bdrStyle:'all', bdrColor:'#dddddd', bdrWidth:1
        };

        // ── CSS builder ──────────────────────────────────────────────────
        function buildCSS(scope) {
            var s = scope || '.cdtv-table-wrap table.cdtv-table';
            var hdrBg     = $('#dg-hdr-bg').val();
            var hdrColor  = $('#dg-hdr-color').val();
            var hdrSize   = parseInt($('#dg-hdr-size').val(),10)||14;
            var hdrBold   = $('#dg-hdr-bold').is(':checked') ? 'bold' : 'normal';
            var rowBg     = $('#dg-row-bg').val();
            var rowColor  = $('#dg-row-color').val();
            var rowStripe = $('#dg-row-stripe').val();
            var rowHover  = $('#dg-row-hover').val();
            var rowHeight = parseInt($('#dg-row-height').val(),10)||36;
            var bdrStyle  = $('#dg-bdr-style').val();
            var bdrColor  = $('#dg-bdr-color').val();
            var bdrWidth  = parseInt($('#dg-bdr-width').val(),10)||1;
            var bdrRule   = bdrWidth + 'px solid ' + bdrColor;
            // Borders: target both th and td
            var bdrCSS    = bdrStyle==='all'   ? s+' thead th,'+s+' tbody td{border:'+bdrRule+';}' :
                            bdrStyle==='outer' ? s+'{border:'+bdrRule+';}' : '';
            return [
                s+' thead th{background-color:'+hdrBg+';color:'+hdrColor+';font-size:'+hdrSize+'px;font-weight:'+hdrBold+';}',
                s+' tbody td{background-color:'+rowBg+';color:'+rowColor+';min-height:'+rowHeight+'px;}',
                s+' tbody tr:nth-child(even) td{background-color:'+rowStripe+';}',
                s+' tbody tr:hover td{background-color:'+rowHover+';}',
                s+'{border-collapse:collapse;}',
                bdrCSS
            ].join('\n');
        }

        function applyPreview() {
            $('#dg-preview-style').text( buildCSS('#dg-preview-table') );
        }

        // ── Apply values from object ──────────────────────────────────────
        function applyValues(v) {
            $('#dg-hdr-bg').val(v.hdrBg||DEFAULTS.hdrBg);
            $('#dg-hdr-color').val(v.hdrColor||DEFAULTS.hdrColor);
            $('#dg-hdr-size').val(v.hdrSize||DEFAULTS.hdrSize);
            $('#dg-hdr-bold').prop('checked', !!v.hdrBold);
            $('#dg-row-bg').val(v.rowBg||DEFAULTS.rowBg);
            $('#dg-row-color').val(v.rowColor||DEFAULTS.rowColor);
            $('#dg-row-stripe').val(v.rowStripe||DEFAULTS.rowStripe);
            $('#dg-row-hover').val(v.rowHover||DEFAULTS.rowHover);
            $('#dg-row-height').val(v.rowHeight||DEFAULTS.rowHeight);
            $('#dg-bdr-style').val(v.bdrStyle||DEFAULTS.bdrStyle);
            $('#dg-bdr-color').val(v.bdrColor||DEFAULTS.bdrColor);
            $('#dg-bdr-width').val(v.bdrWidth||DEFAULTS.bdrWidth);
            applyPreview();
        }

        // ── Sort-style picker: highlight active card ─────────────────────
        function setSortStyleUI(val) {
            $('input[name="dg_sort_indicator_style"]').each(function() {
                $(this).prop('checked', $(this).val() === val);
                $(this).closest('.cdtv-ind-style-btn').css('border-color', $(this).val() === val ? '#2271b1' : '#ddd');
            });
        }
        $(document).on('click', '.cdtv-ind-style-btn', function() {
            var val = $(this).find('input[type=radio]').val();
            setSortStyleUI(val);
            updatePreviewFeatures();
        });

        // ── Mode switch ───────────────────────────────────────────────────
        $('input[name="cdtv_dg_mode"]').on('change', function(){
            var isTable = $(this).val() === 'table';
            $('#dg-table-select').prop('disabled', !isTable);
            if (!isTable) {
                $('#dg-table-options').hide();
                applyValues(DEFAULTS); // Reset to global defaults on switch back
                updatePreviewFeatures(); // Clear sort/filter hints from preview
            }
        });

        // ── Table select ──────────────────────────────────────────────────
        $('#dg-table-select').on('change', function(){
            var tid = $(this).val();
            if (!tid) { $('#dg-table-options').hide(); updatePreviewFeatures(); return; }

            $.post(ajaxurl, { action:'cdtv_get_table_design', nonce:nonce, table_id:tid }, function(res){
                if (!res.success) return;
                var d = res.data;
                $('#dg-table-options').show();
                $('#dg-enable-search').prop('checked',       !!d.enable_search);
                $('#dg-enable-sort').prop('checked',         !!d.enable_sort);
                $('#dg-enable-excel-format').prop('checked', !!d.enable_excel_format);
                $('#dg-rows-per-page').val( d.rows_per_page || 0 );
                // Sort style: show picker only when sort is enabled
                if (d.enable_sort) {
                    $('#dg-sort-style-wrap').show();
                    setSortStyleUI(d.sort_indicator_style || 'badge');
                } else {
                    $('#dg-sort-style-wrap').hide();
                }

                // Render column filter checkboxes
                var filterColsActive = d.filter_cols ? d.filter_cols.split(',').filter(function(x){return x!=='';}).map(Number) : [];
                var $fcw = $('#dg-filter-cols-wrap');
                if (d.headers && d.headers.length) {
                    var html = '';
                    d.headers.forEach(function(hdr, idx) {
                        var checked = filterColsActive.indexOf(idx) !== -1 ? 'checked' : '';
                        html += '<label class="cdtv-filter-col-item">';
                        html += '<input type="checkbox" class="cdtv-filter-col-cb" value="' + idx + '" ' + checked + '> ';
                        html += $('<span>').text(hdr).html();
                        html += '</label> ';
                    });
                    $fcw.html(html);
                } else {
                    $fcw.html('<em>No columns found.</em>');
                }

                // Load saved design values, fall back to DEFAULTS if none saved yet
                var vals = DEFAULTS;
                if (d.design && d.design.hdr_bg) {
                    vals = {
                        hdrBg:     d.design.hdr_bg     || DEFAULTS.hdrBg,
                        hdrColor:  d.design.hdr_color  || DEFAULTS.hdrColor,
                        hdrSize:   d.design.hdr_size   || DEFAULTS.hdrSize,
                        hdrBold:   !!d.design.hdr_bold,
                        rowBg:     d.design.row_bg     || DEFAULTS.rowBg,
                        rowColor:  d.design.row_color  || DEFAULTS.rowColor,
                        rowStripe: d.design.row_stripe || DEFAULTS.rowStripe,
                        rowHover:  d.design.row_hover  || DEFAULTS.rowHover,
                        rowHeight: d.design.row_height || DEFAULTS.rowHeight,
                        bdrStyle:  d.design.bdr_style  || DEFAULTS.bdrStyle,
                        bdrColor:  d.design.bdr_color  || DEFAULTS.bdrColor,
                        bdrWidth:  d.design.bdr_width  || DEFAULTS.bdrWidth
                    };
                }
                applyValues(vals);

                // Update sort/filter indicators in preview after loading table settings
                updatePreviewFeatures();
            });
        });

        // ── React to sort / search / filter-col checkbox changes ──────────
        $('#dg-table-options').on('change', '#dg-enable-sort, #dg-enable-search, .cdtv-filter-col-cb', function(){
            if ($(this).is('#dg-enable-sort')) {
                if ($(this).is(':checked')) {
                    $('#dg-sort-style-wrap').show();
                } else {
                    $('#dg-sort-style-wrap').hide();
                }
            }
            updatePreviewFeatures();
        });

        // ── Live preview: sort + filter indicators ────────────────────────
        function updatePreviewFeatures() {
            var sortOn     = $('#dg-enable-sort').is(':checked');
            var sortStyle  = $('input[name="dg_sort_indicator_style"]:checked').val() || 'badge';
            var $ths       = $('#dg-preview-table thead th');

            // Collect active filter col indices from checkboxes
            var filterCols = [];
            $('.cdtv-filter-col-cb:checked').each(function() {
                filterCols.push(parseInt($(this).val(), 10));
            });

            // Sort indicator HTML per style
            var sortHintHTML = '';
            // Two spans mirror the frontend: badge stays same width, each arrow at 55% opacity.
            var arrowContent = '<span style="opacity:0.55;line-height:1;">▲</span><span style="opacity:0.55;line-height:1;">▼</span>';
            if (sortOn && sortStyle !== 'none') {
                if (sortStyle === 'badge') {
                    sortHintHTML = '<span class="dg-sort-hint" style="display:inline-flex;align-items:center;justify-content:center;vertical-align:middle;margin-left:5px;padding:1px 5px 2px;background:rgba(255,255,255,0.22);border:1px solid rgba(255,255,255,0.5);border-radius:3px;font-size:9px;line-height:1.2;">' + arrowContent + '</span>';
                } else if (sortStyle === 'outline') {
                    sortHintHTML = '<span class="dg-sort-hint" style="display:inline-flex;align-items:center;justify-content:center;vertical-align:middle;margin-left:5px;padding:1px 5px 2px;background:transparent;border:1px solid rgba(255,255,255,0.5);border-radius:3px;font-size:9px;line-height:1.2;">' + arrowContent + '</span>';
                } else if (sortStyle === 'text') {
                    sortHintHTML = '<span class="dg-sort-hint" style="display:inline-block;vertical-align:middle;margin-left:4px;font-size:11px;opacity:0.75;">▲▼</span>';
                }
            }

            $ths.each(function(idx) {
                var $th = $(this);
                $th.find('.dg-sort-hint, .dg-filter-hint').remove();

                if (sortHintHTML) $th.append(sortHintHTML);

                if (filterCols.indexOf(idx) !== -1) {
                    $th.append('<span class="dg-filter-hint" style="display:inline-flex;align-items:center;justify-content:center;vertical-align:middle;margin-left:5px;padding:1px 5px 2px;background:rgba(255,255,255,0.22);border:1px solid rgba(255,255,255,0.5);border-radius:3px;color:inherit;font-size:9px;line-height:1.2;cursor:default;user-select:none;">▼</span>');
                }
            });
        }

        // ── Live preview on change ────────────────────────────────────────
        $('.cdtv-design-controls').on('input change', 'input, select', applyPreview);

        // ── Toast notification ────────────────────────────────────────────
        function showToast(message, type) {
            var existing = document.getElementById('cdtv-dg-toast');
            if (existing) existing.remove();
            var toast = document.createElement('div');
            toast.id = 'cdtv-dg-toast';
            toast.style.cssText = [
                'position:fixed', 'bottom:32px', 'right:32px', 'z-index:999999',
                'padding:14px 22px', 'border-radius:8px',
                'font-size:14px', 'font-weight:600',
                'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',
                'color:#fff', 'box-shadow:0 6px 20px rgba(0,0,0,0.22)',
                'background:' + (type === 'success' ? '#1e8a44' : '#c0392b'),
                'opacity:0', 'transform:translateY(16px)',
                'transition:opacity 0.25s ease,transform 0.25s ease',
                'pointer-events:none'
            ].join(';');
            toast.textContent = message;
            document.body.appendChild(toast);
            requestAnimationFrame(function () {
                requestAnimationFrame(function () {
                    toast.style.opacity = '1';
                    toast.style.transform = 'translateY(0)';
                });
            });
            setTimeout(function () {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(16px)';
                setTimeout(function () { if (toast.parentNode) toast.remove(); }, 300);
            }, 3000);
        }

        // ── Save ──────────────────────────────────────────────────────────
        $('#dg-save').on('click', function(){
            var mode     = $('input[name="cdtv_dg_mode"]:checked').val();
            var tableId  = $('#dg-table-select').val();
            if (mode === 'table' && !tableId) {
                showToast('✖ <?php echo esc_js( __( 'Please select a table first.', 'codede-table-viewer' ) ); ?>', 'error');
                return;
            }

            // Per-table: save with plain '.cdtv-table' scope.
            //   render_table() does str_replace('.cdtv-table', '#cdtv-table-{id} .cdtv-table')
            //   so the final CSS gets an ID-scoped selector, which beats the base stylesheet.
            //   DO NOT pre-scope to '#id .cdtv-table' here – str_replace would double it.
            // Global: must match base CSS selector exactly so inline style (loaded after)
            //   can override it via source order.
            var cssScope = (mode === 'table' && tableId)
                ? '.cdtv-table'
                : '.cdtv-table-wrap table.cdtv-table';

            var filterCols = [];
            $('.cdtv-filter-col-cb:checked').each(function() { filterCols.push($(this).val()); });

            var $btn = $(this).prop('disabled', true).text('<?php echo esc_js( __( 'Saving…', 'codede-table-viewer' ) ); ?>');
            $.post(ajaxurl, {
                action:        'cdtv_save_design',
                nonce:         nonce,
                mode:          mode,
                table_id:      tableId || 0,
                css:           buildCSS(cssScope),
                enable_search:          $('#dg-enable-search').is(':checked')       ? 1 : 0,
                enable_sort:            $('#dg-enable-sort').is(':checked')         ? 1 : 0,
                enable_excel_format:    $('#dg-enable-excel-format').is(':checked') ? 1 : 0,
                rows_per_page:          parseInt($('#dg-rows-per-page').val(), 10) || 0,
                sort_indicator_style:   $('input[name="dg_sort_indicator_style"]:checked').val() || 'badge',
                filter_cols:   filterCols.join(','),
                hdr_bg:        $('#dg-hdr-bg').val(),
                hdr_color:     $('#dg-hdr-color').val(),
                hdr_size:      $('#dg-hdr-size').val(),
                hdr_bold:      $('#dg-hdr-bold').is(':checked') ? 1 : 0,
                row_bg:        $('#dg-row-bg').val(),
                row_color:     $('#dg-row-color').val(),
                row_stripe:    $('#dg-row-stripe').val(),
                row_hover:     $('#dg-row-hover').val(),
                row_height:    $('#dg-row-height').val(),
                bdr_style:     $('#dg-bdr-style').val(),
                bdr_color:     $('#dg-bdr-color').val(),
                bdr_width:     $('#dg-bdr-width').val()
            }, function(res){
                $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Save Design', 'codede-table-viewer' ) ); ?>');
                if (res.success) {
                    showToast('✔ <?php echo esc_js( __( 'Design saved!', 'codede-table-viewer' ) ); ?>', 'success');
                } else {
                    var errMsg = (res.data && res.data.message) ? res.data.message : '<?php echo esc_js( __( 'Save failed. Please try again.', 'codede-table-viewer' ) ); ?>';
                    showToast('✖ ' + errMsg, 'error');
                }
            }).fail(function(){
                $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Save Design', 'codede-table-viewer' ) ); ?>');
                showToast('✖ <?php echo esc_js( __( 'Connection error. Please try again.', 'codede-table-viewer' ) ); ?>', 'error');
            });
        });

        // ── Reset ─────────────────────────────────────────────────────────
        $('#dg-reset').on('click', function(){ applyValues(DEFAULTS); });

        // ── Initial preview ───────────────────────────────────────────────
        applyPreview();

    }(jQuery));
    </script>

    <?php endif; ?>
</div>
