<?php

/**

 * Enterprise Validation Rules - Block & Allow Management

 *

 * @package    SensFRX

 * @subpackage SensFRX/admin/partials

 */



if (!defined('WPINC')) { die; }

?>



<div class="sensfrx-enterprise-wrapper">

    <?php include_once plugin_dir_path(__FILE__) . 'sensfrx-navigation.php'; ?>



    <div class="sensfrx-enterprise-dashboard">

        

        <!-- Page Header -->

        <div style="margin-bottom: 32px;">

            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">

                <div>

                    <h1 style="margin: 0; font-size: 28px; font-weight: 700; color: #111827;">Protect Your Store</h1>

                    <p style="margin: 8px 0 0; color: #6b7280; font-size: 15px;">Stop fraudsters and welcome real customers with smart protection rules</p>

                </div>

                <button class="sensfrx-btn-primary" onclick="openRuleModal()" style="padding: 12px 24px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px; box-shadow: 0 4px 6px rgba(37, 99, 235, 0.25);">

                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">

                        <path d="M10 4v12M4 10h12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>

                    </svg>

                    Create Rule

                </button>

            </div>

        </div>



        <!-- Stats Dashboard -->

        <div id="stats-dashboard" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px;">

            

            <div class="sensfrx-stat-card" style="background: linear-gradient(135deg, #0EA5E9 0%, #0284C7 100%); color: white; padding: 24px; border-radius: 12px; position: relative; overflow: hidden;">

                <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255,255,255,0.1); border-radius: 50%;"></div>

                <div style="position: relative;">

                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">

                        <div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 10px;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <span id="rules-count-badge" style="background: rgba(255,255,255,0.25); padding: 4px 12px; border-radius: 16px; font-size: 13px; font-weight: 700;">0</span>

                    </div>

                    <div style="font-size: 36px; font-weight: 800; margin-bottom: 6px; letter-spacing: -1px;" id="total-rules-count">0</div>

                    <div style="font-size: 14px; font-weight: 500; opacity: 0.95; margin-bottom: 14px; display: flex; align-items: center; gap: 6px;">

                        Your Active Protections

                        <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.8;">

                                <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                                <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                            </svg>

                            <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 12px 14px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -140px; width: 280px; font-size: 12px; line-height: 1.5; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                                <strong style="display: block; margin-bottom: 6px; color: #3B82F6;">What are Active Protections?</strong>

                                This includes:<br>

                                • Block/Allow rules you created<br>

                                • Smart Protection rules you enabled<br>

                                • AI Protection rules you turned on<br><br>

                                The more protections active, the safer your store!

                            </span>

                        </div>

                    </div>

                    <div style="padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.25); font-size: 13px; font-weight: 500; opacity: 0.9; display: flex; align-items: center; gap: 4px; flex-wrap: wrap;">

                        <span style="display: inline-flex; align-items: center; gap: 4px;">

                            <span id="block-rules-count">0</span> stopping fraud

                            <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.7;">

                                    <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                                    <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                                </svg>

                                <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 10px 12px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -110px; width: 220px; font-size: 11px; line-height: 1.4; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                                    <strong style="color: #EF4444;">Blocking Rules</strong><br>

                                    Rules that automatically reject suspicious activity like disposable emails, known fraudsters, etc.

                                </span>

                            </div>

                        </span>

                        <span>•</span>

                        <span style="display: inline-flex; align-items: center; gap: 4px;">

                            <span id="allow-rules-count">0</span> welcoming real customers

                            <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.7;">

                                    <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                                    <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                                </svg>

                                <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 10px 12px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -110px; width: 220px; font-size: 11px; line-height: 1.4; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                                    <strong style="color: #10B981;">Allowing Rules</strong><br>

                                    Rules that automatically approve trusted customers, VIP emails, or corporate domains.

                                </span>

                            </div>

                        </span>

                    </div>

                </div>

            </div>



            <div class="sensfrx-stat-card" style="background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%); color: white; padding: 24px; border-radius: 12px;">

                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">

                    <div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 10px;">

                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                            <path d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </div>

                </div>

                <div style="font-size: 36px; font-weight: 800; margin-bottom: 6px; letter-spacing: -1px;" id="threats-blocked-count">--</div>

                <div style="font-size: 14px; font-weight: 500; opacity: 0.95; margin-bottom: 14px; display: flex; align-items: center; gap: 6px;">

                    Fraudsters Stopped (Last 30 Days)

                    <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.8;">

                            <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                            <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                        </svg>

                        <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 12px 14px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -140px; width: 280px; font-size: 12px; line-height: 1.5; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                            <strong style="display: block; margin-bottom: 6px; color: #EF4444;">What does this number mean?</strong>

                            This shows how many suspicious activities (logins, transactions, registrations) with critical risk (score 90+) were blocked in the last 30 days.<br><br>

                            Each blocked fraudster is:<br>

                            • A potentially stolen card prevented<br>

                            • A chargeback you avoided<br>

                            • Money and time saved for your business

                        </span>

                    </div>

                </div>

                <div style="padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.25); font-size: 13px; font-weight: 500; opacity: 0.9;">

                    Your rules are working! 

                </div>

            </div>



            <div class="sensfrx-stat-card" style="background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; padding: 24px; border-radius: 12px;">

                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">

                    <div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 10px;">

                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </div>

                </div>

                <div style="font-size: 36px; font-weight: 800; margin-bottom: 6px; letter-spacing: -1px;" id="legitimate-orders-count">--</div>

                <div style="font-size: 14px; font-weight: 500; opacity: 0.95; margin-bottom: 14px; display: flex; align-items: center; gap: 6px;">

                    Happy Customers (Last 30 Days)

                    <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.8;">

                            <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                            <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                        </svg>

                        <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 12px 14px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -140px; width: 280px; font-size: 12px; line-height: 1.5; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                            <strong style="display: block; margin-bottom: 6px; color: #3B82F6;">What does this number mean?</strong>

                            This shows unique customers (by email) who had smooth experiences with low risk scores in the last 30 days.<br><br>

                            Happy customers means:<br>

                            • No false positives blocking real buyers<br>

                            • Smooth checkout experience<br>

                            • More sales and repeat customers

                        </span>

                    </div>

                </div>

                <div style="padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.25); font-size: 13px; font-weight: 500; opacity: 0.9;">

                    Smooth checkout experience 

                </div>

            </div>



            <div class="sensfrx-stat-card" style="background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%); color: white; padding: 24px; border-radius: 12px;">

                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">

                    <div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 10px;">

                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                            <circle cx="12" cy="12" r="10" stroke="white" stroke-width="2"/>

                            <path d="M12 6v6l4 2" stroke="white" stroke-width="2" stroke-linecap="round"/>

                        </svg>

                    </div>

                </div>

                <div style="font-size: 36px; font-weight: 800; margin-bottom: 6px; letter-spacing: -1px;">

                    <span id="time-saved-value">--</span> <span style="font-size: 20px; font-weight: 600; opacity: 0.9;">Hours</span>

                </div>

                <div style="font-size: 14px; font-weight: 500; opacity: 0.95; margin-bottom: 14px; display: flex; align-items: center; gap: 6px;">

                    Time Saved

                    <div class="sensfrx-tooltip" style="position: relative; display: inline-flex;">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="cursor: help; opacity: 0.8;">

                            <circle cx="8" cy="8" r="7" stroke="white" stroke-width="1.5"/>

                            <path d="M8 11v-1m0-4h.01M8 4a4 4 0 00-4 4" stroke="white" stroke-width="1.5" stroke-linecap="round"/>

                        </svg>

                        <span class="sensfrx-tooltiptext" style="visibility: hidden; background: rgba(0,0,0,0.95); color: #fff; text-align: left; padding: 12px 14px; border-radius: 8px; position: absolute; z-index: 1000; bottom: 125%; left: 50%; margin-left: -140px; width: 280px; font-size: 12px; line-height: 1.5; opacity: 0; transition: opacity 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">

                            <strong style="display: block; margin-bottom: 6px; color: #8B5CF6;">Time saved this month</strong>

                            Time saved by reducing manual fraud reviews. Each automated decision saves ~5 minutes of review time.<br><br>

                            More automation means:<br>

                            • Less time reviewing cases<br>

                            • More time growing your business<br>

                            • Faster customer experience

                        </span>

                    </div>

                </div>

                <div style="padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.25); font-size: 13px; font-weight: 500; opacity: 0.9;" id="cases-handled-text">

                    Manual reviews avoided

                </div>

            </div>

        </div>



        <?php

        /*

        ============================================================

        ONE-CLICK PROTECTION SECTION - TEMPORARILY DISABLED

        Will be re-enabled in future release

        ============================================================



        <!-- Quick Templates -->

        <div class="sensfrx-card" style="margin-bottom: 28px; padding: 24px; background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%); border: 2px solid #E2E8F0; border-radius: 12px;">

            <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">

                <div style="background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center;">

                    <svg width="22" height="22" viewBox="0 0 22 22" fill="none">

                        <path d="M13 3L4 14h7l-1 6 9-11h-7l1-6z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <div>

                    <h3 style="margin: 0 0 2px; font-size: 18px; font-weight: 700; color: #111827;">One-Click Protection</h3>

                    <p style="margin: 0; font-size: 14px; color: #64748B;">Set up professional fraud protection instantly</p>

                </div>

            </div>



            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px;">

                

                <div class="sensfrx-template" onclick="applyTemplate('disposable')" style="background: white; padding: 18px; border: 2px solid #E5E7EB; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                    <div style="display: flex; gap: 14px;">

                        <div style="background: #D1FAE5; width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" stroke="#10B981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <div style="flex: 1;">

                            <h4 style="margin: 0 0 6px; font-size: 15px; font-weight: 600; color: #111827;">Block Disposable Emails</h4>

                            <p style="margin: 0 0 10px; font-size: 13px; color: #6B7280; line-height: 1.5;">Block 20+ temporary email services used by fraudsters. SFX detects throw-away accounts instantly.</p>

                            <span style="display: inline-block; padding: 4px 10px; background: #DBEAFE; color: #166534; border-radius: 6px; font-size: 12px; font-weight: 600;">Recommended by SFX</span>

                        </div>

                    </div>

                </div>



                <div class="sensfrx-template" onclick="applyTemplate('vpn')" style="background: white; padding: 18px; border: 2px solid #E5E7EB; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                    <div style="display: flex; gap: 14px;">

                        <div style="background: #FEE2E2; width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" stroke="#DC2626" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <div style="flex: 1;">

                            <h4 style="margin: 0 0 6px; font-size: 15px; font-weight: 600; color: #111827;">Block VPN & Proxy IPs</h4>

                            <p style="margin: 0 0 10px; font-size: 13px; color: #6B7280; line-height: 1.5;">Block known VPN and proxy IP addresses from 15 major providers. This creates individual IP blocking rules to prevent anonymous fraudulent activity.</p>

                            <span style="display: inline-block; padding: 4px 10px; background: #EDE9FE; color: #6D28D9; border-radius: 6px; font-size: 12px; font-weight: 600;">⚡ Creates ~400 rules</span>

                        </div>

                    </div>

                </div>



                <div class="sensfrx-template" onclick="applyTemplate('trusted')" style="background: white; padding: 18px; border: 2px solid #E5E7EB; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                    <div style="display: flex; gap: 14px;">

                        <div style="background: #DBEAFE; width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M5 13l4 4L19 7" stroke="#2563EB" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <div style="flex: 1;">

                            <h4 style="margin: 0 0 6px; font-size: 15px; font-weight: 600; color: #111827;">VIP Customer List</h4>

                            <p style="margin: 0 0 10px; font-size: 13px; color: #6B7280; line-height: 1.5;">Whitelist trusted customers to bypass all SFX fraud checks. Zero friction for your best customers.</p>

                            <span style="display: inline-block; padding: 4px 10px; background: #E0E7FF; color: #3730A3; border-radius: 6px; font-size: 12px; font-weight: 600;">SFX Best Practice</span>

                        </div>

                    </div>

                </div>

            </div>

        </div>

        

        ============================================================

        END OF ONE-CLICK PROTECTION SECTION

        ============================================================

        */

        ?>



        <!-- Tab Navigation -->

        <div style="background: white; border-radius: 12px; padding: 0; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.08);">

            <div style="border-bottom: 2px solid #F1F5F9; display: flex; gap: 4px; padding: 0 20px;">

                <button class="sfx-policy-tab sfx-tab-active" data-tab="blacklist-whitelist" style="background: transparent; border: none; padding: 16px 24px; font-size: 15px; font-weight: 600; color: #6B7280; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.2s; display: flex; align-items: center; gap: 8px;">

                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">

                        <path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.040A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" stroke="currentColor" stroke-width="1.8"/>

                    </svg>

                    Block & Allow Lists

                </button>

                <button class="sfx-policy-tab" data-tab="default-policies" style="background: transparent; border: none; padding: 16px 24px; font-size: 15px; font-weight: 600; color: #6B7280; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.2s; display: flex; align-items: center; gap: 8px;">

                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">

                        <path d="M9 11l3 3L22 4M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" stroke="currentColor" stroke-width="1.8"/>

                    </svg>

                    Smart Protection

                    <span id="smart-protection-count" style="background: #2563EB; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 700;">0</span>

                </button>

                <button class="sfx-policy-tab" data-tab="advanced-policies" style="background: transparent; border: none; padding: 16px 24px; font-size: 15px; font-weight: 600; color: #6B7280; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.2s; display: flex; align-items: center; gap: 8px;">

                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">

                        <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="currentColor" stroke-width="1.8"/>

                    </svg>

                    AI Protection

                    <span id="ai-protection-count" style="background: #2563EB; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 700;">0</span>

                </button>

            </div>

        </div>



        <style>

        .sfx-policy-tab:hover {

            color: #2563EB !important;

            background: #F0FDF4 !important;

        }

        .sfx-policy-tab.sfx-tab-active {

            color: #2563EB !important;

            border-bottom-color: #2563EB !important;

            background: #F0FDF4 !important;

        }

        .sfx-tab-content {

            display: none;

        }

        .sfx-tab-content.sfx-tab-active {

            display: block;

        }

        

@keyframes slideInRight {

    from {

        transform: translateX(400px);

        opacity: 0;

    }

    to {

        transform: translateX(0);

        opacity: 1;

    }

}





/* Success Checkmark Animation */

@keyframes checkmark {

    0% {

        stroke-dashoffset: 50;

    }

    100% {

        stroke-dashoffset: 0;

    }

}



.toast-checkmark {

    stroke-dasharray: 50;

    stroke-dashoffset: 50;

    animation: checkmark 0.3s ease-in-out 0.1s forwards;

}



@keyframes fadeOut {

    from {

        opacity: 1;

    }

    to {

        opacity: 0;

        transform: translateX(400px);

    }

}



/* Tooltip styles */

.sfx-tooltip {

    position: relative;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    width: 18px;

    height: 18px;

    background: #E5E7EB;

    border-radius: 50%;

    cursor: help;

    margin-left: 6px;

    font-size: 12px;

    color: #6B7280;

    font-weight: 600;

}



