// OLX Parser — Popup Script

let results = [];
let isRunning = false;
let selectedCount = 100;
let targetTotal = 0;
let timerInterval = null;
let timerStart = 0;
let trialMode = false;
let trialUsed = 0;
const TRIAL_LIMIT = 100;
let selectedSpeed = 'normal';

const SPEED_CONFIG = {
  safe: {
    label: 'Безпечний',
    delay: '20–45с',
    per100: '~3–4 год',
    risk: 'Мінімальний',
    riskClass: 'si-risk-low',
    infoClass: 'safe',
  },
  normal: {
    label: 'Звичайний',
    delay: '8–20с',
    per100: '~40–80 хв',
    risk: 'Середній',
    riskClass: 'si-risk-mid',
    infoClass: 'normal',
  },
  fast: {
    label: 'Швидкий',
    delay: '3–6с',
    per100: '~10–15 хв',
    risk: '⚠ Блокування',
    riskClass: 'si-risk-high',
    infoClass: 'fast',
  },
};

// ─── Session helpers (read-only in popup — background owns the session) ───
async function clearSession() {
  await chrome.storage.local.remove('parseSession');
}

async function loadSession() {
  const data = await chrome.storage.local.get('parseSession');
  return data.parseSession || null;
}

const $ = id => document.getElementById(id);
const ALL = Infinity;
const VALIDATE_URL = 'https://www.zennotemplates.com/api/extensions/validate';

// ─── License System ───────────────────────────────────────────────

async function getOrCreateInstanceId() {
  const data = await chrome.storage.local.get('instanceId');
  if (data.instanceId) return data.instanceId;
  const id = crypto.randomUUID();
  await chrome.storage.local.set({ instanceId: id });
  return id;
}

async function validateLicense(key) {
  const instanceId = await getOrCreateInstanceId();
  try {
    const res = await fetch(`${VALIDATE_URL}?key=${encodeURIComponent(key)}&instanceId=${encodeURIComponent(instanceId)}`);
    return await res.json(); // { valid, message, owner?, product?, expiresAt? }
  } catch (_) {
    return { valid: false, message: 'Немає зʼєднання з сервером ліцензій' };
  }
}

async function initLicense() {
  const data = await chrome.storage.local.get(['licenseKey', 'licenseOwner', 'trialUsed']);

  // Trial mode: no key yet
  if (!data.licenseKey) {
    trialMode = true;
    trialUsed = data.trialUsed || 0;
    if (trialUsed >= TRIAL_LIMIT) {
      showLicenseGate('', true); // trial exhausted
      return;
    }
    showMainApp('');
    showTrialBadge();
    await setupMainApp();
    return;
  }

  // Re-validate saved key on each open
  const result = await validateLicense(data.licenseKey);
  if (result.valid) {
    trialMode = false;
    showMainApp(data.licenseOwner || result.owner || '');
    await setupMainApp();
  } else {
    showLicenseGate(result.message);
  }
}

function showTrialBadge() {
  const badge = $('trialBadge');
  if (badge) {
    badge.classList.remove('hidden');
    $('trialUsedCount').textContent = trialUsed;
  }
}

function updateTrialBadge() {
  $('trialUsedCount').textContent = trialUsed;
}

function showLicenseGate(errorMsg = '', trialExhausted = false) {
  $('licenseGate').classList.remove('hidden');
  $('mainApp').classList.add('hidden');
  if (trialExhausted) {
    $('licenseSubText').innerHTML = `✅ Ви зібрали <strong>${TRIAL_LIMIT} безкоштовних номерів</strong>. Активуйте ліцензію для необмеженого доступу на <strong>zennotemplates.com</strong>`;
    $('licenseError').classList.add('hidden');
  } else if (errorMsg) {
    $('licenseError').textContent = errorMsg;
    $('licenseError').classList.remove('hidden');
  }
}

function showMainApp(owner = '') {
  $('licenseGate').classList.add('hidden');
  $('mainApp').classList.remove('hidden');
  if (owner) $('licenseOwner').textContent = owner;
}

