const { useState, useEffect } = React;

function App() {
  const [currentPage, setCurrentPage] = useState('dashboard');
  const [selectedContactId, setSelectedContactId] = useState(null);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Check if user is authenticated
    fetch('/api/auth/me')
      .then(res => {
        if (res.ok) return res.json();
        throw new Error('Not authenticated');
      })
      .then(data => {
        setUser(data);
        setLoading(false);
      })
      .catch(() => {
        // Not logged in - redirect to login
        window.location.href = '/login';
      });
  }, []);

  if (loading) return <div style={{ padding: '20px' }}>Loading...</div>;
  if (!user) return null;

  return (
    <div className="app">
      {/* Sidebar Navigation */}
      <div className="sidebar">
        <h2>CRM</h2>
        <nav>
          <a
            href="#"
            onClick={() => setCurrentPage('dashboard')}
            className={currentPage === 'dashboard' ? 'active' : ''}
          >
            Dashboard
          </a>
          <a
            href="#"
            onClick={() => setCurrentPage('contacts')}
            className={currentPage === 'contacts' ? 'active' : ''}
          >
            Contacts
          </a>
          <a
            href="#"
            onClick={() => setCurrentPage('email-queue')}
            className={currentPage === 'email-queue' ? 'active' : ''}
          >
            Email Queue
          </a>
          <a
            href="#"
            onClick={() => setCurrentPage('new-contact')}
            className={currentPage === 'new-contact' ? 'active' : ''}
          >
            + New Contact
          </a>
        </nav>
        <div className="user-section">
          <p>{user.email}</p>
          <p>{user.role.toUpperCase()}</p>
          <button onClick={() => fetch('/api/auth/logout', { method: 'POST' }).then(() => window.location.href = '/login')} style={{ marginTop: '10px', width: '100%' }}>
            Logout
          </button>
        </div>
      </div>

      {/* Main Content */}
      <div className="main">
        {currentPage === 'dashboard' && <Dashboard />}
        {currentPage === 'contacts' && <ContactsList onSelectContact={(id) => {
          setSelectedContactId(id);
          setCurrentPage('contact-detail');
        }} />}
        {currentPage === 'contact-detail' && <ContactDetail contactId={selectedContactId} />}
        {currentPage === 'email-queue' && <EmailQueue user={user} />}
        {currentPage === 'new-contact' && <NewContact onContactCreated={() => {
          setCurrentPage('contacts');
        }} />}
      </div>
    </div>
  );
}
