async function checkMembership() {
    return await new Promise(function (resolve, reject) {
        chrome.runtime.sendMessage({
            type: 'checkMembership',
            // Sniper List features (Sell Similar, Bulk Revise, Boost My Listings)
            // require an actual paid plan — trial accounts should not pass.
            requirePaidOnly: true
        }, function (response) {
            const lastError = chrome.runtime.lastError;
            if (lastError) {
                console.error('checkMembership failed:', lastError.message);
                reject(new Error(lastError.message));
                return;
            }
            // NOTE: response.membership is only ever 'active' | 'none' | 'expired' —
            // it is NOT a plan name. The background script already resolves
            // paid-vs-not-paid for us via response.allowed, so that's the field
            // to trust here rather than comparing membership to a tier string.
            if (!response || typeof response.allowed === 'undefined') {
                console.error('checkMembership: invalid/empty response from background script', response);
                reject(new Error('No membership info returned from background script.'));
                return;
            }
            console.log('result: ', response.membership, 'allowed:', response.allowed);
            resolve(!!response.allowed);
        });
    });
}
async function checkCredits() {
    return await new Promise(function (resolve, reject) {
        chrome.runtime.sendMessage({
            type: 'checkCredits'
        }, function (response) {
            const lastError = chrome.runtime.lastError;
            if (lastError) {
                console.error('checkCredits failed:', lastError.message);
                reject(new Error(lastError.message));
                return;
            }
            if (!response || typeof response.creditsAvailable === 'undefined') {
                console.error('checkCredits: invalid/empty response from background script', response);
                reject(new Error('No credits info returned from background script.'));
                return;
            }
            console.log('result: ', response.creditsAvailable);
            resolve(response.creditsAvailable);
        });
    });
}
async function gateFeatureByCredits(creditAmount) {
    if (!await checkMembership()) return {
        success: false,
        message: 'You must be a paid member to use this feature.'
    };
    if (0 == await checkCredits()) return {
        success: false,
        message: 'You have no credits available.'
    };
    return chrome.runtime.sendMessage({
        type: 'deductCredits',
        amount: creditAmount
    }), {
        success: true,
        message: 'Credits deducted.'
    };
}
console.log('script.js loaded');
const OFFER_PERCENT_STORAGE_KEY = 'watcherOfferPercent',
    DEFAULT_OFFER_PERCENT = 5;

function clampOfferPercent(value) {
    return Number.isFinite(value) ? Math.min(100, Math.max(0, value)) : 5;
}
async function loadOfferPercentIntoInput(inputEl) {
    if (!inputEl) return;
    const stored = await chrome.storage.local.get(OFFER_PERCENT_STORAGE_KEY),
        storedNumber = Number(stored[OFFER_PERCENT_STORAGE_KEY]),
        clamped = clampOfferPercent(storedNumber);
    inputEl.value = clamped, Number.isFinite(storedNumber) || await chrome.storage.local.set({
        [OFFER_PERCENT_STORAGE_KEY]: clamped
    });
}
const offerPercentInput = document.getElementById('offer_percent_input'),
    sendOffersButton = document.getElementById('send_offers_button'),
    sendOffersLabel = sendOffersButton ? sendOffersButton.querySelector('.label') : null,
    bestOfferMarkupInput = document.getElementById('best_offer_markup_multiplier'),
    reviewOffersButton = document.getElementById('review_offers_button'),
    reviewOffersLabel = reviewOffersButton ? reviewOffersButton.querySelector('.label') : null;

