export const formatChangesJson = (items = []) => JSON.stringify(items, null, 2)

export const parseChangesJson = (value = "[]") => {
  try {
    return JSON.parse(value || "[]")
  } catch (error) {
    throw new Error("變更 JSON 格式錯誤。")
  }
}

export const mapEditorSession = (item = {}) => ({
  id: item.id || "",
  status: item.status || "",
  baseUrl: item.base_url || "",
})

export const mapPreviewOperations = (preview = {}) => preview.operations || []

export const summarizeChanges = (items = []) => {
  const byType = items.reduce((summary, item) => {
    const changeType = item.change_type || "unknown"
    summary[changeType] = (summary[changeType] || 0) + 1
    return summary
  }, {})

  return {
    total: items.length,
    byType,
    selectors: [...new Set(items.map((item) => item.selector_value).filter(Boolean))],
  }
}

export const changeTypeLabelMap = {
  replace_text: "替換文字",
  set_html: "替換 HTML",
  set_style: "調整樣式",
  set_attribute: "調整屬性",
}

export const canvasEventLabelMap = {
  ready: "畫布已就緒",
  selection: "收到區塊選取事件",
  "focus-selector": "已同步目前焦點到畫布",
  "inspect-selector": "已要求畫布檢查區塊",
  "status-summary": "已同步畫布回饋摘要",
  "select-current": "已從頁內操作選定目前區塊",
  "inspect-current": "已從頁內操作檢查目前區塊",
  "edit-current": "已從頁內操作開始編輯目前區塊",
  "edit-text-current": "已從頁內操作開始修改文字",
  "edit-link-current": "已從頁內操作開始調整連結",
  "edit-image-current": "已從頁內操作開始調整圖片",
  "edit-style-current": "已從頁內操作開始調整樣式",
  "confirm-current": "已從頁內操作回到畫面確認",
}

export const canvasModeLabelMap = {
  idle: "等待選取",
  hover: "候選比對中",
  compare: "比較候選中",
  inspect: "正式檢查中",
  focus: "回到畫面確認",
  "preview-ready": "可回畫面確認",
  "preview-pending": "預覽待更新",
}

export const suggestChangeTypeFromElement = (selectedElementMeta = {}) => {
  const tag = String(selectedElementMeta.tag || "").toLowerCase()
  const text = String(selectedElementMeta.text || "").trim()
  const href = String(selectedElementMeta.href || "").trim()
  const src = String(selectedElementMeta.src || "").trim()

  if (tag === "img" || src) {
    return {
      changeType: "set_attribute",
      label: "調整圖片",
      reason: "目前選到的是圖片區塊，通常會先調整圖片來源或相關屬性。",
    }
  }

  if (tag === "a" || href) {
    return {
      changeType: "set_attribute",
      label: "調整連結",
      reason: "目前選到的是連結，通常會先調整網址或追蹤參數。",
    }
  }

  if (["h1", "h2", "h3", "p", "span", "button"].includes(tag) && text) {
    return {
      changeType: "replace_text",
      label: "修改文字",
      reason: "目前選到的是文字區塊，先直接改文案通常最直覺。",
    }
  }

  return {
    changeType: "set_style",
    label: "調整樣式",
    reason: "目前看起來比較像容器或版型區塊，先從樣式調整開始會比較安全。",
  }
}

export const buildCanvasCandidates = (items = []) => {
  const selectors = [...new Set(items.map((item) => item.selector_value).filter(Boolean))]

  if (selectors.length > 0) {
    return selectors.slice(0, 6).map((selector, index) => ({
      id: `${selector}-${index}`,
      selector,
      label: `區塊 ${index + 1}`,
      source: "changes",
    }))
  }

  return [
    {
      id: "hero-title",
      selector: ".hero-title",
      label: "主標題",
      source: "placeholder",
    },
    {
      id: "hero-copy",
      selector: ".hero-copy",
      label: "主說明",
      source: "placeholder",
    },
    {
      id: "cta-button",
      selector: "a.cta-button",
      label: "行動按鈕",
      source: "placeholder",
    },
  ]
}

