/*
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, { useState, useEffect, useContext } from 'react';
import { Button, Input, ScrollList, ScrollItem } from '@douyinfe/semi-ui';
import { IconPlay, IconFile, IconCopy, IconActivity, IconHistogram, IconCloudStroked } from '@douyinfe/semi-icons';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { copy, showSuccess } from '../../../helpers';
import { StatusContext } from '../../../context/Status';
import { API_ENDPOINTS } from '../../../constants/common.constant';

const HeroSection = () => {
  const { t, i18n } = useTranslation();
  const [statusState] = useContext(StatusContext);
  const isChinese = i18n.language.startsWith('zh');

  const serverAddress = statusState?.status?.server_address || `${window.location.origin}`;
  const isDemoSiteMode = statusState?.status?.demo_site_enabled || false;

  const endpointItems = API_ENDPOINTS.map((e) => ({ value: e }));
  const [endpointIndex, setEndpointIndex] = useState(0);

  const handleCopyBaseURL = async () => {
    const ok = await copy(serverAddress);
    if (ok) {
      showSuccess(t('已复制到剪切板'));
    }
  };

  useEffect(() => {
    const timer = setInterval(() => {
      setEndpointIndex((prev) => (prev + 1) % endpointItems.length);
    }, 3000);
    return () => clearInterval(timer);
  }, [endpointItems.length]);

  const features = [
    {
      icon: <IconActivity size={18} />,
      title: t('实时调度'),
      description: t('健康度与延迟权重动态切换，保证最优响应。'),
    },
    {
      icon: <IconHistogram size={18} />,
      title: t('统一监控'),
      description: t('调用、费用、异常一站式可视化，随时掌握运行状态。'),
    },
    {
      icon: <IconCloudStroked size={18} />,
      title: t('安全可控'),
      description: t('多维策略保障核心业务优先级，避免突发拥堵。'),
    },
  ];

  const stats = [
    { value: '100+', label: t('可覆盖模型') },
    { value: '99.9%', label: t('SLA 可用性') },
    { value: '7', label: t('多区域节点') },
  ];

  return (
    <section className="home-snap-section home-snap-section-hero bg-[var(--semi-color-bg-0)]">
      {/* 背景光晕 */}
      <div className="hero-blur-ball-1" />
      <div className="hero-blur-ball-2" />

      <div className="relative z-10 mx-auto w-full max-w-6xl px-5 pt-14 pb-8 md:px-6 md:pt-32 md:pb-20 lg:px-8 lg:pt-36 lg:pb-24">
        <div className="grid items-center gap-12 hero-grid lg:grid-cols-[1.1fr_0.9fr]">
          {/* 左侧内容 */}
          <div className="flex flex-col gap-8">
            {/* 标签 */}
            <span className="hero-tag self-start">
              {t('面向企业的 AI 生产力基座')}
            </span>

            {/* 大标题 */}
            <div
              className={`text-2xl font-bold text-semi-color-text-0 leading-tight md:text-4xl lg:text-5xl ${
                isChinese ? 'tracking-wide md:tracking-wider' : ''
              }`}
            >
              <span className="mb-8 block whitespace-nowrap">{t('统一的大模型接口网关')}</span>
              <span className="shine-text block whitespace-nowrap">{t('链接顶级 AI 能力')}</span>
            </div>

            {/* 描述 */}
            <p className="max-w-xl text-base leading-relaxed text-semi-color-text-1 md:text-lg">
              {t('以一套域名、密钥与风控策略连接顶级大模型资源，保障可观测、可拓展、可控。')}
            </p>

            {/* API URL 输入框 */}
            <div className="api-url-card">
              <span className="mb-3 block text-xs uppercase tracking-wide text-semi-color-text-2">
                {t('替换基础 URL 即可接入')}
              </span>
              <Input
                readonly
                value={serverAddress}
                className="!rounded-2xl"
                size="large"
                suffix={
                  <div className="flex items-center gap-2">
                    <ScrollList
                      bodyHeight={32}
                      style={{ border: 'unset', boxShadow: 'unset' }}
                    >
                      <ScrollItem
                        mode="wheel"
                        cycled={true}
                        list={endpointItems}
                        selectedIndex={endpointIndex}
                        onSelect={({ index }) => setEndpointIndex(index)}
                      />
                    </ScrollList>
                    <Button
                      type="primary"
                      onClick={handleCopyBaseURL}
                      icon={<IconCopy />}
                      className="!rounded-full"
                      size="small"
                    />
                  </div>
                }
              />
            </div>

            {/* CTA 按钮 */}
            <div className="flex flex-wrap items-center gap-4">
              <Link to="/console">
                <Button
                  theme="solid"
                  type="primary"
                  size="large"
                  className="!rounded-3xl px-8 py-2"
                  icon={<IconPlay />}
                >
                  {t('获取密钥')}
                </Button>
              </Link>
              {isDemoSiteMode && statusState?.status?.version ? (
                <Button
                  size="large"
                  className="flex items-center !rounded-3xl px-6 py-2"
                  icon={<IconFile />}
                  onClick={() =>
                    window.open(
                      'https://github.com/QuantumNous/new-api',
                      '_blank'
                    )
                  }
                >
                  {statusState.status.version}
                </Button>
              ) : null}
            </div>

            {/* 统计数据 */}
            <div className="flex flex-wrap gap-8 pt-2">
              {stats.map((stat, index) => (
                <div key={index} className="stat-card">
                  <span className="stat-card-value">{stat.value}</span>
                  <span className="stat-card-label">{stat.label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* 右侧功能卡片 */}
          <div className="relative hidden lg:block">
            <div className="feature-card-container">
              <div className="feature-card">
                {features.map((feature, index) => (
                  <div key={index} className="feature-card-item">
                    <div className="flex items-center gap-3">
                      <div className="feature-card-icon">{feature.icon}</div>
                      <span className="text-sm font-semibold text-semi-color-text-0">
                        {feature.title}
                      </span>
                    </div>
                    <span className="text-xs leading-relaxed text-semi-color-text-2">
                      {feature.description}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default HeroSection;
