/**
 * Admin JavaScript for WooCommerce Tier and Package Prices
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        let tierIndex = $('.wc-tpp-tier-row').length;
        let packageIndex = $('.wc-tpp-package-row').length;

        // Add tier
        $('.wc-tpp-add-tier').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-tier-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, tierIndex);
            $('.wc-tpp-tiers-container').append(newRow);
            tierIndex++;
        });

        // Remove tier
        $(document).on('click', '.wc-tpp-remove-tier', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to remove this tier?')) {
                $(this).closest('.wc-tpp-tier-row').remove();
            }
        });

        // Add package
        $('.wc-tpp-add-package').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-package-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, packageIndex);
            $('.wc-tpp-packages-container').append(newRow);
            packageIndex++;
        });

        // Remove package
        $(document).on('click', '.wc-tpp-remove-package', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to remove this package?')) {
                $(this).closest('.wc-tpp-package-row').remove();
            }
        });

        // Validate inputs
        $(document).on('input', 'input[name*="[min_qty]"], input[name*="[qty]"]', function() {
            const value = parseInt($(this).val());
            if (value < 1) {
                $(this).val(1);
            }
        });

        $(document).on('input', 'input[name*="[price]"]', function() {
            const value = parseFloat($(this).val());
            if (value < 0) {
                $(this).val(0);
            }
        });
    });

})(jQuery);