.sfx-tooltip:hover::after {

    content: attr(data-tip);

    position: absolute;

    bottom: calc(100% + 8px);

    left: 50%;

    transform: translateX(-50%);

    background: #1F2937;

    color: white;

    padding: 8px 12px;

    border-radius: 6px;

    font-size: 13px;

    font-weight: 500;

    white-space: nowrap;

    z-index: 1000;

    box-shadow: 0 4px 12px rgba(0,0,0,0.15);

}



.sfx-tooltip:hover::before {

    content: '';

    position: absolute;

    bottom: calc(100% + 2px);

    left: 50%;

    transform: translateX(-50%);

    border: 6px solid transparent;

    border-top-color: #1F2937;

    z-index: 1001;

}



/* Enhanced Button Hover States */

.sensfrx-btn-primary:hover {

    transform: translateY(-1px);

    box-shadow: 0 6px 12px rgba(37, 99, 235, 0.35) !important;

    transition: all 0.2s ease;

}



.sensfrx-btn-primary:active {

    transform: translateY(0);

    box-shadow: 0 4px 6px rgba(37, 99, 235, 0.25) !important;

}



/* Template Button Hover - DISABLED (One-Click Protection not active) */

/*

button[onclick*="applyTemplate"]:hover {

    transform: translateY(-2px);

    box-shadow: 0 8px 16px rgba(0,0,0,0.1) !important;

    transition: all 0.2s ease;

}

*/



/* Stat Card Hover */

.sensfrx-stat-card {

    transition: transform 0.2s ease, box-shadow 0.2s ease;

}



.sensfrx-stat-card:hover {

    transform: translateY(-2px);

    box-shadow: 0 12px 24px rgba(0,0,0,0.15) !important;

}



/* Table Row Hover */

table tbody tr {

    transition: background-color 0.15s ease;

}



table tbody tr:hover {

    background-color: #F9FAFB !important;

}



/* Search/Filter Input Focus */

input[type="text"]:focus,

input[type="number"]:focus,

select:focus {

    outline: none;

    border-color: #2563EB !important;

    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1) !important;

    transition: all 0.2s ease;

}



/* Policy Action Dropdown Focus */

.sfx-policy-action:focus {

    outline: none;

    border-color: #2563EB !important;

    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1) !important;

}

</style>



        <!-- Tab 1: Blacklist/Whitelist -->

        <div class="sfx-tab-content sfx-tab-active" id="blacklist-whitelist">

        <!-- Quota Usage Display -->

        <div class="sensfrx-card" style="padding: 16px 20px; margin-bottom: 20px; background: linear-gradient(135deg, #F0FDF4 0%, #DBEAFE 100%); border: 2px solid #3B82F6;">

            <div id="quota-usage-display" style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">

                <div style="display: flex; align-items: center; gap: 12px;">

                    <div style="background: white; padding: 8px; border-radius: 8px;">

                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                            <path d="M12 2v20M17 12a5 5 0 11-10 0 5 5 0 0110 0z" stroke="#2563EB" stroke-width="2" stroke-linecap="round"/>

                        </svg>

                    </div>

                    <div>

                        <div style="font-size: 13px; color: #6B7280; margin-bottom: 2px;">Block & Allow List Usage</div>

                        <div id="quota-usage-text" style="font-size: 16px; font-weight: 700; color: #1E40AF;">Loading...</div>

                    </div>

                </div>

                <div style="font-size: 13px; color: #6B7280;">

                    Plan: <strong id="quota-plan-name" style="color: #1E40AF;">-</strong>

                </div>

            </div>

        </div>



            <!-- Main Content Card -->

            <div class="sensfrx-card" style="margin-bottom: 24px;">

                <!-- Header Section -->

                <div style="padding: 24px 28px; border-bottom: 1px solid #F1F5F9; display: flex; justify-content: space-between; align-items: center;">

                    <div>

                        <h3 style="margin: 0 0 4px; font-size: 20px; font-weight: 700; color: #111827;">Custom Block & Allow Rules</h3><span class="sfx-tooltip" data-tip="Create your own rules to block or allow specific IPs, emails, and more">?</span>

                        <p style="margin: 0; font-size: 14px; color: #6B7280;">Add custom rules to block fraudsters or whitelist trusted customers</p>

                    </div>

                    <div style="display: flex; gap: 12px;">

                        <button class="sensfrx-btn-primary" onclick="openRuleModal()" style="padding: 12px 24px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px; box-shadow: 0 4px 6px rgba(37, 99, 235, 0.25);">

                            <svg width="18" height="18" viewBox="0 0 20 20" fill="none">

                                <path d="M10 4v12M4 10h12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>

                            </svg>

                            Create Rule

                        </button>

                    </div>

                </div>



                <div style="padding: 20px 28px;">

                    <!-- Rules Active Statistics -->

                    <div id="rules-active-stats" style="display: none; margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, #F0F9FF 0%, #E0F2FE 100%); border-radius: 10px; border: 1px solid #BAE6FD;">

                        <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px;">

                            <div style="display: flex; gap: 24px;">

                                <div>

                                    <div style="font-size: 24px; font-weight: 700; color: #0369A1;" id="total-custom-rules">0</div>

                                    <div style="font-size: 12px; color: #075985;">Total Rules</div>

                                </div>

                                <div style="border-left: 2px solid #BAE6FD; padding-left: 24px;">

                                    <div style="font-size: 13px; color: #075985;"><span id="active-block-rules" style="font-weight: 700; color: #DC2626;">0</span> Blocking</div>

                                    <div style="font-size: 13px; color: #075985;"><span id="active-allow-rules" style="font-weight: 700; color: #10B981;">0</span> Allowing</div>

                                </div>

                            </div>

                            <div style="font-size: 12px; color: #0369A1;">

                                Protection Level: <span id="custom-protection-level" style="font-weight: 700;">Custom</span>

                            </div>

                        </div>

                    </div>



                    <!-- Search & Filter Bar -->

                    <div style="margin-bottom: 16px; display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">

                <div style="flex: 1; min-width: 280px; position: relative;">

                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style="position: absolute; left: 14px; top: 50%; transform: translateY(-50%); pointer-events: none;">

                        <circle cx="8" cy="8" r="6" stroke="#9CA3AF" stroke-width="1.5"/>

                        <path d="M12.5 12.5l3.5 3.5" stroke="#9CA3AF" stroke-width="1.5" stroke-linecap="round"/>

                    </svg>

                    <input type="text" id="rules-search" placeholder="Search by IP, email, user ID..." style="width: 100%; padding: 11px 14px 11px 42px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;" onkeyup="filterRules()">

                </div>

                <select id="filter-type" onchange="filterRules()" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                    <option value="">All Types</option>

                    <option value="ip">IP Address</option>

                    <option value="ue">Email</option>

                    <option value="uID">User ID</option>

                    <option value="un">Username</option>

                </select>

                <select id="filter-action" onchange="filterRules()" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                    <option value="">All Responses</option>

                    <option value="block">Block</option>

                    <option value="allow">Allow</option>

                </select>

                <button id="delete-selected-btn" onclick="deleteSelectedRules()" style="padding: 11px 18px; background: #FEE2E2; color: #DC2626; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: none;">

                    Delete Selected (<span id="selected-count">0</span>)

                </button>

        </div>



        <!-- Rules Table -->

                    <div>

            <div id="rules-loading" style="text-align: center; padding: 60px 20px;">

                <div style="width: 50px; height: 50px; border: 4px solid #F3F4F6; border-top-color: #2563EB; border-radius: 50%; margin: 0 auto 20px; animation: spin 0.8s linear infinite;"></div>

                <div style="font-size: 15px; color: #6B7280; font-weight: 500;">Loading your protection rules...</div>

            </div>



            <div id="rules-empty" style="display: none; text-align: center; padding: 60px 30px;">

                <div style="background: linear-gradient(135deg, #F0FDF4 0%, #DBEAFE 100%); width: 100px; height: 100px; border-radius: 50%; margin: 0 auto 24px; display: flex; align-items: center; justify-content: center;">

                    <svg width="50" height="50" viewBox="0 0 50 50" fill="none">

                        <path d="M25 15v20M15 25h20" stroke="#2563EB" stroke-width="4" stroke-linecap="round"/>

                    </svg>

                </div>

                <h3 style="margin: 0 0 10px; font-size: 22px; font-weight: 700; color: #111827;">👋 Ready to Add Protection?</h3>

                            <p style="margin: 0 0 28px; font-size: 15px; color: #6B7280; max-width: 440px; margin-left: auto; margin-right: auto; line-height: 1.6;">Create custom rules for your specific needs - block known fraudsters or whitelist trusted customers.</p>

                <button onclick="openRuleModal()" style="padding: 12px 28px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);">

                    + Add Your First Rule

                </button>

            </div>



            <div id="rules-content" style="display: none;">

                <div style="overflow-x: auto;">

                    <table style="width: 100%; border-collapse: collapse;">

                        <thead style="background: #F9FAFB;">

                            <tr>

                                <th style="padding: 16px 20px; text-align: left; width: 50px;">

                                    <input type="checkbox" id="select-all-rules" onchange="toggleSelectAll()" style="width: 18px; height: 18px; cursor: pointer;">

                                </th>

                                <th style="padding: 16px 20px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">What to Check</th>

                                <th style="padding: 16px 20px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Block/Allow This</th>

                                <th style="padding: 16px 20px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Action</th>

                                <!-- <th style="padding: 16px 20px; text-align: center; font-weight: 600; font-size: 13px; color: #6B7280;">How Well It Works</th> -->

                                <th style="padding: 16px 20px; text-align: right; font-weight: 600; font-size: 13px; color: #6B7280;">Actions</th>

                            </tr>

                        </thead>

                        <tbody id="rules-table-body"></tbody>

                    </table>

                </div>

            </div>

        </div>

                </div>

            </div>

        </div>

        <!-- End Tab 1: Blacklist/Whitelist -->



        <!-- Tab 2: Smart Protection (39 Rules) -->

        <div class="sfx-tab-content" id="default-policies">

            <!-- Quota Usage Display -->

            <div class="sensfrx-card" style="padding: 16px 20px; margin-bottom: 20px; background: linear-gradient(135deg, #F0FDF4 0%, #DBEAFE 100%); border: 2px solid #3B82F6;">

                <div id="default-quota-display" style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">

                    <div style="display: flex; align-items: center; gap: 12px;">

                        <div style="background: white; padding: 8px; border-radius: 8px;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M9 11l3 3L22 4M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" stroke="#2563EB" stroke-width="1.8"/>

                            </svg>

                        </div>

                        <div>

                            <div style="font-size: 13px; color: #6B7280; margin-bottom: 2px;">Smart Protection Usage</div>

                            <div id="default-quota-text" style="font-size: 16px; font-weight: 700; color: #1E40AF;">Loading...</div>

                        </div>

                    </div>

                    <div style="font-size: 13px; color: #6B7280;">

                        Plan: <strong id="default-plan-name" style="color: #1E40AF;">-</strong>

                    </div>

                </div>

            </div>



            <div class="sensfrx-card" style="margin-bottom: 24px;">

                <div style="padding: 24px 28px; border-bottom: 1px solid #F1F5F9; display: flex; justify-content: space-between; align-items: center;">

                    <div>

                        <h3 style="margin: 0 0 4px; font-size: 20px; font-weight: 700; color: #111827;">Default Fraud Detection Policies</h3><span class="sfx-tooltip" data-tip="Pre-built rules that look for common fraud patterns">?</span>

                        <p style="margin: 0; font-size: 14px; color: #6B7280;">Turn on/off smart protections - each rule looks for specific fraud patterns</p>

                    </div>

                    <div style="display: flex; gap: 12px;">

                        <button id="bulk-enable-default" onclick="bulkToggleDefault(true)" style="padding: 10px 18px; background: #DBEAFE; color: #2563EB; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: none;">

                            Enable Selected (<span id="default-selected-count">0</span>)

                        </button>

                        <button id="bulk-disable-default" onclick="bulkToggleDefault(false)" style="padding: 10px 18px; background: #FEE2E2; color: #DC2626; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: none;">

                            Disable Selected (<span id="default-selected-count-2">0</span>)

                        </button>

                        <button id="save-default-policies" style="padding: 12px 24px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;">

                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">

                                <path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/>

                            </svg>

                            Save Changes

                        </button>

                    </div>

                </div>



                <div style="padding: 20px 28px;">

                    <!-- Statistics Summary -->

                    <div id="default-stats" style="display: none; margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, #F0F9FF 0%, #E0F2FE 100%); border-radius: 10px; border: 1px solid #BAE6FD;">

                        <div style="display: flex; align-items: center; justify-content: space-between;">

                            <div style="display: flex; gap: 24px;">

                                <div>

                                    <div style="font-size: 24px; font-weight: 700; color: #0369A1;" id="default-enabled-count">0</div>

                                    <div style="font-size: 12px; color: #075985;">Rules Active</div>

                                </div>

                                <div style="border-left: 2px solid #BAE6FD; padding-left: 24px;">

                                    <div style="font-size: 13px; color: #075985;"><span id="default-high-risk-count" style="font-weight: 700;">0</span> High Risk</div>

                                    <div style="font-size: 13px; color: #075985;"><span id="default-tags-count" style="font-weight: 700;">0</span> Categories</div>

                                </div>

                            </div>

                            <div style="font-size: 12px; color: #0369A1;">

                                Protection Level: <span id="default-protection-level" style="font-weight: 700;">Setting up...</span>

                            </div>

                        </div>

                    </div>



                    <!-- Search & Filters -->

                    <div style="margin-bottom: 16px; display: flex; flex-wrap: wrap; gap: 12px;">

                        <div style="flex: 1; min-width: 250px; position: relative;">

                            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style="position: absolute; left: 14px; top: 50%; transform: translateY(-50%);">

                                <circle cx="8" cy="8" r="6" stroke="#9CA3AF" stroke-width="1.5"/>

                                <path d="M12.5 12.5l3.5 3.5" stroke="#9CA3AF" stroke-width="1.5" stroke-linecap="round"/>

                            </svg>

                            <input type="text" id="search-default" placeholder="Search policies..." style="width: 100%; padding: 11px 14px 11px 42px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;" oninput="filterDefaultPolicies()">

                        </div>

                        <select id="filter-default-tag" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;" onchange="filterDefaultPolicies()">

                            <option value="">All Categories</option>

                            <option value="Account Security">Account Security</option>

                            <option value="Transaction">Transaction</option>

                            <option value="Registration">Registration</option>

                        </select>

                        <select id="filter-default-risk" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;" onchange="filterDefaultPolicies()">

                            <option value="">All Risk Levels</option>

                            <option value="reject">High Risk (Block)</option>

                            <option value="review">Medium Risk (Review)</option>

                            <option value="approve">Low Risk (Approve)</option>

                        </select>

                        <select id="filter-default-status" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;" onchange="filterDefaultPolicies()">

                            <option value="">All Status</option>

                            <option value="1">Active</option>

                            <option value="0">Inactive</option>

                        </select>

                    </div>



                    <!-- Bulk Actions -->

                    <div style="margin-bottom: 20px; padding: 14px; background: #F9FAFB; border-radius: 8px; border: 1px solid #E5E7EB;">

                        <div style="font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 10px;">Quick Actions</div>

                        <div style="display: flex; flex-wrap: wrap; gap: 8px;">

                            <button onclick="bulkActionDefault('enable-high-risk')" style="padding: 8px 14px; background: white; border: 1.5px solid #DC2626; color: #DC2626; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                Enable High Risk (Block)

                            </button>

                            <button onclick="bulkActionDefault('enable-account')" style="padding: 8px 14px; background: white; border: 1.5px solid #2563EB; color: #2563EB; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                Enable Account Security

                            </button>

                            <button onclick="bulkActionDefault('enable-transaction')" style="padding: 8px 14px; background: white; border: 1.5px solid #2563EB; color: #2563EB; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                Enable Transaction Rules

                            </button>

                            <button onclick="bulkActionDefault('enable-all')" style="padding: 8px 14px; background: white; border: 1.5px solid #059669; color: #059669; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                Enable All

                            </button>

                            <button onclick="bulkActionDefault('disable-all')" style="padding: 8px 14px; background: white; border: 1.5px solid #6B7280; color: #6B7280; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                Disable All

                            </button>

                        </div>

                    </div>



                    <div id="default-policies-loading" style="text-align: center; padding: 40px;">

                        <div style="width: 50px; height: 50px; border: 4px solid #F3F4F6; border-top-color: #2563EB; border-radius: 50%; margin: 0 auto 16px; animation: spin 0.8s linear infinite;"></div>

                        <div style="font-size: 15px; color: #6B7280;">Loading default policies...</div>

                    </div>



                    <div id="default-policies-table" style="display: none; overflow-x: auto;">

                        <table style="width: 100%; border-collapse: collapse;">

                            <thead style="background: #F9FAFB;">

                                <tr>

                                    <th style="padding: 14px 16px; text-align: left; width: 50px;">

                                        <input type="checkbox" id="select-all-default" onchange="toggleSelectAllDefault()" style="width: 18px; height: 18px; cursor: pointer;">

                                    </th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Policy</th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Description</th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Platform</th>

                                    <th style="padding: 16px 20px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Action</th>

                                    <th style="padding: 14px 16px; text-align: center; font-weight: 600; font-size: 13px; color: #6B7280;">Score</th>

                                    <th style="padding: 14px 16px; text-align: center; font-weight: 600; font-size: 13px; color: #6B7280;">Active</th>

                                </tr>

                            </thead>

                            <tbody id="default-policies-tbody"></tbody>

                        </table>

                    </div>

                </div>

            </div>

        </div>



        <!-- Tab 3: AI Protection (17 Rules) -->

        <div class="sfx-tab-content" id="advanced-policies">

            <!-- Quota Usage Display -->

            <div class="sensfrx-card" style="padding: 16px 20px; margin-bottom: 20px; background: linear-gradient(135deg, #F5F3FF 0%, #EDE9FE 100%); border: 2px solid #7C3AED;">

                <div id="advanced-quota-display" style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">

                    <div style="display: flex; align-items: center; gap: 12px;">

                        <div style="background: white; padding: 8px; border-radius: 8px;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#7C3AED" stroke-width="1.8"/>

                            </svg>

                        </div>

                        <div>

                            <div style="font-size: 13px; color: #6B7280; margin-bottom: 2px;">AI Protection Usage</div>

                            <div id="advanced-quota-text" style="font-size: 16px; font-weight: 700; color: #6D28D9;">Loading...</div>

                        </div>

                    </div>

                    <div style="font-size: 13px; color: #6B7280;">

                        Plan: <strong id="advanced-plan-name" style="color: #6D28D9;">-</strong>

                    </div>

                </div>

            </div>



            <!-- Upgrade Banner for Free Plan Users -->

            <div id="ai-protection-upgrade-banner" style="display: none; margin-bottom: 20px;">

                <div class="sensfrx-card" style="background: linear-gradient(135deg, #FEFCE8 0%, #FEF9C3 100%); border: 2px solid #EAB308; overflow: hidden; position: relative;">

                    <div style="padding: 24px 28px; position: relative; z-index: 1;">

                        <div style="display: flex; align-items: start; gap: 20px;">

                            <div style="flex-shrink: 0; width: 48px; height: 48px; background: white; border-radius: 12px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">

                                <svg width="28" height="28" viewBox="0 0 24 24" fill="none">

                                    <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" fill="#EAB308" stroke="#CA8A04" stroke-width="1.5"/>

                                </svg>

                            </div>

                            <div style="flex: 1;">

                                <h3 style="margin: 0 0 8px; font-size: 18px; font-weight: 700; color: #854D0E;">AI Protection Available on Pro Plans</h3>

                                <p style="margin: 0 0 16px; font-size: 14px; color: #713F12; line-height: 1.6;">

                                    Advanced AI-powered fraud detection policies leverage machine learning to identify sophisticated fraud patterns. Upgrade to Pro, Growth, Business, or Enterprise to enable these 17 advanced protection rules.

                                </p>

                                <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: center;">

                                    <a href="<?php echo esc_url(get_option('sensfrx_upgrade_url', 'https://client.sensfrx.ai/account/upgrade-plan')); ?>" target="_blank" style="display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; background: #EAB308; color: white; text-decoration: none; border-radius: 8px; font-size: 14px; font-weight: 600; box-shadow: 0 4px 6px -1px rgba(234, 179, 8, 0.3); transition: all 0.2s;">

                                        <span>View Plan Options</span>

                                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                            <path d="M6 3l5 5-5 5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </a>

                                    <div style="font-size: 13px; color: #92400E;">

                                        <strong>Pro Plan:</strong> $29/month • 17 AI Policies • 2,000 Credits

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>

                    <div style="position: absolute; right: -20px; bottom: -20px; width: 120px; height: 120px; background: radial-gradient(circle, rgba(234, 179, 8, 0.15) 0%, transparent 70%); border-radius: 50%;"></div>

                </div>

            </div>



            <div class="sensfrx-card" style="margin-bottom: 24px;">

                <div style="padding: 24px 28px; border-bottom: 1px solid #F1F5F9; display: flex; justify-content: space-between; align-items: center;">

                    <div>

                        <h3 style="margin: 0 0 4px; font-size: 20px; font-weight: 700; color: #111827;">Advanced Fraud Detection Policies</h3>

                        <p style="margin: 0; font-size: 14px; color: #6B7280;">Configure 17 ML-powered fraud detection policies</p>

                    </div>

                    <div style="display: flex; gap: 12px;">

                        <button id="bulk-enable-advanced" onclick="bulkToggleAdvanced(true)" style="padding: 10px 18px; background: #EDE9FE; color: #7C3AED; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: none;">

                            Enable Selected (<span id="advanced-selected-count">0</span>)

                        </button>

                        <button id="bulk-disable-advanced" onclick="bulkToggleAdvanced(false)" style="padding: 10px 18px; background: #FEE2E2; color: #DC2626; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: none;">

                            Disable Selected (<span id="advanced-selected-count-2">0</span>)

                        </button>

                        <button id="save-advanced-policies" style="padding: 12px 24px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;">

                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">

                                <path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/>

                            </svg>

                            Save Changes

                        </button>

                    </div>

                </div>



                <div style="padding: 20px 28px;">

                    <!-- Statistics Summary -->

                    <div id="advanced-stats" style="display: none; margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, #F5F3FF 0%, #EDE9FE 100%); border-radius: 10px; border: 1px solid #DDD6FE;">

                        <div style="display: flex; align-items: center; justify-content: space-between;">

                            <div style="display: flex; gap: 24px;">

                                <div>

                                    <div style="font-size: 24px; font-weight: 700; color: #6D28D9;" id="advanced-enabled-count">0</div>

                                    <div style="font-size: 12px; color: #7C3AED;">AI Rules Active</div>

                                </div>

                                <div style="border-left: 2px solid #DDD6FE; padding-left: 24px;">

                                    <div style="font-size: 13px; color: #7C3AED;"><span id="advanced-high-risk-count" style="font-weight: 700;">0</span> High Risk</div>

                                    <div style="font-size: 13px; color: #7C3AED;"><span id="advanced-tags-count" style="font-weight: 700;">0</span> Categories</div>

                                </div>

                            </div>

                            <div style="font-size: 12px; color: #6D28D9;">

                                AI Protection: <span id="advanced-protection-level" style="font-weight: 700;">Setting up...</span>

                            </div>

                        </div>

                    </div>



                    <!-- Search & Filters -->

                    <div style="margin-bottom: 16px; display: flex; flex-wrap: wrap; gap: 12px;">

                        <div style="flex: 1; min-width: 250px; position: relative;">

                            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style="position: absolute; left: 14px; top: 50%; transform: translateY(-50%);">

                                <circle cx="8" cy="8" r="6" stroke="#9CA3AF" stroke-width="1.5"/>

                                <path d="M12.5 12.5l3.5 3.5" stroke="#9CA3AF" stroke-width="1.5" stroke-linecap="round"/>

                            </svg>

                            <input type="text" id="search-advanced" placeholder="Search policies..." oninput="filterAdvancedPolicies()" style="width: 100%; padding: 11px 14px 11px 42px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                        </div>

                        <select id="filter-advanced-tag" onchange="filterAdvancedPolicies()" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                            <option value="">All Categories</option>

                            <option value="Account Security">Account Security</option>

                            <option value="Transaction">Transaction</option>

                            <option value="Registration">Registration</option>

                        </select>

                        <select id="filter-advanced-risk" onchange="filterAdvancedPolicies()" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                            <option value="">All Risk Levels</option>

                            <option value="reject">High Risk (Block)</option>

                            <option value="review">Medium Risk (Review)</option>

                            <option value="approve">Low Risk (Approve)</option>

                        </select>

                        <select id="filter-advanced-status" onchange="filterAdvancedPolicies()" style="padding: 11px 14px; border: 1.5px solid #E5E7EB; border-radius: 8px; font-size: 14px;">

                            <option value="">All Status</option>

                            <option value="1">Active</option>

                            <option value="0">Inactive</option>

                        </select>

                    </div>



                    <!-- Bulk Actions -->

                    <div style="margin-bottom: 20px; padding: 14px; background: #F9FAFB; border-radius: 8px; border: 1px solid #E5E7EB;">

                        <div style="font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 10px;">Quick Actions</div>

                        <div style="display: flex; flex-wrap: wrap; gap: 8px;">

                            <button onclick="bulkActionAdvanced('enable-high-risk')" style="padding: 8px 14px; background: white; border: 1.5px solid #DC2626; color: #DC2626; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer;">

                                Enable High Risk (Block)

                            </button>

                            <button onclick="bulkActionAdvanced('enable-account')" style="padding: 8px 14px; background: white; border: 1.5px solid #2563EB; color: #2563EB; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer;">

                                Enable Account Security

                            </button>

                            <button onclick="bulkActionAdvanced('enable-transaction')" style="padding: 8px 14px; background: white; border: 1.5px solid #10B981; color: #10B981; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer;">

                                Enable Transaction Rules

                            </button>

                            <button onclick="bulkActionAdvanced('enable-all')" style="padding: 8px 14px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); border: none; color: white; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer;">

                                Enable All

                            </button>

                            <button onclick="bulkActionAdvanced('disable-all')" style="padding: 8px 14px; background: white; border: 1.5px solid #DC2626; color: #DC2626; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer;">

                                Disable All

                            </button>

                        </div>

                    </div>



                    <div id="advanced-policies-loading" style="text-align: center; padding: 40px;">

                        <div style="width: 50px; height: 50px; border: 4px solid #F3F4F6; border-top-color: #2563EB; border-radius: 50%; margin: 0 auto 16px; animation: spin 0.8s linear infinite;"></div>

                        <div style="font-size: 15px; color: #6B7280;">Loading advanced policies...</div>

                    </div>



                    <div id="advanced-policies-table" style="display: none; overflow-x: auto;">

                        <table style="width: 100%; border-collapse: collapse;">

                            <thead style="background: #F9FAFB;">

                                <tr>

                                    <th style="padding: 14px 16px; text-align: left; width: 50px;">

                                        <input type="checkbox" id="select-all-advanced" onchange="toggleSelectAllAdvanced()" style="width: 18px; height: 18px; cursor: pointer;">

                                    </th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Policy</th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Description</th>

                                    <th style="padding: 14px 16px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Platform</th>

                                    <th style="padding: 16px 20px; text-align: left; font-weight: 600; font-size: 13px; color: #6B7280;">Action</th>

                                    <th style="padding: 14px 16px; text-align: center; font-weight: 600; font-size: 13px; color: #6B7280;">Score</th>

                                    <th style="padding: 14px 16px; text-align: center; font-weight: 600; font-size: 13px; color: #6B7280;">Active</th>

                                </tr>

                            </thead>

                            <tbody id="advanced-policies-tbody"></tbody>

                        </table>

                    </div>

                </div>

            </div>

        </div>



    </div>

