// ========================================
// Text Vault - Popup Script
// ========================================

// DOM Elements
const highlightsList = document.getElementById('highlights-list');
const emptyState = document.getElementById('empty-state');
const highlightCount = document.getElementById('highlight-count');
const searchInput = document.getElementById('search-input');
const filterTabs = document.getElementById('filter-tabs');
const exportBtn = document.getElementById('export-btn');
const clearBtn = document.getElementById('clear-btn');
const exportModal = document.getElementById('export-modal');
const closeModal = document.getElementById('close-modal');
const editModal = document.getElementById('edit-modal');
const editEditor = document.getElementById('edit-editor');
const cancelEditBtn = document.getElementById('cancel-edit');
const saveEditBtn = document.getElementById('save-edit');
const themeToggle = document.getElementById('theme-toggle');
const themeOptions = document.getElementById('theme-options');

// State
let highlights = [];
let activeFilter = 'all';
let searchQuery = '';
let editingHighlightId = null;
let currentTheme = 'dark';

// Categories config
const categories = {
  quotes: { name: 'Quotes', color: '#f0b429' },
  ideas: { name: 'Ideas', color: '#4da6ff' },
  research: { name: 'Research', color: '#45c48a' },
  inspiration: { name: 'Inspiration', color: '#e066a0' },
  uncategorized: { name: 'Uncategorized', color: '#6b6050' }
};

// ========== Initialize ==========
document.addEventListener('DOMContentLoaded', init);

function init() {
  loadTheme();
  loadHighlights();
  setupEventListeners();
}

// ========== Theme ==========
function loadTheme() {
  chrome.storage.local.get(['theme'], function(result) {
    currentTheme = result.theme || 'dark';
    applyTheme(currentTheme);
  });
}

function applyTheme(theme) {
  document.body.setAttribute('data-theme', theme);
  currentTheme = theme;
}

function saveTheme(theme) {
  chrome.storage.local.set({ theme: theme });
}

// ========== Storage ==========
function loadHighlights() {
  chrome.storage.local.get(['highlights'], function(result) {
    highlights = result.highlights || [];
    renderHighlights();
    updateCount();
  });
}

function saveHighlights() {
  chrome.storage.local.set({ highlights: highlights }, function() {
    updateCount();
  });
}

// ========== Event Listeners ==========
function setupEventListeners() {
  // Search
  searchInput.addEventListener('input', function(e) {
    searchQuery = e.target.value.toLowerCase();
    renderHighlights();
  });

  // Filter tabs
  filterTabs.addEventListener('click', function(e) {
    if (e.target.classList.contains('filter-btn')) {
      document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
      e.target.classList.add('active');
      activeFilter = e.target.dataset.category;
      renderHighlights();
    }
  });

  // Export button
  exportBtn.addEventListener('click', function() {
    if (highlights.length > 0) {
      exportModal.classList.add('active');
    } else {
      showToast('No highlights to export');
    }
  });

  // Close modal
  closeModal.addEventListener('click', function() {
    exportModal.classList.remove('active');
  });

  // Export options
  document.getElementById('copy-md').addEventListener('click', function() {
    copyToClipboard(exportAsMarkdown());
    showToast('Copied as Markdown!');
    exportModal.classList.remove('active');
  });

  document.getElementById('copy-txt').addEventListener('click', function() {
    copyToClipboard(exportAsText());
    showToast('Copied as Text!');
    exportModal.classList.remove('active');
  });

  document.getElementById('download-md').addEventListener('click', function() {
    downloadFile(exportAsMarkdown(), 'highlights.md', 'text/markdown');
    showToast('Downloaded!');
    exportModal.classList.remove('active');
  });

  document.getElementById('download-txt').addEventListener('click', function() {
    downloadFile(exportAsText(), 'highlights.txt', 'text/plain');
    showToast('Downloaded!');
    exportModal.classList.remove('active');
  });

  // Clear all
  clearBtn.addEventListener('click', function() {
    if (highlights.length === 0) {
      showToast('Nothing to clear');
      return;
    }
    if (confirm('Are you sure you want to delete all highlights?')) {
      highlights = [];
      saveHighlights();
      renderHighlights();
      showToast('All highlights cleared');
    }
  });

  // Close modal on outside click
  exportModal.addEventListener('click', function(e) {
    if (e.target === exportModal) {
      exportModal.classList.remove('active');
    }
  });

  // Edit modal events
  cancelEditBtn.addEventListener('click', function() {
    closeEditModal();
  });

  saveEditBtn.addEventListener('click', function() {
    saveEditedHighlight();
  });

  editModal.addEventListener('click', function(e) {
    if (e.target === editModal) {
      closeEditModal();
    }
  });

  // Formatting toolbar
  document.querySelectorAll('.format-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const format = btn.dataset.format;
      const color = btn.dataset.color;
      applyFormat(format, color);
    });
  });

  // Theme toggle
  themeToggle.addEventListener('click', function(e) {
    e.stopPropagation();
    themeOptions.classList.toggle('hidden');
  });

  // Theme options
  document.querySelectorAll('.theme-option').forEach(btn => {
    btn.addEventListener('click', function() {
      const theme = btn.dataset.theme;
      applyTheme(theme);
      saveTheme(theme);
      themeOptions.classList.add('hidden');
      showToast(`${theme.charAt(0).toUpperCase() + theme.slice(1)} theme applied`);
    });
  });

  // Close theme options on outside click
  document.addEventListener('click', function(e) {
    if (!themeToggle.contains(e.target) && !themeOptions.contains(e.target)) {
      themeOptions.classList.add('hidden');
    }
  });
}

