<template>
  <AdminPageShell
    eyebrow="實驗詳情"
    :title="experiment?.name || '載入中...'"
    :description="experiment?.experimentKey || route.params.experimentId"
  >
    <template #actions>
      <el-button @click="goBack">返回列表</el-button>
      <el-button @click="loadPage">重新整理</el-button>
    </template>

    <el-alert
      v-if="errorMessage"
      type="error"
      :closable="false"
      :title="errorMessage"
      show-icon
      style="margin-bottom: 16px"
    />

    <template #summary>
      <div class="metrics-grid">
        <AdminMetricCard label="狀態" :value="statusLabelMap[experiment?.status] || experiment?.status || '-'" hint="目前實驗狀態" />
        <AdminMetricCard label="變體數量" :value="variants.length" hint="目前設定的分流變體數量" />
        <AdminMetricCard label="版本數量" :value="releases.length" hint="已建立的版本數量" />
        <AdminMetricCard label="已發佈版本" :value="latestRelease?.status === 'published' ? latestRelease.releaseVersion : '無'" tone="success" hint="目前線上版本" />
      </div>
    </template>

    <el-tabs v-model="activeTab" class="detail-tabs">

      <!-- ── 實驗設定 ── -->
      <el-tab-pane label="實驗設定" name="settings">
        <div class="tab-card">
          <div class="section">
            <p class="section__title">基礎設定</p>

            <div class="field">
              <label class="field__label">實驗名稱 <span class="field__required">*</span></label>
              <el-input v-model="settingsForm.name" placeholder="例：首頁主視覺 A/B 測試" />
              <p v-if="settingsErrors.name" class="field__error">{{ settingsErrors.name }}</p>
            </div>

            <div class="field">
              <label class="field__label">狀態</label>
              <div class="status-pills">
                <button
                  v-for="opt in statusOptions"
                  :key="opt.value"
                  class="status-pill"
                  :class="{ 'status-pill--active': settingsForm.status === opt.value, [`status-pill--${opt.value}`]: true }"
                  type="button"
                  @click="settingsForm.status = opt.value"
                >
                  {{ opt.label }}
                </button>
              </div>
            </div>

            <div class="field-row">
              <div class="field">
                <label class="field__label">開始時間</label>
                <el-date-picker v-model="settingsForm.start_at" type="datetime" placeholder="選擇開始時間" style="width: 100%" />
              </div>
              <div class="field">
                <label class="field__label">結束時間</label>
                <el-date-picker v-model="settingsForm.end_at" type="datetime" placeholder="選擇結束時間" style="width: 100%" />
              </div>
            </div>
          </div>

          <div class="section">
            <p class="section__title">啟用條件</p>
            <p class="section__desc">設定這個實驗要套用在哪些頁面網址。</p>

            <div class="field">
              <label class="field__label">實驗頁面網址</label>
              <el-input v-model="settingsForm.base_url" placeholder="例：https://www.example.com/products/page" clearable />
              <p class="field__hint">這個網址也會作為視覺編輯器的預設載入頁面。</p>
            </div>

            <div class="field">
              <label class="field__label">網址規則</label>
              <div class="rules-box">
                <template v-if="settingsForm.url_rules.length === 0">
                  <p class="rules-empty">尚未設定規則 — 實驗將只依據上方網址判斷。</p>
                </template>
                <template v-else>
                  <div v-for="(rule, idx) in settingsForm.url_rules" :key="rule._id" class="rule-row-wrap">
                    <div class="rule-connector">
                      <span class="rule-connector__badge">{{ idx === 0 ? '當' : '且' }}</span>
                    </div>
                    <div class="rule-row">
                      <el-select v-model="rule.operator" style="width: 160px; flex-shrink: 0">
                        <el-option v-for="op in urlRuleOperators" :key="op.value" :label="op.label" :value="op.value" />
                      </el-select>
                      <el-input v-model="rule.value" placeholder="輸入網址或關鍵字" style="flex: 1" clearable />
                      <button class="rule-delete" type="button" @click="removeRule(idx)">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                          <polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/>
                        </svg>
                      </button>
                    </div>
                  </div>
                </template>
                <button class="add-rule-btn" type="button" @click="addRule">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                  新增網址規則
                </button>
              </div>
            </div>

            <div class="field">
              <label class="field__label">規則測試</label>
              <div class="url-tester">
                <el-input v-model="testUrl" placeholder="輸入網址來測試規則是否符合" clearable style="flex: 1" />
                <el-button type="button" @click="runUrlTest">檢查</el-button>
              </div>
              <div v-if="testResult !== null" class="test-result" :class="testResult ? 'test-result--pass' : 'test-result--fail'">
                {{ testResult ? '✓ 符合規則，實驗將套用到此網址' : '✗ 不符合規則，實驗不會套用到此網址' }}
              </div>
            </div>
          </div>

          <div class="section">
            <p class="section__title">進階設定</p>

            <div class="field">
              <label class="field__label">裝置限制</label>
              <p class="field__hint">不選則代表全裝置。</p>
              <div class="device-pills">
                <button
                  v-for="d in deviceOptions"
                  :key="d.value"
                  class="device-pill"
                  :class="{ 'device-pill--active': settingsForm.device_targets.includes(d.value) }"
                  type="button"
                  @click="toggleDevice(d.value)"
                >
                  <svg v-if="settingsForm.device_targets.includes(d.value)" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>
                  {{ d.label }}
                </button>
              </div>
            </div>

            <div class="field">
              <label class="checkbox-row">
                <input type="checkbox" v-model="settingsForm.hide_hashtag" class="checkbox-input" />
                <span class="checkbox-label">隱藏網址片段（hashtag）</span>
              </label>
            </div>
          </div>

          <div class="settings-footer">
            <el-button type="primary" :loading="settingsSaving" @click="handleSaveSettings">
              儲存設定
            </el-button>
          </div>
        </div>
      </el-tab-pane>

      <!-- ── 變體列表 ── -->
      <el-tab-pane label="變體列表" name="variants">
        <div class="tab-card">
          <div class="tab-card__header">
            <p class="tab-card__title">
              變體列表
              <span class="tab-card__count">{{ variants.length }}</span>
            </p>
            <el-button size="small" type="primary" @click="openCreateVariantDialog">新增變體</el-button>
          </div>

          <div v-if="variants.length === 0" class="empty-state">
            尚未建立任何變體，點擊「新增變體」開始設定。
          </div>
          <el-table v-else :data="variants" stripe>
            <el-table-column prop="name" label="名稱" min-width="160" />
            <el-table-column prop="variantKey" label="變體代號" min-width="160" />
            <el-table-column label="流量權重" width="100">
              <template #default="{ row }">{{ row.trafficWeight ?? 0 }}%</template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right">
              <template #default="{ row }">
                <div class="row-actions">
                  <el-button link type="success" @click="openEditor(row.id)">編輯</el-button>
                  <el-button link @click="openEditVariantDialog(row)">編輯</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- ── 版本列表 ── -->
      <el-tab-pane label="版本列表" name="releases">
        <div class="tab-card">
          <div class="tab-card__header">
            <p class="tab-card__title">
              版本列表
              <span class="tab-card__count">{{ releases.length }}</span>
            </p>
            <el-button
              size="small"
              type="primary"
              :loading="buildingRelease"
              :disabled="variants.length === 0"
              @click="handleBuildRelease"
            >
              建立版本
            </el-button>
          </div>

          <div v-if="releases.length === 0" class="empty-state">
            尚未建立任何版本，點擊「建立版本」從目前變體快照建立版本。
          </div>
          <div v-else class="release-list">
            <div
              v-for="row in releases"
              :key="row.id"
              class="release-card"
              :class="`release-card--${row.status}`"
            >
              <div class="release-card__left">
                <span class="release-card__version">{{ row.releaseVersion }}</span>
                <span class="release-card__status-badge" :class="`release-card__status-badge--${row.status}`">
                  {{ releaseStatusLabel[row.status] || row.status }}
                </span>
              </div>
              <div class="release-card__actions">
                <template v-if="row.status !== 'archived'">
                  <button
                    v-if="row.status === 'draft'"
                    class="release-btn release-btn--publish"
                    :disabled="releaseActionLoading === row.id + '_publish'"
                    @click="handlePublish(row.id)"
                  >
                    {{ releaseActionLoading === row.id + '_publish' ? '處理中...' : '發佈' }}
                  </button>
                  <button
                    v-if="row.status === 'published'"
                    class="release-btn release-btn--rollback"
                    :disabled="releaseActionLoading === row.id + '_rollback'"
                    @click="handleRollback(row.id)"
                  >
                    {{ releaseActionLoading === row.id + '_rollback' ? '處理中...' : '回退草稿' }}
                  </button>
                  <button
                    class="release-btn release-btn--archive"
                    :disabled="releaseActionLoading === row.id + '_archive'"
                    @click="handleArchive(row.id)"
                  >
                    {{ releaseActionLoading === row.id + '_archive' ? '處理中...' : '封存' }}
                  </button>
                </template>
                <span v-else class="muted-text">已封存</span>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- ── 目標設定 ── -->
      <el-tab-pane label="目標設定" name="goals">
        <div class="tab-card">
          <div class="tab-card__header">
            <p class="tab-card__title">
              轉換目標
              <span class="tab-card__count">{{ goals.length }}</span>
            </p>
          </div>
          <p class="section__desc" style="margin-bottom: 16px">
            目標用於追蹤實驗的轉換成效。當訪客完成以下任一目標行為時，系統將記錄為一次轉換，作為實驗結果分析的依據。
          </p>

          <div v-if="goals.length === 0" class="empty-state">
            這個網站尚未設定轉換目標，請至後台新增目標後再回來查看。
          </div>
          <div v-else class="goals-grid">
            <div v-for="goal in goals" :key="goal.id" class="goal-item">
              <div class="goal-item__top">
                <div>
                  <p class="goal-item__name">{{ goal.name || goal.goal_key }}</p>
                  <p class="goal-item__key">{{ goal.goal_key }}</p>
                </div>
                <el-tag size="small" type="info" effect="plain">{{ goalTypeLabel[goal.goal_type] || goal.goal_type }}</el-tag>
              </div>
              <pre v-if="goal.match_rule" class="code-block code-block--sm"><code>{{ JSON.stringify(goal.match_rule, null, 2) }}</code></pre>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- ── 操作紀錄 ── -->
      <el-tab-pane label="操作紀錄" name="activity">
        <div class="tab-card">
          <p class="tab-card__title" style="margin-bottom: 20px">操作紀錄</p>

          <div v-if="activityLog.length === 0" class="empty-state">
            尚無操作紀錄。對實驗、變體或版本進行任何操作後將顯示於此。
          </div>
          <div v-else class="activity-list">
            <div
              v-for="entry in activityLog"
              :key="entry.id"
              class="activity-item"
              :class="`activity-item--${entry.action}`"
            >
              <div class="activity-item__dot" />
              <div class="activity-item__content">
                <p class="activity-item__label">
                  <span class="activity-item__action">{{ entry.action_label }}</span>
                  <span class="activity-item__collection">{{ entry.collection_label }}</span>
                </p>
                <p class="activity-item__meta">
                  <span v-if="entry.actor_email">{{ entry.actor_email }}</span>
                  <span v-else class="muted-text">系統操作</span>
                  <span v-if="entry.timestamp" class="activity-item__time">
                    &nbsp;·&nbsp;{{ formatActivityTime(entry.timestamp) }}
                  </span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

    </el-tabs>

    <VariantFormDialog
      v-model="variantDialogOpen"
      :experiment-id="experimentId"
      :variant="editingVariant"
      @saved="loadPage"
    />
  </AdminPageShell>