function setSendOffersButtonState({
    loading,
    labelText,
    completed
} = {}) {
    sendOffersButton && ('string' == typeof labelText && sendOffersLabel && (sendOffersLabel.textContent = labelText), 'boolean' == typeof loading && (sendOffersButton.disabled = loading, sendOffersButton.classList.toggle('is-loading', loading)), completed && (sendOffersButton.classList.add('completed'), setTimeout(() => sendOffersButton.classList.remove('completed'), 600)));
}
offerPercentInput && (loadOfferPercentIntoInput(offerPercentInput), offerPercentInput.addEventListener('change', async () => {
    const clamped = clampOfferPercent(Number(offerPercentInput.value));
    offerPercentInput.value = clamped, await chrome.storage.local.set({
        [OFFER_PERCENT_STORAGE_KEY]: clamped
    });
}));
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    return console.log('message received in script.js', message), 'progress-update' == message.type && (console.log('progress-update message received in script.js'), updateProgress(message.progress, message.message)), 'restart-sell-similar-tab' == message.type && (console.log('restart-sell-similar-tab message received in script.js'), restartSellSimilarTab()), 'start-boost-my-listings' == message.type && (console.log('start-boost-my-listings message received in script.js'), handleStartBoostMyListings()), true;
});
async function handleStartBoostMyListings() {
    let isPaidMember;
    try {
        isPaidMember = await checkMembership();
    } catch (err) {
        console.error('handleStartBoostMyListings: membership check failed', err);
        alert('Could not verify your membership. Please try again in a moment.');
        return;
    }
    console.log('membership allowed:', isPaidMember);
    if (isPaidMember) {
        var {
            sellSimilarScheduleAutomation
        } = await chrome.storage.local.get('sellSimilarScheduleAutomation'), {
            reviseListingScheduleAutomation
        } = await chrome.storage.local.get('reviseListingScheduleAutomation');
        sellSimilarScheduleAutomation && (document.getElementById('end_and_sell_similar_button').disabled = true, await runEndAndSellSimilar(), document.getElementById('end_and_sell_similar_button').disabled = false), reviseListingScheduleAutomation && (document.getElementById('bulk_revise_listing_button').disabled = true, await runBulkReviseListing(), document.getElementById('bulk_revise_listing_button').disabled = false);
    } else alert('You are not a member of the sniper list. Please contact support.'), endAndSellSimilarButton.disabled = false;
}
async function restartSellSimilarTab() {
    console.log('restartSellSimilarTab'), await new Promise(r => setTimeout(r, 2000)), updateProgress(0, 'Restarting until no more low performing items'), await new Promise(r => setTimeout(r, 2000)), document.getElementById('end_and_sell_similar_button').click();
}
var endAndSellSimilarButton = document.getElementById('end_and_sell_similar_button');
endAndSellSimilarButton.addEventListener('click', async function () {
    endAndSellSimilarButton.disabled = true;
    let isPaidMember;
    try {
        isPaidMember = await checkMembership();
    } catch (err) {
        console.error('end_and_sell_similar_button: membership check failed', err);
        alert('Could not verify your membership. Please try again in a moment.');
        endAndSellSimilarButton.disabled = false;
        return;
    }
    console.log('membership allowed:', isPaidMember), isPaidMember ? (console.log('end_and_sell_similar_button clicked'), await runEndAndSellSimilar(), endAndSellSimilarButton.disabled = false) : (alert('You are not a member of the sniper list. Please contact support.'), endAndSellSimilarButton.disabled = false);
});
async function runEndAndSellSimilar() {
    var minSoldValue = document.getElementById('minSold').value,
        minViewsValue = document.getElementById('minViews').value,
        filterByHours = document.getElementById('timeLeft').value;
    updateProgress(0, '0% Attempting to end low performing items... Please wait.');
    const rawResponse = await new Promise(resolve => {
        chrome.runtime.sendMessage({
            type: 'end-and-sell-similar-button-clicked',
            minSold: minSoldValue,
            minViews: minViewsValue,
            filterByHours: filterByHours
        }, function (resp) {
            const lastError = chrome.runtime.lastError;
            if (lastError) console.error('end-and-sell-similar-button-clicked failed:', lastError.message);
            console.log(resp), resolve(resp);
        });
    });
    if (!rawResponse || !rawResponse.response || typeof rawResponse.response.status !== 'string') {
        console.error('runEndAndSellSimilar: no valid response from background script', rawResponse);
        updateProgress(100, '100% Error: background script did not respond. Please try again.');
        return;
    }
    const response = rawResponse.response;
    updateProgress(100, '100% ' + response.status);
    var {
        autoRepeatSellSimilarTab
    } = await chrome.storage.local.get('autoRepeatSellSimilarTab');
    response.status.includes('listings are now live') && autoRepeatSellSimilarTab && (await new Promise(r => setTimeout(r, 2000)), updateProgress(0, '0% Restarting until no more low performing items'), await new Promise(r => setTimeout(r, 2000)), await runEndAndSellSimilar());
}