export const buildInspectorSummary = ({ selectedSelector, changes = [], previewOperations = [] }) => {
  const matchedChanges = changes.filter(
    (item) => item.selector_value && item.selector_value === selectedSelector
  )
  const matchedOperations = previewOperations.filter(
    (item) => item.selector_value && item.selector_value === selectedSelector
  )

  if (!selectedSelector) {
    return {
      title: "等待選取畫布元素",
      description: "先從可編輯區塊選一個目標，這裡才會顯示對應的修改與預覽狀態。",
      risk: "neutral",
      matchedChanges: 0,
      matchedOperations: 0,
    }
  }

  return {
    title: selectedSelector,
    description:
      matchedChanges.length > 0
        ? "這個區塊目前已經有修改內容，可以直接檢查預覽結果。"
        : "這個區塊目前還沒有修改內容，可以直接從快速範本開始。",
    risk: matchedChanges.length > 0 ? "active" : "pending",
    matchedChanges: matchedChanges.length,
    matchedOperations: matchedOperations.length,
  }
}

export const buildInteractionStateSummary = ({
  hoveredElementMeta = {},
  selectedSelector,
  selectedElementMeta = {},
}) => {
  if (!hoveredElementMeta.selector && !selectedSelector) {
    return {
      title: "先在畫面上滑過一個區塊",
      description: "先滑過看看目前候選的是哪個區塊，確認對了再把它設成正式檢查目標。",
      stage: "idle",
      actionLabel: "前往畫面區",
    }
  }

  if (hoveredElementMeta.selector && !selectedSelector) {
    return {
      title: "目前正在預覽候選區塊",
      description: `目前滑過：${hoveredElementMeta.selector}，如果是你要改的區塊，可以直接設成正式檢查目標。`,
      stage: "hover",
      actionLabel: "設為檢查目標",
    }
  }

  if (hoveredElementMeta.selector && hoveredElementMeta.selector !== selectedSelector) {
    return {
      title: "已鎖定檢查目標，仍可繼續滑過比較",
      description: `目前檢查：${selectedSelector}；目前滑過：${hoveredElementMeta.selector}。你可以比較後再決定要不要切換。`,
      stage: "compare",
      actionLabel: "檢查目前目標",
    }
  }

  return {
    title: "目前正在正式檢查這個區塊",
    description: `目前檢查：${selectedSelector}。接下來可直接進入修改、預覽與畫面確認。`,
    stage: selectedElementMeta.source === "canvas-hover-promoted" ? "selected" : "inspect",
    actionLabel: "回到畫面檢查",
  }
}

export const buildWorkspaceConsistency = ({
  selectedSelector,
  draft,
  changes = [],
  previewOperations = [],
}) => {
  const draftSelector = draft?.selector_value || ""
  const changeSelectors = [...new Set(changes.map((item) => item.selector_value).filter(Boolean))]
  const previewSelectors = [
    ...new Set(previewOperations.map((item) => item.selector_value).filter(Boolean)),
  ]

  const issues = []

  if (!selectedSelector) {
    issues.push("尚未從 canvas 選取目標元素")
  }

  if (selectedSelector && draftSelector !== selectedSelector) {
    issues.push("目前草稿 selector 尚未同步到最新選取元素")
  }

  if (!draftSelector) {
    issues.push("目前草稿還沒有 selector")
  }

  if (draftSelector && !changeSelectors.includes(draftSelector)) {
    issues.push("草稿尚未寫入變更清單")
  }

  if (changeSelectors.length > 0 && previewSelectors.length === 0) {
    issues.push("已有變更但尚未建立 preview")
  }

  if (issues.length === 0) {
    return {
      level: "ready",
      title: "目前編輯流程是同步的",
      description: "目前選取區塊、修改內容、變更清單與預覽結果已大致一致。",
      issues: [],
    }
  }

  return {
    level: issues.length >= 3 ? "warning" : "info",
    title: "還有幾個步驟沒對齊",
    description: "先把下面幾個缺口補齊，這次編輯流程會更順。",
    issues,
  }
}

