import { describe, expect, test, vi } from "vitest";
import { TSurveyBlock } from "@formbricks/types/surveys/blocks";
import { TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import {
  addBlock,
  addElementToBlock,
  deleteBlock,
  deleteElementFromBlock,
  duplicateBlock,
  duplicateElementInBlock,
  fillEmptyBlockButtonLabels,
  findElementLocation,
  getBlockDisplayName,
  isAutoBlockName,
  isElementIdUnique,
  moveBlock,
  moveElementInBlock,
  renumberAutoNamedBlocks,
  updateBlock,
  updateElementInBlock,
} from "./blocks";

vi.mock("@paralleldrive/cuid2", () => ({
  createId: vi.fn(() => "test-cuid-" + Math.random().toString(36).substring(7)),
}));

// Mirrors the real interpolation for the one key under test; every other key passes through.
const mockT = ((key: string, options?: { blockNumber?: number }) =>
  key === "workspace.surveys.edit.block_n" ? `Block ${options?.blockNumber}` : key) as never;

const createMockElement = (id: string): TSurveyElement => ({
  id,
  type: TSurveyElementTypeEnum.OpenText,
  headline: { default: "Test Question" },
  required: false,
  inputType: "text",
  longAnswer: true,
  charLimit: { enabled: false },
});

const createMockBlock = (id: string, name: string, elements: TSurveyElement[] = []): TSurveyBlock => ({
  id,
  name,
  elements,
});

const createMockSurvey = (blocks: TSurveyBlock[] = []): TSurvey => ({
  id: "survey-1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Test Survey",
  type: "link",
  workspaceId: "ws-1",
  createdBy: null,
  status: "draft",
  visibility: "workspace",
  ownerId: null,
  visibilityVersion: 0,
  visibilityProjectedVersion: 0,
  visibilityChangedAt: null,
  visibilityChangedById: null,
  displayOption: "respondMultiple",
  autoClose: null,
  publishOn: null,
  closeOn: null,
  isAutoProgressingEnabled: false,
  triggers: [],
  recontactDays: null,
  displayLimit: null,
  welcomeCard: {
    enabled: false,
    headline: { default: "Welcome" },
    timeToFinish: false,
    showResponseCount: false,
  },
  questions: [],
  blocks,
  endings: [],
  hiddenFields: { enabled: false, fieldIds: [] },
  variables: [],
  styling: null,
  segment: null,
  languages: [],
  displayPercentage: null,
  isVerifyEmailEnabled: false,
  singleUse: null,
  pin: null,
  workspaceOverwrites: null,
  surveyClosedMessage: null,
  followUps: [],
  delay: 0,
  autoComplete: null,
  showLanguageSwitch: null,
  recaptcha: null,
  isBackButtonHidden: false,
  metadata: {},
  isCaptureIpEnabled: false,
  isAnonymizeResponsesEnabled: false,
  slug: null,
});

describe("isAutoBlockName", () => {
  test("should treat the auto-generated pattern as unset", () => {
    expect(isAutoBlockName("Block 1")).toBe(true);
    expect(isAutoBlockName("Block 42")).toBe(true);
  });

  test("should not treat a blank name as auto-generated", () => {
    // A cleared field is an edit in progress; renumbering must not overwrite it.
    expect(isAutoBlockName("")).toBe(false);
    expect(isAutoBlockName("   ")).toBe(false);
  });

  test("should treat a creator-set name as set", () => {
    expect(isAutoBlockName("Screening")).toBe(false);
    expect(isAutoBlockName("Block A")).toBe(false);
    expect(isAutoBlockName("Block 1 - Screening")).toBe(false);
  });
});

describe("getBlockDisplayName", () => {
  test("should return the creator's name when set", () => {
    const block = createMockBlock("block-1", "Screening");
    expect(getBlockDisplayName(block, 4, mockT)).toBe("Screening");
  });

  test("should trim the creator's name", () => {
    const block = createMockBlock("block-1", "  Screening  ");
    expect(getBlockDisplayName(block, 0, mockT)).toBe("Screening");
  });

  test("should keep an auto-generated name as-is", () => {
    // Resequencing auto names is renumberAutoNamedBlocks's job, not the label helper's.
    const block = createMockBlock("block-1", "Block 3");
    expect(getBlockDisplayName(block, 0, mockT)).toBe("Block 3");
  });

  test("should fall back to the current position for a blank name", () => {
    const block = createMockBlock("block-1", "   ");
    expect(getBlockDisplayName(block, 1, mockT)).toBe("Block 2");
  });
});

describe("renumberAutoNamedBlocks", () => {
  test("should resequence auto-generated names to match position", () => {
    const blocks = [createMockBlock("b1", "Block 4"), createMockBlock("b2", "Block 9")];

    expect(renumberAutoNamedBlocks(blocks).map((block) => block.name)).toEqual(["Block 1", "Block 2"]);
  });

  test("should leave creator-set names untouched", () => {
    const blocks = [
      createMockBlock("b1", "Screening"),
      createMockBlock("b2", "Block 7"),
      createMockBlock("b3", "Feedback"),
    ];

    expect(renumberAutoNamedBlocks(blocks).map((block) => block.name)).toEqual([
      "Screening",
      "Block 2",
      "Feedback",
    ]);
  });

  test("should leave a blank name blank", () => {
    const blocks = [createMockBlock("b1", "Screening"), createMockBlock("b2", "   ")];

    expect(renumberAutoNamedBlocks(blocks)[1].name).toBe("   ");
  });
});

describe("isElementIdUnique", () => {
  test("should return true for a unique element ID", () => {
    const blocks = [
      createMockBlock("block-1", "Block 1", [createMockElement("q1")]),
      createMockBlock("block-2", "Block 2", [createMockElement("q2")]),
    ];

    expect(isElementIdUnique("q3", blocks)).toBe(true);
  });

  test("should return false for a duplicate element ID", () => {
    const blocks = [
      createMockBlock("block-1", "Block 1", [createMockElement("q1")]),
      createMockBlock("block-2", "Block 2", [createMockElement("q2")]),
    ];

    expect(isElementIdUnique("q1", blocks)).toBe(false);
    expect(isElementIdUnique("q2", blocks)).toBe(false);
  });

  test("should return true for empty blocks", () => {
    expect(isElementIdUnique("q1", [])).toBe(true);
  });
});

describe("findElementLocation", () => {
  test("should find element location correctly", () => {
    const element1 = createMockElement("q1");
    const element2 = createMockElement("q2");
    const block1 = createMockBlock("block-1", "Block 1", [element1]);
    const block2 = createMockBlock("block-2", "Block 2", [element2]);
    const survey = createMockSurvey([block1, block2]);

    const result = findElementLocation(survey, "q2");

    expect(result.blockId).toBe("block-2");
    expect(result.blockIndex).toBe(1);
    expect(result.elementIndex).toBe(0);
    expect(result.block).toEqual(block2);
  });

  test("should return null values when element is not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);

    const result = findElementLocation(survey, "nonexistent");

    expect(result.blockId).toBe(null);
    expect(result.blockIndex).toBe(-1);
    expect(result.elementIndex).toBe(-1);
    expect(result.block).toBe(null);
  });

  test("should find element in the middle of multiple elements", () => {
    const elements = [createMockElement("q1"), createMockElement("q2"), createMockElement("q3")];
    const block = createMockBlock("block-1", "Block 1", elements);
    const survey = createMockSurvey([block]);

    const result = findElementLocation(survey, "q2");

    expect(result.blockId).toBe("block-1");
    expect(result.blockIndex).toBe(0);
    expect(result.elementIndex).toBe(1);
  });
});

