<template>
  <div class="work-analytics">
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <span class="filter-label">开始时间</span>
        <el-date-picker
          v-model="startDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px"
          :disabled-date="(date: Date) => endDate ? date > new Date(endDate) : false"
          @change="handleFilterChange"
        />
        <span class="filter-label">结束时间</span>
        <el-date-picker
          v-model="endDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px"
          :disabled-date="(date: Date) => startDate ? date < new Date(startDate) : false"
          @change="handleFilterChange"
        />
        <div class="quick-btns">
          <el-button 
            v-for="btn in quickDateBtns" 
            :key="btn.value"
            :type="activeQuickBtn === btn.value ? 'primary' : 'default'"
            size="small"
            @click="handleQuickDate(btn.value)"
          >
            {{ btn.label }}
          </el-button>
        </div>
        <el-select 
          v-model="selectedAccounts" 
          multiple 
          collapse-tags 
          collapse-tags-tooltip
          placeholder="选择账号" 
          style="width: 200px"
          @change="handleFilterChange"
        >
          <el-option 
            v-for="account in accountList" 
            :key="account.id" 
            :label="`${account.nickname} (${getPlatformName(account.platform)})`" 
            :value="account.id"
          />
        </el-select>
      </div>
      <div class="filter-right">
        <el-button @click="handleExport">导出数据</el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-card" v-for="(item, index) in summaryStats" :key="index">
        <div class="stat-icon">
          <el-icon :size="18"><component :is="item.icon" /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-label">{{ item.label }}</div>
          <div class="stat-value">{{ item.value }}</div>
        </div>
      </div>
    </div>
    
    <!-- 第二行筛选 -->
    <div class="filter-bar secondary">
      <div class="filter-left">
        <el-select v-model="selectedGroup" placeholder="全部" clearable style="width: 120px" @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option 
            v-for="group in accountGroups" 
            :key="group.id" 
            :label="group.name" 
            :value="group.id" 
          />
        </el-select>
        <el-select v-model="selectedPlatform" placeholder="全部平台" clearable style="width: 120px" @change="handleFilterChange">
          <el-option label="全部平台" value="" />
          <el-option 
            v-for="platform in availablePlatforms" 
            :key="platform.value" 
            :label="platform.label" 
            :value="platform.value"
          />
        </el-select>
        <el-select v-model="sortBy" style="width: 200px" @change="handleFilterChange">
          <el-option label="按发布时间倒序排列" value="publish_desc" />
          <el-option label="按播放量倒序排列" value="views_desc" />
        </el-select>
        <el-input 
          v-model="searchKeyword" 
          placeholder="请输入要搜索的作品标题" 
          clearable
          style="width: 240px"
          @input="handleSearchInput"
          @clear="handleFilterChange"
          @keyup.enter="handleFilterChange"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="data-table">
      <el-table :data="workList" v-loading="loading" stripe>
        <el-table-column label="账号" width="150">
          <template #default="{ row }">
            <div class="account-cell">
              <el-avatar :size="32" :src="row.accountAvatar">
                {{ row.accountName?.[0] }}
              </el-avatar>
              <span class="account-name">{{ row.accountName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平台" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small" :type="getPlatformTagType(row.platform)">
              {{ getPlatformName(row.platform) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标题" min-width="300">
          <template #default="{ row }">
            <div class="title-cell">
              <div class="work-title">{{ row.title }}</div>
              <div class="work-stats">
                <!-- 推荐暂不展示
                <span class="stat-item">推荐 <em>{{ row.recommendCount ?? '--' }}</em></span>
                -->
                <span class="stat-item">播放 <em>{{ row.viewsCount ?? 0 }}</em></span>
                <span class="stat-item">评论 <em>{{ row.commentsCount ?? 0 }}</em></span>
                <span class="stat-item">分享 <em>{{ row.sharesCount ?? 0 }}</em></span>
                <span class="stat-item">收藏 <em>{{ row.collectsCount ?? 0 }}</em></span>
                <span class="stat-item">点赞 <em>{{ row.likesCount ?? 0 }}</em></span>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- 类型列暂时不展示
        <el-table-column prop="workType" label="类型" width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.workType || '动态' }}</span>
          </template>
        </el-table-column>
        -->
        <el-table-column prop="publishTime" label="发布时间" width="160" align="center">
          <template #default="{ row }">
            <span class="publish-time">{{ formatTime(row.publishTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalWorks"
          layout="total, prev, pager, next"
          @current-change="handleQuery"
        />
      </div>
    </div>
    
    <!-- 作品详情弹窗 -->
    <el-dialog
      v-model="drawerVisible"
      title="作品详情"
      width="80%"
      :close-on-click-modal="false"
      destroy-on-close
      class="work-detail-dialog"
    >
      <div v-if="selectedWork" class="work-detail">
        <!-- 标题和发布时间 -->
        <div class="detail-header">
          <h3 class="work-title">{{ selectedWork.title }}</h3>
          <div class="publish-time">{{ formatTime(selectedWork.publishTime) }}</div>
        </div>

        <!-- 标签页 -->
        <el-tabs v-model="activeTab" class="detail-tabs">
          <!-- 核心数据标签页 -->
          <el-tab-pane label="核心数据" name="core">
            <div class="core-data-content">
              <!-- 流量数据卡片 -->
              <div class="traffic-data">
                <div class="section-title-row">
                  <h4 class="section-title">流量数据</h4>
                </div>
                <div class="data-cards">
                  <!-- 小红书：指标更多 + 支持点选联动趋势图 -->
                  <template v-if="selectedWork.platform === 'xiaohongshu'">
                    <div
                      v-for="item in xhsMetricCards"
                      :key="item.key"
                      class="data-card"
                      :class="{ highlight: activeTrendMetric === item.key }"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric(item.key)"
                      @keyup.enter="setTrendMetric(item.key)"
                    >
                      <div class="card-label">{{ item.label }}</div>
                      <div class="card-value">{{ item.value }}</div>
                    </div>
                  </template>

                  <!-- 抖音：按小红书样式展示可用字段 -->
                  <template v-else-if="selectedWork.platform === 'douyin'">
                    <div
                      v-for="item in douyinMetricCards"
                      :key="item.label"
                      class="data-card"
                      :class="{ highlight: item.key && activeTrendMetric === item.key }"
                      role="button"
                      tabindex="0"
                      @click="item.key && setTrendMetric(item.key)"
                      @keyup.enter="item.key && setTrendMetric(item.key)"
                    >
                      <div class="card-label">{{ item.label }}</div>
                      <div class="card-value">{{ item.value }}</div>
                    </div>
                  </template>

                  <!-- 视频号：播放、点赞、评论、分享、收藏、关注数、涨粉量、平均观看时长、完播率、2s退出率 -->
                  <template v-else-if="selectedWork.platform === 'weixin_video'">
                    <div
                      v-for="item in weixinMetricCards"
                      :key="item.label"
                      class="data-card"
                      :class="{ highlight: item.key && activeTrendMetric === item.key }"
                      role="button"
                      tabindex="0"
                      @click="item.key && setTrendMetric(item.key)"
                      @keyup.enter="item.key && setTrendMetric(item.key)"
                    >
                      <div class="card-label">{{ item.label }}</div>
                      <div class="card-value">{{ item.value }}</div>
                    </div>
                  </template>

                  <!-- 百家号：推荐量、播放(阅读)量、评论量、点赞量、收藏量、分享量、完播率、涨粉量 -->
                  <template v-else-if="selectedWork.platform === 'baijiahao'">
                    <div
                      v-for="item in baijiahaoMetricCards"
                      :key="item.key || item.label"
                      class="data-card"
                      :class="{ highlight: item.key && activeTrendMetric === item.key }"
                      role="button"
                      tabindex="0"
                      @click="item.key && setTrendMetric(item.key)"
                      @keyup.enter="item.key && setTrendMetric(item.key)"
                    >
                      <div class="card-label">{{ item.label }}</div>
                      <div class="card-value">{{ item.value }}</div>
                    </div>
                  </template>

                  <!-- 其他平台：保持原口径 -->
                  <template v-else>
                    <div
                      class="data-card highlight"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('playCount')"
                      @keyup.enter="setTrendMetric('playCount')"
                    >
                      <div class="card-label">播放量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.playCount || 0) }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('totalWatchDuration')"
                      @keyup.enter="setTrendMetric('totalWatchDuration')"
                    >
                      <div class="card-label">播放总时长</div>
                      <div class="card-value">{{ workDetailData.totalWatchDuration || '0秒' }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('likeCount')"
                      @keyup.enter="setTrendMetric('likeCount')"
                    >
                      <div class="card-label">点赞量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.likeCount || 0) }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('commentCount')"
                      @keyup.enter="setTrendMetric('commentCount')"
                    >
                      <div class="card-label">评论量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.commentCount || 0) }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('collectCount')"
                      @keyup.enter="setTrendMetric('collectCount')"
                    >
                      <div class="card-label">收藏量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.collectCount || 0) }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('shareCount')"
                      @keyup.enter="setTrendMetric('shareCount')"
                    >
                      <div class="card-label">分享量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.shareCount || 0) }}</div>
                    </div>
                    <div
                      class="data-card"
                      role="button"
                      tabindex="0"
                      @click="setTrendMetric('fansIncrease')"
                      @keyup.enter="setTrendMetric('fansIncrease')"
                    >
                      <div class="card-label">涨粉量</div>
                      <div class="card-value">{{ formatNumber(workDetailData.fansIncrease || 0) }}</div>
                    </div>
                  </template>
                </div>
              </div>

              <!-- 播放量趋势 -->
              <div class="trend-section">
                <h4 class="section-title">{{ trendTitle }}</h4>
                <div ref="playTrendChartRef" style="height: 300px" v-loading="detailLoading"></div>
              </div>
            </div>
          </el-tab-pane>

        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { Search, Picture, Document, View, ChatDotRound, Share, Star, Pointer } from '@element-plus/icons-vue';
