<template>
  <div v-if="canViewDashboard" class="dashboard-container">
    <div class="dashboard-header">
      <h1>环境监测系统仪表盘</h1>
      <div class="dashboard-actions">
        <el-button type="primary" :icon="Refresh" @click="refreshAllData">刷新全部</el-button>
        <el-button type="success" :icon="Setting">设置</el-button>
      </div>
    </div>
    <div class="dashboard-grid">
      <!-- Top Row: Key Stats -->
      <el-card shadow="hover" class="grid-item kpi-card" v-for="kpi in kpiStats" :key="kpi.title">
        <div class="kpi-content">
          <div class="kpi-icon" :style="{ backgroundColor: kpi.color }">
            <component :is="kpi.icon" />
          </div>
          <div class="kpi-details">
            <div class="kpi-title">{{ kpi.title }}</div>
            <div class="kpi-value">
              <span v-if="!loading.stats">{{ kpi.value }}</span>
              <span v-else class="loading-text">--</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- AQI Distribution Chart -->
      <el-card shadow="never" class="grid-item chart-card aqi-distribution" :body-style="{ padding: '16px', height: 'calc(100% - 53px)' }">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><DataAnalysis /></el-icon>
            <span>AQI 级别分布</span>
            <div class="card-actions">
              <el-tooltip content="查看详细数据" placement="top">
                <el-button type="success" :icon="View" circle size="small" @click="showAqiDetailData" />
              </el-tooltip>
              <el-tooltip content="刷新数据" placement="top">
                <el-button type="primary" :icon="Refresh" circle size="small" @click="refreshAqiData" :loading="loading.aqi" />
              </el-tooltip>
            </div>
          </div>
        </template>
        <div ref="aqiDistributionChartRef" class="chart" v-if="!loading.aqi" />
        <el-skeleton :rows="5" animated v-else />
      </el-card>

      <!-- Task Status Chart -->
      <el-card shadow="never" class="grid-item chart-card task-status" :body-style="{ padding: '16px', height: 'calc(100% - 53px)' }">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><Finished /></el-icon>
            <span>任务状态分布</span>
            <div class="card-actions">
              <el-tooltip content="查看详细数据" placement="top">
                <el-button type="success" :icon="View" circle size="small" @click="showTaskDetailData" />
              </el-tooltip>
              <el-tooltip content="刷新数据" placement="top">
                <el-button type="primary" :icon="Refresh" circle size="small" @click="refreshTaskData" :loading="loading.tasks" />
              </el-tooltip>
            </div>
          </div>
        </template>
        <div ref="taskStatusChartRef" class="chart" v-if="!loading.tasks" />
        <el-skeleton :rows="5" animated v-else />
      </el-card>

      <!-- Exceedance Trend Chart -->
      <el-card shadow="never" class="grid-item chart-card exceedance-trend" :body-style="{ padding: '16px', height: 'calc(100% - 53px)' }">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><TrendCharts /></el-icon>
            <span>月度超标趋势</span>
            <div class="card-actions">
              <el-tooltip content="查看详细数据" placement="top">
                <el-button type="success" :icon="View" circle size="small" @click="showTrendDetailData" />
              </el-tooltip>
              <el-tooltip content="刷新数据" placement="top">
                <el-button type="primary" :icon="Refresh" circle size="small" @click="refreshTrendData" :loading="loading.trend" />
              </el-tooltip>
            </div>
          </div>
        </template>
        <div ref="exceedanceTrendChartRef" class="chart" v-if="!loading.trend" />
        <el-skeleton :rows="8" animated v-else />
      </el-card>

      <!-- Pollutant Trend Chart -->
      <el-card shadow="never" class="grid-item chart-card pollutant-trend" :body-style="{ padding: '16px', height: 'calc(100% - 53px)' }">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><DataLine /></el-icon>
            <span>污染物趋势</span>
            <div class="card-actions">
              <el-select v-model="selectedPollutantType" placeholder="选择污染物" size="small" style="width: 120px; margin-right: 10px;" @change="handlePollutantTypeChange">
                <el-option v-for="item in pollutantTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-tooltip content="查看详细数据" placement="top">
                <el-button type="success" :icon="View" circle size="small" @click="showPollutantDetailData" />
              </el-tooltip>
              <el-tooltip content="刷新数据" placement="top">
                <el-button type="primary" :icon="Refresh" circle size="small" @click="refreshPollutantTrendData" :loading="loading.pollutantTrend" />
              </el-tooltip>
            </div>
          </div>
        </template>
        <div ref="pollutantTrendChartRef" class="chart" v-if="!loading.pollutantTrend && !errors.pollutantTrend" />
        <el-skeleton :rows="8" animated v-else-if="loading.pollutantTrend" />
        <el-result v-else icon="error" title="数据加载失败" sub-title="无法加载污染物趋势数据，请稍后重试。">
          <template #extra>
            <el-button type="primary" @click="refreshPollutantTrendData">重试</el-button>
          </template>
        </el-result>
      </el-card>

      <!-- Grid Coverage Table -->
      <el-card 
        shadow="never" 
        class="grid-item table-card grid-coverage"
        body-style="padding: 16px; height: calc(100% - 53px); box-sizing: border-box;"
        header-class="coverage-header"
        body-class="coverage-body"
        footer-class=""
      >
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><Grid /></el-icon>
            <span>网格覆盖率 (按城市)</span>
            <div class="card-actions">
              <el-tooltip content="刷新数据" placement="top">
                <el-button type="primary" :icon="Refresh" circle size="small" @click="refreshCoverageData" :loading="loading.coverage" />
              </el-tooltip>
            </div>
          </div>
        </template>
        <el-table 
          :data="gridCoverageData" 
          style="width: 100%" 
          height="100%" 
          v-if="!loading.coverage"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
          :row-class-name="coverageTableRowClassName"
          border
        >
          <el-table-column prop="city" label="城市" />
          <el-table-column prop="coverageRate" label="覆盖率" width="220">
            <template #default="{ row }">
              <el-progress 
                :percentage="row.coverageRate" 
                :color="getCoverageColor(row.coverageRate)"
                :stroke-width="18"
                :show-text="true"
                :format="percentageFormat"
              />
            </template>
          </el-table-column>
          <el-table-column prop="coveredGrids" label="已覆盖" align="center" />
          <el-table-column prop="totalGrids" label="总网格" align="center" />
        </el-table>
        <el-skeleton :rows="5" animated v-else />
      </el-card>
    </div>
    <div class="dashboard-footer">
      <p>© 2025 环境监测系统 - 实时数据更新于 {{ currentTime }}</p>
    </div>

    <!-- 详细数据对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailDialogTitle"
      width="80%"
      :before-close="closeDetailDialog"
      destroy-on-close
      class="detail-dialog"
    >
      <div class="detail-table-container">
        <el-table
          :data="detailTableData"
          border
          style="width: 100%"
          :header-cell-style="{ 
            background: 'linear-gradient(to right, #409EFF, #67C23A)', 
            color: '#fff', 
            fontWeight: 'bold',
            fontSize: '16px',
            padding: '12px 8px',
            textAlign: 'center'
          }"
          :cell-style="{ 
            textAlign: 'center', 
            padding: '12px 8px',
            fontSize: '14px'
          }"
          :row-class-name="tableRowClassName"
          highlight-current-row
        >
          <el-table-column
            v-for="column in detailTableColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :align="column.align || 'center'"
          />
        </el-table>
      </div>
      <template #footer>
        <div class="detail-dialog-footer">
          <el-button @click="closeDetailDialog" plain>关闭</el-button>
          <el-button type="primary" @click="exportDetailData" :icon="Download">导出数据</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div v-else class="welcome-container">
    <el-result
      icon="success"
      title="欢迎回来"
      :sub-title="`您好, ${user?.name || '用户'}！您当前的角色是 ${user?.role || '未知'}，没有权限访问仪表盘。`"
    >
      <template #extra>
        <el-button type="primary" @click="goBack">返回上一页</el-button>
      </template>
    </el-result>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, onBeforeUnmount, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart, LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components';