</template>

<script setup>
import { ref, watch } from "vue"
import { ElMessage } from "element-plus"
import AdminMetricCard from "@/components/AdminMetricCard.vue"
import AdminPageShell from "@/components/AdminPageShell.vue"
import { useExperimentDetailPage } from "@/module/experiment/service/use-experiment-detail-page"
import VariantFormDialog from "@/module/variant/components/VariantFormDialog.vue"

const {
  route,
  experiment,
  experimentId,
  variants,
  releases,
  goals,
  activityLog,
  errorMessage,
  recommendedBaseUrl,
  latestRelease,
  loadPage,
  saveExperimentSettings,
  buildRelease,
  publishRelease,
  rollbackRelease,
  archiveRelease,
  goBack,
  openEditor,
} = useExperimentDetailPage()

const formatActivityTime = (iso) => {
  if (!iso) return ""
  const d = new Date(iso)
  return d.toLocaleString("zh-TW", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" })
}

// ── Tab ──
const activeTab = ref("settings")

// ── Status / label maps ──
const statusLabelMap = { draft: "草稿", running: "進行中", paused: "暫停", ended: "已結束" }
const releaseStatusLabel = { draft: "草稿", published: "已發佈", archived: "已封存" }
const goalTypeLabel = { conversion: "轉換", click: "點擊", pageview: "頁面瀏覽", custom: "自訂" }

// ── 實驗設定 form ──
const statusOptions = [
  { value: "draft", label: "草稿" },
  { value: "running", label: "進行中" },
  { value: "paused", label: "暫停" },
  { value: "ended", label: "已結束" },
]
const urlRuleOperators = [
  { value: "contains", label: "完整網址包含" },
  { value: "equals", label: "完整網址等於" },
  { value: "starts_with", label: "網址開頭為" },
  { value: "regex", label: "符合正規表達式" },
]
const deviceOptions = [
  { value: "mobile", label: "手機" },
  { value: "tablet", label: "平板" },
  { value: "desktop", label: "桌機" },
]

const defaultSettingsForm = () => ({
  name: "",
  status: "draft",
  start_at: null,
  end_at: null,
  base_url: "",
  url_rules: [],
  device_targets: [],
  hide_hashtag: false,
})

const settingsForm = ref(defaultSettingsForm())
const settingsErrors = ref({})
const settingsSaving = ref(false)
const testUrl = ref("")
const testResult = ref(null)

watch(experiment, (val) => {
  if (!val) return
  const tc = val.targetingConfig || {}
  settingsForm.value = {
    name: val.name || "",
    status: val.status || "draft",
    start_at: val.startAt || null,
    end_at: val.endAt || null,
    base_url: tc.base_url || "",
    url_rules: (tc.url_rules || []).map((r, i) => ({ ...r, _id: i })),
    device_targets: tc.device_targets || [],
    hide_hashtag: tc.hide_hashtag || false,
  }
}, { immediate: true })

const addRule = () => {
  settingsForm.value.url_rules.push({ _id: Date.now(), operator: "contains", value: "" })
}
const removeRule = (idx) => {
  settingsForm.value.url_rules.splice(idx, 1)
  testResult.value = null
}
const toggleDevice = (value) => {
  const idx = settingsForm.value.device_targets.indexOf(value)
  if (idx === -1) settingsForm.value.device_targets.push(value)
  else settingsForm.value.device_targets.splice(idx, 1)
}
const runUrlTest = () => {
  if (!testUrl.value.trim()) return
  if (settingsForm.value.url_rules.length === 0) { testResult.value = true; return }
  testResult.value = settingsForm.value.url_rules.every(rule => {
    const url = testUrl.value
    switch (rule.operator) {
      case "contains": return url.includes(rule.value)
      case "equals": return url === rule.value
      case "starts_with": return url.startsWith(rule.value)
      case "regex": try { return new RegExp(rule.value).test(url) } catch { return false }
      default: return false
    }
  })
}

const buildTargetingConfig = () => {
  const config = {}
  if (settingsForm.value.base_url.trim()) config.base_url = settingsForm.value.base_url.trim()
  const cleanRules = settingsForm.value.url_rules
    .filter(r => r.value.trim())
    .map(({ operator, value }) => ({ operator, value }))
  if (cleanRules.length > 0) config.url_rules = cleanRules
  if (settingsForm.value.device_targets.length > 0) config.device_targets = settingsForm.value.device_targets
  if (settingsForm.value.hide_hashtag) config.hide_hashtag = true
  return Object.keys(config).length > 0 ? config : null
}

const handleSaveSettings = async () => {
  settingsErrors.value = {}
  if (!settingsForm.value.name.trim()) {
    settingsErrors.value.name = "請填入實驗名稱"
    return
  }
  settingsSaving.value = true
  try {
    await saveExperimentSettings({
      name: settingsForm.value.name,
      status: settingsForm.value.status,
      start_at: settingsForm.value.start_at || null,
      end_at: settingsForm.value.end_at || null,
      targeting_config: buildTargetingConfig(),
    })
    ElMessage.success("設定已儲存")
  } catch (error) {
    ElMessage.error(error?.message || "儲存失敗")
  } finally {
    settingsSaving.value = false
  }
}

// ── 變體 ──
const variantDialogOpen = ref(false)
const editingVariant = ref(null)

const openCreateVariantDialog = () => {
  editingVariant.value = null
  variantDialogOpen.value = true
}
const openEditVariantDialog = (row) => {
  editingVariant.value = row
  variantDialogOpen.value = true
}

// ── Release ──
const buildingRelease = ref(false)
const releaseActionLoading = ref("")

const handleBuildRelease = async () => {
  buildingRelease.value = true
  try {
    await buildRelease()
    ElMessage.success("版本已建立")
  } catch (error) {
    ElMessage.error(error?.message || "建立版本失敗")
  } finally {
    buildingRelease.value = false
  }
}

const handlePublish = async (releaseId) => {
  releaseActionLoading.value = releaseId + "_publish"
  try {
    await publishRelease(releaseId)
    ElMessage.success("版本已發佈")
  } catch (error) {
    ElMessage.error(error?.message || "發佈失敗")
  } finally {
    releaseActionLoading.value = ""
  }
}

const handleRollback = async (releaseId) => {
  releaseActionLoading.value = releaseId + "_rollback"
  try {
    await rollbackRelease(releaseId)
    ElMessage.success("已回退至草稿")
  } catch (error) {
    ElMessage.error(error?.message || "回退失敗")
  } finally {
    releaseActionLoading.value = ""
  }
}

const handleArchive = async (releaseId) => {
  releaseActionLoading.value = releaseId + "_archive"
  try {
    await archiveRelease(releaseId)
    ElMessage.success("版本已封存")
  } catch (error) {
    ElMessage.error(error?.message || "封存失敗")
  } finally {
    releaseActionLoading.value = ""
  }
}
</script>

<style scoped>
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

/* ── Tabs ── */
.detail-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
}
.detail-tabs :deep(.el-tabs__nav-wrap::after) {
  background: #e2e8f0;
}

