<script>
    $(document).ready(function () {
        'use strict';

        // Initialize tooltips
        if (typeof $('[data-bs-toggle="tooltip"]').tooltip === 'function') {
            $('[data-bs-toggle="tooltip"]').tooltip();
        }

        // Approve Gold Request
        $(document).on('click', '.approve-gold-btn', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const id = $btn.data('id');
            const originalText = $btn.html();

            Swal.fire({
                title: '<%= i18n.__("products.approveGoldConfirm") %>',
                text: '<%= i18n.__("products.approveGoldConfirmDesc") %>',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28c76f',
                cancelButtonColor: '#82868b',
                confirmButtonText: '<%= i18n.__("products.approveGold") %>',
                cancelButtonText: '<%= i18n.__("common.cancel") %>',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return $.ajax({
                        url: '/dashboard/products/goldRequests/approve/' + id,
                        type: 'PATCH',
                        headers: {
                            'X-CSRF-Token': '<%= csrfToken %>'
                        }
                    }).then(response => {
                        if (response.key !== 'success') {
                            throw new Error(response.message || '<%= i18n.__("common.returnDeveloper") %>');
                        }
                        return response;
                    }).catch(error => {
                        Swal.showValidationMessage(error.responseJSON?.message || error.message || '<%= i18n.__("common.returnDeveloper") %>');
                    });
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed && result.value) {
                    Swal.fire({
                        icon: 'success',
                        title: result.value.message || '<%= i18n.__("products.goldRequestCreatedSuccessfully") %>',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                }
            });
        });

        // Reject Gold Request
        $(document).on('click', '.reject-gold-btn', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const id = $btn.data('id');

            Swal.fire({
                title: '<%= i18n.__("products.rejectGoldConfirm") %>',
                text: '<%= i18n.__("products.rejectGoldConfirmDesc") %>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ea5455',
                cancelButtonColor: '#82868b',
                confirmButtonText: '<%= i18n.__("products.rejectGold") %>',
                cancelButtonText: '<%= i18n.__("common.cancel") %>',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return $.ajax({
                        url: '/dashboard/products/goldRequests/reject/' + id,
                        type: 'PATCH',
                        headers: {
                            'X-CSRF-Token': '<%= csrfToken %>'
                        }
                    }).then(response => {
                        if (response.key !== 'success') {
                            throw new Error(response.message || '<%= i18n.__("common.returnDeveloper") %>');
                        }
                        return response;
                    }).catch(error => {
                        Swal.showValidationMessage(error.responseJSON?.message || error.message || '<%= i18n.__("common.returnDeveloper") %>');
                    });
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed && result.value) {
                    Swal.fire({
                        icon: 'success',
                        title: result.value.message || '<%= i18n.__("products.rejectGold") %>',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                }
            });
        });

        // Refresh button
        $(document).on('click', '.refresh-btn', function (e) {
            e.preventDefault();
            location.reload();
        });

        // Admin rate (stars)
        $(document).on('mouseenter', '.rate-star', function () {
            const val = parseInt($(this).data('value'), 10);
            $('#adminRateStars .rate-star').each(function () {
                const s = parseInt($(this).data('value'), 10);
                if (s <= val) {
                    $(this).removeClass('ti-star text-muted').addClass('ti-star-filled text-warning');
                } else {
                    $(this).removeClass('ti-star-filled text-warning').addClass('ti-star text-muted');
                }
            });
        });

        $(document).on('mouseleave', '#adminRateStars', function () {
            const current = parseInt($('#adminRateInput').val() || '0', 10);
            $('#adminRateStars .rate-star').each(function () {
                const s = parseInt($(this).data('value'), 10);
                if (s <= current) {
                    $(this).removeClass('ti-star text-muted').addClass('ti-star-filled text-warning');
                } else {
                    $(this).removeClass('ti-star-filled text-warning').addClass('ti-star text-muted');
                }
            });
        });

        $(document).on('click', '.rate-star', function () {
            const val = parseInt($(this).data('value'), 10);
            $('#adminRateInput').val(val);
            $('#adminRateValue').text(val);
            $('#adminRateStars').trigger('mouseleave');
        });

        // Submit admin rate
        $(document).on('submit', '#adminRateForm', function (e) {
            e.preventDefault();

            const productId = ($(this).data('product-id') || '').toString();
            // Guard: this form exists only on show page; if no product id, do nothing.
            if (!productId) return;
            const rate = parseInt($('#adminRateInput').val() || '0', 10);

            if (!rate || rate < 1 || rate > 5) {
                Swal.fire({
                    icon: 'warning',
                    title: '<%= i18n.__("common.rate") %>',
                    text: '<%= i18n.__("common.invalidRate") %>',
                });
                return;
            }

            const url = '/dashboard/products/goldRequests/rate/' + productId;
            const payload = {
                rate,
                comment: ($('#adminRateComment').val() || '').toString(),
            };

            $.ajax({
                url,
                type: 'PATCH',
                data: payload,
                headers: {
                    'X-CSRF-Token': '<%= csrfToken %>'
                }
            }).done(function (resp) {
                if (resp.key !== 'success') {
                    Swal.fire({ icon: 'error', title: resp.message || '<%= i18n.__("common.returnDeveloper") %>' });
                    return;
                }
                Swal.fire({
                    icon: 'success',
                    title: resp.message || '<%= i18n.__("products.rateSaved") %>',
                    timer: 1200,
                    showConfirmButton: false
                });
            }).fail(function (xhr) {
                Swal.fire({
                    icon: 'error',
                    title: xhr.responseJSON?.message || '<%= i18n.__("common.returnDeveloper") %>',
                });
            });
        });
    });
</script>