import { ElMessage } from 'element-plus';
import { getDashboardStats, getAqiDistribution, getTaskCompletionStats, getMonthlyExceedanceTrend, getGridCoverageByCity, getPollutantMonthlyTrends } from '@/api/dashboard';
import type { DashboardStatsDTO, AqiDistributionDTO, TaskStatsDTO, TrendDataPointDTO, GridCoverageDTO } from '@/api/types';
import { Briefcase, CircleCheck, WarnTriangleFilled, Grid, DataAnalysis, Finished, TrendCharts, Refresh, Setting, DataLine, View, Download } from '@element-plus/icons-vue';

const authStore = useAuthStore();
const user = computed(() => authStore.user);
const canViewDashboard = computed(() => {
  if (!user.value) return false;
  return ['ADMIN', 'DECISION_MAKER'].includes(user.value.role);
});

const router = useRouter();

echarts.use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// --- Chart Element Refs ---
const aqiDistributionChartRef = ref<HTMLElement | null>(null);
const taskStatusChartRef = ref<HTMLElement | null>(null);
const exceedanceTrendChartRef = ref<HTMLElement | null>(null);
const pollutantTrendChartRef = ref<HTMLElement | null>(null);

// --- Timer Ref ---
const timer = ref<number | null>(null);

// --- Loading & Data State ---
const loading = reactive({
  stats: false,
  aqi: false,
  tasks: false,
  trend: false,
  coverage: false,
  pollutantTrend: false,
});

const errors = reactive({
  stats: false,
  aqi: false,
  tasks: false,
  trend: false,
  coverage: false,
  pollutantTrend: false,
});

const statsData = ref<Partial<DashboardStatsDTO & TaskStatsDTO>>({});
const aqiDistributionData = ref<AqiDistributionDTO[]>([]);
const taskStatusData = ref<TaskStatsDTO>({ totalTasks: 0, completedTasks: 0, completionRate: 0 });
const exceedanceTrendData = ref<TrendDataPointDTO[]>([]);
const gridCoverageData = ref<GridCoverageDTO[]>([]);
const pollutantTrendData = ref<Record<string, TrendDataPointDTO[]>>({});
const currentTime = ref(new Date().toLocaleString());

