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);
  const [visitorInfo, setVisitorInfo] = useState(null);
  const [visitorInfoLoading, setVisitorInfoLoading] = useState(true);

  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获取所有数据
    // 使用环境变量配置的API地址，默认为 nav.api.shumengya.top
    const apiBaseUrl = process.env.REACT_APP_API_URL || 
                      (process.env.NODE_ENV === 'development' 
                        ? 'http://localhost:5000/api' 
                        : 'https://nav.api.shumengya.top/api');
    fetch(`${apiBaseUrl}/all`)
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应失败');
        }
        return response.json();
      })
      .then(data => {
        setData(data);

        // 设置 favicon：优先使用 cf-favicon API，失败则用后端返回的 logo
        const applyFavicon = (url) => {
          let faviconTag = document.querySelector('link[rel="icon"]');
          if (!faviconTag) {
            faviconTag = document.createElement('link');
            faviconTag.rel = 'icon';
            document.head.appendChild(faviconTag);
          }
          faviconTag.href = url;
        };
        const fallbackFavicon = data.profile?.favicon || '';
        const siteUrl = data.profile?.site
          || data.profile?.homepage
          || (data.contacts?.contacts?.find((c) => c.type === 'personprofile')?.link)
          || (data.contacts?.contacts?.find((c) => c.link?.startsWith('https://'))?.link)
          || window.location.origin;
        const apiFaviconUrl = `https://cf-favicon.pages.dev/api/favicon?url=${encodeURIComponent(siteUrl)}`;
        const img = new Image();
        img.onload = () => applyFavicon(apiFaviconUrl);
        img.onerror = () => { if (fallbackFavicon) applyFavicon(fallbackFavicon); };
        img.src = apiFaviconUrl;
        if (fallbackFavicon && !siteUrl) applyFavicon(fallbackFavicon);

        // 如果启用了本地背景，则获取随机背景图
        if (data.profile?.showlocalbackground) {
          fetch(`${apiBaseUrl}/random-background`)
            .then(res => res.json())
            .then(bgData => {
              if (bgData.image) {
                // 如果返回的是相对路径（以 /api/ 开头），转换为完整的 API URL
                let imageUrl = bgData.image;
                if (imageUrl.startsWith('/api/')) {
                  // 相对路径，需要添加域名
                  const baseUrl = apiBaseUrl.replace('/api', '');
                  imageUrl = `${baseUrl}${imageUrl}`;
                } else if (imageUrl.startsWith('/')) {
                  // 其他相对路径
                  const baseUrl = apiBaseUrl.replace('/api', '');
                  imageUrl = `${baseUrl}${imageUrl}`;
                }
                setBackgroundImage(imageUrl);
              }
            })
            .catch(err => console.error('获取背景图片失败:', err));
        }
        
        setLoading(false);
      })
      .catch(error => {
        console.error('获取数据失败:', error);
        setError(error.message);
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    setVisitorInfoLoading(true);

    fetch('https://cf-ip-geo.smyhub.com/api', {
      signal: controller.signal,
      headers: { Accept: 'application/json' },
      cache: 'no-store'
    })
      .then((res) => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}`);
        }
        return res.json();
      })
      .then((payload) => {
        setVisitorInfo(payload);
        setVisitorInfoLoading(false);
      })
      .catch((err) => {
        if (err?.name === 'AbortError') return;
        console.warn('获取访客 IP/地理位置失败:', err);
        setVisitorInfo(null);
        setVisitorInfoLoading(false);
      });

    return () => controller.abort();
  }, []);

  if (loading) {
    return (
      <div className="pwa-launch">
        <div className="pwa-launch-bg" />
        <div className="pwa-launch-content">
          <div className="pwa-launch-logo-wrap">
            <img
              src={`${process.env.PUBLIC_URL || ''}/logo192.png`}
              alt="萌芽"
              className="pwa-launch-logo"
            />
            <div className="pwa-launch-ring pwa-launch-ring-1" />
            <div className="pwa-launch-ring pwa-launch-ring-2" />
            <div className="pwa-launch-ring pwa-launch-ring-3" />
          </div>
          <h1 className="pwa-launch-title">萌芽主页</h1>
          <p className="pwa-launch-subtitle">加载中</p>
          <div className="pwa-launch-dots">
            <span className="pwa-launch-dot" />
            <span className="pwa-launch-dot" />
            <span className="pwa-launch-dot" />
          </div>
        </div>
      </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>
        <div className="footer-visitor">
          {visitorInfoLoading ? (
            <span>访客信息加载中</span>
          ) : visitorInfo?.ip ? (
            <span>
              访客 IP：{visitorInfo.ip}
              {visitorInfo.geo ? (
                <>
                  {' · '}
                  {[
                    visitorInfo.geo.country,
                    visitorInfo.geo.region,
                    visitorInfo.geo.city
                  ].filter(Boolean).join(' · ')}
                </>
              ) : null}
            </span>
          ) : (
            <span>访客信息获取失败</span>
          )}
        </div>
      </footer>
    </div>
  );
}

export default App;
