<template>
  <section class="section-marketplace">
    <div class="marketplace-inner">
    <div class="marketplace-header">
      <div class="section-badge">
        <span class="badge-dot"></span>
        <span>{{ $t('marketplace.badge') }}</span>
      </div>
      <h2 class="section-title">{{ $t('marketplace.title') }} <span class="gradient-text">200K+</span> {{ $t('marketplace.subtitle') }}</h2>
      <p class="section-desc">{{ $t('marketplace.description') }}</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-input-wrap">
        <span class="search-icon">🔍</span>
        <input
          v-model="searchQuery"
          type="text"
          :placeholder="$t('marketplace.search.placeholder')"
          class="search-input"
          @input="filterWorkflows"
        />
        <button class="search-btn" @click="filterWorkflows">{{ $t('marketplace.search.button') }}</button>
      </div>
    </div>

    <!-- 分类标签 -->
    <div class="category-tabs">
      <button
        v-for="cat in categories"
        :key="cat.category2Name"
        class="cat-tab"
        :class="{ active: activeCategory === cat.categoryId2 }"
        @click="selectCategory(cat.categoryId2)"
      >
        <span>{{ cat.icon }}</span>
        <span>{{ cat.category2Name }}</span>
        <span class="cat-count">{{ cat.downCount }}</span>
      </button>
    </div>

    <!-- 工作流卡片网格 -->
    <div class="marketplace-grid">
      <div
        v-for="(wf, i) in filteredWorkflows"
        :key="i"
        class="market-card"
        @mouseenter="hoveredCard = i"
        @mouseleave="hoveredCard = null"
      >
        <!-- 封面图 -->
        <div class="market-card-cover">
          <img :src="wf.coverImage" :alt="wf.title" class="market-cover-img" />
          <div class="market-cover-overlay"></div>
          <div class="market-platform-chip" :style="{ background: wf.platformColor }">{{ wf.categoryName1 }}</div>
          <div class="market-views">▶ {{ wf.downCount }}</div>
        </div>

        <!-- 卡片内容 -->
        <div class="market-card-body">
          <div class="market-card-top">
            <h4 class="market-title">{{ wf.workflowTitle }}</h4>
            <!-- <div class="market-rating">⭐ {{ wf.rating }}</div> -->
          </div>
          <p class="market-desc">{{ wf.description }}</p>
          <!-- <div class="market-tags">
            <span class="market-tag" v-for="tag in wf.tags" :key="tag">{{ tag }}</span>
          </div> -->
          <div class="market-footer">
            <div class="market-author">
              <img :src="wf.userAvatar" :alt="wf.author" class="market-avatar" />
              <span>{{ wf.nickName }}</span>
            </div>
            <button class="market-use-btn">{{ $t('marketplace.cta.use') }} →</button>
          </div>
        </div>

        <!-- 悬停遮罩 -->
        <div class="market-hover-overlay" :class="{ visible: hoveredCard === i }">
          <button class="overlay-btn primary" @click="handleUseClick($event, wf)">{{ $t('marketplace.cta.use2') }}</button>
          <button class="overlay-btn secondary" @click="handlePreviewClick($event, wf)">{{ $t('marketplace.cta.details') }}</button>
        </div>
      </div>
    </div>

    <!-- 查看更多 -->
    <div class="marketplace-footer">
      <button class="view-all-btn" @click="goWorkflowMarket">{{ $t('marketplace.cta.viewAll') }} →</button>
    </div>
    </div><!-- /.marketplace-inner -->
  </section>
</template>

<script setup>
import {ref, computed, onMounted, inject} from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import {isLogin, openNewTab} from "@/utils/util.js";
import { getPublishList,workflowCategoryStats } from '@/api/publish.js'
const { t } = useI18n()
const router = useRouter()
const searchQuery = ref('')
const activeCategory = ref('')
const hoveredCard = ref(null)
const icons = ['🌟','✍️','📊','🤖','💼','⚡']
const categories = ref([
  // { label: '全部', icon: '🌟', count: '200K+' },
  // { label: '内容创作', icon: '✍️', count: '45K+' },
  // { label: '数据分析', icon: '📊', count: '38K+' },
  // { label: '客服自动化', icon: '🤖', count: '52K+' },
  // { label: '销售运营', icon: '💼', count: '29K+' },
  // { label: '效率工具', icon: '⚡', count: '36K+' }
])

const allWorkflows = ref([])

const filteredWorkflows = computed(() => {
  return allWorkflows.value.filter(wf => {
    const matchCategory = wf.categoryId2 === activeCategory.value
    const matchSearch = !searchQuery.value || 
      (wf.workflowTitle && wf.workflowTitle.includes(searchQuery.value)) || 
      (wf.description && wf.description.includes(searchQuery.value))
    return matchCategory && matchSearch
  })
})

