/**
 * 60s API 入口页面
 * 展示分类标签和 API 卡片网格，点击卡片跳转到对应子页面
 */
import React, { useState, useEffect, useMemo } from 'react';
import styled, { keyframes } from 'styled-components';
import { useNavigate } from 'react-router-dom';
import { API_CATEGORIES } from '../config/Api60sConfig';
import {
  PageWrapper,
  PageHeader,
  PageTitle,
  FeatureGrid,
  FeatureCard,
  FeatureCardIcon,
  FeatureCardTitle,
  FeatureCardDesc,
} from '../styles/shared';
import { fetch60sDisabledSet, filterApi60sCategories } from '../utils/site60sVisibility';

const fadeUp = keyframes`from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}`;

const Tabs = styled.div`
  display: flex;
  gap: 10px;
  margin: 0 auto 18px;
  max-width: 1200px;
  padding: 0 20px;
  overflow-x: auto;
  justify-content: center;
  scrollbar-width: none;
  &::-webkit-scrollbar { display: none; }
  @media (max-width: 640px) {
    justify-content: flex-start;
    padding: 0 16px;
    gap: 8px;
  }
`;

const Tab = styled.button`
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border: 1px solid ${({ $on }) => ($on ? 'transparent' : 'rgba(255,255,255,0.55)')};
  border-radius: 12px;
  font-size: 14px;
  font-weight: 600;
  font-family: inherit;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  background: ${({ $on, $c }) =>
    $on ? `linear-gradient(135deg, ${$c} 0%, #22c55e 100%)` : 'rgba(255,255,255,0.92)'};
  color: ${({ $on }) => ($on ? '#fff' : '#166534')};
  text-shadow: ${({ $on }) => ($on ? '0 1px 2px rgba(0,0,0,0.12)' : 'none')};
  box-shadow: ${({ $on }) =>
    $on ? '0 4px 16px rgba(34,197,94,0.35)' : '0 2px 8px rgba(255,255,255,0.5)'};
  &:hover {
    transform: translateY(-1px);
    border-color: ${({ $on }) => ($on ? 'transparent' : 'rgba(129,199,132,0.8)')};
  }
  @media (max-width: 640px) {
    padding: 9px 16px;
    font-size: 13px;
    border-radius: 10px;
  }
`;

const Grid = styled(FeatureGrid)``;

const Card = styled(FeatureCard)`
  &::before {
    background: linear-gradient(90deg, ${({ $c }) => $c || '#4ade80'}, #86efac);
  }
`;

const Api60sPage = () => {
  const [catId, setCatId] = useState(API_CATEGORIES[0].id);
  const [disabledSet, setDisabledSet] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    let cancel = false;
    fetch60sDisabledSet().then((set) => {
      if (!cancel) setDisabledSet(set);
    });
    return () => { cancel = true; };
  }, []);

  const visibleCategories = useMemo(
    () => (disabledSet === null ? null : filterApi60sCategories(API_CATEGORIES, disabledSet)),
    [disabledSet],
  );

  useEffect(() => {
    if (!visibleCategories?.length) return;
    if (!visibleCategories.some((c) => c.id === catId)) {
      setCatId(visibleCategories[0].id);
    }
  }, [visibleCategories, catId]);

  const cat = visibleCategories?.find(c => c.id === catId);

  return (
    <PageWrapper>
      <PageHeader>
        <PageTitle>60s API</PageTitle>
      </PageHeader>

      {disabledSet === null && (
        <div style={{
          textAlign: 'center',
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: '15px',
          padding: '40px 16px'
        }}>
          正在同步站点配置…
        </div>
      )}
      
      {visibleCategories && visibleCategories.length === 0 && (
        <div style={{
          textAlign: 'center',
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: '15px',
          padding: '40px 16px',
          opacity: 0.95
        }}>
          当前站点暂未开放任何 60s 功能，请联系管理员。
        </div>
      )}

      {visibleCategories && visibleCategories.length > 0 && (
        <>
          <Tabs>
            {visibleCategories.map(c => (
              <Tab key={c.id} $on={catId === c.id} $c={c.color} onClick={() => setCatId(c.id)}>
                {c.icon} {c.title}
              </Tab>
            ))}
          </Tabs>
          
          <Grid key={catId}>
            {cat?.items.map(item => (
              <Card key={item.id} $c={cat.color} onClick={() => navigate(`/60sapi/${item.id}`)}>
                <FeatureCardIcon>{item.icon}</FeatureCardIcon>
                <FeatureCardTitle>{item.title}</FeatureCardTitle>
                <FeatureCardDesc>{item.desc || '点击查看详情'}</FeatureCardDesc>
              </Card>
            ))}
          </Grid>
        </>
      )}
    </PageWrapper>
  );
};

export default Api60sPage;
