const { chromium } = require('playwright');

let browser = null;
let context = null;
let page = null;

async function start() {
  if (browser) return;
  if (page) return;

  browser = await chromium.launch({
    headless: false,
    args: ['--disable-blink-features=AutomationControlled']
  });

  context = await browser.newContext({
    viewport: { width: 1280, height: 720 },
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  });

  page = await context.newPage();

  browser.on('disconnected', () => {
    browser = null;
    context = null;
    page = null;
  });
}

async function ensurePage() {
  if (!browser) {
    await start();
    return page;
  }

  if (!page || page.isClosed()) {
    page = await context.newPage();
  }

  return page;
}

async function goto(url) {
  const p = await ensurePage();
  await p.goto(url, {
    waitUntil: 'domcontentloaded',
    timeout: 30000
  });

  await p.waitForTimeout(1500);
}

async function click(selector) {
  const p = await ensurePage();
  await p.waitForSelector(selector, { state: 'visible', timeout: 10000 });
  await p.click(selector);
}

async function type(selector, text) {
  const p = await ensurePage();
  await p.waitForSelector(selector, { state: 'visible', timeout: 10000 });
  await p.fill(selector, text);
}

async function content() {
  const p = await ensurePage();
  return await p.content();
}

async function title() {
  const p = await ensurePage();
  return await p.title();
}

async function screenshot(path, fullPage = true) {
  const p = await ensurePage();
  await p.screenshot({ path, fullPage });
}

async function newTab() {
  const p = await context.newPage();
  page = p;
  return p;
}

async function close() {
  if (browser) {
    try {
      await browser.close();
    } catch (e) {
    }
    browser = null;
    context = null;
    page = null;
  }
}

module.exports = {
  start,
  goto,
  click,
  type,
  content,
  title,
  screenshot,
  close,
  newTab,
  ensurePage,

  get page() {
    return page;
  },

  get browser() {
    return browser;
  },

  get context() {
    return context;
  }
};
