'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Grid,
  CircularProgress,
  IconButton,
  Tooltip,
} from '@mui/material';
import {
  PieChart as PieChartIcon,
  ShowChart as ShowChartIcon,
  Payments,
  People,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import {
  Chart as ChartJS,
  ArcElement,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip as ChartTooltip,
  Legend,
} from 'chart.js';
import { Pie, Line } from 'react-chartjs-2';
import Header from '@/shared/ui/Header';
import {
  cardStyles,
  colors,
  responsiveText,
} from '@/shared/lib/button-styles';
import { useAuthContext } from '@/features/auth';
import { analyticsApi } from '@/entities/analytics';
import type {
  UserAnalyticsDashboardResponse,
  UserTimelineAnalyticsResponse,
  UserRoiAnalyticsResponse,
  UserChannelAnalyticsResponse,
} from '@/entities/analytics';

// Chart.js 등록
ChartJS.register(
  ArcElement,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  ChartTooltip,
  Legend
);

export default function AnalyticsPage() {
  const { user } = useAuthContext();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [dashboardData, setDashboardData] = useState<UserAnalyticsDashboardResponse | null>(null);
  const [timelineData, setTimelineData] = useState<UserTimelineAnalyticsResponse | null>(null);
  const [roiData, setRoiData] = useState<UserRoiAnalyticsResponse | null>(null);
  const [channelData, setChannelData] = useState<UserChannelAnalyticsResponse | null>(null);
  const [lastUpdate, setLastUpdate] = useState<Date>(new Date());
  const [updateText, setUpdateText] = useState('방금 전');

  // Analytics 데이터 로드 함수
  const fetchAnalytics = async (forceRefresh = false) => {
    try {
      if (forceRefresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }

      // 항상 store_001로 고정하여 Analytics 조회
      const userId = 'store_001';

      // 병렬로 모든 Analytics API 호출
      const [dashboard, timeline, roi, channels] = await Promise.all([
        analyticsApi.getUserAnalytics(userId, { refresh: forceRefresh }),
        analyticsApi.getUserTimelineAnalytics(userId, { interval: 'hourly', refresh: forceRefresh }),
        analyticsApi.getUserRoiAnalytics(userId, { includeProjection: true, refresh: forceRefresh }),
        analyticsApi.getUserChannelAnalytics(userId, { sortBy: 'participants', order: 'desc', refresh: forceRefresh }),
      ]);

      console.log('📊 [Analytics] Timeline API response:', {
        totalEvents: timeline.totalEvents,
        interval: timeline.interval,
        dataPointsCount: timeline.dataPoints.length,
        dataSource: timeline.dataSource,
        period: timeline.period,
      });

      setDashboardData(dashboard);
      setTimelineData(timeline);
      setRoiData(roi);
      setChannelData(channels);
      setLastUpdate(new Date());
    } catch (error: any) {
      console.error('❌ Analytics 데이터 로드 실패:', error);

      // 404 또는 400 에러는 아직 Analytics 데이터가 없는 경우
      if (error.response?.status === 404 || error.response?.status === 400) {
        // 에러 상태를 설정하지 않고 빈 데이터로 표시
      } else {
        // 다른 에러는 에러로 처리
        console.error('❌ 예상치 못한 에러:', error);
      }
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 새로고침 핸들러
  const handleRefresh = () => {
    fetchAnalytics(true);
  };

  // 초기 데이터 로드
  useEffect(() => {
    fetchAnalytics(false);
  }, [user?.userId]);

  // 업데이트 시간 표시 갱신
  useEffect(() => {
    const updateInterval = setInterval(() => {
      const now = new Date();
      const diff = Math.floor((now.getTime() - lastUpdate.getTime()) / 1000);

      let text;
      if (diff < 60) {
        text = '방금 전';
      } else if (diff < 3600) {
        text = `${Math.floor(diff / 60)}분 전`;
      } else {
        text = `${Math.floor(diff / 3600)}시간 전`;
      }

      setUpdateText(text);
    }, 30000); // 30초마다 갱신

    return () => {
      clearInterval(updateInterval);
    };
  }, [lastUpdate]);

  // 로딩 중 표시
  if (loading) {
    return (
      <>
        <Header title="성과 분석" showBack={true} showMenu={false} showProfile={true} />
        <Box
          sx={{
            pt: { xs: 7, sm: 8 },
            pb: { xs: 4, sm: 10 },
            bgcolor: colors.gray[50],
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <CircularProgress />
        </Box>
      </>
    );
  }

  // 데이터 없음 표시
  if (!dashboardData || !timelineData || !roiData || !channelData) {
    return (
      <>
        <Header title="성과 분석" showBack={true} showMenu={false} showProfile={true} />
        <Box
          sx={{
            pt: { xs: 7, sm: 8 },
            pb: { xs: 4, sm: 10 },
            bgcolor: colors.gray[50],
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Typography variant="body1" color="text.secondary">
            Analytics 데이터를 불러올 수 없습니다.
          </Typography>
        </Box>
      </>
    );
  }

  // API 데이터에서 필요한 값 추출
  const summary = {
    participants: 1234, // 고정값으로 설정
    participantsDelta: dashboardData.overallSummary.participantsDelta,
    totalCost: roiData.overallInvestment.total,
    expectedRevenue: roiData.overallRevenue.total,
    roi: roiData.overallRoi.roiPercentage,
    targetRoi: dashboardData.overallSummary.targetRoi,
  };

  // 채널별 성과 데이터 변환 (Channels API 상세 데이터 활용)
  const channelColors = ['#F472B6', '#60A5FA', '#FB923C', '#A78BFA', '#34D399'];
  const channelPerformance = channelData.channels.map((channel, index) => {
    // 참여자 수를 기준으로 비율 계산, 참여자가 없으면 노출 수(impressions) 기준으로 계산
    const totalParticipants = dashboardData.overallSummary.participants;
    const totalImpressions = channelData.channels.reduce((sum, ch) => sum + ch.metrics.impressions, 0);

    let percentage = 0;
    let displayValue = 0;

    if (totalParticipants > 0) {
      // 참여자가 있으면 참여자 수 기준
      percentage = Math.round((channel.metrics.participants / totalParticipants) * 100);
      displayValue = channel.metrics.participants;
    } else if (totalImpressions > 0) {
      // 참여자가 없으면 노출 수 기준
      percentage = Math.round((channel.metrics.impressions / totalImpressions) * 100);
      displayValue = channel.metrics.impressions;
    }

    // 채널명 정리 - 안전한 방식으로 처리
    let cleanChannelName = channel.channelName;

    // 백엔드에서 UTF-8로 전달되는 경우 그대로 사용
    // URL 인코딩된 경우에만 디코딩 시도
    if (cleanChannelName && cleanChannelName.includes('%')) {
      try {
        cleanChannelName = decodeURIComponent(cleanChannelName);
      } catch (e) {
        // 디코딩 실패 시 원본 사용
      }
    }

    return {
      channel: cleanChannelName || '알 수 없는 채널',
      channelType: channel.channelType,
      participants: channel.metrics.participants,
      views: channel.metrics.views,
      clicks: channel.metrics.clicks,
      impressions: channel.metrics.impressions,
      conversions: channel.metrics.conversions,
      engagementRate: channel.performance.engagementRate,
      conversionRate: channel.performance.conversionRate,
      clickThroughRate: channel.performance.clickThroughRate,
      roi: channel.costs.roi,
      costPerAcquisition: channel.costs.costPerAcquisition,
      percentage,
      displayValue, // 차트에 표시할 값 (participants 또는 impressions)
      color: channelColors[index % channelColors.length],
    };
  });

  // 채널 데이터 유효성 확인 (participants 또는 impressions가 있으면 표시)
  const hasChannelData = channelPerformance.length > 0 &&
                         channelPerformance.some(ch => ch.participants > 0 || ch.impressions > 0);

  // 시간대별 데이터 집계 (0시~23시, 날짜별 평균) - API 추가 지표 활용

  // 0시~23시까지 24개 시간대 초기화 (합계와 카운트 추적)
  const hourlyData = Array.from({ length: 24 }, (_, hour) => ({
    hour,
    totalParticipants: 0,
    totalViews: 0,
    totalEngagement: 0,
    totalConversions: 0,
    count: 0,
    participants: 0, // 최종 평균값
    views: 0,
    engagement: 0,
    conversions: 0,
  }));

  // 각 데이터 포인트를 시간대별로 집계
  timelineData.dataPoints.forEach((point) => {
    const date = new Date(point.timestamp);
    const hour = date.getHours();
    if (hour >= 0 && hour < 24) {
      hourlyData[hour].totalParticipants += point.participants;
      hourlyData[hour].totalViews += point.views;
      hourlyData[hour].totalEngagement += point.engagement;
      hourlyData[hour].totalConversions += point.conversions;
      hourlyData[hour].count += 1;
    }
  });

  // 시간대별 평균 계산
  hourlyData.forEach((data) => {
    if (data.count > 0) {
      data.participants = Math.round(data.totalParticipants / data.count);
      data.views = Math.round(data.totalViews / data.count);
      data.engagement = Math.round(data.totalEngagement / data.count);
      data.conversions = Math.round(data.totalConversions / data.count);
    }
  });

  // 시간대별 데이터 유효성 확인
  const hasTimelineData = hourlyData.some(h => h.participants > 0 || h.views > 0 || h.engagement > 0);

  console.log('📊 [Analytics] Hourly data aggregation:', {
    totalDataPoints: timelineData.dataPoints.length,
    hasData: hasTimelineData,
    sampleHours: hourlyData.slice(8, 12).map(h => ({
      hour: h.hour,
      participants: h.participants,
      views: h.views,
      engagement: h.engagement,
    })),
  });

  // 피크 시간 찾기 (hourlyData에서 최대 참여자 수를 가진 시간대)
  const peakHour = hourlyData.reduce((max, current) =>
    current.participants > max.participants ? current : max
  , hourlyData[0]);

  // 시간대별 성과 데이터 (피크 시간 정보)
  const timePerformance = {
    peakTime: `${peakHour.hour}시`,
    peakParticipants: peakHour.participants,
    peakViews: peakHour.views,
    peakEngagement: peakHour.engagement,
    avgPerHour: Math.round(
      hourlyData.reduce((sum, data) => sum + data.participants, 0) / 24
    ),
    avgViewsPerHour: Math.round(
      hourlyData.reduce((sum, data) => sum + data.views, 0) / 24
    ),
  };

  // ROI 상세 데이터
  const roiDetail = {
    totalCost: roiData.overallInvestment.total,
    prizeCost: roiData.overallInvestment.prizeCost, // ✅ 백엔드 prizeCost 필드 사용
    channelCost: roiData.overallInvestment.distribution,
    otherCost: roiData.overallInvestment.contentCreation + roiData.overallInvestment.operation, // ✅ 그 외 비용
    expectedRevenue: roiData.overallRevenue.total,
    salesIncrease: roiData.overallRevenue.total, // ✅ 변경: total 사용
    newCustomerLTV: roiData.overallRevenue.newCustomerRevenue, // ✅ 변경: newCustomerRevenue 사용
  };

  // 참여자 프로필 데이터 (임시로 Mock 데이터 사용 - API에 없음)
  const participantProfile = {
    age: [
      { label: '20대', percentage: 35 },
      { label: '30대', percentage: 40 },
      { label: '40대', percentage: 25 },
    ],
    gender: [
      { label: '여성', percentage: 60 },
      { label: '남성', percentage: 40 },
    ],
  };

  return (
    <>
      <Header title="성과 분석" showBack={true} showMenu={false} showProfile={true} />
      <Box
        sx={{
          pt: { xs: 7, sm: 8 },
          pb: { xs: 4, sm: 10 },
          bgcolor: colors.gray[50],
          minHeight: '100vh',
        }}
      >
        <Container maxWidth="lg" sx={{ pt: { xs: 4, sm: 8 }, pb: { xs: 4, sm: 6 }, px: { xs: 3, sm: 6, md: 10 } }}>
        {/* Title with Real-time Indicator */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            mb: { xs: 4, sm: 10 },
          }}
        >
          <Typography variant="h5" sx={{ ...responsiveText.h3 }}>
            📊 요약 (실시간)
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 1, sm: 2 } }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 0.5, sm: 1 } }}>
              <Box
                sx={{
                  width: { xs: 6, sm: 8 },
                  height: { xs: 6, sm: 8 },
                  borderRadius: '50%',
                  bgcolor: colors.mint,
                  animation: 'pulse 2s infinite',
                  '@keyframes pulse': {
                    '0%, 100%': { opacity: 1 },
                    '50%': { opacity: 0.3 },
                  },
                }}
              />
              <Typography variant="caption" sx={{ ...responsiveText.body2 }}>
                {updateText}
              </Typography>
            </Box>
            <Tooltip title="데이터 새로고침">
              <IconButton
                onClick={handleRefresh}
                disabled={refreshing}
                size="small"
                sx={{
                  color: colors.gray[700],
                  '&:hover': {
                    bgcolor: colors.gray[100],
                    color: colors.mint,
                  },
                  '&.Mui-disabled': {
                    color: colors.gray[300],
                  },
                }}
              >
                <RefreshIcon
                  sx={{
                    fontSize: { xs: 20, sm: 24 },
                    animation: refreshing ? 'spin 1s linear infinite' : 'none',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' },
                    },
                  }}
                />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {/* Summary KPI Cards */}
        <Grid container spacing={{ xs: 2, sm: 6 }} sx={{ mb: { xs: 4, sm: 10 } }}>
          <Grid item xs={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.purpleLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 6 }, px: { xs: 2, sm: 4 } }}>
                <Typography
                  variant="body2"
                  sx={{
                    mb: { xs: 1, sm: 2 },
                    color: 'rgba(255, 255, 255, 0.9)',
                    fontWeight: 500,
                    fontSize: { xs: '0.75rem', sm: '1rem' },
                  }}
                >
                  참여자 수
                </Typography>
                <Typography variant="h3" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '1.5rem', sm: '2.5rem' } }}>
                  {summary.participants}
                </Typography>
                <Typography
                  variant="caption"
                  sx={{ color: 'rgba(255, 255, 255, 0.8)', fontWeight: 600, fontSize: { xs: '0.6875rem', sm: '0.875rem' } }}
                >
                  ↑ {summary.participantsDelta}명
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.orange} 0%, ${colors.orangeLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 6 }, px: { xs: 2, sm: 4 } }}>
                <Typography
                  variant="body2"
                  sx={{
                    mb: { xs: 1, sm: 2 },
                    color: 'rgba(255, 255, 255, 0.9)',
                    fontWeight: 500,
                    fontSize: { xs: '0.75rem', sm: '1rem' },
                  }}
                >
                  총 비용
                </Typography>
                <Typography variant="h3" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '1.5rem', sm: '2.5rem' } }}>
                  {Math.floor(summary.totalCost / 10000)}만
                </Typography>
                <Typography
                  variant="caption"
                  sx={{ color: 'rgba(255, 255, 255, 0.8)', fontWeight: 600, fontSize: { xs: '0.6875rem', sm: '0.875rem' } }}
                >
                  경품+채널
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.mint} 0%, ${colors.mintLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 6 }, px: { xs: 2, sm: 4 } }}>
                <Typography
                  variant="body2"
                  sx={{
                    mb: { xs: 1, sm: 2 },
                    color: 'rgba(255, 255, 255, 0.9)',
                    fontWeight: 500,
                    fontSize: { xs: '0.75rem', sm: '1rem' },
                  }}
                >
                  예상 수익
                </Typography>
                <Typography variant="h3" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '1.5rem', sm: '2.5rem' } }}>
                  {Math.floor(summary.expectedRevenue / 10000)}만
                </Typography>
                <Typography
                  variant="caption"
                  sx={{ color: 'rgba(255, 255, 255, 0.8)', fontWeight: 600, fontSize: { xs: '0.6875rem', sm: '0.875rem' } }}
                >
                  매출+LTV
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.blue} 0%, ${colors.blueLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 6 }, px: { xs: 2, sm: 4 } }}>
                <Typography
                  variant="body2"
                  sx={{
                    mb: { xs: 1, sm: 2 },
                    color: 'rgba(255, 255, 255, 0.9)',
                    fontWeight: 500,
                    fontSize: { xs: '0.75rem', sm: '1rem' },
                  }}
                >
                  ROI
                </Typography>
                <Typography variant="h3" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '1.5rem', sm: '2.5rem' } }}>
                  {summary.roi}%
                </Typography>
                <Typography
                  variant="caption"
                  sx={{ color: 'rgba(255, 255, 255, 0.8)', fontWeight: 600, fontSize: { xs: '0.6875rem', sm: '0.875rem' } }}
                >
                  목표 {summary.targetRoi}%
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Charts Grid */}
        <Grid container spacing={{ xs: 3, sm: 6 }} sx={{ mb: { xs: 4, sm: 10 } }}>
          {/* Channel Performance */}
          <Grid item xs={12} md={6}>
            <Card elevation={0} sx={{ ...cardStyles.default, height: '100%' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6, md: 8 }, height: '100%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 2, sm: 3 }, mb: { xs: 3, sm: 6 } }}>
                  <Box
                    sx={{
                      width: { xs: 32, sm: 40 },
                      height: { xs: 32, sm: 40 },
                      borderRadius: '12px',
                      background: `linear-gradient(135deg, ${colors.pink} 0%, ${colors.pinkLight} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <PieChartIcon sx={{ fontSize: { xs: 20, sm: 24 }, color: 'white' }} />
                  </Box>
                  <Typography variant="h6" sx={{ fontWeight: 700, color: colors.gray[900], fontSize: { xs: '1rem', sm: '1.25rem' } }}>
                    채널별 성과
                  </Typography>
                </Box>

                {/* Pie Chart */}
                <Box
                  sx={{
                    width: '100%',
                    maxWidth: { xs: 200, sm: 300 },
                    mx: 'auto',
                    mb: { xs: 2, sm: 3 },
                    flex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  {hasChannelData ? (
                    <Pie
                      data={{
                        labels: channelPerformance.map((item) => item.channel),
                        datasets: [
                          {
                            data: channelPerformance.map((item) => item.displayValue),
                            backgroundColor: channelPerformance.map((item) => item.color),
                            borderColor: '#fff',
                            borderWidth: 2,
                          },
                        ],
                      }}
                      options={{
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                          legend: {
                            display: false,
                          },
                          tooltip: {
                            callbacks: {
                              label: function (context) {
                                const label = context.label || '';
                                const value = context.parsed || 0;
                                const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
                                const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0';
                                const hasParticipants = channelPerformance.some(ch => ch.participants > 0);
                                const unit = hasParticipants ? '명' : '노출';
                                return `${label}: ${value.toLocaleString()}${unit} (${percentage}%)`;
                              },
                            },
                          },
                        },
                      }}
                    />
                  ) : (
                    <Box sx={{ textAlign: 'center', pt: { xs: 2, sm: 6 }, pb: { xs: 2, sm: 6 } }}>
                      <Typography variant="body2" color="text.secondary" sx={{ fontSize: { xs: '0.875rem', sm: '1rem' } }}>
                        채널별 참여 데이터가 없습니다.
                      </Typography>
                      <Typography variant="caption" color="text.disabled" sx={{ mt: 1, display: 'block', fontSize: { xs: '0.75rem', sm: '0.875rem' } }}>
                        참여자가 발생하면 차트가 표시됩니다.
                      </Typography>
                    </Box>
                  )}
                </Box>

                {/* Legend */}
                {hasChannelData && (
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: { xs: 0.75, sm: 1 } }}>
                    {channelPerformance.map((item) => {
                      const hasParticipants = channelPerformance.some(ch => ch.participants > 0);
                      const unit = hasParticipants ? '명' : '노출';

                      return (
                        <Box
                          key={item.channel}
                          sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
                        >
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Box
                              sx={{
                                width: { xs: 10, sm: 12 },
                                height: { xs: 10, sm: 12 },
                                borderRadius: '50%',
                                bgcolor: item.color,
                              }}
                            />
                            <Typography variant="body2" sx={{ color: colors.gray[700], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                              {item.channel}
                            </Typography>
                          </Box>
                          <Typography variant="body2" sx={{ fontWeight: 600, color: colors.gray[900], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                            {item.percentage}% ({item.displayValue.toLocaleString()}{unit})
                          </Typography>
                        </Box>
                      );
                    })}
                  </Box>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* Time Trend - 임시 주석처리 */}
          {/* <Grid item xs={12} md={6}>
            <Card elevation={0} sx={{ ...cardStyles.default, height: '100%' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6, md: 8 }, height: '100%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 2, sm: 3 }, mb: { xs: 3, sm: 6 } }}>
                  <Box
                    sx={{
                      width: { xs: 32, sm: 40 },
                      height: { xs: 32, sm: 40 },
                      borderRadius: '12px',
                      background: `linear-gradient(135deg, ${colors.blue} 0%, ${colors.blueLight} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <ShowChartIcon sx={{ fontSize: { xs: 20, sm: 24 }, color: 'white' }} />
                  </Box>
                  <Typography variant="h6" sx={{ fontWeight: 700, color: colors.gray[900], fontSize: { xs: '1rem', sm: '1.25rem' } }}>
                    시간대별 참여 추이
                  </Typography>
                </Box>

                <Box
                  sx={{
                    width: '100%',
                    mb: { xs: 2, sm: 3 },
                    flex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    minHeight: { xs: 150, sm: 200 },
                    position: 'relative',
                  }}
                >
                  {!hasTimelineData && (
                    <Box
                      sx={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        textAlign: 'center',
                        color: colors.gray[400],
                      }}
                    >
                      <ShowChartIcon sx={{ fontSize: 48, mb: 2, opacity: 0.3 }} />
                      <Typography variant="body2" sx={{ color: colors.gray[500] }}>
                        시간대별 데이터가 수집되면 차트가 표시됩니다.
                      </Typography>
                    </Box>
                  )}
                  <Line
                    data={{
                      labels: hourlyData.map((item) => `${item.hour}시`),
                      datasets: [
                        {
                          label: '참여자 수',
                          data: hourlyData.map((item) => item.participants),
                          borderColor: hasTimelineData ? colors.blue : `${colors.blue}40`,
                          backgroundColor: hasTimelineData ? `${colors.blue}33` : `${colors.blue}10`,
                          fill: true,
                          tension: 0.4,
                          pointBackgroundColor: hasTimelineData ? colors.blue : `${colors.blue}40`,
                          pointBorderColor: '#fff',
                          pointBorderWidth: 2,
                          pointRadius: 3,
                          pointHoverRadius: 5,
                          yAxisID: 'y',
                        },
                        {
                          label: '조회 수',
                          data: hourlyData.map((item) => item.views),
                          borderColor: hasTimelineData ? colors.mint : `${colors.mint}40`,
                          backgroundColor: hasTimelineData ? `${colors.mint}20` : `${colors.mint}10`,
                          fill: false,
                          tension: 0.4,
                          pointBackgroundColor: hasTimelineData ? colors.mint : `${colors.mint}40`,
                          pointBorderColor: '#fff',
                          pointBorderWidth: 2,
                          pointRadius: 3,
                          pointHoverRadius: 5,
                          yAxisID: 'y',
                        },
                        {
                          label: '참여 활동',
                          data: hourlyData.map((item) => item.engagement),
                          borderColor: hasTimelineData ? colors.orange : `${colors.orange}40`,
                          backgroundColor: hasTimelineData ? `${colors.orange}20` : `${colors.orange}10`,
                          fill: false,
                          tension: 0.4,
                          pointBackgroundColor: hasTimelineData ? colors.orange : `${colors.orange}40`,
                          pointBorderColor: '#fff',
                          pointBorderWidth: 2,
                          pointRadius: 3,
                          pointHoverRadius: 5,
                          yAxisID: 'y',
                        },
                      ],
                    }}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      interaction: {
                        mode: 'index',
                        intersect: false,
                      },
                      plugins: {
                        legend: {
                          display: true,
                          position: 'top',
                          labels: {
                            boxWidth: 12,
                            boxHeight: 12,
                            padding: 10,
                            font: {
                              size: 11,
                            },
                            color: colors.gray[700],
                          },
                        },
                        tooltip: {
                          backgroundColor: colors.gray[900],
                          padding: 12,
                          displayColors: true,
                          callbacks: {
                            label: function (context) {
                              const label = context.dataset.label || '';
                              return `${label}: ${context.parsed.y}`;
                            },
                          },
                        },
                      },
                      scales: {
                        y: {
                          beginAtZero: true,
                          ticks: {
                            color: colors.gray[600],
                            font: {
                              size: 10,
                            },
                          },
                          grid: {
                            color: colors.gray[200],
                          },
                        },
                        x: {
                          ticks: {
                            color: colors.gray[600],
                            font: {
                              size: 10,
                            },
                          },
                          grid: {
                            display: false,
                          },
                        },
                      },
                    }}
                  />
                </Box>

                <Box>
                  <Typography variant="body2" sx={{ mb: 0.5, color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                    피크 시간: {timePerformance.peakTime} (참여 {timePerformance.peakParticipants}명, 조회 {timePerformance.peakViews})
                  </Typography>
                  <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                    평균 시간당: 참여 {timePerformance.avgPerHour}명 / 조회 {timePerformance.avgViewsPerHour}
                  </Typography>
                </Box>
              </CardContent>
            </Card>
          </Grid> */}
        </Grid>

        {/* ROI Detail & Participant Profile */}
        <Grid container spacing={{ xs: 3, sm: 6 }}>
          {/* ROI Detail */}
          <Grid item xs={12} md={6}>
            <Card elevation={0} sx={{ ...cardStyles.default, height: '100%' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6, md: 8 }, height: '100%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 2, sm: 3 }, mb: { xs: 3, sm: 6 } }}>
                  <Box
                    sx={{
                      width: { xs: 32, sm: 40 },
                      height: { xs: 32, sm: 40 },
                      borderRadius: '12px',
                      background: `linear-gradient(135deg, ${colors.orange} 0%, ${colors.orangeLight} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <Payments sx={{ fontSize: { xs: 20, sm: 24 }, color: 'white' }} />
                  </Box>
                  <Typography variant="h6" sx={{ fontWeight: 700, color: colors.gray[900], fontSize: { xs: '1rem', sm: '1.25rem' } }}>
                    ROI 상세
                  </Typography>
                </Box>

                <Box sx={{ display: 'flex', flexDirection: 'column', gap: { xs: 2, sm: 3 } }}>
                  <Box>
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: { xs: 1, sm: 1.5 }, color: colors.gray[900], fontSize: { xs: '0.9375rem', sm: '1rem' } }}>
                      총 비용: {Math.floor(roiDetail.totalCost / 10000)}만원
                    </Typography>
                    <Box sx={{ pl: { xs: 1.5, sm: 2 }, display: 'flex', flexDirection: 'column', gap: { xs: 0.75, sm: 1 } }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          • 경품 비용
                        </Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: colors.gray[900], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          {Math.floor(roiDetail.prizeCost / 10000)}만원
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          • 채널 비용
                        </Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: colors.gray[900], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          {Math.floor(roiDetail.channelCost / 10000)}만원
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          • 그 외
                        </Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: colors.gray[900], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          {Math.floor(roiDetail.otherCost / 10000)}만원
                        </Typography>
                      </Box>
                    </Box>
                  </Box>

                  <Box>
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: { xs: 1, sm: 1.5 }, color: colors.gray[900], fontSize: { xs: '0.9375rem', sm: '1rem' } }}>
                      예상 수익: {Math.floor(roiDetail.expectedRevenue / 10000)}만원
                    </Typography>
                    <Box sx={{ pl: { xs: 1.5, sm: 2 }, display: 'flex', flexDirection: 'column', gap: { xs: 0.75, sm: 1 } }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          • 매출 증가
                        </Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: colors.mint, fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          {Math.floor(roiDetail.salesIncrease / 10000)}만원
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" sx={{ color: colors.gray[600], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          • 신규 고객 LTV
                        </Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: colors.mint, fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                          {Math.floor(roiDetail.newCustomerLTV / 10000)}만원
                        </Typography>
                      </Box>
                    </Box>
                  </Box>

                  <Box>
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: { xs: 1, sm: 1.5 }, color: colors.mint, fontSize: { xs: '0.9375rem', sm: '1rem' } }}>
                      투자대비수익률
                    </Typography>
                    <Box
                      sx={{
                        p: { xs: 2, sm: 2.5 },
                        bgcolor: colors.gray[100],
                        borderRadius: 2,
                        textAlign: 'center',
                      }}
                    >
                      <Typography variant="body2" sx={{ mb: 0.5, color: colors.gray[700], fontSize: { xs: '0.75rem', sm: '0.875rem' } }}>
                        (수익 - 비용) ÷ 비용 × 100
                      </Typography>
                      <Typography variant="body2" sx={{ mb: { xs: 1, sm: 1.5 }, color: colors.gray[600], fontSize: { xs: '0.6875rem', sm: '0.875rem' } }}>
                        ({Math.floor(roiDetail.expectedRevenue / 10000)}만 -{' '}
                        {Math.floor(roiDetail.totalCost / 10000)}만) ÷{' '}
                        {Math.floor(roiDetail.totalCost / 10000)}만 × 100
                      </Typography>
                      <Typography variant="h5" sx={{ fontWeight: 700, color: colors.mint, fontSize: { xs: '1.25rem', sm: '1.5rem' } }}>
                        = {summary.roi}%
                      </Typography>
                    </Box>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </Grid>

          {/* Participant Profile */}
          <Grid item xs={12} md={6}>
            <Card elevation={0} sx={{ ...cardStyles.default, height: '100%' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6, md: 8 }, height: '100%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 2, sm: 3 }, mb: { xs: 3, sm: 6 } }}>
                  <Box
                    sx={{
                      width: { xs: 32, sm: 40 },
                      height: { xs: 32, sm: 40 },
                      borderRadius: '12px',
                      background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.purpleLight} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <People sx={{ fontSize: { xs: 20, sm: 24 }, color: 'white' }} />
                  </Box>
                  <Typography variant="h6" sx={{ fontWeight: 700, color: colors.gray[900], fontSize: { xs: '1rem', sm: '1.25rem' } }}>
                    참여자 프로필
                  </Typography>
                </Box>

                {/* Age Distribution */}
                <Box sx={{ mb: { xs: 3, sm: 4 } }}>
                  <Typography variant="body1" sx={{ fontWeight: 600, mb: { xs: 1.5, sm: 2 }, color: colors.gray[900], fontSize: { xs: '0.9375rem', sm: '1rem' } }}>
                    연령별
                  </Typography>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: { xs: 1.25, sm: 1.5 } }}>
                    {participantProfile.age.map((item) => (
                      <Box key={item.label}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 1, sm: 1.5 } }}>
                          <Typography variant="body2" sx={{ minWidth: { xs: 45, sm: 60 }, color: colors.gray[700], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                            {item.label}
                          </Typography>
                          <Box
                            sx={{
                              flex: 1,
                              height: { xs: 24, sm: 28 },
                              bgcolor: colors.gray[200],
                              borderRadius: 1.5,
                              overflow: 'hidden',
                            }}
                          >
                            <Box
                              sx={{
                                width: `${item.percentage}%`,
                                height: '100%',
                                background: `linear-gradient(135deg, ${colors.blue} 0%, ${colors.blueLight} 100%)`,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'flex-end',
                                pr: { xs: 1, sm: 1.5 },
                              }}
                            >
                              <Typography
                                variant="caption"
                                sx={{ color: 'white', fontWeight: 600, fontSize: { xs: 10, sm: 12 } }}
                              >
                                {item.percentage}%
                              </Typography>
                            </Box>
                          </Box>
                        </Box>
                      </Box>
                    ))}
                  </Box>
                </Box>

                {/* Gender Distribution */}
                <Box>
                  <Typography variant="body1" sx={{ fontWeight: 600, mb: { xs: 1.5, sm: 2 }, color: colors.gray[900], fontSize: { xs: '0.9375rem', sm: '1rem' } }}>
                    성별
                  </Typography>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: { xs: 1.25, sm: 1.5 } }}>
                    {participantProfile.gender.map((item) => (
                      <Box key={item.label}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: { xs: 1, sm: 1.5 } }}>
                          <Typography variant="body2" sx={{ minWidth: { xs: 45, sm: 60 }, color: colors.gray[700], fontSize: { xs: '0.8125rem', sm: '0.875rem' } }}>
                            {item.label}
                          </Typography>
                          <Box
                            sx={{
                              flex: 1,
                              height: { xs: 24, sm: 28 },
                              bgcolor: colors.gray[200],
                              borderRadius: 1.5,
                              overflow: 'hidden',
                            }}
                          >
                            <Box
                              sx={{
                                width: `${item.percentage}%`,
                                height: '100%',
                                background: `linear-gradient(135deg, ${colors.pink} 0%, ${colors.pinkLight} 100%)`,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'flex-end',
                                pr: { xs: 1, sm: 1.5 },
                              }}
                            >
                              <Typography
                                variant="caption"
                                sx={{ color: 'white', fontWeight: 600, fontSize: { xs: 10, sm: 12 } }}
                              >
                                {item.percentage}%
                              </Typography>
                            </Box>
                          </Box>
                        </Box>
                      </Box>
                    ))}
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
      </Box>
    </>
  );
}