function setupLicenseGate() {
  $('activateBtn').addEventListener('click', async () => {
    const key = $('licenseKeyInput').value.trim();
    if (!key) return;

    $('activateBtn').disabled = true;
    $('activateBtn').textContent = 'Перевіряю...';
    $('licenseError').classList.add('hidden');
    $('licenseKeyInput').classList.remove('error');

    const result = await validateLicense(key);

    if (result.valid) {
      trialMode = false;
      await chrome.storage.local.set({
        licenseKey: key,
        licenseOwner: result.owner || '',
        trialUsed: 0
      });
      showMainApp(result.owner || '');
      setupMainApp();
    } else {
      $('licenseError').textContent = result.message || 'Невірний ключ';
      $('licenseError').classList.remove('hidden');
      $('licenseKeyInput').classList.add('error');
      $('activateBtn').disabled = false;
      $('activateBtn').textContent = 'Активувати';
    }
  });

  // Allow Enter key to submit
  $('licenseKeyInput').addEventListener('keydown', e => {
    if (e.key === 'Enter') $('activateBtn').click();
  });
}

function setupDeactivate() {
  $('deactivateBtn').addEventListener('click', async () => {
    if (!confirm('Деактивувати ліцензію на цьому пристрої?')) return;
    await chrome.storage.local.remove(['licenseKey', 'licenseOwner', 'instanceId']);
    showLicenseGate();
  });

  // Clear done URLs history
  async function refreshDoneCount() {
    const resp = await chrome.runtime.sendMessage({ type: 'GET_DONE_COUNT' });
    $('doneCount').textContent = resp?.count ?? 0;
  }
  refreshDoneCount();

  $('clearHistoryBtn').addEventListener('click', async () => {
    const resp = await chrome.runtime.sendMessage({ type: 'GET_DONE_COUNT' });
    const count = resp?.count ?? 0;
    if (count === 0) { alert('Історія порожня'); return; }
    if (!confirm(`Очистити історію ${count} оброблених оголошень?\nПісля цього вони будуть парситися знову.`)) return;
    await chrome.runtime.sendMessage({ type: 'CLEAR_DONE_URLS' });
    $('doneCount').textContent = '0';
  });
}

// ─── Init ─────────────────────────────────────────────────────────

document.addEventListener('DOMContentLoaded', async () => {
  setupLicenseGate();
  setupDeactivate();
  await initLicense();
});

async function setupMainApp() {
  setupCountButtons();
  setupSpeedButtons();
  setupExportButtons();
  setupStartButton();
  setupClearButton();
  setupTabs();
  await checkCurrentPage();
}

function setupSpeedButtons() {
  updateSpeedInfo(selectedSpeed);
  document.querySelectorAll('.speed-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      if (isRunning) return;
      selectedSpeed = btn.dataset.speed;
      document.querySelectorAll('.speed-btn').forEach(b => {
        b.classList.remove('active', 'safe', 'normal', 'fast');
      });
      btn.classList.add('active', selectedSpeed);
      updateSpeedInfo(selectedSpeed);
    });
  });
  // Set initial active class on default button
  const defaultBtn = document.querySelector(`.speed-btn[data-speed="${selectedSpeed}"]`);
  if (defaultBtn) defaultBtn.classList.add('active', selectedSpeed);
}

function updateSpeedInfo(speed) {
  const cfg = SPEED_CONFIG[speed];
  const el = $('speedInfo');
  if (!el || !cfg) return;
  el.className = `speed-info ${cfg.infoClass}`;
  el.innerHTML = `
    <span class="si-label">Пауза</span>
    <span class="si-label">100 номерів</span>
    <span class="si-label">Ризик</span>
    <span class="si-val">${cfg.delay}</span>
    <span class="si-val">${cfg.per100}</span>
    <span class="${cfg.riskClass}">${cfg.risk}</span>
  `;
}

// --- Count selector ---
function setupCountButtons() {
  document.querySelectorAll('.count-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      if (isRunning) return;
      document.querySelectorAll('.count-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      selectedCount = btn.dataset.count === 'all' ? ALL : parseInt(btn.dataset.count, 10);
    });
  });
}

// --- Check current tab + restore session if parsing was running ---
async function checkCurrentPage() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) return;

    const url = tab.url || '';
    const isOlx = url.includes('olx.ua');
    const isListing = url.includes('/d/uk/obyavlenie/') || url.includes('/uk/obyavlenie/');

    if (!isOlx) {
      $('pageCategory').textContent = 'Не OLX — відкрийте olx.ua';
      $('warningBlock').classList.remove('hidden');
      $('startBtn').disabled = true;
      // Still try to restore results (user may have navigated away)
      await tryRestoreSession(false);
      return;
    }

    if (isListing) {
      $('pageCategory').textContent = 'Відкрита сторінка оголошення — перейдіть до категорії';
      $('warningBlock').classList.remove('hidden');
      $('startBtn').disabled = true;
      await tryRestoreSession(false);
      return;
    }

    const category = extractCategoryName(url);
    $('pageCategory').textContent = `📍 ${category}`;
    $('warningBlock').classList.add('hidden');
    $('startBtn').disabled = false;

    await tryRestoreSession(true);

  } catch (e) {
    $('pageCategory').textContent = 'Помилка перевірки сторінки';
  }
}