function updateProgress(percent, message) {
    const progressBarEl = document.getElementById('loading_progress'),
        statusMessageEl = document.getElementById('status_message');
    progressBarEl.style.width = percent + '%', statusMessageEl.textContent = message, addLogEntry(percent, message), percent >= 100 && (endAndSellSimilarButton.disabled = false);
}
var minSoldInput = document.getElementById('minSold');
minSoldInput.addEventListener('change', async function () {
    await chrome.storage.local.set({
        minSoldQuantity: minSoldInput.value
    });
});
var minViewsInput = document.getElementById('minViews');
minViewsInput.addEventListener('change', async function () {
    await chrome.storage.local.set({
        minViewCount: minViewsInput.value
    });
});
var timeLeftInput = document.getElementById('timeLeft');
timeLeftInput.addEventListener('change', async function () {
    await chrome.storage.local.set({
        filterByHours: timeLeftInput.value
    });
}), chrome.storage.local.get(['minSoldQuantity', 'minViewCount', 'filterByHours'], function (stored) {
    console.log('Value currently is ' + stored.minSoldQuantity), stored.minSoldQuantity ? minSoldInput.value = stored.minSoldQuantity : chrome.storage.local.set({
        minSoldQuantity: minSoldInput.value
    }), stored.minViewCount ? minViewsInput.value = stored.minViewCount : chrome.storage.local.set({
        minViewCount: minViewsInput.value
    }), stored.filterByHours ? timeLeftInput.value = stored.filterByHours : chrome.storage.local.set({
        filterByHours: timeLeftInput.value
    });
});
var autoCloseToggle = document.getElementById('autoCloseToggle');
autoCloseToggle.addEventListener('change', async function () {
    console.log('autoCloseToggle', autoCloseToggle.checked), await chrome.storage.local.set({
        autoCloseSellSimilarTab: autoCloseToggle.checked
    });
}), chrome.storage.local.get(['autoCloseSellSimilarTab'], function (stored) {
    console.log('autoCloseSellSimilarTab Value currently is ' + stored.autoCloseSellSimilarTab), null == stored.autoCloseSellSimilarTab ? (console.log('autoCloseSellSimilarTab not found'), chrome.storage.local.set({
        autoCloseSellSimilarTab: autoCloseToggle.checked
    })) : (console.log('autoCloseSellSimilarTab found'), autoCloseToggle.checked = stored.autoCloseSellSimilarTab);
});
var autoRepeatToggle = document.getElementById('autoRepeatToggle');
autoRepeatToggle.addEventListener('change', async function () {
    await chrome.storage.local.set({
        autoRepeatSellSimilarTab: autoRepeatToggle.checked
    });
}), chrome.storage.local.get(['autoRepeatSellSimilarTab'], function (stored) {
    console.log('Value currently is ' + stored.autoRepeatSellSimilarTab), null == stored.autoRepeatSellSimilarTab ? chrome.storage.local.set({
        autoRepeatSellSimilarTab: autoRepeatToggle.checked
    }) : autoRepeatToggle.checked = stored.autoRepeatSellSimilarTab;
});
var scheduledTimeEl = document.getElementById('scheduled_time'),
    countdownEl = document.getElementById('countdown'),
    countdownIntervalId = null;

