// Product Finder for Amazon/eBay - Chrome Extension

console.log('product_finder.js loaded');

let productList = [];

// ============================================================================
// MEMBERSHIP GATE
// Plans with access: Trial (active), Novice, Professional, Prestige.
// Same pattern as bulk_post_settings_bundle — checks result.allowed from the
// background's checkMembership handler, with _trackerUid as a logged-out guard
// and _cachedPlan as a secondary fallback.
// ============================================================================

const PRODUCT_FINDER_ALLOWED_PLANS = ['trial', 'novice', 'professional', 'prestige'];

/**
 * Returns true if the current user has Product Finder access.
 * Step 1 — _trackerUid absent → user is logged out, reject immediately.
 * Step 2 — ask background (getCachedTrackerAuth → Firestore → { allowed }).
 * Step 3 — fallback to _cachedPlan (safe because step 1 confirmed logged in).
 */
async function verifyProductFinderAccess() {
    const { _trackerUid } = await chrome.storage.local.get('_trackerUid');
    if (!_trackerUid) {
        showProductFinderGateModal('none', null);
        return false;
    }

    const result = await new Promise(resolve => {
        chrome.runtime.sendMessage({ type: 'checkMembership' }, res => {
            void chrome.runtime.lastError;
            resolve(res || null);
        });
    });

    if (result?.allowed === true) return true;

    const { _cachedPlan } = await chrome.storage.local.get('_cachedPlan');
    if (_cachedPlan && PRODUCT_FINDER_ALLOWED_PLANS.includes(_cachedPlan.toLowerCase().trim())) {
        return true;
    }

    showProductFinderGateModal(result?.membership ?? null, _cachedPlan ?? null);
    return false;
}

/**
 * Overlay shown when the user doesn't have Product Finder access.
 */
function showProductFinderGateModal(membership, cachedPlan) {
    const existing = document.getElementById('ss-product-finder-gate-modal');
    if (existing) existing.remove();

    let bodyText;
    if (membership === 'expired') {
        bodyText = 'Your membership has <strong style="color:#f87171">expired</strong>. Please renew to continue using the Product Finder.';
    } else if (cachedPlan && !PRODUCT_FINDER_ALLOWED_PLANS.includes(cachedPlan.toLowerCase().trim())) {
        bodyText = `Your current plan <strong style="color:#f87171">${cachedPlan}</strong> does not have Product Finder access.`;
    } else {
        bodyText = 'No active membership was found. Please log in through the website.';
    }

    const overlay = document.createElement('div');
    overlay.id = 'ss-product-finder-gate-modal';
    overlay.style.cssText = [
        'position:fixed', 'inset:0', 'z-index:99999',
        'background:rgba(0,0,0,0.65)', 'backdrop-filter:blur(4px)',
        'display:flex', 'align-items:center', 'justify-content:center',
    ].join(';');

    overlay.innerHTML = `
        <div style="background:#0f1624;border:1px solid #2a3a5c;border-radius:16px;
                    padding:44px 48px;max-width:480px;width:90%;text-align:center;
                    box-shadow:0 12px 60px rgba(0,0,0,0.7);">
            <div style="font-size:52px;margin-bottom:18px;">🔒</div>
            <h2 style="color:#e2e8f0;font-size:22px;margin:0 0 12px 0;font-weight:700;">Access Restricted</h2>
            <p style="color:#94a3b8;font-size:15px;margin:0 0 20px 0;line-height:1.7;">
                ${bodyText}
            </p>
            <p style="color:#64748b;font-size:13px;margin:0 0 28px 0;line-height:1.6;">
                Eligible plans:<br>
                Trial &nbsp;·&nbsp; Novice &nbsp;·&nbsp; Professional &nbsp;·&nbsp; Prestige
            </p>
            <button id="ss-pf-gate-close"
                style="background:#1e3a5f;color:#e2e8f0;border:1px solid #2a4a7f;
                       border-radius:8px;padding:12px 36px;cursor:pointer;font-size:15px;font-weight:600;">
                Close
            </button>
        </div>`;

    document.body.appendChild(overlay);
    document.getElementById('ss-pf-gate-close').addEventListener('click', () => overlay.remove());
    overlay.addEventListener('click', e => { if (e.target === overlay) overlay.remove(); });
}



// ============================================================================
// URL BUILDING FUNCTIONS
// ============================================================================

/**
 * Build Amazon search URL with filters
 */
function buildAmazonSearchUrl(searchQuery, {
    primeEligible = true,
    maxPrice = null,
    minPrice = null,
    pageNumber = 1,
    sort = 'reviews',
    freeShipping = true,
    domain = 'com',
    isSellerAmazon = false
} = {}) {
    console.log('buildAmazonSearchUrl');
    console.log(searchQuery);
    console.log('maxPrice: ' + maxPrice);
    console.log('minPrice: ' + minPrice);

    let url = `https://www.amazon.${domain}/s?k=${encodeURIComponent(searchQuery)}`;

    // Price filters (prices are multiplied by 100 for Amazon's format)
    if (minPrice != null && maxPrice == null) {
        url += `&rh=p_36%3A${minPrice * 100}-`;
    } else if (minPrice == null && maxPrice != null) {
        url += `&rh=p_36%3A-${maxPrice * 100}`;
    } else if (minPrice != null && maxPrice != null) {
        url += `&rh=p_36%3A${minPrice * 100}-${maxPrice * 100}`;
    } else if (minPrice == null && maxPrice == null) {
        url += '&rh=p_36%3A-';
    }

    // Prime eligible filter (domain-specific)
    if (domain === 'com') {
        url += '%2Cp_85%3A2470955011';
    } else if (domain === 'ca') {
        url += '%2Cp_85%3A5690392011';
    }

    if (domain === 'com.au') {
        url += '%2Cp_n_prime_domestic%3A6845356051';
    }

    if (domain === 'nl') {
        url += '%2Cp_n_free_shipping_eligible%3A17033278031';
    }

    // Free shipping filter
    if (freeShipping) {
        if (domain === 'com') {
            url += '%2C';
            url += 'p_76%3A1249155011';
        } else if (domain === 'ca') {
            url += '%2C';
            url += 'p_76%3A3276484011';
        }
    }

    // Amazon as seller filter
    if (isSellerAmazon) {
        if (domain === 'com') {
            url += '%2C';
            url += 'p_n_feature_forty-seven_browse-bin%3A24677333011';
        } else if (domain === 'ca') {
            url += '%2C';
            url += 'p_6%3AA3DWYIK6Y9EEQB';
        }
    }

    // Prime eligible refinement
    if (primeEligible) {
        url += '&rhf=gp%3Aa';
    }

    // Sort options
    if (sort === 'lowest-price') {
        url += '&s=price-asc-rank';
    } else if (sort === 'reviews') {
        url += '&s=review-count-rank';
    }

    return url;
}