/* ── Tab card ── */
.tab-card {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 0 16px 16px 16px;
  padding: 24px 28px;
  margin-top: -1px;
}

.tab-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 14px;
  border-bottom: 1px solid #f1f5f9;
}

.tab-card__title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #0f172a;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tab-card__count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background: #f1f5f9;
  color: #64748b;
  font-size: 11px;
  font-weight: 600;
}

.tab-card__actions {
  display: flex;
  gap: 8px;
}

/* ── Section (within settings tab) ── */
.section {
  padding-bottom: 24px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f1f5f9;
}

.section:last-of-type {
  border-bottom: none;
  padding-bottom: 0;
  margin-bottom: 0;
}

.section__title {
  margin: 0 0 12px;
  font-size: 13px;
  font-weight: 700;
  color: #0f172a;
  text-transform: uppercase;
  letter-spacing: 0.08em;
}

.section__desc {
  margin: -8px 0 16px;
  font-size: 13px;
  color: #64748b;
  line-height: 1.6;
}

/* ── Form fields ── */
.field {
  margin-bottom: 16px;
}

.field:last-child {
  margin-bottom: 0;
}

.field__label {
  display: block;
  margin-bottom: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #374151;
}

.field__required {
  color: #ef4444;
  margin-left: 2px;
}