// 污染物类型选择
const selectedPollutantType = ref<string>('ALL');
const pollutantTypes = [
  { label: '全部污染物', value: 'ALL' },
  { label: 'PM2.5', value: 'PM25' },
  { label: '臭氧(O₃)', value: 'O3' },
  { label: '二氧化氮(NO₂)', value: 'NO2' },
  { label: '二氧化硫(SO₂)', value: 'SO2' },
  { label: '其他污染物', value: 'OTHER' }
];

// 处理污染物类型变化
const handlePollutantTypeChange = () => {
  console.log('选择的污染物类型:', selectedPollutantType.value);
  // 先销毁旧的图表实例
  if (pollutantTrendChartRef.value) {
    const oldChart = echarts.getInstanceByDom(pollutantTrendChartRef.value);
    if (oldChart) {
      oldChart.dispose();
    }
  }
  // 然后重新初始化图表
  nextTick(() => {
    initPollutantTrendChart();
  });
};

// --- Timer for current time ---
const timeInterval = setInterval(() => {
  currentTime.value = new Date().toLocaleString();
}, 1000);

// --- KPI Stats ---
const kpiStats = computed(() => [
  {
    title: '待办任务总数',
    value: statsData.value?.totalTasks ?? 0,
    icon: Briefcase,
    color: '#409EFF',
  },
  {
    title: '待处理任务',
    value: (statsData.value?.totalTasks ?? 0) - (statsData.value?.completedTasks ?? 0),
    icon: CircleCheck,
    color: '#67C23A',
  },
  {
    title: '待人工审核反馈',
    value: statsData.value?.totalFeedbacks ?? 0,
    icon: WarnTriangleFilled,
    color: '#E6A23C',
  },
  {
    title: '活动用户数',
    value: statsData.value?.activeGridWorkers ?? 0,
    icon: Grid,
    color: '#F56C6C',
  }
]);

// --- Chart Logic ---

const getAqiColor = (level: string): string => {
  const colorMap: { [key: string]: string } = {
    'Good': '#67c23a',
    'Moderate': '#f5c85b',
    'Unhealthy for Sensitive Groups': '#f5a623',
    'Unhealthy': '#d0021b',
    'Very Unhealthy': '#8b0000',
    'Hazardous': '#4a0000',
  };
  return colorMap[level] || '#999';
};

const initAqiChart = () => {
  if (aqiDistributionChartRef.value && aqiDistributionData.value.length > 0) {
    const chart = echarts.init(aqiDistributionChartRef.value);
    chart.setOption({
      tooltip: { 
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: { 
        type: 'scroll',
        top: '85%', 
        left: 'center',
        textStyle: { fontWeight: 'bold' },
        formatter: function(name: string) {
          // 如果名称太长，截断并添加省略号
          return name.length > 10 ? name.slice(0, 10) + '...' : name;
        }
      },
      series: [{
        name: 'AQI 分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: true,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { 
          show: true, 
          position: 'outside',
          formatter: '{d}%',
          overflow: 'truncate',
          width: 80
        },
        labelLine: {
          length: 15,
          length2: 10,
          smooth: true
        },
        emphasis: { 
          label: { show: true, fontSize: '18', fontWeight: 'bold' },
          itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
        },
        data: aqiDistributionData.value.map(item => ({
          value: item.count,
          name: item.level,
          itemStyle: { color: getAqiColor(item.level) }
        })),
      }]
    });
    
    // 响应式调整
    window.addEventListener('resize', () => chart.resize());
  }
};

const initTaskChart = () => {
  if (taskStatusChartRef.value && taskStatusData.value.totalTasks > 0) {
    const chart = echarts.init(taskStatusChartRef.value);
    const notCompleted = taskStatusData.value.totalTasks - taskStatusData.value.completedTasks;
    chart.setOption({
      tooltip: { 
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: { 
        top: '85%', 
        left: 'center',
        textStyle: { fontWeight: 'bold' }
      },
      series: [{
        name: '任务状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        itemStyle: { 
          borderRadius: 10, 
          borderColor: '#fff', 
          borderWidth: 2 
        },
        label: { 
          show: true, 
          position: 'inside',
          formatter: '{d}%',
          fontSize: 16,
          fontWeight: 'bold'
        },
        emphasis: { 
          label: { show: true, fontSize: '20', fontWeight: 'bold' },
          itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
        },
        data: [
          { 
            value: taskStatusData.value.completedTasks, 
            name: '已完成', 
            itemStyle: { 
              color: '#67c23a',
              borderRadius: 10,
              borderColor: '#fff', 
              borderWidth: 2
            } 
          },
          { 
            value: notCompleted, 
            name: '未完成', 
            itemStyle: { 
              color: '#f56c6c',
              borderRadius: 10,
              borderColor: '#fff', 
              borderWidth: 2
            } 
          },
        ],
      }]
    });
    
    // 响应式调整
    window.addEventListener('resize', () => chart.resize());
  }
};

