import { ApolloProvider } from '@apollo/client/react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { apolloClient } from './api/client';
import { Layout } from './components/layout/Layout';
import { LocationProvider } from './hooks/useLocation';
import { AuthProvider, useAuth } from './hooks/useAuth';
import { StreamChatProvider } from './context/StreamChatContext';
import { LoginPage } from './components/LoginPage';
import { DiscoverPage } from './pages/Discover';
import { LikesPage } from './pages/Likes';
import { MessagesPage } from './pages/Messages';
import { ChatPage } from './pages/Chat';
import { ProfilePage } from './pages/Profile';
import { SettingsPage } from './pages/Settings';
import { SentPingsPage } from './pages/SentPings';
import { MatchesPage } from './pages/Matches';
import { ApiExplorerPage } from './pages/ApiExplorer';
import { OkCupidPage } from './pages/OkCupid';
import { useEffect, useState, useRef } from 'react';
import { initialSync } from './api/dataSync';
import { authManager } from './api/auth';

// One-time credential reset (v2) — remove this block after it runs once
if (!localStorage.getItem('_cred_reset_v2')) {
  localStorage.removeItem('feeld_refresh_token');
  localStorage.removeItem('feeld_auth_token');
  localStorage.setItem('_cred_reset_v2', '1');
}

// Prevent browser tab discarding by keeping minimal activity
function usePreventTabDiscard() {
  const intervalRef = useRef<number | null>(null);

  useEffect(() => {
    // Ping every 30 seconds to prevent browser from discarding tab
    intervalRef.current = window.setInterval(() => {
      // Minimal operation to keep tab alive
      localStorage.setItem('_keepalive', Date.now().toString());
    }, 30000);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);
}

function AuthenticatedApp() {
  const [tokenReady, setTokenReady] = useState(false);
  const [tokenError, setTokenError] = useState<string | null>(null);

  // Ensure Firebase token is ready before rendering Apollo content
  useEffect(() => {
    authManager.ensureReady()
      .then((ready) => {
        if (ready) {
          setTokenReady(true);
          // Sync data after token is ready
          initialSync().catch(console.error);
        } else {
          setTokenError('Failed to initialize authentication');
        }
      })
      .catch((err) => {
        setTokenError(err.message || 'Authentication failed');
      });
  }, []);

  if (tokenError) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#0f0f14',
        color: '#ef4444',
        gap: '1rem',
        padding: '20px',
      }}>
        <div style={{ fontSize: '1.25rem', fontWeight: 600 }}>Authentication Error</div>
        <div style={{ color: '#6b7280', fontSize: '0.875rem', textAlign: 'center', maxWidth: '400px' }}>{tokenError}</div>
        <div style={{ display: 'flex', gap: '12px', marginTop: '16px' }}>
          <button
            onClick={() => {
              setTokenError(null);
              setTokenReady(false);
              authManager.forceRefresh()
                .then(() => setTokenReady(true))
                .catch(err => setTokenError(err.message || 'Retry failed'));
            }}
            style={{
              padding: '14px 28px',
              background: 'rgba(255,255,255,0.1)',
              border: '1px solid rgba(255,255,255,0.2)',
              borderRadius: '12px',
              color: '#ffffff',
              fontSize: '15px',
              fontWeight: 600,
              cursor: 'pointer',
            }}
          >
            Retry
          </button>
          <button
            onClick={() => {
              localStorage.clear();
              window.location.reload();
            }}
            style={{
              padding: '14px 28px',
              background: 'rgba(239, 68, 68, 0.15)',
              border: '1px solid rgba(239, 68, 68, 0.3)',
              borderRadius: '12px',
              color: '#ef4444',
              fontSize: '15px',
              fontWeight: 600,
              cursor: 'pointer',
            }}
          >
            Logout &amp; Start Over
          </button>
        </div>
      </div>
    );
  }

  if (!tokenReady) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#0f0f14',
        color: '#6b7280',
      }}>
        Connecting...
      </div>
    );
  }

  return (
    <ApolloProvider client={apolloClient}>
      <StreamChatProvider>
        <LocationProvider>
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<Layout />}>
                <Route index element={<Navigate to="/discover" replace />} />
                <Route path="discover" element={<DiscoverPage />} />
                <Route path="likes" element={<LikesPage />} />
                <Route path="messages" element={<MessagesPage />} />
                <Route path="chat/:channelId" element={<ChatPage />} />
                <Route path="profile" element={<ProfilePage />} />
                <Route path="settings" element={<SettingsPage />} />
                <Route path="sent-pings" element={<SentPingsPage />} />
                <Route path="matches" element={<MatchesPage />} />
                <Route path="okcupid" element={<OkCupidPage />} />
                <Route path="api-explorer" element={<ApiExplorerPage />} />
              </Route>
            </Routes>
          </BrowserRouter>
        </LocationProvider>
      </StreamChatProvider>
    </ApolloProvider>
  );
}

function AppContent() {
  const { isAuthenticated, isLoading } = useAuth();

  if (isLoading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#0f0f14',
        color: '#6b7280',
      }}>
        Loading...
      </div>
    );
  }

  if (!isAuthenticated) {
    return <LoginPage />;
  }

  return <AuthenticatedApp />;
}

function App() {
  // Prevent browser from discarding this tab when inactive
  usePreventTabDiscard();

  return (
    <AuthProvider>
      <AppContent />
    </AuthProvider>
  );
}

export default App;
