// ─── Utility: Parse CSV string into 2D array ───────────────────────────────
function parseCSV(csvString, delimiter) {
    delimiter = delimiter || ',';
    var regex = new RegExp(
        '(\\' + delimiter + '|\\r?\\n|\\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^"\\' + delimiter + '\\r\\n]*))',
        'gi'
    );
    var rows = [[]];
    var match = null;
    while ((match = regex.exec(csvString))) {
        var matchedDelimiter = match[1];
        if (matchedDelimiter.length && matchedDelimiter !== delimiter) {
            rows.push([]);
        }
        var cell;
        if (match[2]) {
            cell = match[2].replace(new RegExp('""', 'g'), '"');
        } else {
            cell = match[3];
        }
        rows[rows.length - 1].push(cell);
    }
    return rows;
}

// ─── Utility: Save a value to chrome.storage.local ─────────────────────────
function saveToLocalStorage(key, value) {
    console.log('test save to local storage');
    console.log('key ' + key + ', value ' + value);
    return new Promise((resolve, reject) => {
        chrome.storage.local.set({ [key]: value }, function () {
            console.log('my key', key);
            chrome.storage.local.get(key, function (result) {
                console.log('the Value currently is ', result[key]);
                resolve();
            });
        });
    });
}

// ─── Utility: Read a value from chrome.storage.local ───────────────────────
function getFromLocalStorage(key) {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get(key, function (result) {
            console.log('Value currently is ', result[key]);
            resolve(result[key]);
        });
    });
}

// ─── On window load ─────────────────────────────────────────────────────────
window.onload = function () {
    loadMarkupPrice();
};

// ─── Main button: start scraping ────────────────────────────────────────────
document.getElementById('main_button').addEventListener('click', async function (event) {
    event.preventDefault();
    var pageNumber = document.getElementById('page_number').value;
    await saveToLocalStorage('page_number', pageNumber);
    chrome.runtime.sendMessage({ type: 'start', page_number: pageNumber });
});

// ─── Markup price ────────────────────────────────────────────────────────────
var markupPriceInput = document.getElementById('markup-price');
markupPriceInput.addEventListener('change', function () {
    const value = markupPriceInput.value;
    chrome.storage.local.set({ markupPrice: value });
});

function loadMarkupPrice() {
    chrome.storage.local.get('markupPrice', function (result) {
        const markupPrice = result['markupPrice'];
        if (undefined !== markupPrice) {
            document.getElementById('markup-price').value = markupPrice;
        }
    });
}

// ─── Sniper price markdown ────────────────────────────────────────────────────
document.getElementById('sniper-price-markdown').addEventListener('change', async function (event) {
    event.preventDefault();
    var value = document.getElementById('sniper-price-markdown').value;
    await saveToLocalStorage('sniper_price_markdown', value);
    var stored = await getFromLocalStorage('sniper_price_markdown');
    document.getElementById('sniper-price-markdown').value = stored;
});

chrome.storage.local.get(['sniper_price_markdown'], (result) => {
    let value = result && undefined !== result['sniper_price_markdown'] ? result['sniper_price_markdown'] : 0.05;
    if (undefined === result || undefined === result['sniper_price_markdown']) {
        chrome.storage.local.set({ sniper_price_markdown: value });
    }
    const el = document.getElementById('sniper-price-markdown');
    if (el) el.value = value;
});

// ─── Promoted listing ad rate ─────────────────────────────────────────────────
document.getElementById('promoted_listing_ad_rate').addEventListener('change', async function (event) {
    event.preventDefault();
    var value = document.getElementById('promoted_listing_ad_rate').value;
    await saveToLocalStorage('promoted_listing_ad_rate', value);
    var stored = await getFromLocalStorage('promoted_listing_ad_rate');
    document.getElementById('promoted_listing_ad_rate').value = stored;
});

chrome.storage.local.get(['promoted_listing_ad_rate'], (result) => {
    const value = result && undefined !== result['promoted_listing_ad_rate'] ? result['promoted_listing_ad_rate'] : 5;
    if (undefined === result || undefined === result['promoted_listing_ad_rate']) {
        chrome.storage.local.set({ promoted_listing_ad_rate: value });
    }
    const el = document.getElementById('promoted_listing_ad_rate');
    if (el) el.value = value;
});