/**
 * Build eBay research URL
 */
function buildEbayResearchUrl(
    keywords,
    domain = 'ca',
    dayRange = 30,
    categoryId = 0,
    offset = 0,
    limit = 50,
    sorting = '-itemssold',
    tabName = 'SOLD',
    marketplace = 'EBAY-CA',
    timezone = 'America/Toronto',
    buyerLocation = 'BuyerLocation:::CA',
    minPrice = 30
) {
    marketplace = '';

    switch (domain) {
        case 'ca':
        default:
            marketplace = 'EBAY-CA';
            break;
        case 'com':
            marketplace = 'EBAY-US';
            break;
        case 'co.uk':
            marketplace = 'EBAY-UK';
    }

    return `https://www.ebay.${domain}/sh/research?` + [
        `keywords=${keywords}`,
        `dayRange=${dayRange}`,
        `categoryId=${categoryId}`,
        `offset=${offset}`,
        `limit=${limit}`,
        `sorting=${sorting}`,
        `tabName=${tabName}`,
        `marketplace=${marketplace}`,
        `tz=${encodeURIComponent(timezone)}`,
        `minPrice=${minPrice}`
    ].join('&');
}

/**
 * Build eBay active listings URL (legacy function)
 */
function buildEbayActiveUrl(keywords) {
    return `https://www.ebay.ca/sh/research?marketplace=EBAY-CA&keywords=${encodeURIComponent(keywords)}&dayRange=30&endDate=1679082379576&startDate=1676493979576&categoryId=0&offset=0&limit=50&tabName=ACTIVE&tz=America%2FToronto`;
}

// ============================================================================
// INITIALIZATION
// ============================================================================