export const createChangeDraft = (selector = "") => ({
  change_type: "replace_text",
  selector_type: "css",
  selector_value: selector,
  payload: {
    text: "新的主標題文案",
  },
})

export const normalizeDraftByType = (draft = {}) => {
  const nextDraft = {
    change_type: draft.change_type || "replace_text",
    selector_type: draft.selector_type || "css",
    selector_value: draft.selector_value || "",
    payload: draft.payload || {},
  }

  switch (nextDraft.change_type) {
    case "set_html":
      nextDraft.payload = {
        html: nextDraft.payload.html || "<strong>新的 HTML 內容</strong>",
      }
      break
    case "set_style":
      nextDraft.payload = {
        property: nextDraft.payload.property || "backgroundColor",
        value: nextDraft.payload.value || "#111827",
      }
      break
    case "set_attribute":
      nextDraft.payload = {
        name: nextDraft.payload.name || "href",
        value: nextDraft.payload.value || "https://ose.tw",
      }
      break
    default:
      nextDraft.payload = {
        text: nextDraft.payload.text || "新的主標題文案",
      }
      break
  }

  return nextDraft
}

export const buildSelectedSelectorSnapshot = ({
  selectedSelector,
  changes = [],
  previewOperations = [],
}) => {
  if (!selectedSelector) {
    return {
      changes: [],
      previewOperations: [],
    }
  }

  return {
    changes: changes.filter((item) => item.selector_value === selectedSelector),
    previewOperations: previewOperations.filter(
      (item) => item.selector_value === selectedSelector
    ),
  }
}

export const buildSelectedElementSummary = ({
  selectedSelector,
  selectedElementMeta = {},
}) => {
  if (!selectedSelector) {
    return {
      title: "尚未選取畫面區塊",
      description: "先從畫面編輯區選一個區塊，這裡才會顯示元素摘要。",
      tagLabel: "-",
      textPreview: "尚未收到畫面元素內容",
      attributeLabel: "等待畫布回應",
      sourceLabel: "等待畫布回應",
    }
  }

  const tag = selectedElementMeta.tag || "未知元素"
  const textPreview = selectedElementMeta.text || "目前這個區塊還沒有文字摘要。"
  const href = selectedElementMeta.href || ""
  const src = selectedElementMeta.src || ""
  const source = selectedElementMeta.source || "editor-workspace"
  const suggestion = suggestChangeTypeFromElement(selectedElementMeta)
  const attributeLabel =
    tag === "a" || href
      ? href || "目前沒有連結網址"
      : tag === "img" || src
      ? src || "目前沒有圖片來源"
      : "這個區塊目前沒有重點屬性"

  return {
    title: selectedSelector,
    description: "這是目前畫布回傳的元素摘要，後面會再接上更多 inspect 細節。",
    tagLabel: tag,
    textPreview,
    attributeLabel,
    recommendedChangeType: suggestion.changeType,
    recommendedLabel: suggestion.label,
    recommendedActionLabel:
      suggestion.changeType === "replace_text"
        ? "開始修改文字"
        : suggestion.label === "調整圖片"
        ? "開始調整圖片"
        : suggestion.changeType === "set_attribute"
        ? "開始調整連結"
        : suggestion.changeType === "set_html"
        ? "開始調整內容區塊"
        : "開始調整樣式",
    recommendedReason: suggestion.reason,
    sourceLabel:
      source === "canvas-click"
        ? "來自畫面點選"
        : source === "candidate-button"
        ? "來自候選區塊"
        : source === "canvas-bridge"
        ? "來自畫布橋接"
        : source,
  }
}