const initTrendChart = () => {
  if (exceedanceTrendChartRef.value && exceedanceTrendData.value.length > 0) {
    const chart = echarts.init(exceedanceTrendChartRef.value);
    
    // 确保数据格式正确
    console.log("趋势数据详情:", JSON.stringify(exceedanceTrendData.value));
    
    // 准备数据
    const xAxisData = exceedanceTrendData.value.map(p => p.yearMonth || '未知');
    const seriesData = exceedanceTrendData.value.map(p => p.count || 0);
    
    console.log("X轴数据:", xAxisData);
    console.log("系列数据:", seriesData);
    
    const option = {
      title: {
        text: '过去12个月污染超标情况',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal',
          color: '#303133'
        }
      },
      tooltip: { 
        trigger: 'axis',
        axisPointer: { 
          type: 'shadow',
          shadowStyle: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        formatter: function(params: any) {
          const data = params[0];
          return `${data.name}<br/>${data.seriesName}: <strong>${data.value}</strong> 次`;
        }
      },
      grid: { 
        left: '3%', 
        right: '4%', 
        bottom: '15%', 
        top: '15%',
        containLabel: true 
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData,
        axisLabel: {
          interval: 'auto',
          rotate: 45,
          formatter: function(value: string) {
            if (!value || value === '未知') return '未知';
            // 将 yyyy-MM 格式转换为 yyyy年MM月
            const parts = value.split('-');
            if (parts.length === 2) {
              return `${parts[0]}年${parts[1]}月`;
            }
            return value;
          },
          margin: 14,
          hideOverlap: true
        },
        name: '',
        nameTextStyle: {
          fontWeight: 'bold',
          color: '#606266'
        },
        axisLine: {
          lineStyle: {
            color: '#DCDFE6'
          }
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: { 
        type: 'value',
        name: '',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#DCDFE6'
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        },
        axisLabel: {
          formatter: '{value} 次'
        }
      },
      series: [{
        name: '超标次数',
        type: 'line',
        smooth: true,
        data: seriesData,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ],
          symbolSize: 60,
          itemStyle: {
            color: '#F56C6C',
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          label: {
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }],
          lineStyle: {
            color: '#E6A23C',
            type: 'dashed',
            width: 2
          },
          label: {
            formatter: '平均: {c} 次',
            position: 'middle',
            color: '#E6A23C',
            fontSize: 14,
            fontWeight: 'bold',
            backgroundColor: 'rgba(255, 255, 255, 0.8)',
            padding: [4, 8],
            borderRadius: 4
          }
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(245, 108, 108, 0.7)'
            }, {
              offset: 0.5, color: 'rgba(245, 108, 108, 0.3)'
            }, {
              offset: 1, color: 'rgba(245, 108, 108, 0.05)'
            }]
          },
          shadowColor: 'rgba(0, 0, 0, 0.1)',
          shadowBlur: 10
        },
        lineStyle: { 
          color: '#f56c6c', 
          width: 4,
          shadowColor: 'rgba(245, 108, 108, 0.5)',
          shadowBlur: 10
        },
        itemStyle: { 
          color: '#f56c6c', 
          borderWidth: 2,
          borderColor: '#fff',
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5
        },
        emphasis: {
          itemStyle: {
            borderWidth: 6,
            shadowBlur: 20
          },
          lineStyle: {
            width: 6
          }
        },
        // 增加动画效果，但速度更慢
        animationDuration: 3000,
        animationEasing: 'cubicOut',
        animationDelay: function (idx: number) {
          return idx * 300;
        }
      }]
    };
    
    // 应用配置
    chart.setOption(option);
    
    // 响应式调整
    window.addEventListener('resize', () => chart.resize());
  } else {
    console.warn("无法初始化趋势图表，元素不存在或数据为空", 
      { hasRef: !!exceedanceTrendChartRef.value, dataLength: exceedanceTrendData.value.length });
  }
};