document.addEventListener('DOMContentLoaded', async function (event) {
    // Load search state
    const [
        amazonSearchQueryPosition,
        totalAsinsToFetchFromSearch,
        minPrice,
        maxPrice,
        runStatus,
        amazonSearchQueries,
        duplicateProtection
    ] = await new Promise((resolve, reject) => {
        chrome.storage.local.get([
            'amazonSearchQueryPosition',
            'totalAsinsToFetchFromSearch',
            'minPrice',
            'maxPrice',
            'run_status',
            'amazonSearchQuerys',
            'duplicate_protection'
        ], function (result) {
            resolve([
                result.amazonSearchQueryPosition,
                result.totalAsinsToFetchFromSearch,
                result.minPrice,
                result.maxPrice,
                result.run_status,
                result.amazonSearchQuerys,
                result.duplicate_protection
            ]);
        });
    });

    // Load product list
    productList = await new Promise((resolve, reject) => {
        chrome.storage.local.get(['productList'], function (result) {
            console.log('productList: ', result.productList);
            resolve(result.productList);
        });
    });

    console.log('amazonSearchQueryPosition: ' + amazonSearchQueryPosition);
    console.log('totalAsinsToFetchFromSearch: ' + totalAsinsToFetchFromSearch);
    console.log('productList: ', productList);
    console.log('minPrice: ' + minPrice);
    console.log('maxPrice: ' + maxPrice);
    console.log('run_status: ' + runStatus);
    console.log('amazonSearchQuerys: ' + amazonSearchQueries);
    console.log('duplicate_protection: ' + duplicateProtection);

    // Load filter settings
    const [
        sortByReviews,
        prioritizeAmazonChoice,
        prioritizeBestSellers,
        removeBooks,
        minReviews,
        maxReviews
    ] = await new Promise((resolve, reject) => {
        chrome.storage.local.get([
            'sortByReviews',
            'prioritizeAmazonChoice',
            'prioritizeBestSellers',
            'remove_books',
            'min_reviews',
            'max_reviews'
        ], function (result) {
            resolve([
                result.sortByReviews,
                result.prioritizeAmazonChoice,
                result.prioritizeBestSellers,
                result.remove_books,
                result.min_reviews,
                result.max_reviews
            ]);
        });
    });

    console.log('sortByReviews: ' + sortByReviews);
    console.log('prioritizeAmazonChoice: ' + prioritizeAmazonChoice);
    console.log('prioritizeBestSellers: ' + prioritizeBestSellers);
    console.log('remove_books: ' + removeBooks);
    console.log('min_reviews: ' + minReviews);
    console.log('max_reviews: ' + maxReviews);

    // Load amazon_is_seller setting
    const { amazon_is_seller: amazonIsSeller } = await chrome.storage.local.get('amazon_is_seller');

    if (amazonIsSeller == null) {
        console.log('amazon_is_seller: ', amazonIsSeller);
        chrome.storage.local.set({ amazon_is_seller: false });
        document.getElementById('amazon_is_seller').checked = false;
    } else {
        document.getElementById('amazon_is_seller').checked = amazonIsSeller;
    }

    // Set button states based on run status
    if (runStatus == null || runStatus === 0) {
        chrome.storage.local.set({ run_status: false });
        document.getElementById('pause_button').disabled = true;
    } else if (runStatus === 1) {
        document.getElementById('resume_button').disabled = true;
    }

    // Initialize UI with saved values
    if (amazonSearchQueryPosition == null) {
        chrome.storage.local.set({ amazonSearchQueryPosition: 0 });
    } else {
        document.getElementById('searchTermPosition').value = amazonSearchQueryPosition;
    }

    if (totalAsinsToFetchFromSearch == null) {
        chrome.storage.local.set({ totalAsinsToFetchFromSearch: 2 });
    } else {
        document.getElementById('numberToExtract').value = totalAsinsToFetchFromSearch;
    }

    if (productList == null) {
        chrome.storage.local.set({ productList: [] });
    } else {
        renderProductTable(productList);
    }

    if (minPrice == null) {
        chrome.storage.local.set({ minPrice: 1 });
    } else {
        document.getElementById('minPrice').value = minPrice;
    }

    if (maxPrice == null) {
        chrome.storage.local.set({ maxPrice: 100 });
    } else {
        document.getElementById('maxPrice').value = maxPrice;
    }

    // Initialize search queries
    if (amazonSearchQueries == null) {
        chrome.storage.local.set({ amazonSearchQuerys: [] });
    } else {
        document.getElementById('searchTerms').value = amazonSearchQueries.join('\n');
        document.getElementById('searchTermTotal').innerHTML = amazonSearchQueries.length;
    }

    // Initialize sort settings
    if (sortByReviews == null) {
        chrome.storage.local.set({ sortByReviews: true });
    } else {
        console.log('sortByReviews: ', sortByReviews);
        document.getElementById('sort-by-reviews').checked = sortByReviews;
    }

    if (prioritizeAmazonChoice == null) {
        chrome.storage.local.set({ prioritizeAmazonChoice: true });
    } else {
        document.getElementById('prioritizeAmazonChoice').checked = prioritizeAmazonChoice;
    }

    if (prioritizeBestSellers == null) {
        chrome.storage.local.set({ prioritizeBestSellers: true });
    } else {
        document.getElementById('prioritizeBestSellers').checked = prioritizeBestSellers;
    }

    // Initialize duplicate protection
    if (duplicateProtection == null) {
        console.log('duplicate_protection: ', duplicateProtection);
        chrome.storage.local.set({ duplicate_protection: true });
    } else {
        document.getElementById('duplicate_protection').checked = duplicateProtection;
    }

    // Initialize remove books filter
    if (removeBooks == null) {
        console.log('remove_books: ', removeBooks);
        chrome.storage.local.set({ remove_books: true });
    } else {
        document.getElementById('remove_books').checked = removeBooks;
    }

    // Initialize review range
    if (minReviews == null) {
        console.log('min_reviews: ', minReviews);
        chrome.storage.local.set({ min_reviews: 1 });
    } else {
        document.getElementById('min_reviews').value = minReviews;
    }

    if (maxReviews == null) {
        console.log('max_reviews: ', maxReviews);
        chrome.storage.local.set({ max_reviews: 100000 });
    } else {
        document.getElementById('max_reviews').value = maxReviews;
    }

    // Load restricted words
    const { restricted_words: restrictedWords } = await chrome.storage.local.get('restricted_words');

    if (restrictedWords == null) {
        console.log('restricted_words: ', restrictedWords);
        fetch(chrome.runtime.getURL('/restricted_words.txt'))
            .then(response => response.text())
            .then(text => {
                const wordsArray = text.split('\n');
                const wordsString = wordsArray.join('\n');
                document.getElementById('restricted_words').value = wordsString;
                chrome.storage.local.set({ restricted_words: wordsArray });
            });
    } else {
        const wordsString = restrictedWords.join('\n');
        document.getElementById('restricted_words').value = wordsString;
    }

    // Load VERO protection setting
    const { veroProtectionEnabled } = await chrome.storage.local.get('veroProtectionEnabled');

    if (veroProtectionEnabled == null) {
        console.log('veroProtectionEnabled: ', veroProtectionEnabled);
        chrome.storage.local.set({ veroProtectionEnabled: true });
    } else {
        document.getElementById('vero_protection_switch').checked = veroProtectionEnabled;
    }

    // Load max similar niche items
    const { max_similiar_niche_items: maxSimilarNicheItems } =
        await chrome.storage.local.get('max_similiar_niche_items');

    if (maxSimilarNicheItems == null) {
        console.log('max_similiar_niche_items: ', maxSimilarNicheItems);
        chrome.storage.local.set({ max_similiar_niche_items: 2 });
    } else {
        document.getElementById('max_similiar_niche_items').value = maxSimilarNicheItems;
    }

    // Load product hunter supplier
    const { product_hunter_supplier: productHunterSupplier } =
        await chrome.storage.local.get('product_hunter_supplier');

    if (productHunterSupplier == null) {
        console.log('product_hunter_supplier: ', productHunterSupplier);
        chrome.storage.local.set({ product_hunter_supplier: 'amazon' });
    } else {
        document.getElementById('product_hunter_supplier').value = productHunterSupplier;
    }

    // Load thread count
    const { hunterThreadCount } = await chrome.storage.local.get('hunterThreadCount');

    if (hunterThreadCount == null) {
        console.log('hunterThreadCount: ', hunterThreadCount);
        chrome.storage.local.set({ hunterThreadCount: 3 });
        document.getElementById('hunterThreadCount').value = 3;
    } else {
        document.getElementById('hunterThreadCount').value = hunterThreadCount;
    }

    // chinese_only removed from UI — hardcode off
    chrome.storage.local.set({ chinese_only: false });

    // Load delivery days filter
    const { getItemsWithMaxDeliveryDays } =
        await chrome.storage.local.get('getItemsWithMaxDeliveryDays');

    if (getItemsWithMaxDeliveryDays == null) {
        console.log('getItemsWithMaxDeliveryDays: ', getItemsWithMaxDeliveryDays);
        chrome.storage.local.set({ getItemsWithMaxDeliveryDays: false });
    } else {
        document.getElementById('getItemsWithMaxDeliveryDays').checked = getItemsWithMaxDeliveryDays;
    }

    const { maxExtendedDeliveryDays } =
        await chrome.storage.local.get('maxExtendedDeliveryDays');

    if (maxExtendedDeliveryDays == null) {
        console.log('maxExtendedDeliveryDays: ', maxExtendedDeliveryDays);
        chrome.storage.local.set({ maxExtendedDeliveryDays: 7 });
    } else {
        document.getElementById('maxExtendedDeliveryDays').value = maxExtendedDeliveryDays;
    }

    // Initialize UI components
    updateDuplicateBatchInfo();
    setupModalHandlers();
    setupModalCloseHandlers();
    setupKeywordFilters();
    await loadKeywordSettings();

    // ── Membership gate on open ────────────────────────
    // Show the modal immediately if the user isn't authenticated.
    verifyProductFinderAccess();
    // ────────────────────────────────────────────────
});

// ============================================================================
// TABLE RENDERING
// ============================================================================