export const buildQuickEditActions = ({
  selectedSelector,
  selectedElementSummary = {},
  selectedElementMeta = {},
}) => {
  if (!selectedSelector) {
    return []
  }

  const tag = String(selectedElementMeta.tag || "").toLowerCase()
  const hasHref = Boolean(selectedElementMeta.href)
  const hasSrc = Boolean(selectedElementMeta.src)
  const actions = []

  if (tag === "img" || hasSrc) {
    actions.push({
      key: "set_attribute",
      label: "換圖片",
      description: "直接調整圖片網址或圖片來源。",
    })
  } else if (tag === "a" || hasHref) {
    actions.push({
      key: "set_attribute",
      label: "改連結",
      description: "直接調整網址或追蹤參數。",
    })
  } else {
    actions.push({
      key: "replace_text",
      label: "改文字",
      description: "先從文案開始修改，最直覺也最好驗證。",
    })
  }

  actions.push({
    key: "set_style",
    label: "改樣式",
    description: "調整外觀、背景、間距或其他版型樣式。",
  })

  if (selectedElementSummary?.recommendedChangeType === "set_html") {
    actions.unshift({
      key: "set_html",
      label: "改內容區塊",
      description: "需要一起調整排版時，可以直接改區塊內容。",
    })
  }

  return actions.slice(0, 3)
}

export const buildRecommendedFlowSummary = ({
  selectedSelector,
  selectedElementSummary,
  draft,
  previewOperations = [],
}) => {
  if (!selectedSelector) {
    return {
      title: "先從畫面中選一個區塊",
      description: "選到區塊後，系統才知道要幫你推薦哪種修改方式。",
      actionLabel: "等待選取區塊",
      readyForPreview: false,
    }
  }

  const draftMatchesSelection =
    draft?.selector_value && draft.selector_value === selectedSelector
  const previewMatchesSelection = previewOperations.some(
    (item) => item.selector_value && item.selector_value === selectedSelector
  )

  if (!draftMatchesSelection) {
    return {
      title: `建議先用「${selectedElementSummary.recommendedLabel}」開始`,
      description: selectedElementSummary.recommendedReason,
      actionLabel: "先套用建議到草稿",
      readyForPreview: false,
    }
  }

  if (!previewMatchesSelection) {
    return {
      title: "這個區塊還沒進入最新預覽",
      description: "目前草稿已經對齊這個區塊，下一步建議直接建立預覽確認結果。",
      actionLabel: "建立這個區塊的預覽",
      readyForPreview: true,
    }
  }

  return {
    title: "這個區塊已經可以檢查預覽",
    description: "目前草稿與預覽都已經對齊，可以回到畫面上確認效果。",
    actionLabel: "回到畫面檢查",
    readyForPreview: true,
  }
}

