import { TFunction } from "i18next";
import { toast } from "react-hot-toast";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { TI18nString } from "@formbricks/types/i18n";
import { ZSegmentFilters } from "@formbricks/types/segment";
import { TSurveyBlockLogic } from "@formbricks/types/surveys/blocks";
import {
  TSurveyAddressElement,
  TSurveyCTAElement,
  TSurveyConsentElement,
  TSurveyContactInfoElement,
  TSurveyElementTypeEnum,
  TSurveyMatrixElement,
  TSurveyMultipleChoiceElement,
  TSurveyNPSElement,
  TSurveyOpenTextElement,
  TSurveyPictureSelectionElement,
  TSurveyRatingElement,
} from "@formbricks/types/surveys/elements";
import { validateElementLabels } from "@formbricks/types/surveys/elements-validation";
import {
  TSurvey,
  TSurveyEndScreenCard,
  TSurveyLanguage,
  TSurveyRedirectUrlCard,
  TSurveyWelcomeCard,
  ZSurvey,
} from "@formbricks/types/surveys/types";
import {
  TValidateIdErrorCode,
  validateCardFieldsForAllLanguages,
  validateQuestionLabels,
} from "@formbricks/types/surveys/validation";
import { checkForEmptyFallBackValue } from "@/lib/utils/recall";
import * as validation from "./validation";

vi.mock("react-hot-toast", () => ({
  toast: {
    error: vi.fn(),
    success: vi.fn(),
  },
}));

// Mock recall utility
vi.mock("@/lib/utils/recall", async (importOriginal) => ({
  ...(await importOriginal()),
  checkForEmptyFallBackValue: vi.fn(),
}));