async function tryRestoreSession(canResume) {
  const session = await loadSession();
  if (!session) return;

  // Always restore collected results
  results = session.results || [];
  targetTotal = session.total || 0;
  timerStart = session.timerStarted || Date.now();

  if (results.length > 0) {
    showProgress(true);
    showResults(true);
    updateResultsTable();
    results.forEach((r, i) => appendResultRow(r, i + 1));
    updateResultsCount();
    enableExport();
    updateProgress(session.currentIndex, targetTotal);
  }

  if (results.length > 0) {
    // Always just show results — never auto-resume, user must click manually
    setStatus('done');
    setProgressText(`Відновлено: ${results.length} записів`);
    updateProgress(results.length, targetTotal || results.length);
    if (session.active && session.currentIndex < session.listings.length) {
      setStatusMsg(`Парсинг був перерваний на ${session.currentIndex} / ${session.total}. Натисніть «Почати парсинг» щоб розпочати нову сесію.`);
    }
  }
}


function extractCategoryName(url) {
  const path = url.replace(/https?:\/\/www\.olx\.ua/, '').split('?')[0].split('#')[0];

  const knownCategories = {
    '/uk/transport': 'Транспорт',
    '/uk/nedvizhimost': 'Нерухомість',
    '/d/uk/transport': 'Транспорт',
    '/d/uk/nedvizhimost': 'Нерухомість',
    '/uk/elektronika': 'Електроніка',
    '/uk/rabota': 'Робота',
    '/uk/moda-i-stil': 'Мода і стиль',
    '/uk/detskiy-mir': 'Дитячий світ',
    '/uk/dom-i-sad': 'Дім і сад',
    '/uk/biznes-i-uslug': 'Бізнес і послуги',
  };

  for (const [key, name] of Object.entries(knownCategories)) {
    if (path.startsWith(key)) return name;
  }

  const parts = path.replace(/^\/d\//, '/').replace(/^\//, '').split('/');
  const readable = parts.filter(Boolean).slice(0, 2).join(' › ');
  return readable || 'Поточна сторінка';
}

// --- Start / Stop ---
function setupStartButton() {
  $('startBtn').addEventListener('click', async () => {
    if (isRunning) {
      await stopParsing();
    } else {
      await startParsing();
    }
  });
}

async function startParsing() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) return;

  results = [];
  isRunning = true;
  targetTotal = selectedCount;

  setRunningUI(true);
  showProgress(true);
  showResults(true);
  updateResultsTable();
  clearLog();
  setStatus('running');
  startTimer();

  if (selectedCount === ALL) {
    $('progressCount').textContent = '0 / ?';
    $('progressText').textContent = 'Парсинг усіх оголошень...';
  }

  // Phase 1: collect listings via content script
  chrome.runtime.onMessage.addListener(onContentMessage);

  try {
    await chrome.tabs.sendMessage(tab.id, {
      type: 'START_PARSE',
      count: selectedCount === ALL ? 999999 : selectedCount
    });
  } catch (e) {
    try {
      await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
      await new Promise(r => setTimeout(r, 300));
      await chrome.tabs.sendMessage(tab.id, {
        type: 'START_PARSE',
        count: selectedCount === ALL ? 999999 : selectedCount
      });
    } catch (err) {
      setStatusMsg('Помилка: не вдалось запустити парсер. Оновіть сторінку OLX.');
      stopUI();
    }
  }
  // Phase 2 starts when we receive LISTINGS_READY in onContentMessage
}

function startTimer() {
  timerStart = Date.now();
  $('timerDisplay').textContent = '0:00';
  timerInterval = setInterval(() => {
    const s = Math.floor((Date.now() - timerStart) / 1000);
    $('timerDisplay').textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  }, 1000);
}

function startTimerFromSaved(savedStart) {
  timerStart = savedStart || Date.now();
  const tick = () => {
    const s = Math.floor((Date.now() - timerStart) / 1000);
    $('timerDisplay').textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  };
  tick();
  timerInterval = setInterval(tick, 1000);
}