async function renderProductTable(products) {
    const tableBody = document.getElementById('productTable').getElementsByTagName('tbody')[0];

    const { domain } = await chrome.storage.local.get('domain');
    const { product_hunter_supplier: supplier } =
        await chrome.storage.local.get('product_hunter_supplier');

    for (const product of products) {
        const row = tableBody.insertRow();
        const imageCell = row.insertCell();
        const titleCell = row.insertCell();
        const priceCell = row.insertCell();
        const reviewsCell = row.insertCell();
        const asinCell = row.insertCell();

        asinCell.style.display = 'none';
        asinCell.className = 'asin';

        const actionsCell = row.insertCell();

        // Image with click handler
        imageCell.innerHTML = `<img class="img-link" src="${product.image}" alt="${product.title}">`;
        imageCell.addEventListener('click', event => {
            console.log('e.target', event.target.parentElement.parentElement);

            const asin = event.target.parentElement.parentElement.querySelector('.asin').textContent;
            let url = '';

            if (supplier === 'amazon') {
                console.log('amazon');
                url = `https://www.amazon.${domain}/dp/${asin}`;
            } else if (supplier === 'home-depot') {
                console.log('home-depot');
                url = `https://www.homedepot.com/p/${asin}`;
            }

            window.open(url, '_blank');
        });

        titleCell.textContent = product.title;
        priceCell.textContent = product.price;
        reviewsCell.textContent = product.reviewCount;
        asinCell.textContent = product.asin;

        // Delete button
        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'Delete';
        deleteButton.addEventListener('click', () => {
            row.remove();
        });
        actionsCell.appendChild(deleteButton);

        // eBay listing if available
        if (product.json) {
            const { title, price, image, itemNumber } = product.json;
            const ebayCell = row.insertCell();

            const container = document.createElement('div');
            container.style.cssText = `
                font-family: sans-serif;
                font-size: 13px;
                display: flex;
                align-items: center;
                gap: 8px;
                border: 1px solid #ccc;
                padding: 6px;
                border-radius: 4px;
                max-width: 400px;
            `;

            const link = document.createElement('a');
            link.href = `https://www.ebay.com/itm/${itemNumber}`;
            link.target = '_blank';

            const img = document.createElement('img');
            img.src = image;
            img.alt = 'product image';
            img.style.cssText = `
                width: 60px;
                height: 60px;
                object-fit: cover;
                border-radius: 4px;
            `;
            link.appendChild(img);

            const info = document.createElement('div');
            info.style.flex = '1';

            const titleDiv = document.createElement('div');
            titleDiv.textContent = title;
            titleDiv.style.cssText = `
                font-weight: bold;
                margin-bottom: 4px;
            `;

            const priceDiv = document.createElement('div');
            priceDiv.textContent = `Price: $${price}`;
            priceDiv.style.color = '#444';

            info.appendChild(titleDiv);
            info.appendChild(priceDiv);
            container.appendChild(link);
            container.appendChild(info);
            ebayCell.appendChild(container);
        }
    }

    document.getElementById('totalResults').innerHTML = `${products.length} results`;
}

// ============================================================================
// EVENT HANDLERS - Search Terms
// ============================================================================

document.getElementById('searchTerms').addEventListener('change', function (event) {
    let searchTerms = document.getElementById('searchTerms').value.split('\n');
    console.log(searchTerms);

    searchTerms = searchTerms.filter(function (term) {
        return term !== '';
    });

    document.getElementById('searchTerms').value = searchTerms.join('\n');
    chrome.storage.local.set({ amazonSearchQuerys: searchTerms });
    document.getElementById('searchTermTotal').innerHTML = searchTerms.length;
});

document.getElementById('clearTerms').addEventListener('click', function (event) {
    document.getElementById('searchTerms').value = '';
    chrome.storage.local.set({ amazonSearchQuerys: [] });
    document.getElementById('searchTermTotal').innerHTML = '0';
    chrome.storage.local.set({ amazonSearchQueryPosition: 0 });
    document.getElementById('searchTermPosition').value = 0;
});

document.getElementById('clearResults').addEventListener('click', function (event) {
    clearProductTable();
    chrome.storage.local.set({ productList: [] });
    document.getElementById('totalResults').innerHTML = '0 results';
});

function clearProductTable() {
    const table = document.getElementById('productTable');
    for (let i = table.getElementsByTagName('tr').length - 1; i > 0; i--) {
        table.deleteRow(i);
    }
}

// ============================================================================
// EVENT HANDLERS - Search Actions
// ============================================================================

document.getElementById('searchTitles').addEventListener('click', async function (event) {
    event.preventDefault();

    // ── Membership gate ────────────────────────────────────────
    const hasAccess = await verifyProductFinderAccess();
    if (!hasAccess) return;
    // ────────────────────────────────────────────────

    const searchPosition = document.getElementById('searchTermPosition').value;
    let jsonData = null;

    // Try to parse as JSON
    try {
        jsonData = JSON.parse(document.getElementById('searchTerms').value);
    } catch (error) {
        console.log('searchTermPosition is not a json');
    }

    let searchTerms;

    if (jsonData) {
        console.log('json', jsonData);
        searchTerms = jsonData.map(item =>
            item.title || item.name || item.product_name || item
        );
        document.getElementById('searchTermTotal').innerHTML = searchTerms.length;
    } else {
        console.log('searchTermPosition is not a json, using it as search terms position');
        searchTerms = document.getElementById('searchTerms').value.split('\n');
    }

    if (searchPosition != searchTerms.length) {
        // Disable buttons temporarily
        document.getElementById('searchTitles').disabled = true;
        document.getElementById('searchKeywords').disabled = true;

        setTimeout(function () {
            document.getElementById('searchTitles').disabled = false;
            document.getElementById('searchKeywords').disabled = false;
        }, 3000);

        chrome.runtime.sendMessage({ type: 'terminateSearch' });
        document.getElementById('searchTerms').dispatchEvent(new Event('input'));
        updateProgressBar(0);
        chrome.storage.local.set({ run_status: true });
        document.getElementById('pause_button').disabled = false;
        document.getElementById('resume_button').disabled = true;

        const options = {
            minPrice: document.getElementById('minPrice').value,
            maxPrice: document.getElementById('maxPrice').value,
            isSellerAmazon: document.getElementById('amazon_is_seller').checked
        };

        const supplier = document.getElementById('product_hunter_supplier').value;
        options.product_hunter_supplier = supplier;

        if (jsonData) {
            console.log('searching amazon with json');
            chrome.runtime.sendMessage({
                type: 'startSearchingAmazon',
                searchType: 'title-price',
                options: options,
                json: jsonData
            });
        } else {
            chrome.runtime.sendMessage({
                type: 'startSearchingAmazon',
                searchType: 'title',
                options: options
            });
        }
    } else {
        alert('All search terms have been searched. Please reset the search term position to 0 to search again.');
        document.getElementById('searchTermPosition').classList.add('alert');
        setTimeout(function () {
            document.getElementById('searchTermPosition').classList.remove('alert');
        }, 6000);
    }
});

