/**
 * Canifa Note Extension Popup
 *
 * Redesigned with shadcn/ui dark mode + Canifa branding.
 * Auth: Extracts Memos access-token from open tabs.
 * Always shows NoteForm — no login wall.
 */

import { useState, useEffect, useCallback } from 'react';
import { createRoot } from 'react-dom/client';
import { NoteForm } from '../components/NoteForm';
import './popup.css';

const WEB_APP_URL = 'http://172.16.2.210:5230';

// ========== Token Grabber (Memos) ==========

async function grabTokenFromTabs(): Promise<string | null> {
  try {
    const allTabs = await chrome.tabs.query({});
    const candidates = allTabs.filter((t) => {
      const url = t.url || '';
      return (
        url.includes('172.16.2.210') ||
        url.includes('localhost:5230') ||
        url.includes('cucunote') ||
        url.includes('canifa')
      );
    });

    for (const tab of candidates) {
      if (!tab.id) continue;
      try {
        const results = await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: 'MAIN',
          func: () => {
            try {
              // 1. Memos access-token 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 && val.length > 20 && !val.startsWith('{')) return val;
                }
              }
            } catch { /* ignore */ }
            return null;
          },
        });
        const token = results[0]?.result;
        if (token && typeof token === 'string' && token.length > 10) {
          await chrome.storage.local.set({
            memosAccessToken: token,
            tokenSyncedAt: Date.now(),
          });
          return token;
        }
      } catch {
        // Tab didn't work, try next
      }
    }
  } catch { /* Tab query failed */ }

  // Fallback: stored token
  try {
    const stored = await chrome.storage.local.get(['memosAccessToken', 'tokenSyncedAt']);
    if (stored.memosAccessToken) {
      const age = Date.now() - (stored.tokenSyncedAt || 0);
      if (age < 24 * 60 * 60 * 1000) { // Memos tokens last much longer than Clerk
        return stored.memosAccessToken;
      }
    }
  } catch { /* storage failed */ }

  return null;
}

// ========== Main App ==========

function App() {
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [currentUrl, setCurrentUrl] = useState('');
  const [currentTitle, setCurrentTitle] = useState('');
  const [pendingText, setPendingText] = useState('');

  useEffect(() => {
    (async () => {
      // Get current tab info
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab) {
          setCurrentUrl(tab.url || '');
          setCurrentTitle(tab.title || '');
        }
      } catch { /* ignore */ }

      // Get pending note
      try {
        const result = await chrome.storage.local.get(['pendingNote']);
        if (result.pendingNote) {
          setPendingText(result.pendingNote.text || '');
          chrome.storage.local.remove(['pendingNote']);
        }
      } catch { /* ignore */ }

      // Grab token
      const t = await grabTokenFromTabs();
      setIsConnected(!!t);
      setIsLoading(false);
    })();
  }, []);

  const getFreshToken = useCallback(async (): Promise<string | null> => {
    const fresh = await grabTokenFromTabs();
    setIsConnected(!!fresh);
    return fresh;
  }, []);

  const handleOpenApp = () => {
    chrome.tabs.create({ url: `${WEB_APP_URL}` });
  };

  return (
    <div className="popup-container">
      {/* Header */}
      <header className="header">
        <div className="header-brand">
          <img src="/image.png" alt="Canifa" className="header-brand-logo" />
          <span className="header-brand-name">CANIFA</span>
          <span className="header-brand-suffix">Note</span>
        </div>
        <div className="header-actions">
          <div className="header-status">
            {isLoading ? (
              <span className="spinner" style={{ width: 10, height: 10 }} />
            ) : (
              <>
                <span className={`status-dot ${isConnected ? 'connected' : 'disconnected'}`} />
                <span className="status-text">{isConnected ? 'Synced' : 'Offline'}</span>
              </>
            )}
          </div>
          <button className="btn-icon" onClick={handleOpenApp} title="Open Canifa Note">
            ↗
          </button>
        </div>
      </header>

      {/* Connection Banner (only when disconnected) */}
      {!isLoading && !isConnected && (
        <div className="content">
          <div className="inline-banner">
            <span className="inline-banner-icon">⚡</span>
            <span>
              <a onClick={handleOpenApp}>Mở Canifa Note</a> trên trình duyệt và đăng nhập để đồng bộ.
            </span>
          </div>
        </div>
      )}

      {/* Always show NoteForm */}
      <NoteForm
        initialText={pendingText}
        initialUrl={currentUrl}
        initialTitle={currentTitle}
        getToken={getFreshToken}
      />
    </div>
  );
}

// Mount
const root = document.getElementById('popup-root');
if (root) {
  createRoot(root).render(<App />);
}