// ─── End price ────────────────────────────────────────────────────────────────
document.getElementById('end-price').addEventListener('change', async function (event) {
    event.preventDefault();
    var value = document.getElementById('end-price').value;
    await chrome.storage.local.set({ end_price: value });
});

chrome.storage.local.get('end_price', (result) => {
    var endPrice = result['end_price'];
    if (endPrice) {
        document.getElementById('end-price').value = endPrice;
    } else {
        document.getElementById('end-price').value = 0.99;
        chrome.storage.local.set({ end_price: 0.99 });
    }
});

// ─── Save SKUs on page ────────────────────────────────────────────────────────
document.getElementById('save_sku_on_page').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.runtime.sendMessage({ type: 'save_sku_on_page' });
});

chrome.storage.local.get('skuList', (result) => {
    var skuList = result['skuList'];
    if (skuList) {
        console.log('skuList', skuList.length);
        document.getElementById('skuFound').innerHTML = skuList.length;
    } else {
        document.getElementById('skuFound').innerHTML = 'No Skus Found, start scraping';
    }
});

// ─── Watermark image ──────────────────────────────────────────────────────────
document.getElementById('save_image_to_local_storage').addEventListener('click', async function (event) {
    event.preventDefault();
    var watermarkUrl = document.getElementById('watermark_url').value;
    await saveToLocalStorage('watermark_url', watermarkUrl);
    var stored = await getFromLocalStorage('watermark_url');
    document.getElementById('image_from_local_storage').src = stored;
});

// ─── API key ──────────────────────────────────────────────────────────────────
document.getElementById('save_api_key').addEventListener('click', async function (event) {
    event.preventDefault();
    var apiKey = document.getElementById('api_key').value;
    await saveToLocalStorage('api_key', apiKey);
    var stored = await getFromLocalStorage('api_key');
    document.getElementById('api_key_display').innerHTML = stored;
});

chrome.storage.local.get('api_key', (result) => {
    var apiKey = result['api_key'];
    document.getElementById('api_key_display').innerHTML = apiKey;
});

// ─── Load watermark image on init ────────────────────────────────────────────
async function loadWatermarkImage() {
    var watermarkUrl = await getFromLocalStorage('watermark_url');
    document.getElementById('image_from_local_storage').src = watermarkUrl;
}
loadWatermarkImage();

// ─── Delete SKUs ──────────────────────────────────────────────────────────────
document.getElementById('delete_skus').addEventListener('click', async function (event) {
    event.preventDefault();
    await clearSkuList();
    chrome.storage.local.get('skuList', (result) => {
        var skuList = result['skuList'];
        console.log('skuList', skuList.length);
        document.getElementById('skuFound').innerHTML = skuList.length;
    });
});

function clearSkuList() {
    return new Promise((resolve, reject) => {
        chrome.storage.local.set({ skuList: [] }, () => {
            resolve();
        });
    });
}

// ─── Pause / Resume buttons ───────────────────────────────────────────────────
const pauseButton = document.getElementById('pause_button');
const resumeButton = document.getElementById('resume_button');

chrome.storage.local.get(['pauseDisabled', 'resumeDisabled'], function (result) {
    const pauseDisabled = result['pauseDisabled'];
    const resumeDisabled = result['resumeDisabled'];
    pauseButton.disabled = true === pauseDisabled;
    resumeButton.disabled = true === resumeDisabled;
});

pauseButton.addEventListener('click', () => {
    pauseButton.disabled = true;
    resumeButton.disabled = false;
    chrome.storage.local.set({ pauseDisabled: true, resumeDisabled: false });
    chrome.runtime.sendMessage({ type: 'pause' });
});

resumeButton.addEventListener('click', () => {
    resumeButton.disabled = true;
    pauseButton.disabled = false;
    chrome.storage.local.set({ pauseDisabled: false, resumeDisabled: true });
    chrome.runtime.sendMessage({ type: 'resume' });
});