</div>



<!-- Rule Modal (continued in next part due to size) -->



<!-- Rule Creation Modal -->

<div id="rule-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); z-index: 999999; align-items: center; justify-content: center; backdrop-filter: blur(4px);">

    <div style="background: white; border-radius: 16px; max-width: 580px; width: 92%; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px rgba(0,0,0,0.25);">

        <div style="padding: 28px 32px; border-bottom: 1px solid #E5E7EB;">

            <div style="display: flex; justify-content: space-between; align-items: center;">

                <div>

                    <h3 style="margin: 0 0 4px; font-size: 22px; font-weight: 700; color: #111827;">Create Protection Rule</h3>

                    <p style="margin: 0; font-size: 14px; color: #6B7280;">Define who to block or allow</p>

                </div>

                <button onclick="closeRuleModal()" style="background: #F3F4F6; width: 36px; height: 36px; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s;">

                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">

                        <path d="M6 6l8 8M6 14l8-8" stroke="#6B7280" stroke-width="2" stroke-linecap="round"/>

                    </svg>

                </button>

            </div>

        </div>



        <form id="rule-form" style="padding: 28px 32px;">

            <div style="margin-bottom: 22px;">

                <label style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; color: #374151;">Rule Type</label>

                <select id="rule-type" required style="width: 100%; padding: 12px 14px; border: 1.5px solid #D1D5DB; border-radius: 8px; font-size: 14px; background: white;">

                    <option value="">Select what to match...</option>

                    <option value="ip">IP Address</option>

                    <option value="ue">Email Address</option>

                    <option value="uID">User ID</option>

                    <option value="un">Username</option>

                </select>

            </div>



            <div style="margin-bottom: 22px;">

                <label style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; color: #374151;">What to Block or Allow</label>

                <input type="text" id="rule-pattern" required placeholder="e.g., 192.168.*.*, *@tempmail.com" style="width: 100%; padding: 12px 14px; border: 1.5px solid #D1D5DB; border-radius: 8px; font-size: 14px;">

                <p style="margin: 6px 0 0; color: #6B7280; font-size: 13px;">Tip: Use * as wildcard (e\.g\., \*@gmail\.com)</p>

            </div>



            <div style="margin-bottom: 22px;">

                <label style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; color: #374151;">Action</label>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">

                    <label style="padding: 14px; border: 2px solid #E5E7EB; border-radius: 10px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 10px;">

                        <input type="radio" name="rule-action" value="block" id="action-block" required style="width: 18px; height: 18px;">

                        <div>

                            <div style="font-weight: 600; font-size: 14px; color: #DC2626;">Block</div>

                            <div style="font-size: 12px; color: #6B7280;">Stop them</div>

                        </div>

                    </label>

                    <label style="padding: 14px; border: 2px solid #E5E7EB; border-radius: 10px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 10px;">

                        <input type="radio" name="rule-action" value="allow" id="action-allow" required style="width: 18px; height: 18px;">

                        <div>

                            <div style="font-weight: 600; font-size: 14px; color: #2563EB;">Allow</div>

                            <div style="font-size: 12px; color: #6B7280;">Always allow</div>

                        </div>

                    </label>

                </div>

            </div>



            <div style="display: flex; gap: 12px; margin-top: 28px; padding-top: 24px; border-top: 1px solid #E5E7EB;">

                <button type="button" onclick="closeRuleModal()" style="flex: 1; padding: 12px; background: white; color: #374151; border: 1.5px solid #D1D5DB; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer;">

                    Cancel

                </button>

                <button type="submit" style="flex: 1; padding: 12px; background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%); color: white; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);">

                    Create Rule

                </button>

            </div>

        </form>

    </div>

