// Watchman Theological Auditor - Sidebar Script
// Displays audit results using the 4-tier discernment framework

let currentAuditResult = null;

function escapeHtml(str) {
  if (!str) return '';
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}

// Tier display configuration - "Smoke Detector" language with CTA to The Berean
// Watchman detects patterns; The Berean analyzes context
const TIER_CONFIG = {
  pastoral_boundary: {
    icon: '🔴',
    label: 'Strong Alert',
    color: '#B91C1C',
    bgColor: 'rgba(185, 28, 28, 0.12)',
    textColor: '#FECACA',
    description: 'High-priority pattern detected. This touches on core doctrine. → Strongly recommend full analysis with The Berean for context.',
    cta: 'Analyze with The Berean →'
  },
  strong_caution: {
    icon: '🟠',
    label: 'Consider Reviewing',
    color: '#F59E0B',
    bgColor: 'rgba(245, 158, 11, 0.12)',
    textColor: '#FDE68A',
    description: 'Multiple patterns detected that may warrant attention. Compare with Scripture. → Recommended: Full analysis with The Berean.',
    cta: 'Get full analysis →'
  },
  call_to_discernment: {
    icon: '🟡',
    label: 'May Warrant Discernment',
    color: '#EAB308',
    bgColor: 'rgba(234, 179, 8, 0.12)',
    textColor: '#FEF08A',
    description: 'Pattern detected that touches on theological matters. Test through Scripture and prayer. → Analyze with The Berean for full context.',
    cta: 'Analyze with The Berean →'
  },
  invitation_to_test: {
    icon: '🔵',
    label: 'Invitation to Test',
    color: '#3B82F6',
    bgColor: 'rgba(59, 130, 246, 0.12)',
    textColor: '#93C5FD',
    description: 'This statement involves interpretation. Compare with Scripture in context.',
    cta: null
  }
};

// Category configuration - Primary (1-15) vs Additional (16-19)
const CATEGORY_CONFIG = {
  primary: {
    icon: '📜',
    label: 'Primary Theological Audit',
    sublabel: 'Charter Points 1-15: Core Doctrine',
    color: '#DC2626',
    bgColor: 'rgba(220, 38, 38, 0.08)',
    borderColor: '#DC2626'
  },
  additional: {
    icon: '🤖',
    label: 'Additional AI-Specific Audit',
    sublabel: 'Charter Points 16-19: Formational Guardrails',
    color: '#8B5CF6',
    bgColor: 'rgba(139, 92, 246, 0.08)',
    borderColor: '#8B5CF6'
  }
};

// Helper function to group flags by tier
function groupByTier(flags) {
  const grouped = {
    pastoral_boundary: [],
    strong_caution: [],
    call_to_discernment: [],
    invitation_to_test: []
  };
  flags.forEach((flag) => {
    const tier = flag.tier || 'invitation_to_test';
    if (grouped[tier]) {
      grouped[tier].push(flag);
    }
  });
  return grouped;
}

document.addEventListener('DOMContentLoaded', () => {
  // Tab switching
  document.querySelectorAll('.tab').forEach((tab) => {
    tab.addEventListener('click', () => switchTab(tab.dataset.tab));
  });

  // Manual audit
  document.getElementById('auditBtn').addEventListener('click', performManualAudit);
  document.getElementById('newAuditBtn').addEventListener('click', resetAuditForm);

  // Auto-audit toggle
  document.getElementById('autoAuditToggle').addEventListener('change', toggleAutoAudit);

  // Load initial data
  loadSettings();
  loadHistory();
});

function switchTab(tabName) {
  // Update tab buttons
  document.querySelectorAll('.tab').forEach((tab) => {
    tab.classList.remove('active');
  });
  document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

  // Update tab content
  document.querySelectorAll('.tab-content').forEach((content) => {
    content.classList.remove('active');
  });
  document.getElementById(`${tabName}-tab`).classList.add('active');

  if (tabName === 'history') {
    loadHistory();
  }
}

function performManualAudit() {
  const text = document.getElementById('auditText').value.trim();

  if (!text) {
    showError('Please enter text to audit');
    return;
  }

  if (text.length < 10) {
    showError('Text must be at least 10 characters');
    return;
  }

  // Show loading
  showLoading();

  // Send audit request
  chrome.runtime.sendMessage(
    { action: 'performAudit', text: text },
    (response) => {
      if (response && response.success) {
        currentAuditResult = response.data;
        displayAuditResults(response.data);
      } else if (response && response.error) {
        showError(response.error);
      } else {
        showError('Failed to audit response. Please try again.');
      }
    }
  );
}

