
var accumulatedData = [];

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    const activeTab = tabs[0];
    const activeTabId = activeTab.id;
    
    //console.log("pages_scraped after reset:", localStorage.getItem('pages_scraped'));

  
    chrome.storage.local.set({ accumulatedData: [] }, () => {
        if (chrome.runtime.lastError) {
           // console.error("Error resetting data:", chrome.runtime.lastError);
        } else {
          //  console.log("accumulatedData reset in storage.");
        }
        console.log("storage set callback finished");
    });

    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0) {
            console.log("Tabs found, sending message");
            chrome.tabs.sendMessage(tabs[0].id, { action: 'resetStat' }, (response) => {
                if (chrome.runtime.lastError) {
                   // console.error("Error sending message:", chrome.runtime.lastError);
                } else {
                   // console.log("Message sent, response:", response);
                }
            });
        } else {
            console.log("No active tabs found.");
        }
    });
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0) {
            //console.log("Tabs found, sending message");
            chrome.tabs.sendMessage(tabs[0].id, { action: 'resetAccumulatedData' }, (response) => {
                if (chrome.runtime.lastError) {
                   // console.error("Error sending message:", chrome.runtime.lastError);
                } else {
                  //  console.log("Message sent, response:", response);
                }
            });
        } else {
            //console.log("No active tabs found.");
        }
    });
    

    // Inject a content script to scrape tables from the page
    chrome.scripting.executeScript(
        {
            target: { tabId: activeTabId },
            func: async () => { // Make the func an async function
                // Helper function to wait for an element
                function waitForElement(selector, timeout = 5000) {
                    return new Promise((resolve, reject) => {
                        const startTime = Date.now();
                        const interval = setInterval(() => {
                            const element = document.querySelector(selector);
                            if (element) {
                                clearInterval(interval);
                                resolve(element);
                            } else if (Date.now() - startTime > timeout) {
                                clearInterval(interval);
                                reject(new Error(`Element with selector "${selector}" not found within ${timeout}ms.`));
                            }
                        }, 100);
                    });
                }
    
                try {
                    // Wait for the Zillow listing elements
                    await waitForElement('#grid-search-results .photo-cards.photo-cards_extra-attribution > li');
    
                    const tables = document.querySelectorAll('#grid-search-results .photo-cards.photo-cards_extra-attribution > li');
                    if (tables.length === 0) {
                        console.log("No tables found after waiting for Zillow.");
                        return null;
                    }
    
                    const scrapedListings = [];
    
                    tables.forEach((li) => { // Iterate over each <li> representing a listing
                        const listingData = {};
    
                        const priceElem = li.querySelector('[data-test="property-card-price"]');
                        listingData.price = priceElem ? priceElem.innerText.trim() : '';
    
                        const propertyUrlElem = li.querySelector('[data-test="property-card-link"]');
                        listingData.property_url = propertyUrlElem ? propertyUrlElem.href.trim() : '';
    
                        const addressElem = li.querySelector('[data-test="property-card-link"] address');
                        listingData.address = addressElem ? addressElem.innerText.trim() : '';
    
                        const pics = li.querySelectorAll('picture source');
                        const imageUrls = [];
                        pics.forEach((pic) => {
                            if (pic.srcset) {
                                const urls = pic.srcset.split(',').map(url => url.trim().split(' ')[0]);
                                imageUrls.push(...urls);
                            }
                        });
                        listingData.images = imageUrls;
    
                        const propertyByElem = li.querySelector('.StyledPropertyCardDataArea-c11n-8-109-3__sc-10i1r6-0.tCgTM');
                        listingData.property_by = propertyByElem ? propertyByElem.innerText.trim() : '';
    
                        scrapedListings.push(listingData);
                    });
    
                    console.log("Scraped Zillow Listings:", scrapedListings);
                    return scrapedListings;
                } catch (error) {
                    console.error("Error during Zillow scraping:", error);
                    return null;
                }
            },
        },
        (results) => {
            if (!results || !results[0] || !results[0].result || results[0].result.length === 0) {
                alert("No Zillow listings found on this page or an error occurred during scraping.");
                return;
            }
    
            const scrapedData = results[0].result;
            let tableHTML = "";
    
            // Define headers for the Zillow-specific data
            const heading = ['Price', 'Property URL', 'Address', 'Images', 'Property By'];
    
            tableHTML += `<table border="1" style="width:100%; border-collapse: collapse;">`;
            tableHTML += `<tr>${heading.map(header => `<th style="background:#4682B4; color:white; padding:5px;">${header}</th>`).join("")}</tr>`;
    
            scrapedData.forEach((listing) => {
                tableHTML += `<tr>`;
                tableHTML += `<td style="padding:5px;">${listing.price}</td>`;
                tableHTML += `<td style="padding:5px;"><a href="${listing.property_url}" target="_blank">${listing.property_url}</a></td>`;
                tableHTML += `<td style="padding:5px;">${listing.address}</td>`;
                tableHTML += `<td style="padding:5px;">${listing.images.join(', ')}</td>`; // Join images for display
                tableHTML += `<td style="padding:5px;">${listing.property_by}</td>`;
                tableHTML += `</tr>`;
            });
            tableHTML += `</table><br>`;
    
            localStorage.setItem('tableData', tableHTML);
            localStorage.setItem('tabId', activeTabId);
            localStorage.setItem('pages_scraped', (parseInt(localStorage.getItem('pages_scraped') || '0') + 1));
            localStorage.setItem('rows_collected', scrapedData.length); // Assuming each object is a row
            localStorage.setItem('rows_from_last_page', scrapedData.length);
    
            let accumulatedData = [];
            chrome.storage.local.get(['accumulatedData'], (result) => {
                if (result.accumulatedData) {
                    accumulatedData = result.accumulatedData;
                }
    
                // Transform the scraped Zillow data into a flat array structure for accumulation
                const newRowsToAccumulate = scrapedData.map(listing => [
                    listing.price,
                    listing.property_url,
                    listing.address,
                    listing.images.join(', '), // Flatten images for accumulation if needed
                    listing.property_by
                ]);
    
                sendDataToPopup(newRowsToAccumulate);
            });
    
            function sendDataToPopup(data) {
                if (accumulatedData.length === 0) {
                    accumulatedData = data;
                } else {
                    accumulatedData = [...accumulatedData, ...data]; // Simple concatenation for now
                }
    
                console.log("Accumulated Data:", accumulatedData);
    
                chrome.storage.local.set({ accumulatedData: accumulatedData }, () => {
                    // You can add error handling here if needed
                    if (chrome.runtime.lastError) {
                        console.error("Error saving accumulated data:", chrome.runtime.lastError);
                    }
                });
            }
    
            // Open the popup if it's not already open or refresh its content
            chrome.windows.create({
                url: chrome.runtime.getURL('popup/popup_content.html'),
                type: 'popup',
                width: 800,
                height: 600
            });
        }
    );
});