import { PLATFORMS, AVAILABLE_PLATFORM_TYPES } from '@media-manager/shared';
import type { PlatformType } from '@media-manager/shared';
import { useAuthStore } from '@/stores/auth';
import { useServerStore } from '@/stores/server';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import request from '@/api/request';
import * as echarts from 'echarts';

const authStore = useAuthStore();
const serverStore = useServerStore();
const loading = ref(false);

// 日期筛选
const startDate = ref(dayjs().subtract(30, 'day').format('YYYY-MM-DD'));
const endDate = ref(dayjs().format('YYYY-MM-DD'));
const activeQuickBtn = ref('lastMonth');

// 快捷日期按钮
const quickDateBtns = [
  { label: '近三天', value: 'last3days' },
  { label: '近七天', value: 'last7days' },
  { label: '近一个月', value: 'lastMonth' },
];

// 账号选择（带平台信息，便于同名账号区分）
const selectedAccounts = ref<number[]>([]);
const accountList = ref<{ id: number; nickname: string; platform: PlatformType }[]>([]);

// 分组和平台筛选
const selectedGroup = ref<number | ''>('');
const selectedPlatform = ref<PlatformType | ''>('');
const sortBy = ref('publish_desc');
const searchKeyword = ref('');

// 分组列表
interface AccountGroup {
  id: number;
  name: string;
}
const accountGroups = ref<AccountGroup[]>([]);

