// ============================================================
// No-auth shim — Firebase and login removed
// All tools unlocked by default
// ============================================================

// Stub out any Firebase/auth references the rest of the code might call
const saveToLocalStorage = (key, value) =>
    new Promise(resolve => chrome.storage.local.set({ [key]: value }, resolve));

const getFromLocalStorage = (key) =>
    new Promise(resolve =>
        chrome.storage.local.get(key, result => resolve(result[key]))
    );

const getAsinFromUrl = (url) => {
    const match = url.match(/\/dp\/([A-Z0-9]{10})/i);
    return match ? match[1] : null;
};

const getDecodedSkuList = async () => {
    const result = await new Promise(resolve => chrome.storage.local.get('skuList', resolve));
    return (result.skuList || []).map(sku => {
        try { return atob(sku); } catch { return sku; }
    });
};

// Stub ChatGPT functions so buttons don't throw
async function askChatGptForHighQualityTitles(title, desc) {
    console.log('askChatGptForHighQualityTitles stub called');
    return [];
}
async function generateSeoTitles() { return []; }
async function askChatGptToCreateSEOTitles() { return []; }

// Show main UI immediately — no login required
document.addEventListener('DOMContentLoaded', () => {
    const loginContainer = document.getElementById('login_container');
    const mainButton = document.getElementById('main_button');
    const userFeatures = document.getElementById('user_features_containers');
    const logoutIcon = document.getElementById('logout_icon');
    const statusText = document.getElementById('status_text');

    if (loginContainer) loginContainer.style.display = 'none';
    if (mainButton) mainButton.style.display = 'block';
    if (userFeatures) userFeatures.style.display = 'block';
    if (logoutIcon) logoutIcon.style.display = 'none';
    if (statusText) statusText.textContent = '';
});

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

