import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { SMALL_GAMES } from '../config/StaticPageConfig';
import {
  PageWrapper,
  Container,
  PageHeader,
  PageTitle,
  FeatureGrid,
  FeatureCard,
  FeatureCardIcon,
  FeatureCardTitle,
  FeatureCardDesc,
} from '../styles/shared';
import FullscreenEmbed from '../components/FullscreenEmbed';
import { SmallGameIcon } from '../components/SmallGameIcons';

const SmallGamePage = () => {
  const [games, setGames] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [embeddedGame, setEmbeddedGame] = useState(null);

  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);
    }
  };

  const handlePlayGame = (game) => {
    setEmbeddedGame({ ...game, link: game.link });
  };

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

        {loading ? (
          <div style={{
            background: 'white',
            borderRadius: '16px',
            padding: '48px 32px',
            textAlign: 'center',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
            marginBottom: '32px'
          }}>
            <h2 style={{ fontSize: '22px', fontWeight: '700', color: '#1f2937', marginBottom: '12px' }}>加载游戏中...</h2>
            <p style={{ color: '#6b7280', fontSize: '15px', lineHeight: '1.6' }}>正在为您准备精彩的小游戏，请稍候...</p>
          </div>
        ) : error ? (
          <div style={{
            background: 'white',
            borderRadius: '16px',
            padding: '48px 32px',
            textAlign: 'center',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
            marginBottom: '32px'
          }}>
            <h2 style={{ fontSize: '22px', fontWeight: '700', color: '#1f2937', marginBottom: '12px' }}>加载失败</h2>
            <p style={{ color: '#6b7280', fontSize: '15px', lineHeight: '1.6', marginBottom: '20px' }}>
              {error}
              <br />
              <button
                type="button"
                onClick={fetchGames}
                style={{
                  background: 'linear-gradient(135deg, #4ade80 0%, #22c55e 100%)',
                  color: 'white',
                  border: 'none',
                  padding: '10px 18px',
                  borderRadius: '10px',
                  cursor: 'pointer',
                  marginTop: '16px',
                  fontWeight: 600
                }}
              >
                重新加载
              </button>
            </p>
          </div>
        ) : games.length > 0 ? (
          <FeatureGrid>
            {games.map((game) => (
              <FeatureCard key={game.id} onClick={() => handlePlayGame(game)}>
                <FeatureCardIcon>
                  <SmallGameIcon gameId={game.id} />
                </FeatureCardIcon>
                <FeatureCardTitle>{game.title}</FeatureCardTitle>
                <FeatureCardDesc>{game.description}</FeatureCardDesc>
              </FeatureCard>
            ))}
          </FeatureGrid>
        ) : (
          <div style={{
            background: 'white',
            borderRadius: '16px',
            padding: '48px 32px',
            textAlign: 'center',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
            marginBottom: '32px'
          }}>
            <h2 style={{ fontSize: '22px', fontWeight: '700', color: '#1f2937', marginBottom: '12px' }}>暂无游戏</h2>
            <p style={{ color: '#6b7280', fontSize: '15px', lineHeight: '1.6' }}>目前还没有可用的游戏，请稍后再来查看。</p>
          </div>
        )}

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

export default SmallGamePage;