export const buildDraftFormGuide = ({
  draft = {},
  selectedElementSummary = {},
  selectedElementMeta = {},
}) => {
  const changeType = draft?.change_type || "replace_text"
  const recommendedLabel = selectedElementSummary?.recommendedLabel || "修改內容"
  const tag = String(selectedElementMeta?.tag || "").toLowerCase()
  const hasHref = Boolean(selectedElementMeta?.href)
  const hasSrc = Boolean(selectedElementMeta?.src)

  const baseGuide = {
    sectionTitle: "修改草稿",
    sectionDescription: `你現在正在準備「${recommendedLabel}」的內容，確認後再加入修改清單。`,
    selectorLabel: "目標區塊",
    changeTypeLabel: "修改方式",
    primaryFieldLabel: "內容",
    secondaryFieldLabel: "值",
    primaryPlaceholder: "",
    secondaryPlaceholder: "",
  }

  if (changeType === "replace_text") {
    return {
      ...baseGuide,
      sectionDescription: "直接修改這個區塊要顯示的文案內容。",
      primaryFieldLabel: "文字內容",
      primaryPlaceholder: selectedElementMeta?.text || "輸入新的文案內容",
    }
  }

  if (changeType === "set_html") {
    return {
      ...baseGuide,
      sectionDescription: "直接替換這個區塊的 HTML 內容，適合需要同時調整排版時使用。",
      primaryFieldLabel: "HTML 內容",
      primaryPlaceholder: selectedElementMeta?.text || "<strong>輸入新的 HTML 內容</strong>",
    }
  }

  if (changeType === "set_attribute") {
    const isImage = tag === "img" || hasSrc
    const isLink = tag === "a" || hasHref

    return {
      ...baseGuide,
      sectionDescription: isImage
        ? "調整這張圖片的來源網址或相關屬性。"
        : isLink
        ? "調整這個連結的網址或追蹤參數。"
        : "調整這個區塊的屬性值。",
      primaryFieldLabel: isImage
        ? "圖片屬性"
        : isLink
        ? "連結屬性"
        : "屬性名稱",
      secondaryFieldLabel: isImage
        ? "圖片網址"
        : isLink
        ? "連結網址"
        : "屬性值",
      primaryPlaceholder: isImage ? "src" : isLink ? "href" : "輸入屬性名稱",
      secondaryPlaceholder: isImage
        ? selectedElementMeta?.src || "輸入新的圖片網址"
        : isLink
        ? selectedElementMeta?.href || "輸入新的連結網址"
        : "輸入新的屬性值",
    }
  }

  if (changeType === "set_style") {
    return {
      ...baseGuide,
      sectionDescription: "調整這個區塊的外觀，例如顏色、背景或間距。",
      primaryFieldLabel: "樣式欄位",
      secondaryFieldLabel: "樣式值",
      primaryPlaceholder: "例如：backgroundColor",
      secondaryPlaceholder: "例如：#111827",
    }
  }

  return baseGuide
}

export const buildSelectedPreviewSummary = ({
  selectedSelector,
  selectedSelectorSnapshot,
}) => {
  if (!selectedSelector) {
    return {
      title: "先選取一個區塊",
      description: "選到區塊後，這裡才會告訴你目前預覽有沒有反映它的修改。",
      status: "idle",
      actionLabel: "等待選取區塊",
    }
  }

  if ((selectedSelectorSnapshot?.previewOperations || []).length === 0) {
    return {
      title: "這個區塊還沒有預覽結果",
      description: "目前這個區塊還沒進入 preview，建議先建立或更新預覽。",
      status: "warning",
      actionLabel: "建立這個區塊的預覽",
    }
  }

  return {
    title: "這個區塊已有預覽結果",
    description: "目前預覽已經有對應這個區塊的操作，可以回到畫面編輯區檢查效果。",
    status: "ready",
    actionLabel: "回到畫面檢查",
  }
}

export const buildCanvasCheckSummary = ({
  selectedSelector,
  selectedElementSummary,
  selectedPreviewSummary,
}) => {
  if (!selectedSelector) {
    return {
      title: "先在畫面中選一個區塊",
      description: "選到區塊後，才有辦法回到畫面上確認目前修改是不是對準目標。",
      actionLabel: "等待選取區塊",
      emphasis: "idle",
    }
  }

  if (selectedPreviewSummary.status !== "ready") {
    return {
      title: "先讓這個區塊進入預覽",
      description: "這樣回到畫面檢查時，才看得到目前這個區塊的修改結果。",
      actionLabel: "先完成預覽",
      emphasis: "warning",
    }
  }

  return {
    title: `回到畫面檢查 ${selectedElementSummary.recommendedLabel}`,
    description: "目前這個區塊已經有預覽結果，下一步建議回到畫面編輯區確認實際效果。",
    actionLabel: "回到畫面檢查",
    emphasis: "ready",
  }
}

