import { formatDateTime } from "@/module/experiment/model/experiment-view-model";

export const mapVariantDetail = (item = {}) => ({
  id: item.id || "",
  experimentId: item.experiment_id || "",
  variantKey: item.variant_key || "",
  name: item.name || "未命名 Variant",
  trafficWeight: item.traffic_weight ?? 0,
  contentConfig: item.content_config || {},
});

export const summarizeVariantChanges = (items = []) => ({
  total: items.length,
  text: items.filter((item) => item.change_type === "replace_text").length,
  html: items.filter((item) => item.change_type === "set_html").length,
  style: items.filter((item) => item.change_type === "set_style").length,
  attribute: items.filter((item) => item.change_type === "set_attribute").length,
});

export const buildVariantEditorEntry = ({ variant, changes = [], baseUrl }) => {
  if (!baseUrl) {
    return {
      level: "warning",
      title: "尚未帶入可編輯頁面網址",
      description: "先從實驗設定帶入 base URL，進 editor 後才會直接定位到正確頁面。",
      actionLabel: "先補頁面網址",
    };
  }

  if (!variant?.id) {
    return {
      level: "warning",
      title: "Variant 尚未就緒",
      description: "先確認 variant 基本資料，再進入 editor。",
      actionLabel: "等待載入",
    };
  }

  if (changes.length === 0) {
    return {
      level: "info",
      title: "可以開始建立第一個修改內容",
      description: "目前還沒有變更內容，適合直接進 editor 先建立第一筆調整。",
      actionLabel: "開始編輯這個 Variant",
    };
  }

  return {
    level: "ready",
    title: "這個 Variant 已有修改內容",
    description: "可以直接進 editor 繼續調整，或回頭檢查 preview 與 runtime payload。",
    actionLabel: "繼續編輯這個 Variant",
  };
};

export const buildVariantRoleLabel = () => "實驗版本";

export const mapVariantChangeCards = (items = []) =>
  items.map((item, index) => ({
    id: `${item.selector_value || "selector"}-${item.change_type || "change"}-${index}`,
    selector: item.selector_value || "未指定區塊",
    changeType: item.change_type || "unknown",
    changeTypeLabel:
      item.change_type === "replace_text"
        ? "替換文字"
        : item.change_type === "set_html"
        ? "替換 HTML"
        : item.change_type === "set_style"
        ? "調整樣式"
        : item.change_type === "set_attribute"
        ? "調整屬性"
        : item.change_type || "未命名操作",
    payloadPreview: JSON.stringify(item.payload || {}, null, 2),
  }));

export const buildVariantUpdatedHint = (value) =>
  value ? formatDateTime(value) : "目前尚未記錄更新時間";