describe("addBlock", () => {
  test("should add a block to empty survey", () => {
    const survey = createMockSurvey([]);
    const result = addBlock(mockT, survey, { name: "Block 1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(1);
      expect(result.data.blocks[0].name).toBe("Block 1");
      expect(result.data.blocks[0].elements).toEqual([]);
    }
  });

  test("should append block to end by default", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = addBlock(mockT, survey, { name: "Block 2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(2);
      expect(result.data.blocks[1].name).toBe("Block 2");
    }
  });

  test("should insert block at specific index", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
    ]);
    const result = addBlock(mockT, survey, { name: "Block 1.5" }, 1);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(3);
      // The inserted block keeps the name it was given; the auto-named ones it displaced resequence.
      expect(result.data.blocks.map((block) => block.name)).toEqual(["Block 1", "Block 1.5", "Block 3"]);
    }
  });

  test("should return error for invalid index", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = addBlock(mockT, survey, { name: "Invalid" }, 10);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain("Invalid index");
    }
  });

  test("should return error for negative index", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = addBlock(mockT, survey, { name: "Invalid" }, -1);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain("Invalid index");
    }
  });
});

describe("updateBlock", () => {
  test("should update block name", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Old Name")]);
    const result = updateBlock(survey, "block-1", { name: "New Name" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].name).toBe("New Name");
    }
  });

  test("should update multiple block attributes", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = updateBlock(survey, "block-1", {
      name: "Updated",
      buttonLabel: { default: "Next" },
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].name).toBe("Updated");
      expect(result.data.blocks[0].buttonLabel).toEqual({ default: "Next" });
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = updateBlock(survey, "nonexistent", { name: "Updated" });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error when trying to update id", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = updateBlock(survey, "block-1", { id: "new-id" } as Parameters<typeof updateBlock>[2]);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toBe("Block ID cannot be updated");
    }
  });
});