// ─── Auto AI title checkbox ───────────────────────────────────────────────────
document.getElementById('auto_ai_title_checkbox').addEventListener('click', async function (event) {
    var checked = document.getElementById('auto_ai_title_checkbox').checked;
    await saveToLocalStorage('auto_ai_title_checkbox', checked);
    var stored = await getFromLocalStorage('auto_ai_title_checkbox');
    document.getElementById('auto_ai_title_checkbox').checked = stored;
});

chrome.storage.local.get('auto_ai_title_checkbox', (result) => {
    var checked = result['auto_ai_title_checkbox'];
    document.getElementById('auto_ai_title_checkbox').checked = checked;
});

// ─── Domain select ────────────────────────────────────────────────────────────
function saveDomain() {
    var domain = document.querySelector('#domain-select').value;
    chrome.storage.local.set({ domain: domain });
    console.log('domain', domain);
}

function loadDomain() {
    chrome.storage.local.get('domain', function (result) {
        var domain = result['domain'];
        if (domain) {
            document.querySelector('#domain-select').value = domain;
            console.log('domain', domain);
        }
    });
}

document.addEventListener('DOMContentLoaded', loadDomain);
document.querySelector('#domain-select').addEventListener('change', saveDomain);

// ─── VeRO protection switch ───────────────────────────────────────────────────
const veroProtectionSwitch = document.getElementById('vero_protection_switch');
veroProtectionSwitch.addEventListener('change', () => {
    chrome.storage.local.set({ veroProtectionEnabled: veroProtectionSwitch.checked });
});

chrome.storage.local.get('veroProtectionEnabled', (result) => {
    const enabled = result['veroProtectionEnabled'] ?? true;
    veroProtectionSwitch.checked = enabled;
});

// ─── Auto submit switch ───────────────────────────────────────────────────────
document.getElementById('auto_submit_switch').addEventListener('change', async function (event) {
    chrome.storage.local.set({ autoSubmitEnabled: document.getElementById('auto_submit_switch').checked });
});

chrome.storage.local.get('autoSubmitEnabled', (result) => {
    if (null == result['autoSubmitEnabled']) {
        result['autoSubmitEnabled'] = true;
        chrome.storage.local.set({ autoSubmitEnabled: result['autoSubmitEnabled'] });
    }
    document.getElementById('auto_submit_switch').checked = result['autoSubmitEnabled'];
});

// ─── Enable image template switch ────────────────────────────────────────────
document.getElementById('enable_image_template_switch').addEventListener('change', async function (event) {
    chrome.storage.local.set({ enableImageTemplate: document.getElementById('enable_image_template_switch').checked });
});

chrome.storage.local.get('enableImageTemplate', (result) => {
    if (null == result['enableImageTemplate']) {
        result['enableImageTemplate'] = false;
        chrome.storage.local.set({ enableImageTemplate: result['enableImageTemplate'] });
    }
    document.getElementById('enable_image_template_switch').checked = result['enableImageTemplate'];
});

// ─── Use review images switch ─────────────────────────────────────────────────
document.getElementById('use_review_images_switch').addEventListener('change', async function (event) {
    if (document.getElementById('use_review_images_switch').checked !== document.getElementById('use_simple_description_switch').checked) {
        document.getElementById('use_simple_description_switch').click();
    }
    chrome.storage.local.set({ useReviewImages: document.getElementById('use_review_images_switch').checked });
});

chrome.storage.local.get('useReviewImages', (result) => {
    if (null == result['useReviewImages']) {
        result['useReviewImages'] = false;
        chrome.storage.local.set({ useReviewImages: result['useReviewImages'] });
    }
    document.getElementById('use_review_images_switch').checked = result['useReviewImages'];
});

// ─── Amazon links list button ─────────────────────────────────────────────────
const listButton = document.getElementById('list-btn');
const totalLinksLabel = document.getElementById('total-links-label');