document.getElementById('searchKeywords').addEventListener('click', async function (event) {
    event.preventDefault();

    // ── Membership gate ────────────────────────────────────────
    const hasAccess = await verifyProductFinderAccess();
    if (!hasAccess) return;
    // ────────────────────────────────────────────────

    document.getElementById('searchKeywords').disabled = true;
    document.getElementById('searchTitles').disabled = true;

    chrome.runtime.sendMessage({ type: 'terminateSearch' });
    document.getElementById('searchTerms').dispatchEvent(new Event('input'));
    updateProgressBar(0);
    chrome.storage.local.set({ run_status: true });
    document.getElementById('pause_button').disabled = false;
    document.getElementById('resume_button').disabled = true;

    const options = {
        minPrice: document.getElementById('minPrice').value,
        maxPrice: document.getElementById('maxPrice').value,
        isSellerAmazon: document.getElementById('amazon_is_seller').checked
    };

    chrome.runtime.sendMessage({
        type: 'startSearchingAmazon',
        searchType: 'keywords',
        options: options
    });
});

// ============================================================================
// EVENT HANDLERS - Pause/Resume
// ============================================================================

document.getElementById('pause_button').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ run_status: false });
    document.getElementById('pause_button').disabled = true;
    document.getElementById('resume_button').disabled = false;
});

document.getElementById('resume_button').addEventListener('click', async function (event) {
    event.preventDefault();
    chrome.storage.local.set({ run_status: true });
    document.getElementById('pause_button').disabled = false;
    document.getElementById('resume_button').disabled = true;
});

// ============================================================================
// EVENT HANDLERS - Settings Changes
// ============================================================================

document.getElementById('searchTermPosition').addEventListener('change', function (event) {
    const position = document.getElementById('searchTermPosition').value;
    console.log(position);
    chrome.storage.local.set({ amazonSearchQueryPosition: position });
});

document.getElementById('numberToExtract').addEventListener('change', function (event) {
    const count = document.getElementById('numberToExtract').value;
    chrome.storage.local.set({ totalAsinsToFetchFromSearch: count });
});

document.getElementById('minPrice').addEventListener('change', function (event) {
    const price = document.getElementById('minPrice').value;
    chrome.storage.local.set({ minPrice: price });
});

document.getElementById('maxPrice').addEventListener('change', function (event) {
    const price = document.getElementById('maxPrice').value;
    chrome.storage.local.set({ maxPrice: price });
});

document.getElementById('sort-by-reviews').addEventListener('change', function (event) {
    const checked = document.getElementById('sort-by-reviews').checked;
    chrome.storage.local.set({ sortByReviews: checked });
});

document.getElementById('prioritizeAmazonChoice').addEventListener('change', function (event) {
    const checked = document.getElementById('prioritizeAmazonChoice').checked;
    chrome.storage.local.set({ prioritizeAmazonChoice: checked });
});

document.getElementById('prioritizeBestSellers').addEventListener('change', function (event) {
    const checked = document.getElementById('prioritizeBestSellers').checked;
    chrome.storage.local.set({ prioritizeBestSellers: checked });
});

document.getElementById('duplicate_protection').addEventListener('change', function (event) {
    const checked = document.getElementById('duplicate_protection').checked;
    chrome.storage.local.set({ duplicate_protection: checked });
});

document.getElementById('remove_books').addEventListener('change', function (event) {
    const checked = document.getElementById('remove_books').checked;
    chrome.storage.local.set({ remove_books: checked });
});

document.getElementById('amazon_is_seller').addEventListener('change', function (event) {
    const checked = document.getElementById('amazon_is_seller').checked;
    chrome.storage.local.set({ amazon_is_seller: checked });
});

document.getElementById('min_reviews').addEventListener('change', function (event) {
    const value = document.getElementById('min_reviews').value;
    chrome.storage.local.set({ min_reviews: value });
});

document.getElementById('max_reviews').addEventListener('change', function (event) {
    const value = document.getElementById('max_reviews').value;
    chrome.storage.local.set({ max_reviews: value });
});

document.getElementById('max_similiar_niche_items').addEventListener('change', function (event) {
    let value = document.getElementById('max_similiar_niche_items').value;
    value = parseInt(value);
    chrome.storage.local.set({ max_similiar_niche_items: value });
});

document.getElementById('product_hunter_supplier').addEventListener('change', function (event) {
    const value = document.getElementById('product_hunter_supplier').value;
    chrome.storage.local.set({ product_hunter_supplier: value });
});

document.getElementById('restricted_words').addEventListener('change', function (event) {
    let words = document.getElementById('restricted_words').value;
    words = words.split('\n');

    words = words.filter(function (word) {
        return word !== '';
    });

    words = [...new Set(words)];

    words = words.map(function (word) {
        return word.toLowerCase();
    });

    chrome.storage.local.set({ restricted_words: words });
    document.getElementById('restricted_words').value = words.join('\n');
});

document.getElementById('vero_protection_switch').addEventListener('change', function (event) {
    const checked = document.getElementById('vero_protection_switch').checked;
    chrome.storage.local.set({ veroProtectionEnabled: checked });
});

// ============================================================================
// EVENT HANDLERS - Export/Open Actions
// ============================================================================

document.getElementById('openResults').addEventListener('click', async function (event) {
    event.preventDefault();

    chrome.storage.local.get(['productList'], function (result) {
        const products = result.productList;
        for (let i = 0; i < products.length; i++) {
            chrome.runtime.sendMessage({
                type: 'openNewTab',
                url: products[i]
            });
        }
    });
});