</div>



<!-- Toast Notification Container (Non-blocking) -->

<div id="sfx-toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 9999999; display: flex; flex-direction: column; gap: 12px; max-width: 400px; pointer-events: none;"></div>



<!-- Alert Modal (For important messages only) -->

<div id="alert-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999999; align-items: center; justify-content: center;">

    <div style="background: white; border-radius: 16px; max-width: 440px; width: 90%; padding: 32px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">

        <div id="alert-icon" style="width: 56px; height: 56px; margin: 0 auto 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center;"></div>

        <h3 id="alert-title" style="margin: 0 0 10px; font-size: 20px; font-weight: 700; color: #111827; text-align: center;"></h3>

        <p id="alert-message" style="margin: 0 0 24px; color: #6B7280; font-size: 15px; line-height: 1.6; text-align: center; white-space: pre-line;"></p>

        <div id="alert-dont-show-container" style="display: none;"></div>

        <button id="alert-confirm-btn" onclick="closeAlertModal()" style="width: 100%; padding: 12px 20px; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer;"></button>

    </div>

</div>



<!-- Confirmation Modal -->

<div id="confirm-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); z-index: 9999999; align-items: center; justify-content: center; backdrop-filter: blur(4px);">

    <div style="background: white; border-radius: 16px; max-width: 500px; width: 90%; box-shadow: 0 25px 50px rgba(0,0,0,0.25);">

        <div style="padding: 28px 32px; border-bottom: 1px solid #E5E7EB;">

            <div style="display: flex; align-items: flex-start; gap: 16px;">

                <div id="confirm-icon" style="width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;"></div>

                <div style="flex: 1;">

                    <h3 id="confirm-title" style="margin: 0 0 8px; font-size: 20px; font-weight: 700; color: #111827;"></h3>

                    <p id="confirm-message" style="margin: 0; color: #6B7280; font-size: 14px; line-height: 1.6; white-space: pre-line;"></p>

                </div>

            </div>

        </div>

        <div id="confirm-dont-show-container" style="display: none; padding: 14px 32px; border-top: 1px solid #E5E7EB;">

            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">

                <input type="checkbox" id="confirm-dont-show" style="width: 16px; height: 16px; cursor: pointer;">

                <span style="font-size: 13px; color: #6B7280;">Don't show this message again</span>

            </label>

        </div>

        <div style="padding: 20px 32px; display: flex; gap: 12px; background: #F9FAFB; border-radius: 0 0 16px 16px;">

            <button id="confirm-cancel-btn" onclick="closeConfirmModal(false)" style="flex: 1; padding: 11px 20px; background: white; color: #374151; border: 1.5px solid #D1D5DB; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                Cancel

            </button>

            <button id="confirm-yes-btn" onclick="closeConfirmModal(true)" style="flex: 1; padding: 12px 20px; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3); transition: all 0.2s;"></button>

        </div>

    </div>

</div>



<style>

.sensfrx-card {

    background: white;

    border: 1px solid #E5E7EB;

    border-radius: 12px;

    box-shadow: 0 1px 3px rgba(0,0,0,0.05);

}



/* Template Hover - DISABLED (One-Click Protection not active) */

/*

.sensfrx-template:hover {

    border-color: #2563EB;

    box-shadow: 0 8px 16px rgba(37, 99, 235, 0.15);

    transform: translateY(-3px);

}

*/



.sensfrx-btn-primary:hover {

    background: linear-gradient(135deg, #1E40AF 0%, #6D28D9 100%);

    box-shadow: 0 6px 20px rgba(37, 99, 235, 0.4);

    transform: translateY(-2px);

}



#rules-search:focus, #filter-type:focus, #filter-action:focus, 

#rule-type:focus, #rule-pattern:focus {

    outline: none;

    border-color: #2563EB;

    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);

}



#rules-table-body tr {

    border-bottom: 1px solid #F3F4F6;

    transition: all 0.15s;

}



#rules-table-body tr:hover {

    background: #F9FAFB;

}



#confirm-cancel-btn:hover {

    background: #F9FAFB;

    border-color: #9CA3AF;

}



#confirm-yes-btn:hover {

    transform: translateY(-1px);

    box-shadow: 0 6px 20px rgba(37, 99, 235, 0.4);

}



@keyframes spin {

    to { transform: rotate(360deg); }

}



/* Tooltip styles */

.sensfrx-tooltip:hover .sensfrx-tooltiptext {

    visibility: visible !important;

    opacity: 1 !important;

}



.sensfrx-tooltiptext::after {

    content: "";

    position: absolute;

    top: 100%;

    left: 50%;

    margin-left: -5px;

    border-width: 5px;

    border-style: solid;

    border-color: rgba(0,0,0,0.95) transparent transparent transparent;

}



/* Enhanced Toggle Switches */

.sfx-toggle {

    position: relative;

    display: inline-block;

    width: 48px;

    height: 26px;

}



.sfx-toggle input {

    opacity: 0;

    width: 0;

    height: 0;

}



.sfx-toggle-slider {

    position: absolute;

    cursor: pointer;

    top: 0;

    left: 0;

    right: 0;

    bottom: 0;

    background: #CBD5E1;

    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    border-radius: 26px;

    box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);

}



.sfx-toggle-slider:hover {

    background: #B0BEC5;

}



.sfx-toggle-slider:before {

    position: absolute;

    content: "";

    height: 20px;

    width: 20px;

    left: 3px;

    bottom: 3px;

    background: white;

    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    border-radius: 50%;

    box-shadow: 0 2px 6px rgba(0,0,0,0.2);

}



