<script setup lang="ts">
definePageMeta({
  layout: 'home',
})

const { $toast } = useNuxtApp()

// ── Form state ──
const author = ref('')
const content = ref('')
const platform = ref<string | null>(null)
const submitting = ref(false)

// Platform options
const platforms = ['网站', 'Windows 应用', 'App', '小程序', '插件/扩展', '命令行工具', '其他']

// ── Ideas list ──
const page = ref(1)
const { data, refresh, pending } = await useFetch('/api/ideas', {
  query: computed(() => ({ page: page.value, pageSize: 30 })),
})

const ideas = computed(() => (data.value as any)?.data?.items ?? [])
const hasMore = computed(() => (data.value as any)?.data?.hasMore ?? false)

// ── Detail dialog ──
const selectedIdea = ref<any>(null)
const showDetail = ref(false)

function openDetail(idea: any) {
  selectedIdea.value = idea
  showDetail.value = true
}

function closeDetail() {
  showDetail.value = false
}

// ── Submit ──
async function submitIdea() {
  const trimmedAuthor = author.value.trim()
  const trimmedContent = content.value.trim()

  if (!trimmedContent) {
    $toast.warning('请输入你的想法')
    return
  }

  submitting.value = true
  try {
    await $fetch('/api/ideas', {
      method: 'POST',
      body: { author: trimmedAuthor, content: trimmedContent, platform: platform.value },
    })
    author.value = ''
    content.value = ''
    platform.value = null
    $toast.success('想法已发布 ✨')
    await refresh()
  } catch (e: any) {
    $toast.error(e?.data?.message || '发布失败，请重试')
  } finally {
    submitting.value = false
  }
}

// ── Load more ──
async function loadMore() {
  page.value++
  await refresh()
}
</script>

<template>
  <div class="home-split">
    <!-- Left: Form Panel -->
    <aside class="form-panel">
      <div class="form-sticky">
        <div class="form-header">
          <h2 class="form-title">想开发什么？</h2>
          <p class="form-desc">每一个点子都值得被看见</p>
        </div>

        <div class="form-body">
          <!-- Platform selector -->
          <div class="field">
            <label class="field-label">目标平台</label>
            <div class="platform-chips">
              <button
                v-for="p in platforms"
                :key="p"
                type="button"
                :class="['platform-chip', { 'platform-chip--active': platform === p }]"
                :disabled="submitting"
                @click="platform = platform === p ? null : p"
              >
                {{ p }}
              </button>
            </div>
          </div>

          <div class="field">
            <label class="field-label" for="author-input">你的昵称</label>
            <input
              id="author-input"
              v-model="author"
              type="text"
              class="field-input"
              placeholder="怎么称呼你？（选填）"
              maxlength="30"
              :disabled="submitting"
            />
          </div>

          <div class="field">
            <label class="field-label" for="content-input">你的想法</label>
            <textarea
              id="content-input"
              v-model="content"
              class="field-textarea"
              placeholder="写下你的点子、灵感或想法..."
              rows="4"
              maxlength="500"
              :disabled="submitting"
            />
            <span class="field-count">{{ content.length }}/500</span>
          </div>

          <BoButton
            type="primary"
            size="large"
            :loading="submitting"
            class="submit-btn"
            @click="submitIdea"
          >
            发布想法
          </BoButton>
        </div>
      </div>
    </aside>

    <!-- Right: Card Collection -->
    <main class="cards-panel">
      <!-- Empty state -->
      <div v-if="!pending && ideas.length === 0" class="empty-state">
        <div class="empty-icon">💡</div>
        <h3 class="empty-title">还没有想法</h3>
        <p class="empty-desc">成为第一个分享的人吧</p>
      </div>

      <!-- Loading -->
      <div v-if="pending && ideas.length === 0" class="loading-state">
        <div class="loading-spinner" />
        <p>加载中...</p>
      </div>

      <!-- Cards grid -->
      <div v-if="ideas.length > 0" class="cards-grid">
        <IndexIdeaCard
          v-for="(idea, idx) in ideas"
          :key="idea.id"
          :idea="idea"
          :index="idx"
          :focused="selectedIdea?.id === idea.id"
          @select="openDetail(idea)"
        />
      </div>

      <!-- Load more -->
      <div v-if="hasMore" class="load-more-wrap">
        <BoButton
          type="secondary"
          size="medium"
          :loading="pending"
          @click="loadMore"
        >
          加载更多
        </BoButton>
      </div>
    </main>
  </div>

  <!-- Detail Dialog -->
  <BoDialog v-model:show="showDetail" @close="closeDetail">
    <div v-if="selectedIdea" class="detail-card" :style="{ '--detail-accent': selectedIdea.color || '#cc785c' }">
      <div class="detail-accent-bar" />
      <div class="detail-body">
        <div class="detail-meta">
          <span class="detail-author">{{ selectedIdea.author || '匿名' }}</span>
          <span v-if="selectedIdea.platform" class="detail-platform">{{ selectedIdea.platform }}</span>
          <span class="detail-date">{{ new Date(selectedIdea.createdAt).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }) }}</span>
        </div>
        <p class="detail-content">{{ selectedIdea.content }}</p>
        <div class="detail-footer">
          <BoButton type="secondary" size="small" @click="closeDetail">关闭</BoButton>
        </div>
      </div>
    </div>
  </BoDialog>
