import React, { useState, useEffect } from 'react';
import { HashRouter } from 'react-router-dom';
import Layout from './components/Layout';
import Interaction from './pages/Interaction';
import Discovery from './pages/Discovery';
import Library from './pages/Library';
import ManualControl from './pages/ManualControl';
import Profile from './pages/Profile';
import Player from './pages/Player';
import TopUp from './pages/TopUp';
import DeviceManager from './pages/DeviceManager';
import Subscription from './pages/Subscription';
import PrivacySafety from './pages/PrivacySafety';
import HelpFeedback from './pages/HelpFeedback';
import Settings from './pages/Settings';
import { UserTab, Scenario, Character, DeviceStatus } from './types';

const App: React.FC = () => {
  const [currentTab, setCurrentTab] = useState<UserTab>(UserTab.Discovery);
  const [activeScenario, setActiveScenario] = useState<Scenario | null>(null);
  const [activeCharacter, setActiveCharacter] = useState<Character | null>(null);
  const [showTopUp, setShowTopUp] = useState(false);
  const [showDeviceManager, setShowDeviceManager] = useState(false);
  const [showSubscription, setShowSubscription] = useState(false);
  const [showPrivacy, setShowPrivacy] = useState(false);
  const [showHelp, setShowHelp] = useState(false);
  const [showSettings, setShowSettings] = useState(false);

  // Global Device State (Mock)
  const [deviceStatus, setDeviceStatus] = useState<DeviceStatus>({
      connected: true,
      battery: 82,
      temperature: 36.5,
      signalStrength: 90,
      currentMode: 'Idle'
  });

  // Mock battery drain
  useEffect(() => {
      const interval = setInterval(() => {
          setDeviceStatus(prev => ({
              ...prev,
              battery: Math.max(0, prev.battery - (prev.connected ? 0.05 : 0)), // Slow drain
              signalStrength: prev.connected ? 85 + Math.random() * 10 : 0
          }));
      }, 5000);
      return () => clearInterval(interval);
  }, []);

  const handleScenarioPlay = (scenario: Scenario) => {
    if (!scenario.isLocked) {
        setActiveScenario(scenario);
    } else {
        alert('Credits required to unlock this premium content.');
    }
  };

  const renderContent = () => {
    switch (currentTab) {
      case UserTab.Discovery:
        return <Discovery onSelectCharacter={setActiveCharacter} />;
      case UserTab.Library:
        return <Library onPlay={handleScenarioPlay} />;
      case UserTab.Control:
        return <ManualControl />;
      case UserTab.Profile:
        return (
            <Profile 
                onTopUp={() => setShowTopUp(true)} 
                onOpenDeviceManager={() => setShowDeviceManager(true)}
                onOpenSubscription={() => setShowSubscription(true)}
                onOpenPrivacy={() => setShowPrivacy(true)}
                onOpenHelp={() => setShowHelp(true)}
                onOpenSettings={() => setShowSettings(true)}
            />
        );
      default:
        return <Discovery onSelectCharacter={setActiveCharacter} />;
    }
  };

  // Define Page Titles based on Tab
  const getPageMeta = (tab: UserTab) => {
      switch (tab) {
          case UserTab.Discovery:
              return { title: '专属推荐', subtitle: '基于偏好生成的私密匹配列表' };
          case UserTab.Library:
              return { title: '剧本馆', subtitle: '沉浸式感官体验库' };
          case UserTab.Control:
              return { title: '手动实验室', subtitle: '实时触觉反馈控制' };
          case UserTab.Profile:
              return { title: '个人中心', subtitle: 'ID: 884-291-00X' };
          default:
              return { title: 'Wei AI', subtitle: '' };
      }
  };

  const meta = getPageMeta(currentTab);

  return (
    <HashRouter>
        {activeScenario ? (
            <Player scenario={activeScenario} onClose={() => setActiveScenario(null)} />
        ) : activeCharacter ? (
            <Interaction character={activeCharacter} onBack={() => setActiveCharacter(null)} />
        ) : showTopUp ? (
            <TopUp onBack={() => setShowTopUp(false)} />
        ) : showDeviceManager ? (
            <DeviceManager onBack={() => setShowDeviceManager(false)} />
        ) : showSubscription ? (
            <Subscription onBack={() => setShowSubscription(false)} />
        ) : showPrivacy ? (
            <PrivacySafety onBack={() => setShowPrivacy(false)} />
        ) : showHelp ? (
            <HelpFeedback onBack={() => setShowHelp(false)} />
        ) : showSettings ? (
            <Settings onBack={() => setShowSettings(false)} />
        ) : (
            <Layout 
                currentTab={currentTab} 
                onTabChange={setCurrentTab}
                title={meta.title}
                subtitle={meta.subtitle}
                deviceStatus={deviceStatus}
                onDeviceClick={() => setShowDeviceManager(true)}
            >
                {renderContent()}
            </Layout>
        )}
    </HashRouter>
  );
};

export default App;