function selectCategory(cat) {
  activeCategory.value = cat;
  searchFom.value.categoryId2=activeCategory.value;
    getList();
}
function filterWorkflows() {
  // 搜索过滤由 computed 处理
}
const searchFom = ref({
  pageNum: 0,
  pageSize: 8,
  orderByColumn: 'downCount',
  isAsc: 'desc',
})
const getWorkflowCategoryStats =async () => {
  let obj ={
    pageNum: 0,
        pageSize: 50}
  const res = await workflowCategoryStats(obj);
  if (res && res.rows) {
      // 处理数据，添加图标
      const processedCategories = res.rows.map((category, index) => ({
        ...category,
        icon: icons[index % icons.length] // 循环使用图标数组
      }));
      categories.value = processedCategories;
    activeCategory.value=categories.value[0].categoryId2;
      console.log(activeCategory.value)
    searchFom.value.categoryId2=activeCategory.value;
    getList()
    } else {
      console.error('Invalid response from workflowCategoryStats');
    }
}

const getList = async () => {
  try {
    const res = await getPublishList(searchFom.value);
    if (res && res.rows) {
      // 转换真实数据格式
      allWorkflows.value = res.rows;
    }
  } catch (error) {
    console.error('Error loading workflows:', error);
    // 加载失败时使用假数据
    allWorkflows.value = [];
  }
};
const openLoginDialog = inject('openLoginDialog')
const handleUseClick = (event, item) => {
  event.stopPropagation(); // 阻止冒泡
  if(!isLogin({callback: openLoginDialog,t})){
    return;
  }
  openNewTab(item.categoryUrl);
};
// 处理预览按钮点击
const handlePreviewClick = (event, item) => {
  event.stopPropagation(); // 阻止冒泡
  //判断是否登录
  if(!isLogin({callback: openLoginDialog,t})){
    return;
  }
  let path = `/workflow-detail`
    //增加参数名称
    router.push({
      path: path,
      query: {
        publishId: item.publishId,
        metaTitle: 'route.WorkflowDetail'
      }
    })
};
const goWorkflowMarket = () => { router.push({ path: '/workflow-trade' }); };
onMounted(() => {
  getWorkflowCategoryStats();

})
</script>

<style scoped>
.section-marketplace {
  padding: 100px 0;
  background: #FFFFFF;
}

/* 内容容器：限制最大宽度，居中对齐 */
.marketplace-inner {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 40px;
}
.marketplace-header {
  text-align: center;
  margin-bottom: 40px;
}
.section-badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: #F5F3FF;
  border: 1px solid rgba(99,102,241,0.2);
  border-radius: 100px;
  padding: 6px 16px;
  font-size: 13px;
  color: #6366F1;
  font-weight: 500;
  margin-bottom: 20px;
}
.badge-dot {
  width: 6px; height: 6px;
  background: #6366F1; border-radius: 50%;
  animation: pulse 2s infinite;
}
@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(1.3); }
}
.section-title {
  font-size: 44px;
  font-weight: 700;
  color: #111827;
  margin-bottom: 16px;
}
.gradient-text {
  background: linear-gradient(135deg, #6366F1, #EC4899);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.section-desc {
  font-size: 17px;
  color: #6B7280;
  max-width: 500px;
  margin: 0 auto;
  line-height: 1.7;
}

/* 搜索栏 */
.search-bar {
  max-width: 600px;
  margin: 0 auto 32px;
}
.search-input-wrap {
  display: flex;
  align-items: center;
  background: white;
  border: 1.5px solid rgba(0,0,0,0.1);
  border-radius: 14px;
  padding: 4px 4px 4px 16px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  transition: all 0.3s;
}
.search-input-wrap:focus-within {
  border-color: #6366F1;
  box-shadow: 0 4px 20px rgba(99,102,241,0.15);
}
.search-icon { font-size: 16px; margin-right: 8px; }
.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 15px;
  color: #111827;
  background: transparent;
}
.search-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #6366F1, #8B5CF6);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-bottom: 40px;
  flex-wrap: wrap;
}
.cat-tab {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 18px;
  border-radius: 100px;
  border: 1.5px solid rgba(0,0,0,0.08);
  background: white;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #6B7280;
  transition: all 0.3s;
}
.cat-tab:hover { border-color: #6366F1; color: #6366F1; }
.cat-tab.active {
  background: linear-gradient(135deg, #6366F1, #8B5CF6);
  color: white;
  border-color: transparent;
  box-shadow: 0 4px 16px rgba(99,102,241,0.3);
}
.cat-count {
  font-size: 11px;
  background: rgba(255,255,255,0.2);
  padding: 1px 6px;
  border-radius: 100px;
}
.cat-tab:not(.active) .cat-count {
  background: #F3F4F6;
  color: #9CA3AF;
}

/* 卡片网格 */
.marketplace-grid {
  display: grid;
  /* 自适应列数：每列最小 260px，最大 1fr，宽屏不超过 4 列 */
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

/* 大屏（≥1400px）强制 4 列，防止卡片过宽 */
@media (min-width: 1400px) {
  .marketplace-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
.market-card {
  background: white;
  border-radius: 16px;
  border: 1px solid rgba(0,0,0,0.06);
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
  position: relative;
}
.market-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 48px rgba(0,0,0,0.12);
}
.market-card.hidden {
  opacity: 0.3;
  transform: scale(0.95);
}

/* 封面图 */
.market-card-cover {
  position: relative;
  height: 160px;
  overflow: hidden;
}
.market-cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.4s;
}
.market-card:hover .market-cover-img { transform: scale(1.05); }
.market-cover-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, transparent 40%, rgba(0,0,0,0.4));
}
.market-platform-chip {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 3px 10px;
  border-radius: 100px;
  font-size: 11px;
  font-weight: 700;
  color: white;
}
.market-views {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: white;
  font-size: 12px;
  font-weight: 600;
}