describe("deleteBlock", () => {
  test("should delete a block", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
    ]);
    const result = deleteBlock(survey, "block-1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(1);
      expect(result.data.blocks[0].id).toBe("block-2");
    }
  });

  test("should return error when trying to delete the last block", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = deleteBlock(survey, "block-1");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toBe("Cannot delete the last block in the survey");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
    ]);
    const result = deleteBlock(survey, "nonexistent");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should handle deleting from empty survey", () => {
    const survey = createMockSurvey([]);
    const result = deleteBlock(survey, "block-1");

    expect(result.ok).toBe(false);
  });
});

describe("duplicateBlock", () => {
  test("should duplicate a block with new IDs", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const result = duplicateBlock(survey, "block-1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(2);
      // The copy carries the source's name, then resequences because that name is auto-generated.
      expect(result.data.blocks[1].name).toBe("Block 2");
      expect(result.data.blocks[1].id).not.toBe("block-1");
      expect(result.data.blocks[1].elements[0].id).not.toBe("q1");
      expect(result.data.blocks[1].elements[1].id).not.toBe("q2");
      expect(result.data.blocks[1].elements[0].isDraft).toBe(true);
      expect(result.data.blocks[1].elements[1].isDraft).toBe(true);
    }
  });

  test("should clear logic when duplicating", () => {
    const blockWithLogic = createMockBlock("block-1", "Block 1", [createMockElement("q1")]);
    blockWithLogic.logic = [
      {
        id: "logic-1",
        conditions: {
          id: "cond-1",
          connector: "and",
          conditions: [],
        },
        actions: [],
      },
    ];
    blockWithLogic.logicFallback = "block-2";

    const survey = createMockSurvey([blockWithLogic]);
    const result = duplicateBlock(survey, "block-1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[1].logic).toBeUndefined();
      expect(result.data.blocks[1].logicFallback).toBeUndefined();
    }
  });

  test("should insert duplicate after original block", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
      createMockBlock("block-3", "Block 3"),
    ]);
    const result = duplicateBlock(survey, "block-2");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks).toHaveLength(4);
      expect(result.data.blocks[2].name).toBe("Block 3");
      expect(result.data.blocks[1].id).toBe("block-2");
      expect(result.data.blocks[3].id).toBe("block-3");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = duplicateBlock(survey, "nonexistent");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });
});

describe("moveBlock", () => {
  test("should move block up", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
      createMockBlock("block-3", "Block 3"),
    ]);
    const result = moveBlock(survey, "block-2", "up");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].id).toBe("block-2");
      expect(result.data.blocks[1].id).toBe("block-1");
      expect(result.data.blocks[2].id).toBe("block-3");
    }
  });

  test("should move block down", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
      createMockBlock("block-3", "Block 3"),
    ]);
    const result = moveBlock(survey, "block-2", "down");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].id).toBe("block-1");
      expect(result.data.blocks[1].id).toBe("block-3");
      expect(result.data.blocks[2].id).toBe("block-2");
    }
  });

  test("should not move first block up", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
    ]);
    const result = moveBlock(survey, "block-1", "up");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].id).toBe("block-1");
      expect(result.data.blocks[1].id).toBe("block-2");
    }
  });

  test("should not move last block down", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1"),
      createMockBlock("block-2", "Block 2"),
    ]);
    const result = moveBlock(survey, "block-2", "down");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].id).toBe("block-1");
      expect(result.data.blocks[1].id).toBe("block-2");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const result = moveBlock(survey, "nonexistent", "up");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });
});