function updateCountdown() {
    chrome.storage.local.get(['scheduledInterval'], function (stored) {
        const intervalHours = stored.scheduledInterval ? parseInt(stored.scheduledInterval) : 24;
        if (!document.getElementById('schedule_toggle').checked) {
            document.getElementById('countdown').textContent = 'Not scheduled', clearInterval(countdownIntervalId);
            return;
        }
        const now = new Date(),
            timeParts = document.getElementById('scheduled_time').value.split(':'),
            hours = parseInt(timeParts[0], 10),
            minutes = parseInt(timeParts[1], 10);
        let nextRun = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes);
        for (; nextRun <= now;) nextRun = new Date(nextRun.getTime() + 3600000 * intervalHours);
        const diffMs = nextRun - now,
            diffHours = Math.floor(diffMs / 3600000),
            diffMinutes = Math.floor(diffMs % 3600000 / 60000),
            diffSeconds = Math.floor(diffMs % 60000 / 1000);
        document.getElementById('countdown').textContent = diffHours + 'h ' + diffMinutes + 'm ' + diffSeconds + 's';
    });
}
document.addEventListener('DOMContentLoaded', function () {
    setInterval(function () {
        const now = new Date();
        document.getElementById('current_time').textContent = now.toLocaleTimeString();
    }, 1000), updateCountdown(), countdownIntervalId = setInterval(updateCountdown, 1000);
});
var scheduleToggle = document.getElementById('schedule_toggle');
scheduleToggle.addEventListener('change', function () {
    chrome.storage.local.set({
        scheduleSellSimilar: scheduleToggle.checked
    });
    var timeUntilScheduleEl = document.getElementById('time_until_schedule');
    scheduleToggle.checked ? (timeUntilScheduleEl.style.display = 'block', countdownIntervalId = setInterval(updateCountdown, 1000), createOrUpdateAlarm(scheduledTimeInput.value, 'scheduleBoostAlarm', scheduledIntervalInput.value)) : (timeUntilScheduleEl.style.display = 'none', clearInterval(countdownIntervalId), removeAlarm('scheduleBoostAlarm'));
}), chrome.storage.local.get(['scheduleSellSimilar'], function (stored) {
    console.log('Value currently is ' + stored.scheduleSellSimilar), scheduleToggle.checked = stored.scheduleSellSimilar || false;
    var timeUntilScheduleEl = document.getElementById('time_until_schedule');
    stored.scheduleSellSimilar ? timeUntilScheduleEl.style.display = 'block' : timeUntilScheduleEl.style.display = 'none';
});
var scheduledTimeInput = document.getElementById('scheduled_time');
scheduledTimeInput.addEventListener('change', function () {
    chrome.storage.local.set({
        scheduledTimeSellSimilar: scheduledTimeInput.value
    }), scheduleToggle.checked && createOrUpdateAlarm(scheduledTimeInput.value, 'scheduleBoostAlarm', scheduledIntervalInput.value);
}), chrome.storage.local.get(['scheduledTimeSellSimilar'], function (stored) {
    console.log('Value currently is ' + stored.scheduledTimeSellSimilar), scheduledTimeInput.value = stored.scheduledTimeSellSimilar || '00:00';
});

function removeAlarm(alarmName) {
    chrome.runtime.sendMessage({
        type: 'removePeriodicAlarm',
        alarmName: alarmName
    });
}

function createOrUpdateAlarm(timeStr, alarmName, intervalMinutes = 24) {
    var periodInMinutes = 60 * intervalMinutes;
    const timeParts = timeStr.split(':'),
        hours = parseInt(timeParts[0], 10),
        minutes = parseInt(timeParts[1], 10),
        now = new Date();
    let when = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes);
    when <= now && when.setDate(when.getDate() + 1), chrome.runtime.sendMessage({
        type: 'createOrUpdateAlarm',
        alarmName: alarmName,
        when: when.getTime(),
        periodInMinutes: periodInMinutes
    });
}
document.addEventListener('DOMContentLoaded', function () {
    const modalTriggers = document.querySelectorAll('[data-modal-target]'),
        modalCloseButtons = document.querySelectorAll('.modal .close');
    document.querySelectorAll('.modal'), modalTriggers.forEach(trigger => {
        trigger.addEventListener('click', () => {
            document.querySelector(trigger.getAttribute('data-modal-target')).style.display = 'block';
        });
    }), modalCloseButtons.forEach(closeBtn => {
        closeBtn.addEventListener('click', () => {
            closeBtn.closest('.modal').style.display = 'none';
        });
    }), window.addEventListener('click', evt => {
        'modal' === evt.target.className && (evt.target.style.display = 'none');
    });
}), document.addEventListener('DOMContentLoaded', async function () {
    var {
        domain
    } = await chrome.storage.local.get(['domain']), activeListingUrl = 'https://www.ebay.' + domain + '/sh/lst/active?action=pagination&sort=timeRemaining&limit=200';
    document.getElementById('activeListingLink').href = activeListingUrl;
    var endedListingUrl = 'https://www.ebay.' + domain + '/sh/lst/ended?status=UNSOLD_NOT_RELISTED&limit=200&sort=-actualEndDate';
    document.getElementById('endedListingLink').href = endedListingUrl;
});
var bulkReviseListingButton = document.getElementById('bulk_revise_listing_button');
bulkReviseListingButton.addEventListener('click', async function () {
    let isPaidMember;
    try {
        isPaidMember = await checkMembership();
    } catch (err) {
        console.error('bulk_revise_listing_button: membership check failed', err);
        alert('Could not verify your membership. Please try again in a moment.');
        return;
    }
    console.log('membership allowed:', isPaidMember);
    if (isPaidMember) bulkReviseListingButton.disabled = true, await runBulkReviseListing(), bulkReviseListingButton.disabled = false;
    else alert('You are not a member of the sniper list. Please contact support.');
});
async function toggleOffersDropdown() {
    var offersDropdown = document.getElementById('offers_dropdown'),
        currentValue = offersDropdown.value;
    offersDropdown.value = 0 == currentValue ? 1 : 0, offersDropdown.dispatchEvent(new Event('change'));
}
async function runBulkReviseListing() {
    updateProgress(0, '0% Starting to revise listings...');
    const rawResponse = await new Promise(resolve => {
        chrome.runtime.sendMessage({
            type: 'bulk-revise-listing-button-clicked'
        }, function (resp) {
            const lastError = chrome.runtime.lastError;
            if (lastError) console.error('bulk-revise-listing-button-clicked failed:', lastError.message);
            console.log(resp), resolve(resp);
        });
    });
    if (!rawResponse || typeof rawResponse.response !== 'string') {
        console.error('runBulkReviseListing: no valid response from background script', rawResponse);
        updateProgress(100, '100% Error: background script did not respond. Please try again.');
        return;
    }
    const response = rawResponse.response;
    console.log('response', response), response.includes('Error occurred') ? updateProgress(100, '100% Error occurred. Please try again later.') : updateProgress(100, '100% ' + response);
    var {
        switchOffer
    } = await chrome.storage.local.get('switchOffer');
    switchOffer && await toggleOffersDropdown();
}
var offersDropdownSelect = document.getElementById('offers_dropdown');
offersDropdownSelect.addEventListener('change', async function () {
    await chrome.storage.local.set({
        offersDropdownOption: offersDropdownSelect.value
    });
}), chrome.storage.local.get(['offersDropdownOption'], function (stored) {
    console.log('Value currently is ' + stored.offersDropdownOption), offersDropdownSelect.value = stored.offersDropdownOption || 0;
});
var logEntries = [];

