// ============================================================
// SECTION 1: Settings with sub-options (stored as objects)
// ============================================================

const settingsWithOptions = [
    {
        elementId: 'enable_stock_monitor',
        storageKey: 'enable_stock_monitor',
        defaultValue: {
            checkbox: false,
            prime_option: 'prime_only',
            restock_quantity: 1
        }
    },
    {
        elementId: 'enable_price_monitor',
        storageKey: 'enable_price_monitor',
        defaultValue: {
            checkbox: false,
            pricing_option: 'markup_pricing',
            markup_percentage: 100,
            price_trigger_threshold: 2
        }
    },
    {
        elementId: 'enable_price_ending_filter',
        storageKey: 'enable_price_ending_filter',
        defaultValue: {
            checkbox: false,
            price_endings: '99, 97, 95'
        }
    },
    {
        elementId: 'enable_delete_policy_violation_items',
        storageKey: 'enable_delete_policy_violation_items',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_delete_items_with_no_sku',
        storageKey: 'enable_delete_items_with_no_sku',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_not_found_on_amazon',
        storageKey: 'enable_delete_items_not_found_on_amazon',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_sku_changed_on_amazon',
        storageKey: 'enable_delete_items_sku_changed_on_amazon',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_with_no_sales',
        storageKey: 'enable_delete_items_with_no_sales',
        defaultValue: {
            checkbox: false,
            action: 'delete',
            sales_threshold: 0,
            days_threshold: 30
        }
    },
    {
        elementId: 'enable_delete_items_with_broken_sku',
        storageKey: 'enable_delete_items_with_broken_sku',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_by_non_chinese_sellers',
        storageKey: 'enable_delete_items_by_non_chinese_sellers',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_set_gspr',
        storageKey: 'enable_set_gspr',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_set_skus_to_items',
        storageKey: 'enable_set_skus_to_items',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_scan_for_restricted_words',
        storageKey: 'enable_scan_for_restricted_words',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'force_restock_quantity_setting',
        storageKey: 'force_restock_quantity_setting',
        defaultValue: { checkbox: false, restock_quantity: 3 }
    }
];

// For each settings block: bind inputs/selects to chrome.storage.local
settingsWithOptions.forEach(function (setting) {
    const container = document.getElementById(setting.elementId);
    if (!container) {
        console.error('Container with id ' + setting.elementId + ' not found');
        return;
    }

    const inputs = container.querySelectorAll('input, select');

    // Collect current values from all inputs and save to storage
    function saveToStorage() {
        const values = {};
        inputs.forEach(function (input) {
            const name = input.name;
            if (name) {
                if (input.type === 'checkbox') {
                    values[name] = input.checked;
                } else {
                    values[name] = input.value;
                }
            }
        });
        chrome.storage.local.set({ [setting.storageKey]: values });
        console.log(setting.storageKey + ':', values);
    }

    // Listen for changes on each input/select
    inputs.forEach(function (input) {
        const eventName = (input.type === 'checkbox' || input.tagName.toLowerCase() === 'select')
            ? 'change'
            : 'input';
        input.addEventListener(eventName, saveToStorage);
    });

    // Load saved values from storage, falling back to defaults
    chrome.storage.local.get(setting.storageKey, function (result) {
        let savedValues = result[setting.storageKey];
        if (savedValues === undefined) {
            savedValues = setting.defaultValue;
            chrome.storage.local.set({ [setting.storageKey]: savedValues });
        }
        inputs.forEach(function (input) {
            const name = input.name;
            if (name && savedValues.hasOwnProperty(name)) {
                if (input.type === 'checkbox') {
                    input.checked = savedValues[name];
                } else {
                    input.value = savedValues[name];
                }
            }
        });
        console.log(setting.storageKey + ':', savedValues);
    });
});


// ============================================================
// SECTION 2: Simple (scalar) settings — checkboxes and inputs
// ============================================================

const simpleSettings = [
    { elementId: 'tracker_run_status', storageKey: 'tracker_run_status', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'enable_continuous_tracking', storageKey: 'enable_continuous_tracking', defaultValue: false, type: 'checkbox', event: 'click' },
    { elementId: 'tracking_timeout', storageKey: 'tracking_timeout', defaultValue: 60, type: 'input', event: 'input' },
    { elementId: 'page_number', storageKey: 'page_number', defaultValue: 1, type: 'input', event: 'input' },
    { elementId: 'current_tracker_position', storageKey: 'current_tracker_position', defaultValue: 1, type: 'input', event: 'input' },
    { elementId: 'should_track_log', storageKey: 'should_track_log', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'should_pin_tabs', storageKey: 'should_pin_tabs', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'stay_on_ebay_page', storageKey: 'stay_on_ebay_page', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'force_domain', storageKey: 'force_domain', defaultValue: false, type: 'checkbox', event: 'change' }
];