const initPollutantTrendChart = () => {
  nextTick(() => {
    if (pollutantTrendChartRef.value && Object.keys(pollutantTrendData.value).length > 0) {
      const chart = echarts.init(pollutantTrendChartRef.value);
      
      // 确保数据格式正确
      console.log("污染物趋势数据详情:", JSON.stringify(pollutantTrendData.value));
      console.log("当前选择的污染物类型:", selectedPollutantType.value);
      
      // 污染物类型对应的颜色
      const colorMap: Record<string, string> = {
        'PM25': '#ff7f50',
        'O3': '#6a5acd',
        'NO2': '#32cd32',
        'SO2': '#ffd700',
        'OTHER': '#808080'
      };
      
      // 获取所有月份
      const allMonths = new Set<string>();
      Object.keys(pollutantTrendData.value).forEach(type => {
        pollutantTrendData.value[type].forEach(point => {
          if (point.yearMonth) {
            allMonths.add(point.yearMonth);
          }
        });
      });
      
      // 转换为数组并排序
      const xAxisData = Array.from(allMonths).sort();
      
      // 准备系列数据
      let series = [];
      
      // 设置动画时间，全部显示时稍慢，单个显示时较快
      const animationDuration = selectedPollutantType.value === 'ALL' ? 2000 : 1200;
      const animationDelayTime = selectedPollutantType.value === 'ALL' ? 200 : 100;
      
      if (selectedPollutantType.value === 'ALL') {
        // 显示所有污染物
        series = Object.keys(pollutantTrendData.value).map(type => {
          // 创建一个映射，方便查找
          const dataMap = new Map<string, number>();
          pollutantTrendData.value[type].forEach(point => {
            if (point.yearMonth) {
              dataMap.set(point.yearMonth, point.count / 100); // 除以100，因为后端乘以了100
            }
          });
          
          // 生成系列数据
          const seriesData = xAxisData.map(month => dataMap.get(month) || 0);
          
          return {
            name: getPollutantDisplayName(type),
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: seriesData,
            lineStyle: {
              width: 3,
              color: colorMap[type] || '#5470c6'
            },
            itemStyle: {
              color: colorMap[type] || '#5470c6'
            },
            emphasis: {
              focus: 'series',
              lineStyle: {
                width: 5
              }
            },
            animationDelay: (idx: number) => idx * animationDelayTime
          };
        });
      } else {
        // 检查选择的污染物类型是否有数据
        if (!pollutantTrendData.value[selectedPollutantType.value]) {
          chart.setOption({
            title: {
              text: `暂无${getPollutantDisplayName(selectedPollutantType.value)}趋势数据`,
              left: 'center',
              top: 'center',
              textStyle: {
                fontSize: 16,
                color: '#909399'
              }
            }
          });
          return;
        }
        
        // 准备数据
        const trendData = pollutantTrendData.value[selectedPollutantType.value];
        
        // 获取月份和数据
        const singleXAxisData = trendData.map(point => point.yearMonth || '未知').sort();
        const seriesData = trendData.map(point => point.count / 100); // 除以100，因为后端乘以了100
        
        const color = colorMap[selectedPollutantType.value] || '#5470c6';
        
        series = [{
          name: getPollutantDisplayName(selectedPollutantType.value),
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: seriesData,
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ],
            symbolSize: 60,
            itemStyle: {
              color: color,
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            },
            label: {
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          markLine: {
            data: [{ type: 'average', name: '平均值' }],
            lineStyle: {
              color: '#E6A23C',
              type: 'dashed',
              width: 2
            },
            label: {
              formatter: '平均: {c}',
              position: 'middle',
              color: '#E6A23C',
              fontSize: 14,
              fontWeight: 'bold',
              backgroundColor: 'rgba(255, 255, 255, 0.8)',
              padding: [4, 8],
              borderRadius: 4
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [{
                offset: 0, color: `${color}CC` // 80% 透明度
              }, {
                offset: 0.5, color: `${color}66` // 40% 透明度
              }, {
                offset: 1, color: `${color}11` // 10% 透明度
              }]
            },
            shadowColor: 'rgba(0, 0, 0, 0.1)',
            shadowBlur: 10
          },
          lineStyle: { 
            color: color, 
            width: 4,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
            shadowBlur: 10
          },
          itemStyle: { 
            color: color, 
            borderWidth: 2,
            borderColor: '#fff',
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowBlur: 5
          },
          emphasis: {
            itemStyle: {
              borderWidth: 6,
              shadowBlur: 20
            },
            lineStyle: {
              width: 6
            }
          }
        }];
      }
      
      const option = {
        title: {
          text: selectedPollutantType.value === 'ALL' ? '所有污染物浓度月度趋势' : `${getPollutantDisplayName(selectedPollutantType.value)}浓度月度趋势`,
          left: 'center',
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#303133'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params: any) {
            if (params.length === 0) return '';
            
            let result = params[0].name + '<br/>';
            params.forEach((param: any) => {
              result += `${param.marker} ${param.seriesName}: <strong>${param.value.toFixed(2)}</strong><br/>`;
            });
            return result;
          }
        },
        legend: {
          data: selectedPollutantType.value === 'ALL' 
            ? Object.keys(pollutantTrendData.value).map(type => getPollutantDisplayName(type))
            : [getPollutantDisplayName(selectedPollutantType.value)],
          top: selectedPollutantType.value === 'ALL' ? '10%' : '5%',
          type: 'scroll',
          textStyle: {
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: selectedPollutantType.value === 'ALL' ? '25%' : '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            interval: 'auto',
            rotate: 45,
            formatter: function(value: string) {
              if (!value || value === '未知') return '未知';
              // 将 yyyy-MM 格式转换为 yyyy年MM月
              const parts = value.split('-');
              if (parts.length === 2) {
                return `${parts[0]}年${parts[1]}月`;
              }
              return value;
            },
            margin: 14,
            hideOverlap: true
          },
          name: '',
          nameTextStyle: {
            fontWeight: 'bold',
            color: '#606266'
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          axisLine: {
            show: true
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLabel: {
            formatter: '{value} μg/m³',
            margin: 16
          }
        },
        series: series,
        animationDuration: animationDuration,
        animationEasing: 'cubicOut' as const,
        animationDelay: function(idx: number) {
          return idx * animationDelayTime;
        }
      };
      
      // 应用配置
      chart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => chart.resize());
    } else {
      console.warn("无法初始化污染物趋势图表，元素不存在或数据为空", 
        { hasRef: !!pollutantTrendChartRef.value, dataLength: Object.keys(pollutantTrendData.value).length });
    }
  });
};

