const puppeteer = require('puppeteer');
const {
    generateRandomUA,
    wait,
    autoScroll
} = require('../utils/browserUtils');
const {
    normalizeURL
} = require('../utils/urlUtils');
const proxyChain = require('proxy-chain');
const {
    getProxy,
    updateProxyUsage,
    resetProxyStatus
} = require('../proxy/database');

const clickLogoContainer = async (page) => {
    try {
        
        await page.waitForSelector('.login-button', { visible: true, timeout: 5000 });
        console.log('Elemen login-button ditemukan di halaman utama.');
    } catch (error) {
        console.log('Elemen login-button tidak ditemukan langsung di halaman utama.');
    }


    const iframeElement = await page.$('iframe');
    if (iframeElement) {
        console.log('Menemukan iframe, masuk ke dalamnya...');
        const frame = await iframeElement.contentFrame();
        try {
            await frame.waitForSelector('.login-button', { visible: true, timeout: 5000 });
            console.log('Elemen login-button ditemukan di dalam iframe.');
            await frame.click('.login-button');
            console.log('OTW MASUK.');
            return;
        } catch (error) {
            console.log('Elemen login-button tidak ditemukan di dalam iframe.');
        }
    }

  
    const shadowHost = await page.$('shadow-host-selector');
    if (shadowHost) {
        console.log('Menemukan shadow DOM, akses shadow root...');
        const shadowRoot = await shadowHost.evaluateHandle(el => el.shadowRoot);
        try {
            const logoContainer = await shadowRoot.$('.login-button');
            await logoContainer.click();
            console.log('Elemen login-button ditemukan dan diklik di dalam shadow DOM.');
            return;
        } catch (error) {
            console.log('Elemen login-button tidak ditemukan di dalam shadow DOM.');
        }
    }

 
    console.log('Menunggu elemen di halaman utama...');
    await page.evaluate(() => {
        const element = document.querySelector('.login-button');
        if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });

    await wait(1000);  

    try {
        await page.click('.login-button');
        console.log('Elemen login-button berhasil diklik.');
    } catch (error) {
        console.log('Gagal mengklik login-button.');
    }
};

const searchAndVisitTarget = async (keyword, targetURL) => {
    while (true) {
        const selectedProxy = await getProxy();

        if (!selectedProxy) {
            console.log('Tidak ada proxy yang tersedia. Menghentikan proses...');
            process.exit(0);
        }

        let proxyChainUrl;
        let proxyUrl;
        if (selectedProxy.proxyAddress.startsWith('socks5://') || selectedProxy.proxyAddress.startsWith('socks4://')) {
            proxyChainUrl = selectedProxy.proxyAddress;
        } else if (selectedProxy.proxyAuth) {
            proxyUrl = `http://${selectedProxy.proxyAuth}@${selectedProxy.proxyAddress}`;
            proxyChainUrl = await proxyChain.anonymizeProxy(proxyUrl);
        } else {
            proxyUrl = `http://${selectedProxy.proxyAddress}`;
            proxyChainUrl = await proxyChain.anonymizeProxy(proxyUrl)
        }

        const launchOptions = {
            headless: false,
            slowMo: 50,
            args: [`--proxy-server=${proxyChainUrl}`]
        };

        console.log(`Menggunakan proxy: ${proxyUrl}`);
        const browser = await puppeteer.launch(launchOptions);
        try {
            const page = await browser.newPage();
            const randomUserAgent = generateRandomUA();
            await page.setUserAgent(randomUserAgent);
            await page.setViewport({
                width: 375,
                height: 667
            });

            let foundMatch = false;

            const searchForTarget = async (targetURL1, targetURL2) => {
                console.log(`Mencari: ${targetURL1} & ${targetURL2}`);

                await page.goto('https://www.google.com', {
                    waitUntil: 'networkidle2',
                    timeout: 60000
                });
                await page.waitForSelector('textarea[name="q"]', {
                    visible: true,
                    timeout: 60000
                });
                await page.type('textarea[name="q"]', keyword, {
                    delay: 10
                });
                await page.keyboard.press('Enter');

                while (true) {
                    await page.waitForSelector('.MBeuO', {
                        visible: true,
                        timeout: 60000
                    });
                    await autoScroll(page);
                    await wait(3000);

                    const ignoredResultsElement = await page.$('div.card-section p#ofr');
                    if (ignoredResultsElement) {
                        console.log('Ditemukan pesan hasil yang diabaikan, klik link untuk melihat hasilnya...');
                        const includeLink = await page.$('div.card-section p#ofr a');
                        if (includeLink) {
                            await includeLink.click();
                            await wait(3000);
                            continue;
                        }
                    } else {
                        console.log('Tidak ditemukan pesan hasil yang diabaikan.');
                    }

                    const results = await page.$$('a.cz3goc');
                    for (let result of results) {
                        const a = await page.evaluate(el => el.href, result);
                        const normalizedHref = normalizeURL(a);
                        if (normalizedHref === targetURL1 || normalizedHref === targetURL2) {
                            console.log('Link cocok dengan TARGET_URL. Mengklik link...');
                            await result.click();
                            foundMatch = true;
                            break;
                        }
                    }

                    if (foundMatch) break;

                    const moreResultsButton = await page.$('a.T7sFge.sW9g3e.VknLRd.CqmPRe');
                    if (moreResultsButton) {
                        console.log('Mengklik tombol "More Results"...');
                        await moreResultsButton.click();
                        await wait(3000);
                    } else {
                        console.log('Tidak ada tombol "More Results" yang ditemukan. Menghentikan pencarian.');
                        break;
                    }
                }
            };

            let targetURL1 = normalizeURL(`https://www.${targetURL.replace(/^(https?:\/\/)?(www\.)?/, '')}`);
            let targetURL2 = normalizeURL(`https://${targetURL.replace(/^(https?:\/\/)?/, '')}`);

            await searchForTarget(targetURL1, targetURL2);

            const status = foundMatch ? 'success' : 'failed';

       
            updateProxyUsage(selectedProxy.id, status);

            if (!foundMatch) {
                console.log('Mencoba lagi dengan "http"');
                targetURL1 = targetURL1.replace('https://', 'http://');
                targetURL2 = targetURL2.replace('https://', 'http://');
                await searchForTarget(targetURL1, targetURL2);
            }

            console.log('Menunggu halaman sepenuhnya dimuat...');
            await page.waitForSelector('body', { visible: true, timeout: 60000 });

         
            console.log('Melakukan scroll perlahan-lahan hingga ke bawah dan kembali ke atas...');

          
            for (let i = 0; i < 10; i++) {
            
                await page.mouse.wheel({ deltaY: 300 }); 
                await wait(1000); 
            }
            
            
            await wait(2000);  
            
            console.log('Scroll selesai ke bawah, sekarang scroll ke atas...');
            
          
            for (let i = 0; i < 10; i++) {
              
                await page.mouse.wheel({ deltaY: -400 });  
                await wait(1000); 
            }
            
         
            await wait(2000); 
            

           
            console.log('Menunggu selama 20 detik...');
            await wait(20000); // Tunggu 20 detik

      
            await clickLogoContainer(page);

            await wait(40000);

        } catch (err) {
            console.error(err);
            updateProxyUsage(selectedProxy.id, 'failed');
        } finally {
            if (browser) {
                resetProxyStatus(selectedProxy.id);
                console.log('Menutup browser...');
                await browser.close();
                console.log('Browser berhasil ditutup.');
            }
        }
    }
};

module.exports = {
    searchAndVisitTarget
};
