class SyncManager {

    _pollInterval = null;
    _labels = {};

    init() {
        if (!jQuery('#btn-start-sync')[0]) {
            return;
        }

        this._labels = window.SHOPYPRESS_ADMIN_SETTINGS?.labels || {};
        this._handleEvents();
        this._autoStartPolling();
    }

    _handleEvents() {
        const _this = this;

        // Start sync button
        jQuery('#btn-start-sync').on('click', function(e) {
            e.preventDefault();
            _this._startSync();
        });

        // Reset sync button
        jQuery('#btn-reset-sync').on('click', function(e) {
            e.preventDefault();
            _this._resetSync();
        });
    }

    _startSync() {
        const $btn = jQuery('#btn-start-sync');
        $btn.prop('disabled', true).text('Starting...');

        setTimeout(() => {
            location.reload();
        }, 2000);

        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: {
                action: 'shopypress_start_product_sync',
                nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || ''
            },
            success: (response) => {
                if (response.success) {
                    if (typeof toastr !== 'undefined') {
                        toastr.success(this._labels.syncStarted || 'Sync started');
                    }
                    this._startPolling();
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    if (typeof toastr !== 'undefined') {
                        toastr.error('Failed to start sync');
                    }
                    $btn.prop('disabled', false).text('Start Sync');
                }
            },
            error: () => {
                if (typeof toastr !== 'undefined') {
                    toastr.error('Failed to start sync');
                }
                $btn.prop('disabled', false).text('Start Sync');
            }
        });
    }

    _resetSync() {
        if (!confirm(this._labels.confirmReset || 'Are you sure you want to reset the sync?')) {
            return;
        }

        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: {
                action: 'shopypress_reset_product_sync',
                nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || ''
            },
            success: (response) => {
                if (response.success) {
                    if (typeof toastr !== 'undefined') {
                        toastr.success('Sync reset');
                    }
                    this._stopPolling();
                    setTimeout(() => {
                        location.reload();
                    }, 500);
                }
            },
            error: () => {
                if (typeof toastr !== 'undefined') {
                    toastr.error('Failed to reset sync');
                }
            }
        });
    }

    _startPolling() {
        if (this._pollInterval) {
            return;
        }
        this._pollInterval = setInterval(() => this._pollSyncStatus(), 2000);
    }

    _stopPolling() {
        if (this._pollInterval) {
            clearInterval(this._pollInterval);
            this._pollInterval = null;
        }
    }

    _pollSyncStatus() {
        jQuery.ajax({
            url: window.SHOPYPRESS_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: {
                action: 'shopypress_get_sync_status',
                nonce: window.SHOPYPRESS_ADMIN_SETTINGS?.nonce || ''
            },
            success: (response) => {
                if (response.success && response.data.state) {
                    this._updateSyncUI(response.data.state);

                    if (response.data.state.status !== 'working') {
                        this._stopPolling();
                        location.reload();
                    }
                }
            },
            error: () => {
                // Silently handle polling errors
                this._stopPolling();
            }
        });
    }

    _updateSyncUI(state) {
        if (!state) {
            return;
        }

        const progress = (state.total_products > 0) ?
            (state.total_processed / state.total_products * 100) : 0;

        const $progressBar = jQuery('#sync-progress-bar');
        if ($progressBar.length) {
            $progressBar.css('width', progress + '%')
                .attr('aria-valuenow', progress);

            jQuery('#sync-progress-text').text(Math.round(progress) + '%');
            jQuery('#sync-progress-details').text(
                state.total_processed + ' ' +
                (this._labels.of || 'of') + ' ' +
                state.total_products + ' ' +
                (this._labels.productsProcessed || 'products processed')
            );
        }
    }

    _autoStartPolling() {
        // Check if sync is currently working (via data attribute or class)
        const isSyncWorking = jQuery('#sync-status-container').find('.badge.bg-primary').length > 0;

        if (isSyncWorking) {
            this._startPolling();
        }
    }
}

export default SyncManager;