chrome.storage.local.get(['sniper_price_markdown'], (result) => {
    let value = result && result.sniper_price_markdown !== undefined ? result.sniper_price_markdown : 0.05;
    if (result === undefined || result.sniper_price_markdown === undefined) {
        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 (e) {
    e.preventDefault();
    const value = document.getElementById('promoted_listing_ad_rate').value;
    await saveToLocalStorage('promoted_listing_ad_rate', value);
    const 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 && result.promoted_listing_ad_rate !== undefined ? result.promoted_listing_ad_rate : 5;
    if (result === undefined || result.promoted_listing_ad_rate === undefined) {
        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 (e) {
    e.preventDefault();
    const value = document.getElementById('end-price').value;
    await chrome.storage.local.set({ end_price: value });
});

chrome.storage.local.get('end_price', (result) => {
    const 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 SKU on Page ---
document.getElementById('save_sku_on_page').addEventListener('click', function (e) {
    e.preventDefault();
    chrome.runtime.sendMessage({ type: 'save_sku_on_page' });
});

chrome.storage.local.get('skuList', (result) => {
    const 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 URL ---
document.getElementById('save_image_to_local_storage').addEventListener('click', async function (e) {
    e.preventDefault();
    const url = document.getElementById('watermark_url').value;
    await saveToLocalStorage('watermark_url', url);
    const stored = await getFromLocalStorage('watermark_url');
    document.getElementById('image_from_local_storage').src = stored;
});

// --- API Key ---
document.getElementById('save_api_key').addEventListener('click', async function (e) {
    e.preventDefault();
    const apiKey = document.getElementById('api_key').value;
    await saveToLocalStorage('api_key', apiKey);
    const stored = await getFromLocalStorage('api_key');
    document.getElementById('api_key_display').innerHTML = stored;
});

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

async function loadWatermarkImage() {
    const url = await getFromLocalStorage('watermark_url');
    document.getElementById('image_from_local_storage').src = url;
}
loadWatermarkImage();

// --- Delete SKUs ---
document.getElementById('delete_skus').addEventListener('click', async function (e) {
    e.preventDefault();
    await clearSkuList();
    chrome.storage.local.get('skuList', (result) => {
        const 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'], (result) => {
    pauseButton.disabled = result.pauseDisabled === true;
    resumeButton.disabled = result.resumeDisabled === true;
});

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 (e) {
    const checked = document.getElementById('auto_ai_title_checkbox').checked;
    await saveToLocalStorage('auto_ai_title_checkbox', checked);
    const stored = await getFromLocalStorage('auto_ai_title_checkbox');
    document.getElementById('auto_ai_title_checkbox').checked = stored;
});

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

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

function loadDomain() {
    chrome.storage.local.get('domain', (result) => {
        const 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 veroSwitch = document.getElementById('vero_protection_switch');
veroSwitch.addEventListener('change', () => {
    chrome.storage.local.set({ veroProtectionEnabled: veroSwitch.checked });
});
chrome.storage.local.get('veroProtectionEnabled', (result) => {
    const enabled = result.veroProtectionEnabled ?? true;
    veroSwitch.checked = enabled;
});

// --- Auto Submit Switch ---
document.getElementById('auto_submit_switch').addEventListener('change', async function (e) {
    chrome.storage.local.set({ autoSubmitEnabled: document.getElementById('auto_submit_switch').checked });
});
chrome.storage.local.get('autoSubmitEnabled', (result) => {
    if (result.autoSubmitEnabled == null) {
        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 (e) {
    chrome.storage.local.set({ enableImageTemplate: document.getElementById('enable_image_template_switch').checked });
});
chrome.storage.local.get('enableImageTemplate', (result) => {
    if (result.enableImageTemplate == null) {
        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 (e) {
    // Keep review images and simple description in sync
    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 (result.useReviewImages == null) {
        result.useReviewImages = false;
        chrome.storage.local.set({ useReviewImages: result.useReviewImages });
    }
    document.getElementById('use_review_images_switch').checked = result.useReviewImages;
});

// --- Amazon Links List ---
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');
    // Reset position to 0 every time a fresh run is started, so the lister
    // doesn't skip items that were processed in a previous session.
    chrome.storage.local.set({ amazonLinks: links, position: 0 }, () => {
        console.log('Amazon links saved to local storage:', links);
        positionInput.value = 0;   // keep the UI input in sync
        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 / Deduplication ---
const positionInput = document.getElementById('position-input');
const updatePositionButton = document.getElementById('update-position-btn');

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

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

    const decodedSkus = await getDecodedSkuList();
    const filteredLinks = [];

    for await (const link of links) {
        if (link !== '') {
            const asin = getAsinFromUrl(link);
            console.log('asin', asin);
            const isDuplicate = decodedSkus.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);
    // Use explicit check so position 0 is treated as valid, not as "missing"
    if (result.position != null) {
        positionInput.value = result.position;
    } else {
        chrome.storage.local.set({ position: 0 }, () => {
            console.log('Position set to 0');
            positionInput.value = 0;
        });
    }
});

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

document.getElementById('toggle_chatgpt_test_mode').addEventListener('click', async function (e) {
    e.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('ChatGpt_Test_Mode/index.html') });
});

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

// --- Max / Min Price ---
document.getElementById('max-price').addEventListener('change', () => {
    chrome.storage.local.set({ maxPrice: document.getElementById('max-price').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 });
    }
});

document.getElementById('min-price').addEventListener('change', () => {
    chrome.storage.local.set({ minPrice: document.getElementById('min-price').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', () => {
    chrome.storage.local.set({ totalAsinsToFetchFromSearch: document.getElementById('total-asins-to-fetch-from-search').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 ---
const searchQueriesTextarea = document.getElementById('amazon-search-querys');
searchQueriesTextarea.addEventListener('change', () => {
    const queries = searchQueriesTextarea.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) {
        searchQueriesTextarea.value = queries.join('\n');
        document.getElementById('amazon-search-total-querys-label').innerText = queries.length;
    }
});

document.getElementById('amazon-search-position-input').addEventListener('change', () => {
    const pos = parseInt(document.getElementById('amazon-search-position-input').value);
    if (!isNaN(pos)) {
        chrome.storage.local.set({ amazonSearchQueryPosition: pos }, () => {
            console.log('amazonSearchQueryPosition updated:', pos);
        });
    }
});
chrome.storage.local.get('amazonSearchQueryPosition', (result) => {
    const pos = result.amazonSearchQueryPosition;
    if (pos) {
        document.getElementById('amazon-search-position-input').value = pos;
    } else {
        document.getElementById('amazon-search-position-input').value = 0;
        chrome.storage.local.set({ amazonSearchQueryPosition: 0 });
    }
});

document.getElementById('search-amazon-querys-btn').addEventListener('click', async function (e) {
    e.preventDefault();
    chrome.runtime.sendMessage({ type: 'startSearchingAmazon', searchType: 'title' });
});

document.getElementById('search-amazon-keywords-btn').addEventListener('click', async function (e) {
    e.preventDefault();
    chrome.runtime.sendMessage({ type: 'startSearchingAmazon', searchType: 'keywords' });
});

// --- Open Sub-Pages ---
document.getElementById('open_duplicate_checker').addEventListener('click', function (e) {
    e.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Duplicate_Settings/page.html') });
});

document.getElementById('research_seo').addEventListener('click', function (e) {
    console.log('research_seo clicked');
    e.preventDefault();
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: 'research_seo' });
    });
});

document.getElementById('toggle_test_mode_ebay').addEventListener('click', async function (e) {
    e.preventDefault();
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: 'toggle_test_mode_ebay' });
    });
});

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

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

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

document.getElementById('open_tracker').addEventListener('click', function (e) {
    e.preventDefault();
    const url = chrome.runtime.getURL('Stock_Monitor_Repricer/index.html');
    console.log('url ', url);
    chrome.tabs.create({ url });
});

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

document.getElementById('open_quick_chat_settings').addEventListener('click', function (e) {
    e.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 lastFetchStr = new Date(result.lastFetch).toLocaleString();
                veroBrandStatus.textContent += ' Last fetched on ' + lastFetchStr + '.';
            }
        }
    });

    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 data = await response.json();
                return data.data.map(item => item.title);
            } catch (e) {
                console.error('There has been a problem with your fetch operation:', e);
                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';
        }
    });
});

// --- ChatGPT Test Button ---
document.getElementById('ask_chatgpt').addEventListener('click', async function (e) {
    e.preventDefault();
    const input = document.getElementById('chatgpt_input').value;
    console.log('chatgpt_input ', input);
    const 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);
});

// --- Amazon Affiliate Tag Switch ---
document.getElementById('apply_amazon_affiliate_tag_switch').addEventListener('change', async function (e) {
    e.preventDefault();
    chrome.storage.local.set({ applyAmazonAffiliateTag: document.getElementById('apply_amazon_affiliate_tag_switch').checked });
});
chrome.storage.local.get('applyAmazonAffiliateTag', (result) => {
    if (result.applyAmazonAffiliateTag == null) {
        result.applyAmazonAffiliateTag = false;
        chrome.storage.local.set({ applyAmazonAffiliateTag: result.applyAmazonAffiliateTag });
    } else {
        document.getElementById('apply_amazon_affiliate_tag_switch').checked = result.applyAmazonAffiliateTag;
    }
});

document.getElementById('open_advanced_title_builder').addEventListener('click', function (e) {
    e.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Advanced_Title_Builder/index.html') });
});

// --- Fill Required Item Specifics ---
document.getElementById('fill_required_item_specifics_switch').addEventListener('change', async function (e) {
    e.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 (result.shouldFillRequiredItemSpecifics == null) {
        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 ---
document.getElementById('fill_optional_item_specifics_switch').addEventListener('change', async function (e) {
    e.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 (result.shouldFillOptionalItemSpecifics == null) {
        result.shouldFillOptionalItemSpecifics = true;
        chrome.storage.local.set({ shouldFillOptionalItemSpecifics: result.shouldFillOptionalItemSpecifics });
    } else {
        document.getElementById('fill_optional_item_specifics_switch').checked = result.shouldFillOptionalItemSpecifics;
    }
});

// --- Hide Personal Information ---
document.getElementById('hide_personal_information_switch').addEventListener('change', async function (e) {
    e.preventDefault();
    chrome.storage.local.set({ shouldHidePersonalInformation: document.getElementById('hide_personal_information_switch').checked });
});
chrome.storage.local.get('shouldHidePersonalInformation', (result) => {
    if (result.shouldHidePersonalInformation == null) {
        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 (e) {
    e.preventDefault();
    const productData = await fetch('../amazonDataTest.json').then(r => r.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 (e) {
    e.preventDefault();
    chrome.storage.local.set({ agentName: document.getElementById('agent_name').value });
});
chrome.storage.local.get('agentName', (result) => {
    if (result.agentName == null) {
        chrome.storage.local.set({ agentName: document.getElementById('agent_name').value });
    } else {
        document.getElementById('agent_name').value = result.agentName;
    }
});

// --- Virtual Clipboard Keys ---
document.getElementById('virtual_clipboard_1_key').addEventListener('input', async function (e) {
    e.preventDefault();
    chrome.storage.local.set({ virtualClipboard1Key: document.getElementById('virtual_clipboard_1_key').value });
});
chrome.storage.local.get('virtualClipboard1Key', async (result) => {
    if (result.virtualClipboard1Key == null) {
        chrome.storage.local.set({ virtualClipboard1Key: '' });
        document.getElementById('virtual_clipboard_1_key').value = '';
    } else {
        document.getElementById('virtual_clipboard_1_key').value = result.virtualClipboard1Key;
    }
});

document.getElementById('virtual_clipboard_2_key').addEventListener('input', async function (e) {
    e.preventDefault();
    chrome.storage.local.set({ virtualClipboard2Key: document.getElementById('virtual_clipboard_2_key').value });
});
chrome.storage.local.get('virtualClipboard2Key', (result) => {
    if (result.virtualClipboard2Key == null) {
        chrome.storage.local.set({ virtualClipboard2Key: document.getElementById('virtual_clipboard_2_key').value });
    } else {
        document.getElementById('virtual_clipboard_2_key').value = result.virtualClipboard2Key;
    }
});

// --- Snipe Mode ---
document.getElementById('snipe_mode_switch').addEventListener('change', async function (e) {
    e.preventDefault();
    chrome.storage.local.set({ snipeModeEnabled: document.getElementById('snipe_mode_switch').checked });
});
chrome.storage.local.get('snipeModeEnabled', (result) => {
    if (result.snipeModeEnabled == null || result.snipeModeEnabled === '') {
        result.snipeModeEnabled = false;
        chrome.storage.local.set({ snipeModeEnabled: result.snipeModeEnabled });
    } else {
        document.getElementById('snipe_mode_switch').checked = result.snipeModeEnabled;
    }
});

// --- Use Simple Description ---
document.getElementById('use_simple_description_switch').addEventListener('change', async function (e) {
    e.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 (result.useSimpleDescription == null) {
        result.useSimpleDescription = false;
        chrome.storage.local.set({ useSimpleDescription: result.useSimpleDescription });
    } else {
        document.getElementById('use_simple_description_switch').checked = result.useSimpleDescription;
    }
});

// --- More Navigation Buttons ---
document.getElementById('open_boost_my_listings').addEventListener('click', function (e) {
    e.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Boost_My_Listings/index.html') });
});

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

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

// --- Schedule Listing Time ---
const scheduleListingTimeSelect = document.getElementById('schedule_listing_time');
scheduleListingTimeSelect.addEventListener('change', function (e) {
    e.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 (result.scheduleListingTime === undefined) {
        chrome.storage.local.set({ scheduleListingTime: false });
        scheduleListingTimeSelect.value = 'false';
    } else {
        const value = result.scheduleListingTime;
        scheduleListingTimeSelect.value = value === false ? 'false' : String(value);
    }
});