// --- Utility Functions ---
const getCoverageColor = (percentage: number) => {
  if (percentage < 50) return '#f56c6c';
  if (percentage < 80) return '#e6a23c';
  return '#67c23a';
};

// 获取污染物显示名称
const getPollutantDisplayName = (type: string): string => {
  const nameMap: Record<string, string> = {
    'PM25': 'PM2.5',
    'O3': '臭氧(O₃)',
    'NO2': '二氧化氮(NO₂)',
    'SO2': '二氧化硫(SO₂)',
    'OTHER': '其他污染物'
  };
  
  return nameMap[type] || type;
};

const percentageFormat = (percentage: number) => {
  return `${percentage}%`;
};

const tableRowClassName = ({ row, rowIndex }: { row: any, rowIndex: number }) => {
  if (rowIndex % 2 === 0) {
    return 'even-row';
  }
  return 'odd-row';
};

const coverageTableRowClassName = ({ row }: { row: any }) => {
  if (row.coverageRate < 50) return 'coverage-row-low';
  if (row.coverageRate < 80) return 'coverage-row-medium';
  return 'coverage-row-high';
};

// --- Data Fetching ---
const refreshAqiData = () => {
  loading.aqi = true;
  getAqiDistribution().then(data => {
    aqiDistributionData.value = data;
  }).catch(e => {
    console.error('获取AQI分布数据失败:', e);
    ElMessage.error('获取AQI分布数据失败');
  }).finally(() => {
    loading.aqi = false;
    nextTick(initAqiChart);
  });
};

const refreshTaskData = () => {
  loading.tasks = true;
  getTaskCompletionStats().then(data => {
    taskStatusData.value = data;
  }).catch(e => {
    console.error('获取任务统计数据失败:', e);
    ElMessage.error('获取任务统计数据失败');
  }).finally(() => {
    loading.tasks = false;
    nextTick(initTaskChart);
  });
};

const refreshTrendData = () => {
  loading.trend = true;
  getMonthlyExceedanceTrend().then(data => {
    console.log("获取到的月度趋势数据:", JSON.stringify(data));
    exceedanceTrendData.value = data;
  }).catch(e => {
    console.error('获取月度趋势数据失败:', e);
    ElMessage.error('获取月度趋势数据失败');
  }).finally(() => {
    loading.trend = false;
    nextTick(() => {
      console.log("准备初始化趋势图，数据:", JSON.stringify(exceedanceTrendData.value));
      initTrendChart();
    });
  });
};

const refreshCoverageData = () => {
  loading.coverage = true;
  getGridCoverageByCity().then(data => {
    gridCoverageData.value = data;
  }).catch(e => {
    console.error('获取网格覆盖率数据失败:', e);
    ElMessage.error('获取网格覆盖率数据失败');
  }).finally(() => {
    loading.coverage = false;
  });
};

const refreshPollutantTrendData = async () => {
  console.log('开始获取污染物趋势数据...');
  loading.pollutantTrend = true;
  errors.pollutantTrend = false;
  try {
    const data = await getPollutantMonthlyTrends(selectedPollutantType.value);
    console.log('获取到的污染物趋势数据:', data);
    pollutantTrendData.value = data;
  } catch (error) {
    console.error('获取污染物趋势数据失败:', error);
    errors.pollutantTrend = true;
    pollutantTrendData.value = {}; // Clear data on error, ensure it's an object
  } finally {
    loading.pollutantTrend = false;
    console.log('污染物趋势数据获取流程结束。');
  }
};

const refreshAllData = () => {
  console.log("开始刷新所有数据...");
  
  loading.stats = true;
  loading.aqi = true;
  loading.tasks = true;
  loading.trend = true;
  loading.coverage = true;
  loading.pollutantTrend = true;

  getDashboardStats().then(data => {
    console.log("获取到的关键指标数据:", data);
    statsData.value = data;
  }).catch(e => {
    console.error('获取关键指标失败:', e);
    ElMessage.error('获取关键指标失败');
  }).finally(() => {
    loading.stats = false;
  });

  refreshAqiData();
  refreshTaskData();
  refreshTrendData();
  refreshCoverageData();
  refreshPollutantTrendData();
  
  console.log("所有数据刷新请求已发送");
};

// --- Lifecycle Hooks ---
watch(pollutantTrendData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    initPollutantTrendChart();
  }
}, { deep: true });

onMounted(() => {
  console.log("组件挂载，开始加载数据...");
  if (canViewDashboard.value) {
    refreshAllData();
    timer.value = setInterval(refreshAllData, 300000); // 5分钟刷新一次
  } else {
    console.log(`用户角色: ${user.value?.role}, 无需加载仪表盘数据。`);
  }
});

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  clearInterval(timeInterval);
});

// --- Navigation ---
const goBack = () => {
  router.back();
};

