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

let currentAuditResult = null;
let currentSelectedFlag = 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: 'Weighty Concern',
    color: '#e05a5a',
    bgColor: 'transparent',
    textColor: '#e05a5a',
    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: 'Worth a Second Look',
    color: '#e09d3a',
    bgColor: 'transparent',
    textColor: '#e09d3a',
    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: 'Pause and Test',
    color: '#5b8dee',
    bgColor: 'transparent',
    textColor: '#5b8dee',
    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: 'Gentle Invitation to Test',
    color: '#5b8dee',
    bgColor: 'transparent',
    textColor: '#5b8dee',
    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: 'Core Doctrine',
    sublabel: 'Doctrinal Foundations',
    color: '#5b8dee',
    bgColor: 'transparent',
    borderColor: 'rgba(255,255,255,0.07)'
  },
  additional: {
    icon: '🤖',
    label: 'AI-Specific Guardrails',
    sublabel: 'Formational Pattern Checks',
    color: '#5b8dee',
    bgColor: 'transparent',
    borderColor: 'rgba(255,255,255,0.07)'
  }
};

// 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();
  bindFlagInteractions();
});

function bindFlagInteractions() {
  document.addEventListener('click', (event) => {
    const tab = event.target.closest('.flag-tab');
    if (tab) {
      const flagId = tab.dataset.flagId;
      const panel = tab.dataset.flagTab;
      document.querySelectorAll(`[data-flag-id="${flagId}"].flag-tab`).forEach((btn) => btn.classList.remove('active'));
      tab.classList.add('active');
      document.querySelectorAll(`[data-flag-id="${flagId}"].flag-panel`).forEach((el) => {
        el.hidden = el.dataset.flagPanel !== panel;
      });
      return;
    }

    const toggle = event.target.closest('.flag-details-toggle');
    if (toggle) {
      const flagId = toggle.dataset.flagId;
      const details = document.querySelector(`[data-flag-details="${flagId}"]`);
      const open = !details.hidden;
      details.hidden = open;
      toggle.textContent = open ? 'Show details' : 'Hide details';
    }
  });
}

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 some text to examine');
    return;
  }

  if (text.length < 10) {
    showError('Text needs to 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('Couldn’t examine that response. Please try again.');
      }
    }
  );
}

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

  let html = `<div class="review-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(180deg, var(--wm-bg-header) 0%, var(--wm-bg-card) 100%); border-radius: 12px; margin-bottom: 16px; border: 1px solid var(--wm-border-subtle);">
    <span style="font-size: 24px;">${summaryIcon}</span>
    <div style="flex: 1;">
      <div style="font-weight: 600; color: var(--wm-text-primary); font-size: 15px;">${auditData.message || 'Ready for Your Review'}</div>
      <div style="font-size: 12px; color: var(--wm-text-secondary); margin-top: 6px; display: flex; flex-wrap: wrap; gap: 8px;">
        <span style="color: var(--wm-text-primary); font-weight: 500;">${auditData.total || 0} finding(s)</span>
        <span style="color: var(--wm-accent-primary); background: transparent; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--wm-border-subtle);">📜 ${auditData.primary_count || 0} Core Doctrine</span>
        <span style="color: var(--wm-accent-gold); background: transparent; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--wm-border-subtle);">🤖 ${auditData.additional_count || 0} AI-Specific Guardrails</span>
      </div>
      <div style="font-size: 11px; color: #64748B; margin-top: 6px; display: flex; flex-wrap: wrap; gap: 6px;">
        <span style="color: var(--wm-critical-text);">🔴 ${auditData.pastoral_boundary || 0}</span>
        <span style="color: var(--wm-warning-text);">🟠 ${auditData.strong_caution || 0}</span>
        <span style="color: var(--wm-info-text);">🔵 ${auditData.call_to_discernment || 0}</span>
        <span style="color: var(--wm-info-text);">🔵 ${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: transparent; border-radius: 12px; border: 1px solid var(--wm-border-subtle);">`;
      html += `<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-bottom: 10px; border-bottom: 1px solid var(--wm-border-subtle);">
        <span style="font-size: 22px;">${catConfig.icon}</span>
        <div>
        <div style="font-weight: 700; color: var(--wm-text-primary); font-size: 14px;">${catConfig.label}</div>
        <div style="font-size: 11px; color: var(--wm-text-secondary); margin-top: 2px;">${catConfig.sublabel}</div>
        </div>
        <div style="margin-left: auto; background: transparent; color: var(--wm-text-primary); padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; border: 1px solid var(--wm-border-subtle);">${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, index) => {
            html += createFlagHtml(flag, tierConfig, index, 'primary');
          });
          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: transparent; border-radius: 12px; border: 1px solid var(--wm-border-subtle);">`;
      html += `<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-bottom: 10px; border-bottom: 1px solid var(--wm-border-subtle);">
        <span style="font-size: 22px;">${catConfig.icon}</span>
        <div>
        <div style="font-weight: 700; color: var(--wm-text-primary); font-size: 14px;">${catConfig.label}</div>
        <div style="font-size: 11px; color: var(--wm-text-secondary); margin-top: 2px;">${catConfig.sublabel}</div>
        </div>
        <div style="margin-left: auto; background: transparent; color: var(--wm-text-primary); padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; border: 1px solid var(--wm-border-subtle);">${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, index) => {
            html += createFlagHtml(flag, tierConfig, index, 'additional');
          });
          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;">Nothing flagged here</div>
      <div style="font-size: 12px; margin-top: 8px; color: #92400e;">This response appears steady; keep testing all things in Scripture.</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, index = 0, category = 'primary') {
  const charter = flag.charter || 'Unknown';
  const scripture = flag.scripture || '';
  const explanation = flag.explanation || '';
  const prompt = flag.prompt || '';
  const flagId = `${category}-${index}-${(charter || '').replace(/[^a-z0-9]+/gi, '-').toLowerCase()}`;
  const confidence = getConfidenceDots(flag.tier || 'invitation_to_test');
  const distortionPatterns = flag.distortion_patterns || [];
  const patternTags = distortionPatterns.length > 0 ? `
    <div style="display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 8px;">
      ${distortionPatterns.map(p => `
        <span style="background: linear-gradient(135deg, #f8fafc, #f1f5f9); border: 1px solid #e2e8f0; color: #475569; padding: 3px 8px; border-radius: 999px; font-size: 10px; font-weight: 600; display: inline-flex; align-items: center; gap: 3px;">
          <span style="font-size: 9px;">🔍</span>
          ${p.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())}
        </span>`).join('')}
    </div>` : '';
  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 detectedText = flag.match || '';
  const prefillUrl = detectedText ? `https://berean.faithguard.ai/dashboard?prefill=${encodeURIComponent(detectedText)}` : 'https://berean.faithguard.ai';
  const ctaHtml = tierConfig.cta ? `
      <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid ${tierConfig.color}30; display: flex; flex-wrap: wrap; gap: 6px; align-items: center;">
        <a href="${prefillUrl}" target="_blank" rel="noopener noreferrer"
           style="display: inline-block; background: linear-gradient(135deg, #b8860b, #d4af37); color: #1a2332; padding: 8px 14px; border-radius: 999px; font-size: 12px; font-weight: 700; text-decoration: none; transition: transform 0.2s; box-shadow: 0 2px 8px rgba(212,175,55,0.3);">
          📘 ${tierConfig.cta}
        </a>
        ${wrestleHtml}
      </div>` : (wrestleHtml ? `
      <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid ${tierConfig.color}30;">
        ${wrestleHtml}
      </div>` : '');

  return `
    <div class="watchman-flag-card" id="flag-${flagId}" style="background: linear-gradient(180deg, rgba(255,251,235,0.98), rgba(254,243,199,0.9)); border: 1px solid rgba(180, 83, 9, 0.16); border-left: 5px solid ${tierConfig.color}; border-radius: 14px; padding: 12px; margin-bottom: 10px; box-shadow: 0 6px 18px rgba(15, 23, 42, 0.08);">
      <div style="display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom: 10px;">
        <div style="font-weight:700; color:#78350f; font-size:13px;">${escapeHtml(charter)}</div>
        <div style="display:flex; align-items:center; gap:4px;">${confidence}</div>
      </div>
      ${patternTags}
      <div class="flag-tabs" style="display:flex; gap:6px; flex-wrap:wrap; margin-bottom:10px;">
        <button class="flag-tab active" data-flag-tab="summary" data-flag-id="${flagId}" style="padding:6px 10px; border-radius:999px; border:1px solid ${tierConfig.color}; background:#fff7ed; color:#7c2d12; font-size:11px; font-weight:700; cursor:pointer;">Summary</button>
        <button class="flag-tab" data-flag-tab="scripture" data-flag-id="${flagId}" style="padding:6px 10px; border-radius:999px; border:1px solid rgba(180,83,9,0.25); background:#fffaf0; color:#7c2d12; font-size:11px; font-weight:700; cursor:pointer;">Scripture</button>
        <button class="flag-tab" data-flag-tab="discernment" data-flag-id="${flagId}" style="padding:6px 10px; border-radius:999px; border:1px solid rgba(180,83,9,0.25); background:#fffaf0; color:#7c2d12; font-size:11px; font-weight:700; cursor:pointer;">Discernment</button>
      </div>
      <div class="flag-panel flag-panel-summary" data-flag-panel="summary" data-flag-id="${flagId}">
        <div style="background: rgba(255,255,255,0.8); padding: 10px; border-radius: 10px; margin-bottom: 8px; font-size: 12px; color: #7c2d12; font-style: italic; border: 1px solid rgba(180,83,9,0.12);">
          "${escapeHtml(flag.match || '')}"
        </div>
        <div style="font-size: 12px; color: #7c2d12; line-height: 1.5;">${escapeHtml(explanation)}</div>
      </div>
      <div class="flag-panel" data-flag-panel="scripture" data-flag-id="${flagId}" hidden>
        <div style="font-size: 11px; color: #92400e; margin-bottom: 4px;"><strong>Scripture:</strong></div>
        <div style="font-size: 12px; color: #92400e; font-weight: 600;">${escapeHtml(scripture)}</div>
      </div>
      <div class="flag-panel" data-flag-panel="discernment" data-flag-id="${flagId}" hidden>
        <div style="background: rgba(255,255,255,0.8); padding: 10px; border-radius: 10px; border-left: 3px solid ${tierConfig.color};">
          <div style="font-size: 11px; color: #92400e; margin-bottom: 4px;"><strong>What to Ask:</strong></div>
          <div style="font-size: 12px; color: #7c2d12; line-height: 1.5;">${escapeHtml(prompt)}</div>
        </div>
      </div>
      <button class="flag-details-toggle" data-flag-id="${flagId}" style="margin-top:10px; background:transparent; border:none; color:#b45309; font-size:11px; font-weight:700; cursor:pointer; padding:0;">Open details</button>
      <div class="flag-details" data-flag-details="${flagId}" hidden>
        <div style="margin-top:8px; font-size:11px; color:#a16207; padding-top:8px; border-top:1px solid rgba(180,83,9,0.15);">
          <strong>Context:</strong> ${escapeHtml(flag.context || 'No context available')}
        </div>
        ${ctaHtml}
      </div>
    </div>
  `;
}

function getConfidenceDots(tier) {
  const count = tier === 'pastoral_boundary' ? 3 : tier === 'strong_caution' ? 2 : 1;
  return Array.from({ length: 3 }, (_, i) => `<span style="width:8px; height:8px; border-radius:999px; display:inline-block; background:${i < count ? '#b45309' : 'rgba(180,83,9,0.2)'};"></span>`).join('');
}

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;">Listening carefully...</div>
      <div style="color: #999; font-size: 12px; margin-top: 8px;">Comparing against the 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 reviews 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;
}
