// OLX Parser — Content Script (Phase 1 only: collect listing URLs)
// Phase 2 (phone extraction) is done by popup.js via tab injection

if (window.__olxParserLoaded) { throw new Error('OLX Parser already loaded'); }
window.__olxParserLoaded = true;

const OLX_BASE = 'https://www.olx.ua';

let parsingState = {
  running: false,
  results: [],
  count: 0,
  target: 0
};

// --- Extract listing IDs + URLs from HTML document ---
function extractListings(doc) {
  const listings = [];
  const seen = new Set();

  const cards = doc.querySelectorAll('[data-cy="l-card"], [data-testid="l-card"]');
  cards.forEach(card => {
    const id = card.id || card.getAttribute('data-id');
    if (!id || !/^\d{6,12}$/.test(id)) return;
    if (seen.has(id)) return;
    seen.add(id);
    const link = card.querySelector('a[href*="obyavlenie"]') || card.querySelector('a[href]');
    const href = link ? (link.href || link.getAttribute('href') || '') : '';
    const url = href.startsWith('http') ? href : (href ? OLX_BASE + href : '');
    listings.push({ id, url });
  });

  if (listings.length > 0) return listings;

  // Fallback: old URL format
  const links = doc.querySelectorAll('a[href*="obyavlenie"]');
  links.forEach(link => {
    const href = link.href || link.getAttribute('href') || '';
    const fullUrl = href.startsWith('http') ? href : OLX_BASE + href;
    const numMatch = fullUrl.match(/-(\d{6,12})\.html/);
    if (numMatch) {
      const id = numMatch[1];
      if (!seen.has(id)) { seen.add(id); listings.push({ id, url: fullUrl }); }
    }
  });

  return listings;
}

// --- Get next page URL ---
function getNextPageUrl(doc, currentUrl) {
  const selectors = [
    '[data-cy="pagination-forward"]',
    'a[data-testid="pagination-forward"]',
    'a[aria-label="Наступна"]',
    'a[aria-label="Next"]',
    '.pager a:last-child',
    'li.pager-next a',
  ];
  for (const selector of selectors) {
    const el = doc.querySelector(selector);
    if (!el) continue;
    const href = el.href || el.getAttribute('href');
    if (!href) continue;
    const url = href.startsWith('http') ? href : OLX_BASE + href;
    if (url !== currentUrl) return url;
  }
  return null;
}

// --- Fetch a category page ---
async function fetchCategoryPage(url) {
  try {
    const res = await fetch(url, {
      credentials: 'include',
      headers: { 'Accept': 'text/html,application/xhtml+xml' }
    });
    if (!res.ok) return null;
    const html = await res.text();
    const doc = new DOMParser().parseFromString(html, 'text/html');
    doc.querySelectorAll('a[href]').forEach(a => {
      const href = a.getAttribute('href');
      if (href && href.startsWith('/')) a.setAttribute('href', OLX_BASE + href);
    });
    return { doc, nextUrl: getNextPageUrl(doc, url) };
  } catch (_) {
    return null;
  }
}

const sleep = ms => new Promise(r => setTimeout(r, ms));

function send(msg) {
  try { chrome.runtime.sendMessage(msg); } catch (_) {}
}

// --- Collect listings (Phase 1) ---
async function collectListings(targetCount) {
  parsingState.running = true;
  parsingState.results = [];
  parsingState.count = 0;
  parsingState.target = targetCount;

  const allListings = [];
  let currentUrl = window.location.href;
  let pageNum = 1;

  send({ type: 'STATUS', message: 'Збираю список оголошень...' });

  while (parsingState.running && allListings.length < targetCount) {
    let doc, nextUrl;

    if (pageNum === 1) {
      doc = document;
      nextUrl = getNextPageUrl(document, currentUrl);
    } else {
      send({ type: 'STATUS', message: `Завантажую сторінку ${pageNum}...` });
      const page = await fetchCategoryPage(currentUrl);
      if (!page) break;
      doc = page.doc;
      nextUrl = page.nextUrl;
    }

    const pageListings = extractListings(doc);
    for (const l of pageListings) {
      if (!allListings.find(x => x.id === l.id)) allListings.push(l);
    }

    send({ type: 'STATUS', message: `Знайдено ${allListings.length} оголошень (стор. ${pageNum})` });

    if (!nextUrl || allListings.length >= targetCount) break;
    currentUrl = nextUrl;
    pageNum++;
    await sleep(300);
  }

  const listings = allListings.slice(0, targetCount);
  send({ type: 'LISTINGS_READY', listings, total: listings.length });
}

// --- Message listener ---
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg.type === 'START_PARSE') {
    if (!parsingState.running) collectListings(msg.count);
    sendResponse({ ok: true });
    return true;
  }

  if (msg.type === 'STOP_PARSE') {
    parsingState.running = false;
    sendResponse({ ok: true });
    return true;
  }

  if (msg.type === 'PING') {
    sendResponse({
      ok: true,
      url: window.location.href,
      isCategory: !window.location.href.includes('/obyavlenie/')
    });
    return true;
  }

  if (msg.type === 'GET_STATE') {
    sendResponse({
      ok: true,
      running: parsingState.running,
      results: parsingState.results,
      count: parsingState.count,
      target: parsingState.target
    });
    return true;
  }

  return true;
});
