'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { isAuthenticated, getEmail } from '@/lib/auth';
import { useIsMobile } from '@/lib/useIsMobile';
import AppHeader from '@/components/AppHeader';
import { useTranslation } from '@/lib/i18n';
import {
  MOCK_TRENDING_TECHNIQUES,
  SKILL_COLORS,
  SKILL_CATEGORIES,
  type TrendingTechnique,
} from '@/lib/mockRankingData';
import {
  fetchRankingData,
  type SkillRanking,
  type ToolRanking,
  type WeeklyTrend,
  type CommunityFavorite,
  type RecentlyAdded,
} from '@/lib/rankingApi';

// ─── Mini Sparkline Chart ────────────────────────────────────

function MiniSparkline({ data, color = '#5c5fbc' }: { data: number[]; color?: string }) {
  if (!data || data.length === 0) return null;

  const max = Math.max(...data, 1);
  const min = Math.min(...data);
  const range = max - min || 1;
  const width = 60;
  const height = 24;
  const padding = 2;

  const points = data.map((val, i) => {
    const x = (i / (data.length - 1)) * (width - padding * 2) + padding;
    const y = height - padding - ((val - min) / range) * (height - padding * 2);
    return `${x},${y}`;
  }).join(' ');

  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <polyline
        points={points}
        fill="none"
        stroke={color}
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// ─── SVG Icons ───────────────────────────────────────────────

function TrophyIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" /><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
      <path d="M4 22h16" /><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20 7 22" />
      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20 17 22" />
      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" />
    </svg>
  );
}

function ToolIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />
    </svg>
  );
}

function TrendingIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="22 7 13.5 15.5 8.5 10.5 2 17" />
      <polyline points="16 7 22 7 22 13" />
    </svg>
  );
}

function StarIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  );
}

function SparkleIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z" />
    </svg>
  );
}

function ChartIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="20" x2="18" y2="10" /><line x1="12" y1="20" x2="12" y2="4" /><line x1="6" y1="20" x2="6" y2="14" />
    </svg>
  );
}

// ─── Stacked Bar Chart (SVG) ──────────────────────────────────

const CHART_COLORS = [
  '#5c5fbc', '#e67e22', '#27ae60', '#e74c3c', '#3498db',
  '#9b59b6', '#f39c12', '#1abc9c', '#e91e63', '#00bcd4',
];

