export const statusTypeMap = {
  draft: "warning",
  running: "success",
  paused: "info",
  ended: "danger",
}

export const statusLabelMap = {
  draft: "草稿",
  running: "進行中",
  paused: "暫停",
  ended: "已結束",
}

export const moduleTypeLabelMap = {
  visual: "視覺編輯",
  code: "代碼注入",
  redirect: "重定向",
}

export const formatDateTime = (value) => {
  if (!value) {
    return "-"
  }

  try {
    return new Date(value).toLocaleString("zh-TW")
  } catch (error) {
    return value
  }
}

export const mapExperimentListItem = (item = {}) => ({
  id: item.id || "",
  name: item.name || "未命名實驗",
  experimentKey: item.experiment_key || "",
  moduleType: item.module_type || "-",
  moduleTypeLabel: moduleTypeLabelMap[item.module_type] || item.module_type || "-",
  status: item.status || "draft",
  statusLabel: statusLabelMap[item.status] || item.status || "-",
  startAt: item.start_at || null,
  endAt: item.end_at || null,
  startAtLabel: formatDateTime(item.start_at),
  endAtLabel: formatDateTime(item.end_at),
})

export const mapExperimentDetail = (item = {}) => ({
  id: item.id || "",
  siteId: item.site_id || "",
  name: item.name || "未命名 Experiment",
  experimentKey: item.experiment_key || "",
  moduleType: item.module_type || "-",
  status: item.status || "draft",
  startAt: item.start_at || null,
  endAt: item.end_at || null,
  startAtLabel: formatDateTime(item.start_at),
  endAtLabel: formatDateTime(item.end_at),
  targetingConfig: item.targeting_config || {},
})

export const resolveExperimentBaseUrl = (experiment = null) => {
  const targetingConfig = experiment?.targetingConfig || {}
  return (
    targetingConfig.base_url ||
    targetingConfig.baseUrl ||
    targetingConfig.url ||
    targetingConfig.page_url ||
    ""
  )
}

export const summarizeExperiments = (items = []) => ({
  total: items.length,
  running: items.filter((item) => item.status === "running").length,
  draft: items.filter((item) => item.status === "draft").length,
  ended: items.filter((item) => ["ended", "paused"].includes(item.status)).length,
})

export const mapVariantItem = (item = {}) => ({
  id: item.id || "",
  variantKey: item.variant_key || "",
  name: item.name || "未命名 Variant",
  trafficWeight: item.traffic_weight ?? 0,
})

export const mapReleaseItem = (item = {}) => ({
  id: item.id || "",
  versionNo: item.version_no ?? 0,
  releaseVersion: item.version_no != null ? `v${item.version_no}` : "-",
  status: item.status || "draft",
  publishedAt: item.published_at || null,
  publishedAtLabel: formatDateTime(item.published_at),
})