export const buildPreviewFreshness = ({
  changes = [],
  previewOperations = [],
  draft = {},
}) => {
  const selectorsInChanges = [
    ...new Set(changes.map((item) => item.selector_value).filter(Boolean)),
  ]
  const selectorsInPreview = [
    ...new Set(previewOperations.map((item) => item.selector_value).filter(Boolean)),
  ]

  const draftHasSelector = Boolean(draft?.selector_value)
  const missingFromPreview = selectorsInChanges.filter(
    (selector) => !selectorsInPreview.includes(selector)
  )

  if (changes.length === 0) {
    return {
      level: "neutral",
      title: "目前還沒有修改內容",
      description: "目前還沒有建立任何修改，所以還不需要產生預覽。",
      actionHint: "先建立第一筆修改",
    }
  }

  if (previewOperations.length === 0) {
    return {
      level: "warning",
      title: "預覽還沒建立",
      description: "目前已經有修改內容，但還沒有產生預覽結果。",
      actionHint: "立即建立預覽",
    }
  }

  if (missingFromPreview.length > 0) {
    return {
      level: "warning",
      title: "預覽可能不是最新的",
      description: `目前有 ${missingFromPreview.length} 個修改區塊還沒有反映到預覽結果。`,
      actionHint: "重新建立預覽",
    }
  }

  if (draftHasSelector && !selectorsInChanges.includes(draft.selector_value)) {
    return {
      level: "info",
      title: "目前草稿還沒進入預覽",
      description: "你已經選好區塊並編輯草稿，但這筆內容還沒加入修改清單。",
      actionHint: "先把草稿加入修改清單",
    }
  }

  return {
    level: "ready",
    title: "預覽與修改內容大致同步",
    description: "目前預覽內容已能反映既有修改，可繼續檢查畫面與細節。",
    actionHint: "可繼續檢查畫面與細節",
  }
}

export const buildCanvasFeedbackSummary = ({
  interactionStateSummary,
  selectedSelector,
  hoveredElementMeta = {},
  selectedElementSummary,
  selectedPreviewSummary,
  previewFreshness,
}) => {
  if (!selectedSelector && !hoveredElementMeta.selector) {
    return {
      mode: "idle",
      modeLabel: "等待選取",
      status: "info",
      title: "先在畫面上滑過想調整的區塊",
      selectorLabel: "尚未選取區塊",
      detail: "滑過畫面後，這裡會同步顯示目前候選區塊與下一步。",
      helper: "先移到畫面編輯區找目標區塊",
      primaryActionLabel: "",
      secondaryActionLabel: "",
    }
  }

  if (interactionStateSummary?.stage === "hover" && hoveredElementMeta.selector) {
    return {
      mode: "hover",
      modeLabel: "候選比對中",
      status: "warning",
      title: "目前正在比對候選區塊",
      selectorLabel: hoveredElementMeta.selector,
      detail:
        hoveredElementMeta.text || "目前已滑到一個候選區塊，確認正確後可直接設成檢查目標。",
      helper: "確認這個區塊對不對，再設成正式檢查目標",
      primaryActionLabel: "設為檢查目標",
      secondaryActionLabel: "先檢查這個區塊",
    }
  }

  if (interactionStateSummary?.stage === "compare" && hoveredElementMeta.selector) {
    return {
      mode: "compare",
      modeLabel: "比較候選中",
      status: "warning",
      title: "目前正在比較兩個區塊",
      selectorLabel: `${selectedSelector} ↔ ${hoveredElementMeta.selector}`,
      detail: `目前已鎖定 ${selectedSelector}，但滑過的候選區塊是 ${hoveredElementMeta.selector}，可先比較再決定是否切換。`,
      helper: "可先檢查目前目標，或改成新的候選區塊",
      primaryActionLabel: "設為檢查目標",
      secondaryActionLabel: "先檢查這個區塊",
    }
  }

  if (selectedPreviewSummary?.status === "ready") {
    return {
      mode: "preview-ready",
      modeLabel: "可回畫面確認",
      status: "success",
      title: "這個區塊已可回到畫面檢查",
      selectorLabel: selectedSelector,
      detail:
        selectedElementSummary?.textPreview ||
        "這個區塊目前已有預覽結果，可以直接回到畫面確認修改效果。",
      helper: "目前預覽已就緒，可回畫面檢查實際效果",
      primaryActionLabel: "回到畫面確認",
      secondaryActionLabel:
        selectedElementSummary?.recommendedActionLabel || "調整這個區塊",
    }
  }

  if (previewFreshness?.level === "warning") {
    return {
      mode: "preview-pending",
      modeLabel: "預覽待更新",
      status: "warning",
      title: "這個區塊還需要更新預覽",
      selectorLabel: selectedSelector,
      detail:
        previewFreshness.description ||
        "目前這個區塊已有修改內容，但預覽還沒有完全跟上。",
      helper: previewFreshness.actionHint || "先建立或更新預覽，再回畫面檢查",
      primaryActionLabel: "回到畫面確認",
      secondaryActionLabel:
        selectedElementSummary?.recommendedActionLabel || "調整這個區塊",
    }
  }

  return {
    mode: "inspect",
    modeLabel: "正式檢查中",
    status: "info",
    title: selectedElementSummary?.title || "目前正在檢查這個區塊",
    selectorLabel: selectedSelector || "尚未選取區塊",
    detail:
      selectedElementSummary?.textPreview ||
      "目前正在檢查這個區塊的元素摘要，可繼續修改內容或建立預覽。",
    helper: "可繼續調整草稿，或直接建立預覽",
    primaryActionLabel: "回到畫面確認",
    secondaryActionLabel:
      selectedElementSummary?.recommendedActionLabel || "開始修改這個區塊",
  }
}

