/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { marked } from 'marked';
import { StatusContext } from '../../context/Status';
import { useActualTheme } from '../../context/Theme';
import { API, showError } from '../../helpers';
import NoticeModal from '../../components/layout/NoticeModal';
import { useIsMobile } from '../../hooks/common/useIsMobile';

// 首页组件
import HeroSection from './components/HeroSection';
import ValueSection from './components/ValueSection';
import WorkflowSection from './components/WorkflowSection';
import ToolsSection from './components/ToolsSection';
import PartnersSection from './components/PartnersSection';
import CTASection from './components/CTASection';
import HomePageFooter from './components/HomePageFooter';

// 模型广场
import HomePricingFilters from './HomePricingFilters';

const Home = () => {
  const { i18n } = useTranslation();
  const [statusState] = useContext(StatusContext);
  const actualTheme = useActualTheme();
  const [homePageContentLoaded, setHomePageContentLoaded] = useState(false);
  const [homePageContent, setHomePageContent] = useState('');
  const [noticeVisible, setNoticeVisible] = useState(false);
  const isMobile = useIsMobile();

  const displayHomePageContent = async () => {
    setHomePageContent(localStorage.getItem('home_page_content') || '');
    const res = await API.get('/api/home_page_content');
    const { success, message, data } = res.data;
    if (success) {
      let content = data;
      if (!data.startsWith('https://')) {
        content = marked.parse(data);
      }
      setHomePageContent(content);
      localStorage.setItem('home_page_content', content);

      // 如果内容是 URL，则发送主题模式
      if (data.startsWith('https://')) {
        const iframe = document.querySelector('iframe');
        if (iframe) {
          iframe.onload = () => {
            iframe.contentWindow.postMessage({ themeMode: actualTheme }, '*');
            iframe.contentWindow.postMessage({ lang: i18n.language }, '*');
          };
        }
      }
    } else {
      showError(message);
      setHomePageContent('加载首页内容失败...');
    }
    setHomePageContentLoaded(true);
  };

  useEffect(() => {
    const checkNoticeAndShow = async () => {
      const lastCloseDate = localStorage.getItem('notice_close_date');
      const today = new Date().toDateString();
      if (lastCloseDate !== today) {
        try {
          const res = await API.get('/api/notice');
          const { success, data } = res.data;
          if (success && data && data.trim() !== '') {
            setNoticeVisible(true);
          }
        } catch (error) {
          console.error('获取公告失败:', error);
        }
      }
    };

    checkNoticeAndShow();
  }, []);

  useEffect(() => {
    displayHomePageContent().then();
  }, []);

  // 如果有自定义首页内容，显示自定义内容
  if (homePageContentLoaded && homePageContent !== '') {
    return (
      <div className="w-full overflow-x-hidden">
        {homePageContent.startsWith('https://') ? (
          <iframe
            src={homePageContent}
            className="h-screen w-full border-none"
          />
        ) : (
          <div
            className="mt-[60px]"
            dangerouslySetInnerHTML={{ __html: homePageContent }}
          />
        )}
      </div>
    );
  }

  // 默认首页布局
  return (
    <div className="home-snap-container">
      <NoticeModal
        visible={noticeVisible}
        onClose={() => setNoticeVisible(false)}
        isMobile={isMobile}
      />

      {/* Hero Section */}
      <HeroSection />

      {/* 工具链 Section */}
      <ToolsSection />

      {/* 核心价值 Section */}
      <ValueSection />

      {/* 工作流 Section */}
      <WorkflowSection />

      {/* 生态伙伴 Section */}
      <PartnersSection />

      {/* 模型广场 Section */}
      <section className="home-snap-section home-snap-section-pricing bg-[var(--semi-color-bg-0)]">
        <div className="mx-auto w-full max-w-6xl px-5 py-16 md:px-6 lg:px-8">
          <HomePricingFilters t={(key) => key} />
        </div>
      </section>

      {/* CTA Section */}
      <CTASection />

      {/* Footer */}
      <HomePageFooter />
    </div>
  );
};

export default Home;