listButton.addEventListener('click', () => {
    const links = document.getElementById('amazon-links').value.split('\n');
    chrome.storage.local.set({ amazonLinks: links }, () => {
        console.log('Amazon links saved to local storage:', links);
        chrome.runtime.sendMessage({ action: 'listAmazonProducts' });
    });
    pauseButton.disabled = false;
    resumeButton.disabled = true;
    chrome.storage.local.set({ pauseDisabled: false, resumeDisabled: true });
});

chrome.storage.local.get('amazonLinks', (result) => {
    const links = result['amazonLinks'];
    console.log('amazonLinks', links);
    if (links) {
        document.getElementById('amazon-links').value = links.join('\n');
        totalLinksLabel.innerText = links.length;
    }
});

// ─── Position / update position button ───────────────────────────────────────
const positionInput = document.getElementById('position-input');
const updatePositionBtn = document.getElementById('update-position-btn');

updatePositionBtn.addEventListener('click', async () => {
    const position = parseInt(positionInput.value);
    if (!isNaN(position)) {
        chrome.storage.local.set({ position: position }, () => {
            console.log('Position updated:', position);
            positionInput.value = position;
        });
    }

    var linksRaw = document.getElementById('amazon-links').value.trim();
    var links = linksRaw === '' ? [] : linksRaw.split('\n');
    console.log('Amazon links saved to local storage:', links);
    console.log('amazonLinks.length', links.length);
    totalLinksLabel.innerText = links.length;

    var skuList = await getSkuListFromLocalStorage();
    var filteredLinks = [];

    for await (const link of links) {
        if (link !== '') {
            var asin = getTheAsinFromUrl(link);
            console.log('asin', asin);
            var isDuplicate = skuList.includes(asin);
            console.log('isDuplicate', isDuplicate);
            if (!isDuplicate) filteredLinks.push(link);
        }
    }

    await chrome.storage.local.set({ amazonLinks: filteredLinks });
    console.log('Amazon links saved to local storage:', filteredLinks);
    totalLinksLabel.innerText = filteredLinks.length;
    document.getElementById('amazon-links').value = filteredLinks.join('\n');
});

chrome.storage.local.get('position', (result) => {
    console.log('Position restored:', result['position']);
    if (result['position']) {
        positionInput.value = result['position'];
    } else {
        chrome.storage.local.set({ position: 0 }, () => {
            console.log('Position set to 0');
        });
    }
});

// ─── Status report button ─────────────────────────────────────────────────────
document.getElementById('status-report').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('bulk_post/table.html') });
});

// ─── Toggle ChatGPT test mode ─────────────────────────────────────────────────
document.getElementById('toggle_chatgpt_test_mode').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('ChatGpt_Test_Mode/index.html') });
});

// ─── Thread count ─────────────────────────────────────────────────────────────
const threadCountInput = document.getElementById('thread-count');
threadCountInput.addEventListener('change', () => {
    const value = threadCountInput.value;
    chrome.storage.local.set({ threadCount: value });
});

chrome.storage.local.get('threadCount', ({ threadCount }) => {
    if (threadCount) {
        threadCountInput.value = threadCount;
    } else {
        threadCountInput.value = 1;
        chrome.storage.local.set({ threadCount: 1 });
    }
});

// ─── Max price ────────────────────────────────────────────────────────────────
document.getElementById('max-price').addEventListener('change', () => {
    const value = document.getElementById('max-price').value;
    chrome.storage.local.set({ maxPrice: value });
});

chrome.storage.local.get('maxPrice', ({ maxPrice }) => {
    if (maxPrice) {
        document.getElementById('max-price').value = maxPrice;
    } else {
        document.getElementById('max-price').value = 100;
        chrome.storage.local.set({ maxPrice: 100 });
    }
});

// ─── Min price ────────────────────────────────────────────────────────────────
document.getElementById('min-price').addEventListener('change', () => {
    const value = document.getElementById('min-price').value;
    chrome.storage.local.set({ minPrice: value });
});

chrome.storage.local.get('minPrice', ({ minPrice }) => {
    if (minPrice) {
        document.getElementById('min-price').value = minPrice;
    } else {
        document.getElementById('min-price').value = 0;
        chrome.storage.local.set({ minPrice: 0 });
    }
});