function WeeklyTrendsChart({ data, skillRankings }: { data: WeeklyTrend[]; skillRankings: SkillRanking[] }) {
  const { t } = useTranslation();
  if (!data || data.length === 0) {
    return <div style={{ padding: '40px', textAlign: 'center', color: '#999' }}>{t('ranking.noData')}</div>;
  }

  // Build slug→color map from actual rankings
  const colorMap: Record<string, string> = {};
  skillRankings.forEach((s, i) => {
    colorMap[s.slug] = CHART_COLORS[i % CHART_COLORS.length];
  });

  // Collect all skill slugs present in data
  const allSlugs = Array.from(new Set(data.flatMap(d => Object.keys(d.skills))));

  const maxTotal = Math.max(...data.map(d => Object.values(d.skills).reduce((a, b) => a + b, 0)), 1);
  const chartH = 220;
  const leftMargin = 40;
  const rightMargin = 20;
  const containerWidth = 1000; // Target container width

  // Calculate bar width to fill container
  const availableWidth = containerWidth - leftMargin - rightMargin;
  let barW: number;
  let gap: number;

  if (data.length <= 7) {
    // This Week: fill the container
    gap = 20;
    barW = (availableWidth - gap * (data.length - 1)) / data.length;
  } else if (data.length <= 12) {
    // 12 weeks: medium bars
    gap = 12;
    barW = Math.min(60, (availableWidth - gap * (data.length - 1)) / data.length);
  } else if (data.length <= 30) {
    // This Month: narrower bars
    gap = 4;
    barW = Math.max(20, (availableWidth - gap * (data.length - 1)) / data.length);
  } else {
    // More data: very narrow
    gap = 2;
    barW = 16;
  }

  const totalW = data.length * (barW + gap) - gap;
  const svgWidth = Math.max(totalW + leftMargin + rightMargin, containerWidth);

  return (
    <div style={{ overflowX: 'auto', paddingBottom: '8px' }}>
      <svg width={svgWidth} height={chartH + 40} style={{ display: 'block', minWidth: '100%' }}>
        {/* Y-axis labels */}
        {[0, 0.25, 0.5, 0.75, 1].map(frac => {
          const y = chartH - frac * chartH + 10;
          const val = Math.round(frac * maxTotal);
          return (
            <g key={frac}>
              <text x="30" y={y + 4} textAnchor="end" fill="#999" fontSize="11">{val}</text>
              <line x1="36" y1={y} x2={totalW + leftMargin + 10} y2={y} stroke="#eee" strokeWidth="1" />
            </g>
          );
        })}
        {/* Bars */}
        {data.map((item, wi) => {
          const x = wi * (barW + gap) + leftMargin;
          let cumY = chartH + 10;
          return (
            <g key={`${item.week}-${wi}`}>
              {allSlugs.map(sk => {
                const v = item.skills[sk] || 0;
                const h = (v / maxTotal) * chartH;
                cumY -= h;
                const color = colorMap[sk] || CHART_COLORS[allSlugs.indexOf(sk) % CHART_COLORS.length];
                return (
                  <rect key={sk} x={x} y={cumY} width={barW} height={h} fill={color} rx="2" opacity="0.85" />
                );
              })}
              {/* Show all labels for <= 12 data points, otherwise sample */}
              {(data.length <= 12 || wi % Math.ceil(data.length / 12) === 0 || wi === data.length - 1) && (
                <text x={x + barW / 2} y={chartH + 28} textAnchor="middle" fill="#999" fontSize="10">{item.week}</text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

// ─── Skill Leaderboard Row ──────────────────────────────────

function SkillRow({ skill, isMobile }: { skill: SkillRanking; isMobile: boolean }) {
  const { t } = useTranslation();
  const color = CHART_COLORS[(skill.rank - 1) % CHART_COLORS.length];
  const trendColor = skill.trend >= 0 ? '#27ae60' : '#e74c3c';
  const trendArrow = skill.trend >= 0 ? '↑' : '↓';

  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      padding: isMobile ? '12px 8px' : '14px 16px',
      borderBottom: '1px solid #f0f0f0',
      gap: isMobile ? '8px' : '16px',
      transition: 'background 0.15s',
    }}
      onMouseEnter={e => (e.currentTarget.style.background = '#fafafa')}
      onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
    >
      <div style={{ width: '32px', fontSize: '16px', fontWeight: 700, color: skill.rank <= 3 ? '#5c5fbc' : '#888', textAlign: 'center', flexShrink: 0 }}>
        {skill.rank}.
      </div>
      <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: color, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: '14px', fontWeight: 600, color: '#1a1a2e', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {skill.name}
        </div>
        <div style={{ fontSize: '12px', color: '#999', marginTop: '2px' }}>
          {t('ranking.byProvider', { provider: skill.provider })}
        </div>
      </div>
      {!isMobile && skill.history && skill.history.length > 0 && (
        <div style={{ flexShrink: 0 }}>
          <MiniSparkline data={skill.history} color={color} />
        </div>
      )}
      {!isMobile && (
        <div style={{ textAlign: 'right', flexShrink: 0, minWidth: '100px' }}>
          <div style={{ fontSize: '14px', fontWeight: 600, color: '#333' }}>{skill.weeklyInvocations}</div>
          <div style={{ fontSize: '12px', color: trendColor, fontWeight: 500, marginTop: '2px' }}>
            {trendArrow}{Math.abs(skill.trend)}%
          </div>
        </div>
      )}
      {isMobile && (
        <div style={{ fontSize: '12px', color: trendColor, fontWeight: 500, flexShrink: 0 }}>
          {trendArrow}{Math.abs(skill.trend)}%
        </div>
      )}
    </div>
  );
}

// ─── Tool Row ────────────────────────────────────────────────

function ToolRow({ tool, isMobile }: { tool: ToolRanking; isMobile: boolean }) {
  const { t } = useTranslation();
  const trendColor = tool.trend >= 0 ? '#27ae60' : '#e74c3c';
  const trendArrow = tool.trend >= 0 ? '↑' : '↓';

  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      padding: isMobile ? '12px 8px' : '14px 16px',
      borderBottom: '1px solid #f0f0f0',
      gap: isMobile ? '8px' : '16px',
      transition: 'background 0.15s',
    }}
      onMouseEnter={e => (e.currentTarget.style.background = '#fafafa')}
      onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
    >
      <div style={{ width: '32px', fontSize: '16px', fontWeight: 700, color: tool.rank <= 3 ? '#5c5fbc' : '#888', textAlign: 'center', flexShrink: 0 }}>
        {tool.rank}.
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: '14px', fontWeight: 600, color: '#1a1a2e', fontFamily: 'monospace' }}>
          {tool.name}
        </div>
        <div style={{ fontSize: '12px', color: '#999', marginTop: '2px' }}>
          {t('ranking.totalCalls', { count: tool.totalCalls.toLocaleString(), time: tool.avgResponseTime })}
        </div>
      </div>
      {/* Sparkline */}
      {!isMobile && tool.history && tool.history.length > 0 && (
        <div style={{ flexShrink: 0 }}>
          <MiniSparkline data={tool.history} color="#3498db" />
        </div>
      )}
      {/* Success rate bar */}
      <div style={{ flexShrink: 0, width: isMobile ? '70px' : '130px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
          <span style={{ color: '#999' }}>{t('ranking.succLabel')}</span>
          <span style={{ fontWeight: 600, color: '#333' }}>{tool.successRate}%</span>
        </div>
        <div style={{ height: '4px', background: '#eee', borderRadius: '2px', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${tool.successRate}%`, background: tool.successRate >= 90 ? '#27ae60' : tool.successRate >= 80 ? '#f39c12' : '#e74c3c', borderRadius: '2px' }} />
        </div>
      </div>
    </div>
  );
}

// ─── Technique Card ─────────────────────────────────────────

function TechniqueCard({ technique }: { technique: TrendingTechnique }) {
  const { t } = useTranslation();
  return (
    <div style={{
      background: '#fff',
      borderRadius: '12px',
      border: '1px solid #eee',
      padding: '20px',
      transition: 'box-shadow 0.15s',
    }}
      onMouseEnter={e => (e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.08)')}
      onMouseLeave={e => (e.currentTarget.style.boxShadow = 'none')}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
        <div style={{ fontSize: '15px', fontWeight: 600, color: '#1a1a2e' }}>{technique.title}</div>
        <span style={{ fontSize: '11px', fontWeight: 500, color: '#5c5fbc', background: '#ededf7', padding: '2px 8px', borderRadius: '4px', flexShrink: 0, marginLeft: '8px' }}>
          {technique.category}
        </span>
      </div>
      <div style={{ fontSize: '13px', color: '#666', marginBottom: '12px', lineHeight: 1.5 }}>
        {technique.description}
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', marginBottom: '12px' }}>
        {technique.steps.map((step, i) => (
          <span key={i} style={{
            fontSize: '11px',
            color: '#555',
            background: '#f5f5f5',
            padding: '3px 8px',
            borderRadius: '4px',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '4px',
          }}>
            <span style={{ fontWeight: 600, color: '#5c5fbc' }}>{i + 1}</span>
            {step}
          </span>
        ))}
      </div>
      <div style={{ fontSize: '12px', color: '#999' }}>
        {t('ranking.usedTimes', { count: technique.usageCount })}
      </div>
    </div>
  );
}

// ─── Section Header ─────────────────────────────────────────

function SectionHeader({ icon, title, subtitle }: { icon: React.ReactNode; title: string; subtitle?: string }) {
  return (
    <div style={{ marginBottom: '16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
        <span style={{ color: '#5c5fbc', display: 'flex' }}>{icon}</span>
        <span style={{ fontSize: '18px', fontWeight: 700, color: '#1a1a2e' }}>{title}</span>
      </div>
      {subtitle && <div style={{ fontSize: '13px', color: '#999', marginTop: '4px' }}>{subtitle}</div>}
    </div>
  );
}

// ─── Time Range Selector ──────────────────────────────────

function TimeRangeSelector({ value, onChange }: { value: string; onChange: (v: string) => void }) {
  const { t } = useTranslation();
  const options: { key: string; label: string }[] = [
    { key: 'This Week', label: t('ranking.timeRangeWeek') },
    { key: 'This Month', label: t('ranking.timeRangeMonth') },
    { key: 'All Time', label: t('ranking.timeRangeAll') },
  ];
  return (
    <div style={{ display: 'flex', gap: '4px', background: '#f5f5f5', borderRadius: '8px', padding: '3px' }}>
      {options.map(opt => (
        <button
          key={opt.key}
          onClick={() => onChange(opt.key)}
          style={{
            padding: '6px 14px',
            border: 'none',
            borderRadius: '6px',
            fontSize: '13px',
            fontWeight: 500,
            cursor: 'pointer',
            background: value === opt.key ? '#fff' : 'transparent',
            color: value === opt.key ? '#333' : '#999',
            boxShadow: value === opt.key ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',
            transition: 'all 0.15s',
          }}
        >
          {opt.label}
        </button>
      ))}
    </div>
  );
}

// ─── Legend ──────────────────────────────────────────────────

function ChartLegend({ skillRankings }: { skillRankings?: SkillRanking[] }) {
  if (!skillRankings || skillRankings.length === 0) return null;

  const legendItems = skillRankings.slice(0, 10).map((skill, i) => ({
    slug: skill.slug,
    name: skill.name,
    color: CHART_COLORS[i % CHART_COLORS.length],
  }));

  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', marginTop: '8px' }}>
      {legendItems.map(({ slug, name, color }) => (
        <div key={slug} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
          <div style={{ width: '10px', height: '10px', borderRadius: '2px', background: color }} />
          <span style={{ fontSize: '12px', color: '#666' }}>{name}</span>
        </div>
      ))}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// ─── Main Page ────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════

export default function RankingPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const isMobile = useIsMobile();
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [timeRange, setTimeRange] = useState('This Week');
  const [settingsOpen, setSettingsOpen] = useState(false);

  // Real data state
  const [skillRankings, setSkillRankings] = useState<SkillRanking[]>([]);
  const [toolRankings, setToolRankings] = useState<ToolRanking[]>([]);
  const [weeklyTrends, setWeeklyTrends] = useState<WeeklyTrend[]>([]);
  const [communityFavorites, setCommunityFavorites] = useState<CommunityFavorite[]>([]);
  const [recentlyAdded, setRecentlyAdded] = useState<RecentlyAdded[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch ranking data based on time range
  const loadRankingData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      // Map time range to days parameter
      let days = 7; // This Week
      if (timeRange === 'This Month') days = 30;
      else if (timeRange === 'All Time') days = 365;

      const data = await fetchRankingData(days);
      setSkillRankings(data.skillRankings);
      setToolRankings(data.toolRankings);
      setWeeklyTrends(data.weeklyTrends);
      setCommunityFavorites(data.communityFavorites);
      setRecentlyAdded(data.recentlyAdded);
    } catch (err) {
      console.error('Failed to load ranking data:', err);
      setError(err instanceof Error ? err.message : t('ranking.loadFailed'));
    } finally {
      setLoading(false);
    }
  }, [timeRange, t]);

  useEffect(() => {
    if (!isAuthenticated()) {
      router.replace(`/login?redirect=${encodeURIComponent(window.location.pathname + window.location.search)}`);
      return;
    }
    setUserEmail(getEmail());
    loadRankingData();
  }, [router, loadRankingData]);

  const handleLogout = async () => {
    const { logout } = await import('@/lib/auth');
    await logout();
    router.replace('/login');
  };

  return (
    <div style={{ minHeight: '100vh', background: '#f8f9fa' }}>
      <AppHeader
        activePage="ranking"
        email={userEmail}
        isMobile={isMobile}
        onSettings={() => setSettingsOpen(true)}
        onLogout={handleLogout}
      />

      {/* ─── Content ─── */}
      <div style={{ maxWidth: '1100px', margin: '0 auto', padding: isMobile ? '20px 16px' : '32px 40px' }}>

        {/* Page header */}
        <div style={{ marginBottom: '32px' }}>
          <h1 style={{ fontSize: isMobile ? '22px' : '28px', fontWeight: 700, color: '#1a1a2e', margin: 0 }}>
            {t('ranking.title')}
          </h1>
          <p style={{ fontSize: '14px', color: '#999', margin: '8px 0 0 0' }}>
            {t('ranking.subtitle')}
          </p>
        </div>

        {/* Loading State */}
        {loading && (
          <div style={{
            background: '#fff',
            border: '1px solid #eee',
            borderRadius: '10px',
            padding: '40px',
            marginBottom: '24px',
            textAlign: 'center',
          }}>
            <div style={{ fontSize: '14px', color: '#999' }}>{t('ranking.loading')}</div>
          </div>
        )}

        {/* Error State */}
        {error && (
          <div style={{
            background: '#fee',
            border: '1px solid #fcc',
            borderRadius: '10px',
            padding: '14px 18px',
            marginBottom: '24px',
            display: 'flex',
            alignItems: 'flex-start',
            gap: '12px',
          }}>
            <span style={{ fontSize: '20px', flexShrink: 0, lineHeight: 1.4 }}>⚠️</span>
            <div>
              <div style={{ fontSize: '14px', fontWeight: 600, color: '#c00', marginBottom: '4px' }}>
                {t('ranking.errorTitle')}
              </div>
              <div style={{ fontSize: '13px', color: '#900', lineHeight: 1.6 }}>
                {error}
              </div>
            </div>
          </div>
        )}

        {/* Empty State Notice */}
        {!loading && !error && skillRankings.length === 0 && (
          <div style={{
            background: '#f0f9ff',
            border: '1px solid #bae6fd',
            borderRadius: '10px',
            padding: '14px 18px',
            marginBottom: '24px',
            display: 'flex',
            alignItems: 'flex-start',
            gap: '12px',
          }}>
            <span style={{ fontSize: '20px', flexShrink: 0, lineHeight: 1.4 }}>ℹ️</span>
            <div>
              <div style={{ fontSize: '14px', fontWeight: 600, color: '#0369a1', marginBottom: '4px' }}>
                {t('ranking.noDataTitle')}
              </div>
              <div style={{ fontSize: '13px', color: '#0c4a6e', lineHeight: 1.6 }}>
                {t('ranking.noDataBody')}
              </div>
            </div>
          </div>
        )}

        {/* ─── Section 1: Weekly Trends Chart ─── */}
        {!loading && !error && (
          <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #eee', padding: isMobile ? '16px' : '24px', marginBottom: '24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px', flexWrap: 'wrap', gap: '12px' }}>
              <SectionHeader
                icon={<ChartIcon />}
                title={t('ranking.topSkills')}
                subtitle={
                  timeRange === 'This Week' ? t('ranking.weeklyTrendsThisWeek') :
                  timeRange === 'This Month' ? t('ranking.weeklyTrendsThisMonth') :
                  t('ranking.weeklyTrendsAllTime')
                }
              />
              <TimeRangeSelector value={timeRange} onChange={setTimeRange} />
            </div>
            <WeeklyTrendsChart data={weeklyTrends} skillRankings={skillRankings} />
            {weeklyTrends.length > 0 && <ChartLegend skillRankings={skillRankings} />}
          </div>
        )}

        {/* ─── Section 2: Skill Leaderboard ─── */}
        {!loading && !error && skillRankings.length > 0 && (
          <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #eee', padding: isMobile ? '16px' : '24px', marginBottom: '24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px', flexWrap: 'wrap', gap: '12px' }}>
              <SectionHeader icon={<TrophyIcon />} title={t('ranking.skillLeaderboard')} subtitle={t('ranking.skillLeaderboardSubtitle')} />
              <TimeRangeSelector value={timeRange} onChange={setTimeRange} />
            </div>
            <div>
              {skillRankings.map(s => <SkillRow key={s.rank} skill={s} isMobile={isMobile} />)}
            </div>
          </div>
        )}

        {/* ─── Section 3: Top Call Tools ─── */}
        {!loading && !error && toolRankings.length > 0 && (
          <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #eee', padding: isMobile ? '16px' : '24px', marginBottom: '24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px', flexWrap: 'wrap', gap: '12px' }}>
              <SectionHeader icon={<ToolIcon />} title={t('ranking.topCallTools')} subtitle={t('ranking.topCallToolsSubtitle')} />
              <TimeRangeSelector value={timeRange} onChange={setTimeRange} />
            </div>
            {toolRankings.map(t => <ToolRow key={t.rank} tool={t} isMobile={isMobile} />)}
          </div>
        )}

        {/* ─── Section 4: Trending Techniques (Hidden - Coming Soon) ─── */}
        {false && !loading && !error && (
          <div style={{ marginBottom: '24px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
              <SectionHeader icon={<TrendingIcon />} title={t('ranking.trendingTechniques')} subtitle={t('ranking.trendingTechniquesSubtitle')} />
              <span style={{
                fontSize: '11px',
                fontWeight: 500,
                color: '#f39c12',
                background: '#fef3e2',
                padding: '2px 8px',
                borderRadius: '4px',
                marginLeft: '8px',
              }}>
                {t('ranking.comingSoon')}
              </span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: '16px' }}>
              {MOCK_TRENDING_TECHNIQUES.map(t => <TechniqueCard key={t.title} technique={t} />)}
            </div>
          </div>
        )}

        {/* ─── Bottom row: Community Favorites + Recently Added ─── */}
        {!loading && !error && (
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: '24px', marginBottom: '48px' }}>

            {/* Community Favorites */}
            {communityFavorites.length > 0 && (
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #eee', padding: isMobile ? '16px' : '24px' }}>
                <SectionHeader icon={<StarIcon />} title={t('ranking.communityFavorites')} subtitle={t('ranking.communityFavoritesSubtitle')} />
                {communityFavorites.map((fav, i) => (
                  <div key={fav.slug} style={{
                    display: 'flex', alignItems: 'center', gap: '12px',
                    padding: '10px 0', borderBottom: i < communityFavorites.length - 1 ? '1px solid #f0f0f0' : 'none',
                  }}>
                    <div style={{ width: '28px', fontSize: '14px', fontWeight: 700, color: i < 3 ? '#f39c12' : '#999', textAlign: 'center' }}>
                      {i + 1}.
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: '14px', fontWeight: 600, color: '#1a1a2e', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {fav.name}
                      </div>
                      <div style={{ fontSize: '12px', color: '#999', marginTop: '2px' }}>{t('ranking.repeatUsers', { count: fav.repeatUsers })}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Recently Added */}
            {recentlyAdded.length > 0 && (
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #eee', padding: isMobile ? '16px' : '24px' }}>
                <SectionHeader icon={<SparkleIcon />} title={t('ranking.recentlyAdded')} subtitle={t('ranking.recentlyAddedSubtitle')} />
                {recentlyAdded.map((item, i) => (
                  <div key={item.slug} style={{
                    padding: '10px 0', borderBottom: i < recentlyAdded.length - 1 ? '1px solid #f0f0f0' : 'none',
                  }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div style={{ fontSize: '14px', fontWeight: 600, color: '#1a1a2e' }}>{item.name}</div>
                      <span style={{ fontSize: '11px', color: '#999' }}>{item.addedDate}</span>
                    </div>
                    <div style={{ fontSize: '12px', color: '#888', marginTop: '4px', lineHeight: 1.4 }}>
                      {item.description}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* ─── Settings Modal (lazy import) ─── */}
      {settingsOpen && <SettingsModalWrapper open={settingsOpen} onClose={() => setSettingsOpen(false)} />}
    </div>
  );
}

// Lazy wrapper to avoid circular dep
function SettingsModalWrapper({ open, onClose }: { open: boolean; onClose: () => void }) {
  const SettingsModal = require('@/components/SettingsModal').default;
  return <SettingsModal open={open} onClose={onClose} />;
}