// 详细数据对话框
const detailDialogVisible = ref(false);
const detailDialogTitle = ref('');
const detailTableData = ref<any[]>([]);
const detailTableColumns = ref<any[]>([]);

// 显示AQI详细数据
const showAqiDetailData = () => {
  detailDialogTitle.value = 'AQI级别分布详细数据';
  detailTableData.value = aqiDistributionData.value.map(item => ({
    level: item.level,
    count: item.count,
    percentage: ((item.count / aqiDistributionData.value.reduce((sum, i) => sum + i.count, 0)) * 100).toFixed(2) + '%'
  }));
  detailTableColumns.value = [
    { prop: 'level', label: 'AQI级别', width: '180' },
    { prop: 'count', label: '记录数量', width: '120' },
    { prop: 'percentage', label: '百分比', width: '120' }
  ];
  detailDialogVisible.value = true;
};

// 显示任务详细数据
const showTaskDetailData = () => {
  detailDialogTitle.value = '任务状态分布详细数据';
  detailTableData.value = [
    { status: '已完成', count: taskStatusData.value.completedTasks, percentage: taskStatusData.value.completionRate.toFixed(2) + '%' },
    { status: '未完成', count: taskStatusData.value.totalTasks - taskStatusData.value.completedTasks, percentage: (100 - taskStatusData.value.completionRate).toFixed(2) + '%' }
  ];
  detailTableColumns.value = [
    { prop: 'status', label: '任务状态', width: '180' },
    { prop: 'count', label: '任务数量', width: '120' },
    { prop: 'percentage', label: '百分比', width: '120' }
  ];
  detailDialogVisible.value = true;
};

// 显示超标趋势详细数据
const showTrendDetailData = () => {
  detailDialogTitle.value = '月度超标趋势详细数据';
  detailTableData.value = exceedanceTrendData.value.map(item => ({
    yearMonth: item.yearMonth || '未知',
    count: item.count
  })).sort((a, b) => a.yearMonth.localeCompare(b.yearMonth));
  detailTableColumns.value = [
    { prop: 'yearMonth', label: '年月', width: '180' },
    { prop: 'count', label: '超标次数', width: '120' }
  ];
  detailDialogVisible.value = true;
};

// 显示污染物趋势详细数据
const showPollutantDetailData = () => {
  detailDialogTitle.value = '污染物趋势详细数据';
  
  if (selectedPollutantType.value === 'ALL') {
    // 获取所有月份
    const allMonths = new Set<string>();
    Object.keys(pollutantTrendData.value).forEach(type => {
      pollutantTrendData.value[type].forEach(point => {
        if (point.yearMonth) {
          allMonths.add(point.yearMonth);
        }
      });
    });
    
    // 转换为数组并排序
    const months = Array.from(allMonths).sort();
    
    // 创建数据映射
    const dataMap: Record<string, Record<string, number>> = {};
    months.forEach(month => {
      dataMap[month] = {};
      Object.keys(pollutantTrendData.value).forEach(type => {
        dataMap[month][type] = 0;
      });
    });
    
    // 填充数据
    Object.keys(pollutantTrendData.value).forEach(type => {
      pollutantTrendData.value[type].forEach(point => {
        if (point.yearMonth) {
          dataMap[point.yearMonth][type] = point.count / 100;
        }
      });
    });
    
    // 转换为表格数据
    detailTableData.value = months.map(month => {
      const row: any = { yearMonth: month };
      Object.keys(pollutantTrendData.value).forEach(type => {
        row[type] = dataMap[month][type].toFixed(2);
      });
      return row;
    });
    
    // 创建表格列
    detailTableColumns.value = [
      { prop: 'yearMonth', label: '年月', width: '120' },
      ...Object.keys(pollutantTrendData.value).map(type => ({
        prop: type,
        label: getPollutantDisplayName(type),
        width: '120'
      }))
    ];
  } else {
    // 单个污染物
    const type = selectedPollutantType.value;
    detailTableData.value = pollutantTrendData.value[type].map(item => ({
      yearMonth: item.yearMonth || '未知',
      value: (item.count / 100).toFixed(2)
    })).sort((a, b) => a.yearMonth.localeCompare(b.yearMonth));
    
    detailTableColumns.value = [
      { prop: 'yearMonth', label: '年月', width: '180' },
      { prop: 'value', label: `${getPollutantDisplayName(type)}浓度 (μg/m³)`, width: '180' }
    ];
  }
  
  detailDialogVisible.value = true;
};

// 关闭详细数据对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false;
};

// 导出详细数据
const exportDetailData = () => {
  // 创建CSV内容
  let csvContent = '';
  
  // 添加表头
  csvContent += detailTableColumns.value.map(col => `"${col.label}"`).join(',') + '\n';
  
  // 添加数据行
  detailTableData.value.forEach(row => {
    const rowData = detailTableColumns.value.map(col => {
      const value = row[col.prop];
      return `"${value !== undefined ? value : ''}"`;
    });
    csvContent += rowData.join(',') + '\n';
  });
  
  // 创建Blob对象
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  
  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `${detailDialogTitle.value}.csv`);
  link.style.visibility = 'hidden';
  
  // 添加到DOM并触发点击
  document.body.appendChild(link);
  link.click();
  
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  
  ElMessage.success('数据导出成功');
};