.field__hint {
  margin: 4px 0 0;
  font-size: 12px;
  color: #94a3b8;
}

.field__error {
  margin: 4px 0 0;
  font-size: 12px;
  color: #ef4444;
}

.field-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

/* ── Status pills ── */
.status-pills {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.status-pill {
  padding: 6px 14px;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  background: #f8fafc;
  font-size: 13px;
  color: #64748b;
  cursor: pointer;
  transition: all 0.15s;
}

.status-pill--active.status-pill--draft { border-color: #94a3b8; background: #f1f5f9; color: #1e293b; }
.status-pill--active.status-pill--running { border-color: #6ee7b7; background: #d1fae5; color: #065f46; }
.status-pill--active.status-pill--paused { border-color: #fde68a; background: #fef3c7; color: #92400e; }
.status-pill--active.status-pill--ended { border-color: #fecaca; background: #fee2e2; color: #991b1b; }

/* ── URL Rules ── */
.rules-box {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 12px;
  background: #f8fafc;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.rules-empty {
  margin: 0;
  font-size: 13px;
  color: #94a3b8;
  padding: 4px 2px;
}

.rule-row-wrap {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.rule-connector {
  padding-left: 4px;
}

.rule-connector__badge {
  display: inline-block;
  padding: 1px 8px;
  border-radius: 6px;
  background: #e2e8f0;
  font-size: 11px;
  font-weight: 600;
  color: #475569;
}

.rule-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.rule-delete {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: #ffffff;
  color: #94a3b8;
  cursor: pointer;
  flex-shrink: 0;
  transition: all 0.15s;
}
.rule-delete:hover { border-color: #fecaca; background: #fff1f2; color: #ef4444; }

.add-rule-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 5px 10px;
  border-radius: 8px;
  border: 1px dashed #cbd5e1;
  background: transparent;
  font-size: 12.5px;
  color: #64748b;
  cursor: pointer;
  align-self: flex-start;
  transition: all 0.15s;
}
.add-rule-btn:hover { border-color: #2563eb; color: #2563eb; }

/* ── URL Tester ── */
.url-tester {
  display: flex;
  gap: 8px;
}

.test-result {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 12.5px;
  font-weight: 500;
}
.test-result--pass { background: #d1fae5; color: #065f46; }
.test-result--fail { background: #fee2e2; color: #991b1b; }

/* ── Device pills ── */
.device-pills {
  display: flex;
  gap: 8px;
}

.device-pill {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 14px;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  background: #f8fafc;
  font-size: 13px;
  color: #64748b;
  cursor: pointer;
  transition: all 0.15s;
}
.device-pill--active { border-color: #2563eb; background: #eff6ff; color: #1d4ed8; }

/* ── Checkbox row ── */
.checkbox-row {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-input {
  width: 15px;
  height: 15px;
  accent-color: #2563eb;
}

.checkbox-label {
  font-size: 13px;
  color: #374151;
}

/* ── Settings footer ── */
.settings-footer {
  margin-top: 28px;
  padding-top: 20px;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: flex-end;
}

/* ── Row actions ── */
.row-actions {
  display: flex;
  gap: 2px;
  align-items: center;
}

.muted-text {
  font-size: 12px;
  color: #94a3b8;
}

/* ── Code block ── */
.code-block {
  margin: 0;
  overflow: auto;
  border-radius: 10px;
  background: #0f172a;
  padding: 14px 16px;
  font-size: 12px;
  line-height: 1.6;
  color: #e2e8f0;
}

.code-block--sm {
  font-size: 11px;
  padding: 10px 12px;
}

/* ── Goals ── */
.goals-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
}

.goal-item {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 14px 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.goal-item__top {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 8px;
}

.goal-item__name {
  margin: 0;
  font-size: 13.5px;
  font-weight: 600;
  color: #0f172a;
}

.goal-item__key {
  margin: 3px 0 0;
  font-size: 11.5px;
  color: #94a3b8;
}

/* ── Release cards ── */
.release-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.release-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 18px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  background: #ffffff;
  gap: 16px;
}

.release-card--published {
  border-color: #a7f3d0;
  background: #f0fdf4;
}

.release-card--archived {
  opacity: 0.6;
  background: #f8fafc;
}

.release-card__left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.release-card__version {
  font-size: 16px;
  font-weight: 700;
  color: #0f172a;
  min-width: 36px;
}

.release-card__status-badge {
  display: inline-flex;
  align-items: center;
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.release-card__status-badge--draft {
  background: #fef3c7;
  color: #92400e;
}

.release-card__status-badge--published {
  background: #d1fae5;
  color: #065f46;
}

.release-card__status-badge--archived {
  background: #f1f5f9;
  color: #64748b;
}

.release-card__actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.release-btn {
  padding: 6px 14px;
  border-radius: 8px;
  border: 1px solid;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.release-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.release-btn--publish {
  border-color: #6ee7b7;
  background: #d1fae5;
  color: #065f46;
}
.release-btn--publish:hover:not(:disabled) {
  background: #a7f3d0;
}

.release-btn--rollback {
  border-color: #fde68a;
  background: #fef3c7;
  color: #92400e;
}
.release-btn--rollback:hover:not(:disabled) {
  background: #fde68a;
}

.release-btn--archive {
  border-color: #e2e8f0;
  background: #f8fafc;
  color: #64748b;
}
.release-btn--archive:hover:not(:disabled) {
  border-color: #fecaca;
  background: #fff1f2;
  color: #dc2626;
}

/* ── Activity log ── */
.activity-list {
  display: flex;
  flex-direction: column;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding: 14px 0;
  border-bottom: 1px solid #f1f5f9;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-item__dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #cbd5e1;
  margin-top: 5px;
  flex-shrink: 0;
}

.activity-item--create .activity-item__dot { background: #3b82f6; }
.activity-item--update .activity-item__dot { background: #f59e0b; }
.activity-item--delete .activity-item__dot { background: #ef4444; }

.activity-item__content {
  flex: 1;
}

.activity-item__label {
  margin: 0;
  font-size: 13.5px;
  color: #1e293b;
  display: flex;
  gap: 6px;
  align-items: center;
}

.activity-item__action {
  font-weight: 600;
}

.activity-item__collection {
  font-size: 12px;
  color: #64748b;
  background: #f1f5f9;
  padding: 1px 7px;
  border-radius: 6px;
}

.activity-item__meta {
  margin: 3px 0 0;
  font-size: 12px;
  color: #94a3b8;
}

.activity-item__time {
  color: #94a3b8;
}

/* ── Empty state ── */
.empty-state {
  border: 1px dashed #e2e8f0;
  border-radius: 12px;
  background: #f8fafc;
  padding: 32px;
  text-align: center;
  font-size: 13.5px;
  color: #94a3b8;
}
</style>
