import React, { useState, useRef, useEffect } from 'react';
import './App.css';
import { VideoManagerLocal } from './utils/VideoManagerLocal';

import Home from './components/Home';
import FocusPageLocal from './components/FocusPageLocal';
import Achievement from './components/Achievement';
import Records from './components/Records';
import Customise from './components/Customise';
import Help from './components/Help';

function App() {
  const [activeTab, setActiveTab] = useState('home');
  const videoManagerRef = useRef(null);
  const [isSessionActive, setIsSessionActive] = useState(false);
  const [sessionResult, setSessionResult] = useState(null);

  useEffect(() => {
    const callbacks = {
      onSessionStart: () => {
        setIsSessionActive(true);
        setSessionResult(null);
      },
      onSessionEnd: (summary) => {
        setIsSessionActive(false);
        if (summary) setSessionResult(summary);
      }
    };
    videoManagerRef.current = new VideoManagerLocal(callbacks);

    return () => {
      if (videoManagerRef.current) videoManagerRef.current.stopStreaming();
    };
  }, []);

  const renderMenuButton = (tabId, label) => (
    <button
      className={`menu-btn ${activeTab === tabId ? 'active' : ''}`}
      onClick={() => setActiveTab(tabId)}
    >
      {label}
    </button>
  );

  return (
    <div className="app-container">
      <nav id="top-menu">
        <div className="top-menu-links">
        <button
          type="button"
          className={`menu-btn ${activeTab === 'home' ? 'active' : ''}`}
          onClick={() => setActiveTab('home')}
        >
          Home
        </button>
        <div className="separator" aria-hidden />
        <button className={`menu-btn ${activeTab === 'focus' ? 'active' : ''}`} onClick={() => setActiveTab('focus')}>
          Start Focus {isSessionActive && <span style={{ marginLeft: '8px', color: '#00FF00' }}>●</span>}
        </button>
        <div className="separator"></div>

        {renderMenuButton('achievement', 'My Achievement')}
        <div className="separator"></div>

        {renderMenuButton('records', 'My Records')}
        <div className="separator"></div>

        {renderMenuButton('customise', 'Customise')}
        <div className="separator"></div>

        {renderMenuButton('help', 'Help')}
        </div>
      </nav>

      {activeTab === 'home' && <Home setActiveTab={setActiveTab} />}

      <FocusPageLocal
        videoManager={videoManagerRef.current}
        sessionResult={sessionResult}
        setSessionResult={setSessionResult}
        isActive={activeTab === 'focus'}
      />
      {activeTab === 'achievement' && <Achievement />}
      {activeTab === 'records' && <Records />}
      {activeTab === 'customise' && <Customise />}
      {activeTab === 'help' && <Help />}
    </div>
  );
}

export default App;