describe("creator-set block names survive block mutations", () => {
  // Blocks used to be renumbered on every mutation, which silently overwrote any name the
  // creator had typed. These pin that down: a title has to outlive each block operation.
  const surveyWithTitledBlock = () =>
    createMockSurvey([
      createMockBlock("block-1", "Screening", [createMockElement("q1")]),
      createMockBlock("block-2", "Block 2", [createMockElement("q2")]),
      createMockBlock("block-3", "Feedback", [createMockElement("q3")]),
    ]);

  test("should keep names when a block is added before them", () => {
    const result = addBlock(mockT, surveyWithTitledBlock(), { elements: [createMockElement("q0")] }, 0);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks.map((block) => block.name)).toEqual([
        "Block 1",
        "Screening",
        "Block 3",
        "Feedback",
      ]);
    }
  });

  test("should keep names when a block is deleted", () => {
    const result = deleteBlock(surveyWithTitledBlock(), "block-2");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks.map((block) => block.name)).toEqual(["Screening", "Feedback"]);
    }
  });

  test("should carry the name onto a duplicated block", () => {
    const result = duplicateBlock(surveyWithTitledBlock(), "block-1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks.map((block) => block.name)).toEqual([
        "Screening",
        "Screening",
        "Block 3",
        "Feedback",
      ]);
    }
  });

  test("should keep names when blocks are reordered", () => {
    const result = moveBlock(surveyWithTitledBlock(), "block-3", "up");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks.map((block) => block.name)).toEqual(["Screening", "Feedback", "Block 3"]);
    }
  });
});

describe("addElementToBlock", () => {
  test("should add element to block", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const element = createMockElement("q1");
    const result = addElementToBlock(survey, "block-1", element);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(1);
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
      expect(result.data.blocks[0].elements[0].isDraft).toBe(true);
    }
  });

  test("should append element to end by default", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const element = createMockElement("q3");
    const result = addElementToBlock(survey, "block-1", element);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(3);
      expect(result.data.blocks[0].elements[2].id).toBe("q3");
    }
  });

  test("should insert element at specific index", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const element = createMockElement("q1.5");
    const result = addElementToBlock(survey, "block-1", element, 1);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(3);
      expect(result.data.blocks[0].elements[1].id).toBe("q1.5");
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
      expect(result.data.blocks[0].elements[2].id).toBe("q2");
    }
  });

  test("should return error for duplicate element ID", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1")]),
      createMockBlock("block-2", "Block 2", [createMockElement("q2")]),
    ]);
    const element = createMockElement("q1");
    const result = addElementToBlock(survey, "block-2", element);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Element ID "q1" already exists');
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1")]);
    const element = createMockElement("q1");
    const result = addElementToBlock(survey, "nonexistent", element);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error for invalid index", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const element = createMockElement("q2");
    const result = addElementToBlock(survey, "block-1", element, 10);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain("Invalid index");
    }
  });
});

describe("updateElementInBlock", () => {
  test("should update element headline", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = updateElementInBlock(survey, "block-1", "q1", {
      headline: { default: "Updated Question" },
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].headline).toEqual({ default: "Updated Question" });
    }
  });

  test("should refuse to change the element ID", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = updateElementInBlock(survey, "block-1", "q1", { id: "q2" });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toBe("Element ID cannot be updated");
    }
  });

  test("should accept an update that repeats the element's own ID", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = updateElementInBlock(survey, "block-1", "q1", {
      id: "q1",
      headline: { default: "Same ID" },
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = updateElementInBlock(survey, "nonexistent", "q1", {
      headline: { default: "Updated" },
    });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error when element not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = updateElementInBlock(survey, "block-1", "nonexistent", {
      headline: { default: "Updated" },
    });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Element with ID "nonexistent" not found');
    }
  });
});