/* 卡片内容 */
.market-card-body { padding: 16px; }
.market-card-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}
.market-title {
  font-size: 14px;
  font-weight: 700;
  color: #111827;
  flex: 1;
  margin-right: 8px;
  line-height: 1.3;
}
.market-rating { font-size: 12px; color: #F59E0B; font-weight: 600; white-space: nowrap; }
.market-desc {
  font-size: 12px;
  color: #6B7280;
  line-height: 1.5;
  margin-bottom: 10px;
}
.market-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 12px;
}
.market-tag {
  padding: 2px 8px;
  background: #F3F4F6;
  border-radius: 100px;
  font-size: 10px;
  color: #6B7280;
}
.market-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.market-author {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6B7280;
}
.market-avatar {
  width: 22px; height: 22px;
  border-radius: 50%;
  object-fit: cover;
}
.market-use-btn {
  padding: 5px 12px;
  background: #F5F3FF;
  color: #6366F1;
  border: 1px solid rgba(99,102,241,0.2);
  border-radius: 8px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}
.market-use-btn:hover {
  background: #6366F1;
  color: white;
}

/* 悬停遮罩 */
.market-hover-overlay {
  position: absolute;
  inset: 0;
  background: rgba(99,102,241,0.92);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  opacity: 0;
  transition: opacity 0.3s;
}
.market-hover-overlay.visible { opacity: 1; }
.overlay-btn {
  width: 160px;
  padding: 10px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}
.overlay-btn.primary {
  background: white;
  color: #6366F1;
}
.overlay-btn.secondary {
  background: rgba(255,255,255,0.15);
  color: white;
  border: 1px solid rgba(255,255,255,0.3);
}

/* ===== 响应式 ===== */

/* 标题自适应 */
.section-title {
  font-size: clamp(1.75rem, 4vw, 2.75rem);
}
.section-desc {
  font-size: clamp(0.875rem, 1.8vw, 1.0625rem);
}

/* 平板（≤1200px）：3 列 */
@media (max-width: 1200px) {
  .marketplace-inner { padding: 0 24px; }
  .marketplace-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* 小平板（≤900px）：2 列 */
@media (max-width: 900px) {
  .section-marketplace { padding: 4rem 0; }
  .marketplace-inner { padding: 0 16px; }
  .marketplace-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
  .market-card-cover { height: 140px; }
}

/* 手机竖屏（≤600px）：2 列紧凑 */
@media (max-width: 600px) {
  .section-marketplace { padding: 3rem 0; }
  .marketplace-inner { padding: 0 12px; }
  .marketplace-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  .market-card-cover { height: 120px; }
  .market-card-body { padding: 12px; }
  .market-title { font-size: 12px; }
  .market-desc { font-size: 11px; }
  .market-tags { display: none; }
  .cat-tab { padding: 6px 12px; font-size: 12px; }
  .cat-count { display: none; }
}

/* 极小屏（≤400px）：1 列 */
@media (max-width: 400px) {
  .marketplace-grid {
    grid-template-columns: 1fr;
  }
  .market-card-cover { height: 160px; }
}

/* 查看更多 */
.marketplace-footer { text-align: center; }
.view-all-btn {
  padding: 14px 40px;
  background: white;
  border: 1.5px solid rgba(99,102,241,0.3);
  border-radius: 12px;
  font-size: 15px;
  font-weight: 600;
  color: #6366F1;
  cursor: pointer;
  transition: all 0.3s;
}
.view-all-btn:hover {
  background: #F5F3FF;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(99,102,241,0.15);
}
</style>