.sfx-toggle-slider.checked {

    background: linear-gradient(135deg, #2563EB 0%, #1E40AF 100%);

    box-shadow: inset 0 1px 3px rgba(0,0,0,0.1), 0 0 0 2px rgba(37,99,235,0.15);

}



.sfx-toggle-slider.checked:hover {

    background: linear-gradient(135deg, #1E40AF 0%, #6D28D9 100%);

}



.sfx-toggle-slider.checked:before {

    transform: translateX(22px);

}



.sfx-toggle-slider.saving {

    opacity: 0.7;

    cursor: wait;

}



/* Disabled toggle styling for Free plan users */

.sfx-toggle-disabled .sfx-toggle-slider {

    cursor: not-allowed;

    background: #E5E7EB;

    box-shadow: none;

}



.sfx-toggle-disabled .sfx-toggle-slider:hover {

    background: #E5E7EB;

}



.sfx-toggle-disabled .sfx-toggle-slider:before {

    background: #F3F4F6;

}



/* Restricted AI policy row hover tooltip */

.ai-policy-row-restricted {

    position: relative;

}



.ai-policy-row-restricted:hover::after {

    content: "Upgrade to Pro to enable this AI policy";

    position: absolute;

    right: 20px;

    top: 50%;

    transform: translateY(-50%);

    padding: 6px 12px;

    background: #1F2937;

    color: white;

    font-size: 12px;

    font-weight: 500;

    border-radius: 6px;

    white-space: nowrap;

    pointer-events: none;

    z-index: 10;

    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

    animation: fadeIn 0.2s ease-in-out;

}



@keyframes fadeIn {

    from { opacity: 0; transform: translateY(calc(-50% + 5px)); }

    to { opacity: 1; transform: translateY(-50%); }

}

</style>



<script>

let userTier = 'FREE';

let tierLimit = 5;

let currentRulesCount = 0;

let allRules = [];



jQuery(document).ready(function($) {



    // fetching review count

    fetch(sensfrxData.restUrl + 'get_sensfrx_review_count', {

        method: 'GET',

        headers: {

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            const badge = document.querySelector('.sensfrx-nav-badge');

            if (badge) {

                badge.textContent = data.reviewCount || 0;

            }

        }

    })

    .catch(error => console.error('Error fetching review count:', error));



    // Fetch protection stats (Fraudsters Stopped & Happy Customers - Last 30 Days)

    fetchFraudstersStoppedStats();

 

    fetchUserTier().then(function() {

        loadValidationRules();

    });



    // Load policy counts immediately on page load for tab badges

    loadDefaultPolicies();

    loadAdvancedPolicies();



    $('#rule-form').on('submit', function(e) {

        e.preventDefault();

        createValidationRule();

    });

});



// Function to get last 30 days date range in dd-MM-yyyy format

function getLast30DaysDates() {

    const today = new Date();

    const thirtyDaysAgo = new Date(today);

    thirtyDaysAgo.setDate(today.getDate() - 30);

    

    function formatDate(date) {

        const day = String(date.getDate()).padStart(2, '0');

        const month = String(date.getMonth() + 1).padStart(2, '0');

        const year = date.getFullYear();

        return day + '-' + month + '-' + year;

    }

    

    return {

        from: formatDate(thirtyDaysAgo),

        to: formatDate(today)

    };

}



// Function to fetch protection stats from new combined API

function fetchFraudstersStoppedStats() {

    const dates = getLast30DaysDates();

    const $ = jQuery;

    

    // Show loading state

    document.getElementById('threats-blocked-count').textContent = '...';

    document.getElementById('legitimate-orders-count').textContent = '...';

    document.getElementById('time-saved-value').textContent = '...';

    

    // Fetch from new combined protection-stats API

    $.ajax({

        url: sensfrxData.restUrl + 'protection-stats',

        method: 'GET',

        data: {

            from_date: dates.from,

            to_date: dates.to

        }

    })

    .done(function(response) {

        if (response.status === 'success' && response.data) {

            // Update Fraudsters Stopped

            document.getElementById('threats-blocked-count').textContent = response.data.fraudsters_stopped || 0;

            

            // Update Happy Customers (unique count!)

            document.getElementById('legitimate-orders-count').textContent = response.data.happy_customers || 0;

            

            // Update Time Saved

            const hoursSaved = response.data.hours_saved || 0;

            document.getElementById('time-saved-value').textContent = hoursSaved;

            

            // Update cases handled text

            const casesHandled = response.data.auto_handled_cases || 0;

            document.getElementById('cases-handled-text').textContent = casesHandled + ' cases handled automatically';

        } else {

            document.getElementById('threats-blocked-count').textContent = '--';

            document.getElementById('legitimate-orders-count').textContent = '--';

            document.getElementById('time-saved-value').textContent = '--';

            document.getElementById('cases-handled-text').textContent = 'Manual reviews avoided';

        }

    })

    .fail(function(error) {

        console.error('Error fetching protection stats:', error);

        document.getElementById('threats-blocked-count').textContent = '--';

        document.getElementById('legitimate-orders-count').textContent = '--';

        document.getElementById('time-saved-value').textContent = '--';

        document.getElementById('cases-handled-text').textContent = 'Manual reviews avoided';

    });

}



function fetchUserTier() {

    const $ = jQuery;

    return $.ajax({

        url: sensfrxData.restUrl + 'get_license_info',

        method: 'GET',

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(response) {

            if (response.status === 'success' && response.data) {

                const planName = response.data.planName || response.data.plan_name || response.data.plan || 'FREE';

                userTier = planName.toUpperCase();

                

                if (userTier.includes('PRO') || userTier.includes('PREMIUM') || userTier.includes('ENTERPRISE')) {

                    tierLimit = 999999;

                } else {

                    tierLimit = parseInt(response.data.custom_validation_limit) || 5;

                }

                

            }

        }

    });

}



const fieldTypeNames = {

    'ip': 'IP Address',

    'ue': 'Email',

    'uID': 'User ID',

    'un': 'Username'

};



// Non-blocking toast notification (for passive feedback)

function showToast(message, type = 'success', duration = 3000) {

    const container = document.getElementById('sfx-toast-container');

    const toast = document.createElement('div');

    toast.style.cssText = 'pointer-events: auto; background: white; padding: 14px 18px; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,0.15); display: flex; align-items: center; gap: 12px; min-width: 300px; animation: slideInRight 0.3s ease-out, fadeOut 0.3s ease-in ' + ((duration - 300) / 1000) + 's forwards; border-left: 4px solid;';



    let icon, bgColor, borderColor, textColor;

    if (type === 'success') {

        icon = '<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M5 10l3 3 7-7" stroke="#2563EB" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';

        bgColor = '#DBEAFE';

        borderColor = '#2563EB';

        textColor = '#0E7490';

    } else if (type === 'error') {

        icon = '<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="#DC2626" stroke-width="2"/><path d="M10 6v4m0 3h.01" stroke="#DC2626" stroke-width="2" stroke-linecap="round"/></svg>';

        bgColor = '#FEE2E2';

        borderColor = '#DC2626';

        textColor = '#991B1B';

    } else if (type === 'info') {

        icon = '<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="#3B82F6" stroke-width="2"/><path d="M10 9v4m0-7h.01" stroke="#3B82F6" stroke-width="2" stroke-linecap="round"/></svg>';

        bgColor = '#DBEAFE';

        borderColor = '#3B82F6';

        textColor = '#1E40AF';

    }



    toast.style.borderLeftColor = borderColor;

    toast.innerHTML = `

        <div style="background: ${bgColor}; padding: 8px; border-radius: 8px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">

            ${icon}

        </div>

        <span style="font-size: 14px; font-weight: 600; color: ${textColor}; flex: 1;">${message}</span>

        <button onclick="this.parentElement.remove()" style="background: none; border: none; color: #9CA3AF; cursor: pointer; font-size: 20px; line-height: 1; padding: 0; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;">&times;</button>

    `;



    container.appendChild(toast);

    setTimeout(() => toast.remove(), duration);

}



function showAlert(title, message, type = 'info', dontShowKey = null, customAction = null) {

    // Check if user has chosen to hide this alert type

    if (dontShowKey && localStorage.getItem('sfx_hide_' + dontShowKey) === 'true') {

        return; // Don't show if user chose "don't show again"

    }



    const modal = document.getElementById('alert-modal');

    const icon = document.getElementById('alert-icon');

    const titleEl = document.getElementById('alert-title');

    const messageEl = document.getElementById('alert-message');

    const confirmBtn = document.getElementById('alert-confirm-btn');

    const checkboxContainer = document.getElementById('alert-dont-show-container');



    titleEl.textContent = title;

    messageEl.innerHTML = message; // Use innerHTML to render HTML tags like <br>, <strong>, etc.



    // Show/hide "don't show again" checkbox

    if (dontShowKey) {

        checkboxContainer.style.display = 'block';

        checkboxContainer.innerHTML = `

            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 12px; background: #F9FAFB; border-radius: 8px; margin-top: 16px;">

                <input type="checkbox" id="sfx-dont-show-checkbox" style="width: 18px; height: 18px; cursor: pointer;">

                <span style="font-size: 14px; color: #6B7280;">Don't show this message again</span>

            </label>

        `;



        const checkbox = document.getElementById('sfx-dont-show-checkbox');

        checkbox.addEventListener('change', function() {

            if (this.checked) {

                localStorage.setItem('sfx_hide_' + dontShowKey, 'true');

            } else {

                localStorage.removeItem('sfx_hide_' + dontShowKey);

            }

        });

    } else {

        checkboxContainer.style.display = 'none';

        checkboxContainer.innerHTML = '';

    }



    if (type === 'success') {

        icon.style.background = '#DBEAFE';

        icon.innerHTML = '<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M7 14l4 4L21 8" stroke="#2563EB" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>';

        confirmBtn.style.background = 'linear-gradient(135deg, #2563EB 0%, #1E40AF 100%)';

        confirmBtn.style.color = 'white';

        confirmBtn.textContent = 'Got it';

        confirmBtn.onclick = closeAlertModal;

    } else if (type === 'error') {

        icon.style.background = '#FEE2E2';

        icon.innerHTML = '<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M9 9l10 10M9 19l10-10" stroke="#DC2626" stroke-width="3" stroke-linecap="round"/></svg>';

        confirmBtn.style.background = '#DC2626';

        confirmBtn.style.color = 'white';

        confirmBtn.textContent = 'Close';

        confirmBtn.onclick = closeAlertModal;

    } else if (type === 'warning') {

        icon.style.background = '#DBEAFE';

        icon.innerHTML = '<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M14 9v6m0 4h.01" stroke="#2563EB" stroke-width="3" stroke-linecap="round"/></svg>';

        confirmBtn.style.background = '#2563EB';

        confirmBtn.style.color = 'white';



        // Use custom action if provided

        if (customAction) {

            confirmBtn.textContent = customAction.text || 'Understood';

            confirmBtn.onclick = function() {

                if (customAction.url) {

                    window.location.href = customAction.url;

                } else if (customAction.callback) {

                    customAction.callback();

                }

                closeAlertModal();

            };

        } else {

            confirmBtn.textContent = 'Understood';

            confirmBtn.onclick = closeAlertModal;

        }

    } else {

        icon.style.background = '#DBEAFE';

        icon.innerHTML = '<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><circle cx="14" cy="14" r="10" stroke="#3B82F6" stroke-width="2"/><path d="M14 9v6m0 4h.01" stroke="#3B82F6" stroke-width="2.5" stroke-linecap="round"/></svg>';

        confirmBtn.style.background = 'linear-gradient(135deg, #3B82F6 0%, #2563EB 100%)';

        confirmBtn.style.color = 'white';

        confirmBtn.textContent = 'Got it';

        confirmBtn.onclick = closeAlertModal;

    }



    modal.style.display = 'flex';

}





function closeAlertModal() {

    document.getElementById('alert-modal').style.display = 'none';

}



let confirmCallback = null;



function showConfirm(title, message, type = 'info', dontShowKey = null) {

    return new Promise((resolve) => {

        // Check localStorage if dontShowKey is provided

        if (dontShowKey && localStorage.getItem('sfx_dont_show_' + dontShowKey) === 'true') {

            // User chose not to show this again, auto-approve

            resolve(true);

            return;

        }



        const modal = document.getElementById('confirm-modal');

        const icon = document.getElementById('confirm-icon');

        const titleEl = document.getElementById('confirm-title');

        const messageEl = document.getElementById('confirm-message');

        const yesBtn = document.getElementById('confirm-yes-btn');

        const dontShowContainer = document.getElementById('confirm-dont-show-container');

        const dontShowCheckbox = document.getElementById('confirm-dont-show');



        titleEl.textContent = title;

        messageEl.textContent = message;



        // Show/hide "Don't show again" checkbox

        if (dontShowKey) {

            dontShowContainer.style.display = 'block';

            dontShowCheckbox.checked = false;

            dontShowCheckbox.setAttribute('data-key', dontShowKey);

        } else {

            dontShowContainer.style.display = 'none';

        }



        confirmCallback = resolve;



        if (type === 'warning') {

            icon.style.background = '#DBEAFE';

            icon.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="#2563EB" stroke-width="2"/><path d="M12 8v5m0 3h.01" stroke="#2563EB" stroke-width="2" stroke-linecap="round"/></svg>';

            yesBtn.style.background = 'linear-gradient(135deg, #2563EB 0%, #1E40AF 100%)';

            yesBtn.style.color = 'white';

            yesBtn.textContent = 'Apply Template';

        } else if (type === 'danger') {

            icon.style.background = '#FEE2E2';

            icon.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" stroke="#DC2626" stroke-width="2" stroke-linecap="round"/></svg>';

            yesBtn.style.background = '#DC2626';

            yesBtn.style.color = 'white';

            yesBtn.textContent = 'Confirm';

        } else {

            icon.style.background = '#DBEAFE';

            icon.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="#3B82F6" stroke-width="2"/><path d="M12 16v-4m0-4h.01" stroke="#3B82F6" stroke-width="2" stroke-linecap="round"/></svg>';

            yesBtn.style.background = 'linear-gradient(135deg, #2563EB 0%, #1E40AF 100%)';

            yesBtn.style.color = 'white';

            yesBtn.textContent = 'Confirm';

        }



        modal.style.display = 'flex';

    });

}



function closeConfirmModal(result) {

    const modal = document.getElementById('confirm-modal');

    const dontShowCheckbox = document.getElementById('confirm-dont-show');



    // Save preference if checkbox is checked and user clicked Yes

    if (result && dontShowCheckbox.checked) {

        const key = dontShowCheckbox.getAttribute('data-key');

        if (key) {

            localStorage.setItem('sfx_dont_show_' + key, 'true');

        }

    }



    modal.style.display = 'none';

    if (confirmCallback) {

        confirmCallback(result);

        confirmCallback = null;

    }

}



function loadValidationRules() {

    const $ = jQuery;



    Promise.all([

        $.ajax({ url: sensfrxData.restUrl + 'get_sensfrx_blacklist', method: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce); } }),

        $.ajax({ url: sensfrxData.restUrl + 'get_sensfrx_whitelist', method: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce); } }),

        $.ajax({ url: sensfrxData.restUrl + 'get_license_info', method: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce); } })

    ]).then(function(responses) {

        const blacklistData = responses[0];

        const whitelistData = responses[1];

        const licenseData = responses[2];





        allRules = [];



        // Process blacklist

        ['ip', 'ue', 'uID', 'un'].forEach(function(field) {

            if (blacklistData[field] && Array.isArray(blacklistData[field])) {

                blacklistData[field].forEach(function(value) {

                    allRules.push({ field: field, value: value, action: 'block', source: 'blacklist' });

                });

            }

        });



        // Process whitelist

        ['ip', 'ue', 'uID', 'un'].forEach(function(field) {

            if (whitelistData[field] && Array.isArray(whitelistData[field])) {

                whitelistData[field].forEach(function(value) {

                    allRules.push({ field: field, value: value, action: 'allow', source: 'whitelist' });

                });

            }

        });





        currentRulesCount = allRules.length;



        // Update quota usage display

        if (licenseData && licenseData.data) {

            const planName = licenseData.data.plan || 'FREE';

            const limit = licenseData.data.blacklist_whitelist_limit || 5;

            const currentUsage = allRules.length;

            const isUnlimited = limit === 'Unlimited' || limit >= 999999;



            // Also get policy quota info

            const policyLimit = licenseData.data.custom_risk_rules_limit || 0;

            const policyIsUnlimited = policyLimit === 'Unlimited' || policyLimit >= 999999;

            const defaultPoliciesEnabled = sfxDefaultPolicies ? sfxDefaultPolicies.filter(p => p.active == 1).length : 0;

            const advancedPoliciesEnabled = sfxAdvancedPolicies ? sfxAdvancedPolicies.filter(p => p.active == 1).length : 0;

            const totalPoliciesEnabled = defaultPoliciesEnabled + advancedPoliciesEnabled;



            $('#quota-plan-name').text(planName.toUpperCase());



            // Build quota display with both blocklist and policy quotas

            let quotaHtml = '';



            // Block & Allow List quota (rules only - no policy quota here)

            if (isUnlimited) {

                quotaHtml += '<strong>' + currentUsage + '</strong> block/allow rules <span style="color: #10B981;">• Unlimited</span>';

            } else {

                const available = Math.max(0, limit - currentUsage);

                const percentage = Math.min(100, (currentUsage / limit) * 100);

                const color = percentage >= 90 ? '#DC2626' : percentage >= 75 ? '#F59E0B' : '#10B981';



                quotaHtml += '<strong>' + currentUsage + ' / ' + limit + '</strong> block/allow rules <span style="color: ' + color + ';">• ' + available + ' available</span>';

            }



            $('#quota-usage-text').html(quotaHtml);

        }



        updateStats();

        displayRules(allRules);

    });

}



function updateStats() {

    // Count blacklist/whitelist rules from Block & Allow Lists tab

    var blacklistCount = 0;

    var whitelistCount = 0;



    if (typeof allRules !== 'undefined' && Array.isArray(allRules)) {

        blacklistCount = allRules.filter(r => r.action === 'block').length;

        whitelistCount = allRules.filter(r => r.action === 'allow').length;

    }



    // Count enabled policies from default and advanced

    var defaultEnabledReject = 0;

    var defaultEnabledApprove = 0;

    var advancedEnabledReject = 0;

    var advancedEnabledApprove = 0;



    if (typeof sfxDefaultPolicies !== 'undefined' && Array.isArray(sfxDefaultPolicies)) {

        sfxDefaultPolicies.forEach(function(p) {

            if (p.active == 1) {

                if (p.action === 'reject') defaultEnabledReject++;

                else if (p.action === 'approve') defaultEnabledApprove++;

            }

        });

    }



    if (typeof sfxAdvancedPolicies !== 'undefined' && Array.isArray(sfxAdvancedPolicies)) {

        sfxAdvancedPolicies.forEach(function(p) {

            if (p.active == 1) {

                if (p.action === 'reject') advancedEnabledReject++;

                else if (p.action === 'approve') advancedEnabledApprove++;

            }

        });

    }



    // Combine both types of protections

    const totalBlockingRules = blacklistCount + defaultEnabledReject + advancedEnabledReject;

    const totalAllowingRules = whitelistCount + defaultEnabledApprove + advancedEnabledApprove;

    const totalActiveProtections = totalBlockingRules + totalAllowingRules;



    // Update tab badges with enabled rule counts

    const smartProtectionEnabled = defaultEnabledReject + defaultEnabledApprove;

    const aiProtectionEnabled = advancedEnabledReject + advancedEnabledApprove;



    document.getElementById('total-rules-count').textContent = totalActiveProtections;

    document.getElementById('rules-count-badge').textContent = totalActiveProtections;

    document.getElementById('block-rules-count').textContent = totalBlockingRules;

    document.getElementById('allow-rules-count').textContent = totalAllowingRules;

    document.getElementById('smart-protection-count').textContent = smartProtectionEnabled;

    document.getElementById('ai-protection-count').textContent = aiProtectionEnabled;

}



function displayRules(rules) {

    document.getElementById('rules-loading').style.display = 'none';

    

    if (rules.length === 0) {

        document.getElementById('rules-empty').style.display = 'block';

        document.getElementById('rules-content').style.display = 'none';

        document.getElementById('rules-active-stats').style.display = 'none';

        return;

    }



    document.getElementById('rules-empty').style.display = 'none';

    document.getElementById('rules-content').style.display = 'block';

    document.getElementById('rules-active-stats').style.display = 'block';



    // Calculate statistics

    const totalRules = rules.length;

    const blockRules = rules.filter(r => r.action === 'block').length;

    const allowRules = rules.filter(r => r.action === 'allow').length;



    // Update statistics display

    document.getElementById('total-custom-rules').textContent = totalRules;

    document.getElementById('active-block-rules').textContent = blockRules;

    document.getElementById('active-allow-rules').textContent = allowRules;



    const tbody = jQuery('#rules-table-body');

    tbody.empty();



    rules.forEach(function(rule) {

        const actionBadge = rule.action === 'block'

            ? '<span style="display:inline-flex;align-items:center;padding:6px 12px;background:#FEE2E2;color:#991B1B;border-radius:6px;font-size:13px;font-weight:600;">Block</span>'

            : '<span style="display:inline-flex;align-items:center;padding:6px 12px;background:#DBEAFE;color:#166534;border-radius:6px;font-size:13px;font-weight:600;">Allow</span>';



        const typeBadge = '<span style="display:inline-flex;align-items:center;padding:5px 10px;background:#F3F4F6;color:#374151;border-radius:6px;font-size:12px;font-weight:600;">' + fieldTypeNames[rule.field] + '</span>';



        const row = jQuery('<tr>').html(

            '<td style="padding:16px 20px;"><input type="checkbox" class="rule-checkbox" data-field="' + rule.field + '" data-value="' + rule.value + '" data-source="' + rule.source + '" onchange="updateSelectedCount()" style="width:18px;height:18px;cursor:pointer;"></td>' +

            '<td style="padding:16px 20px;font-size:14px;">' + typeBadge + '</td>' +

            '<td style="padding:16px 20px;font-size:14px;font-family:monospace;color:#374151;"><strong>' + rule.value + '</strong></td>' +

            '<td style="padding:16px 20px;">' + actionBadge + '</td>' +

            // '<td style="padding:16px 20px;text-align:center;color:#6B7280;font-size:13px;">--</td>' +

            '<td style="padding:16px 20px;text-align:right;"><button onclick="deleteRule(\'' + rule.field + '\', \'' + rule.value + '\', \'' + rule.source + '\')" style="padding:8px 14px;background:#FEE2E2;color:#DC2626;border:none;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer;">Delete</button></td>'

        );

        tbody.append(row);

    });

}



function filterRules() {

    const search = document.getElementById('rules-search').value.toLowerCase();

    const typeFilter = document.getElementById('filter-type').value;

    const actionFilter = document.getElementById('filter-action').value;



    const filtered = allRules.filter(rule => {

        const matchesSearch = rule.value.toLowerCase().includes(search);

        const matchesType = !typeFilter || rule.field === typeFilter;

        const matchesAction = !actionFilter || rule.action === actionFilter;

        return matchesSearch && matchesType && matchesAction;

    });



    displayRules(filtered);

}



function openRuleModal(type) {

    if (userTier === 'FREE' && currentRulesCount >= tierLimit) {

        showAlert('Limit Reached', 'You\'ve reached the FREE tier limit of ' + tierLimit + ' custom rules.\n\nUpgrade to SensFRX PRO for unlimited protection rules and advanced fraud detection.', 'warning');

        return;

    }



    if (type) {

        document.getElementById('rule-type').value = type;

    }

    document.getElementById('rule-modal').style.display = 'flex';

}