function stopTimer() {
  clearInterval(timerInterval);
  timerInterval = null;
  const s = Math.floor((Date.now() - timerStart) / 1000);
  const formatted = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  $('timerDisplay').textContent = formatted;
  return formatted;
}

async function stopParsing() {
  isRunning = false;
  stopTimer();
  // Stop Phase 1 (content script)
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tab) {
    try { await chrome.tabs.sendMessage(tab.id, { type: 'STOP_PARSE' }); } catch (_) {}
  }
  // Stop Phase 2 (service worker)
  chrome.runtime.sendMessage({ type: 'STOP_PHASE2' }).catch(() => {});
  chrome.runtime.onMessage.removeListener(onContentMessage);
  stopUI();
  enableExport();
}

// --- Log panel ---
function logTime() {
  const d = new Date();
  return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`;
}

function appendLog(msg, level = 'info') {
  const panel = $('logPanel');
  if (!panel) return;
  const entry = document.createElement('div');
  entry.className = `log-entry ${level}`;
  entry.innerHTML = `<span class="log-time">[${logTime()}]</span><span class="log-msg">${escHtml(msg)}</span>`;
  panel.appendChild(entry);
  // auto-scroll only if log tab is active
  panel.scrollTop = panel.scrollHeight;
}

function clearLog() {
  const panel = $('logPanel');
  if (panel) panel.innerHTML = '';
}

// --- Tab switching ---
function setupTabs() {
  document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      if (!btn.dataset.tab) return; // skip copy button
      document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const tab = btn.dataset.tab;
      $('tabResults').classList.toggle('hidden', tab !== 'results');
      $('tabLog').classList.toggle('hidden', tab !== 'log');
      $('copyLogBtn').classList.toggle('hidden', tab !== 'log');
    });
  });

  $('copyLogBtn').addEventListener('click', () => {
    const panel = $('logPanel');
    if (!panel) return;
    const text = Array.from(panel.querySelectorAll('.log-entry'))
      .map(e => {
        const t = e.querySelector('.log-time')?.textContent || '';
        const m = e.querySelector('.log-msg')?.textContent || '';
        return `${t} ${m}`;
      })
      .join('\n');
    navigator.clipboard.writeText(text).then(() => {
      const btn = $('copyLogBtn');
      btn.textContent = '✅ Скопійовано';
      btn.classList.add('copied');
      setTimeout(() => {
        btn.textContent = '📋 Копіювати';
        btn.classList.remove('copied');
      }, 2000);
    }).catch(() => {});
  });
}

// --- Handle ALL runtime messages (content script Phase 1 + background Phase 2) ---
function onContentMessage(msg) {
  // Phase 1: content script
  if (msg.type === 'STATUS') {
    const text = msg.message;
    setStatusMsg(text);
    const level = text.includes('⚠️') || text.includes('❌') ? 'warn'
                : text.includes('✅') || text.includes('Готово') ? 'ok' : 'info';
    appendLog(text, level);
    return;
  }

  if (msg.type === 'LISTINGS_READY') {
    const listings = msg.listings || [];
    const total = listings.length;
    appendLog(`📋 Зібрано ${total} оголошень — відкриваю вкладки...`, 'ok');
    setStatusMsg(`Зібрано ${total} оголошень. Відкриваю вкладки...`);
    if (total === 0) { finishParsing(0); return; }

    // Hand off Phase 2 to the service worker
    let categoryUrl = 'https://www.olx.ua/';
    chrome.tabs.query({ active: true, currentWindow: true }).then(([tab]) => {
      if (tab?.url?.includes('olx.ua')) categoryUrl = tab.url;
      chrome.runtime.sendMessage({
        type: 'START_PHASE2',
        listings,
        categoryUrl,
        startIndex: 0,
        timerStart: timerStart,
        results: [],
        trialMode,
        trialUsed,
        speed: selectedSpeed
      });
    });
    return;
  }

  if (msg.type === 'ERROR') {
    setStatusMsg(`⚠️ ${msg.message}`);
    setStatus('error');
    appendLog(`❌ ${msg.message}`, 'error');
    return;
  }

  // Phase 2: messages from background service worker
  if (msg.type === 'PHASE2_STATUS') {
    setStatusMsg(msg.message);
    return;
  }

  if (msg.type === 'PHASE2_LOG') {
    appendLog(msg.text, msg.level || 'info');
    return;
  }

  if (msg.type === 'PHASE2_RESULT') {
    const { result, num, total, trialUsed: tu } = msg;
    results.push(result);
    if (tu !== undefined) {
      trialUsed = tu;
      updateTrialBadge();
    }
    updateProgress(num, total);
    appendResultRow(result, results.length);
    updateResultsCount();
    enableExport();
    return;
  }

  if (msg.type === 'PHASE2_DONE') {
    finishParsing(msg.count, msg.elapsed);
    return;
  }

  if (msg.type === 'PHASE2_STOPPED') {
    stopUI();
    setStatus('idle');
    enableExport();
    return;
  }

  if (msg.type === 'PHASE2_TRIAL_EXHAUSTED') {
    isRunning = false;
    stopTimer();
    stopUI();
    showLicenseGate('', true);
    return;
  }
}

function finishParsing(count, elapsedStr) {
  isRunning = false;
  chrome.runtime.onMessage.removeListener(onContentMessage);
  if (!elapsedStr) elapsedStr = stopTimer();
  else stopTimer();
  setProgressText(`Готово! ${count} записів за ${elapsedStr}`);
  updateProgress(count, targetTotal || count);
  stopUI();
  setStatus('done');
  enableExport();
  appendLog(`✅ Парсинг завершено: ${count} записів за ${elapsedStr}`, 'ok');
  playDoneSound();
  // Refresh done count badge
  chrome.runtime.sendMessage({ type: 'GET_DONE_COUNT' }).then(r => {
    if ($('doneCount')) $('doneCount').textContent = r?.count ?? 0;
  }).catch(() => {});
}

// --- Sound notification ---
function playDoneSound() {
  try {
    const ctx = new (window.AudioContext || window.webkitAudioContext)();

    const notes = [523.25, 659.25, 783.99]; // C5, E5, G5 — мажорний акорд
    notes.forEach((freq, i) => {
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();

      osc.connect(gain);
      gain.connect(ctx.destination);

      osc.type = 'sine';
      osc.frequency.value = freq;

      const startTime = ctx.currentTime + i * 0.15;
      const endTime = startTime + 0.35;

      gain.gain.setValueAtTime(0, startTime);
      gain.gain.linearRampToValueAtTime(0.25, startTime + 0.02);
      gain.gain.exponentialRampToValueAtTime(0.001, endTime);

      osc.start(startTime);
      osc.stop(endTime);
    });
  } catch (_) {}
}

// --- UI helpers ---
function setRunningUI(running) {
  $('btnIcon').textContent = running ? '⏹' : '▶';
  $('btnText').textContent = running ? 'Зупинити' : 'Почати парсинг';
  $('startBtn').classList.toggle('stopping', running);
  document.querySelectorAll('.count-btn').forEach(b => b.disabled = running);
  $('exportCsvBtn').disabled = true;
  $('exportTxtBtn').disabled = true;
  $('copyPhonesBtn').disabled = true;
  $('clearBtn').disabled = true;
}

function stopUI() {
  isRunning = false;
  $('btnIcon').textContent = '▶';
  $('btnText').textContent = 'Почати парсинг';
  $('startBtn').classList.remove('stopping');
  document.querySelectorAll('.count-btn').forEach(b => b.disabled = false);
}

function enableExport() {
  if (results.length > 0) {
    $('exportCsvBtn').disabled = false;
    $('exportTxtBtn').disabled = false;
    $('copyPhonesBtn').disabled = false;
    $('clearBtn').disabled = false;
  }
}

function setStatus(state) {
  $('statusDot').className = `status-dot ${state}`;
}

function showProgress(show) {
  $('progressBlock').classList.toggle('hidden', !show);
}

function showResults(show) {
  $('resultsBlock').classList.toggle('hidden', !show);
}

function setProgressText(text) {
  $('progressText').textContent = text;
}

function setStatusMsg(msg) {
  $('statusMessage').textContent = msg;
}

function updateProgress(current, total) {
  const pct = total > 0 ? Math.round((current / total) * 100) : 0;
  $('progressBar').style.width = `${pct}%`;
  $('progressCount').textContent = `${current} / ${total}`;
  $('progressText').textContent = `Парсинг... ${pct}%`;
}

function updateResultsCount() {
  $('resultsCount').textContent = `Результати: ${results.length}`;
}

// --- Table ---
function updateResultsTable() {
  $('resultsBody').innerHTML = '';
  $('emptyState').style.display = results.length === 0 ? 'block' : 'none';
}

function appendResultRow(result, index) {
  $('emptyState').style.display = 'none';
  const tbody = $('resultsBody');
  const tr = document.createElement('tr');
  const badgeClass = result.adType === 'Бізнес' ? 'badge-business' : 'badge-private';

  tr.innerHTML = `
    <td>${index}</td>
    <td class="td-name" title="${escHtml(result.name)}">${escHtml(result.name)}</td>
    <td class="td-phone">${escHtml(result.phone)}</td>
    <td><span class="badge ${badgeClass}">${escHtml(result.adType)}</span></td>
  `;

  tbody.appendChild(tr);
  tbody.parentElement.scrollTop = tbody.parentElement.scrollHeight;
}

function escHtml(str) {
  return String(str || '').replace(/[&<>"']/g, c =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])
  );
}

// --- Clear ---
function resetSettings() {
  // Reset count to 100
  selectedCount = 100;
  document.querySelectorAll('.count-btn').forEach(b => b.classList.remove('active'));
  const defaultCount = document.querySelector('.count-btn[data-count="100"]');
  if (defaultCount) defaultCount.classList.add('active');

  // Reset speed to normal
  selectedSpeed = 'normal';
  document.querySelectorAll('.speed-btn').forEach(b => {
    b.classList.remove('active', 'safe', 'normal', 'fast');
  });
  const defaultSpeed = document.querySelector('.speed-btn[data-speed="normal"]');
  if (defaultSpeed) defaultSpeed.classList.add('active', 'normal');
  updateSpeedInfo('normal');
}

function setupClearButton() {
  $('clearBtn').addEventListener('click', async () => {
    if (isRunning) return;
    results = [];
    targetTotal = 0;
    // Stop background worker if it's still running from a previous session
    chrome.runtime.sendMessage({ type: 'STOP_PHASE2' }).catch(() => {});
    await clearSession();
    updateResultsTable();
    updateResultsCount();
    clearLog();
    $('exportCsvBtn').disabled = true;
    $('exportTxtBtn').disabled = true;
    $('copyPhonesBtn').disabled = true;
    $('clearBtn').disabled = true;
    showProgress(false);
    showResults(false);
    setStatus('idle');
    setStatusMsg('');
    resetSettings();
  });
}

// --- Export ---
function setupExportButtons() {
  $('exportCsvBtn').addEventListener('click', exportExcel);
  $('exportTxtBtn').addEventListener('click', exportTxt);
  $('copyPhonesBtn').addEventListener('click', copyPhones);
}

function exportExcel() {
  if (!results.length) return;

  const BOM = '\uFEFF';
  const header = ['№', "Ім'я", 'Телефон', 'Тип оголошення', 'URL'];
  const rows = results.map((r, i) => [i + 1, r.name, r.phone, r.adType, r.url || '']);

  const csv = [header, ...rows]
    .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(';'))
    .join('\r\n');

  const blob = new Blob([BOM + csv], { type: 'text/csv;charset=utf-8;' });
  downloadFile(blob, `olx_phones_${timestamp()}.csv`);
}

function copyPhones() {
  if (!results.length) return;
  const text = results.map((r, i) => `${i + 1}. ${r.name} | ${r.phone} | ${r.adType}`).join('\n');
  navigator.clipboard.writeText(text).then(() => {
    const btn = $('copyPhonesBtn');
    const orig = btn.textContent;
    btn.textContent = '✅ Скопійовано';
    btn.classList.add('copied');
    setTimeout(() => { btn.textContent = orig; btn.classList.remove('copied'); }, 2000);
  }).catch(() => {});
}

function exportTxt() {
  if (!results.length) return;

  const lines = results.map((r, i) => `${i + 1}. ${r.name} | ${r.phone} | ${r.adType}`);

  const header =
    `OLX Парсер — ${results.length} записів\n` +
    `Дата: ${new Date().toLocaleString('uk-UA')}\n` +
    '='.repeat(50) + '\n\n';

  const blob = new Blob([header + lines.join('\n')], { type: 'text/plain;charset=utf-8;' });
  downloadFile(blob, `olx_phones_${timestamp()}.txt`);
}

function downloadFile(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

function timestamp() {
  const d = new Date();
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}`;
}

function pad(n) { return String(n).padStart(2, '0'); }
