/**
 * CuCu Note Extension Popup
 * 
 * Simple, reliable approach:
 * 1. On open → grab fresh Clerk token from any OpenNotion tab
 * 2. If token found → show NoteForm
 * 3. If no token → show "Sign in" button
 * 4. Popup stays OPEN after save
 */

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://160.191.50.138:3001';

// ========== Theme Hook ==========

function useTheme() {
  const [theme, setTheme] = useState<'light' | 'dark' | 'system'>('dark');

  useEffect(() => {
    const saved = localStorage.getItem('cucu-theme') as 'light' | 'dark' | 'system' | null;
    if (saved) setTheme(saved);
  }, []);

  useEffect(() => {
    localStorage.setItem('cucu-theme', theme);
    const root = document.documentElement;
    if (theme === 'system') {
      const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      root.setAttribute('data-theme', isDark ? 'dark' : 'light');
    } else {
      root.setAttribute('data-theme', theme);
    }
  }, [theme]);

  const cycleTheme = () => {
    setTheme((prev) => (prev === 'light' ? 'dark' : prev === 'dark' ? 'system' : 'light'));
  };

  const icon = theme === 'light' ? '☀️' : theme === 'dark' ? '🌙' : '🌓';
  return { theme, cycleTheme, icon };
}

// ========== Token Grabber ==========

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('160.191.50.138') ||
        url.includes('localhost:3001') ||
        url.includes('opennotion') ||
        url.includes('cucunote')
      );
    });

    for (const tab of candidates) {
      if (!tab.id) continue;
      try {
        const results = await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: 'MAIN',
          func: async () => {
            try {
              const clerk = (window as any).Clerk;
              if (clerk?.session?.getToken) {
                return await clerk.session.getToken();
              }
            } catch { /* Clerk not available */ }
            return null;
          },
        });
        const token = results[0]?.result;
        if (token && typeof token === 'string' && token.length > 50) {
          // Save to storage for other parts of extension
          await chrome.storage.local.set({
            clerkSessionToken: token,
            clerkTokenSyncedAt: Date.now(),
          });
          return token;
        }
      } catch {
        // This tab didn't work, try next
      }
    }
  } catch { /* Tab query failed */ }

  // Fallback: check storage
  try {
    const stored = await chrome.storage.local.get(['clerkSessionToken', 'clerkTokenSyncedAt']);
    if (stored.clerkSessionToken) {
      const age = Date.now() - (stored.clerkTokenSyncedAt || 0);
      if (age < 5 * 60 * 1000) { // less than 5 minutes old
        return stored.clerkSessionToken;
      }
    }
  } catch { /* storage failed */ }

  return null;
}

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

function App() {
  const { cycleTheme, icon: themeIcon } = useTheme();

  const [status, setStatus] = useState<'loading' | 'connected' | 'disconnected'>('loading');
  const [currentUrl, setCurrentUrl] = useState('');
  const [currentTitle, setCurrentTitle] = useState('');
  const [pendingText, setPendingText] = useState('');

  // Initialize: grab token + tab info
  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 from context menu / content script
      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();
      setStatus(t ? 'connected' : 'disconnected');
    })();
  }, []);

  // Fresh token getter for NoteForm — re-grabs from tab each time
  const getFreshToken = useCallback(async (): Promise<string | null> => {
    const fresh = await grabTokenFromTabs();
    if (fresh) setStatus('connected');
    return fresh;
  }, []);

  // Retry connection
  const handleRetry = async () => {
    setStatus('loading');
    const t = await grabTokenFromTabs();
    setStatus(t ? 'connected' : 'disconnected');
  };

  return (
    <div className="popup-container">
      {/* Header */}
      <header className="header">
        <div className="header-brand">
          <span className="header-brand-icon">🐣</span>
          <span>CuCu Note</span>
          <button className="btn btn-ghost btn-sm" onClick={cycleTheme} title="Toggle theme">
            {themeIcon}
          </button>
        </div>
        <div className="header-status">
          {status === 'loading' && (
            <>
              <span className="spinner" style={{ width: 10, height: 10 }} />
              <span className="status-text">Connecting...</span>
            </>
          )}
          {status === 'connected' && (
            <>
              <span className="status-dot status-connected" />
              <span className="status-text">Connected</span>
            </>
          )}
          {status === 'disconnected' && (
            <>
              <span className="status-dot status-offline" />
              <span className="status-text">Offline</span>
            </>
          )}
        </div>
      </header>

      {/* Loading */}
      {status === 'loading' && (
        <div className="content" style={{ textAlign: 'center', padding: '40px' }}>
          <span className="spinner" /> Connecting...
        </div>
      )}

      {/* Connected → NoteForm */}
      {status === 'connected' && (
        <NoteForm
          initialText={pendingText}
          initialUrl={currentUrl}
          initialTitle={currentTitle}
          getToken={getFreshToken}
        />
      )}

      {/* Disconnected → Sign in prompt */}
      {status === 'disconnected' && (
        <div className="content" style={{ padding: '24px', textAlign: 'center' }}>
          <div style={{ fontSize: '48px', marginBottom: '16px' }}>🔐</div>
          <h3 style={{ margin: '0 0 8px', fontSize: '16px', color: 'var(--text-primary)' }}>
            Sign in to CuCu Note
          </h3>
          <p style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '20px', lineHeight: 1.5 }}>
            Open the web app ad sign in, then come back here
          </p>
          <button
            className="btn btn-primary"
            onClick={() => chrome.tabs.create({ url: `${WEB_APP_URL}/auth` })}
            style={{ width: '100%', padding: '10px', fontSize: '14px', marginBottom: '10px' }}
          >
            🚀 Open CuCu Note to Sign In
          </button>
          <button
            className="btn btn-ghost"
            onClick={handleRetry}
            style={{ width: '100%', padding: '8px', fontSize: '13px' }}
          >
            🔄 Retry Connection
          </button>
        </div>
      )}
    </div>
  );
}

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