// ========== Render ==========
function renderHighlights() {
  const filtered = highlights.filter(h => {
    const matchesSearch = searchQuery === '' || 
      h.text.toLowerCase().includes(searchQuery) ||
      h.sourceTitle.toLowerCase().includes(searchQuery);
    const matchesFilter = activeFilter === 'all' || h.category === activeFilter;
    return matchesSearch && matchesFilter;
  });

  if (highlights.length === 0) {
    emptyState.classList.remove('hidden');
    highlightsList.innerHTML = '';
    return;
  }

  emptyState.classList.add('hidden');

  if (filtered.length === 0) {
    highlightsList.innerHTML = '<p style="text-align: center; color: var(--text-muted); padding: 20px;">No matches found</p>';
    return;
  }

  highlightsList.innerHTML = filtered.map(h => createHighlightCard(h)).join('');

  // Add event listeners for card actions
  highlightsList.querySelectorAll('.action-btn').forEach(btn => {
    btn.addEventListener('click', handleCardAction);
  });
}

function createHighlightCard(highlight) {
  const date = new Date(highlight.createdAt).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  });

  const category = categories[highlight.category] || categories.uncategorized;
  const formattedText = formatDisplayText(highlight.text);

  return `
    <article class="highlight-card" data-id="${highlight.id}">
      <div class="card-header">
        <span class="category-tag ${highlight.category}">${category.name}</span>
        <span class="card-date">${date}</span>
      </div>
      <blockquote class="card-text">${formattedText}</blockquote>
      <div class="card-source">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
          <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
        </svg>
        <a href="${escapeHtml(highlight.sourceUrl)}" target="_blank" title="${escapeHtml(highlight.sourceTitle)}">
          ${escapeHtml(highlight.sourceTitle)}
        </a>
      </div>
      <div class="card-actions">
        <button class="action-btn edit" data-action="edit" data-id="${highlight.id}">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
          </svg>
          Edit
        </button>
        <button class="action-btn" data-action="visit" data-url="${escapeHtml(highlight.sourceUrl)}">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
            <polyline points="15,3 21,3 21,9"/>
            <line x1="10" y1="14" x2="21" y2="3"/>
          </svg>
          Visit
        </button>
        <button class="action-btn" data-action="copy" data-id="${highlight.id}">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect width="14" height="14" x="8" y="8" rx="2" ry="2"/>
            <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>
          </svg>
          Copy
        </button>
        <button class="action-btn delete" data-action="delete" data-id="${highlight.id}">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 6h18"/>
            <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/>
            <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
          </svg>
        </button>
      </div>
    </article>
  `;
}

// ========== Text Formatting ==========
function formatDisplayText(text) {
  // If text already contains HTML (from rich editor), use it directly
  if (text.includes('<') && text.includes('>')) {
    return '"' + text + '"';
  }
  
  // Legacy: convert markdown-style formatting for old highlights
  let formatted = escapeHtml(text);
  
  // Bold: **text**
  formatted = formatted.replace(/\*\*(.+?)\*\*/g, '<span class="bold">$1</span>');
  
  // Italic: *text*
  formatted = formatted.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<span class="italic">$1</span>');
  
  // Indent: >> text
  formatted = formatted.replace(/^&gt;&gt;\s*(.+)$/gm, '<span class="indent">$1</span>');
  
  // Numbered list: 1. text
  formatted = formatted.replace(/^(\d+)\.\s+(.+)$/gm, '<span class="indent">$1. $2</span>');
  
  return '"' + formatted + '"';
}