document.getElementById('open-duplicate-skus-10').addEventListener('click', async function (event) {
    event.preventDefault();

    const urls = getNextDuplicateBatch();
    console.log(urls);

    for (let i = 0; i < urls.length; i++) {
        chrome.runtime.sendMessage({
            type: 'openNewTab',
            url: urls[i]
        });
    }
});

function getNextDuplicateBatch() {
    const allUrls = document.querySelector('#results').value.split('\n');
    const batchNumber = document.querySelector('#duplicate-batch-number').value;

    const startIndex = 5 * (batchNumber - 1);
    let endIndex = startIndex + 5;

    if (endIndex > allUrls.length) {
        endIndex = allUrls.length;
    }

    const batch = allUrls.slice(startIndex, endIndex);

    document.querySelector('#duplicate-batch-number').value = parseInt(batchNumber) + 1;

    return batch;
}

function updateDuplicateBatchInfo() {
    chrome.storage.local.get(['productList'], function (result) {
        const products = result.productList;
        const totalBatches = Math.ceil(products.length / 5);
        document.querySelector('#duplicate-batch-total').textContent = totalBatches;
    });
}

// ============================================================================
// PROGRESS BAR
// ============================================================================

function updateProgressBar(percentage) {
    const progressBar = document.getElementById('progress-bar');
    const percentageLabels = document.querySelectorAll('.progress-percentage');

    if (percentage < 0) {
        percentage = 0;
    } else if (percentage > 100) {
        percentage = 100;
    }

    progressBar.style.width = percentage + '%';

    percentageLabels.forEach(function (label) {
        label.textContent = percentage + '%';
    });

    if (percentage > 0) {
        percentageLabels.forEach(function (label) {
            label.style.visibility = 'visible';
        });
        progressBar.style.backgroundColor = '#90ee90';
    }

    if (percentage >= 100) {
        progressBar.style.backgroundColor = '#008000';
        document.getElementById('searchTitles').disabled = false;
        document.getElementById('searchKeywords').disabled = false;
    }
}

// ============================================================================
// MESSAGE LISTENERS
// ============================================================================

chrome.runtime.onMessage.addListener(async function (message, sender, sendResponse) {
    if (message.type === 'updateProgressBar') {
        console.log('updateProgressBar: ', message.percentage);
        updateProgressBar(message.percentage);

        chrome.storage.local.get(['productList'], function (result) {
            clearProductTable();
            renderProductTable(result.productList);
        });

        chrome.storage.local.get(['amazonSearchQueryPosition'], function (result) {
            document.getElementById('searchTermPosition').value = result.amazonSearchQueryPosition;
        });

        updateDuplicateBatchInfo();
    }

    if (message.type === 'search_product_hunter') {
        console.log('search_product_hunter: ', message.searchTerms);
        searchProductHunter(message.searchTerms);
    }
});

async function searchProductHunter(searchTerms) {
    const cleanedTerms = searchTerms.filter(term => term.trim() !== '');

    chrome.runtime.sendMessage({ type: 'terminateSearch' });
    await new Promise(resolve => setTimeout(resolve, 200));

    await chrome.storage.local.set({
        productList: [],
        amazonSearchQuerys: cleanedTerms,
        amazonSearchQueryPosition: 0,
        run_status: true
    });

    productList = [];

    document.getElementById('searchTerms').value = cleanedTerms.join('\n');
    document.getElementById('searchTermPosition').value = 0;
    document.getElementById('searchTermTotal').innerText = cleanedTerms.length;
    document.getElementById('totalResults').innerText = '0 results';

    clearProductTable();
    updateProgressBar(0);

    const options = {
        minPrice: document.getElementById('minPrice').value,
        maxPrice: document.getElementById('maxPrice').value,
        isSellerAmazon: document.getElementById('amazon_is_seller').checked,
        product_hunter_supplier: document.getElementById('product_hunter_supplier').value
    };

    document.getElementById('searchTitles').disabled = true;
    document.getElementById('searchKeywords').disabled = true;
    document.getElementById('pause_button').disabled = false;
    document.getElementById('resume_button').disabled = true;

    chrome.runtime.sendMessage({
        type: 'startSearchingAmazon',
        searchType: 'title',
        options: options
    }, function (response) {
        console.log('Search initiated with response: ', response);
        clearProductTable();
        renderProductTable(response.productList || []);
    });
}

// ============================================================================
// RANDOM WORD GENERATION
// ============================================================================

document.getElementById('generateRandomWords').addEventListener('click', async function (event) {
    document.getElementById('generateRandomWords').disabled = true;
    document.getElementById('generateRandomWords').innerHTML = 'Generating 100 random words...';
    document.getElementById('loadingBarContainer').style.display = 'block';

    const randomWords = await generateRandomWords();
    const textarea = document.getElementById('searchTerms');

    textarea.value = randomWords.join('\n');
    textarea.dispatchEvent(new Event('change'));

    document.getElementById('loadingBarContainer').style.display = 'none';
    document.getElementById('loadingBar').style.width = '0%';
    document.getElementById('generateRandomWords').disabled = false;
    document.getElementById('generateRandomWords').innerHTML = 'Generate 100 Random Words';
});

async function generateRandomWords() {
    let words = [];

    for (let i = 0; i < 100; i++) {
        const response = await fetch('https://random-word-api.herokuapp.com/word?number=1');

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const data = await response.json();
        words.push(data[0]);

        document.getElementById('loadingBar').style.width = (i + 1) + '%';
    }

    return words;
}

// ============================================================================
// EXPORT FUNCTIONALITY
// ============================================================================

document.getElementById('exportResults').addEventListener('click', async function (event) {
    event.preventDefault();

    const table = document.getElementById('productTable');
    const asins = [];

    for (let row, i = 1; row = table.rows[i]; i++) {
        const asin = row.cells[4].textContent;
        asins.push(asin);
    }

    const { domain } = await chrome.storage.local.get('domain');

    const urls = asins.map(asin =>
        `https://www.amazon.${domain}/dp/${asin}?th=1&psc=1`
    );

    const modal = document.getElementById('myModal');
    const textarea = document.getElementById('myTextarea');

    textarea.value = urls.join('\n');
    document.getElementById('totalLinks').textContent = urls.length;
    modal.style.display = 'block';

    document.getElementById('myButton').onclick = function () {
        textarea.select();
        document.execCommand('copy');
    };

    document.getElementById('closeModal').onclick = function () {
        modal.style.display = 'none';
    };
});

