import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import AnonymizeUAPlugin from 'puppeteer-extra-plugin-anonymize-ua';
import AdblockerPlugin from 'puppeteer-extra-plugin-adblocker';
import fs from 'fs';

puppeteer.use(StealthPlugin());
puppeteer.use(AnonymizeUAPlugin());
puppeteer.use(
  AdblockerPlugin({
    blockTrackers: true,
  }
));

// Toggle browser for platform
const browser_path = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
//const browser_path = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';

const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    ignoreDefaultArgs: ["--disable-extensions"],
    dumpio: true,
    args: ["--start-maximized", "--no-sandbox", "--disable-setuid-sandbox"],
    executablePath: browser_path,
  });

const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto('https://www.bestbuy.com/identity/global/signin');

// // Wait for the login form to be available and fill it in
// await page.waitForSelector('#fld-e');

// // Wait for the "Sign in with Google" button to be available and click it
// await page.waitForSelector('button[aria-labelledby="button-label"]');
// await page.click('button[aria-labelledby="button-label"]');

// // Wait for navigation after clicking the button
// await page.waitForNavigation();


// // Uncomment and replace with your credentials
// // await page.type('#fld-e', 'your-email@example.com'); // Replace with your email
// // await page.type('#fld-p1', 'your-password'); // Replace with your password
// // await page.click('.cia-form__controls__submit');

// Wait for navigation after login -- you have 1 minute!
await new Promise(resolve => setTimeout(resolve, 60000));

// Save cookies
const cookies = await page.cookies();
fs.writeFileSync('./cookies.json', JSON.stringify(cookies, null, 2));

// Save local storage data
const localStorageData = await page.evaluate(() => {
let json = {};
for (let i = 0; i < localStorage.length; i++) {
    let key = localStorage.key(i);
    json[key] = localStorage.getItem(key);
}
return json;
});
fs.writeFileSync('./localStorage.json', JSON.stringify(localStorageData, null, 2));

console.log('Login session saved.');
await browser.close();