simpleSettings.forEach(function (setting) {
    console.log(setting);
    const element = document.getElementById(setting.elementId);

    // Save value on user interaction
    element.addEventListener(setting.event, function () {
        let value;
        if (setting.type === 'checkbox') {
            value = element.checked;
        } else if (setting.type === 'input') {
            value = element.value;
        }
        chrome.storage.local.set({ [setting.storageKey]: value });
        console.log(setting.storageKey + ':', value);
    });

    // Load value from storage, falling back to default
    chrome.storage.local.get(setting.storageKey, function (result) {
        let value = result[setting.storageKey];
        if (value === undefined) {
            value = setting.defaultValue;
            chrome.storage.local.set({ [setting.storageKey]: value });
        }
        if (setting.type === 'checkbox') {
            element.checked = value;
        } else if (setting.type === 'input') {
            element.value = value;
        }
        console.log(setting.storageKey + ':', value);
    });
});


// ============================================================
// SECTION 3: Button event listeners
// ============================================================
// Start tracking button
document.getElementById('start_tracking').addEventListener('click', async function () {
    console.log('Sending message to background.js to start tracking');
    document.getElementById('tracker_run_status').checked = true;

    // Require at least one filter checkbox to be checked
    const filterCheckboxes = document.getElementById('tracker_filters').querySelectorAll('input[type="checkbox"]');
    let anyChecked = false;
    for (let i = 0; i < filterCheckboxes.length; i++) {
        if (filterCheckboxes[i].checked) {
            anyChecked = true;
            break;
        }
    }

    if (anyChecked) {
        chrome.storage.local.set({ tracker_run_status: true });
        chrome.runtime.sendMessage({ type: 'start_tracking' });
    } else {
        alert('Please select at least one filter to track');
        document.getElementById('tracker_run_status').checked = false;
        chrome.storage.local.set({ tracker_run_status: false });
    }
});

// Test button — sends a single item number to background for testing
document.getElementById('test_button').addEventListener('click', async function () {
    console.log('Sending message to background.js to test item');
    const itemNumber = document.getElementById('test_button_value').value;
    chrome.storage.local.set({ test_button_value: itemNumber });

    const { response } = await new Promise(resolve => {
        chrome.runtime.sendMessage(
            { type: 'track_single_item', itemNumber: itemNumber },
            function (reply) { resolve(reply); }
        );
    });
    console.log('response', response);
});

// Open logs button — opens the tracking logs page in a new tab
document.getElementById('open_logs').addEventListener('click', async function (event) {
    const { tracking_log } = await chrome.storage.local.get('tracking_log');
    console.log('tracking_log', tracking_log);
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Stock_Monitor_Repricer/tracking_logs/index.html') });
});

// Toggle hidden menu sections
document.getElementById('tracking_filters_title').addEventListener('click', function () {
    document.querySelectorAll('.hidden_menu').forEach(function (menu) {
        menu.style.display = (menu.style.display === 'none') ? 'block' : 'none';
    });
});

// Export non-Chinese seller item IDs to a text file
document.getElementById('print_non_chinese_sellers_item_ids').addEventListener('click', async function () {
    const { nonChineseSellerItemIds } = await chrome.storage.local.get('nonChineseSellerItemIds');
    console.log('nonChineseSellerItemIds', nonChineseSellerItemIds);

    if (nonChineseSellerItemIds && nonChineseSellerItemIds.length !== 0) {
        const text = nonChineseSellerItemIds.join('\n');
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'non_chinese_sellers_item_ids.txt';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        alert('Item IDs have been saved to a text file');
    } else {
        alert('No non-Chinese seller item IDs found');
    }
});

// Clear non-Chinese seller item IDs from storage
document.getElementById('clear_non_chinese_sellers_item_ids').addEventListener('click', async function () {
    await chrome.storage.local.remove('nonChineseSellerItemIds');
    alert('Non-Chinese seller item IDs have been cleared');
});

// Export failed GSPR items to a text file
document.getElementById('print_failed_gspr_items').addEventListener('click', async function () {
    const { failedGsprItems } = await chrome.storage.local.get('failedGsprItems');
    console.log('failedGsprItems', failedGsprItems);

    if (failedGsprItems && failedGsprItems.length !== 0) {
        const text = failedGsprItems.join('\n');
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'failed_gspr_items.txt';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        alert('Failed GSPR items have been saved to a text file');
    } else {
        alert('No failed GSPR items found');
    }
});