// ─── Total ASINs to fetch from search ────────────────────────────────────────
document.getElementById('total-asins-to-fetch-from-search').addEventListener('change', () => {
    const value = document.getElementById('total-asins-to-fetch-from-search').value;
    chrome.storage.local.set({ totalAsinsToFetchFromSearch: value });
});

chrome.storage.local.get('totalAsinsToFetchFromSearch', ({ totalAsinsToFetchFromSearch }) => {
    if (totalAsinsToFetchFromSearch) {
        document.getElementById('total-asins-to-fetch-from-search').value = totalAsinsToFetchFromSearch;
    } else {
        document.getElementById('total-asins-to-fetch-from-search').value = 2;
        chrome.storage.local.set({ totalAsinsToFetchFromSearch: 2 });
    }
});

// ─── Amazon search queries ────────────────────────────────────────────────────
var amazonSearchQueriesTextarea = document.getElementById('amazon-search-querys');

amazonSearchQueriesTextarea.addEventListener('change', () => {
    const queries = amazonSearchQueriesTextarea.value.split('\n');
    chrome.storage.local.set({ amazonSearchQuerys: queries }, () => {
        console.log('Amazon Search Querys saved to local storage:', queries);
    });
    document.getElementById('amazon-search-total-querys-label').innerText = queries.length;
});

chrome.storage.local.get('amazonSearchQuerys', (result) => {
    const queries = result['amazonSearchQuerys'];
    if (queries) {
        amazonSearchQueriesTextarea.value = queries.join('\n');
        document.getElementById('amazon-search-total-querys-label').innerText = queries.length;
    }
});

// ─── Amazon search query position ────────────────────────────────────────────
document.getElementById('amazon-search-position-input').addEventListener('change', () => {
    const position = parseInt(document.getElementById('amazon-search-position-input').value);
    if (!isNaN(position)) {
        chrome.storage.local.set({ amazonSearchQueryPosition: position }, () => {
            console.log('amazonSearchQueryPosition updated:', position);
        });
    }
});

chrome.storage.local.get('amazonSearchQueryPosition', (result) => {
    const position = result['amazonSearchQueryPosition'];
    if (position) {
        document.getElementById('amazon-search-position-input').value = position;
    } else {
        document.getElementById('amazon-search-position-input').value = 0;
        chrome.storage.local.set({ amazonSearchQueryPosition: 0 });
    }
});

// ─── Search Amazon by title button ───────────────────────────────────────────
document.getElementById('search-amazon-querys-btn').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.runtime.sendMessage({ type: 'startSearchingAmazon', searchType: 'title' });
});

// ─── Search Amazon by keywords button ────────────────────────────────────────
document.getElementById('search-amazon-keywords-btn').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.runtime.sendMessage({ type: 'startSearchingAmazon', searchType: 'keywords' });
});

// ─── Open duplicate checker ───────────────────────────────────────────────────
var openDuplicateCheckerBtn = document.getElementById('open_duplicate_checker');
openDuplicateCheckerBtn.addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Duplicate_Settings/page.html') });
});

// ─── Research SEO ─────────────────────────────────────────────────────────────
var researchSeoBtn = document.getElementById('research_seo');
researchSeoBtn.addEventListener('click', function (event) {
    console.log('research_seo clicked');
    event.preventDefault();
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: 'research_seo' });
    });
});

// ─── Toggle test mode (eBay) ──────────────────────────────────────────────────
document.getElementById('toggle_test_mode_ebay').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: 'toggle_test_mode_ebay' });
    });
});

// ─── Open product finder ──────────────────────────────────────────────────────
document.getElementById('open_product_finder_button').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Product_Finder/product_finder.html') });
});

// ─── Open bulk lister ─────────────────────────────────────────────────────────
document.getElementById('open_bulk_lister').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('bulk_post/bulk_post_settings.html') });
});

// ─── Open image template ──────────────────────────────────────────────────────
document.getElementById('open_image_template').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Image_Template_Designer/index.html') });
});