function closeRuleModal() {

    document.getElementById('rule-modal').style.display = 'none';

    document.getElementById('rule-form').reset();

}



function createValidationRule() {

    const $ = jQuery;

 

    const field = $('#rule-type').val();    

    const value = $('#rule-pattern').val();

    const action = $('input[name="rule-action"]:checked').val();



    if (field === 'ue') {

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;



        if (!emailRegex.test(value)) {

            showAlert(

                'Invalid Email',

                'Please enter a valid email address before creating the rule.',

                'error'

            );

            return; // 🚫 Stop execution

        }

    }

 

    const endpoint = action === 'block' ? 'post_sensfrx_blacklist' : 'post_sensfrx_whitelist';

 

    $.ajax({

        url: sensfrxData.restUrl + endpoint,

        method: 'POST',

        contentType: 'application/json', // ✅ FIX 1: Tell jQuery to send JSON

        dataType: 'json',                // ✅ FIX 2: Expect JSON response

        data: JSON.stringify({           // ✅ FIX 3: Stringify the data

            field: field, 

            value: value 

        }),

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(response) {

            if (response.status === 'success') {

                showAlert(response.message, 'Protection rule created successfully! SensFRX is now enforcing this rule.', 'success');

                closeRuleModal();

                loadValidationRules();

            } else {

                showAlert('SFX Error', 'Failed to create rule: ' + (response.message || 'Unknown error'), 'error');

            }

        },

        error: function(xhr, status, error) {

            // ✅ FIX 4: Properly extract error message from response

            let errorMsg = 'Failed to create rule. Please try again.';

            try {

                // Try to parse the response as JSON

                const errorResponse = xhr.responseJSON || JSON.parse(xhr.responseText);

                if (errorResponse && errorResponse.message) {

                    errorMsg = errorResponse.message; // This will now show the REAL error!

                } else if (errorResponse && errorResponse.data && errorResponse.data.message) {

                    errorMsg = errorResponse.data.message;

                }

            } catch (e) {

                // If parsing fails, use response text or default message

                errorMsg = xhr.responseText || errorMsg;

            }

            showAlert('Error', errorMsg, 'error');

        }

    });

}



async function deleteRule(field, value, source) {

    const confirmed = await showConfirm(

        'Delete Protection Rule?',

        fieldTypeNames[field] + ': ' + value + '\n\nThis action cannot be undone.',

        'danger'

    );



    if (!confirmed) {

        return;

    }



    const $ = jQuery;

    const endpoint = source === 'blacklist' ? 'post_sensfrx_delete_blacklist' : 'post_sensfrx_delete_whitelist';



    $.ajax({

        url: sensfrxData.restUrl + endpoint,

        method: 'POST',

        data: { field: field, value: value },

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(response) {

            if (response.status === 'success' || response.message === 'Settings updated successfully') {

                showAlert('Rule Deleted', 'Protection rule removed successfully! SensFRX has updated your protection settings.', 'success');

                loadValidationRules();

            } else {

                showAlert('Error', 'Failed to delete rule: ' + (response.message || 'Unknown error'), 'error');

            }

        },

        error: function() {

            showAlert('Error', 'Failed to delete rule. Please try again.', 'error');

        }

    });

}



// Toggle select all checkboxes

function toggleSelectAll() {

    const selectAll = document.getElementById('select-all-rules');

    const checkboxes = document.querySelectorAll('.rule-checkbox');

    checkboxes.forEach(cb => cb.checked = selectAll.checked);

    updateSelectedCount();

}



// Update selected count and show/hide delete button

function updateSelectedCount() {

    const checkboxes = document.querySelectorAll('.rule-checkbox:checked');

    const count = checkboxes.length;

    const deleteBtn = document.getElementById('delete-selected-btn');

    const countSpan = document.getElementById('selected-count');



    countSpan.textContent = count;

    deleteBtn.style.display = count > 0 ? 'block' : 'none';



    // Update select-all checkbox state

    const allCheckboxes = document.querySelectorAll('.rule-checkbox');

    const selectAll = document.getElementById('select-all-rules');

    selectAll.checked = allCheckboxes.length > 0 && count === allCheckboxes.length;

}



// Delete all selected rules

async function deleteSelectedRules() {

    const checkboxes = document.querySelectorAll('.rule-checkbox:checked');

    if (checkboxes.length === 0) return;



    const confirmed = await showConfirm(

        'Delete Selected Rules?',

        'You are about to delete ' + checkboxes.length + ' protection rule(s).\n\nThis action cannot be undone.',

        'danger'

    );



    if (!confirmed) return;



    const $ = jQuery;

    let successCount = 0;

    let errorCount = 0;



    // Show progress alert

    showAlert('Deleting Rules', 'Deleting selected rules...<br><br>Progress: 0/' + checkboxes.length, 'info');



    // Delete rules sequentially

    for (let i = 0; i < checkboxes.length; i++) {

        const cb = checkboxes[i];

        const field = cb.dataset.field;

        const value = cb.dataset.value;

        const source = cb.dataset.source;

        const endpoint = source === 'blacklist' ? 'post_sensfrx_delete_blacklist' : 'post_sensfrx_delete_whitelist';



        try {

            const response = await $.ajax({

                url: sensfrxData.restUrl + endpoint,

                method: 'POST',

                data: { field: field, value: value },

                beforeSend: function(xhr) {

                    xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

                }

            });



            if (response.status === 'success' || response.message === 'Settings updated successfully') {

                successCount++;

            } else {

                errorCount++;

            }

        } catch (error) {

            errorCount++;

        }



        // Update progress

        $('#alert-message').html(

            'Deleting selected rules...<br><br><strong>Progress: ' + (i + 1) + '/' + checkboxes.length + '</strong><br>' +

            '<small style="color: #6B7280;">' + successCount + ' deleted • ' + errorCount + ' failed</small>'

        );

    }



    // Reload rules and show completion message

    loadValidationRules();



    if (successCount > 0 && errorCount === 0) {

        showAlert('Rules Deleted', '<strong>Successfully deleted ' + successCount + ' protection rules</strong><br><br>Your protection settings have been updated.', 'success');

    } else if (successCount > 0) {

        showAlert('Partial Success', '<strong>Deleted ' + successCount + ' rules</strong><br><br>' + errorCount + ' rules failed to delete.', 'warning');

    } else {

        showAlert('Deletion Failed', 'Failed to delete the selected rules. Please try again.', 'error');

    }

}



// Get current blacklist + whitelist quota usage and limits from license API

async function getQuotaInfo() {

    const $ = jQuery;

    try {

        const [blacklistRes, whitelistRes, licenseRes] = await Promise.all([

            $.ajax({

                url: sensfrxData.restUrl + 'get_sensfrx_blacklist',

                type: 'GET',

                headers: { 'X-WP-Nonce': sensfrxData.nonce }

            }),

            $.ajax({

                url: sensfrxData.restUrl + 'get_sensfrx_whitelist',

                type: 'GET',

                headers: { 'X-WP-Nonce': sensfrxData.nonce }

            }),

            $.ajax({

                url: sensfrxData.restUrl + 'get_license_info',

                type: 'GET',

                headers: { 'X-WP-Nonce': sensfrxData.nonce }

            })

        ]);



        const blacklistCount = (blacklistRes.data && Array.isArray(blacklistRes.data)) ? blacklistRes.data.length : 0;

        const whitelistCount = (whitelistRes.data && Array.isArray(whitelistRes.data)) ? whitelistRes.data.length : 0;

        const currentUsage = blacklistCount + whitelistCount;



        // Get plan limit from license info

        let planLimit = 5; // Default to free plan

        let planName = 'Free';



        if (licenseRes && licenseRes.data) {

            planLimit = licenseRes.data.blacklist_whitelist_limit || 5;

            planName = licenseRes.data.plan || 'Free';



            // Handle "Unlimited" as a very large number

            if (planLimit === 'Unlimited' || planLimit === 'unlimited') {

                planLimit = 999999;

            } else {

                planLimit = parseInt(planLimit);

            }

        }



        return {

            currentUsage: currentUsage,

            limit: planLimit,

            available: Math.max(0, planLimit - currentUsage),

            planName: planName,

            isUnlimited: planLimit >= 999999

        };

    } catch (error) {

        return {

            currentUsage: 0,

            limit: 5,

            available: 5,

            planName: 'Unknown',

            isUnlimited: false

        };

    }

}



// Show provider selection modal

function showProviderSelection(providers, templateType, onConfirm) {

    const $ = jQuery;



    const modal = $('<div>').attr('id', 'provider-selection-modal').css({

        display: 'flex',

        position: 'fixed',

        top: 0,

        left: 0,

        right: 0,

        bottom: 0,

        background: 'rgba(0,0,0,0.5)',

        alignItems: 'center',

        justifyContent: 'center',

        zIndex: 100000,

        animation: 'fadeIn 0.2s ease-out'

    });



    const content = $('<div>').css({

        background: 'white',

        borderRadius: '12px',

        padding: '24px',

        maxWidth: '600px',

        width: '90%',

        maxHeight: '80vh',

        overflow: 'auto',

        boxShadow: '0 20px 60px rgba(0,0,0,0.3)'

    });



    const title = templateType === 'vpn' ? 'VPN/Proxy Providers' : 'Disposable Email Services';

    const itemType = templateType === 'vpn' ? 'IP addresses' : 'domains';



    content.html(`

        <h3 style="margin: 0 0 8px; font-size: 20px; font-weight: 700; color: #111827;">${title}</h3>

        <p style="margin: 0 0 20px; font-size: 14px; color: #6B7280;">

            <span id="usage-info">Loading usage...</span>

        </p>

        <div id="provider-list" style="margin-bottom: 20px; max-height: 400px; overflow-y: auto;"></div>

        <div style="padding: 12px; background: #F3F4F6; border-radius: 8px; margin-bottom: 20px;">

            <div style="font-size: 14px; color: #374151;">

                <strong>Selected:</strong> <span id="selected-count">0</span> ${itemType}

            </div>

            <div id="quota-warning" style="font-size: 13px; color: #DC2626; margin-top: 4px; display: none;"></div>

        </div>

        <div style="display: flex; gap: 12px; justify-content: flex-end;">

            <button id="cancel-selection" style="padding: 10px 20px; border: 2px solid #E5E7EB; background: white; color: #374151; border-radius: 8px; font-weight: 600; cursor: pointer;">Cancel</button>

            <button id="confirm-selection" style="padding: 10px 20px; border: none; background: #2563EB; color: white; border-radius: 8px; font-weight: 600; cursor: pointer;">Add Selected</button>

        </div>

    `);



    modal.append(content);

    $('body').append(modal);



    // Populate provider list

    const providerList = $('#provider-list');

    providers.forEach((provider, index) => {

        const checkbox = $('<label>').css({

            display: 'flex',

            alignItems: 'center',

            padding: '12px',

            cursor: 'pointer',

            borderRadius: '8px',

            marginBottom: '8px',

            background: '#F9FAFB',

            border: '1px solid #E5E7EB'

        }).html(`

            <input type="checkbox" class="provider-checkbox" data-index="${index}" style="width: 18px; height: 18px; margin-right: 12px; cursor: pointer;" checked>

            <div style="flex: 1;">

                <div style="font-weight: 600; color: #111827;">${provider.name}</div>

                <div style="font-size: 13px; color: #6B7280;">${provider.count} ${itemType}</div>

            </div>

        `);

        providerList.append(checkbox);

    });



    // Update counts when checkboxes change

    function updateCounts() {

        getQuotaInfo().then(quotaInfo => {

            let selectedCount = 0;

            $('.provider-checkbox:checked').each(function() {

                const index = $(this).data('index');

                selectedCount += providers[index].count;

            });



            const limitText = quotaInfo.isUnlimited ? 'Unlimited' : quotaInfo.limit;

            $('#usage-info').html(

                `Plan: <strong>${quotaInfo.planName}</strong> | ` +

                `Limit: <strong>${limitText}</strong> | ` +

                `Used: <strong>${quotaInfo.currentUsage}</strong> | ` +

                `Available: <strong>${quotaInfo.isUnlimited ? 'Unlimited' : quotaInfo.available}</strong>`

            );

            $('#selected-count').text(selectedCount);



            // Show warnings

            const quotaWarning = $('#quota-warning');

            if (!quotaInfo.isUnlimited && selectedCount > quotaInfo.available) {

                quotaWarning.html(

                    `<strong>Selection exceeds your plan limit</strong><br>` +

                    `You can add ${quotaInfo.available} more items. Remaining ${selectedCount - quotaInfo.available} will hit the limit and prompt you to upgrade.`

                ).show();

            } else if (selectedCount > 100) {

                quotaWarning.text('Note: Large selection may take a few minutes to add').show();

            } else {

                quotaWarning.hide();

            }

        });

    }



    updateCounts();



    // Use event delegation since checkboxes are dynamically created

    modal.on('change', '.provider-checkbox', updateCounts);



    // Cancel button

    $('#cancel-selection').on('click', function() {

        modal.remove();

    });



    // Confirm button

    $('#confirm-selection').on('click', function() {

        const selected = [];

        $('.provider-checkbox:checked').each(function() {

            const index = $(this).data('index');

            selected.push(providers[index]);

        });

        modal.remove();

        onConfirm(selected);

    });



    // Close on outside click

    modal.on('click', function(e) {

        if (e.target === modal[0]) {

            modal.remove();

        }

    });

}



<?php

/*

============================================================

APPLY TEMPLATE FUNCTION - TEMPORARILY DISABLED

This function is not used as One-Click Protection is disabled

============================================================

*/



/*

============================================================

END OF APPLY TEMPLATE FUNCTION

============================================================

*/

?>



// ==================================================================================================

// POLICY MANAGEMENT - INTEGRATED INTO VALIDATION RULES

// ==================================================================================================



jQuery(document).ready(function($) {

    // Tab switching

    $('.sfx-policy-tab').on('click', function() {

        var tab = $(this).data('tab');

        

        $('.sfx-policy-tab').removeClass('sfx-tab-active');

        $(this).addClass('sfx-tab-active');

        

        $('.sfx-tab-content').removeClass('sfx-tab-active');

        $('#' + tab).addClass('sfx-tab-active');

        

        // Load policies when tab is first clicked

        if (tab === 'default-policies' && !window.sfxDefaultLoaded) {

            loadDefaultPolicies();

            window.sfxDefaultLoaded = true;

        } else if (tab === 'advanced-policies' && !window.sfxAdvancedLoaded) {

            loadAdvancedPolicies();

            window.sfxAdvancedLoaded = true;

        }

    });

});



var sfxDefaultPolicies = [];

var sfxAdvancedPolicies = [];

var userPlan = 'FREE'; // User's current plan

var canAccessAIProtection = false; // Whether user can access AI Protection

var policyQuotaLimit = 0; // License quota limit for policies

var policyQuotaIsUnlimited = false; // Whether quota is unlimited