</template>

<style scoped>
/* ── Layout ── */
.home-split {
  flex: 1;
  display: flex;
}

/* ── Left Form Panel ── */
.form-panel {
  width: 380px;
  flex-shrink: 0;
  border-right: 1px solid var(--color-hairline, #e6dfd8);
  background: var(--color-canvas, #faf9f5);
}

.form-sticky {
  position: sticky;
  top: 64px;
  padding: 40px 32px;
}

.form-header {
  margin-bottom: 32px;
}

.form-title {
  font-family: var(--font-display, 'Abril Fatface', Georgia, serif);
  font-size: 26px;
  font-weight: 400;
  color: var(--color-ink, #141413);
  margin: 0 0 6px;
  letter-spacing: -0.5px;
}

.form-desc {
  font-size: 14px;
  color: var(--color-muted, #6c6a64);
  margin: 0;
}

/* ── Fields ── */
.form-body {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 6px;
  position: relative;
}

.field-label {
  font-size: 13px;
  font-weight: 600;
  color: var(--color-body-strong, #252523);
  letter-spacing: 0.02em;
}

.field-input,
.field-textarea {
  width: 100%;
  padding: 10px 14px;
  font-size: 14px;
  font-family: var(--font-body, Inter, sans-serif);
  color: var(--color-body, #3d3d3a);
  background: var(--color-surface-soft, #f5f0e8);
  border: 1px solid var(--color-hairline, #e6dfd8);
  border-radius: 8px;
  outline: none;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  resize: vertical;
  box-sizing: border-box;
}

.field-input:focus,
.field-textarea:focus {
  border-color: var(--color-primary, #cc785c);
  box-shadow: 0 0 0 3px rgba(204, 120, 92, 0.1);
}

.field-textarea {
  min-height: 100px;
  line-height: 1.6;
}

.field-count {
  position: absolute;
  bottom: -18px;
  right: 0;
  font-size: 11px;
  color: var(--color-muted-soft, #8e8b82);
}

/* ── Platform Chips ── */
.platform-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.platform-chip {
  padding: 6px 14px;
  font-size: 13px;
  font-family: var(--font-body, Inter, sans-serif);
  color: var(--color-body, #3d3d3a);
  background: var(--color-surface-soft, #f5f0e8);
  border: 1px solid var(--color-hairline, #e6dfd8);
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;
}

.platform-chip:hover {
  border-color: var(--color-primary, #cc785c);
  color: var(--color-primary, #cc785c);
}

.platform-chip--active {
  background: var(--color-primary, #cc785c);
  border-color: var(--color-primary, #cc785c);
  color: #fff;
}

.platform-chip:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.submit-btn {
  margin-top: 4px;
  width: 100%;
}

/* ── Right Cards Panel ── */
.cards-panel {
  flex: 1;
  padding: 40px 36px;
  overflow-y: auto;
  background: linear-gradient(
    180deg,
    var(--color-canvas, #faf9f5) 0%,
    var(--color-surface-soft, #f5f0e8) 100%
  );
}

/* ── Cards Grid ── */
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
}

/* ── Empty State ── */
.empty-state,
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  color: var(--color-muted, #6c6a64);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-title {
  font-size: 18px;
  color: var(--color-body, #3d3d3a);
  margin: 0 0 6px;
}

.empty-desc {
  font-size: 14px;
  margin: 0;
}

/* ── Loading ── */
.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--color-hairline, #e6dfd8);
  border-top-color: var(--color-primary, #cc785c);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* ── Load More ── */
.load-more-wrap {
  display: flex;
  justify-content: center;
  margin-top: 36px;
  padding-bottom: 40px;
}

</style>

<style>
/* ── Detail Dialog (non-scoped for Teleport) ── */
.detail-card {
  background: var(--color-canvas, #faf9f5);
  border-radius: 16px;
  overflow: hidden;
  max-width: 520px;
  width: 90vw;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.detail-accent-bar {
  height: 4px;
  background: var(--detail-accent, #cc785c);
}

.detail-body {
  padding: 28px;
}

.detail-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.detail-author {
  font-size: 15px;
  font-weight: 600;
  color: var(--detail-accent, #cc785c);
  letter-spacing: 0.02em;
}

.detail-platform {
  font-size: 12px;
  font-weight: 600;
  padding: 3px 12px;
  background: var(--detail-accent, #cc785c);
  color: #fff;
  border-radius: 14px;
  letter-spacing: 0.02em;
}

.detail-date {
  font-size: 12px;
  color: var(--color-muted-soft, #8e8b82);
}

.detail-content {
  font-size: 16px;
  line-height: 1.75;
  color: var(--color-body, #3d3d3a);
  margin: 0 0 24px;
  white-space: pre-wrap;
  word-break: break-word;
}

.detail-footer {
  display: flex;
  justify-content: flex-end;
}

/* ── Responsive ── */
@media (max-width: 860px) {
  .home-split {
    flex-direction: column;
  }

  .form-panel {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid var(--color-hairline, #e6dfd8);
  }

  .form-sticky {
    position: static;
    padding: 28px 20px;
  }

  .cards-panel {
    padding: 28px 20px;
  }

  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px;
  }
}
</style>
