// Popup Script for Berean Theological Auditor

document.addEventListener('DOMContentLoaded', () => {
  // Load settings
  loadSettings();
  loadHistory();

  // Event listeners
  document.getElementById('openSidebar').addEventListener('click', openSidebar);
  document.getElementById('viewSettings').addEventListener('click', () => {
    chrome.tabs.create({ url: 'settings.html' });
  });
  document.getElementById('viewCharter').addEventListener('click', viewCharter);
  document.getElementById('autoAuditToggle').addEventListener('click', toggleAutoAudit);
});

function loadSettings() {
  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    const toggle = document.getElementById('autoAuditToggle');
    
    if (settings.autoAuditEnabled) {
      toggle.classList.add('active');
    }
  });
}

function loadHistory() {
  chrome.storage.local.get('auditHistory', (data) => {
    const history = data.auditHistory || [];
    const container = document.getElementById('historyContainer');

    if (history.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <div class="empty-state-icon">📋</div>
          <div class="empty-state-text">No reviews yet</div>
        </div>
      `;
      return;
    }

    container.innerHTML = history.slice(0, 5).map((item) => `
      <div class="history-item" data-id="${item.id}">
        <div class="history-item-text">${escapeHtml(item.text)}</div>
        <div class="history-item-time">${formatTime(item.timestamp)}</div>
      </div>
    `).join('');

    // Add click handlers
    container.querySelectorAll('.history-item').forEach((item) => {
      item.addEventListener('click', () => {
        const id = item.getAttribute('data-id');
        viewAuditDetail(parseInt(id));
      });
    });
  });
}

function toggleAutoAudit() {
  const toggle = document.getElementById('autoAuditToggle');
  const isActive = toggle.classList.contains('active');

  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    settings.autoAuditEnabled = !isActive;

    chrome.storage.local.set({ settings }, () => {
      if (!isActive) {
        toggle.classList.add('active');
      } else {
        toggle.classList.remove('active');
      }
    });
  });
}

function openSidebar() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs[0]) {
      // Try to open sidePanel if available, otherwise open as popup
      if (chrome.sidePanel) {
        chrome.sidePanel.open({ tabId: tabs[0].id }).catch(() => {
          // Fallback: open sidebar.html in a new window
          chrome.windows.create({ url: 'sidebar.html', type: 'popup', width: 400, height: 600 });
        });
      } else {
        // Fallback for older Chrome versions
        chrome.windows.create({ url: 'sidebar.html', type: 'popup', width: 400, height: 600 });
      }
      window.close();
    }
  });
}

function viewCharter() {
  chrome.tabs.create({ url: 'charter.html' });
}

function viewAuditDetail(id) {
  chrome.storage.local.get('auditHistory', (data) => {
    const history = data.auditHistory || [];
    const audit = history.find((a) => a.id === id);

    if (audit) {
      chrome.tabs.create({
        url: `audit-detail.html?id=${id}`
      });
    }
  });
}

function formatTime(timestamp) {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;

  if (diff < 60000) return 'Just now';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
  
  return date.toLocaleDateString();
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}