// ─── Open tracker ─────────────────────────────────────────────────────────────
document.getElementById('open_tracker').addEventListener('click', function (event) {
    event.preventDefault();
    var url = chrome.runtime.getURL('Stock_Monitor_Repricer/index.html');
    console.log('url ', url);
    chrome.tabs.create({ url: url });
});

// ─── Open competitor research ─────────────────────────────────────────────────
document.getElementById('open_competitor_research').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Competitor_Research/index.html') });
});

// ─── Open quick chat settings ─────────────────────────────────────────────────
document.getElementById('open_quick_chat_settings').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Quick_Chat_Settings/index.html') });
});

// ─── VeRO brands fetcher ──────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
    const getVeroBrandsButton = document.getElementById('getVeroBrandsButton');
    const veroBrandStatus = document.getElementById('veroBrandStatus');
    const spinner = document.getElementById('spinner');
    const statusIcon = document.getElementById('statusIcon');
    const fetchedCount = document.getElementById('fetchedCount');

    chrome.storage.local.get(['status', 'veroBrands', 'lastFetch'], (result) => {
        if (result['status'] && result['veroBrands']) {
            veroBrandStatus.textContent = result['status'] === 'success' ? 'Success!' : 'Failed!';
            statusIcon.className = 'icon ' + (result['status'] === 'success' ? 'success' : 'fail');
            statusIcon.textContent = result['status'] === 'success' ? '✓' : '✗';
            fetchedCount.textContent = 'Total Brands: ' + result['veroBrands'].length;
            if (result['lastFetch']) {
                const lastFetchDate = new Date(result['lastFetch']).toLocaleString();
                veroBrandStatus.textContent += ' Last fetched on ' + lastFetchDate + '.';
            }
        }
    });

    getVeroBrandsButton.addEventListener('click', async () => {
        spinner.classList.remove('hidden');
        veroBrandStatus.textContent = 'Fetching...';
        statusIcon.classList.add('hidden');
        fetchedCount.classList.add('hidden');

        const brands = await (async function fetchVeroBrands() {
            try {
                const response = await fetch('https://us-central1-silentsnipe-ce4ca.cloudfunctions.net/app/api/v1/veroBrands');
                if (!response.ok) throw new Error('Network response was not ok ' + response.statusText);
                const json = await response.json();
                return json['data'].map(item => item['title']);
            } catch (error) {
                console.error('There has been a problem with your fetch operation:', error);
                return null;
            }
        }());

        spinner.classList.add('hidden');
        fetchedCount.classList.remove('hidden');

        if (brands) {
            const now = new Date();
            chrome.storage.local.set({ status: 'success', veroBrands: brands, lastFetch: now.getTime() });
            veroBrandStatus.textContent = 'Success! Last fetched on ' + now.toLocaleString() + '.';
            statusIcon.className = 'icon success';
            statusIcon.textContent = '✓';
            fetchedCount.textContent = 'Total Brands: ' + brands.length;
        } else {
            chrome.storage.local.set({ status: 'fail' });
            veroBrandStatus.textContent = 'Failed!';
            statusIcon.className = 'icon fail';
            statusIcon.textContent = '✗';
            fetchedCount.textContent = 'Total Brands: 0';
        }
    });
});

// ─── Ask ChatGPT test button ──────────────────────────────────────────────────
document.getElementById('ask_chatgpt').addEventListener('click', async function (event) {
    event.preventDefault();
    var input = document.getElementById('chatgpt_input').value;
    console.log('chatgpt_input ', input);
    var response = await askChatGptForHighQualityTitles(
        'Pawfly Adjustable Aquarium Air Pump 4-LPM 2 Outlets with Oxygen Accessories f...',
        'Pawfly Adjustable Aquarium Air Pump 4-LPM 2 Outlets with Oxygen Accessories for 20-100 Gallon Fish Tank Pond\n  Pawfly Adjustable aquarium air pump is perfect for both medium Freshwater and Marine fish tank.\n  Ultra whisper quiet, Minimum 25 dB in lowest flow rate(sound like rusting leaves, ticking watch)\n  Adjustable flow rate with 2 outlets, fit for fish tanks up to 100-gallon.\n  4-LPM, 4 Watt, Pressure: 0.016 Mpa.\n  Comes with Accessories you need: 6.5 ft Airline, 2 x Air Stone, 2 x Return Valve, 2 Connectors.'
    );
    console.log('response ', response);
});

