<?php

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

$badge = static function ($txt, $bg, $fg) {
    return '<span style="display:inline-block;padding:1px 7px;border-radius:10px;font-size:11px;font-weight:600;background:' . $bg . ';color:' . $fg . ';">' . esc_html($txt) . '</span>';
};
$totals  = isset($totals) && is_array($totals) ? $totals : array('count' => 0, 'units' => 0, 'turnover' => 0, 'recoverable' => 0, 'recoverable_pess' => 0, 'recoverable_opt' => 0, 'window_days' => 0);
$gap_win = (int) (!empty($totals['window_days']) ? $totals['window_days'] : (isset($gap_recency) ? $gap_recency : 60));
$ch_pct  = isset($channel_pct) ? (int) $channel_pct : 17;
$ch_r    = $ch_pct / 100.0;
$gap_statuses = isset($gap_statuses) && is_array($gap_statuses) ? $gap_statuses : array('draft', '__needs_creation__');
$gap_excludes = isset($gap_excludes) && is_array($gap_excludes) ? $gap_excludes : array();
$gap_excluded = isset($gap_excluded) && is_array($gap_excluded) ? $gap_excluded : array();
$has_status   = static function ($k) use ($gap_statuses) { return in_array($k, $gap_statuses, true); };
$n_excl       = count($gap_excludes) + count($gap_excluded);
?>
<style>
.aieo-mhs-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:8px;}
.aieo-mhs-table th,.aieo-mhs-table td{padding:7px 8px;border-bottom:1px solid #eef0f2;text-align:left;vertical-align:top;}
.aieo-mhs-table th{font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;}
.aieo-mhs-chip{display:inline-block;margin:1px 3px 1px 0;padding:1px 7px;border-radius:9px;font-size:11px;background:#fef3c7;color:#92400e;}
.aieo-mhs-table td:last-child,.aieo-mhs-table th:last-child{text-align:right;white-space:nowrap;}
.aieo-mhs-table td:last-child{vertical-align:middle;}
.aieo-mhs-table td:last-child .button{vertical-align:middle;margin-left:4px;}
.aieo-mhs-table th.sortable{cursor:pointer;user-select:none;}
.aieo-mhs-table th.sortable:hover{color:#111827;}
.aieo-mhs-table th .arr{font-size:9px;margin-left:3px;color:#9ca3af;}
.aieo-mhs-table tfoot td{font-weight:700;border-top:2px solid #e5e7eb;background:#fafbfc;color:#111827;}
.aieo-mhs-rank{font-size:11px;color:#9ca3af;width:26px;}
.aieo-mhs-set label{font-size:12px;color:#374151;font-weight:600;margin-right:6px;}
.aieo-mhs-set input[type=number]{width:90px;}
.aieo-pr-btn-sm{font-size:11px!important;height:auto!important;min-height:0!important;padding:2px 8px!important;line-height:1.7!important;}
#aieo-mhs-status{font-size:12px;margin-left:10px;}
.aieo-mhs-kpis{display:flex;flex-wrap:wrap;gap:12px;margin-top:8px;}
.aieo-mhs-kpi{flex:1 1 180px;background:#f8fafc;border:1px solid #e6e9ee;border-radius:8px;padding:12px 14px;}
.aieo-mhs-kpi.hot{background:#fef2f2;border-color:#fecaca;}
.aieo-mhs-kpi .n{font-size:22px;font-weight:700;color:#111827;line-height:1.1;}
.aieo-mhs-kpi .l{font-size:11px;color:#6b7280;margin-top:3px;}
.mhs-statlbl{font-size:12px;color:#374151;font-weight:500;margin-right:14px;}
.mhs-statlbl input{margin-right:3px;vertical-align:-2px;}
.aieo-mhs-excl{margin:2px 0 6px;font-size:13px;}
.aieo-mhs-excl>summary{cursor:pointer;font-weight:600;color:#374151;}
.aieo-mhs-excl-body{padding:8px 0 2px;}
.aieo-mhs-excl-body textarea{width:100%;max-width:540px;font-family:Consolas,Monaco,monospace;font-size:12px;}
.aieo-mhs-dismissed{margin:0;max-height:190px;overflow:auto;font-size:12px;}
.aieo-mhs-dismissed li{padding:2px 0;border-bottom:1px solid #f1f3f5;}
.aieo-mhs-dismissed code{color:#9ca3af;margin-left:4px;}
.aieo-mhs-dismissed .mhs-restore{margin-left:6px;}
</style>

<div class="aieo-dmm-section">

    <h2><?php esc_html_e('Missing Hot Sellers', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('SKUs selling well in the physical stores that are NOT live in the eshop yet — auto-imported drafts that still need images / description / categories / brand (or products that don’t exist online at all). Publish the top of this list first.', 'ai-eshop-optimizer'); ?>
        <br><?php printf(esc_html__('Ranked by in-store turnover in the last %d days', 'ai-eshop-optimizer'), $gap_win); ?><?php if (!empty($data_asof)) : ?> — <?php esc_html_e('data through', 'ai-eshop-optimizer'); ?> <strong><?php echo esc_html($data_asof); ?></strong><?php endif; ?>.
        <br><span class="description"><?php esc_html_e('Offers you took offline (private) and any dismissed/excluded items are not counted in the list or the totals below — adjust “Include” and the exclude patterns to keep the estimate realistic.', 'ai-eshop-optimizer'); ?></span>
    </p>
    <p style="margin:0 0 6px;">
        <button type="button" class="button button-primary" id="aieo-mhs-run"><?php esc_html_e('Refresh list now', 'ai-eshop-optimizer'); ?></button>
        <span class="aieo-mhs-set" style="margin-left:14px;">
            <label><?php esc_html_e('Min units sold', 'ai-eshop-optimizer'); ?></label>
            <input type="number" id="mhs-gap_min_units" min="1" max="999" value="<?php echo esc_attr($gap_min_units); ?>">
            <label style="margin-left:10px;"><?php esc_html_e('Over last (days)', 'ai-eshop-optimizer'); ?></label>
            <input type="number" id="mhs-gap_recency" min="3" max="365" value="<?php echo esc_attr($gap_recency); ?>">
            <button type="button" class="button button-secondary" id="aieo-mhs-save" style="margin-left:6px;"><?php esc_html_e('Save', 'ai-eshop-optimizer'); ?></button>
        </span>
        <span id="aieo-mhs-status"></span>
    </p>
    <p class="aieo-mhs-set" style="margin:0 0 4px;">
        <label style="margin-right:8px;"><?php esc_html_e('Include:', 'ai-eshop-optimizer'); ?></label>
        <label class="mhs-statlbl"><input type="checkbox" class="mhs-status" value="draft" <?php checked($has_status('draft')); ?>> <?php esc_html_e('Drafts to complete', 'ai-eshop-optimizer'); ?></label>
        <label class="mhs-statlbl"><input type="checkbox" class="mhs-status" value="__needs_creation__" <?php checked($has_status('__needs_creation__')); ?>> <?php esc_html_e('Not in eshop at all', 'ai-eshop-optimizer'); ?></label>
        <label class="mhs-statlbl"><input type="checkbox" class="mhs-status" value="private" <?php checked($has_status('private')); ?>> <?php esc_html_e('Private (offers taken offline)', 'ai-eshop-optimizer'); ?></label>
        <label class="mhs-statlbl"><input type="checkbox" class="mhs-status" value="pending" <?php checked($has_status('pending')); ?>> <?php esc_html_e('Pending', 'ai-eshop-optimizer'); ?></label>
        <span class="description" style="margin-left:6px;"><?php esc_html_e('Click Save to apply.', 'ai-eshop-optimizer'); ?></span>
    </p>
    <details class="aieo-mhs-excl"<?php echo $n_excl ? ' open' : ''; ?>>
        <summary><?php esc_html_e('Excluded items & patterns', 'ai-eshop-optimizer'); ?><?php echo $n_excl ? ' <span class="description">(' . esc_html(number_format_i18n($n_excl)) . ')</span>' : ''; ?></summary>
        <div class="aieo-mhs-excl-body">
            <p style="margin:0 0 4px;"><strong style="font-size:12px;"><?php esc_html_e('Exclude by name / SKU pattern', 'ai-eshop-optimizer'); ?></strong><br>
            <span class="description"><?php esc_html_e('One per line. Any product whose name OR SKU contains the text is removed from the list AND the totals — now and for future imports (e.g. recurring offers, coupons, gift vouchers, catch-all accounting SKUs).', 'ai-eshop-optimizer'); ?></span></p>
            <textarea id="mhs-gap_excludes" rows="4" placeholder="Προσφορά&#10;Δωροεπιταγή&#10;ΔΙΑΦΟΡΑ ΕΙΔΗ&#10;9.99."><?php echo esc_textarea(implode("\n", $gap_excludes)); ?></textarea>
            <p style="margin:6px 0 0;"><button type="button" class="button button-secondary" id="aieo-mhs-save-excl"><?php esc_html_e('Save exclusions', 'ai-eshop-optimizer'); ?></button></p>
            <?php if (!empty($gap_excluded)) : ?>
            <p style="margin:12px 0 2px;"><strong style="font-size:12px;"><?php printf(esc_html__('Dismissed items (%s)', 'ai-eshop-optimizer'), esc_html(number_format_i18n(count($gap_excluded)))); ?></strong></p>
            <ul class="aieo-mhs-dismissed">
                <?php foreach ($gap_excluded as $x) : ?>
                <li data-sku="<?php echo esc_attr($x['sku_norm']); ?>">
                    <?php echo esc_html($x['name'] !== '' ? $x['name'] : $x['sku']); ?>
                    <code><?php echo esc_html($x['sku']); ?></code>
                    <a href="#" class="mhs-restore"><?php esc_html_e('Restore', 'ai-eshop-optimizer'); ?></a>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </div>
    </details>

    <?php ?>
    <?php if ((int) $totals['count'] > 0) : ?>
    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('In-store sales we are missing online', 'ai-eshop-optimizer'); ?></h3>
        <div class="aieo-mhs-kpis">
            <div class="aieo-mhs-kpi hot">
                <div class="n"><?php echo esc_html(number_format_i18n((float) $totals['turnover'], 2)); ?> €</div>
                <div class="l"><?php printf(esc_html__('In-store sales of products not live in the eshop · last %d days', 'ai-eshop-optimizer'), $gap_win); ?></div>
            </div>
            <div class="aieo-mhs-kpi">
                <div class="n"><?php echo esc_html(number_format_i18n((int) $totals['count'])); ?></div>
                <div class="l"><?php esc_html_e('Products (drafts + not created online)', 'ai-eshop-optimizer'); ?></div>
            </div>
            <div class="aieo-mhs-kpi">
                <div class="n"><?php echo esc_html(number_format_i18n((float) $totals['units'], 0)); ?></div>
                <div class="l"><?php printf(esc_html__('Units sold in the stores · last %d days', 'ai-eshop-optimizer'), $gap_win); ?></div>
            </div>
            <?php if ((float) $totals['recoverable'] > 0) : ?>
            <div class="aieo-mhs-kpi" style="background:#eef2ff;border-color:#c7d2fe;flex:1 1 240px;" title="<?php printf(esc_attr__('Estimate of the online sales we would capture if these products went live = their in-store sales (last %1$d days) x the eshop\'s share of total demand (%2$d%%). Optimistic reflects the eshop\'s national reach (~6,000 visitors/day) beyond the 4 stores\' catchment. An estimate, not a guarantee.', 'ai-eshop-optimizer'), $gap_win, $ch_pct); ?>">
                <div class="n">≈ <?php echo esc_html(number_format_i18n((float) $totals['recoverable'], 2)); ?> €</div>
                <div class="l">
                    <?php printf(esc_html__('Est. recoverable online sales if published · last %d days', 'ai-eshop-optimizer'), $gap_win); ?>
                    <br><strong style="font-size:12px;color:#4b5563;"><?php esc_html_e('pessimistic', 'ai-eshop-optimizer'); ?> <?php echo esc_html(number_format_i18n((float) $totals['recoverable_pess'], 0)); ?> € · <?php esc_html_e('optimistic', 'ai-eshop-optimizer'); ?> <?php echo esc_html(number_format_i18n((float) $totals['recoverable_opt'], 0)); ?> €</strong>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <p class="description" style="margin:10px 0 0;"><?php printf(esc_html__('Net physical-store revenue (ex-VAT) in the last %1$d days, for SKUs not live in the eshop yet — the sales we are missing by not having these products online. The recoverable estimate applies the eshop\'s channel share (%2$d%%) to that in-store demand.', 'ai-eshop-optimizer'), $gap_win, $ch_pct); ?></p>
    </div>
    <?php endif; ?>

    <?php ?>
    <?php $pub = isset($pub_kpis) && is_array($pub_kpis) ? $pub_kpis : array(); $pub_events = isset($pub_events) && is_array($pub_events) ? $pub_events : array(); ?>
    <?php if ((int) ($pub['published_count'] ?? 0) > 0) : ?>
    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('Published from this list — what it earned online', 'ai-eshop-optimizer'); ?></h3>
        <div class="aieo-mhs-kpis">
            <div class="aieo-mhs-kpi">
                <div class="n"><?php echo esc_html(number_format_i18n((int) $pub['published_count'])); ?></div>
                <div class="l"><?php printf(esc_html__('Products published from this list (%s still live)', 'ai-eshop-optimizer'), esc_html(number_format_i18n((int) ($pub['open_count'] ?? 0)))); ?></div>
            </div>
            <div class="aieo-mhs-kpi" style="background:#ecfdf5;border-color:#a7f3d0;">
                <div class="n"><?php echo esc_html(number_format_i18n((float) ($pub['turnover_since'] ?? 0), 2)); ?> €</div>
                <div class="l"><?php esc_html_e('Online sales earned since they were published', 'ai-eshop-optimizer'); ?></div>
            </div>
            <div class="aieo-mhs-kpi">
                <div class="n"><?php echo esc_html(number_format_i18n((float) ($pub['units_since'] ?? 0), 0)); ?></div>
                <div class="l"><?php printf(esc_html__('Online units sold since publishing (%s orders)', 'ai-eshop-optimizer'), esc_html(number_format_i18n((int) ($pub['orders_since'] ?? 0)))); ?></div>
            </div>
            <div class="aieo-mhs-kpi">
                <div class="n"><?php echo esc_html(number_format_i18n((float) ($pub['instore_turnover'] ?? 0), 2)); ?> €</div>
                <div class="l"><?php esc_html_e('In-store demand they had when published (reference)', 'ai-eshop-optimizer'); ?></div>
            </div>
        </div>
        <p class="description" style="margin:10px 0 0;"><?php esc_html_e('Every time you publish a product from this list, we start counting the real online sales it makes. This is the concrete payoff of acting on the list — the online revenue you would not have had if these SKUs stayed offline. (Online sales are attributed from each product\'s publish date, excluding cancelled/refunded orders.)', 'ai-eshop-optimizer'); ?></p>
        <?php if (!empty($pub_events)) : ?>
        <table class="aieo-mhs-table" style="margin-top:10px;">
            <thead><tr>
                <th><?php esc_html_e('Product / SKU', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Published', 'ai-eshop-optimizer'); ?></th>
                <th title="<?php esc_attr_e('In-store net turnover this product had when it was published', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('In-store demand', 'ai-eshop-optimizer'); ?></th>
                <th title="<?php esc_attr_e('Online sales earned since it went live', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('Online earned since', 'ai-eshop-optimizer'); ?></th>
            </tr></thead>
            <tbody>
            <?php foreach (array_slice($pub_events, 0, 50) as $pe) :
                $pe_pid  = (int) $pe['product_id'];
                $pe_edit = $pe_pid > 0 ? admin_url('post.php?post=' . $pe_pid . '&action=edit') : '';
                $pe_name = $pe['product_name'] ?: ($pe['name'] ?: ($pe['sku'] ?: ('#' . $pe_pid)));
                $pe_live = empty($pe['unpublished_at']);
            ?>
                <tr>
                    <td>
                        <div style="display:flex;align-items:center;gap:8px;">
                            <?php if (!empty($pe['image_url'])) : ?><img src="<?php echo esc_url($pe['image_url']); ?>" alt="" style="width:30px;height:30px;object-fit:cover;border-radius:4px;flex:0 0 auto;"><?php endif; ?>
                            <span>
                                <?php if ($pe_edit) : ?><a href="<?php echo esc_url($pe_edit); ?>" target="_blank" rel="noopener"><strong><?php echo esc_html($pe_name); ?></strong></a><?php else : ?><strong><?php echo esc_html($pe_name); ?></strong><?php endif; ?>
                                <?php if (!$pe_live) { echo ' ' . $badge(__('unpublished', 'ai-eshop-optimizer'), '#f3f4f6', '#6b7280'); } ?>
                                <?php if (!empty($pe['sku'])) : ?><br><code style="font-size:11px;color:#9ca3af;"><?php echo esc_html($pe['sku']); ?></code><?php endif; ?>
                            </span>
                        </div>
                    </td>
                    <td style="font-size:11px;color:#6b7280;white-space:nowrap;"><?php echo esc_html(substr((string) $pe['published_at'], 0, 10)); ?></td>
                    <td><?php echo esc_html(number_format_i18n((float) ($pe['phys_turnover_recent_at_publish'] ?? 0), 2)); ?> €</td>
                    <td style="white-space:nowrap;"><strong style="color:#047857;"><?php echo esc_html(number_format_i18n((float) ($pe['eshop_turnover_since'] ?? 0), 2)); ?> €</strong> <span style="color:#9ca3af;font-size:11px;">· <?php echo esc_html(rtrim(rtrim((string) ($pe['eshop_units_since'] ?? 0), '0'), '.')); ?> <?php esc_html_e('u', 'ai-eshop-optimizer'); ?></span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="aieo-dmm-card">
        <h3 style="display:inline-block;"><?php esc_html_e('Priority list', 'ai-eshop-optimizer'); ?> <?php echo !empty($gaps) ? '<span class="description">(' . esc_html(number_format_i18n(count($gaps))) . ')</span>' : ''; ?></h3>
        <?php if (!empty($gaps)) : ?>
            <a class="button" style="float:right;" href="<?php echo esc_url(admin_url('admin-ajax.php') . '?action=aieo_pr_export_gaps&nonce=' . rawurlencode($nonce)); ?>"><?php esc_html_e('Export to Excel', 'ai-eshop-optimizer'); ?></a>
        <?php endif; ?>
        <?php if (empty($gaps)) : ?>
            <p class="description"><?php esc_html_e('No missing hot sellers detected yet. Click “Refresh list now” (needs physical-store sales data).', 'ai-eshop-optimizer'); ?></p>
        <?php else : ?>
        <table class="aieo-mhs-table">
            <thead><tr>
                <th>#</th>
                <th class="sortable" data-key="name"><?php esc_html_e('Product / SKU', 'ai-eshop-optimizer'); ?><span class="arr"></span></th>
                <th class="sortable" data-key="units"><?php esc_html_e('Phys. sold', 'ai-eshop-optimizer'); ?><span class="arr">▼</span></th>
                <th title="<?php printf(esc_attr__('Units sold per physical store over the last %d days — where this SKU is selling', 'ai-eshop-optimizer'), $gap_win); ?>"><?php esc_html_e('By branch (units)', 'ai-eshop-optimizer'); ?></th>
                <th class="sortable" data-key="turnover" title="<?php esc_attr_e('Net physical-store revenue (ex-VAT) over the period', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('Turnover (net)', 'ai-eshop-optimizer'); ?><span class="arr"></span></th>
                <th class="sortable" data-key="units30" title="<?php esc_attr_e('Units sold in the physical stores in the last 30 days', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('Units · 30d', 'ai-eshop-optimizer'); ?><span class="arr"></span></th>
                <th class="sortable" data-key="sales30" title="<?php esc_attr_e('Net physical-store revenue (ex-VAT) in the last 30 days', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('Sales · 30d', 'ai-eshop-optimizer'); ?><span class="arr"></span></th>
                <th class="sortable" data-key="created" title="<?php esc_attr_e('When the product was first created in the eshop (from the ERP daily import), and how long it has been sitting un-published', 'ai-eshop-optimizer'); ?>"><?php esc_html_e('First created', 'ai-eshop-optimizer'); ?><span class="arr"></span></th>
                <th><?php esc_html_e('Status / needs', 'ai-eshop-optimizer'); ?></th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php $rank = 0; foreach ($gaps as $g) : $rank++;
                $gpid = (int) $g['product_id'];
                $edit = $gpid > 0 ? admin_url('post.php?post=' . $gpid . '&action=edit') : '';
                $fc      = !empty($g['first_created']) ? substr((string) $g['first_created'], 0, 10) : '';
                $fc_sort = $fc !== '' ? (int) str_replace('-', '', $fc) : 0; 
            ?>
                <tr data-sku="<?php echo esc_attr($g['sku_norm']); ?>"
                    data-name="<?php echo esc_attr(function_exists('mb_strtolower') ? mb_strtolower((string) ($g['name'] ?: $g['sku'])) : strtolower((string) ($g['name'] ?: $g['sku']))); ?>"
                    data-units="<?php echo esc_attr((float) $g['phys_units']); ?>"
                    data-turnover="<?php echo esc_attr((float) $g['phys_turnover']); ?>"
                    data-units30="<?php echo esc_attr((float) ($g['phys_units_30d'] ?? 0)); ?>"
                    data-sales30="<?php echo esc_attr((float) ($g['phys_turnover_30d'] ?? 0)); ?>"
                    data-created="<?php echo esc_attr($fc_sort); ?>">
                    <td class="aieo-mhs-rank"><?php echo esc_html($rank); ?></td>
                    <td>
                        <strong><?php echo esc_html($g['name'] ?: $g['sku']); ?></strong><br>
                        <code style="font-size:11px;color:#6b7280;"><?php echo esc_html($g['sku']); ?></code>
                    </td>
                    <td>
                        <strong><?php echo esc_html(rtrim(rtrim((string) $g['phys_units'], '0'), '.')); ?></strong> <?php esc_html_e('units', 'ai-eshop-optimizer'); ?><br>
                        <span style="font-size:11px;color:#6b7280;"><?php echo esc_html((int) $g['phys_sale_days']); ?> <?php esc_html_e('sale-days · last', 'ai-eshop-optimizer'); ?> <?php echo esc_html($g['last_phys_sale_date']); ?></span>
                    </td>
                    <?php
                    $gbr = array();
                    foreach (array('piraeus' => 'Πειραιάς', 'keratsini' => 'Κερατσίνι', 'korydallos' => 'Κορυδαλλός', 'kallithea' => 'Καλλιθέα') as $bk => $bl) {
                        $bv = (float) ($g['phys_' . $bk] ?? 0);
                        if ($bv > 0) { $gbr[] = $bl . ' ' . rtrim(rtrim(number_format($bv, 3, '.', ''), '0'), '.'); }
                    }
                    ?>
                    <td style="font-size:11px;color:#4b5563;"><?php echo $gbr ? esc_html(implode(', ', $gbr)) : '—'; ?></td>
                    <td><strong><?php echo esc_html(number_format_i18n((float) $g['phys_turnover'], 2)); ?> €</strong><br><span style="font-size:11px;color:#4338ca;" title="<?php printf(esc_attr__('Estimated recoverable online sales if published = in-store turnover × %d%% channel share', 'ai-eshop-optimizer'), $ch_pct); ?>">≈ <?php echo esc_html(number_format_i18n(min((float) $g['phys_turnover'] * $ch_r, (float) $g['phys_turnover']), 2)); ?> € <?php esc_html_e('recoverable', 'ai-eshop-optimizer'); ?></span></td>
                    <td><strong><?php echo esc_html(rtrim(rtrim((string) ($g['phys_units_30d'] ?? 0), '0'), '.')); ?></strong> <?php esc_html_e('units', 'ai-eshop-optimizer'); ?></td>
                    <td><strong><?php echo esc_html(number_format_i18n((float) ($g['phys_turnover_30d'] ?? 0), 2)); ?> €</strong></td>
                    <td>
                        <?php if ($fc !== '') : ?>
                            <strong><?php echo esc_html($fc); ?></strong><br>
                            <span style="font-size:11px;color:#6b7280;"><?php echo esc_html(max(0, (int) $g['days_not_live'])); ?> <?php esc_html_e('days not live', 'ai-eshop-optimizer'); ?></span>
                        <?php else : ?>
                            <span style="color:#9ca3af;font-size:12px;"><?php esc_html_e('not imported', 'ai-eshop-optimizer'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php
                        if ((int) $g['needs_creation'] === 1) {
                            echo $badge(__('not in eshop — create it', 'ai-eshop-optimizer'), '#fee2e2', '#991b1b');
                        } else {
                            echo $g['post_status'] ? $badge($g['post_status'], '#f3f4f6', '#6b7280') . ' ' : '';
                            if ((int) $g['missing_image'] === 1) { echo '<span class="aieo-mhs-chip">' . esc_html__('image', 'ai-eshop-optimizer') . '</span>'; }
                            if ((int) $g['missing_desc'] === 1)  { echo '<span class="aieo-mhs-chip">' . esc_html__('description', 'ai-eshop-optimizer') . '</span>'; }
                            if ((int) $g['missing_cats'] === 1)  { echo '<span class="aieo-mhs-chip">' . esc_html__('categories', 'ai-eshop-optimizer') . '</span>'; }
                            if ((int) $g['missing_brand'] === 1) { echo '<span class="aieo-mhs-chip">' . esc_html__('brand', 'ai-eshop-optimizer') . '</span>'; }
                        }
                        ?>
                    </td>
                    <td style="white-space:nowrap;">
                        <?php if ($edit) : ?>
                            <a href="<?php echo esc_url($edit); ?>" target="_blank" rel="noopener" class="button button-primary aieo-pr-btn-sm"><?php esc_html_e('Edit in Woo →', 'ai-eshop-optimizer'); ?></a>
                        <?php endif; ?>
                        <button type="button" class="button aieo-pr-btn-sm mhs-dismiss"><?php esc_html_e('Dismiss', 'ai-eshop-optimizer'); ?></button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot><tr>
                <td></td>
                <td><?php printf(esc_html__('Total — %s products', 'ai-eshop-optimizer'), esc_html(number_format_i18n((int) $totals['count']))); ?></td>
                <td><?php echo esc_html(number_format_i18n((float) $totals['units'], 0)); ?> <?php esc_html_e('units', 'ai-eshop-optimizer'); ?></td>
                <td></td>
                <td><?php echo esc_html(number_format_i18n((float) $totals['turnover'], 2)); ?> €<br><span style="font-size:11px;color:#4338ca;font-weight:600;">≈ <?php echo esc_html(number_format_i18n((float) $totals['recoverable'], 2)); ?> € <?php esc_html_e('recoverable', 'ai-eshop-optimizer'); ?></span></td>
                <td><?php echo esc_html(number_format_i18n((float) ($totals['units_30d'] ?? 0), 0)); ?> <?php esc_html_e('units', 'ai-eshop-optimizer'); ?></td>
                <td><?php echo esc_html(number_format_i18n((float) ($totals['turnover_30d'] ?? 0), 2)); ?> €</td>
                <td></td>
                <td colspan="2"></td>
            </tr></tfoot>
        </table>
        <div class="aieo-mhs-pager" style="margin-top:12px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
            <label style="font-size:12px;color:#646970;"><?php esc_html_e('Rows per page:', 'ai-eshop-optimizer'); ?>
                <select id="aieo-mhs-perpage" style="margin-left:4px;">
                    <option value="25">25</option>
                    <option value="50" selected>50</option>
                    <option value="100">100</option>
                    <option value="0"><?php esc_html_e('All', 'ai-eshop-optimizer'); ?></option>
                </select>
            </label>
            <span id="aieo-mhs-pageinfo" style="font-size:12px;color:#646970;"></span>
            <span id="aieo-mhs-pagebtns" style="display:inline-flex;gap:4px;flex-wrap:wrap;"></span>
        </div>
        <?php endif; ?>
    </div>

</div>

<script>
(function(){
    var NONCE = <?php echo wp_json_encode($nonce); ?>;
    var statusEl = document.getElementById('aieo-mhs-status');
    function setStatus(msg, ok){ if(!statusEl) return; statusEl.textContent = msg; statusEl.style.color = ok===false ? '#b91c1c' : (ok ? '#15803d' : '#6b7280'); }
    function post(action, data){
        var fd = new FormData(); fd.append('action', action); fd.append('nonce', NONCE);
        Object.keys(data||{}).forEach(function(k){ fd.append(k, data[k]); });
        return fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'}).then(function(r){ return r.json(); });
    }
    var runBtn = document.getElementById('aieo-mhs-run');
    runBtn && runBtn.addEventListener('click', function(){
        runBtn.disabled = true; setStatus('<?php echo esc_js(__('Refreshing…', 'ai-eshop-optimizer')); ?>');
        post('aieo_pr_run_detection', {}).then(function(j){
            runBtn.disabled = false;
            if (j && j.success) { setStatus('<?php echo esc_js(__('Done.', 'ai-eshop-optimizer')); ?>', true); setTimeout(function(){ location.reload(); }, 800); }
            else { setStatus((j&&j.data&&j.data.message)||'error', false); }
        }).catch(function(){ runBtn.disabled=false; setStatus('<?php echo esc_js(__('network error', 'ai-eshop-optimizer')); ?>', false); });
    });
    // Save all gap settings (min units / recency / status whitelist / exclude
    // patterns) in one call, then reload — the status & pattern filters are
    // applied at read-time so the list + totals change on the next render.
    function saveAll(){
        setStatus('<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>');
        var fd = new FormData(); fd.append('action', 'aieo_pr_save_gap_settings'); fd.append('nonce', NONCE);
        fd.append('gap_min_units', document.getElementById('mhs-gap_min_units').value);
        fd.append('gap_recency',   document.getElementById('mhs-gap_recency').value);
        var ex = document.getElementById('mhs-gap_excludes'); if (ex) { fd.append('gap_name_excludes', ex.value); }
        var st = Array.prototype.map.call(document.querySelectorAll('.mhs-status:checked'), function(c){ return c.value; });
        if (st.length === 0) { fd.append('gap_statuses[]', ''); } else { st.forEach(function(s){ fd.append('gap_statuses[]', s); }); }
        return fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'}).then(function(r){ return r.json(); }).then(function(j){
            if (j && j.success) { setStatus('<?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?>', true); setTimeout(function(){ location.reload(); }, 500); }
            else { setStatus((j&&j.data&&j.data.message)||'error', false); }
        }).catch(function(){ setStatus('<?php echo esc_js(__('network error', 'ai-eshop-optimizer')); ?>', false); });
    }
    var saveBtn = document.getElementById('aieo-mhs-save');
    saveBtn && saveBtn.addEventListener('click', saveAll);
    var saveExclBtn = document.getElementById('aieo-mhs-save-excl');
    saveExclBtn && saveExclBtn.addEventListener('click', saveAll);
    document.addEventListener('click', function(ev){
        if (ev.target.classList.contains('mhs-dismiss')) {
            var tr = ev.target.closest('tr');
            post('aieo_pr_gap_dismiss', {sku_norm: tr.getAttribute('data-sku')}).then(function(){ tr.style.opacity=0.4; });
        } else if (ev.target.classList.contains('mhs-restore')) {
            ev.preventDefault();
            var li = ev.target.closest('li');
            post('aieo_pr_gap_restore', {sku_norm: li.getAttribute('data-sku')}).then(function(){
                li.style.opacity = 0.4;
                setStatus('<?php echo esc_js(__('Restored — refresh to see it back in the list.', 'ai-eshop-optimizer')); ?>', true);
            });
        }
    });

    // Column sorting (client-side, re-numbers the rank) + pagination over the
    // full (optionally sorted) set. The Priority list can hold up to 500 rows,
    // so we page them and let every sortable header reorder the WHOLE set then
    // reset to page 1.
    var table = document.querySelector('.aieo-mhs-table');
    if (table) {
        var tbody    = table.querySelector('tbody');
        var dir      = {};
        var perSel   = document.getElementById('aieo-mhs-perpage');
        var pageInfo = document.getElementById('aieo-mhs-pageinfo');
        var pageBtns = document.getElementById('aieo-mhs-pagebtns');
        var perPage  = perSel ? (parseInt(perSel.value, 10) || 0) : 50;
        var page     = 1;
        var L_SHOW   = <?php echo wp_json_encode(__('Showing', 'ai-eshop-optimizer')); ?>;
        var L_OF     = <?php echo wp_json_encode(__('of', 'ai-eshop-optimizer')); ?>;

        function rowsArr(){ return Array.prototype.slice.call(tbody.querySelectorAll('tr')); }

        function renderPage(){
            var all = rowsArr();
            var total = all.length;
            var pp = perPage > 0 ? perPage : total;
            var pages = Math.max(1, Math.ceil(total / Math.max(1, pp)));
            if (page > pages) { page = pages; }
            if (page < 1) { page = 1; }
            var start = (page - 1) * pp;
            var end   = perPage > 0 ? start + pp : total;
            all.forEach(function(r, i){ r.style.display = (i >= start && i < end) ? '' : 'none'; });
            if (pageInfo) {
                var from = total === 0 ? 0 : start + 1;
                var to   = Math.min(end, total);
                pageInfo.textContent = L_SHOW + ' ' + from + '–' + to + ' ' + L_OF + ' ' + total;
            }
            if (pageBtns) {
                pageBtns.innerHTML = '';
                if (pages <= 1) { return; }
                var mk = function(label, target, disabled, current){
                    var b = document.createElement('button');
                    b.type = 'button';
                    b.className = 'button' + (current ? ' button-primary' : '');
                    b.textContent = label;
                    b.style.minWidth = '34px';
                    if (disabled) { b.disabled = true; }
                    else { b.addEventListener('click', function(){ page = target; renderPage(); }); }
                    pageBtns.appendChild(b);
                };
                mk('‹', page - 1, page <= 1, false);
                var win = [];
                for (var i = 1; i <= pages; i++) {
                    if (i === 1 || i === pages || (i >= page - 2 && i <= page + 2)) { win.push(i); }
                    else if (win[win.length - 1] !== '…') { win.push('…'); }
                }
                win.forEach(function(i){
                    if (i === '…') { var s = document.createElement('span'); s.textContent = '…'; s.style.padding = '0 4px'; pageBtns.appendChild(s); }
                    else { mk(String(i), i, false, i === page); }
                });
                mk('›', page + 1, page >= pages, false);
            }
        }

        table.querySelectorAll('th.sortable').forEach(function(th){
            th.style.cursor = 'pointer';
            th.addEventListener('click', function(){
                var key = th.getAttribute('data-key');
                // First click on a column: numeric → desc (biggest first), text → asc.
                // Subsequent clicks toggle.
                if (dir[key] === undefined) { dir[key] = (key === 'name') ? 'asc' : 'desc'; }
                else { dir[key] = (dir[key] === 'asc') ? 'desc' : 'asc'; }
                var d = dir[key];
                var all = rowsArr();
                all.sort(function(a, b){
                    var av = a.getAttribute('data-' + key) || '', bv = b.getAttribute('data-' + key) || '';
                    if (key === 'name') { return d === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av); }
                    av = parseFloat(av) || 0; bv = parseFloat(bv) || 0;
                    return d === 'asc' ? av - bv : bv - av;
                });
                all.forEach(function(r, i){ tbody.appendChild(r); var rk = r.querySelector('.aieo-mhs-rank'); if (rk) { rk.textContent = (i + 1); } });
                table.querySelectorAll('th.sortable .arr').forEach(function(a){ a.textContent = ''; });
                var arr = th.querySelector('.arr'); if (arr) { arr.textContent = d === 'asc' ? '▲' : '▼'; }
                page = 1; renderPage();
            });
        });

        if (perSel) { perSel.addEventListener('change', function(){ perPage = parseInt(perSel.value, 10) || 0; page = 1; renderPage(); }); }
        renderPage();
    }
})();
</script>