// Clear failed GSPR items from storage and reset UI
document.getElementById('clear_failed_gspr_items').addEventListener('click', async function () {
    await chrome.storage.local.remove('failedGsprItems');
    alert('Failed GSPR items have been cleared');
    document.getElementById('total_failed_gspr_items').innerText = 0;
    document.getElementById('gspr_item_numbers').value = '';
});


// ============================================================
// SECTION 4: Initial UI population on popup load
// ============================================================

async function initializePopup() {
    // Restore test button value
    const { test_button_value } = await chrome.storage.local.get('test_button_value');
    console.log('test_button_value', test_button_value);
    if (test_button_value) {
        document.getElementById('test_button_value').value = test_button_value;
    }
    document.getElementById('test_button_value').addEventListener('input', function () {
        console.log('test_button_value input event');
        const value = document.getElementById('test_button_value').value;
        chrome.storage.local.set({ test_button_value: value });
    });

    // Restore markup percentage
    const { markupPrice } = await chrome.storage.local.get('markupPrice');
    console.log('markupPrice', markupPrice);
    document.querySelector('input[name="markup_percentage"]').value = markupPrice;
    document.querySelector('input[name="markup_percentage"]').addEventListener('input', function () {
        console.log('markup_percentage input event');
        const value = document.querySelector('input[name="markup_percentage"]').value;
        chrome.storage.local.set({ markupPrice: value });
    });

    // Restore total page count
    let { totalPageNumber } = await chrome.storage.local.get('totalPageNumber');
    if (!totalPageNumber) totalPageNumber = 1;
    document.getElementById('totalPageNumber').innerText = totalPageNumber;

    // Restore current tracker position
    let { current_tracker_position } = await chrome.storage.local.get('current_tracker_position');
    if (!current_tracker_position) current_tracker_position = 1;
    document.getElementById('current_tracker_position').value = current_tracker_position;

    // Restore failed GSPR items list
    chrome.storage.local.get('failedGsprItems', function (result) {
        const { failedGsprItems } = result;
        if (failedGsprItems && failedGsprItems.length > 0) {
            document.getElementById('gspr_item_numbers').value = failedGsprItems.join('\n');
            document.getElementById('total_failed_gspr_items').innerText = failedGsprItems.length;
        }
    });
}

initializePopup();


// ============================================================
// SECTION 5: Runtime message listener (progress updates)
// ============================================================

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.type === 'update_tracker_position') {
        const { page_number, total_pages, position_in_page, total_items_in_page } = message;

        // Update item-level progress bar
        const itemPercent = total_items_in_page > 0 ? (position_in_page / total_items_in_page * 100) : 0;
        const itemPercentClamped = Math.min(Math.max(itemPercent, 0), 100);
        document.getElementById('current_item_label').textContent = position_in_page;
        document.getElementById('total_item_label').textContent = total_items_in_page;
        document.getElementById('item_percentage_label').textContent = itemPercentClamped.toFixed(0) + '%';
        document.getElementById('item_progress_fill').style.width = itemPercentClamped + '%';

        // Update page-level progress bar
        const pagePercent = total_pages > 0 ? (page_number / total_pages * 100) : 0;
        const pagePercentClamped = Math.min(Math.max(pagePercent, 0), 100);
        document.getElementById('current_page_label').textContent = page_number;
        document.getElementById('total_page_label').textContent = total_pages;
        document.getElementById('page_percentage_label').textContent = pagePercentClamped.toFixed(0) + '%';
        document.getElementById('page_progress_fill').style.width = pagePercentClamped + '%';

        // Sync input fields
        document.getElementById('current_tracker_position').value = position_in_page;
        document.getElementById('totalPageNumber').innerText = total_pages;
        document.getElementById('page_number').value = page_number;

        // Refresh failed GSPR items display
        chrome.storage.local.get('failedGsprItems', function (result) {
            const { failedGsprItems } = result;
            if (failedGsprItems && failedGsprItems.length > 0) {
                document.getElementById('gspr_item_numbers').value = failedGsprItems.join('\n');
                document.getElementById('total_failed_gspr_items').innerText = failedGsprItems.length;
            }
        });
    }
});


// ============================================================
// SECTION 6: Reset tracking position
// ============================================================

document.getElementById('reset_tracking').addEventListener('click', function () {
    document.getElementById('current_tracker_position').value = 1;
    document.getElementById('page_number').value = 1;
    chrome.storage.local.set({
        current_tracker_position: 1,
        page_number: 1
    });
});