// ─── Apply Amazon affiliate tag switch ───────────────────────────────────────
document.getElementById('apply_amazon_affiliate_tag_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ applyAmazonAffiliateTag: document.getElementById('apply_amazon_affiliate_tag_switch').checked });
});

chrome.storage.local.get('applyAmazonAffiliateTag', (result) => {
    if (null == result['applyAmazonAffiliateTag']) {
        result['applyAmazonAffiliateTag'] = false;
        chrome.storage.local.set({ applyAmazonAffiliateTag: result['applyAmazonAffiliateTag'] });
    } else {
        document.getElementById('apply_amazon_affiliate_tag_switch').checked = result['applyAmazonAffiliateTag'];
    }
});

// ─── Open advanced title builder ─────────────────────────────────────────────
document.getElementById('open_advanced_title_builder').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Advanced_Title_Builder/index.html') });
});

// ─── Fill required item specifics switch ─────────────────────────────────────
document.getElementById('fill_required_item_specifics_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ shouldFillRequiredItemSpecifics: document.getElementById('fill_required_item_specifics_switch').checked });
});

chrome.storage.local.get('shouldFillRequiredItemSpecifics', (result) => {
    console.log('res.shouldFillRequiredItemSpecifics ', result['shouldFillRequiredItemSpecifics']);
    if (null == result['shouldFillRequiredItemSpecifics']) {
        result['shouldFillRequiredItemSpecifics'] = true;
        chrome.storage.local.set({ shouldFillRequiredItemSpecifics: result['shouldFillRequiredItemSpecifics'] });
    } else {
        document.getElementById('fill_required_item_specifics_switch').checked = result['shouldFillRequiredItemSpecifics'];
    }
});

// ─── Fill optional item specifics switch ─────────────────────────────────────
document.getElementById('fill_optional_item_specifics_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ shouldFillOptionalItemSpecifics: document.getElementById('fill_optional_item_specifics_switch').checked });
});

chrome.storage.local.get('shouldFillOptionalItemSpecifics', (result) => {
    console.log('res.shouldFillOptionalItemSpecifics ', result['shouldFillOptionalItemSpecifics']);
    if (null == result['shouldFillOptionalItemSpecifics']) {
        result['shouldFillOptionalItemSpecifics'] = true;
        chrome.storage.local.set({ shouldFillOptionalItemSpecifics: result['shouldFillOptionalItemSpecifics'] });
    } else {
        document.getElementById('fill_optional_item_specifics_switch').checked = result['shouldFillOptionalItemSpecifics'];
    }
});

// ─── Hide personal information switch ────────────────────────────────────────
document.getElementById('hide_personal_information_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ shouldHidePersonalInformation: document.getElementById('hide_personal_information_switch').checked });
});

chrome.storage.local.get('shouldHidePersonalInformation', (result) => {
    if (null == result['shouldHidePersonalInformation']) {
        result['shouldHidePersonalInformation'] = false;
        chrome.storage.local.set({ shouldHidePersonalInformation: result['shouldHidePersonalInformation'] });
    } else {
        document.getElementById('hide_personal_information_switch').checked = result['shouldHidePersonalInformation'];
    }
});

// ─── Test identify listing ────────────────────────────────────────────────────
document.getElementById('test_identify_listing').addEventListener('click', async function (event) {
    event.preventDefault();
    var productData = await fetch('../amazonDataTest.json').then(res => res.json());
    console.log('product_data ', productData);
    chrome.runtime.sendMessage({ type: 'list_to_ebay_in_same_tab', product_data: productData });
});

// ─── Agent name ───────────────────────────────────────────────────────────────
document.getElementById('agent_name').addEventListener('input', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ agentName: document.getElementById('agent_name').value });
});

chrome.storage.local.get('agentName', (result) => {
    if (null == result['agentName']) {
        chrome.storage.local.set({ agentName: document.getElementById('agent_name').value });
    } else {
        document.getElementById('agent_name').value = result['agentName'];
    }
});

