// Options page JS — Texter Captcha Solver Analytics Dashboard
(function () {
  'use strict';

  // Dynamic engine config (loaded from server via background)
  let ENGINE_NAMES = {};
  let ENGINE_ICONS = {};
  let ENGINE_ICON_COLORS = {};

  /** Load engine config from background */
  function loadEngineConfig(callback) {
    chrome.runtime.sendMessage({ action: 'GET_SOLVER_CONFIG' }, (response) => {
      if (response && response.config && response.config.engines) {
        response.config.engines.forEach(e => {
          ENGINE_NAMES[e.key] = e.name;
          ENGINE_ICONS[e.key] = e.icon || e.key.charAt(0).toUpperCase();
          ENGINE_ICON_COLORS[e.key] = e.iconColor || '#7c6aff';
        });
      }
      if (callback) callback();
    });
  }

  // DOM refs
  const statTotal = document.getElementById('statTotal');
  const statSuccess = document.getElementById('statSuccess');
  const statFailed = document.getElementById('statFailed');
  const statRate = document.getElementById('statRate');
  const statAvgTime = document.getElementById('statAvgTime');
  const statAvgConf = document.getElementById('statAvgConf');
  const statTimeSaved = document.getElementById('statTimeSaved');
  const engineCards = document.getElementById('engineCards');
  const siteTableBody = document.getElementById('siteTableBody');
  const emptySiteTable = document.getElementById('emptySiteTable');
  const activityList = document.getElementById('activityList');
  const emptyActivity = document.getElementById('emptyActivity');

  let allStats = [];

  // ── Load Stats ──
  function loadStats() {
    chrome.runtime.sendMessage({ action: 'GET_SOLVE_STATS' }, (response) => {
      allStats = (response && response.stats) || [];
      renderDashboard(allStats);
    });
  }

  // ── Render Dashboard ──
  function renderDashboard(stats) {
    // Overview stats
    const total = stats.length;
    const successes = stats.filter(s => s.success);
    const failures = stats.filter(s => !s.success);
    const rate = total > 0 ? ((successes.length / total) * 100) : 0;
    const avgTime = successes.length > 0
      ? Math.round(successes.reduce((a, s) => a + (s.solveTimeMs || 0), 0) / successes.length)
      : 0;
    const avgConf = successes.length > 0
      ? ((successes.reduce((a, s) => a + (s.confidence || 0), 0) / successes.length) * 100)
      : 0;

    statTotal.textContent = total;
    statSuccess.textContent = successes.length;
    statFailed.textContent = failures.length;
    statRate.textContent = rate.toFixed(1) + '%';
    statAvgTime.textContent = avgTime + 'ms';
    statAvgConf.textContent = avgConf.toFixed(1) + '%';

    // Time saved: assume 20s manual effort per captcha, subtract actual solve time
    const MANUAL_TIME_MS = 20000;
    const totalSavedMs = successes.reduce((a, s) => a + Math.max(0, MANUAL_TIME_MS - (s.solveTimeMs || 0)), 0);
    statTimeSaved.textContent = formatDuration(totalSavedMs);

    // Engine breakdown
    renderEngineBreakdown(stats);

    // Site table
    renderSiteTable(stats);

    // Recent activity
    renderActivity(stats);
  }

  // ── Engine Breakdown (dynamic) ──
  function renderEngineBreakdown(stats) {
    engineCards.innerHTML = '';

    const engines = {};
    stats.forEach(s => {
      const e = s.engine || 'unknown';
      if (!engines[e]) engines[e] = { total: 0, success: 0, failed: 0, totalTime: 0, successTime: 0 };
      engines[e].total++;
      if (s.success) {
        engines[e].success++;
        engines[e].successTime += s.solveTimeMs || 0;
      } else {
        engines[e].failed++;
      }
      engines[e].totalTime += s.solveTimeMs || 0;
    });

    // Add known engines from config that have no stats yet
    Object.keys(ENGINE_NAMES).forEach(key => {
      if (!engines[key]) engines[key] = { total: 0, success: 0, failed: 0, totalTime: 0, successTime: 0 };
    });

    Object.keys(engines).forEach(key => {
      const e = engines[key];
      const rate = e.total > 0 ? ((e.success / e.total) * 100).toFixed(1) : '0.0';
      const avgTime = e.success > 0 ? Math.round(e.successTime / e.success) : 0;

      const letter = ENGINE_ICONS[key] || key.charAt(0).toUpperCase();
      const iconColor = ENGINE_ICON_COLORS[key] || '#7c6aff';

      const card = document.createElement('div');
      card.className = 'engine-card';
      card.innerHTML = `
        <div class="engine-card-header">
          <span class="engine-badge" style="background:${esc(iconColor)};color:#fff">${esc(letter)}</span>
          <span class="engine-name">${esc(ENGINE_NAMES[key] || key)}</span>
        </div>
        <div class="engine-stats">
          <div class="engine-stat">
            <span class="engine-stat-label">Total</span>
            <span class="engine-stat-value accent">${e.total}</span>
          </div>
          <div class="engine-stat">
            <span class="engine-stat-label">Success</span>
            <span class="engine-stat-value success">${e.success}</span>
          </div>
          <div class="engine-stat">
            <span class="engine-stat-label">Failed</span>
            <span class="engine-stat-value danger">${e.failed}</span>
          </div>
          <div class="engine-stat">
            <span class="engine-stat-label">Avg Time</span>
            <span class="engine-stat-value">${avgTime}ms</span>
          </div>
        </div>
        <div class="progress-bar">
          <div class="progress-fill" style="width: ${rate}%"></div>
        </div>
      `;
      engineCards.appendChild(card);
    });
  }

  // ── Site Table ──
  function renderSiteTable(stats) {
    siteTableBody.innerHTML = '';

    const sites = {};
    stats.forEach(s => {
      const host = s.hostname || 'unknown';
      const engine = s.engine || 'unknown';
      const key = host + '|' + engine;
      if (!sites[key]) sites[key] = { hostname: host, engine: engine, total: 0, success: 0, failed: 0, totalTime: 0 };
      sites[key].total++;
      if (s.success) {
        sites[key].success++;
      } else {
        sites[key].failed++;
      }
      sites[key].totalTime += s.solveTimeMs || 0;
    });

    const siteList = Object.values(sites).sort((a, b) => b.total - a.total);

    if (siteList.length === 0) {
      emptySiteTable.style.display = 'block';
      document.getElementById('siteTable').style.display = 'none';
      return;
    }

    emptySiteTable.style.display = 'none';
    document.getElementById('siteTable').style.display = 'table';

    siteList.forEach(s => {
      const rate = s.total > 0 ? ((s.success / s.total) * 100).toFixed(1) + '%' : '—';
      const avgTime = s.total > 0 ? Math.round(s.totalTime / s.total) + 'ms' : '—';
      const engineName = ENGINE_NAMES[s.engine] || s.engine;

      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td class="hostname">${esc(s.hostname)}</td>
        <td>${esc(engineName)}</td>
        <td>${s.total}</td>
        <td class="success-val">${s.success}</td>
        <td class="fail-val">${s.failed}</td>
        <td>${rate}</td>
        <td>${avgTime}</td>
      `;
      siteTableBody.appendChild(tr);
    });
  }

  // ── Recent Activity ──
  function renderActivity(stats) {
    // Remove old items
    activityList.querySelectorAll('.activity-item').forEach(el => el.remove());

    // Show last 10, newest first
    const recent = stats.slice(-10).reverse();

    if (recent.length === 0) {
      emptyActivity.style.display = 'block';
      return;
    }

    emptyActivity.style.display = 'none';

    recent.forEach(s => {
      const item = document.createElement('div');
      item.className = 'activity-item';

      const dotClass = s.success ? 'success' : 'fail';
      const engineName = ENGINE_NAMES[s.engine] || s.engine;
      const time = s.timestamp ? timeAgo(s.timestamp) : '—';
      const conf = s.success ? ((s.confidence || 0) * 100).toFixed(1) + '%' : '—';
      const solvedText = s.success
        ? `Solved <span class="solved-val">"${esc(s.text)}"</span>`
        : `Failed${s.error ? ': ' + esc(s.error) : ''}`;

      item.innerHTML = `
        <span class="activity-dot ${dotClass}"></span>
        <div class="activity-body">
          <div class="activity-text"><strong>${esc(engineName)}</strong> — ${solvedText}</div>
          <div class="activity-meta">
            <span>${esc(s.hostname || 'unknown')}</span>
            <span>${s.solveTimeMs || 0}ms</span>
            <span>Conf: ${conf}</span>
          </div>
        </div>
        <span class="activity-time">${time}</span>
      `;
      activityList.appendChild(item);
    });
  }

  // ── Helpers ──
  function esc(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  function timeAgo(timestamp) {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);
    if (seconds < 5) return 'just now';
    if (seconds < 60) return seconds + 's ago';
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return minutes + 'm ago';
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return hours + 'h ago';
    const days = Math.floor(hours / 24);
    return days + 'd ago';
  }

  function formatDuration(ms) {
    const totalSec = Math.round(ms / 1000);
    if (totalSec < 60) return totalSec + 's';
    const min = Math.floor(totalSec / 60);
    const sec = totalSec % 60;
    if (min < 60) return min + 'm ' + sec + 's';
    const hr = Math.floor(min / 60);
    const rm = min % 60;
    return hr + 'h ' + rm + 'm';
  }

  // ── Init ──
  loadEngineConfig(() => {
    loadStats();
  });

  // Auto-refresh every 5s
  setInterval(loadStats, 5000);
})();
