/**
 * DeepAnalysis - 深度分析组件
 *
 * 独立一级 Tab 组件，支持：
 * - 按 Tab 懒加载数据
 * - 已加载数据缓存
 * - 业务板块展开状态管理
 */

import React, { useState, useCallback, useEffect, memo } from 'react';
import DeepAnalysisTab from '../CompanyOverview/DeepAnalysisTab';
import type { DeepAnalysisTabKey } from '../CompanyOverview/DeepAnalysisTab/types';
import { useDeepAnalysisData } from './hooks';
import { TAB_API_MAP } from './types';
import type { DeepAnalysisProps } from './types';

/**
 * 深度分析组件
 *
 * @param stockCode 股票代码
 */
const DeepAnalysis: React.FC<DeepAnalysisProps> = memo(({ stockCode }) => {
  // 当前 Tab
  const [activeTab, setActiveTab] = useState<DeepAnalysisTabKey>('strategy');

  // 业务板块展开状态
  const [expandedSegments, setExpandedSegments] = useState<Record<number, boolean>>({});

  // 数据获取 Hook
  const { data, loading, loadTabData } = useDeepAnalysisData(stockCode);

  // stockCode 变更时重置 UI 状态
  useEffect(() => {
    if (stockCode) {
      setActiveTab('strategy');
      setExpandedSegments({});
    }
  }, [stockCode]);

  // 切换业务板块展开状态
  const toggleSegmentExpansion = useCallback((segmentIndex: number) => {
    setExpandedSegments((prev) => ({
      ...prev,
      [segmentIndex]: !prev[segmentIndex],
    }));
  }, []);

  // Tab 切换回调
  const handleTabChange = useCallback(
    (index: number, tabKey: DeepAnalysisTabKey) => {
      setActiveTab(tabKey);
      loadTabData(tabKey);
    },
    [loadTabData]
  );

  // 获取当前 Tab 的 loading 状态
  const currentLoading = (() => {
    const apiKey = TAB_API_MAP[activeTab];
    return apiKey ? loading[apiKey] : false;
  })();

  return (
    <DeepAnalysisTab
      comprehensiveData={data.comprehensive}
      valueChainData={data.valueChain}
      keyFactorsData={data.keyFactors}
      industryRankData={data.industryRank}
      loading={currentLoading}
      cardBg="white"
      expandedSegments={expandedSegments}
      onToggleSegment={toggleSegmentExpansion}
      activeTab={activeTab}
      onTabChange={handleTabChange}
    />
  );
});

DeepAnalysis.displayName = 'DeepAnalysis';

export default DeepAnalysis;