function displayAuditResults(auditData) {
  const resultsSection = document.getElementById('resultsSection');
  const resultsContainer = document.getElementById('resultsContainer');

  let html = `<div class="audit-results">`;
  
  // Display summary with status icon
  const summaryStatus = auditData.status || 'clear';
  const summaryIcon = auditData.icon || '✅';
  html += `<div class="result-summary" style="display: flex; align-items: center; gap: 12px; padding: 16px; background: linear-gradient(135deg, #334155 0%, #1E293B 100%); border-radius: 10px; margin-bottom: 16px; border: 1px solid #334155;">
    <span style="font-size: 24px;">${summaryIcon}</span>
    <div style="flex: 1;">
      <div style="font-weight: 600; color: #F1F5F9; font-size: 15px;">${auditData.message || 'Audit Complete'}</div>
      <div style="font-size: 12px; color: #94A3B8; margin-top: 6px; display: flex; flex-wrap: wrap; gap: 8px;">
        <span style="color: #E2E8F0; font-weight: 500;">${auditData.total || 0} finding(s)</span>
        <span style="color: #DC2626; background: rgba(220, 38, 38, 0.2); padding: 2px 8px; border-radius: 4px;">📜 ${auditData.primary_count || 0} Primary</span>
        <span style="color: #8B5CF6; background: rgba(139, 92, 246, 0.2); padding: 2px 8px; border-radius: 4px;">🤖 ${auditData.additional_count || 0} AI-Specific</span>
      </div>
      <div style="font-size: 11px; color: #64748B; margin-top: 6px; display: flex; flex-wrap: wrap; gap: 6px;">
        <span style="color: #B91C1C;">🔴 ${auditData.pastoral_boundary || 0}</span>
        <span style="color: #F59E0B;">🟠 ${auditData.strong_caution || 0}</span>
        <span style="color: #EAB308;">🟡 ${auditData.call_to_discernment || 0}</span>
        <span style="color: #3B82F6;">🔵 ${auditData.invitation_to_test || 0}</span>
      </div>
    </div>
  </div>`;

  if (auditData.flags && auditData.flags.length > 0) {
    // Separate flags by category (primary vs additional)
    const primaryFlags = auditData.flags.filter(f => f.category === 'primary');
    const additionalFlags = auditData.flags.filter(f => f.category === 'additional');

    // Display PRIMARY AUDIT section (Points 1-15)
    if (primaryFlags.length > 0) {
      const catConfig = CATEGORY_CONFIG.primary;
      html += `<div style="margin-bottom: 20px; padding: 16px; background: ${catConfig.bgColor}; border-radius: 10px; border: 2px solid ${catConfig.borderColor};">`;
      html += `<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-bottom: 10px; border-bottom: 1px solid ${catConfig.borderColor};">
        <span style="font-size: 22px;">${catConfig.icon}</span>
        <div>
          <div style="font-weight: 700; color: ${catConfig.color}; font-size: 14px;">${catConfig.label}</div>
          <div style="font-size: 11px; color: #94A3B8; margin-top: 2px;">${catConfig.sublabel}</div>
        </div>
        <div style="margin-left: auto; background: ${catConfig.color}; color: white; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">${primaryFlags.length}</div>
      </div>`;

      // Group by tier within primary
      const primaryByTier = groupByTier(primaryFlags);
      Object.keys(primaryByTier).forEach((tier) => {
        if (primaryByTier[tier].length > 0) {
          const tierConfig = TIER_CONFIG[tier];
          html += `<div style="margin-bottom: 12px;">`;
          html += `<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 8px;">
            <span style="font-size: 14px;">${tierConfig.icon}</span>
            <div style="font-weight: 600; color: ${tierConfig.color}; font-size: 12px;">${tierConfig.label}</div>
          </div>`;
          primaryByTier[tier].forEach((flag) => {
            html += createFlagHtml(flag, tierConfig);
          });
          html += `</div>`;
        }
      });
      html += `</div>`;
    }

    // Display ADDITIONAL AUDIT section (Points 16-19) with purple color
    if (additionalFlags.length > 0) {
      const catConfig = CATEGORY_CONFIG.additional;
      html += `<div style="margin-bottom: 20px; padding: 16px; background: ${catConfig.bgColor}; border-radius: 10px; border: 2px solid ${catConfig.borderColor};">`;
      html += `<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-bottom: 10px; border-bottom: 1px solid ${catConfig.borderColor};">
        <span style="font-size: 22px;">${catConfig.icon}</span>
        <div>
          <div style="font-weight: 700; color: ${catConfig.color}; font-size: 14px;">${catConfig.label}</div>
          <div style="font-size: 11px; color: #94A3B8; margin-top: 2px;">${catConfig.sublabel}</div>
        </div>
        <div style="margin-left: auto; background: ${catConfig.color}; color: white; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">${additionalFlags.length}</div>
      </div>`;

      // Group by tier within additional
      const additionalByTier = groupByTier(additionalFlags);
      Object.keys(additionalByTier).forEach((tier) => {
        if (additionalByTier[tier].length > 0) {
          const tierConfig = TIER_CONFIG[tier];
          html += `<div style="margin-bottom: 12px;">`;
          html += `<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 8px;">
            <span style="font-size: 14px;">${tierConfig.icon}</span>
            <div style="font-weight: 600; color: ${tierConfig.color}; font-size: 12px;">${tierConfig.label}</div>
          </div>`;
          additionalByTier[tier].forEach((flag) => {
            html += createFlagHtml(flag, tierConfig);
          });
          html += `</div>`;
        }
      });
      html += `</div>`;
    }
  } else {
    html += `<div class="success" style="padding: 16px; background-color: #E8F5E9; border-radius: 6px; color: #2E7D32; text-align: center;">
      <div style="font-size: 24px; margin-bottom: 8px;">✅</div>
      <div style="font-weight: 600;">No theological concerns detected</div>
      <div style="font-size: 12px; margin-top: 8px; color: #558B2F;">This response appears to align with biblical orthodoxy.</div>
    </div>`;
  }

  html += `</div>`;

  resultsContainer.innerHTML = html;
  resultsSection.style.display = 'block';
  document.getElementById('auditText').style.display = 'none';
  document.getElementById('auditBtn').style.display = 'none';
}