// 可用平台（统一配置：小红书、抖音、视频号、百家号）
const availablePlatforms = computed(() => {
  return AVAILABLE_PLATFORM_TYPES.map(key => ({
    value: key,
    label: PLATFORMS[key].name,
  }));
});

// 分页
const currentPage = ref(1);
// 默认每页 15 条
const pageSize = ref(15);
const totalWorks = ref(0);

// 汇总统计
const summaryData = ref({
  totalWorks: 0,
  recommendCount: 0,
  viewsCount: 0,
  commentsCount: 0,
  sharesCount: 0,
  collectsCount: 0,
  likesCount: 0,
});

// 统计卡片数据
const summaryStats = computed(() => [
  { label: '作品总数', value: summaryData.value.totalWorks, icon: Document },
  // { label: '推荐量', value: summaryData.value.recommendCount, icon: Pointer },
  { label: '播放(阅读)量', value: summaryData.value.viewsCount, icon: View },
  { label: '评论量', value: summaryData.value.commentsCount, icon: ChatDotRound },
  { label: '分享量', value: summaryData.value.sharesCount, icon: Share },
  { label: '收藏量', value: summaryData.value.collectsCount, icon: Star },
  { label: '点赞量', value: summaryData.value.likesCount, icon: Pointer },
]);

// 作品数据
interface WorkData {
  id: number;
  title: string;
  coverUrl: string;
  content: string;
  platform: PlatformType;
  accountId: number;
  accountName: string;
  accountAvatar: string;
  workType: string;
  publishTime: string;
  recommendCount: number | null;
  viewsCount: number;
  commentsCount: number;
  sharesCount: number;
  collectsCount: number;
  likesCount: number;
}

const workList = ref<WorkData[]>([]);

// 详情弹窗相关
const drawerVisible = ref(false);
const selectedWork = ref<WorkData | null>(null);
// 作品基础信息（来自 works 表 /api/works/:id）
const selectedWorkBase = ref<any | null>(null);
const activeTab = ref('core');
const detailLoading = ref(false);

// 作品详情数据
interface WorkDetailData {
  playCount: number;
  exposureCount: number;
  totalWatchDuration: string;
  likeCount: number;
  commentCount: number;
  collectCount: number;
  shareCount: number;
  fansIncrease: number;
  followCount: number; // 视频号：关注数
  recommendCount: number; // 百家号等：推荐量
  coverClickRate: string;
  avgWatchDuration: string;
  completionRate: string;
  twoSecondExitRate: string;
  // 抖音：5s 完播率（仅昨日快照，无趋势）
  completionRate5s: string;
}

const workDetailData = ref<WorkDetailData>({
  playCount: 0,
  exposureCount: 0,
  totalWatchDuration: '0秒',
  likeCount: 0,
  commentCount: 0,
  collectCount: 0,
  shareCount: 0,
  fansIncrease: 0,
  followCount: 0,
  recommendCount: 0,
  coverClickRate: '0',
  avgWatchDuration: '0',
  completionRate: '0',
  twoSecondExitRate: '0',
  completionRate5s: '0',
});

// 播放量趋势图
const playTrendChartRef = ref<HTMLElement>();
let playTrendChart: echarts.ECharts | null = null;

type TrendMetricKey =
  | 'exposureCount'
  | 'playCount'
  | 'likeCount'
  | 'commentCount'
  | 'collectCount'
  | 'shareCount'
  | 'coverClickRate'
  | 'avgWatchDuration'
  | 'completionRate'
  | 'twoSecondExitRate'
  | 'fansIncrease'
  | 'followCount'
  | 'totalWatchDuration';

const activeTrendMetric = ref<TrendMetricKey>('playCount');
const workStatsHistory = ref<any[]>([]);

function toIntSafe(v: any): number {
  const n = Number(String(v ?? '0').replace(/[^\d.-]/g, ''));
  if (!Number.isFinite(n)) return 0;
  return Math.max(0, Math.trunc(n));
}

