/**
 * 60s API 单条入口：用全屏嵌入打开 public/60sapi 下对应静态 HTML
 */
import React, { useCallback, useMemo, useState, useEffect } from 'react';
import { useParams, useNavigate, Navigate } from 'react-router-dom';
import FullscreenEmbed from '../components/FullscreenEmbed';
import { API_ITEM_STATIC_HTML, findApiItemMeta } from '../config/Api60sConfig';
import { ENV_CONFIG } from '../config/env';
import { PageWrapper } from '../styles/shared';
import { fetch60sDisabledSet } from '../utils/site60sVisibility';

const Api60sItemPage = () => {
  const { itemId } = useParams();
  const navigate = useNavigate();
  const [hiddenCheck, setHiddenCheck] = useState(null);
  const [sixtyBase, setSixtyBase] = useState(null);

  const htmlPath = itemId ? API_ITEM_STATIC_HTML[itemId] : null;
  const meta = itemId ? findApiItemMeta(itemId) : null;

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

  useEffect(() => {
    let cancel = false;
    fetch(`${ENV_CONFIG.API_URL}/api/site/60s-source`)
      .then((r) => r.json())
      .then((d) => {
        if (cancel) return;
        setSixtyBase(typeof d.base_url === 'string' && d.base_url ? d.base_url : 'https://60s.api.shumengya.top');
      })
      .catch(() => {
        if (!cancel) setSixtyBase('https://60s.api.shumengya.top');
      });
    return () => { cancel = true; };
  }, []);

  const embedUrl = useMemo(() => {
    if (!htmlPath || sixtyBase == null) return null;
    const sep = htmlPath.includes('?') ? '&' : '?';
    return `${htmlPath}${sep}sixty_base=${encodeURIComponent(sixtyBase)}`;
  }, [htmlPath, sixtyBase]);

  const onClose = useCallback(() => {
    navigate('/60sapi', { replace: true });
  }, [navigate]);

  const title = useMemo(() => {
    if (!meta) return '60s API';
    return `${meta.item.icon} ${meta.item.title}`;
  }, [meta]);

  const headerColor = meta?.category?.color || '#22c55e';

  if (!itemId || !htmlPath || !meta) {
    return <Navigate to="/60sapi" replace />;
  }

  if (hiddenCheck === null || sixtyBase == null || !embedUrl) {
    return (
      <PageWrapper>
        <p style={{ textAlign: 'center', color: '#fff', padding: '48px 16px', textShadow: '0 1px 4px rgba(0,0,0,0.2)' }}>
          正在加载…
        </p>
      </PageWrapper>
    );
  }

  if (hiddenCheck) {
    return <Navigate to="/60sapi" replace />;
  }

  return (
    <FullscreenEmbed
      title={title}
      url={embedUrl}
      headerColor={headerColor}
      onClose={onClose}
    />
  );
};

export default Api60sItemPage;