function applyFormat(format, color) {
  editEditor.focus();
  
  switch (format) {
    case 'bold':
      document.execCommand('bold', false, null);
      break;
    case 'italic':
      document.execCommand('italic', false, null);
      break;
    case 'indent':
      document.execCommand('indent', false, null);
      break;
    case 'outdent':
      document.execCommand('outdent', false, null);
      break;
    case 'number':
      document.execCommand('insertOrderedList', false, null);
      break;
    case 'bullet':
      document.execCommand('insertUnorderedList', false, null);
      break;
    case 'color':
      if (color) {
        document.execCommand('foreColor', false, color);
      }
      break;
    default:
      return;
  }
}

// ========== Edit Modal ==========
function openEditModal(id) {
  const highlight = highlights.find(h => h.id === id);
  if (!highlight) return;
  
  editingHighlightId = id;
  // Convert stored HTML back to editor
  editEditor.innerHTML = highlight.text;
  editModal.classList.add('active');
  editEditor.focus();
}

function closeEditModal() {
  editModal.classList.remove('active');
  editingHighlightId = null;
  editEditor.innerHTML = '';
}

function saveEditedHighlight() {
  if (!editingHighlightId) return;
  
  const newText = editEditor.innerHTML.trim();
  if (!newText || newText === '<br>') {
    showToast('Text cannot be empty');
    return;
  }
  
  const index = highlights.findIndex(h => h.id === editingHighlightId);
  if (index !== -1) {
    highlights[index].text = newText;
    saveHighlights();
    renderHighlights();
    showToast('Highlight updated!');
  }
  
  closeEditModal();
}

// ========== Card Actions ==========
function handleCardAction(e) {
  const btn = e.currentTarget;
  const action = btn.dataset.action;

  switch (action) {
    case 'visit':
      chrome.tabs.create({ url: btn.dataset.url });
      break;
    case 'copy':
      copyHighlightText(btn.dataset.id);
      showToast('Copied to clipboard!');
      break;
    case 'edit':
      openEditModal(btn.dataset.id);
      break;
    case 'delete':
      deleteHighlight(btn.dataset.id);
      break;
  }
}

function deleteHighlight(id) {
  highlights = highlights.filter(h => h.id !== id);
  saveHighlights();
  renderHighlights();
  showToast('Highlight deleted');
}

// ========== Export Functions ==========
function exportAsMarkdown() {
  return highlights.map(h => {
    const date = new Date(h.createdAt).toLocaleDateString();
    return `> ${h.text}\n\n— *[${h.sourceTitle}](${h.sourceUrl})* | ${categories[h.category]?.name || 'Uncategorized'} | ${date}\n`;
  }).join('\n---\n\n');
}

function exportAsText() {
  return highlights.map(h => {
    const date = new Date(h.createdAt).toLocaleDateString();
    return `"${h.text}"\n— ${h.sourceTitle} (${h.sourceUrl})\nCategory: ${categories[h.category]?.name || 'Uncategorized'} | ${date}\n`;
  }).join('\n---\n\n');
}

// ========== Utilities ==========
function updateCount() {
  const count = highlights.length;
  highlightCount.textContent = `${count} ${count === 1 ? 'highlight' : 'highlights'}`;
}

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

function copyToClipboard(text) {
  navigator.clipboard.writeText(text);
}

function copyHighlightText(id) {
  const highlight = highlights.find(h => h.id === id);
  if (!highlight) return;
  
  // Strip HTML tags to get plain text
  const temp = document.createElement('div');
  temp.innerHTML = highlight.text;
  const plainText = temp.textContent || temp.innerText || '';
  copyToClipboard(plainText);
}

function downloadFile(content, filename, type) {
  const blob = new Blob([content], { type: type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

function showToast(message) {
  // Remove existing toast
  const existing = document.querySelector('.toast');
  if (existing) existing.remove();

  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.textContent = message;
  document.body.appendChild(toast);

  setTimeout(() => toast.classList.add('show'), 10);
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => toast.remove(), 300);
  }, 2000);
}