const trendTitle = computed(() => {
  if (!selectedWork.value) return '趋势';
  if (selectedWork.value.platform !== 'xiaohongshu') {
    const map: Record<TrendMetricKey, string> = {
      playCount: '播放(阅读)量趋势',
      totalWatchDuration: '播放总时长趋势',
      likeCount: '点赞量趋势',
      commentCount: '评论量趋势',
      collectCount: '收藏量趋势',
      shareCount: '分享量趋势',
      fansIncrease: '涨粉量趋势',
      followCount: '关注量趋势',
      exposureCount: '曝光量趋势',
      coverClickRate: '封面点击率趋势',
      avgWatchDuration: '平均观看时长趋势',
      completionRate: '完播率趋势',
      twoSecondExitRate: '2s退出率趋势',
    };
    return map[activeTrendMetric.value] || '趋势';
  }
  const map: Record<TrendMetricKey, string> = {
    exposureCount: '曝光量趋势',
    playCount: '播放(阅读)量趋势',
    likeCount: '点赞量趋势',
    commentCount: '评论量趋势',
    collectCount: '收藏量趋势',
    shareCount: '分享量趋势',
    coverClickRate: '封面点击率趋势',
    avgWatchDuration: '平均观看时长趋势',
    completionRate: '完播率趋势',
    twoSecondExitRate: '2s退出率趋势',
    fansIncrease: '涨粉量趋势',
    followCount: '关注量趋势',
    totalWatchDuration: '播放总时长趋势',
  };
  return map[activeTrendMetric.value] || '趋势';
});

function setTrendMetric(key: TrendMetricKey) {
  activeTrendMetric.value = key;
  if (workStatsHistory.value.length > 0) {
    updatePlayTrendChart(workStatsHistory.value);
  }
}

function getPlatformName(platform: PlatformType) {
  return PLATFORMS[platform]?.name || platform;
}

function getPlatformTagType(platform: PlatformType) {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
    douyin: 'danger',
    xiaohongshu: 'danger',
    bilibili: 'primary',
    kuaishou: 'warning',
    weixin: 'success',
  };
  return typeMap[platform] || 'info';
}

function formatTime(time: string) {
  if (!time) return '-';
  const d = dayjs(time);
  if (!d.isValid()) return time;
  const nowYear = dayjs().year();
  // 今年：01-22 10:22，往年：2025-12-22 10:22
  return d.year() === nowYear ? d.format('MM-DD HH:mm') : d.format('YYYY-MM-DD HH:mm');
}