// ============================================================================
// QUICK FILTER
// ============================================================================

function extractProductsFromTable(table) {
    const products = [];

    for (let row, i = 1; row = table.rows[i]; i++) {
        console.log('row: ', row);

        let imageSrc;
        try {
            imageSrc = row.cells[0].getElementsByTagName('img')[0].src;
        } catch (error) {
            imageSrc = chrome.runtime.getURL('/Image_Badges/noImage.jpeg');
        }

        const product = {
            image: imageSrc,
            title: row.cells[1].textContent,
            price: row.cells[2].textContent,
            reviews: row.cells[3].textContent,
            asin: row.cells[4].textContent,
            rowIndex: i
        };

        products.push(product);
    }

    return products;
}

function displayProductInModal(container, product) {
    const productDiv = document.createElement('div');
    productDiv.className = 'product-info';

    const img = document.createElement('img');
    img.src = product.image;
    img.className = 'product-image';

    const titleP = document.createElement('p');
    titleP.className = 'product-title';
    titleP.textContent = 'Title: ' + product.title;

    const priceP = document.createElement('p');
    priceP.className = 'product-price';
    priceP.textContent = 'Price: ' + product.price;

    const reviewsP = document.createElement('p');
    reviewsP.className = 'product-reviews';
    reviewsP.textContent = 'Reviews: ' + product.reviews;

    const asinP = document.createElement('p');
    asinP.className = 'product-asin';
    asinP.textContent = 'Asin: ' + product.asin;

    productDiv.appendChild(titleP);
    productDiv.appendChild(img);

    const priceReviewsDiv = document.createElement('div');
    priceReviewsDiv.className = 'price-reviews';
    priceReviewsDiv.appendChild(priceP);
    priceReviewsDiv.appendChild(reviewsP);

    productDiv.appendChild(priceReviewsDiv);
    productDiv.appendChild(asinP);

    container.innerHTML = '';
    container.appendChild(productDiv);
}

let currentProductIndex = 0;

function handleQuickFilterKeyPress(event, table, products, modalContent) {
    if (event.key === 'ArrowLeft') {
        modalContent.firstChild.classList.add('slide-left');

        console.log('currentProductIndex: ' + currentProductIndex);
        console.log('products.length: ' + products.length);
        console.log('products[currentProductIndex].rowIndex: ' + products[currentProductIndex].rowIndex);
        console.log('productTable.rows.length: ' + table.rows.length);

        setTimeout(function () {
            const rowIndex = findProductRowIndexByASIN(products[currentProductIndex].asin);
            table.deleteRow(rowIndex);

            document.getElementById('totalResults').textContent = (table.rows.length - 1) + ' Results';

            currentProductIndex++;
            document.getElementById('itemPosition').textContent = currentProductIndex + 1;

            if (products.length > 0 && currentProductIndex < products.length) {
                displayProductInModal(modalContent, products[currentProductIndex]);
            } else {
                document.getElementById('closeFilterModal').click();
            }
        }, 500);
    } else if (event.key === 'ArrowRight') {
        modalContent.firstChild.classList.add('slide-right');
        currentProductIndex++;

        setTimeout(function () {
            if (currentProductIndex < products.length) {
                document.getElementById('itemPosition').textContent = currentProductIndex + 1;
                displayProductInModal(modalContent, products[currentProductIndex]);
            } else {
                document.getElementById('closeFilterModal').click();
            }
        }, 500);
    }
}

document.getElementById('quickFilter').addEventListener('click', function (event) {
    event.preventDefault();

    const table = document.getElementById('productTable');
    const products = extractProductsFromTable(table);
    const modal = document.getElementById('filterModal');
    const modalContent = document.getElementById('modalContent');

    currentProductIndex = 0;

    console.log('products: ', products);

    document.getElementById('totalItems').textContent = products.length;
    document.getElementById('itemPosition').textContent = currentProductIndex + 1;

    displayProductInModal(modalContent, products[currentProductIndex]);

    document.getElementById('closeFilterModal').onclick = function () {
        modal.style.display = 'none';
        window.removeEventListener('keydown', keyHandler);
    };

    const keyHandler = event => handleQuickFilterKeyPress(event, table, products, modalContent);
    window.addEventListener('keydown', keyHandler);

    modal.style.display = 'block';
});

function findProductRowIndexByASIN(asin) {
    const rows = document.getElementById('productTable').rows;

    for (let i = 1; i < rows.length; i++) {
        if (rows[i].cells[4].innerHTML === asin) {
            return i;
        }
    }

    return -1;
}

// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================

document.getElementById('openKeywordTool').addEventListener('click', function (event) {
    event.preventDefault();
    window.open('https://keywordtool.io/amazon', '_blank');
});

document.getElementById('importTerms').addEventListener('click', async function (event) {
    let clipboardText = await navigator.clipboard.readText();
    let newTerms = clipboardText.split('\n');

    newTerms = newTerms.filter(function (term) {
        return term !== '';
    });

    let existingTerms = document.getElementById('searchTerms').value.split('\n');
    let allTerms = existingTerms.concat(newTerms);

    const uniqueTerms = new Set(allTerms);
    allTerms = Array.from(uniqueTerms);

    document.getElementById('searchTerms').value = allTerms.join('\n');
    document.getElementById('searchTerms').dispatchEvent(new Event('change'));
});

// ============================================================================
// FILTERING AND SORTING
// ============================================================================

document.getElementById('applyFiltersForResults').addEventListener('click', filterProductsForResults);
document.getElementById('sortButtonForResults').addEventListener('click', sortProductsByPrice);

function filterProductsForResults() {
    const minPrice = parseFloat(document.getElementById('minPriceForResults').value);
    const maxPrice = parseFloat(document.getElementById('maxPriceForResults').value);
    const minReviews = parseInt(document.getElementById('minReviewsForResults').value);
    const maxReviews = parseInt(document.getElementById('maxReviewsForResults').value);

    const filteredProducts = productList.filter(product => {
        console.log('product: ', product);

        const price = product.price;
        const reviews = product.reviewCount;

        return price >= minPrice && price <= maxPrice &&
            reviews >= minReviews && reviews <= maxReviews;
    });

    productList = filteredProducts;
    clearProductTable();
    renderProductTable(productList);
}