export const editorChangeTemplates = [
  {
    key: "replace_text",
    label: "文字替換",
    item: {
      change_type: "replace_text",
      selector_type: "css",
      selector_value: ".hero-title",

      payload: {
        text: "新的主標題文案",
      },
    },
  },
  {
    key: "set_html",
    label: "HTML 區塊",
    item: {
      change_type: "set_html",
      selector_type: "css",
      selector_value: ".hero-copy",

      payload: {
        html: "<strong>限時實驗版本</strong>",
      },
    },
  },
  {
    key: "set_style",
    label: "樣式調整",
    item: {
      change_type: "set_style",
      selector_type: "css",
      selector_value: ".hero-banner",

      payload: {
        property: "backgroundColor",
        value: "#111827",
      },
    },
  },
  {
    key: "set_attribute",
    label: "屬性調整",
    item: {
      change_type: "set_attribute",
      selector_type: "css",
      selector_value: "a.cta-button",

      payload: {
        name: "href",
        value: "https://ose.tw",
      },
    },
  },
]

export const buildWorkspaceReadiness = ({
  baseUrl,
  session,
  changes,
  previewOperations,
}) => {
  if (!baseUrl) {
    return {
      level: "warning",
      title: "先填入要編輯的頁面網址",
      description: "先告訴系統你想編輯哪一頁，後面才知道要預覽哪個頁面內容。",
    }
  }

  if (!session?.id) {
    return {
      level: "warning",
      title: "先開始這次編輯",
      description: "按一下開始編輯，系統才會建立這次的工作流程與暫存內容。",
    }
  }

  if (changes.length === 0) {
    return {
      level: "warning",
      title: "先建立第一個修改項目",
      description: "先選一個區塊，建立第一筆修改，後面才能預覽成果。",
    }
  }

  if (previewOperations.length === 0) {
    return {
      level: "neutral",
      title: "可以先看看預覽結果了",
      description: "目前已經有編輯內容，建議先產生預覽，確認改動是否正確。",
    }
  }

  return {
    level: "ready",
    title: "這份編輯內容已準備完成",
    description: "目前已經有編輯內容與預覽結果，接下來可以進一步檢查細節與準備發佈。",
  }
}

