(function ($) {
    $(document).ready(function () {
        // Hide closing hours select if open is selected
        $(document).on('change', '.opening-hours-select', function () {
            const row = $(this).closest('tr');
            if ($(this).val() === 'open' || $(this).val() === 'closed') {
                row.find('.closing-hours-select').addClass('hidden');
                row.find('.col-closing').addClass('hide-closing');
            } else {
                row.find('.closing-hours-select').removeClass('hidden');
                row.find('.col-closing').removeClass('hide-closing');
            }
        });

        $(document).on('click', '.remove-row', function (e) {
            e.preventDefault();
            const row = $(this).closest('tr');
            const prompt = confirm(wcv_days.confirm_remove);
            if (prompt) {
                row.remove();
            }
        });

        $(document).on('click', '#add-work-hours', function (e) {
            e.preventDefault();
            const tbody = $('#opening-hours');
            tbody.append(wcv_days.new_row_data);
        });

        $(document).on('change', '.status', function (e) {
            e.preventDefault();
            if ($(this).is(':checked')) {
                $(this).closest('td').find('input[name="status[]"]').val('1');
            } else {
                $(this).closest('td').find('input[name="status[]"]').val('0');
            }
        });

        $(document).on('click', '.more-actions-trigger', function (e) {
            e.preventDefault();
            const row = $(this).closest('td');
            const moreActions = row.find('.sub-actions');
            moreActions.toggleClass('hidden');
        });

        $(document).on('click', '.add-row-above', function (e) {
            e.preventDefault();
            const row = $(this).closest('tr');
            $(wcv_days.new_row_data).insertBefore(row);
            $(this).closest('.sub-actions').toggleClass('hidden');
        });

        $(document).on('click', '.add-row-below', function (e) {
            e.preventDefault();
            const row = $(this).closest('tr');
            $(wcv_days.new_row_data).insertAfter(row);
            $(this).closest('.sub-actions').toggleClass('hidden');
        });

        // Click outside to close sub-actions
        $(document).on('click', function (e) {
            if (
                !$(e.target).closest('.sub-actions').length &&
                !$(e.target).closest('.more-actions-trigger').length
            ) {
                $('.sub-actions').addClass('hidden');
            }
        });
    });
})(jQuery);