function createFlagHtml(flag, tierConfig) {
  const charter = flag.charter || 'Unknown';
  const scripture = flag.scripture || '';
  const explanation = flag.explanation || '';
  const prompt = flag.prompt || '';
  const wrestleUrl = scripture ? `https://wrestlejournal.faithguard.ai/wrestle/dashboard?scripture=${encodeURIComponent(scripture)}` : '';
  const wrestleHtml = scripture ? `
        <a href="${wrestleUrl}" target="_blank" rel="noopener noreferrer"
           style="display: inline-block; background: linear-gradient(135deg, #292524, #44403C); color: #F5F5F4; padding: 8px 14px; border-radius: 6px; font-size: 12px; font-weight: 500; text-decoration: none; margin-left: 8px;">
          📜 Wrestle with this passage
        </a>` : '';
  const ctaHtml = tierConfig.cta ? `
      <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid ${tierConfig.color}40; display: flex; flex-wrap: wrap; gap: 6px; align-items: center;">
        <a href="https://berean.faithguard.ai" target="_blank" rel="noopener noreferrer" 
           style="display: inline-block; background: linear-gradient(135deg, #1a2332, #2d3748); color: white; padding: 8px 14px; border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; transition: transform 0.2s;">
          📘 ${tierConfig.cta}
        </a>
        ${wrestleHtml}
      </div>` : (wrestleHtml ? `
      <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid ${tierConfig.color}40;">
        ${wrestleHtml}
      </div>` : '');

  return `
    <div style="background-color: ${tierConfig.bgColor}; border-left: 4px solid ${tierConfig.color}; padding: 12px; margin-bottom: 10px; border-radius: 4px;">
      <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 8px;">
        <div style="font-weight: 600; color: #333; font-size: 13px;">${escapeHtml(charter)}</div>
      </div>
      
      <div style="background-color: white; padding: 8px; border-radius: 3px; margin-bottom: 8px; font-size: 12px; color: #555; font-style: italic; border: 1px solid #ddd;">
        "${escapeHtml(flag.match || '')}"
      </div>

      <div style="margin-bottom: 8px;">
        <div style="font-size: 11px; color: #666; margin-bottom: 4px;"><strong>Why This Matters:</strong></div>
        <div style="font-size: 12px; color: #333; line-height: 1.4;">${escapeHtml(explanation)}</div>
      </div>

      <div style="margin-bottom: 8px;">
        <div style="font-size: 11px; color: #666; margin-bottom: 4px;"><strong>Scripture:</strong></div>
        <div style="font-size: 12px; color: #1976D2; font-weight: 500;">${escapeHtml(scripture)}</div>
      </div>

      <div style="background-color: white; padding: 8px; border-radius: 3px; border-left: 3px solid ${tierConfig.color};">
        <div style="font-size: 11px; color: #666; margin-bottom: 4px;"><strong>Discernment Prompt:</strong></div>
        <div style="font-size: 12px; color: #333; line-height: 1.4;">${escapeHtml(prompt)}</div>
      </div>

      <div style="margin-top: 8px; font-size: 11px; color: #999; padding-top: 8px; border-top: 1px solid #ddd;">
        <strong>Context:</strong> ${escapeHtml(flag.context || 'No context available')}
      </div>
      ${ctaHtml}
    </div>
  `;
}