describe("deleteElementFromBlock", () => {
  test("should delete element from block", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const result = deleteElementFromBlock(survey, "block-1", "q1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(1);
      expect(result.data.blocks[0].elements[0].id).toBe("q2");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = deleteElementFromBlock(survey, "nonexistent", "q1");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error when element not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = deleteElementFromBlock(survey, "block-1", "nonexistent");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Element with ID "nonexistent" not found');
    }
  });
});

describe("duplicateElementInBlock", () => {
  test("should duplicate element with new ID", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = duplicateElementInBlock(survey, "block-1", "q1");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(2);
      expect(result.data.blocks[0].elements[1].id).not.toBe("q1");
      expect(result.data.blocks[0].elements[1].isDraft).toBe(true);
      expect(result.data.blocks[0].elements[1].headline).toEqual({ default: "Test Question" });
    }
  });

  test("should insert duplicate after original element", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [
        createMockElement("q1"),
        createMockElement("q2"),
        createMockElement("q3"),
      ]),
    ]);
    const result = duplicateElementInBlock(survey, "block-1", "q2");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements).toHaveLength(4);
      expect(result.data.blocks[0].elements[1].id).toBe("q2");
      expect(result.data.blocks[0].elements[2].id).not.toBe("q2");
      expect(result.data.blocks[0].elements[3].id).toBe("q3");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = duplicateElementInBlock(survey, "nonexistent", "q1");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error when element not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = duplicateElementInBlock(survey, "block-1", "nonexistent");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Element with ID "nonexistent" not found');
    }
  });
});

describe("moveElementInBlock", () => {
  test("should move element up", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [
        createMockElement("q1"),
        createMockElement("q2"),
        createMockElement("q3"),
      ]),
    ]);
    const result = moveElementInBlock(survey, "block-1", "q2", "up");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].id).toBe("q2");
      expect(result.data.blocks[0].elements[1].id).toBe("q1");
      expect(result.data.blocks[0].elements[2].id).toBe("q3");
    }
  });

  test("should move element down", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [
        createMockElement("q1"),
        createMockElement("q2"),
        createMockElement("q3"),
      ]),
    ]);
    const result = moveElementInBlock(survey, "block-1", "q2", "down");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
      expect(result.data.blocks[0].elements[1].id).toBe("q3");
      expect(result.data.blocks[0].elements[2].id).toBe("q2");
    }
  });

  test("should not move first element up", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const result = moveElementInBlock(survey, "block-1", "q1", "up");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
      expect(result.data.blocks[0].elements[1].id).toBe("q2");
    }
  });

  test("should not move last element down", () => {
    const survey = createMockSurvey([
      createMockBlock("block-1", "Block 1", [createMockElement("q1"), createMockElement("q2")]),
    ]);
    const result = moveElementInBlock(survey, "block-1", "q2", "down");

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.data.blocks[0].elements[0].id).toBe("q1");
      expect(result.data.blocks[0].elements[1].id).toBe("q2");
    }
  });

  test("should return error when block not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = moveElementInBlock(survey, "nonexistent", "q1", "up");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Block with ID "nonexistent" not found');
    }
  });

  test("should return error when element not found", () => {
    const survey = createMockSurvey([createMockBlock("block-1", "Block 1", [createMockElement("q1")])]);
    const result = moveElementInBlock(survey, "block-1", "nonexistent", "up");

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.message).toContain('Element with ID "nonexistent" not found');
    }
  });
});

describe("fillEmptyBlockButtonLabels", () => {
  const label = { default: "Continue" };

  test("fills missing and blank labels but keeps filled ones and the skipped block", () => {
    const survey = createMockSurvey([
      { ...createMockBlock("b0", "Block 1"), buttonLabel: { default: "" } },
      createMockBlock("b1", "Block 2"),
      { ...createMockBlock("b2", "Block 3"), buttonLabel: { default: "Go" } },
      createMockBlock("b3", "Block 4"),
    ]);

    const result = fillEmptyBlockButtonLabels(survey, "buttonLabel", label, 3, "default");

    expect(result.blocks.map((block) => block.buttonLabel)).toEqual([
      label,
      label,
      { default: "Go" },
      undefined,
    ]);
  });

  test("leaves a label without the language untouched and returns the same survey when nothing changes", () => {
    const survey = createMockSurvey([
      { ...createMockBlock("b0", "Block 1"), backButtonLabel: { de: "Zurück" } },
    ]);

    expect(fillEmptyBlockButtonLabels(survey, "backButtonLabel", label, -1, "default")).toBe(survey);
  });
});