// ─── Virtual clipboard 1 key ──────────────────────────────────────────────────
document.getElementById('virtual_clipboard_1_key').addEventListener('input', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ virtualClipboard1Key: document.getElementById('virtual_clipboard_1_key').value });
});

chrome.storage.local.get('virtualClipboard1Key', async (result) => {
    if (null == result['virtualClipboard1Key']) {
        // No user login — leave field empty
        chrome.storage.local.set({ virtualClipboard1Key: '' });
        document.getElementById('virtual_clipboard_1_key').value = '';
    } else {
        document.getElementById('virtual_clipboard_1_key').value = result['virtualClipboard1Key'];
    }
});

// ─── Virtual clipboard 2 key ──────────────────────────────────────────────────
document.getElementById('virtual_clipboard_2_key').addEventListener('input', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ virtualClipboard2Key: document.getElementById('virtual_clipboard_2_key').value });
});

chrome.storage.local.get('virtualClipboard2Key', (result) => {
    if (null == result['virtualClipboard2Key']) {
        chrome.storage.local.set({ virtualClipboard2Key: document.getElementById('virtual_clipboard_2_key').value });
    } else {
        document.getElementById('virtual_clipboard_2_key').value = result['virtualClipboard2Key'];
    }
});

// ─── Snipe mode switch ────────────────────────────────────────────────────────
document.getElementById('snipe_mode_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ snipeModeEnabled: document.getElementById('snipe_mode_switch').checked });
});

chrome.storage.local.get('snipeModeEnabled', (result) => {
    if (null == result['snipeModeEnabled'] || result['snipeModeEnabled'] === '') {
        result['snipeModeEnabled'] = false;
        chrome.storage.local.set({ snipeModeEnabled: result['snipeModeEnabled'] });
    } else {
        document.getElementById('snipe_mode_switch').checked = result['snipeModeEnabled'];
    }
});

// ─── Use simple description switch ───────────────────────────────────────────
document.getElementById('use_simple_description_switch').addEventListener('change', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ useSimpleDescription: document.getElementById('use_simple_description_switch').checked });
});

chrome.storage.local.get('useSimpleDescription', (result) => {
    console.log('useSimpleDescription ', result['useSimpleDescription']);
    if (null == result['useSimpleDescription']) {
        result['useSimpleDescription'] = false;
        chrome.storage.local.set({ useSimpleDescription: result['useSimpleDescription'] });
    } else {
        document.getElementById('use_simple_description_switch').checked = result['useSimpleDescription'];
    }
});

// ─── Open boost my listings ───────────────────────────────────────────────────
document.getElementById('open_boost_my_listings').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Boost_My_Listings/index.html') });
});

// ─── Open sniper list ─────────────────────────────────────────────────────────
document.getElementById('open_sniper_list').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Sniper_List/index.html') });
});

// ─── Open stock monitor ───────────────────────────────────────────────────────
document.getElementById('open_stock_monitor').addEventListener('click', function (event) {
    event.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Stock_Monitor_Repricer/index.html') });
});

// ─── Schedule listing time ────────────────────────────────────────────────────
var scheduleListingTimeSelect = document.getElementById('schedule_listing_time');

scheduleListingTimeSelect.addEventListener('change', function (event) {
    event.preventDefault();
    let rawValue = scheduleListingTimeSelect.value;
    let scheduleTime = rawValue !== 'false' && Number(rawValue);
    console.log('scheduleTime', scheduleTime);
    chrome.storage.local.set({ scheduleListingTime: scheduleTime });
});

chrome.storage.local.get('scheduleListingTime', (result) => {
    console.log('scheduleListingTime', result['scheduleListingTime']);
    if (undefined === result['scheduleListingTime']) {
        const defaultValue = false;
        chrome.storage.local.set({ scheduleListingTime: defaultValue });
        scheduleListingTimeSelect.value = 'false';
    } else {
        let value = result['scheduleListingTime'];
        scheduleListingTimeSelect.value = value === false ? 'false' : String(value);
    }
});