function loadDefaultPolicies() {

    jQuery.ajax({

        url: sensfrxData.restUrl + 'get_sensfrx_default_policy_options',

        method: 'GET',

        headers: { 'X-WP-Nonce': sensfrxData.nonce },

        beforeSend: function(xhr) {

        },

        success: function(response) {

            if (response && response.sensfrx_defaul_policy_list) {

                sfxDefaultPolicies = response.sensfrx_defaul_policy_list;

                renderDefaultPolicies();

                updateStats(); // Update tab badge counts

            } else {

                jQuery('#default-policies-loading').html('<div style="color: #DC2626; font-weight: 600;">Invalid response format</div>');

            }

        },

        error: function(xhr, status, error) {

            jQuery('#default-policies-loading').html('<div style="color: #DC2626; font-weight: 600;">Failed to load default policies. Check console for details.</div>');

        }

    });

}



function loadAdvancedPolicies() {



    // First, get the user's plan from license API

    jQuery.ajax({

        url: sensfrxData.restUrl + 'get_license_info',

        method: 'GET',

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(licenseData) {

            if (licenseData && licenseData.data && licenseData.data.plan) {

                userPlan = licenseData.data.plan.toUpperCase();

                canAccessAIProtection = (userPlan !== 'FREE');





                // Show/hide upgrade banner based on plan

                if (!canAccessAIProtection) {

                    jQuery('#ai-protection-upgrade-banner').show();

                } else {

                    jQuery('#ai-protection-upgrade-banner').hide();

                }

            }



            // Now load the advanced policies

            loadAdvancedPoliciesData();

        },

        error: function() {

            // If license API fails, assume free plan and show upgrade banner

            userPlan = 'FREE';

            canAccessAIProtection = false;

            jQuery('#ai-protection-upgrade-banner').show();

            loadAdvancedPoliciesData();

        }

    });

}



function loadAdvancedPoliciesData() {

    jQuery.ajax({

        url: sensfrxData.restUrl + 'get_sensfrx_advance_rules',

        method: 'GET',

        headers: { 'X-WP-Nonce': sensfrxData.nonce },

        beforeSend: function(xhr) {

        },

        success: function(response) {

            if (response && response.sensfrx_advancd_rules_list) {

                sfxAdvancedPolicies = response.sensfrx_advancd_rules_list;

                renderAdvancedPolicies();

                updateStats(); // Update tab badge counts

            } else {

                jQuery('#advanced-policies-loading').html('<div style="color: #DC2626; font-weight: 600;">Invalid response format</div>');

            }

        },

        error: function(xhr, status, error) {

            jQuery('#advanced-policies-loading').html('<div style="color: #DC2626; font-weight: 600;">Failed to load advanced policies. Check console for details.</div>');

        }

    });

}



function renderDefaultPolicies() {

    var html = '';

    sfxDefaultPolicies.forEach(function(policy, idx) {

        var platforms = Array.isArray(policy.plt) ? policy.plt : [];

        html += '<tr style="border-bottom: 1px solid #F3F4F6;">';

        html += '<td style="padding: 14px 16px;"><input type="checkbox" class="policy-checkbox-default" data-idx="' + idx + '" onchange="updateDefaultSelectedCount()" style="width: 18px; height: 18px; cursor: pointer;"></td>';

        html += '<td style="padding: 14px 16px;"><div style="font-weight: 600; color: #111827;">' + policy.title + '</div><div style="font-size: 12px; color: #9CA3AF; margin-top: 2px; font-family: monospace;">' + policy.code + '</div></td>';

        html += '<td style="padding: 14px 16px; font-size: 13px; color: #6B7280;">' + policy.desc + '</td>';

        html += '<td style="padding: 14px 16px;">' + platforms.map(function(p) { 

            var color = p === 'Web' ? '#F59E0B' : p === 'Android' ? '#2563EB' : '#8B5CF6';

            return '<span style="display: inline-block; padding: 4px 8px; background: ' + color + '20; color: ' + color + '; border-radius: 6px; font-size: 11px; font-weight: 600; margin-right: 4px;">' + p + '</span>';

        }).join('') + '</td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><select class="sfx-policy-action" data-idx="' + idx + '" data-type="default" style="padding: 6px 10px; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 13px; font-weight: 500;"><option value="default"' + (policy.action === 'default' ? ' selected' : '') + '>Default</option><option value="reject"' + (policy.action === 'reject' ? ' selected' : '') + '>Reject</option><option value="approve"' + (policy.action === 'approve' ? ' selected' : '') + '>Approve</option><option value="review"' + (policy.action === 'review' ? ' selected' : '') + '>Review</option></select></td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><input type="number" class="sfx-policy-score" data-idx="' + idx + '" data-type="default" value="' + policy.score_value + '" min="0" max="100" style="width: 70px; padding: 6px 8px; border: 1.5px solid #E5E7EB; border-radius: 6px; text-align: center; font-size: 13px; font-weight: 500;"></td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><label class="sfx-toggle"><input type="checkbox" class="sfx-policy-active" data-idx="' + idx + '" data-type="default"' + (policy.active == 1 ? ' checked' : '') + '><span class="sfx-toggle-slider' + (policy.active == 1 ? ' checked' : '') + '"></span></label></td>';

        html += '</tr>';

    });

    jQuery('#default-policies-tbody').html(html);

    jQuery('#default-policies-loading').hide();

    jQuery('#default-policies-table').show();

    updateDefaultStats();

    updateStats();

    attachPolicyHandlers();

    updatePolicyQuotas();

}



function renderAdvancedPolicies() {

    var html = '';

    var isRestricted = !canAccessAIProtection;



    sfxAdvancedPolicies.forEach(function(policy, idx) {

        var platforms = Array.isArray(policy.plt) ? policy.plt : [];



        // Add subtle disabled styling for Free plan users

        var rowStyle = isRestricted ? 'border-bottom: 1px solid #F3F4F6; background: #FAFAFA; opacity: 0.7;' : 'border-bottom: 1px solid #F3F4F6;';

        var disabledAttr = isRestricted ? ' disabled' : '';

        var cursorStyle = isRestricted ? 'cursor: not-allowed;' : 'cursor: pointer;';

        var titleColor = isRestricted ? '#9CA3AF' : '#111827';



        html += '<tr style="' + rowStyle + '" class="' + (isRestricted ? 'ai-policy-row-restricted' : '') + '">';

        html += '<td style="padding: 14px 16px;"><input type="checkbox" class="policy-checkbox-advanced" data-idx="' + idx + '" onchange="updateAdvancedSelectedCount()"' + disabledAttr + ' style="width: 18px; height: 18px; ' + cursorStyle + '"></td>';

        html += '<td style="padding: 14px 16px;">';

        html += '<div style="font-weight: 600; color: ' + titleColor + ';">' + policy.title;

        if (isRestricted) {

            html += ' <span style="font-size: 10px; padding: 2px 6px; background: #FEF3C7; color: #92400E; border-radius: 4px; font-weight: 600; margin-left: 6px;">PRO</span>';

        }

        html += '</div>';

        html += '<div style="font-size: 12px; color: #9CA3AF; margin-top: 2px; font-family: monospace;">' + policy.code + '</div>';

        html += '</td>';

        html += '<td style="padding: 14px 16px; font-size: 13px; color: #6B7280;">' + policy.desc + '</td>';

        html += '<td style="padding: 14px 16px;">' + platforms.map(function(p) {

            var color = p === 'Web' ? '#F59E0B' : p === 'Android' ? '#2563EB' : '#8B5CF6';

            return '<span style="display: inline-block; padding: 4px 8px; background: ' + color + '20; color: ' + color + '; border-radius: 6px; font-size: 11px; font-weight: 600; margin-right: 4px;">' + p + '</span>';

        }).join('') + '</td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><select class="sfx-policy-action" data-idx="' + idx + '" data-type="advanced"' + disabledAttr + ' style="padding: 6px 10px; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 13px; font-weight: 500; ' + cursorStyle + '"><option value="default"' + (policy.action === 'default' ? ' selected' : '') + '>Default</option><option value="reject"' + (policy.action === 'reject' ? ' selected' : '') + '>Reject</option><option value="approve"' + (policy.action === 'approve' ? ' selected' : '') + '>Approve</option><option value="review"' + (policy.action === 'review' ? ' selected' : '') + '>Review</option></select></td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><input type="number" class="sfx-policy-score" data-idx="' + idx + '" data-type="advanced" value="' + policy.score_value + '" min="0" max="100"' + disabledAttr + ' style="width: 70px; padding: 6px 8px; border: 1.5px solid #E5E7EB; border-radius: 6px; text-align: center; font-size: 13px; font-weight: 500; ' + cursorStyle + '"></td>';

        html += '<td style="padding: 14px 16px; text-align: center;"><label class="sfx-toggle' + (isRestricted ? ' sfx-toggle-disabled' : '') + '"><input type="checkbox" class="sfx-policy-active" data-idx="' + idx + '" data-type="advanced"' + (policy.active == 1 ? ' checked' : '') + disabledAttr + '><span class="sfx-toggle-slider' + (policy.active == 1 ? ' checked' : '') + '"></span></label></td>';

        html += '</tr>';

    });

    jQuery('#advanced-policies-tbody').html(html);

    jQuery('#advanced-policies-loading').hide();

    jQuery('#advanced-policies-table').show();

    updateAdvancedStats();

    updateStats();

    attachPolicyHandlers();

    updatePolicyQuotas();

}



function autoSavePolicies(type) {

    var policies = type === 'default' ? sfxDefaultPolicies : sfxAdvancedPolicies;



    var endpoint = type === 'default'

    ? 'post_sensfrx_default_policy_options'

    : 'post_sensfrx_advance_policy';



    // Sanitize data before sending

    var sanitizedPolicies = sanitizePolicies(policies);



    jQuery.ajax({

        url: sensfrxData.restUrl + endpoint,

        method: 'POST',

        headers: { 'X-WP-Nonce': sensfrxData.nonce, 'Content-Type': 'application/json' },

        data: JSON.stringify({ policies: sanitizedPolicies }),

        success: function(response) {

            // Show subtle success feedback

            showToast(type === 'default' ? 'Smart protections updated' : 'AI protections updated', 'success', 2500);

        },

        error: function(xhr, status, error) {



            // Extract actual error message from API response

            var errorMessage = 'Failed to save. Please try again.';

            try {

                var response = JSON.parse(xhr.responseText);

                if (response.message) {

                    errorMessage = response.message;

                } else if (response.error_message) {

                    errorMessage = response.error_message;

                }

            } catch(e) {

            }



            showAlert('Auto-save Failed', errorMessage, 'error');

        }

    });

}



function attachPolicyHandlers() {

    jQuery('.sfx-policy-action').off('change').on('change', function() {

        var idx = jQuery(this).data('idx');

        var type = jQuery(this).data('type');

        if (type === 'default') sfxDefaultPolicies[idx].action = jQuery(this).val();

        else sfxAdvancedPolicies[idx].action = jQuery(this).val();



        // Auto-save when action changes

        autoSavePolicies(type);

    });



    jQuery('.sfx-policy-score').off('change input').on('change input', function() {

        var idx = jQuery(this).data('idx');

        var type = jQuery(this).data('type');

        var val = parseInt(jQuery(this).val());



        // Validate: must be between 0 and 100

        if (isNaN(val) || val < 0) {

            val = 0;

        } else if (val > 100) {

            val = 100;

        }



        // Update input field to show corrected value

        jQuery(this).val(val);



        if (type === 'default') sfxDefaultPolicies[idx].score_value = val;

        else sfxAdvancedPolicies[idx].score_value = val;



        // Auto-save only on change (not on every input)

        if (event.type === 'change') {

            autoSavePolicies(type);

        }

    });



    jQuery('.sfx-policy-active').off('change').on('change', function() {

        var idx = jQuery(this).data('idx');

        var type = jQuery(this).data('type');

        var checked = jQuery(this).is(':checked');

        var $toggle = jQuery(this);



        // Note: No quota limits on Smart Protection or AI Protection policies

        // These are unlimited for all users who have access



        if (type === 'default') {

            sfxDefaultPolicies[idx].active = checked ? 1 : 0;

            updateDefaultStats();

            updateStats();

        } else {

            sfxAdvancedPolicies[idx].active = checked ? 1 : 0;

            updateAdvancedStats();

            updateStats();

        }



        $toggle.next().toggleClass('checked', checked);



        // Update quota display immediately

        updatePolicyQuotas();



        // Auto-save when toggle changes

        autoSavePolicies(type);

    });

}



// Show quota exceeded modal

function showQuotaExceededModal(limit, currentUsage) {

    const modalHtml = `

        <div id="quota-exceeded-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); z-index: 99999; display: flex; align-items: center; justify-content: center;">

            <div style="background: white; border-radius: 12px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); max-width: 500px; width: 90%; padding: 32px;">

                <div style="text-align: center; margin-bottom: 24px;">

                    <div style="display: inline-flex; align-items: center; justify-content: center; width: 64px; height: 64px; background: #FEE2E2; border-radius: 50%; margin-bottom: 16px;">

                        <svg style="width: 32px; height: 32px; color: #DC2626;" fill="none" stroke="currentColor" viewBox="0 0 24 24">

                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>

                        </svg>

                    </div>

                    <h3 style="font-size: 20px; font-weight: 700; color: #111827; margin: 0 0 8px 0;">Policy Quota Limit Reached</h3>

                    <p style="font-size: 14px; color: #6B7280; margin: 0;">You have reached your plan's policy limit</p>

                </div>



                <div style="background: #F9FAFB; border-radius: 8px; padding: 20px; margin-bottom: 24px;">

                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">

                        <span style="font-size: 14px; color: #6B7280;">Policies Enabled:</span>

                        <span style="font-size: 18px; font-weight: 700; color: #DC2626;">${currentUsage} / ${limit}</span>

                    </div>

                    <div style="width: 100%; height: 8px; background: #E5E7EB; border-radius: 4px; overflow: hidden;">

                        <div style="width: 100%; height: 100%; background: #DC2626;"></div>

                    </div>

                </div>



                <p style="font-size: 14px; color: #374151; line-height: 1.6; margin-bottom: 24px;">

                    You have enabled <strong>${currentUsage}</strong> out of <strong>${limit}</strong> allowed policies. To enable more policies, please upgrade your plan or disable some existing policies.

                </p>



                <div style="display: flex; gap: 12px;">

                    <button id="close-quota-modal" style="flex: 1; padding: 12px 24px; background: #F3F4F6; color: #374151; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer;">

                        Close

                    </button>

                    <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-fraud-prevention-for-woocommerce-settings') ); ?>" style="flex: 1; padding: 12px 24px; background: #DC2626; color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; text-decoration: none; text-align: center; display: block;">

                        Upgrade Plan

                    </a>

                </div>

            </div>

        </div>

    `;



    // Remove existing modal if any

    jQuery('#quota-exceeded-modal').remove();



    // Add modal to page

    jQuery('body').append(modalHtml);



    // Close modal on button click or backdrop click

    jQuery('#close-quota-modal, #quota-exceeded-modal').on('click', function(e) {

        if (e.target.id === 'close-quota-modal' || e.target.id === 'quota-exceeded-modal') {

            jQuery('#quota-exceeded-modal').remove();

        }

    });

}



