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

const Api60sPage = () => {
  const [catId, setCatId] = useState(API_CATEGORIES[0].id);
  const [disabledSet, setDisabledSet] = useState(null);
  const navigate = useNavigate();
  const { counts, bump } = useFeatureCardClickStats(FEATURE_CARD_SECTION.API_60S);

  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 className="text-center text-white/90 text-[15px] py-10 px-4">
          正在同步站点配置…
        </div>
      )}

      {visibleCategories && visibleCategories.length === 0 && (
        <div className="text-center text-white/90 text-[15px] py-10 px-4 opacity-95">
          当前站点暂未开放任何 60s 功能，请联系管理员。
        </div>
      )}

      {visibleCategories && visibleCategories.length > 0 && (
        <>
          {/* Tabs */}
          <div className="flex gap-2.5 mx-auto mb-[18px] max-w-[1200px] px-5 overflow-x-auto justify-center sm:justify-start sm:px-4 sm:gap-2 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
            {visibleCategories.map((c) => (
              <button
                key={c.id}
                type="button"
                onClick={() => setCatId(c.id)}
                className={clsx(
                  'flex-shrink-0 flex items-center gap-1.5 px-5 py-2.5 rounded-xl text-sm font-semibold font-[inherit] cursor-pointer transition-all whitespace-nowrap border',
                  'sm:px-4 sm:py-[9px] sm:text-[13px] sm:rounded-[10px]',
                  catId === c.id
                    ? 'border-transparent text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.12)] shadow-[0_4px_16px_rgba(34,197,94,0.35)] hover:-translate-y-px'
                    : 'border-white/55 bg-white/92 text-[#166534] hover:-translate-y-px hover:border-[rgba(129,199,132,0.8)]',
                )}
                style={
                  catId === c.id
                    ? { background: `linear-gradient(135deg, ${c.color} 0%, #22c55e 100%)` }
                    : {}
                }
              >
                {c.icon} {c.title}
              </button>
            ))}
          </div>

          <FeatureGrid key={catId}>
            {cat?.items.map((item) => (
              <CatalogCard
                key={item.id}
                $c={cat.color}
                onClick={() => {
                  bump(item.id);
                  navigate(`/60sapi/${item.id}`);
                }}
              >
                <FeatureCardUseCount>{Number(counts[item.id]) || 0}</FeatureCardUseCount>
                <FeatureCardIcon>{item.icon}</FeatureCardIcon>
                <FeatureCardTitle>{item.title}</FeatureCardTitle>
                <FeatureCardDesc>{item.desc || '点击查看详情'}</FeatureCardDesc>
              </CatalogCard>
            ))}
          </FeatureGrid>
        </>
      )}
    </PageWrapper>
  );
};

export default Api60sPage;
