import React, { useState, useEffect } from 'react';
import { SMALL_GAMES } from '../config/StaticPageConfig';
import {
  PageWrapper,
  Container,
  PageHeader,
  PageTitle,
  FeatureGrid,
  CatalogCard,
  FeatureCardIcon,
  FeatureCardTitle,
  FeatureCardDesc,
  FeatureCardUseCount,
} from '../styles/shared';
import { FEATURE_CARD_SECTION } from '../config/featureCardSections';
import { useFeatureCardClickStats } from '../hooks/useFeatureCardClickStats';
import FullscreenEmbed from '../components/FullscreenEmbed';
import { SmallGameIcon } from '../components/SmallGameIcons';

const StatusBox = ({ children }) => (
  <div className="bg-white rounded-2xl px-8 py-12 text-center shadow-[0_4px_12px_rgba(0,0,0,0.08)] mb-8">
    {children}
  </div>
);

const SmallGamePage = () => {
  const [games, setGames] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [embeddedGame, setEmbeddedGame] = useState(null);
  const { counts, bump } = useFeatureCardClickStats(FEATURE_CARD_SECTION.SMALLGAME);

  useEffect(() => { fetchGames(); }, []);

  const fetchGames = async () => {
    try {
      setLoading(true);
      const visibleGames = SMALL_GAMES.filter((game) => game.IsShow !== false);
      setGames(visibleGames);
    } catch (err) {
      console.error('获取游戏列表失败:', err);
      setError('获取游戏列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageWrapper>
      <Container>
        <PageHeader style={{ marginBottom: '36px' }}>
          <PageTitle>休闲游戏</PageTitle>
        </PageHeader>

        {loading ? (
          <StatusBox>
            <h2 className="text-[22px] font-bold text-gray-800 mb-3">加载游戏中...</h2>
            <p className="text-gray-500 text-[15px] leading-relaxed">正在为您准备精彩的小游戏，请稍候...</p>
          </StatusBox>
        ) : error ? (
          <StatusBox>
            <h2 className="text-[22px] font-bold text-gray-800 mb-3">加载失败</h2>
            <p className="text-gray-500 text-[15px] leading-relaxed mb-5">{error}</p>
            <button
              type="button"
              onClick={fetchGames}
              className="bg-gradient-to-br from-[#4ade80] to-[#22c55e] text-white border-none px-[18px] py-2.5 rounded-[10px] cursor-pointer font-semibold"
            >
              重新加载
            </button>
          </StatusBox>
        ) : games.length > 0 ? (
          <FeatureGrid>
            {games.map((game) => (
              <CatalogCard
                key={game.id}
                $c="#4ade80"
                onClick={() => {
                  bump(game.id);
                  setEmbeddedGame({ ...game, link: game.link });
                }}
              >
                <FeatureCardUseCount>{Number(counts[game.id]) || 0}</FeatureCardUseCount>
                <FeatureCardIcon>
                  <SmallGameIcon gameId={game.id} />
                </FeatureCardIcon>
                <FeatureCardTitle>{game.title}</FeatureCardTitle>
                <FeatureCardDesc>{game.description}</FeatureCardDesc>
              </CatalogCard>
            ))}
          </FeatureGrid>
        ) : (
          <StatusBox>
            <h2 className="text-[22px] font-bold text-gray-800 mb-3">暂无游戏</h2>
            <p className="text-gray-500 text-[15px] leading-relaxed">目前还没有可用的游戏，请稍后再来查看。</p>
          </StatusBox>
        )}

        {embeddedGame && (
          <FullscreenEmbed
            title={embeddedGame.title}
            url={embeddedGame.link}
            onClose={() => setEmbeddedGame(null)}
            iframeAllow="keyboard-map *"
            autoFocus
          />
        )}
      </Container>
    </PageWrapper>
  );
};

export default SmallGamePage;