const surveyLanguagesEnabled: TSurveyLanguage[] = [
  {
    language: {
      id: "1",
      code: "en",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: true,
    enabled: true,
  },
  {
    language: {
      id: "2",
      code: "de",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: true,
  },
];

const surveyLanguagesOnlyDefault: TSurveyLanguage[] = [
  {
    language: {
      id: "1",
      code: "en",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: true,
    enabled: true,
  },
];

const surveyLanguagesWithDisabled: TSurveyLanguage[] = [
  {
    language: {
      id: "1",
      code: "en",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: true,
    enabled: true,
  },
  {
    language: {
      id: "2",
      code: "de",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: true,
  },
  {
    language: {
      id: "3",
      code: "fr",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: false,
  },
];

const surveyLanguagesMultipleEnabled: TSurveyLanguage[] = [
  {
    language: {
      id: "1",
      code: "en",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: true,
    enabled: true,
  },
  {
    language: {
      id: "2",
      code: "de",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: true,
  },
  {
    language: {
      id: "3",
      code: "fr",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: true,
  },
  {
    language: {
      id: "4",
      code: "es",
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "proj1",
    },
    default: false,
    enabled: true,
  },
];

describe("survey schema multilingual label validation", () => {
  test("returns a card issue when the welcome card default headline is missing but translations are present", () => {
    const issue = validateCardFieldsForAllLanguages(
      "cardHeadline",
      { default: "", en: "Welcome", de: "Willkommen" },
      surveyLanguagesEnabled,
      "welcome"
    );

    expect(issue).toMatchObject({
      code: "custom",
      message: "The note on the Welcome card is missing",
      path: ["welcomeCard", "cardHeadline"],
    });
    expect(issue?.params).toBeUndefined();
  });

  test("returns language params when only a translated welcome card headline is missing", () => {
    const issue = validateCardFieldsForAllLanguages(
      "cardHeadline",
      { default: "Welcome", en: "Welcome", de: "" },
      surveyLanguagesEnabled,
      "welcome"
    );

    expect(issue).toMatchObject({
      code: "custom",
      message: "The note on the Welcome card is missing for the following languages:  -fLang- de",
      path: ["welcomeCard", "cardHeadline"],
      params: { invalidLanguageCodes: ["de"] },
    });
  });

  test("returns a card issue without params when the ending card default headline and translations are missing", () => {
    const issue = validateCardFieldsForAllLanguages(
      "cardHeadline",
      { default: "", en: "", de: "" },
      surveyLanguagesEnabled,
      "end",
      2
    );

    expect(issue).toMatchObject({
      code: "custom",
      message: "The note on the Ending card 3 is missing",
      path: ["endings", 2, "cardHeadline"],
    });
    expect(issue?.params).toBeUndefined();
  });

  test("returns all invalid language params for mixed valid and invalid ending card translations", () => {
    const issue = validateCardFieldsForAllLanguages(
      "endingCardButtonLabel",
      { default: "Done", en: "Done", de: "", fr: " ", es: "Listo" },
      surveyLanguagesMultipleEnabled,
      "end",
      1
    );

    expect(issue).toMatchObject({
      code: "custom",
      message:
        "The button label on the Ending card 2 is missing for the following languages:  -fLang- de, fr",
      path: ["endings", 1, "endingCardButtonLabel"],
      params: { invalidLanguageCodes: ["de", "fr"] },
    });
  });

  test("returns a block-editor issue when a block element default headline is missing", () => {
    const issue = validateElementLabels(
      "headline",
      { default: "", en: "", de: "" },
      surveyLanguagesEnabled,
      1,
      0
    );

    expect(issue).toMatchObject({
      message: "The question in question 1 of block 2 is missing",
      path: ["blocks", 1, "elements", 0, "headline"],
    });
    expect(issue?.params).toBeUndefined();
  });

  test("returns a block-editor issue when a question default headline is missing", () => {
    const issue = validateQuestionLabels(
      "headline",
      { default: "", en: "", de: "" },
      surveyLanguagesEnabled,
      0
    );

    expect(issue).toMatchObject({
      message: "The question in question 1 is missing",
      path: ["questions", 0, "headline"],
    });
    expect(issue?.params).toBeUndefined();
  });

  test("returns language params when only a translated block element headline is missing", () => {
    const issue = validateElementLabels(
      "headline",
      { default: "Question", en: "Question", de: "" },
      surveyLanguagesEnabled,
      1,
      0
    );

    expect(issue).toMatchObject({
      message: "The question in question 1 of block 2 is missing for the following languages:  -fLang- de",
      path: ["blocks", 1, "elements", 0, "headline"],
      params: { invalidLanguageCodes: ["de"] },
    });
  });
});

describe("validation.isLabelValidForAllLanguages", () => {
  test("should return true if all enabled languages have non-empty labels", () => {
    const label: TI18nString = { default: "Hello", en: "Hello", de: "Hallo" };
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false if an enabled language has an empty label", () => {
    const label: TI18nString = { default: "Hello", en: "Hello", de: "" };
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false if an enabled language has a label with only whitespace", () => {
    const label: TI18nString = { default: "Hello", en: "Hello", de: "  " };
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false if label is undefined for an enabled language", () => {
    const label: TI18nString = { default: "Hello", en: "Hello" }; // de is missing
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return true if only default language and label is present", () => {
    const label: TI18nString = { default: "Hello", en: "Hello" };
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesOnlyDefault)).toBe(true);
  });

  test("should return false if only default language and label is missing", () => {
    const label: TI18nString = { default: "", en: "" };
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesOnlyDefault)).toBe(false);
  });

  test("should ignore disabled languages", () => {
    const label: TI18nString = { default: "Hello", en: "Hello", de: "Hallo", fr: "" }; // fr is disabled but empty
    expect(validation.isLabelValidForAllLanguages(label, surveyLanguagesWithDisabled)).toBe(true);
  });

  test("should use 'default' if language code is 'default'", () => {
    const labelDefaultCode: TI18nString = { default: "Hello" };
    const surveyLangsWithDefaultCode: TSurveyLanguage[] = [
      {
        language: {
          id: "1",
          code: "default",
          alias: null,
          createdAt: new Date(),
          updatedAt: new Date(),
          workspaceId: "proj1",
        },
        default: true,
        enabled: true,
      },
    ];
    expect(validation.isLabelValidForAllLanguages(labelDefaultCode, surveyLangsWithDefaultCode)).toBe(true);
  });

  test("should return true if no languages are provided (checks for 'default' key)", () => {
    const label: TI18nString = { default: "Fallback" };
    expect(validation.isLabelValidForAllLanguages(label, [])).toBe(true);
  });

  test("should return false if no languages are provided and 'default' key is missing or empty", () => {
    const labelMissing: TI18nString = {};
    const labelEmpty: TI18nString = { default: "" };
    expect(validation.isLabelValidForAllLanguages(labelMissing, [])).toBe(false);
    expect(validation.isLabelValidForAllLanguages(labelEmpty, [])).toBe(false);
  });
});

describe("validation.isWelcomeCardValid", () => {
  const baseWelcomeCard: TSurveyWelcomeCard = {
    enabled: true,
    headline: { default: "Welcome", en: "Welcome", de: "Willkommen" },
    subheader: { default: "<p>Info</p>", en: "<p>Info</p>", de: "<p>Infos</p>" },
    timeToFinish: false,
    showResponseCount: false,
  };

  test("should return true for a valid welcome card", () => {
    expect(validation.isWelcomeCardValid(baseWelcomeCard, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false if headline is invalid", () => {
    const card = { ...baseWelcomeCard, headline: { default: "Welcome", en: "Welcome", de: "" } };
    expect(validation.isWelcomeCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false if subheader is invalid (when subheader is provided)", () => {
    const card = { ...baseWelcomeCard, subheader: { default: "<p>Info</p>", en: "<p>Info</p>", de: "  " } };
    expect(validation.isWelcomeCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return true if subheader is undefined", () => {
    const card = { ...baseWelcomeCard, subheader: undefined };
    expect(validation.isWelcomeCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });
});

describe("validation.isEndingCardValid", () => {
  const baseEndScreenCard: TSurveyEndScreenCard = {
    id: "end1",
    type: "endScreen",
    headline: { default: "Thank You", en: "Thank You", de: "Danke" },
    subheader: { default: "Done", en: "Done", de: "Fertig" },
  };

  const baseRedirectUrlCard: TSurveyRedirectUrlCard = {
    id: "redir1",
    type: "redirectToUrl",
    url: "https://example.com",
    label: "Redirect",
  };

  // EndScreen Card tests
  test("should return true for a valid endScreen card without button", () => {
    expect(validation.isEndingCardValid(baseEndScreenCard, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return true for a valid endScreen card with valid button", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "https://example.com",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("requires every language for image alt text once the default has text", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      imageUrl: "https://example.com/img.jpg",
      imageAltText: { default: "Team photo", en: "Team photo", de: "" },
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
    expect(
      validation.isEndingCardValid(
        { ...card, imageAltText: { default: "Team photo", en: "Team photo", de: "Teamfoto" } },
        surveyLanguagesEnabled
      )
    ).toBe(true);
  });

  test("accepts an empty image alt text without translations (decorative image)", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      imageUrl: "https://example.com/img.jpg",
      imageAltText: { default: "" },
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false for endScreen card if headline is invalid", () => {
    const card = { ...baseEndScreenCard, headline: { default: "Thank You", en: "Thank You", de: "" } };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false for endScreen card if subheader is invalid (when provided)", () => {
    const card = { ...baseEndScreenCard, subheader: { default: "Done", en: "Done", de: "  " } };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false for endScreen card if buttonLabel is invalid (when provided)", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "" },
      buttonLink: "https://example.com",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false for endScreen card if buttonLink is invalid (when buttonLabel is provided)", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "invalid-url",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return true for endScreen card with http:// URL", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "http://example.com",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return true for endScreen card with a mailto: button link", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "mailto:hello@example.com",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false for endScreen card with a javascript: button link", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "javascript:alert(1)",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return false for a redirectToUrl card with a mailto: url", () => {
    const card: TSurveyRedirectUrlCard = { ...baseRedirectUrlCard, url: "mailto:hello@example.com" };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return true for endScreen card with dynamic URL containing recall", () => {
    const card: TSurveyEndScreenCard = {
      ...baseEndScreenCard,
      buttonLabel: { default: "Go", en: "Go", de: "Los" },
      buttonLink: "https://#recall:test123/fallback:example.com#",
    };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  // RedirectURL Card tests
  test("should return true for a valid redirectUrl card", () => {
    expect(validation.isEndingCardValid(baseRedirectUrlCard, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false for redirectUrl card if URL is invalid", () => {
    const card = { ...baseRedirectUrlCard, url: "invalid-url" };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });

  test("should return true for redirectUrl card with http:// URL", () => {
    const card = { ...baseRedirectUrlCard, url: "http://example.com" };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return true for redirectUrl card with dynamic URL containing recall", () => {
    const card = { ...baseRedirectUrlCard, url: "https://#recall:test123/fallback:example.com#" };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(true);
  });

  test("should return false for redirectUrl card if label is empty", () => {
    const card = { ...baseRedirectUrlCard, label: "  " };
    expect(validation.isEndingCardValid(card, surveyLanguagesEnabled)).toBe(false);
  });
});

describe("validation.validateElement", () => {
  const baseElementFields = {
    id: "element1",
    required: false,
  };

  // Test OpenText Element
  describe("OpenText Element", () => {
    const openTextElementBase: TSurveyOpenTextElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.OpenText,
      headline: { default: "Open Text", en: "Open Text", de: "Offener Text" },
      subheader: { default: "Enter here", en: "Enter here", de: "Hier eingeben" },
      placeholder: { default: "Your answer...", en: "Your answer...", de: "Deine Antwort..." },
      inputType: "text",
      charLimit: {
        enabled: true,
        max: 100,
        min: 0,
      },
    };

    test("should return true for a valid OpenText element", () => {
      expect(validation.validateElement(openTextElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if headline is invalid", () => {
      const q = { ...openTextElementBase, headline: { default: "Open Text", en: "Open Text", de: "" } };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if placeholder is valid (default not empty, other languages valid)", () => {
      const q = {
        ...openTextElementBase,
        placeholder: { default: "Type here", en: "Type here", de: "Tippe hier" },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if placeholder.default is not empty but other lang is empty", () => {
      const q = { ...openTextElementBase, placeholder: { default: "Type here", en: "Type here", de: "" } };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if placeholder.default is empty (placeholder validation skipped)", () => {
      const q = { ...openTextElementBase, placeholder: { default: "", en: "Type here", de: "" } };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });
  });

  // Test MultipleChoiceSingle Element
  describe("MultipleChoiceSingle Element", () => {
    const mcSingleElementBase: TSurveyMultipleChoiceElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.MultipleChoiceSingle,
      headline: { default: "Single Choice", en: "Single Choice", de: "Einzelauswahl" },
      choices: [
        { id: "c1", label: { default: "Option 1", en: "Option 1", de: "Option 1" } },
        { id: "c2", label: { default: "Option 2", en: "Option 2", de: "Option 2" } },
      ],
    };

    test("should return true for a valid MultipleChoiceSingle element", () => {
      expect(validation.validateElement(mcSingleElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if a choice label is invalid", () => {
      const q = {
        ...mcSingleElementBase,
        choices: [
          { id: "c1", label: { default: "Option 1", en: "Option 1", de: "Option 1" } },
          { id: "c2", label: { default: "Option 2", en: "Option 2", de: "" } },
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test Consent Element
  describe("Consent Element", () => {
    const consentElementBase: TSurveyConsentElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.Consent,
      headline: { default: "Consent", en: "Consent", de: "Zustimmung" },
      label: { default: "I agree", en: "I agree", de: "Ich stimme zu" },
      subheader: { default: "Details...", en: "Details...", de: "Details..." },
    };

    test("should return true for a valid Consent element", () => {
      expect(validation.validateElement(consentElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if consent label is invalid", () => {
      const q = { ...consentElementBase, label: { default: "I agree", en: "I agree", de: "" } };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test MultipleChoiceMulti Element
  describe("MultipleChoiceMulti Element", () => {
    const mcMultiElementBase: TSurveyMultipleChoiceElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.MultipleChoiceMulti,
      headline: { default: "Multi Choice", en: "Multi Choice", de: "Mehrfachauswahl" },
      choices: [
        { id: "c1", label: { default: "Option 1", en: "Option 1", de: "Option 1" } },
        { id: "c2", label: { default: "Option 2", en: "Option 2", de: "Option 2" } },
      ],
      shuffleOption: "none",
    };

    test("should return true for a valid MultipleChoiceMulti element", () => {
      expect(validation.validateElement(mcMultiElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if a choice label is invalid", () => {
      const q = {
        ...mcMultiElementBase,
        choices: [
          { id: "c1", label: { default: "Option 1", en: "Option 1", de: "Option 1" } },
          { id: "c2", label: { default: "Option 2", en: "Option 2", de: "" } },
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if there are duplicate choice labels", () => {
      const q = {
        ...mcMultiElementBase,
        choices: [
          { id: "c1", label: { default: "Option 1", en: "Option 1", de: "Option 1" } },
          { id: "c2", label: { default: "Option 1", en: "Option 1", de: "Option 1" } }, // Duplicate
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test Picture Selection Element
  describe("PictureSelection Element", () => {
    const pictureSelectionElementBase: TSurveyPictureSelectionElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.PictureSelection,
      headline: { default: "Select Image", en: "Select Image", de: "Bild auswählen" },
      choices: [
        { id: "p1", imageUrl: "https://example.com/img1.jpg" },
        { id: "p2", imageUrl: "https://example.com/img2.jpg" },
      ],
      allowMulti: false,
    };

    test("should return true for a valid PictureSelection element with 2+ choices", () => {
      expect(validation.validateElement(pictureSelectionElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if PictureSelection has less than 2 choices", () => {
      const q = {
        ...pictureSelectionElementBase,
        choices: [{ id: "p1", imageUrl: "https://example.com/img1.jpg" }],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if PictureSelection has 0 choices", () => {
      const q = {
        ...pictureSelectionElementBase,
        choices: [],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("requires every language for a choice's image alt text once the default has text", () => {
      const withAlt = (de: string) => ({
        ...pictureSelectionElementBase,
        choices: [
          { ...pictureSelectionElementBase.choices[0], imageAltText: { default: "Cat", en: "Cat", de } },
          pictureSelectionElementBase.choices[1],
        ],
      });
      expect(validation.validateElement(withAlt(""), surveyLanguagesEnabled)).toBe(false);
      expect(validation.validateElement(withAlt("Katze"), surveyLanguagesEnabled)).toBe(true);
    });

    test("accepts empty choice alt text without translations (decorative image)", () => {
      const q = {
        ...pictureSelectionElementBase,
        choices: pictureSelectionElementBase.choices.map((choice) => ({
          ...choice,
          imageAltText: { default: "" },
        })),
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    test("requires every language for the question image's alt text once the default has text", () => {
      const q = {
        ...pictureSelectionElementBase,
        imageUrl: "https://example.com/hero.jpg",
        imageAltText: { default: "Hero", en: "Hero", de: "" },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test CTA Element
  describe("CTA Element", () => {
    const ctaElementBase: TSurveyCTAElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.CTA,
      headline: { default: "Call to Action", en: "Call to Action", de: "Handlungsaufforderung" },
      subheader: { default: "Click below", en: "Click below", de: "Klicke unten" },
      buttonExternal: false,
      required: false,
    };

    test("should return true for a valid CTA element without external button", () => {
      expect(validation.validateElement(ctaElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return true for a valid CTA element with external button and valid label", () => {
      const q: TSurveyCTAElement = {
        ...ctaElementBase,
        buttonExternal: true,
        ctaButtonLabel: { default: "Click", en: "Click", de: "Klicken" },
        buttonUrl: "https://example.com",
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false for CTA with external button but invalid ctaButtonLabel", () => {
      const q: TSurveyCTAElement = {
        ...ctaElementBase,
        buttonExternal: true,
        ctaButtonLabel: { default: "Click", en: "Click", de: "" }, // Invalid German label
        buttonUrl: "https://example.com",
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true for CTA with buttonExternal true but no ctaButtonLabel", () => {
      const q: TSurveyCTAElement = {
        ...ctaElementBase,
        buttonExternal: true,
        buttonUrl: "https://example.com",
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });
  });

  // Test Matrix Element
  describe("Matrix Element", () => {
    const matrixElementBase: TSurveyMatrixElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.Matrix,
      headline: { default: "Matrix Q", en: "Matrix Q", de: "Matrix F" },
      rows: [
        { id: "r1", label: { default: "Row 1", en: "Row 1", de: "Zeile 1" } },
        { id: "r2", label: { default: "Row 2", en: "Row 2", de: "Zeile 2" } },
      ],
      columns: [
        { id: "c1", label: { default: "Col 1", en: "Col 1", de: "Spalte 1" } },
        { id: "c2", label: { default: "Col 2", en: "Col 2", de: "Spalte 2" } },
      ],
      shuffleOption: "none",
    };

    test("should return true for a valid Matrix element", () => {
      expect(validation.validateElement(matrixElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if a row label is invalid", () => {
      const q = {
        ...matrixElementBase,
        rows: [
          { id: "r1", label: { default: "Row 1", en: "Row 1", de: "Zeile 1" } },
          { id: "r2", label: { default: "Row 2", en: "Row 2", de: "" } }, // Invalid
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if a column label is invalid", () => {
      const q = {
        ...matrixElementBase,
        columns: [
          { id: "c1", label: { default: "Col 1", en: "Col 1", de: "Spalte 1" } },
          { id: "c2", label: { default: "Col 2", en: "Col 2", de: "" } }, // Invalid
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if there are duplicate row labels", () => {
      const q = {
        ...matrixElementBase,
        rows: [
          { id: "r1", label: { default: "Row 1", en: "Row 1", de: "Zeile 1" } },
          { id: "r2", label: { default: "Row 1", en: "Row 1", de: "Zeile 1" } }, // Duplicate
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if there are duplicate column labels", () => {
      const q = {
        ...matrixElementBase,
        columns: [
          { id: "c1", label: { default: "Col 1", en: "Col 1", de: "Spalte 1" } },
          { id: "c2", label: { default: "Col 1", en: "Col 1", de: "Spalte 1" } }, // Duplicate
        ],
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test ContactInfo Element
  describe("ContactInfo Element", () => {
    const contactInfoElementBase: TSurveyContactInfoElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.ContactInfo,
      headline: { default: "Contact", en: "Contact", de: "Kontakt" },
      firstName: {
        show: true,
        required: false,
        placeholder: { default: "First Name", en: "First Name", de: "Vorname" },
      },
      lastName: {
        show: true,
        required: false,
        placeholder: { default: "Last Name", en: "Last Name", de: "Nachname" },
      },
      email: {
        show: true,
        required: false,
        placeholder: { default: "Email", en: "Email", de: "E-Mail" },
      },
      phone: { show: false, required: false, placeholder: { default: "Phone", en: "Phone", de: "Telefon" } },
      company: {
        show: false,
        required: false,
        placeholder: { default: "Company", en: "Company", de: "Firma" },
      },
    };

    test("should return true for a valid ContactInfo element", () => {
      expect(validation.validateElement(contactInfoElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if a visible field placeholder is invalid", () => {
      const q = {
        ...contactInfoElementBase,
        firstName: {
          show: true,
          required: false,
          placeholder: { default: "First Name", en: "First Name", de: "" }, // Invalid
        },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if a hidden field placeholder is invalid (not shown)", () => {
      const q = {
        ...contactInfoElementBase,
        phone: {
          show: false,
          required: false,
          placeholder: { default: "Phone", en: "Phone", de: "" }, // Invalid but hidden
        },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });
  });

  // Test Address Element
  describe("Address Element", () => {
    const addressElementBase: TSurveyAddressElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.Address,
      headline: { default: "Address", en: "Address", de: "Adresse" },
      addressLine1: {
        show: true,
        required: false,
        placeholder: { default: "Address Line 1", en: "Address Line 1", de: "Adresszeile 1" },
      },
      addressLine2: {
        show: true,
        required: false,
        placeholder: { default: "Address Line 2", en: "Address Line 2", de: "Adresszeile 2" },
      },
      city: { show: true, required: false, placeholder: { default: "City", en: "City", de: "Stadt" } },
      state: { show: true, required: false, placeholder: { default: "State", en: "State", de: "Staat" } },
      zip: { show: true, required: false, placeholder: { default: "ZIP", en: "ZIP", de: "PLZ" } },
      country: {
        show: true,
        required: false,
        placeholder: { default: "Country", en: "Country", de: "Land" },
      },
    };

    test("should return true for a valid Address element", () => {
      expect(validation.validateElement(addressElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if a visible field placeholder is invalid", () => {
      const q = {
        ...addressElementBase,
        city: {
          show: true,
          required: false,
          placeholder: { default: "City", en: "City", de: "" }, // Invalid
        },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if a hidden field placeholder is invalid (not shown)", () => {
      const q = {
        ...addressElementBase,
        country: {
          show: false,
          required: false,
          placeholder: { default: "Country", en: "Country", de: "" }, // Invalid but hidden
        },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });
  });

  // Test default validation for elements with upperLabel and lowerLabel
  describe("Default validation for Rating and NPS elements", () => {
    const ratingElementBase: TSurveyRatingElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.Rating,
      headline: { default: "Rating", en: "Rating", de: "Bewertung" },
      range: 5,
      scale: "number",
      lowerLabel: { default: "Bad", en: "Bad", de: "Schlecht" },
      upperLabel: { default: "Good", en: "Good", de: "Gut" },
      isColorCodingEnabled: false,
    };

    test("should return true for a valid Rating element with valid upperLabel and lowerLabel", () => {
      expect(validation.validateElement(ratingElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false if lowerLabel is invalid", () => {
      const q = {
        ...ratingElementBase,
        lowerLabel: { default: "Bad", en: "Bad", de: "" }, // Invalid
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false if upperLabel is invalid", () => {
      const q = {
        ...ratingElementBase,
        upperLabel: { default: "Good", en: "Good", de: "" }, // Invalid
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if lowerLabel is empty/undefined (not validated)", () => {
      const q = {
        ...ratingElementBase,
        lowerLabel: undefined,
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return true if lowerLabel.default is empty string (skipped)", () => {
      const q = {
        ...ratingElementBase,
        lowerLabel: { default: "", en: "", de: "" },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    const npsElementBase: TSurveyNPSElement = {
      ...baseElementFields,
      type: TSurveyElementTypeEnum.NPS,
      headline: { default: "NPS", en: "NPS", de: "NPS" },
      lowerLabel: { default: "Not Likely", en: "Not Likely", de: "Unwahrscheinlich" },
      upperLabel: { default: "Very Likely", en: "Very Likely", de: "Sehr wahrscheinlich" },
      isColorCodingEnabled: false,
    };

    test("should return true for a valid NPS element with valid upperLabel and lowerLabel", () => {
      expect(validation.validateElement(npsElementBase, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return false for NPS if lowerLabel is invalid", () => {
      const q = {
        ...npsElementBase,
        lowerLabel: { default: "Not Likely", en: "Not Likely", de: "" },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return false for NPS if upperLabel is invalid", () => {
      const q = {
        ...npsElementBase,
        upperLabel: { default: "Very Likely", en: "Very Likely", de: "" },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });
  });

  // Test subheader validation
  describe("Subheader validation", () => {
    test("should return false if subheader is invalid when provided", () => {
      const q: TSurveyOpenTextElement = {
        ...baseElementFields,
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Open Text", en: "Open Text", de: "Offener Text" },
        subheader: { default: "Enter here", en: "Enter here", de: "" }, // Invalid
        inputType: "text",
        charLimit: { enabled: false },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(false);
    });

    test("should return true if subheader.default is empty (skipped)", () => {
      const q: TSurveyOpenTextElement = {
        ...baseElementFields,
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Open Text", en: "Open Text", de: "Offener Text" },
        subheader: { default: "", en: "", de: "" },
        inputType: "text",
        charLimit: { enabled: false },
      };
      expect(validation.validateElement(q, surveyLanguagesEnabled)).toBe(true);
    });

    test("should return true if there's only one language (default)", () => {
      const q: TSurveyOpenTextElement = {
        ...baseElementFields,
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Open Text", en: "Open Text" },
        subheader: { default: "Some text", en: "Some text", de: "" }, // de empty but only default language
        inputType: "text",
        charLimit: { enabled: false },
      };
      expect(validation.validateElement(q, surveyLanguagesOnlyDefault)).toBe(true);
    });
  });
});

describe("validation.validateSurveyElementsInBatch", () => {
  const q2Valid: TSurveyOpenTextElement = {
    id: "q2",
    type: TSurveyElementTypeEnum.OpenText,
    headline: { default: "Q2", en: "Q2", de: "Q2" },
    inputType: "text",
    charLimit: {
      enabled: true,
      max: 100,
      min: 0,
    },
    required: false,
  };

  const q2Invalid: TSurveyOpenTextElement = {
    id: "q2",
    type: TSurveyElementTypeEnum.OpenText,
    headline: { default: "Q2", en: "Q2", de: "" },
    inputType: "text",
    charLimit: {
      enabled: true,
      max: 100,
      min: 0,
    },
    required: false,
  };

  test("should return empty array if invalidElements is null", () => {
    expect(validation.validateSurveyElementsInBatch(q2Valid, null, surveyLanguagesEnabled)).toEqual([]);
  });

  test("should add element.id if element is invalid and not already in list", () => {
    const invalidElements = ["q1"];
    expect(
      validation.validateSurveyElementsInBatch(q2Invalid, invalidElements, surveyLanguagesEnabled)
    ).toEqual(["q1", "q2"]);
  });

  test("should not add element.id if element is invalid but already in list", () => {
    const invalidElements = ["q1", "q2"];
    expect(
      validation.validateSurveyElementsInBatch(q2Invalid, invalidElements, surveyLanguagesEnabled)
    ).toEqual(["q1", "q2"]);
  });

  test("should remove element.id if element is valid and in list", () => {
    const invalidElements = ["q1", "q2"];
    expect(
      validation.validateSurveyElementsInBatch(q2Valid, invalidElements, surveyLanguagesEnabled)
    ).toEqual(["q1"]);
  });

  test("should not change list if element is valid and not in list", () => {
    const invalidElements = ["q1"];
    const validateElementSpy = vi.spyOn(validation, "validateElement");
    validateElementSpy.mockReturnValue(true);
    const result = validation.validateSurveyElementsInBatch(
      q2Valid,
      [...invalidElements],
      surveyLanguagesEnabled
    );
    expect(result).toEqual(["q1"]);
  });
});

describe("validation.isSurveyValid", () => {
  const mockT: TFunction = ((key: string) => key) as TFunction;
  let baseSurvey: TSurvey;

  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(checkForEmptyFallBackValue).mockReturnValue(null); // Default: no empty fallback

    baseSurvey = {
      id: "survey1",
      name: "Test Survey",
      type: "web",
      status: "draft",
      questions: [],
      blocks: [
        {
          id: "block1",
          name: "Block 1",
          elements: [
            {
              id: "q1",
              type: TSurveyElementTypeEnum.OpenText,
              headline: { default: "Q1", en: "Q1", de: "Q1" },
              required: false,
              inputType: "text",
              charLimit: {
                enabled: false,
              },
            },
          ],
        },
      ],
      endings: [
        { id: "end1", type: "endScreen", headline: { default: "Thanks", en: "Thanks", de: "Danke" } },
      ],
      welcomeCard: { enabled: true, headline: { default: "Welcome", en: "Welcome", de: "Willkommen" } },
      languages: surveyLanguagesEnabled,
      triggers: [],
      recontactDays: null,
      autoClose: null,
      delay: 0,
      displayOption: "displayOnce",
      displayLimit: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      segment: null,
    } as unknown as TSurvey; // Cast to TSurvey, ensure all required fields are present or mocked
  });

  test("should return true for a completely valid survey", () => {
    expect(validation.isSurveyValid(baseSurvey, "en", mockT)).toBe(true);
    expect(toast.error).not.toHaveBeenCalled();
  });

  test("should return false and toast error if checkForEmptyFallBackValue returns an element", () => {
    vi.mocked(checkForEmptyFallBackValue).mockReturnValue({
      id: "q1",
      type: TSurveyElementTypeEnum.OpenText,
      headline: { default: "Q1", en: "Q1", de: "Q1" },
      inputType: "text",
      charLimit: {
        enabled: true,
        max: 100,
        min: 0,
      },
      required: false,
    });
    expect(validation.isSurveyValid(baseSurvey, "de", mockT)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith("workspace.surveys.edit.fallback_missing");
  });

  test("should return false and toast error if response limit is 0", () => {
    const surveyWithZeroLimit = {
      ...baseSurvey,
      autoComplete: 0,
    };
    expect(validation.isSurveyValid(surveyWithZeroLimit, "en", mockT, 5)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith("workspace.surveys.edit.response_limit_can_t_be_set_to_0");
  });

  test("should return false and toast error if response limit is less than or equal to response count", () => {
    const surveyWithLowLimit = {
      ...baseSurvey,
      autoComplete: 5,
    };
    expect(validation.isSurveyValid(surveyWithLowLimit, "en", mockT, 5)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith(
      "workspace.surveys.edit.response_limit_needs_to_exceed_number_of_received_responses",
      {
        id: "response-limit-error",
      }
    );
  });

  test("should return false and toast error if response limit is less than response count", () => {
    const surveyWithLowLimit = {
      ...baseSurvey,
      autoComplete: 3,
    };
    expect(validation.isSurveyValid(surveyWithLowLimit, "en", mockT, 5)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith(
      "workspace.surveys.edit.response_limit_needs_to_exceed_number_of_received_responses",
      {
        id: "response-limit-error",
      }
    );
  });

  test("should return true if response limit is greater than response count", () => {
    const surveyWithValidLimit = {
      ...baseSurvey,
      autoComplete: 10,
    };
    expect(validation.isSurveyValid(surveyWithValidLimit, "en", mockT, 5)).toBe(true);
    expect(toast.error).not.toHaveBeenCalled();
  });

  test("should return true if autoComplete is null (no limit set)", () => {
    const surveyWithNoLimit = {
      ...baseSurvey,
      autoComplete: null,
    };
    expect(validation.isSurveyValid(surveyWithNoLimit, "en", mockT, 5)).toBe(true);
    expect(toast.error).not.toHaveBeenCalled();
  });

  test("should return false and toast error if a link survey has an empty custom survey closed message heading", () => {
    const surveyWithEmptyClosedMessageHeading = {
      ...baseSurvey,
      type: "link",
      surveyClosedMessage: {
        heading: "",
        subheading: "Closed for now",
      },
    } as unknown as TSurvey;

    expect(validation.isSurveyValid(surveyWithEmptyClosedMessageHeading, "en", mockT)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith("workspace.surveys.edit.survey_closed_message_heading_required");
  });

  test("should return false and toast error if a link survey has a whitespace-only custom survey closed message heading", () => {
    const surveyWithWhitespaceClosedMessageHeading = {
      ...baseSurvey,
      type: "link",
      surveyClosedMessage: {
        heading: "   ",
        subheading: "",
      },
    } as unknown as TSurvey;

    expect(validation.isSurveyValid(surveyWithWhitespaceClosedMessageHeading, "en", mockT)).toBe(false);
    expect(toast.error).toHaveBeenCalledWith("workspace.surveys.edit.survey_closed_message_heading_required");
  });

  test("should return true if a link survey has a custom survey closed message heading and no subheading", () => {
    const surveyWithHeadingOnlyClosedMessage = {
      ...baseSurvey,
      type: "link",
      surveyClosedMessage: {
        heading: "Survey closed",
        subheading: "",
      },
    } as unknown as TSurvey;

    expect(validation.isSurveyValid(surveyWithHeadingOnlyClosedMessage, "en", mockT)).toBe(true);
    expect(toast.error).not.toHaveBeenCalled();
  });

  test("should return true if a link survey has a custom survey closed message heading and subheading", () => {
    const surveyWithClosedMessageContent = {
      ...baseSurvey,
      type: "link",
      surveyClosedMessage: {
        heading: "Survey closed",
        subheading: "Thanks for your interest",
      },
    } as unknown as TSurvey;

    expect(validation.isSurveyValid(surveyWithClosedMessageContent, "en", mockT)).toBe(true);
    expect(toast.error).not.toHaveBeenCalled();
  });

  describe("App Survey Segment Validation", () => {
    test("should return false and toast error for app survey with invalid segment filters", () => {
      const surveyWithInvalidSegment = {
        ...baseSurvey,
        type: "app",
        segment: {
          id: "temp",
          filters: [{ connector: "and", resource: { id: "invalid", name: "invalid", type: "invalid" } }], // Invalid structure for ZSegmentFilters
          isPrivate: false,
          title: "temp segment",
          description: "",
          surveyId: "survey1",
        },
      } as unknown as TSurvey;

      expect(validation.isSurveyValid(surveyWithInvalidSegment, "en", mockT)).toBe(false); // Zod parse will fail
      expect(toast.error).toHaveBeenCalledWith("workspace.surveys.edit.invalid_targeting");
    });

    test("should return true for app survey with valid segment filters", () => {
      const surveyWithValidSegment = {
        ...baseSurvey,
        type: "app",
        segment: {
          id: "temp",
          filters: [
            {
              resource: { id: "userId", name: "User ID", type: "person" },
              condition: { id: "equals", name: "Equals" },
              value: "test",
            },
          ], // Valid structure
          isPrivate: false,
          title: "temp segment",
          description: "",
          surveyId: "survey1",
        },
      } as unknown as TSurvey;
      const mockSafeParse = vi.spyOn(ZSegmentFilters, "safeParse");
      mockSafeParse.mockReturnValue({ success: true, data: surveyWithValidSegment.segment!.filters });

      expect(validation.isSurveyValid(surveyWithValidSegment, "en", mockT)).toBe(true);
      expect(toast.error).not.toHaveBeenCalled();
      mockSafeParse.mockRestore();
    });
  });
});

describe("validation.getValidateIdErrorMessage", () => {
  const mockT: TFunction = ((key: string, params?: Record<string, string>) => {
    if (!params) return key;
    return Object.entries(params).reduce((str, [k, v]) => str.replace(`{${k}}`, v), key);
  }) as TFunction;

  test("returns translated message for Empty error code", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.Empty, field: "" },
      mockT
    );
    expect(result).toContain("validate_id_empty");
  });

  test("returns translated message for Duplicate error code", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.Duplicate, field: "test" },
      mockT
    );
    expect(result).toContain("validate_id_duplicate");
  });

  test("returns translated message for Reserved error code with field name", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.Reserved, field: "userId" },
      mockT
    );
    expect(result).toContain("validate_id_reserved");
  });

  test("returns translated message for HasSpaces error code", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.HasSpaces, field: "my field" },
      mockT
    );
    expect(result).toContain("validate_id_no_spaces");
  });

  test("returns translated message for InvalidChars error code", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.InvalidChars, field: "field!" },
      mockT
    );
    expect(result).toContain("validate_id_invalid_chars");
  });

  test("returns a distinct message for NotSafeIdentifier error code", () => {
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.NotSafeIdentifier, field: "Legacy-Field" },
      mockT
    );
    expect(result).toContain("validate_id_not_safe_identifier");
    expect(result).not.toContain("validate_id_invalid_chars");
  });

  test("asks for the sentence alone, with no entity to interpolate", () => {
    // The `{type}` placeholder is gone with the cards that shared these strings, so a second lookup
    // for "Hidden field" or "Variable" is the regression to catch: it would mean the sentences had
    // drifted back to naming an entity this function no longer knows about.
    const spyT = vi.fn().mockReturnValue("translated");
    const result = validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.Empty, field: "" },
      spyT as unknown as TFunction
    );

    expect(spyT).toHaveBeenCalledTimes(1);
    expect(spyT).toHaveBeenCalledWith("workspace.surveys.edit.validate_id_empty");
    expect(result).toBe("translated");
  });

  test("passes the refused field for Reserved, and nothing else", () => {
    const spyT = vi.fn().mockReturnValue("translated");

    validation.getValidateIdErrorMessage(
      { code: TValidateIdErrorCode.Reserved, field: "userId" },
      spyT as unknown as TFunction
    );

    expect(spyT).toHaveBeenCalledTimes(1);
    expect(spyT).toHaveBeenCalledWith("workspace.surveys.edit.validate_id_reserved", {
      field: "userId",
    });
  });
});

describe("validation.isBlockLogicItemValid", () => {
  // A fully schema-valid rule: a real cuid id, an "and" condition group and a
  // jumpToBlock action pointing at a valid block id.
  const validLogicItem: TSurveyBlockLogic = {
    id: "cs8fnvm1v9d8x1234567890ab",
    conditions: {
      id: "n1x8fq7z9v2c3b4m5k6j7h8g",
      connector: "and",
      conditions: [],
    },
    actions: [
      {
        id: "aq7z9v2c3b4m5k6j7h8g1x8f",
        objective: "jumpToBlock",
        target: "bx8fq7z9v2c3b4m5k6j7h8ga",
      },
    ],
  };

  test("returns true for a schema-valid conditional-logic rule", () => {
    expect(validation.isBlockLogicItemValid(validLogicItem)).toBe(true);
  });

  test("returns false when a jumpToBlock action has an empty target", () => {
    const emptyJumpTarget: TSurveyBlockLogic = {
      ...validLogicItem,
      actions: [{ id: "aq7z9v2c3b4m5k6j7h8g1x8f", objective: "jumpToBlock", target: "" }],
    };

    expect(validation.isBlockLogicItemValid(emptyJumpTarget)).toBe(false);
  });

  test("returns false when a condition is missing its required right operand", () => {
    const missingRightOperand: TSurveyBlockLogic = {
      ...validLogicItem,
      conditions: {
        id: "n1x8fq7z9v2c3b4m5k6j7h8g",
        connector: "and",
        conditions: [
          {
            id: "cx8fq7z9v2c3b4m5k6j7h8ga",
            leftOperand: { type: "element", value: "element-1" },
            // "equals" requires a right operand, which is intentionally omitted.
            operator: "equals",
          },
        ],
      },
    };

    expect(validation.isBlockLogicItemValid(missingRightOperand)).toBe(false);
  });

  test("returns false when the rule id is not a valid cuid", () => {
    expect(validation.isBlockLogicItemValid({ ...validLogicItem, id: "logic-1" })).toBe(false);
  });
});

// Mirrors the en-US strings the element-issue messages are built from, so the assertions below read
// as the author sees them rather than as raw keys.
const elementIssueMessages: Record<string, string> = {
  "common.row_n": "Row {n}",
  "common.column_n": "Column {n}",
  "common.choice_n": "Choice {n}",
  "workspace.surveys.edit.invalid_field_in_question":
    "Check {field} in question {questionNumber} of block {blockNumber}",
  "workspace.surveys.edit.invalid_field_in_question_for_languages":
    "Check {field} in question {questionNumber} of block {blockNumber} for the following languages: {languages}",
  "workspace.surveys.edit.invalid_question_in_block":
    "Check question {questionNumber} in block {blockNumber}",
  "workspace.surveys.edit.issue_in_question": "Question {questionNumber} of block {blockNumber}: {message}",
  "workspace.surveys.edit.field_label_shuffle_option": "ordering",
};

const elementIssueT: TFunction = ((key: string, params?: Record<string, string | number>) => {
  const template = elementIssueMessages[key] ?? key;
  if (!params) return template;
  return Object.entries(params).reduce((str, [k, v]) => str.replace(`{${k}}`, String(v)), template);
}) as TFunction;

describe("validation.describeElementIssue", () => {
  test("names the matrix row, question and block, and reports the failing language", () => {
    const result = validation.describeElementIssue(
      {
        code: "invalid_type",
        expected: "string",
        path: ["blocks", 0, "elements", 0, "rows", 1, "label", "de"],
        message: "Invalid input: expected string, received undefined",
      },
      elementIssueT,
      "en-US"
    );

    expect(result).toEqual({
      languageCode: "de",
      message: "Check Row 2 label in question 1 of block 1 for the following languages: German",
    });
  });

  test("names a matrix column without a language when the path has none", () => {
    const result = validation.describeElementIssue(
      {
        code: "invalid_type",
        expected: "string",
        path: ["blocks", 2, "elements", 1, "columns", 0, "label"],
        message: "Invalid input: expected string, received undefined",
      },
      elementIssueT,
      "en-US"
    );

    expect(result).toEqual({ message: "Check Column 1 label in question 2 of block 3" });
  });

  test("falls back to the language code when the locale has no label for it", () => {
    const result = validation.describeElementIssue(
      {
        code: "invalid_type",
        expected: "string",
        path: ["blocks", 0, "elements", 0, "headline", "xx-not-a-language"],
        message: "Invalid input: expected string, received undefined",
      },
      elementIssueT,
      "en-US"
    );

    expect(result).toEqual({
      languageCode: "xx-not-a-language",
      message: "Check headline in question 1 of block 1 for the following languages: xx-not-a-language",
    });
  });

  test("names only the question and block when the issue points at the element itself", () => {
    const result = validation.describeElementIssue(
      { code: "invalid_union", errors: [], path: ["blocks", 1, "elements", 3], message: "Invalid input" },
      elementIssueT,
      "en-US"
    );

    expect(result).toEqual({ message: "Check question 4 in block 2" });
  });

  test("keeps a message the schema authored and only prepends its location", () => {
    const result = validation.describeElementIssue(
      {
        code: "too_small",
        origin: "array",
        minimum: 2,
        path: ["blocks", 0, "elements", 0, "choices"],
        message: "Multiple Choice Element must have at least two choices",
      },
      elementIssueT,
      "en-US"
    );

    expect(result).toEqual({
      message: "Question 1 of block 1: Multiple Choice Element must have at least two choices",
    });
  });

  test("returns null for issues outside an element so their own message is kept", () => {
    expect(
      validation.describeElementIssue(
        {
          code: "too_small",
          origin: "string",
          minimum: 1,
          path: ["blocks", 0, "name"],
          message: "Block name is required",
        },
        elementIssueT,
        "en-US"
      )
    ).toBeNull();
    expect(
      validation.describeElementIssue(
        { code: "invalid_union", errors: [], path: ["endings", 0, "headline"], message: "Invalid input" },
        elementIssueT,
        "en-US"
      )
    ).toBeNull();
  });
});

describe("ZSurvey element issues reach the editor with a usable path", () => {
  const buildLanguage = (id: string, code: string, isDefault: boolean): TSurveyLanguage => ({
    language: {
      id,
      code,
      alias: null,
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "cl9dsxhzt0000qz0h5z6z6z62",
    },
    default: isDefault,
    enabled: true,
  });

  const buildSurveyWithElement = (element: Record<string, unknown>) => ({
    id: "cl9dsxhzt0000qz0h5z6z6z61",
    createdAt: new Date(),
    updatedAt: new Date(),
    name: "Matrix survey",
    type: "link",
    workspaceId: "cl9dsxhzt0000qz0h5z6z6z62",
    createdBy: null,
    visibility: "workspace",
    ownerId: null,
    visibilityVersion: 0,
    visibilityProjectedVersion: 0,
    visibilityChangedAt: null,
    visibilityChangedById: null,
    status: "draft",
    publishOn: null,
    closeOn: null,
    displayOption: "displayOnce",
    autoClose: null,
    triggers: [],
    recontactDays: null,
    displayLimit: null,
    welcomeCard: { enabled: false, timeToFinish: false, showResponseCount: false },
    questions: [],
    blocks: [{ id: "block1", name: "Block 1", elements: [element] }],
    endings: [],
    hiddenFields: { enabled: false },
    delay: 0,
    displayPercentage: null,
    autoComplete: null,
    surveyClosedMessage: { enabled: false },
    workspaceOverwrites: null,
    recaptcha: null,
    singleUse: null,
    styling: null,
    segment: null,
    languages: [
      buildLanguage("cl9dsxhzt0000qz0h5z6z6z6a", "en", true),
      buildLanguage("cl9dsxhzt0000qz0h5z6z6z6b", "de", false),
    ],
    showLanguageSwitch: false,
    isVerifyEmailEnabled: false,
    variables: [],
    followUps: [],
    isBackButtonHidden: false,
    isAutoProgressingEnabled: true,
    metadata: {},
    slug: null,
    isCaptureIpEnabled: false,
    isAnonymizeResponsesEnabled: false,
  });

  // A matrix element whose second row label has no value for the enabled `de` language. This is the
  // shape a survey ends up in when a translation is dropped, and it must not parse.
  const buildSurveyWithBrokenMatrixRow = () =>
    buildSurveyWithElement({
      id: "matrix1",
      type: "matrix",
      headline: { default: "How satisfied are you?", de: "Wie zufrieden sind Sie?" },
      required: true,
      rows: [
        { id: "r1", label: { default: "Design", de: "Design" } },
        { id: "r2", label: { default: "Performance", de: undefined } },
      ],
      columns: [{ id: "c1", label: { default: "Good", de: "Gut" } }],
    });

  // The shape that blocked the reported survey: a multi-select whose ordering holds a value the
  // enum does not know. `shuffleOption` is what the author has to fix, so the toast has to name it.
  const buildSurveyWithShuffleOption = (shuffleOption: unknown) =>
    buildSurveyWithElement({
      id: "choice1",
      type: "multipleChoiceMulti",
      headline: { default: "What got in the way?", de: "Was stand im Weg?" },
      required: true,
      shuffleOption,
      choices: [
        { id: "c1", label: { default: "Time", de: "Zeit" } },
        { id: "c2", label: { default: "Budget", de: "Budget" } },
      ],
    });

  test("a matrix row label missing an enabled language points at the row, not at the element", () => {
    const result = ZSurvey.safeParse(buildSurveyWithBrokenMatrixRow());

    expect(result.success).toBe(false);
    const issue = result.error?.issues[0];

    // Before the element union was discriminated, this was a single `invalid_union` issue at
    // ["blocks", 0, "elements", 0] carrying Zod's bare "Invalid input" — no field, nothing actionable.
    expect(issue?.path).toEqual(["blocks", 0, "elements", 0, "rows", 1, "label", "de"]);
  });

  test("the editor turns that issue into a message naming the row, question and block", () => {
    const result = ZSurvey.safeParse(buildSurveyWithBrokenMatrixRow());
    const issue = result.error?.issues[0];

    const described = validation.describeElementIssue(
      { ...issue, path: issue?.path ?? [], message: issue?.message ?? "" },
      elementIssueT,
      "en-US"
    );

    expect(described).toEqual({
      languageCode: "de",
      message: "Check Row 2 label in question 1 of block 1 for the following languages: German",
    });
  });

  test("an out-of-enum shuffleOption points at the field, not at the element", () => {
    const result = ZSurvey.safeParse(buildSurveyWithShuffleOption("random"));

    expect(result.success).toBe(false);
    const issue = result.error?.issues[0];

    // On the plain union this was ["blocks", 0, "elements", 0] with the bare "Invalid input" the
    // customer saw. The field name is the one word an author needs to unblock themselves.
    expect(issue?.path).toEqual(["blocks", 0, "elements", 0, "shuffleOption"]);
    expect(issue?.code).toBe("invalid_value");
  });

  test("the editor names the ordering field for that issue", () => {
    const result = ZSurvey.safeParse(buildSurveyWithShuffleOption("random"));
    const issue = result.error?.issues[0];

    const described = validation.describeElementIssue(
      { ...issue, path: issue?.path ?? [], message: issue?.message ?? "" },
      elementIssueT,
      "en-US"
    );

    // Zod renders this as `Invalid option: expected one of "none"|"all"|…`, which is generated rather
    // than schema-authored — so the message is built from the path instead of passed through.
    expect(described).toEqual({ message: "Check ordering in question 1 of block 1" });
  });

  test("an empty shuffleOption is healed on read rather than blocking publish", () => {
    const result = ZSurvey.safeParse(buildSurveyWithShuffleOption(""));

    expect(result.success).toBe(true);
    expect(result.data?.blocks[0].elements[0]).toMatchObject({ shuffleOption: undefined });
  });

  test("an empty shuffleOption on a matrix falls back to its default", () => {
    const survey = buildSurveyWithElement({
      id: "matrix1",
      type: "matrix",
      headline: { default: "How satisfied are you?", de: "Wie zufrieden sind Sie?" },
      required: true,
      shuffleOption: "",
      rows: [{ id: "r1", label: { default: "Design", de: "Design" } }],
      columns: [{ id: "c1", label: { default: "Good", de: "Gut" } }],
    });
    const result = ZSurvey.safeParse(survey);

    expect(result.success).toBe(true);
    expect(result.data?.blocks[0].elements[0]).toMatchObject({ shuffleOption: "none" });
  });
});

// ENG-2581: the editor stopped disabling Save / Save & Close / Publish for a missing trigger and
// now blocks the click instead, so this predicate is what decides whether the click is refused. It is
// the server's publish rule itself (`lib/survey/publish-rule.ts`), so the two can't drift.
describe("validation.isMissingRequiredTrigger", () => {
  const appSurveyWithoutTriggers = { type: "app", triggers: [] } as unknown as TSurvey;

  test.each(["inProgress", "paused", "completed"] as const)(
    "refuses an app survey with no trigger heading for %s",
    (targetStatus) => {
      expect(validation.isMissingRequiredTrigger(appSurveyWithoutTriggers, targetStatus, false)).toBe(true);
    }
  );

  test("publishes an app survey with no trigger of its own when a creative opens it (ENG-3994)", () => {
    expect(validation.isMissingRequiredTrigger(appSurveyWithoutTriggers, "inProgress", true)).toBe(false);
  });

  test("lets an app survey with no trigger be saved as a draft", () => {
    expect(validation.isMissingRequiredTrigger(appSurveyWithoutTriggers, "draft", false)).toBe(false);
  });

  test("lets a link survey publish with no trigger", () => {
    expect(
      validation.isMissingRequiredTrigger(
        { type: "link", triggers: [] } as unknown as TSurvey,
        "inProgress",
        false
      )
    ).toBe(false);
  });

  test("lets an app survey with a trigger publish", () => {
    const withTrigger = {
      type: "app",
      triggers: [{ actionClass: { id: "action1", name: "Click" } }],
    } as unknown as TSurvey;

    expect(validation.isMissingRequiredTrigger(withTrigger, "inProgress", false)).toBe(false);
  });

  test.each([
    ["a null triggers array", null],
    ["an undefined triggers array", undefined],
    ["a hole left by a removed trigger", [undefined]],
  ])("treats %s as no trigger", (_case, triggers) => {
    expect(
      validation.isMissingRequiredTrigger(
        { type: "app", triggers } as unknown as TSurvey,
        "inProgress",
        false
      )
    ).toBe(true);
  });
});