</script>

<style scoped>
.dashboard-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
}

.dashboard-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
}

.dashboard-header h1 {
  font-size: 24px;
  margin: 0;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.dashboard-header h1::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 24px;
  background: linear-gradient(to bottom, #409EFF, #67C23A);
  margin-right: 12px;
  border-radius: 3px;
}

.dashboard-actions {
  display: flex;
  gap: 12px;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto auto auto auto;
  gap: 20px;
  padding: 24px;
  background-color: #f5f7fa;
  flex: 1;
}

.grid-item {
  border-radius: 12px;
  background-color: #fff;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.grid-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.kpi-card {
  grid-column: span 1;
  grid-row: 1 / 2;
  position: relative;
}

.kpi-card::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, rgba(103, 194, 58, 0.6) 0%, rgba(103, 194, 58, 1) 100%);
  transform: scaleX(0.7);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.kpi-card:hover::after {
  transform: scaleX(1);
}

.chart-card {
  grid-column: span 2;
  height: 350px; /* Ensure charts have a consistent height */
  position: relative;
  overflow: hidden;
}

.chart-card::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  height: 6px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0.7;
  border-radius: 6px 6px 0 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 16px 0;
  border-bottom: 1px dashed #EBEEF5;
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-content {
  position: relative;
  height: calc(100% - 50px);
}

.chart-container {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-overlay .el-icon {
  font-size: 24px;
  color: #409EFF;
}

.aqi-distribution {
  grid-column: 1 / 3;
  grid-row: 2 / 3;
}

.task-status {
  grid-column: 3 / 5;
  grid-row: 2 / 3;
}

.exceedance-trend {
  grid-column: 1 / 3;
  grid-row: 3 / 4;
}

.pollutant-trend {
  grid-column: 3 / 5;
  grid-row: 3 / 4;
}

.grid-coverage {
  grid-column: 1 / 5;
  grid-row: 4 / 5;
}

.kpi-content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.kpi-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: grid;
  place-items: center;
  color: white;
  font-size: 28px;
  margin-right: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
}

.kpi-icon::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 70%);
}

.kpi-details {
  display: flex;
  flex-direction: column;
}

.kpi-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 6px;
  font-weight: 500;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  position: relative;
}

.kpi-value::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 0;
  width: 30px;
  height: 3px;
  background-color: #409EFF;
  border-radius: 3px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
  width: 100%;
  justify-content: space-between;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409EFF;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.chart {
  width: 100%;
  height: 100%;
  padding: 10px;
}

:deep(.el-card__header) {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f8f9fb;
}

:deep(.el-card__body) {
  padding: 16px;
  height: calc(100% - 53px); /* Adjust based on header height */
  box-sizing: border-box;
}

.loading-text {
  color: #c0c4cc;
}

.coverage-header {
  background-color: #f8f9fb;
  color: #303133;
  font-weight: bold;
}

.coverage-body {
  padding: 16px;
  height: calc(100% - 53px);
  box-sizing: border-box;
}

.coverage-row-low {
  color: #f56c6c;
  font-weight: 500;
}

.coverage-row-medium {
  color: #e6a23c;
  font-weight: 500;
}

.coverage-row-high {
  color: #67c23a;
  font-weight: 500;
}

.coverage-row-low td,
.coverage-row-medium td,
.coverage-row-high td {
  background-color: transparent !important;
}

:deep(.el-progress-bar__outer) {
  border-radius: 10px;
  background-color: #ebeef5;
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
  transition: all 0.6s ease;
}

:deep(.el-progress__text) {
  font-weight: bold;
}

:deep(.el-table th) {
  background-color: #f8f9fb !important;
  color: #303133;
  font-weight: bold;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--border) {
  border-radius: 8px;
  overflow: hidden;
}

.dashboard-footer {
  text-align: center;
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  color: #909399;
  font-size: 14px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
}

.even-row {
  background-color: #f9f9f9;
}

.odd-row {
  background-color: #ffffff;
}

.even-row td,
.odd-row td {
  transition: background-color 0.3s;
}

.even-row:hover td,
.odd-row:hover td {
  background-color: #ecf5ff !important;
}

.detail-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.detail-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #409EFF, #67C23A);
  padding: 20px;
  border-bottom: none;
  position: relative;
}

.detail-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.detail-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

.detail-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
  font-size: 20px;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 24px;
  max-height: 60vh;
  overflow-y: auto;
  background-color: #f9fafc;
}

.detail-table-container {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  position: relative;
}

.detail-table-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  z-index: 1;
}

.detail-dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background-color: #f9fafc;
  border-top: 1px solid #e4e7ed;
}

.even-row {
  background-color: #f9fafc;
}

.odd-row {
  background-color: #ffffff;
}

.even-row td,
.odd-row td {
  transition: all 0.3s;
  border-bottom: 1px solid #ebeef5;
}

.even-row:hover td,
.odd-row:hover td {
  background-color: #ecf5ff !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.welcome-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}
</style> 