import React, { useState, useEffect } from 'react';
import './App.css';
import ProfileSection from './components/ProfileSection';
import TechStackSection from './components/TechStackSection';
import ProjectsSection from './components/ProjectsSection';
import ContactsSection from './components/ContactsSection';
import ClickParticle from './components/ClickParticle';

function App() {
  const [data, setData] = useState({
    profile: null,
    techstack: null,
    projects: null,
    contacts: null
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [backgroundImage, setBackgroundImage] = useState(null);
  const [isAdminMode, setIsAdminMode] = useState(false);

  useEffect(() => {
    // 检查是否为 admin 模式
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    const pathname = window.location.pathname;
    
    if (pathname.includes('/admin') && token === 'shumengya520') {
      setIsAdminMode(true);
    }

    // 从后端API获取所有数据
    // 开发环境使用完整URL,生产环境使用相对路径
    const apiBaseUrl = process.env.REACT_APP_API_URL || 
                      (process.env.NODE_ENV === 'development' ? 'http://localhost:5000/api' : '/api');
    fetch(`${apiBaseUrl}/all`)
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应失败');
        }
        return response.json();
      })
      .then(data => {
        setData(data);

        // 设置 favicon
        if (data.profile?.favicon) {
          let faviconTag = document.querySelector('link[rel="icon"]');
          if (!faviconTag) {
            faviconTag = document.createElement('link');
            faviconTag.rel = 'icon';
            document.head.appendChild(faviconTag);
          }
          faviconTag.href = data.profile.favicon;
        }

        // 如果启用了本地背景，则获取随机背景图
        if (data.profile?.showlocalbackground) {
          fetch(`${apiBaseUrl}/random-background`)
            .then(res => res.json())
            .then(bgData => {
              if (bgData.image) {
                setBackgroundImage(bgData.image);
              }
            })
            .catch(err => console.error('获取背景图片失败:', err));
        }
        
        setLoading(false);
      })
      .catch(error => {
        console.error('获取数据失败:', error);
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="error-container">
        <h2>加载失败</h2>
        <p>{error}</p>
        <p className="error-hint">请确保后端服务已启动（运行 python app.py）</p>
      </div>
    );
  }

  return (
    <div className="App" style={backgroundImage ? {
      backgroundImage: `url(${backgroundImage})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundAttachment: 'fixed'
    } : {}}>
      {/* 鼠标点击粒子效果 */}
      <ClickParticle />
      
      {backgroundImage && <div className="background-overlay"></div>}
      
      {/* 管理员模式标识 */}
      {isAdminMode && (
        <div style={{
          position: 'fixed',
          top: '10px',
          right: '10px',
          background: 'rgba(82, 183, 136, 0.9)',
          color: 'white',
          padding: '8px 16px',
          borderRadius: '20px',
          fontSize: '14px',
          fontWeight: 'bold',
          zIndex: 9999,
          boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
        }}>
          🔐 管理员模式
        </div>
      )}
      
      <div className="container">
        {/* 个人信息模块 */}
        {data.profile && <ProfileSection profile={data.profile} />}
        
        {/* 技术栈模块 */}
        {data.techstack && <TechStackSection techstack={data.techstack} />}
        
        {/* 精选项目模块 */}
        {data.projects && <ProjectsSection projects={data.projects.projects} />}
        
        {/* 联系方式模块 */}
        {data.contacts && <ContactsSection contacts={data.contacts.contacts} />}
      </div>
      
      {/* 页脚 */}
      <footer className="footer">
        <p><strong>{data.profile?.footer || '© 2025 萌芽个人主页. All rights reserved.'}</strong></p>
      </footer>
    </div>
  );
}

export default App;
