/**
 * Content Script — Canifa Note
 *
 * 1. Auto-sync Memos access token when on Canifa Note pages
 * 2. Detect text selection → Space/Enter → Auto save with toast
 */

let selectedText = '';
let selectedUrl = '';
let selectedTitle = '';

// ========== AUTO MEMOS TOKEN SYNC ==========

async function tryExtractToken(): Promise<string | null> {
  const maxRetries = 3;
  const retryDelay = 500;

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      // 1. Memos cookie
      const match = document.cookie.match(/(?:^|; )memos\.access-token=([^;]+)/);
      if (match && match[1]) return match[1];

      // 2. localStorage
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && (key.includes('access_token') || key.includes('token'))) {
          const val = localStorage.getItem(key);
          if (val && typeof val === 'string' && val.length > 20 && !val.startsWith('{')) {
            return val;
          }
        }
      }
    } catch {
      // Not ready yet
    }

    if (attempt < maxRetries - 1) {
      await new Promise((resolve) => setTimeout(resolve, retryDelay));
    }
  }
  return null;
}

async function autoSyncToken() {
  const hostname = window.location.hostname;
  const isCanifaDomain =
    hostname === '172.16.2.210' ||
    hostname === 'localhost' ||
    hostname.includes('canifa') ||
    hostname.includes('cucunote') ||
    hostname.includes('cucu-note');

  if (!isCanifaDomain) return;

  const token = await tryExtractToken();
  if (token) {
    chrome.runtime.sendMessage({
      type: 'SYNC_AUTH',
      data: { memosAccessToken: token },
    });
  }
}

autoSyncToken();

// On-demand token request
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  if (message.type === 'GET_TOKEN') {
    tryExtractToken().then((token) => {
      sendResponse({ token });
    });
    return true;
  }
});

// ========== TEXT SELECTION → AUTO SAVE ==========

document.addEventListener('mouseup', handleTextSelection);
document.addEventListener('keydown', async (e) => {
  if ((e.key === ' ' || e.key === 'Enter') && selectedText.length > 0) {
    const target = e.target as HTMLElement;
    if (!target || (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA' && !target.isContentEditable)) {
      e.preventDefault();
      e.stopPropagation();
      await handleAutoSave();
      return;
    }
  }
});
document.addEventListener('keyup', handleTextSelection);

function handleTextSelection() {
  try {
    setTimeout(() => {
      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) {
        selectedText = '';
        removeQuickHint();
        return;
      }

      const text = selection.toString().trim();
      if (text.length === 0) {
        selectedText = '';
        removeQuickHint();
        return;
      }

      selectedText = text;
      selectedUrl = window.location.href;
      selectedTitle = document.title;
      showQuickHint();
    }, 50);
  } catch {
    // Silently ignore
  }
}

async function handleAutoSave() {
  if (!selectedText) return;

  try {
    showToast('Đang lưu...', 'loading');

    chrome.runtime.sendMessage({
      type: 'SAVE_NOTE',
      data: {
        text: selectedText,
        url: selectedUrl,
        title: selectedTitle,
      },
    }, (response) => {
      if (chrome.runtime.lastError) {
        showToast(`Lỗi: ${chrome.runtime.lastError.message || 'Extension error'}`, 'error');
        return;
      }

      if (response?.success) {
        showToast('Đã lưu vào Canifa Note', 'success');
        window.getSelection()?.removeAllRanges();
        selectedText = '';
        removeQuickHint();
      } else {
        const reason = response?.error || 'Không thể lưu';
        showToast(reason, 'error');
      }
    });
  } catch (err: any) {
    showToast(err?.message || 'Lỗi khi lưu', 'error');
  }
}

// ========== UI: Quick Hint ==========

function showQuickHint() {
  removeQuickHint();

  const hint = document.createElement('div');
  hint.id = 'cucu-quick-hint';
  hint.textContent = 'Space hoặc Enter để lưu nhanh';

  hint.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: hsl(240 10% 3.9%);
    color: hsl(0 0% 98%);
    padding: 10px 16px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    border: 1px solid hsl(240 3.7% 15.9%);
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 999999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    animation: cucuSlideUp 0.2s ease-out;
    pointer-events: none;
  `;

  if (!document.getElementById('cucu-hint-style')) {
    const style = document.createElement('style');
    style.id = 'cucu-hint-style';
    style.textContent = `
      @keyframes cucuSlideUp {
        from { opacity: 0; transform: translateY(12px); }
        to { opacity: 1; transform: translateY(0); }
      }
    `;
    document.head.appendChild(style);
  }

  try {
    document.body.appendChild(hint);
  } catch {
    document.documentElement.appendChild(hint);
  }

  setTimeout(() => removeQuickHint(), 3000);
}

function removeQuickHint() {
  const hint = document.getElementById('cucu-quick-hint');
  if (hint) {
    try { hint.remove(); } catch { /* ignore */ }
  }
}

// ========== UI: Toast ==========

function showToast(message: string, type: 'success' | 'error' | 'loading' = 'success') {
  const oldToast = document.getElementById('cucu-toast');
  if (oldToast) {
    try { oldToast.remove(); } catch { /* ignore */ }
  }

  const toast = document.createElement('div');
  toast.id = 'cucu-toast';

  const icons = { success: '✓', error: '✕', loading: '⟳' };
  toast.textContent = `${icons[type]} ${message}`;

  const colors = {
    success: 'hsl(142 71% 45%)',
    error: 'hsl(0 72% 51%)',
    loading: 'hsl(240 5% 64.9%)',
  };

  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: hsl(240 10% 3.9%);
    color: ${colors[type]};
    padding: 12px 18px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    border: 1px solid hsl(240 3.7% 15.9%);
    box-shadow: 0 8px 24px rgba(0,0,0,0.4);
    z-index: 999999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    animation: cucuToastSlide 0.25s ease-out;
    max-width: 320px;
    word-wrap: break-word;
  `;

  if (!document.getElementById('cucu-toast-style')) {
    const style = document.createElement('style');
    style.id = 'cucu-toast-style';
    style.textContent = `
      @keyframes cucuToastSlide {
        from { opacity: 0; transform: translateX(100%); }
        to { opacity: 1; transform: translateX(0); }
      }
    `;
    try { document.head.appendChild(style); } catch { /* ignore */ }
  }

  try {
    document.body.appendChild(toast);
  } catch {
    try { document.documentElement.appendChild(toast); } catch { return; }
  }

  if (type !== 'loading') {
    setTimeout(() => {
      if (toast.parentNode) {
        toast.style.animation = 'cucuToastSlide 0.2s ease-out reverse';
        setTimeout(() => {
          try { toast.remove(); } catch { /* ignore */ }
        }, 200);
      }
    }, 3000);
  }
}