// 快捷日期选择
function handleQuickDate(type: string) {
  activeQuickBtn.value = type;
  const today = dayjs();
  
  switch (type) {
    case 'last3days':
      startDate.value = today.subtract(3, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
    case 'last7days':
      startDate.value = today.subtract(7, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
    case 'lastMonth':
      startDate.value = today.subtract(30, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
  }
  handleQuery();
}

// 查询
function handleQuery() {
  loadData();
}

// 平台/分组/日期/账号变更时重置页码并查询
function handleFilterChange() {
  currentPage.value = 1;
  handleQuery();
}

// 搜索框防抖（300ms 后触发查询）
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
function handleSearchInput() {
  if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
  searchDebounceTimer = setTimeout(() => {
    currentPage.value = 1;
    handleQuery();
    searchDebounceTimer = null;
  }, 300);
}

// 加载账号列表
async function loadAccountList() {
  try {
    const res = await request.get('/api/accounts');
    // 新接口：request 已经解包，res 就是账号数组
    if (Array.isArray(res)) {
      accountList.value = res.map((a: any) => ({
        id: a.id,
        nickname: a.accountName || a.nickname || a.username,
        platform: a.platform as PlatformType,
      }));
    } else if ((res as any)?.data?.data) {
      // 兼容旧格式 { data: { data: [] } }
      accountList.value = (res as any).data.data.map((a: any) => ({
        id: a.id,
        nickname: a.accountName || a.nickname || a.username,
        platform: a.platform as PlatformType,
      }));
    }
  } catch (error) {
    console.error('加载账号列表失败:', error);
  }
}

// 加载分组列表
async function loadGroups() {
  try {
    const res = await request.get('/api/accounts/groups');
    // 新接口：request 已经解包，res 就是分组数组
    if (Array.isArray(res)) {
      accountGroups.value = res as AccountGroup[];
    } else if ((res as any)?.data?.data) {
      // 兼容旧格式 { data: { data: [] } }
      accountGroups.value = (res as any).data.data || [];
    }
  } catch (error) {
    console.error('加载分组失败:', error);
  }
}

// 加载数据
async function loadData() {
  const userId = authStore.user?.id;
  if (!userId) return;
  
  loading.value = true;
  
  try {
    const params: Record<string, any> = {
      startDate: startDate.value,
      endDate: endDate.value,
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value,
    };

    if (selectedPlatform.value) {
      params.platform = selectedPlatform.value;
    }

    if (selectedAccounts.value.length > 0) {
      params.accountIds = selectedAccounts.value.join(',');
    }

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    if (selectedGroup.value) {
      params.groupId = selectedGroup.value;
    }

    const data = await request.get('/api/work-day-statistics/works', {
      params,
    });

    if (data) {
      workList.value = (data.works || []) as WorkData[];
      totalWorks.value = data.total || 0;

      if (data.summary) {
        summaryData.value = {
          totalWorks: data.summary.totalWorks || 0,
          recommendCount: data.summary.recommendCount || 0,
          viewsCount: data.summary.viewsCount || 0,
          commentsCount: data.summary.commentsCount || 0,
          sharesCount: data.summary.sharesCount || 0,
          collectsCount: data.summary.collectsCount || 0,
          likesCount: data.summary.likesCount || 0,
        };
      }
    }
  } catch (error) {
    console.error('加载作品数据失败:', error);
    ElMessage.error('加载作品数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 格式化数字
function formatNumber(num: number | null | undefined): string {
  if (num === null || num === undefined) return '0';
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万';
  }
  return String(num);
}

function formatDurationSeconds(secLike: any): string {
  const s = Math.max(0, parseInt(String(secLike ?? '0'), 10) || 0);
  if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  return `${s}秒`;
}

/** 平均观看时长：保留 2 位小数（非小红书口径） */
function formatAvgWatchDurationSeconds(secLike: any): string {
  const s = Math.max(0, parseFloat(String(secLike ?? '0')) || 0);
  if (s >= 60) return `${Math.floor(s / 60)}分${(s % 60).toFixed(2)}秒`;
  return `${s.toFixed(2)}秒`;
}

/** 小红书平均观看时长：取整（秒） */
function formatAvgWatchDurationSecondsInt(secLike: any): string {
  const s = Math.max(0, Math.round(parseFloat(String(secLike ?? '0')) || 0));
  if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  return `${s}秒`;
}

function formatRate(rateLike: any): string {
  const raw = String(rateLike ?? '0').trim();
  if (!raw) return '0%';
  if (raw.includes('%')) return raw;
  const n = Number(raw);
  if (Number.isNaN(n)) return raw;
  // 兼容：有的入库是 0.12（表示 12%），有的是 12（表示 12%）
  const pct = n <= 1 ? n * 100 : n;
  return `${pct.toFixed(2).replace(/\.00$/, '')}%`;
}

function calcDetailRangeDatesFixed14Days(): { start: string; end: string } {
  const publish = dayjs(selectedWork.value?.publishTime);
  const platform = selectedWork.value?.platform;

  // 小红书：趋势固定「发布后 14 天（含发布日）」，与页面时间范围无关
  if (platform === 'xiaohongshu' && publish.isValid()) {
    const start = publish.startOf('day');
    const end = start.add(13, 'day'); // 发布日 + 13 天 = 共 14 天
    return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  }

  const today = dayjs().startOf('day');

  // 抖音：作品详情趋势固定为「今天往回 30 天（含今天）」，与列表筛选无关；且不早于发布时间
  if (platform === 'douyin') {
    let end = today;
    let start = end.subtract(29, 'day'); // 近30天（含当天）
    if (publish.isValid() && publish.isAfter(start)) {
      start = publish.startOf('day');
    }
    return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  }

  const end = dayjs(endDate.value || today);

  // 其他平台：保持原逻辑（以页面 endDate 为截止的近 14 天），且不早于发布时间
  const start14 = end.subtract(13, 'day'); // 近14天（含当天）
  const clampedStart = publish.isValid() && publish.isAfter(start14) ? publish.startOf('day') : start14;
  return { start: clampedStart.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
}

interface MetricCardConfig {
  key?: TrendMetricKey;
  label: string;
  value: string;
}

const xhsMetricCards = computed<MetricCardConfig[]>(() => {
  const d = workDetailData.value;
  return [
    { key: 'exposureCount' as const, label: '曝光量', value: formatNumber(d.exposureCount || 0) },
    { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || selectedWork.value?.viewsCount || 0) },
    { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || selectedWork.value?.likesCount || 0) },
    { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || selectedWork.value?.commentsCount || 0) },
    { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || selectedWork.value?.collectsCount || 0) },
    { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || selectedWork.value?.sharesCount || 0) },
    { key: 'coverClickRate' as const, label: '封面点击率', value: formatRate(d.coverClickRate) },
    { key: 'avgWatchDuration' as const, label: '平均观看时长', value: formatAvgWatchDurationSecondsInt(d.avgWatchDuration) },
    { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
    { key: 'twoSecondExitRate' as const, label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
    { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  ];
});

// 抖音：按照小红书样式展示已有字段（不包含曝光量，新增 5s 完播率与播放总时长）
const douyinMetricCards = computed<MetricCardConfig[]>(() => {
  const d = workDetailData.value;
  const base = selectedWork.value;
  return [
    { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
    { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
    { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
    { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
    { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
    { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
    { key: 'completionRate', label: '完播率', value: formatRate(d.completionRate) },
    { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
    // 5s 完播率仅为昨日快照，不参与趋势联动
    { label: '5s完播率', value: formatRate(d.completionRate5s) },
    { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
  ];
});

// 视频号：播放、点赞、评论、分享、收藏、关注数、涨粉量、平均观看时长、完播率、2s退出率
const weixinMetricCards = computed<MetricCardConfig[]>(() => {
  const d = workDetailData.value;
  const base = selectedWork.value;
  return [
    { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
    { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
    { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
    { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
    { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
    { key: 'followCount', label: '关注数', value: formatNumber(d.followCount || 0) },
    // { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
    { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
    { label: '完播率', value: formatRate(d.completionRate) },
    // { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  ];
});

// 百家号：推荐量、播放(阅读)量、评论量、点赞量、收藏量、分享量、完播率、涨粉量
const baijiahaoMetricCards = computed<MetricCardConfig[]>(() => {
  const d = workDetailData.value;
  const base = selectedWork.value;
  return [
    { label: '推荐量', value: formatNumber(d.recommendCount || 0) },
    { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
    { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
    { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
    { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
    { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
    { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
    { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  ];
});

// 查看详情
async function handleView(row: WorkData) {
  selectedWork.value = row;
  selectedWorkBase.value = null;
  activeTrendMetric.value = row.platform === 'xiaohongshu' ? 'exposureCount' : 'playCount';
  workStatsHistory.value = [];
  drawerVisible.value = true;
  activeTab.value = 'core';

  // [已注释] 视频号：点击详情时先同步每日数据（浏览器自动化 + CSV 导入）
  // if (row.platform === 'weixin_video') {
  //   detailLoading.value = true;
  //   try {
  //     const syncRes = await request.post(`/api/work-day-statistics/sync-weixin-video/${row.id}`);
  //     if (syncRes?.success && (syncRes?.data?.inserted > 0 || syncRes?.data?.updated > 0)) {
  //       ElMessage.success(syncRes.message || `已同步 ${(syncRes.data?.inserted || 0) + (syncRes.data?.updated || 0)} 条日数据`);
  //     }
  //   } catch (e) {
  //     console.warn('视频号日数据同步失败（可忽略）:', e);
  //   } finally {
  //     detailLoading.value = false;
  //   }
  // }
  
  // 先用列表行做“瞬时占位”（列表来自区间汇总，可能不等于 works 表累计值）
  workDetailData.value = {
    playCount: row.viewsCount || 0,
    exposureCount: 0,
    totalWatchDuration: '0秒',
    likeCount: row.likesCount || 0,
    commentCount: row.commentsCount || 0,
    collectCount: row.collectsCount || 0,
    shareCount: row.sharesCount || 0,
    fansIncrease: 0,
    followCount: 0,
    recommendCount: 0,
    coverClickRate: '0',
    avgWatchDuration: '0',
    completionRate: '0',
    twoSecondExitRate: '0',
  };
  
  // 1) 加载 works 表基础信息（标题、发布时间、累计播放/点赞等）
  await loadWorkBase(row.id);
  // 2) 加载 work_day_statistics 历史快照（用于“最新累计值”与趋势）
  await loadWorkDetail(row.id);
}

// 加载作品基础信息（works 表）
async function loadWorkBase(workId: number) {
  try {
    const data = await request.get(`/api/works/${workId}`);
    if (!data) return;
    selectedWorkBase.value = data;

    // 基础信息补齐：以 works 表为准（如果 works 缺失字段则回退到列表行）
    if (selectedWork.value) {
      selectedWork.value = {
        ...selectedWork.value,
        title: data.title || selectedWork.value.title,
        publishTime: data.publishTime || selectedWork.value.publishTime,
        coverUrl: data.coverUrl || selectedWork.value.coverUrl,
      };
    }

    // 顶部卡片：按需求展示 works.yesterday_*（昨日快照）
    workDetailData.value = {
      playCount: toIntSafe(data.yesterdayPlayCount ?? 0),
      exposureCount: toIntSafe(data.yesterdayExposureCount ?? 0),
      totalWatchDuration: formatDurationSeconds(data.yesterdayTotalWatchDuration ?? 0),
      likeCount: toIntSafe(data.yesterdayLikeCount ?? 0),
      commentCount: toIntSafe(data.yesterdayCommentCount ?? 0),
      collectCount: toIntSafe(data.yesterdayCollectCount ?? 0),
      shareCount: toIntSafe(data.yesterdayShareCount ?? 0),
      fansIncrease: toIntSafe(data.yesterdayFansIncrease ?? 0),
      followCount: toIntSafe(data.yesterdayFollowCount ?? 0),
      recommendCount: toIntSafe(data.yesterdayRecommendCount ?? 0),
      coverClickRate: String(data.yesterdayCoverClickRate ?? '0'),
      avgWatchDuration: String(data.yesterdayAvgWatchDuration ?? '0'),
      completionRate: String(data.yesterdayCompletionRate ?? '0'),
      twoSecondExitRate: String(data.yesterdayTwoSecondExitRate ?? '0'),
      completionRate5s: String(data.yesterdayCompletionRate5s ?? '0'),
    };
  } catch (error) {
    // works 表请求失败不影响后续趋势展示
    console.warn('加载作品基础信息失败:', error);
  }
}

// 加载作品详情数据（历史统计数据）
async function loadWorkDetail(workId: number) {
  detailLoading.value = true;
  
  try {
    // 趋势固定：近 14 天（按 work_day_statistics 日新增量口径）
    const { start: startDateStr, end: endDateStr } = calcDetailRangeDatesFixed14Days();
    
    // 调用接口获取该作品的历史统计数据（work_day_statistics 快照）
    const data = await request.get(`/api/work-day-statistics/work/${workId}`, {
      params: {
        // 注意：后端校验参数名为 startDate/endDate
        startDate: startDateStr,
        endDate: endDateStr,
      },
    });
    
    if (data && Array.isArray(data)) {
      const workStats = data;
      workStatsHistory.value = workStats;
      
      // 绘制趋势图（按天新增量）
      await nextTick();
      updatePlayTrendChart(workStats);
    }
  } catch (error) {
    console.error('加载作品详情失败:', error);
    ElMessage.error('加载作品详情失败，请稍后重试');
  } finally {
    detailLoading.value = false;
  }
}

// 更新播放量趋势图
function updatePlayTrendChart(stats: Array<any>) {
  if (!playTrendChartRef.value) return;
  
  if (!playTrendChart) {
    playTrendChart = echarts.init(playTrendChartRef.value);
  }
  
  // 按日期排序
  const sortedStats = [...stats].sort((a, b) => 
    dayjs(a.recordDate).valueOf() - dayjs(b.recordDate).valueOf()
  );
  
  const dates = sortedStats.map(s => dayjs(s.recordDate).format('YYYY-MM-DD'));

  const metric = activeTrendMetric.value;
  const seriesName = trendTitle.value.replace('趋势', '');

  const isRateMetric =
    metric === 'coverClickRate' || metric === 'completionRate' || metric === 'twoSecondExitRate';
  const isDurationMetric = metric === 'avgWatchDuration' || metric === 'totalWatchDuration';

  const values = sortedStats.map((s) => {
    const v = s?.[metric];
    if (isRateMetric) {
      const raw = String(v ?? '0').trim();
      if (raw.includes('%')) return Number(raw.replace('%', '')) || 0;
      const n = Number(raw);
      if (Number.isNaN(n)) return 0;
      return n <= 1 ? n * 100 : n;
    }
    if (metric === 'avgWatchDuration') {
      return Math.max(0, Math.round(parseFloat(String(v ?? '0')) || 0));
    }
    if (metric === 'totalWatchDuration') {
      return Math.max(0, parseInt(String(v ?? '0'), 10) || 0);
    }
    return Number(v) || 0;
  });
  
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      formatter: (params: any) => {
        const arr = Array.isArray(params) ? params : [params];
        if (arr.length === 0) return '';
        const dateLabel = arr[0]?.axisValueLabel || arr[0]?.axisValue || '';
        const lines: string[] = [`${dateLabel}`];
        for (const p of arr) {
          const name = p?.seriesName ?? '';
          const val = typeof p?.data === 'number' ? p.data : Number(p?.data ?? 0);
          if (isRateMetric) {
            lines.push(`${name}：${(Number.isFinite(val) ? val : 0).toFixed(2).replace(/\.00$/, '')}%`);
          } else if (isDurationMetric) {
            lines.push(`${name}：${formatDurationSeconds(Number.isFinite(val) ? Math.round(val) : 0)}`);
          } else {
            lines.push(`${name}：${formatNumber(Number.isFinite(val) ? val : 0)}`);
          }
        }
        return lines.join('<br/>');
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        formatter: (value: string) => {
          return dayjs(value).format('MM-DD');
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => {
          if (isRateMetric) {
            const n = Number.isFinite(value) ? value : 0;
            return `${n.toFixed(2).replace(/\.00$/, '')}%`;
          }
          if (isDurationMetric) {
            return formatDurationSeconds(Number.isFinite(value) ? Math.round(value) : 0);
          }
          if (value >= 10000) return (value / 10000).toFixed(1) + '万';
          return String(value);
        },
      },
    },
    series: [
      {
        name: seriesName || '趋势',
        type: 'line',
        smooth: true,
        data: values,
        itemStyle: {
          color: '#ff6b9d',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(255, 107, 157, 0.3)' },
              { offset: 1, color: 'rgba(255, 107, 157, 0.05)' },
            ],
          },
        },
      },
    ],
  };
  
  playTrendChart.setOption(option, true);
}

// 监听弹窗关闭，清理图表
watch(drawerVisible, (visible) => {
  if (!visible && playTrendChart) {
    playTrendChart.dispose();
    playTrendChart = null;
  }
});

// 导出数据（按当前筛选条件导出作品列表）
async function handleExport() {
  try {
    const baseUrl = serverStore.currentServer?.url;
    if (!baseUrl) {
      ElMessage.error('未连接服务器');
      return;
    }
    if (!authStore.accessToken) {
      ElMessage.error('未连接服务器或未登录');
      return;
    }

    const params = new URLSearchParams();
    params.set('startDate', startDate.value);
    params.set('endDate', endDate.value);
    if (selectedPlatform.value) params.set('platform', selectedPlatform.value);
    if (selectedAccounts.value.length > 0) params.set('accountIds', selectedAccounts.value.join(','));
    if (selectedGroup.value) params.set('groupId', String(selectedGroup.value));
    if (searchKeyword.value) params.set('keyword', searchKeyword.value);
    params.set('sortBy', sortBy.value);

    const url = `${baseUrl}/api/work-day-statistics/works/export?${params.toString()}`;

    const doFetch = async (token: string) => {
      return await fetch(url, {
        method: 'GET',
        headers: { Authorization: `Bearer ${token}` },
      });
    };

    let resp = await doFetch(authStore.accessToken!);
    if (resp.status === 401) {
      const refreshed = await authStore.refreshAccessToken();
      if (!refreshed || !authStore.accessToken) {
        ElMessage.error('登录已过期，请重新登录');
        return;
      }
      resp = await doFetch(authStore.accessToken!);
    }

    if (!resp.ok) {
      const text = await resp.text().catch(() => '');
      throw new Error(text || `导出失败，状态码：${resp.status}`);
    }

    const blob = await resp.blob();
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = `作品数据_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
    ElMessage.success('导出成功');
  } catch (error: any) {
    console.error('导出失败:', error);
    ElMessage.error(error?.message || '导出失败');
  }
}

onMounted(() => {
  loadAccountList();
  loadGroups();
  loadData();
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.work-analytics {
  .filter-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    
    &.secondary {
      margin-bottom: 16px;
      padding: 12px 20px;
    }
    
    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .filter-label {
        font-size: 14px;
        color: $text-regular;
      }
      
      .quick-btns {
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .stats-row {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 0;
    margin-bottom: 20px;
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;
    
    .stat-card {
      padding: 20px 16px;
      display: flex;
      align-items: center;
      gap: 12px;
      border-right: 1px solid #f0f0f0;
      
      &:last-child {
        border-right: none;
      }
      
      .stat-icon {
        width: 36px;
        height: 36px;
        background: $primary-color-light;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $primary-color;
        flex-shrink: 0;
      }
      
      .stat-info {
        .stat-label {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 4px;
          white-space: nowrap;
        }
        
        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: $text-primary;
        }
      }
    }
  }
  
  .data-table {
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;
    
    .account-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .account-name {
        font-weight: 500;
        color: $text-primary;
      }
    }
    
    .title-cell {
      .work-title {
        font-weight: 500;
        color: $primary-color;
        margin-bottom: 6px;
        cursor: pointer;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      .work-stats {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: $text-secondary;
        
        .stat-item {
          em {
            font-style: normal;
            color: $primary-color;
            margin-left: 2px;
          }
        }
      }
    }
    
    .publish-time {
      font-size: 13px;
      color: $text-secondary;
    }
    
    .pagination-wrapper {
      padding: 16px 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

:deep(.work-detail-dialog) {
  .el-dialog__header {
    padding-bottom: 0;
  }
  
  .el-dialog__body {
    padding-top: 20px;
  }
}

.work-detail {
  .detail-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    
    .work-title {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
      color: $text-primary;
    }
    
    .publish-time {
      font-size: 14px;
      color: $text-secondary;
    }
  }
  
  .detail-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 24px;
    }
    
    :deep(.el-tabs__item) {
      font-size: 15px;
      font-weight: 500;
    }
  }
  
  .core-data-content {
    .traffic-data {
      margin-bottom: 32px;
      
      .section-title-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 16px;
      }

      .section-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: $text-primary;
      }

      .detail-range {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        justify-content: flex-end;
      }
      
      .data-cards {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 16px;
        
        @media (max-width: 1400px) {
          grid-template-columns: repeat(4, 1fr);
        }
        
        @media (max-width: 900px) {
          grid-template-columns: repeat(3, 1fr);
        }
        
        @media (max-width: 600px) {
          grid-template-columns: repeat(2, 1fr);
        }
        
        .data-card {
          background: #f8fafc;
          border-radius: 8px;
          padding: 20px 16px;
          text-align: center;
          border: 1px solid #e5e7eb;
          cursor: pointer;
          
          &.highlight {
            background: #fff5f7;
            border-color: #ff6b9d;
            
            .card-value {
              color: #ff6b9d;
              font-weight: 700;
            }
          }
          
          .card-label {
            font-size: 13px;
            color: $text-secondary;
            margin-bottom: 8px;
          }
          
          .card-value {
            font-size: 24px;
            font-weight: 600;
            color: $text-primary;
            line-height: 1.2;
          }
        }
      }
    }
    
    .trend-section {
      .section-title {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
        color: $text-primary;
      }
    }
  }
  
}

@media (max-width: 1400px) {
  .work-analytics {
    .stats-row {
      grid-template-columns: repeat(4, 1fr);
      
      .stat-card {
        &:nth-child(4) {
          border-right: none;
        }
        
        &:nth-child(n+5) {
          border-top: 1px solid #f0f0f0;
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .work-analytics {
    .filter-bar {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .filter-left {
        flex-wrap: wrap;
      }
    }
    
    .stats-row {
      grid-template-columns: repeat(3, 1fr);
      
      .stat-card {
        &:nth-child(3n) {
          border-right: none;
        }
        
        &:nth-child(n+4) {
          border-top: 1px solid #f0f0f0;
        }
      }
    }
  }
}
</style>