function resetAuditForm() {
  document.getElementById('auditText').value = '';
  document.getElementById('auditText').style.display = 'block';
  document.getElementById('auditBtn').style.display = 'block';
  document.getElementById('resultsSection').style.display = 'none';
  currentAuditResult = null;
}

function showLoading() {
  const resultsSection = document.getElementById('resultsSection');
  const resultsContainer = document.getElementById('resultsContainer');

  resultsContainer.innerHTML = `
    <div class="loading" style="text-align: center; padding: 24px;">
      <div class="spinner" style="display: inline-block; width: 32px; height: 32px; border: 3px solid #f3f3f3; border-top: 3px solid #DC143C; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 12px;"></div>
      <div style="color: #666; font-size: 14px;">Auditing text...</div>
      <div style="color: #999; font-size: 12px; margin-top: 8px;">Checking against 19-point Charter</div>
    </div>
    <style>
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    </style>
  `;
  resultsSection.style.display = 'block';
}

function showError(message) {
  const resultsSection = document.getElementById('resultsSection');
  const resultsContainer = document.getElementById('resultsContainer');

  resultsContainer.innerHTML = `<div class="error" style="background-color: #FFEBEE; border-left: 4px solid #DC143C; padding: 12px; border-radius: 4px; color: #C62828;">
    <div style="font-weight: 600; margin-bottom: 4px;">❌ Error</div>
    <div style="font-size: 12px;">${escapeHtml(message)}</div>
  </div>`;
  resultsSection.style.display = 'block';
}

function loadSettings() {
  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    document.getElementById('autoAuditToggle').checked = settings.autoAuditEnabled !== false;
  });
}

function toggleAutoAudit() {
  const isChecked = document.getElementById('autoAuditToggle').checked;

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

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

    if (history.length === 0) {
      container.innerHTML = `
        <div style="text-align: center; padding: 20px; color: #999;">
          <div style="font-size: 32px; margin-bottom: 8px;">📋</div>
          <div style="font-size: 12px;">No audits yet</div>
        </div>
      `;
      return;
    }

    let html = '';
    history.slice(0, 20).forEach((item) => {
      const tierColors = {
        pastoral_boundary: '#B91C1C',
        strong_caution: '#F59E0B',
        call_to_discernment: '#EAB308',
        invitation_to_test: '#3B82F6'
      };

      // Determine highest severity tier in this audit
      let borderColor = '#999';
      if (item.pastoral_boundary > 0) borderColor = tierColors.pastoral_boundary;
      else if (item.strong_caution > 0) borderColor = tierColors.strong_caution;
      else if (item.call_to_discernment > 0) borderColor = tierColors.call_to_discernment;
      else if (item.invitation_to_test > 0) borderColor = tierColors.invitation_to_test;

      html += `
        <div style="background-color: white; border-radius: 6px; padding: 10px; margin-bottom: 8px; border-left: 3px solid ${borderColor}; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.backgroundColor='#f9f9f9'" onmouseout="this.style.backgroundColor='white'" onclick="viewHistoryDetail(${item.id})">
          <div style="font-size: 12px; color: #333; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            ${escapeHtml(item.text)}
          </div>
          <div style="font-size: 11px; color: #999;">
            ${formatTime(item.timestamp)} • ${item.flags ? item.flags.length : 0} findings
          </div>
        </div>
      `;
    });

    container.innerHTML = html;
  });
}

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

    if (audit) {
      // Display in sidebar
      document.querySelector('[data-tab="manual"]').click();
      document.getElementById('auditText').value = audit.text;
      displayAuditResults(audit);
    }
  });
}

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;
}