function addLogEntry(percent, message) {
    const timestamp = new Date().toLocaleTimeString();
    logEntries.push(timestamp + ': ' + percent + '% - ' + message), renderLogList();
}

function renderLogList() {
    document.getElementById('log_list').innerHTML = logEntries.map(entry => '<li>' + entry + '</li>').join('');
}
document.addEventListener('DOMContentLoaded', function () {
    const logButton = document.querySelector('#log_button'),
        logModal = document.querySelector('#log_modal'),
        logModalCloseBtn = logModal.querySelector('.close');
    logButton.addEventListener('click', () => {
        logModal.style.display = 'block';
    }), logModalCloseBtn.addEventListener('click', () => {
        logModal.style.display = 'none';
    }), window.addEventListener('click', evt => {
        evt.target === logModal && (logModal.style.display = 'none');
    });
});
var switchOfferToggle = document.getElementById('switchOfferToggle');
switchOfferToggle.addEventListener('change', async function () {
    console.log('switchOfferToggle', switchOfferToggle.checked), await chrome.storage.local.set({
        switchOffer: switchOfferToggle.checked
    });
}), chrome.storage.local.get(['switchOffer'], function (stored) {
    console.log('switchOffer Value currently is ' + stored.switchOffer), switchOfferToggle.checked = stored.switchOffer, stored.switchOffer || chrome.storage.local.set({
        switchOffer: switchOfferToggle.checked
    });
}), document.getElementById('revise_listing_toggle_schedule_automation').addEventListener('change', async function () {
    const checked = this.checked;
    await chrome.storage.local.set({
        reviseListingScheduleAutomation: checked
    });
}), chrome.storage.local.get('reviseListingScheduleAutomation', function (stored) {
    const reviseListingScheduleAutomation = stored.reviseListingScheduleAutomation;
    void 0 !== reviseListingScheduleAutomation && (document.getElementById('revise_listing_toggle_schedule_automation').checked = reviseListingScheduleAutomation), void 0 === reviseListingScheduleAutomation && chrome.storage.local.set({
        reviseListingScheduleAutomation: false
    });
}), document.getElementById('sell_similar_toggle_schedule_automation').addEventListener('change', async function () {
    const checked = this.checked;
    await chrome.storage.local.set({
        sellSimilarScheduleAutomation: checked
    });
}), chrome.storage.local.get('sellSimilarScheduleAutomation', function (stored) {
    const sellSimilarScheduleAutomation = stored.sellSimilarScheduleAutomation;
    void 0 !== sellSimilarScheduleAutomation && (document.getElementById('sell_similar_toggle_schedule_automation').checked = sellSimilarScheduleAutomation), void 0 === sellSimilarScheduleAutomation && chrome.storage.local.set({
        sellSimilarScheduleAutomation: true
    });
});
var scheduledIntervalInput = document.getElementById('scheduled_interval');
scheduledIntervalInput.addEventListener('change', function () {
    chrome.storage.local.set({
        scheduledInterval: scheduledIntervalInput.value
    });
}), chrome.storage.local.get(['scheduledInterval'], function (stored) {
    console.log('Value currently is ' + stored.scheduledInterval), stored.scheduledInterval && (scheduledIntervalInput.value = stored.scheduledInterval), stored.scheduledInterval || chrome.storage.local.set({
        scheduledInterval: scheduledIntervalInput.value
    });
}), sendOffersButton && sendOffersButton.addEventListener('click', async () => {
    setSendOffersButtonState({
        loading: true,
        labelText: 'Sending...'
    });
    const statusMessageEl = document.getElementById('status_message'),
        percent = clampOfferPercent(offerPercentInput ? Number(offerPercentInput.value) : 5);
    offerPercentInput && (offerPercentInput.value = percent), await chrome.storage.local.set({
        [OFFER_PERCENT_STORAGE_KEY]: percent
    }), statusMessageEl && (statusMessageEl.textContent = 'Sending offers at ' + percent + '% discount...'), chrome.runtime.sendMessage({
        type: 'send-offers-button-clicked',
        percent: percent
    }, resp => {
        const lastError = chrome.runtime.lastError;
        if (lastError) {
            console.error('Error sending offers:', lastError), statusMessageEl && (statusMessageEl.textContent = 'Failed to trigger offers. Please try again.'), setSendOffersButtonState({
                loading: false,
                labelText: 'Send Offers'
            });
            return;
        }
        const success = resp?.response?.success === true;
        statusMessageEl && (statusMessageEl.textContent = success ? 'Offer workflow triggered at ' + percent + '% discount.' : 'Offers could not be sent. Please review the active listings tab.'), success || console.warn('Send offers returned an unsuccessful response:', resp), setSendOffersButtonState({
            loading: false,
            labelText: 'Send Offers',
            completed: success
        });
    });
});
bestOfferMarkupInput && (chrome.storage.local.get('best_offer_markup_multiplier', function (stored) {
    console.log('best_offer_markup_multiplier Value currently is ' + stored.best_offer_markup_multiplier);
    const storedNumber = Number(stored.best_offer_markup_multiplier);
    bestOfferMarkupInput.value = Number.isFinite(storedNumber) ? Math.round(100 * (storedNumber - 1)) : 50;
}), bestOfferMarkupInput.addEventListener('change', async () => {
    const clamped = clampOfferPercent(Number(bestOfferMarkupInput.value));
    bestOfferMarkupInput.value = clamped;
    const multiplier = 1 + clamped / 100;
    await chrome.storage.local.set({
        best_offer_markup_multiplier: multiplier
    });
}));
reviewOffersButton && reviewOffersButton.addEventListener('click', async () => {
    reviewOffersButton.disabled = true, reviewOffersLabel.textContent = 'Reviewing...';
    const statusMessageEl = document.getElementById('status_message');
    statusMessageEl && (statusMessageEl.textContent = 'Reviewing pending offers...'), chrome.runtime.sendMessage({
        type: 'review-offers-button-clicked:boost-my-listings'
    }, resp => {
        const lastError = chrome.runtime.lastError;
        if (lastError) {
            console.error('Error reviewing offers:', lastError), statusMessageEl && (statusMessageEl.textContent = 'Failed to review offers. Please try again.'), reviewOffersButton.disabled = false, reviewOffersLabel.textContent = 'Review Pending Offers';
            return;
        }
        const success = resp?.response?.success === true;
        statusMessageEl && (statusMessageEl.textContent = success ? 'Offers reviewed successfully.' : 'No offers to review.'), reviewOffersButton.disabled = false, reviewOffersLabel.textContent = 'Review Pending Offers', success || console.warn('Review offers returned an unsuccessful response:', resp);
    });
});