describe("default codes (ENG-6782)", () => {
  const coded = (id: string, code: string) => ({ ...createMockElement(id), code }) as TSurveyElement;
  const codesIn = (survey: TSurvey) =>
    survey.blocks.flatMap((block) => block.elements.map((e) => (e as { code?: string }).code));
  const choice = (id: string, code?: string) => ({ id, label: { default: id }, ...(code ? { code } : {}) });
  const single = (id: string, code: string, choices: ReturnType<typeof choice>[]) =>
    ({
      id,
      code,
      type: TSurveyElementTypeEnum.MultipleChoiceSingle,
      headline: { default: id },
      required: false,
      shuffleOption: "none",
      choices,
    }) as unknown as TSurveyElement;

  test("a question added to a block takes the next q<n>, never renumbering the rest", () => {
    const survey = createMockSurvey([createMockBlock("b1", "Block 1", [coded("a", "q1"), coded("b", "q4")])]);
    const result = addElementToBlock(survey, "b1", createMockElement("c"), 0);
    expect(result.ok && codesIn(result.data)).toEqual(["q5", "q1", "q4"]);
  });

  test("a new block's questions are coded", () => {
    const survey = createMockSurvey([createMockBlock("b1", "Block 1", [coded("a", "q1")])]);
    const result = addBlock(mockT, survey, { elements: [createMockElement("b")] });
    expect(result.ok && codesIn(result.data)).toEqual(["q1", "q2"]);
  });

  test("a duplicated question gets the next q<n> and keeps its answer codes", () => {
    const survey = createMockSurvey([
      createMockBlock("b1", "Block 1", [single("a", "q1", [choice("x", "1"), choice("y", "2")])]),
    ]);
    const result = duplicateElementInBlock(survey, "b1", "a");
    if (!result.ok) throw result.error;
    const [original, copy] = result.data.blocks[0].elements as unknown as {
      code: string;
      choices: { code: string }[];
    }[];
    expect(original.code).toBe("q1");
    expect(copy.code).toBe("q2");
    expect(copy.choices.map((c) => c.code)).toEqual(["1", "2"]);
  });

  test("a duplicated block's questions get fresh codes after the survey's highest", () => {
    const survey = createMockSurvey([
      createMockBlock("b1", "Block 1", [coded("a", "q1"), coded("b", "q2")]),
      createMockBlock("b2", "Block 2", [coded("c", "q3")]),
    ]);
    const result = duplicateBlock(survey, "b1");
    expect(result.ok && codesIn(result.data)).toEqual(["q1", "q2", "q4", "q5", "q3"]);
  });

  test("an option added to a question is coded, and the existing codes stay", () => {
    const survey = createMockSurvey([
      createMockBlock("b1", "Block 1", [single("a", "q1", [choice("x", "1"), choice("y", "2")])]),
    ]);
    const result = updateElementInBlock(survey, "b1", "a", {
      choices: [choice("x", "1"), choice("y", "2"), choice("z")],
    });
    if (!result.ok) throw result.error;
    const element = result.data.blocks[0].elements[0] as unknown as { choices: { code: string }[] };
    expect(element.choices.map((c) => c.code)).toEqual(["1", "2", "3"]);
  });

  test("deleting a question does not renumber the others", () => {
    const survey = createMockSurvey([
      createMockBlock("b1", "Block 1", [coded("a", "q1"), coded("b", "q2"), coded("c", "q3")]),
    ]);
    const result = deleteElementFromBlock(survey, "b1", "b");
    expect(result.ok && codesIn(result.data)).toEqual(["q1", "q3"]);
  });

  test("an Embedded Data name is skipped", () => {
    const survey = {
      ...createMockSurvey([createMockBlock("b1", "Block 1", [])]),
      hiddenFields: { enabled: true, fieldIds: ["q1"] },
    } as TSurvey;
    const result = addElementToBlock(survey, "b1", createMockElement("a"));
    expect(result.ok && codesIn(result.data)).toEqual(["q2"]);
  });
});