export const buildWorkspaceNextAction = ({
  baseUrl,
  session,
  changes,
  previewOperations,
}) => {
  if (!baseUrl) {
    return {
      key: "set_base_url",
      label: "先填入頁面網址",
      description: "請先輸入你要編輯的頁面網址，後面才有辦法做預覽。",
      buttonLabel: "請先輸入網址",
      disabled: true,
    }
  }

  if (!session?.id) {
    return {
      key: "create_session",
      label: "開始這次編輯",
      description: "先建立這次編輯工作，後面才能儲存與預覽。",
      buttonLabel: "開始編輯",
      disabled: false,
    }
  }

  if (changes.length === 0) {
    return {
      key: "apply_template",
      label: "加入第一個修改項目",
      description: "可以先用範本快速建立第一筆修改，再慢慢調整內容。",
      buttonLabel: "快速加入文字修改",
      disabled: false,
    }
  }

  if (previewOperations.length === 0) {
    return {
      key: "build_preview",
      label: "先看預覽結果",
      description: "先產生預覽，確認你剛剛的改動是否有套用成功。",
      buttonLabel: "建立預覽",
      disabled: false,
    }
  }

  return {
    key: "canvas_next",
    label: "繼續檢查畫面與細節",
    description: "目前已經有預覽，可往畫面編輯區與右側檢查區繼續確認內容。",
    buttonLabel: "查看畫面編輯區",
    disabled: false,
  }
}

export const buildWorkspaceJourney = ({
  baseUrl,
  session,
  changes,
  previewOperations,
}) => [
  {
    key: "target-page",
    label: "選定頁面",
    description: "填入要編輯的頁面網址。",
    status: baseUrl ? "done" : "active",
  },
  {
    key: "session",
    label: "開始編輯",
    description: "建立這次編輯工作與暫存內容。",
    status: session?.id ? "done" : baseUrl ? "active" : "pending",
  },
  {
    key: "changes",
    label: "設定修改",
    description: "選區塊、改內容，建立第一批修改項目。",
    status:
      changes.length > 0 ? "done" : session?.id ? "active" : "pending",
  },
  {
    key: "preview",
    label: "確認預覽",
    description: "先確認改動有沒有套用成功。",
    status:
      previewOperations.length > 0
        ? "done"
        : changes.length > 0
        ? "active"
        : "pending",
  },
]

export const buildOperatorGuide = ({
  baseUrl,
  session,
  selectedSelector,
  draft,
  changes = [],
  previewOperations = [],
}) => {
  const draftSelector = draft?.selector_value || ""

  return [
    {
      key: "page",
      title: "1. 選好要編輯的頁面",
      done: Boolean(baseUrl),
      description: baseUrl
        ? "目前已指定頁面網址，可以往下一步操作。"
        : "先填入你想編輯的頁面網址，系統才知道要預覽哪一頁。",
    },
    {
      key: "session",
      title: "2. 開始這次編輯",
      done: Boolean(session?.id),
      description: session?.id
        ? "這次編輯工作已建立，可以開始加入修改內容。"
        : "按下「開始編輯」，建立這次的暫存工作流程。",
    },
    {
      key: "select",
      title: "3. 選一個想調整的區塊",
      done: Boolean(selectedSelector),
      description: selectedSelector
        ? `目前已選取：${selectedSelector}`
        : "先從畫面編輯區挑一個想調整的區塊。",
    },
    {
      key: "draft",
      title: "4. 設定修改內容",
      done: Boolean(draftSelector),
      description: draftSelector
        ? "目前草稿已指定目標區塊，可繼續修改內容。"
        : "把選到的區塊同步到草稿，再選擇你要改文字、樣式或連結。",
    },
    {
      key: "changes",
      title: "5. 加入修改清單",
      done: changes.length > 0,
      description:
        changes.length > 0
          ? `目前已有 ${changes.length} 筆修改項目。`
          : "把草稿加入修改清單，後面才能正式產生預覽。",
    },
    {
      key: "preview",
      title: "6. 看預覽結果",
      done: previewOperations.length > 0,
      description:
        previewOperations.length > 0
          ? "目前已建立預覽，可檢查修改是否有正確套用。"
          : "建立預覽，先確認這次改動有沒有成功套用。",
    },
  ]
}