let sortAscending = true;

function sortProductsByPrice() {
    productList.sort((a, b) => {
        const priceA = a.price;
        const priceB = b.price;
        return sortAscending ? priceB - priceA : priceA - priceB;
    });

    sortAscending = !sortAscending;

    document.getElementById('sortButtonForResults').textContent =
        'Sort Price: ' + (sortAscending ? 'High to Low' : 'Low to High');

    clearProductTable();
    renderProductTable(productList);
}

document.getElementById('open-advanced-filter').addEventListener('click', async function (event) {
    event.preventDefault();
    document.getElementById('filterResultsContainer').style.display = 'block';
});

// ============================================================================
// MODAL HANDLERS
// ============================================================================

function setupModalHandlers() {
    document.querySelectorAll('[data-modal-target]').forEach(trigger => {
        trigger.addEventListener('click', function (event) {
            const targetSelector = trigger.getAttribute('data-modal-target');
            const modal = document.querySelector(targetSelector);

            console.log('modal: ', modal);
            modal.style.display = 'block';
            event.preventDefault();
        });
    });
}

function setupModalCloseHandlers() {
    document.querySelectorAll('.modal .close').forEach(closeBtn => {
        closeBtn.addEventListener('click', () => {
            closeBtn.closest('.modal');
            closeBtn.closest('.modal').style.display = 'none';
        });
    });

    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('click', event => {
            if (event.target === modal) {
                console.log('Setting display to none');
                modal.style.display = 'none';
            }
        });
    });
}

// ============================================================================
// KEYWORD FILTERS
// ============================================================================

function setupKeywordFilters() {
    document.getElementById('keywordsArea').addEventListener('input', saveKeywordSettings);

    document.querySelectorAll('[name="keywordRequirement"]').forEach(radio => {
        radio.addEventListener('change', saveKeywordSettings);
    });
}

async function saveKeywordSettings() {
    const keywordsText = document.getElementById('keywordsArea').value;
    const keywords = keywordsText.split('\n')
        .map(keyword => keyword.trim())
        .filter(keyword => keyword.length > 0);

    const requirementType = document.querySelector('input[name="keywordRequirement"]:checked').value;

    try {
        await chrome.storage.local.set({
            keywords: keywords,
            requirementType: requirementType
        });
        console.log('Settings saved');
    } catch (error) {
        console.error('Error saving settings:', error);
    }
}

async function loadKeywordSettings() {
    try {
        const result = await chrome.storage.local.get(['keywords', 'requirementType']);

        if (result.keywords) {
            document.getElementById('keywordsArea').value = result.keywords.join('\n');
        }

        if (result.requirementType) {
            console.log('result.requirementType: ', result.requirementType);
            document.querySelector(
                `input[name="keywordRequirement"][value="${result.requirementType}"]`
            ).checked = true;
        }

        const checkbox = document.getElementById('required_keywords_checkbox');
        const { useRequiredKeywords } = await chrome.storage.local.get('useRequiredKeywords');

        let shouldUse = useRequiredKeywords;
        if (shouldUse == null) {
            shouldUse = false;
            await chrome.storage.local.set({ useRequiredKeywords: shouldUse });
        }

        checkbox.checked = shouldUse;
        checkbox.onchange = async function () {
            await chrome.storage.local.set({
                useRequiredKeywords: checkbox.checked
            });
        };
    } catch (error) {
        console.error('Error loading settings:', error);
    }
}

// ============================================================================
// EXPORT TO BULK UPLOAD
// ============================================================================

document.getElementById('exportResultsToBulk').addEventListener('click', async function (event) {
    event.preventDefault();

    const { domain } = await chrome.storage.local.get('domain');
    const { productList: products } = await chrome.storage.local.get('productList');

    if (!products || products.length === 0) {
        console.warn('No products to export.');
        return;
    }

    console.log('Product List: ', products);

    const amazonLinks = products
        .map(product =>
            product.asin ? `https://www.amazon.${domain}/dp/${product.asin}` : null
        )
        .filter(link => link);

    console.log('Exporting links:', amazonLinks);

    chrome.runtime.sendMessage({
        type: 'openBulkUploadPage',
        amazonLinks: amazonLinks
    });
});

document.getElementById('exportResultsToProductSub').addEventListener('click', async function (event) {
    event.preventDefault();

    const { domain } = await chrome.storage.local.get('domain');
    const { productList: products } = await chrome.storage.local.get('productList');

    if (!products || products.length === 0) {
        console.warn('No products to export.');
        return;
    }

    console.log('Product List: ', products);

    const amazonLinks = products
        .map(product =>
            product.asin ? `https://www.amazon.${domain}/dp/${product.asin}` : null
        )
        .filter(link => link);

    let hasJsonData = false;

    products.forEach(product => {
        if (product.json) {
            hasJsonData = true;
            product.amazonLink = `https://www.amazon.${domain}/dp/${product.asin}`;
        }
    });

    console.log('Exporting links:', amazonLinks);

    if (hasJsonData) {
        chrome.runtime.sendMessage({
            type: 'openBulkUploadPage',
            amazonLinks: products
        });
    } else {
        chrome.runtime.sendMessage({
            type: 'openBulkUploadPage',
            amazonLinks: amazonLinks
        });
    }
});

// ============================================================================
// ADDITIONAL SETTINGS
// ============================================================================

document.getElementById('hunterThreadCount').addEventListener('change', async event => {
    const count = event.target.value;
    await chrome.storage.local.set({ hunterThreadCount: count });
});

document.getElementById('getItemsWithMaxDeliveryDays').addEventListener('change', async event => {
    const checked = event.target.checked;
    console.log('getItemsWithMaxDeliveryDays: ', checked);
    await chrome.storage.local.set({ getItemsWithMaxDeliveryDays: checked });
});

document.getElementById('maxExtendedDeliveryDays').addEventListener('change', async event => {
    const value = event.target.value;
    await chrome.storage.local.set({ maxExtendedDeliveryDays: value });
});