// Sanitize policy data before sending to API

function sanitizePolicies(policies) {

    return policies.map(function(policy) {

        // Create clean copy with all properties

        var cleanPolicy = {};

        for (var key in policy) {

            if (policy.hasOwnProperty(key)) {

                cleanPolicy[key] = policy[key];

            }

        }



        // Ensure active is strictly 0 or 1 integer

        var activeValue = policy.active;

        if (activeValue === true || activeValue === 1 || activeValue === '1') {

            cleanPolicy.active = 1;

        } else {

            cleanPolicy.active = 0;

        }



        // Ensure score_value is integer between 1-100

        var scoreValue = parseInt(policy.score_value);

        if (isNaN(scoreValue) || scoreValue < 1 || scoreValue > 100) {

            cleanPolicy.score_value = 50; // Default to 50 if invalid

        } else {

            cleanPolicy.score_value = scoreValue;

        }



        return cleanPolicy;

    });

}



jQuery(document).ready(function($) {

    $('#save-default-policies').on('click', function() {

        var $btn = $(this);

        $btn.prop('disabled', true).html('<div style="width: 16px; height: 16px; border: 2px solid white; border-top-color: transparent; border-radius: 50%; animation: spin 0.6s linear infinite;"></div> Saving...');





        // Sanitize data before sending

        var sanitizedPolicies = sanitizePolicies(sfxDefaultPolicies);



        // Check active values in sanitized data

        var activeValues = sanitizedPolicies.map(function(p) {

            return {code: p.code, active: p.active, type: typeof p.active};

        });



        var jsonData = JSON.stringify(sanitizedPolicies);



        $.ajax({

            url: sensfrxData.restUrl + 'post_sensfrx_default_policy_options',

            method: 'POST',

            headers: { 'X-WP-Nonce': sensfrxData.nonce, 'Content-Type': 'application/json' },

            data: jsonData,

            beforeSend: function(xhr) {

            },

            success: function(response) {

                $btn.prop('disabled', false).html('<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/></svg> Save Changes');

                showToast('All protections saved successfully', 'success', 3000);

            },

            error: function(xhr, status, error) {



                // Extract actual error message from API response

                var errorMessage = 'Save failed. Please try again.';

                try {

                    var response = JSON.parse(xhr.responseText);

                    if (response.message) {

                        errorMessage = response.message;

                    } else if (response.error_message) {

                        errorMessage = response.error_message;

                    }

                } catch(e) {

                }



                $btn.prop('disabled', false).html('<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/></svg> Save Changes');

                showAlert('Save Failed', errorMessage, 'error');

            }

        });

    });

    

    $('#save-advanced-policies').on('click', function() {

        var $btn = $(this);

        $btn.prop('disabled', true).html('<div style="width: 16px; height: 16px; border: 2px solid white; border-top-color: transparent; border-radius: 50%; animation: spin 0.6s linear infinite;"></div> Saving...');





        // Sanitize data before sending

        var sanitizedPolicies = sanitizePolicies(sfxAdvancedPolicies);



        $.ajax({

            url: sensfrxData.restUrl + 'post_sensfrx_advance_policy',

            method: 'POST',

            headers: { 'X-WP-Nonce': sensfrxData.nonce, 'Content-Type': 'application/json' },

            data: JSON.stringify(sanitizedPolicies),

            beforeSend: function(xhr) {

            },

            success: function(response) {

                $btn.prop('disabled', false).html('<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/></svg> Save Changes');

                showToast('All AI protections saved successfully', 'success', 3000);

            },

            error: function(xhr, status, error) {



                // Extract actual error message from API response

                var errorMessage = 'Save failed. Please try again.';

                try {

                    var response = JSON.parse(xhr.responseText);

                    if (response.message) {

                        errorMessage = response.message;

                    } else if (response.error_message) {

                        errorMessage = response.error_message;

                    }

                } catch(e) {

                }



                $btn.prop('disabled', false).html('<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" stroke="white" stroke-width="2"/></svg> Save Changes');

                showAlert('Save Failed', errorMessage, 'error');

            }

        });

    });

});



// Toggle switch CSS (add to head or inline styles)





// ========================================

// BULK ACTIONS & FILTERING FUNCTIONS

// ========================================



function bulkActionDefault(action) {

    var count = 0;

    var actionLabel = '';



    if (action === 'enable-high-risk') {

        sfxDefaultPolicies.forEach(function(p) {

            if (p.action === 'reject') {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'high-risk rules';

    } else if (action === 'enable-account') {

        sfxDefaultPolicies.forEach(function(p) {

            if (p.tag && p.tag.includes('Account Security')) {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'Account Security rules';

    } else if (action === 'enable-transaction') {

        sfxDefaultPolicies.forEach(function(p) {

            if (p.tag && p.tag.includes('Transaction')) {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'Transaction rules';

    } else if (action === 'enable-all') {

        sfxDefaultPolicies.forEach(function(p) {

            p.active = 1;

            count++;

        });

        actionLabel = 'all rules';

    } else if (action === 'disable-all') {

        sfxDefaultPolicies.forEach(function(p) {

            p.active = 0;

            count++;

        });

        actionLabel = 'all rules';

    }



    renderDefaultPolicies();

    updateDefaultStats();

    autoSavePolicies('default');

    showToast('Updated ' + count + ' ' + actionLabel, 'success', 3000);

}



function bulkActionAdvanced(action) {

    var count = 0;

    var actionLabel = '';



    if (action === 'enable-high-risk') {

        sfxAdvancedPolicies.forEach(function(p) {

            if (p.action === 'reject') {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'high-risk rules';

    } else if (action === 'enable-account') {

        sfxAdvancedPolicies.forEach(function(p) {

            if (p.tag && p.tag.includes('Account Security')) {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'Account Security rules';

    } else if (action === 'enable-transaction') {

        sfxAdvancedPolicies.forEach(function(p) {

            if (p.tag && p.tag.includes('Transaction')) {

                p.active = 1;

                count++;

            }

        });

        actionLabel = 'Transaction rules';

    } else if (action === 'enable-all') {

        sfxAdvancedPolicies.forEach(function(p) {

            p.active = 1;

            count++;

        });

        actionLabel = 'all rules';

    } else if (action === 'disable-all') {

        sfxAdvancedPolicies.forEach(function(p) {

            p.active = 0;

            count++;

        });

        actionLabel = 'all rules';

    }



    renderAdvancedPolicies();

    updateAdvancedStats();

    autoSavePolicies('advanced');

    showToast('Updated ' + count + ' ' + actionLabel, 'success', 3000);

}



function filterDefaultPolicies() {

    var searchTerm = jQuery('#search-default').val().toLowerCase();

    var tagFilter = jQuery('#filter-default-tag').val();

    var riskFilter = jQuery('#filter-default-risk').val();

    var statusFilter = jQuery('#filter-default-status').val();



    jQuery('#default-policies-tbody tr').each(function() {

        var $row = jQuery(this);

        var text = $row.text().toLowerCase();

        var idx = $row.find('[data-idx]').first().data('idx');

        var policy = sfxDefaultPolicies[idx];



        var matchSearch = !searchTerm || text.indexOf(searchTerm) > -1;

        var matchTag = !tagFilter || (policy.tag && policy.tag.includes(tagFilter));

        var matchRisk = !riskFilter || policy.action === riskFilter;

        var matchStatus = !statusFilter || policy.active == parseInt(statusFilter);



        if (matchSearch && matchTag && matchRisk && matchStatus) {

            $row.show();

        } else {

            $row.hide();

        }

    });

}



function filterAdvancedPolicies() {

    var searchTerm = jQuery('#search-advanced').val().toLowerCase();

    var tagFilter = jQuery('#filter-advanced-tag').val();

    var riskFilter = jQuery('#filter-advanced-risk').val();

    var statusFilter = jQuery('#filter-advanced-status').val();



    jQuery('#advanced-policies-tbody tr').each(function() {

        var $row = jQuery(this);

        var text = $row.text().toLowerCase();

        var idx = $row.find('[data-idx]').first().data('idx');

        var policy = sfxAdvancedPolicies[idx];



        var matchSearch = !searchTerm || text.indexOf(searchTerm) > -1;

        var matchTag = !tagFilter || (policy.tag && policy.tag.includes(tagFilter));

        var matchRisk = !riskFilter || policy.action === riskFilter;

        var matchStatus = !statusFilter || policy.active == parseInt(statusFilter);



        if (matchSearch && matchTag && matchRisk && matchStatus) {

            $row.show();

        } else {

            $row.hide();

        }

    });

}



function updateDefaultStats() {

    var enabledCount = 0;

    var highRiskCount = 0;

    var tagsSet = new Set();



    sfxDefaultPolicies.forEach(function(p) {

        if (p.active == 1) {

            enabledCount++;

            if (p.action === 'reject') highRiskCount++;

        }

        if (p.tag && Array.isArray(p.tag)) {

            p.tag.forEach(function(t) { tagsSet.add(t); });

        }

    });



    var protectionLevel = enabledCount === 0 ? 'None' :

                         enabledCount < 15 ? 'Basic' :

                         enabledCount < 32 ? 'Balanced' : 'Maximum';



    jQuery('#default-enabled-count').text(enabledCount);

    jQuery('#default-high-risk-count').text(highRiskCount);

    jQuery('#default-tags-count').text(tagsSet.size);

    jQuery('#default-protection-level').text(protectionLevel);

    jQuery('#default-stats').show();

}



function updateAdvancedStats() {

    var enabledCount = 0;

    var highRiskCount = 0;

    var tagsSet = new Set();



    sfxAdvancedPolicies.forEach(function(p) {

        if (p.active == 1) {

            enabledCount++;

            if (p.action === 'reject') highRiskCount++;

        }

        if (p.tag && Array.isArray(p.tag)) {

            p.tag.forEach(function(t) { tagsSet.add(t); });

        }

    });



    var protectionLevel = enabledCount === 0 ? 'None' :

                         enabledCount < 6 ? 'Basic' :

                         enabledCount < 12 ? 'Balanced' : 'Maximum';



    jQuery('#advanced-enabled-count').text(enabledCount);

    jQuery('#advanced-high-risk-count').text(highRiskCount);

    jQuery('#advanced-tags-count').text(tagsSet.size);

    jQuery('#advanced-protection-level').text(protectionLevel);

    jQuery('#advanced-stats').show();

}



// Bulk selection and toggle functions for policies

function toggleSelectAllDefault() {

    const selectAll = document.getElementById('select-all-default');

    const checkboxes = document.querySelectorAll('.policy-checkbox-default');

    checkboxes.forEach(cb => cb.checked = selectAll.checked);

    updateDefaultSelectedCount();

}



function toggleSelectAllAdvanced() {

    const selectAll = document.getElementById('select-all-advanced');

    const checkboxes = document.querySelectorAll('.policy-checkbox-advanced');

    checkboxes.forEach(cb => cb.checked = selectAll.checked);

    updateAdvancedSelectedCount();

}



function updateDefaultSelectedCount() {

    const count = document.querySelectorAll('.policy-checkbox-default:checked').length;

    document.getElementById('default-selected-count').textContent = count;

    document.getElementById('default-selected-count-2').textContent = count;

    const bulkEnableBtn = document.getElementById('bulk-enable-default');

    const bulkDisableBtn = document.getElementById('bulk-disable-default');

    bulkEnableBtn.style.display = count > 0 ? 'block' : 'none';

    bulkDisableBtn.style.display = count > 0 ? 'block' : 'none';

}



function updateAdvancedSelectedCount() {

    const count = document.querySelectorAll('.policy-checkbox-advanced:checked').length;

    document.getElementById('advanced-selected-count').textContent = count;

    document.getElementById('advanced-selected-count-2').textContent = count;

    const bulkEnableBtn = document.getElementById('bulk-enable-advanced');

    const bulkDisableBtn = document.getElementById('bulk-disable-advanced');

    bulkEnableBtn.style.display = count > 0 ? 'block' : 'none';

    bulkDisableBtn.style.display = count > 0 ? 'block' : 'none';

}



function bulkToggleDefault(enable) {

    document.querySelectorAll('.policy-checkbox-default:checked').forEach(cb => {

        const idx = cb.dataset.idx;

        sfxDefaultPolicies[idx].active = enable ? 1 : 0;

        const toggle = document.querySelector('.sfx-policy-active[data-type="default"][data-idx="' + idx + '"]');

        toggle.checked = enable;

        toggle.parentElement.querySelector('.sfx-toggle-slider').classList.toggle('checked', enable);

    });

    updateDefaultStats();

    updateStats();

    showToast(enable ? 'Policies enabled' : 'Policies disabled', 'info');

}



function bulkToggleAdvanced(enable) {

    document.querySelectorAll('.policy-checkbox-advanced:checked').forEach(cb => {

        const idx = cb.dataset.idx;

        sfxAdvancedPolicies[idx].active = enable ? 1 : 0;

        const toggle = document.querySelector('.sfx-policy-active[data-type="advanced"][data-idx="' + idx + '"]');

        toggle.checked = enable;

        toggle.parentElement.querySelector('.sfx-toggle-slider').classList.toggle('checked', enable);

    });

    updateAdvancedStats();

    updateStats();

    showToast(enable ? 'Policies enabled' : 'Policies disabled', 'info');

}



// Update quota displays for policy tabs

// Note: Smart Protection and AI Protection policies are UNLIMITED for all users

// Only Block & Allow Lists have quota restrictions

function updatePolicyQuotas() {

    jQuery.ajax({

        url: sensfrxData.restUrl + 'get_license_info',

        method: 'GET',

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(licenseData) {

            if (licenseData && licenseData.data) {

                const planName = licenseData.data.plan || 'FREE';



                // Calculate enabled policies in both tabs

                const defaultEnabled = sfxDefaultPolicies ? sfxDefaultPolicies.filter(p => p.active == 1).length : 0;

                const advancedEnabled = sfxAdvancedPolicies ? sfxAdvancedPolicies.filter(p => p.active == 1).length : 0;

                const totalEnabled = defaultEnabled + advancedEnabled;



                // Update Smart Protection (default) quota display - ALWAYS UNLIMITED

                jQuery('#default-plan-name').text(planName.toUpperCase());

                jQuery('#default-quota-text').html(

                    '<strong>' + defaultEnabled + '</strong> policies enabled <span style="color: #10B981;">• Unlimited</span><br>' +

                    '<small style="color: #6B7280;">Total across all protection categories: <strong>' + totalEnabled + '</strong> policies active (' + defaultEnabled + ' Smart + ' + advancedEnabled + ' AI)</small>'

                );



                // Update AI Protection (advanced) quota display - ALWAYS UNLIMITED

                jQuery('#advanced-plan-name').text(planName.toUpperCase());

                jQuery('#advanced-quota-text').html(

                    '<strong>' + advancedEnabled + '</strong> policies enabled <span style="color: #10B981;">• Unlimited</span><br>' +

                    '<small style="color: #6B7280;">Total across all protection categories: <strong>' + totalEnabled + '</strong> policies active (' + defaultEnabled + ' Smart + ' + advancedEnabled + ' AI)</small>'

                );

            }

        }

    });

}



// Toggle CSS styles are in the <style> tag above



</script>

