import React, { useState, useEffect } from 'react';
import './App.css';
import PublicView from './views/PublicView';
import AdminView from './views/AdminView';
import ProfileView from './views/ProfileView';
import LoginModal from './components/LoginModal';
import SavedNotifications from './components/SavedNotifications';

function App() {
  const [view, setView] = useState('public');
  const [currentUser, setCurrentUser] = useState(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [showSaved, setShowSaved] = useState(false);

  useEffect(() => {
    fetch('/api/auth/check')
      .then(r => r.json())
      .then(data => { if (data.authenticated) setCurrentUser(data.user); })
      .catch(() => {})
      .finally(() => setAuthChecked(true));
  }, []);

  function handleLogin(user) {
    setCurrentUser(user);
    setShowLogin(false);
  }

  async function handleLogout() {
    await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
    setCurrentUser(null);
    setView('public');
  }

  function handleProfileSaved(updated) {
    setCurrentUser(prev => ({ ...prev, ...updated }));
  }

  const isAdmin = Boolean(currentUser?.is_admin);

  let activeView;
  if (view === 'profile' && currentUser) {
    activeView = (
      <ProfileView
        currentUser={currentUser}
        onProfileSaved={handleProfileSaved}
        onShowSaved={() => setShowSaved(true)}
        onLogout={handleLogout}
      />
    );
  } else if (view === 'admin' && isAdmin) {
    activeView = <AdminView />;
  } else {
    activeView = (
      <PublicView
        currentUser={currentUser}
        onLoginRequest={() => setShowLogin(true)}
      />
    );
  }

  return (
    <div className="app">
      <nav className="view-switcher" aria-label="Primary">
        <button
          className={view === 'public' ? 'active' : ''}
          onClick={() => setView('public')}
        >
          <span className="nav-icon">🔍</span>
          <span className="nav-label">Search</span>
        </button>
        {isAdmin && (
          <button
            className={view === 'admin' ? 'active' : ''}
            onClick={() => setView('admin')}
          >
            <span className="nav-icon">⚙️</span>
            <span className="nav-label">Admin</span>
          </button>
        )}
        {authChecked && currentUser && (
          <button
            className={view === 'profile' ? 'active' : ''}
            onClick={() => setView('profile')}
          >
            <span className="nav-icon">👤</span>
            <span className="nav-label">Profile</span>
          </button>
        )}
        {authChecked && !currentUser && (
          <button className="auth-btn" onClick={() => setShowLogin(true)}>
            <span className="nav-icon">⤷</span>
            <span className="nav-label">Login</span>
          </button>
        )}
      </nav>

      {activeView}

      {showLogin && (
        <LoginModal
          onLogin={handleLogin}
          onClose={() => setShowLogin(false)}
        />
      )}

      {showSaved && currentUser && (
        <SavedNotifications onClose={() => setShowSaved(false)} />
      )}
    </div>
  );
}

export default App;
