import type { TFunction } from "i18next";
import { describe, expect, test, vi } from "vitest";
import type { TResponseData } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import type {
  TSurveyAddressElement,
  TSurveyContactInfoElement,
  TSurveyElement,
  TSurveyMatrixElement,
  TSurveyOpenTextElement,
  TSurveyRankingElement,
} from "@formbricks/types/surveys/elements";
import { getFirstErrorMessage, validateBlockResponses, validateElementResponse } from "./evaluator";

// Mock translation function
const mockT = vi.fn((key: string) => {
  return key;
}) as unknown as TFunction;

// Mock only getTranslations; keep the real getLocalizedValue so these tests exercise the actual
// localization fallback the evaluator relies on (a hand-rolled mirror masked ENG-2001).
vi.mock("@/lib/i18n", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/i18n")>();
  const mockTFn = vi.fn((key: string) => key) as unknown as TFunction;
  return {
    ...actual,
    getTranslations: () => mockTFn,
  };
});

// Mock i18n.config to return our mock translation function
vi.mock("@/lib/i18n.config", () => ({
  default: {
    language: "en",
    changeLanguage: vi.fn(),
    getFixedT: vi.fn(() => mockT),
  },
}));

describe("validateElementResponse", () => {
  describe("required field validation", () => {
    test("should return error when required field is empty", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: true,
        inputType: "text",
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "", "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
      expect(result.errors[0].ruleId).toBe("required");
    });

    test("should return valid when required field has value", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: true,
        inputType: "text",
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "test value", "en");
      expect(result.valid).toBe(true);
      expect(result.errors).toHaveLength(0);
    });

    describe("Signature element", () => {
      const signatureElement = (required: boolean) =>
        ({
          id: "sig1",
          type: TSurveyElementTypeEnum.Signature,
          headline: { default: "Sign here" },
          required,
          allowTypedSignature: true,
        }) as unknown as TSurveyElement;
      const signatureUrl = "/storage/ws1/private/surveys/survey1/elements/sig1/signature--fid--abc.png";

      test.each([
        ["an empty string", ""],
        ["undefined", undefined],
      ])("should block a required Signature left as %s with the required error", (_label, value) => {
        const result = validateElementResponse(signatureElement(true), value, "en");

        expect(result.valid).toBe(false);
        expect(result.errors).toHaveLength(1);
        expect(result.errors[0].ruleId).toBe("required");
      });

      test("should accept a required Signature that holds a stored URL", () => {
        expect(validateElementResponse(signatureElement(true), signatureUrl, "en").valid).toBe(true);
      });

      test("should let an optional Signature be skipped", () => {
        expect(validateElementResponse(signatureElement(false), "", "en").valid).toBe(true);
        expect(validateElementResponse(signatureElement(false), undefined as never, "en").valid).toBe(true);
      });
    });

    test("should return valid when field is not required", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "", "en");
      expect(result.valid).toBe(true);
    });

    test("should return error when required multi-select has other selected but no text", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, ["opt1", ""], "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("required");
    });

    test("should return error when optional multi-select has other selected but no text", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: false,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, ["Option 1", ""], "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("required");
    });

    test("should return error when optional single-select has other selected but no text", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: false,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, "", "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("required");
    });

    test("should return error when optional single-select has blank other text", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: false,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, "   ", "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("required");
    });

    test("should return valid when optional single-select has no response", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: false,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, undefined, "en");
      expect(result.valid).toBe(true);
    });

    test("should return valid when required multi-select has other with text (legacy sentinel)", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, ["opt1", "", "custom"], "en");
      expect(result.valid).toBe(true);
    });

    test("should return valid when required multi-select has other text without sentinel", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: true,
        // The Other option is what makes the trailing free-text value ("custom") legitimate;
        // legacy clients send it without the "" sentinel.
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, ["opt1", "custom"], "en");
      expect(result.valid).toBe(true);
    });

    test("should reject single-select value that is not a configured option (no Other option)", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "yes", label: { default: "Yes" } },
          { id: "no", label: { default: "No" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, "ARBITRARY_VALUE", "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("invalidOption");
    });

    test("should accept single-select value matching a configured option by id or label", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "yes", label: { default: "Yes" } },
          { id: "no", label: { default: "No" } },
        ],
      } as unknown as TSurveyElement;

      expect(validateElementResponse(element, "yes", "en").valid).toBe(true); // by id
      expect(validateElementResponse(element, "No", "en").valid).toBe(true); // by label
    });

    test("should reject multi-select values that are not configured options (no Other option)", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "opt2", label: { default: "Option 2" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, ["Option 1", "injected"], "en");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("invalidOption");
    });

    test("should accept a choice by its default label when the response language code's label is empty (ENG-2001)", () => {
      // Reproduces the broken-survey state: the default language is keyed by its real code
      // ("en-GB") but that key is empty, while the actual label text lives under "default".
      // The submitted value is the default label; membership must still resolve via the fallback.
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick", "en-GB": "" },
        required: true,
        choices: [
          { id: "c1", label: { default: "AdJUST", "en-GB": "" } },
          { id: "c2", label: { default: "Keep", "en-GB": "" } },
        ],
      } as unknown as TSurveyElement;

      // Response recorded under the default language's real code (see getDefaultLanguageCode).
      expect(validateElementResponse(element, "AdJUST", "en-GB").valid).toBe(true);
      expect(validateElementResponse(element, "c2", "en-GB").valid).toBe(true); // still matches by id
    });

    test("should still reject a genuinely invalid value when labels are empty for the language (ENG-2001)", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick", "en-GB": "" },
        required: true,
        choices: [
          { id: "c1", label: { default: "AdJUST", "en-GB": "" } },
          { id: "c2", label: { default: "Keep", "en-GB": "" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, "INJECTED", "en-GB");
      expect(result.valid).toBe(false);
      expect(result.errors[0].ruleId).toBe("invalidOption");
    });

    test("should accept the rendered default label when the default language's code key holds a stale value (ENG-4103)", () => {
      // The renderer shows `default` but reports the response language as the default's real code,
      // whose key here carries an older label respondents never see.
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Tier" },
        required: true,
        choices: [
          { id: "gold", label: { default: "Gold (200만원)", "ko-KR": "Gold | 2,000,000 KRW" } },
          { id: "silver", label: { default: "Silver (100만원)", "ko-KR": "Silver | 1,000,000 KRW" } },
        ],
      } as unknown as TSurveyElement;

      expect(validateElementResponse(element, "Gold (200만원)", "ko-KR").valid).toBe(true);
      expect(validateElementResponse(element, "Silver | 1,000,000 KRW", "ko-KR").valid).toBe(true);

      const injected = validateElementResponse(element, "Platinum", "ko-KR");
      expect(injected.valid).toBe(false);
      expect(injected.errors[0].ruleId).toBe("invalidOption");
    });

    test("should accept a multi-select label stored under another language than the response's (ENG-4103)", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1", de: "Option eins" } },
          { id: "opt2", label: { default: "Option 2", de: "Option zwei" } },
        ],
      } as unknown as TSurveyElement;

      expect(validateElementResponse(element, ["Option 1", "Option zwei"], "de").valid).toBe(true);
      expect(validateElementResponse(element, ["Option 1", "Option drei"], "de").valid).toBe(false);
    });

    test("should accept arbitrary free text for a single-select with an Other option", () => {
      const element = {
        id: "single1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "other", label: { default: "Other" } },
        ],
      } as unknown as TSurveyElement;

      const result = validateElementResponse(element, "some free text", "en");
      expect(result.valid).toBe(true);
    });

    test("should not throw for a malformed choice element missing choices", () => {
      const element = {
        id: "mc1",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Pick" },
        required: false,
      } as unknown as TSurveyElement; // choices intentionally absent

      expect(() => validateElementResponse(element, "anything", "en")).not.toThrow();
      expect(validateElementResponse(element, "anything", "en").valid).toBe(true);
    });

    test("should handle required ranking element - at least one ranked", () => {
      const element: TSurveyElement = {
        id: "rank1",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank these" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "opt2", label: { default: "Option 2" } },
        ],
      } as unknown as TSurveyRankingElement;

      const result = validateElementResponse(element, ["opt1"], "en");
      expect(result.valid).toBe(true);
    });

    test("should return error when required ranking element has no ranked options", () => {
      const element: TSurveyElement = {
        id: "rank1",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank these" },
        required: true,
        choices: [
          { id: "opt1", label: { default: "Option 1" } },
          { id: "opt2", label: { default: "Option 2" } },
        ],
      } as unknown as TSurveyRankingElement;

      const result = validateElementResponse(element, [], "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
    });

    test("should handle required matrix element - at least 1 row must be answered", () => {
      const element: TSurveyElement = {
        id: "matrix1",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "Matrix question" },
        required: true,
        shuffleOption: "none",
        rows: [
          { id: "row1", label: { default: "Row 1" } },
          { id: "row2", label: { default: "Row 2" } },
        ],
        columns: [
          { id: "col1", label: { default: "Col 1" } },
          { id: "col2", label: { default: "Col 2" } },
        ],
      } as unknown as TSurveyMatrixElement;

      // At least 1 row answered should pass
      const result1 = validateElementResponse(element, { row1: "col1" }, "en");
      expect(result1.valid).toBe(true);

      // All rows answered should also pass
      const result2 = validateElementResponse(element, { row1: "col1", row2: "col2" }, "en");
      expect(result2.valid).toBe(true);
    });

    test("should return error when required matrix element has no rows answered", () => {
      const element: TSurveyElement = {
        id: "matrix1",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "Matrix question" },
        required: true,
        shuffleOption: "none",
        rows: [
          { id: "row1", label: { default: "Row 1" } },
          { id: "row2", label: { default: "Row 2" } },
        ],
        columns: [
          { id: "col1", label: { default: "Col 1" } },
          { id: "col2", label: { default: "Col 2" } },
        ],
      } as unknown as TSurveyMatrixElement;

      const result = validateElementResponse(element, {}, "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
    });
  });

  describe("ranking element with an Other option", () => {
    const buildRanking = (withOther: boolean, required = false): TSurveyElement =>
      ({
        id: "rank1",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank these" },
        required,
        choices: [
          { id: "opt1", label: { default: "Price" } },
          { id: "opt2", label: { default: "Speed" } },
          ...(withOther ? [{ id: "other", label: { default: "Other" } }] : []),
        ],
      }) as unknown as TSurveyRankingElement;

    test("rejects a ranked Other whose text is empty", () => {
      const result = validateElementResponse(buildRanking(true), ["Price", ""], "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
    });

    test("rejects a ranked Other whose text is whitespace only", () => {
      expect(validateElementResponse(buildRanking(true, true), ["  ", "Speed"], "en").valid).toBe(false);
    });

    test("accepts a ranked Other with text", () => {
      expect(validateElementResponse(buildRanking(true), ["Price", "Integrations"], "en").valid).toBe(true);
    });

    test("accepts a ranking that leaves Other unranked", () => {
      expect(validateElementResponse(buildRanking(true), ["Speed", "Price"], "en").valid).toBe(true);
    });

    test("ignores empty entries when the element has no Other option", () => {
      expect(validateElementResponse(buildRanking(false), ["Price", ""], "en").valid).toBe(true);
    });
  });

  describe("validation rules - AND logic", () => {
    test("should return valid when all rules pass", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 5 } },
            { id: "rule2", type: "maxLength", params: { max: 10 } },
          ],
          logic: "and",
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hello", "en");
      expect(result.valid).toBe(true);
    });

    test("should return error when one rule fails", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 10 } },
            { id: "rule2", type: "maxLength", params: { max: 20 } },
          ],
          logic: "and",
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hi", "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
    });

    test("should return multiple errors when multiple rules fail", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 10 } },
            { id: "rule2", type: "maxLength", params: { max: 5 } },
          ],
          logic: "and",
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hello", "en");
      expect(result.valid).toBe(false);
      expect(result.errors.length).toBeGreaterThan(0);
    });

    test("should default to AND logic when logic is not specified", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 10 } },
            { id: "rule2", type: "maxLength", params: { max: 5 } },
          ],
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hello", "en");
      expect(result.valid).toBe(false);
    });
  });

  describe("validation rules - OR logic", () => {
    test("should return valid when at least one rule passes", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 10 } },
            { id: "rule2", type: "maxLength", params: { max: 20 } },
          ],
          logic: "or",
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hello", "en");
      expect(result.valid).toBe(true);
    });

    test("should return error when all rules fail", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [
            { id: "rule1", type: "minLength", params: { min: 10 } },
            { id: "rule2", type: "maxLength", params: { max: 3 } },
          ],
          logic: "or",
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "hello", "en");
      expect(result.valid).toBe(false);
      expect(result.errors.length).toBeGreaterThan(0);
    });
  });

  describe("implicit validation for OpenText inputType", () => {
    test("should add implicit email validation for email inputType", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        inputType: "email",
        required: false,
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "invalid-email", "en");
      expect(result.valid).toBe(false);
      expect(result.errors.some((e) => e.ruleId === "__implicit_email__")).toBe(true);
    });

    test("should add implicit url validation for url inputType", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        inputType: "url",
        required: false,
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "not-a-url", "en");
      expect(result.valid).toBe(false);
      expect(result.errors.some((e) => e.ruleId === "__implicit_url__")).toBe(true);
    });

    test("should add implicit phone validation for phone inputType", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        inputType: "phone",
        required: false,
        charLimit: 0,
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "invalid-phone", "en");
      expect(result.valid).toBe(false);
      expect(result.errors.some((e) => e.ruleId === "__implicit_phone__")).toBe(true);
    });

    test("should not add implicit rule if explicit rule exists", () => {
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        inputType: "email",
        required: false,
        charLimit: 0,
        validation: {
          rules: [{ id: "rule1", type: "email", params: {} }],
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "test@example.com", "en");
      expect(result.valid).toBe(true);
      expect(result.errors.some((e) => e.ruleId === "__implicit_email__")).toBe(false);
    });
  });

  describe("implicit validation for ContactInfo", () => {
    test("should add implicit email validation for email field", () => {
      const element: TSurveyElement = {
        id: "contact1",
        type: TSurveyElementTypeEnum.ContactInfo,
        headline: { default: "Contact Info" },
        firstName: { show: true, required: false, placeholder: { default: "First Name" } },
        lastName: { show: true, required: false, placeholder: { default: "Last Name" } },
        email: { show: true, required: false, placeholder: { default: "Email" } },
        phone: { show: false, required: false, placeholder: { default: "Phone" } },
        company: { show: false, required: false, placeholder: { default: "Company" } },
        required: false,
      } as unknown as TSurveyContactInfoElement;

      const result = validateElementResponse(element, ["John", "Doe", "invalid-email", "", ""], "en");
      expect(result.valid).toBe(false);
      expect(result.errors.some((e) => e.ruleId === "__implicit_email_field__")).toBe(true);
    });

    test("should add implicit phone validation for phone field", () => {
      const element: TSurveyElement = {
        id: "contact1",
        type: TSurveyElementTypeEnum.ContactInfo,
        headline: { default: "Contact Info" },
        firstName: { show: true, required: false, placeholder: { default: "First Name" } },
        lastName: { show: true, required: false, placeholder: { default: "Last Name" } },
        email: { show: false, required: false, placeholder: { default: "Email" } },
        phone: { show: true, required: false, placeholder: { default: "Phone" } },
        company: { show: false, required: false, placeholder: { default: "Company" } },
        required: false,
      } as unknown as TSurveyContactInfoElement;

      const result = validateElementResponse(element, ["John", "Doe", "", "invalid-phone", ""], "en");
      expect(result.valid).toBe(false);
      expect(result.errors.some((e) => e.ruleId === "__implicit_phone_field__")).toBe(true);
    });

    test("should not add implicit rule if explicit rule exists", () => {
      const element: TSurveyElement = {
        id: "contact1",
        type: TSurveyElementTypeEnum.ContactInfo,
        headline: { default: "Contact Info" },
        firstName: { show: true, required: false, placeholder: { default: "First Name" } },
        lastName: { show: true, required: false, placeholder: { default: "Last Name" } },
        email: { show: true, required: false, placeholder: { default: "Email" } },
        phone: { show: false, required: false, placeholder: { default: "Phone" } },
        company: { show: false, required: false, placeholder: { default: "Company" } },
        required: false,
        validation: {
          rules: [{ id: "rule1", type: "email", field: "email", params: {} }],
        },
      } as unknown as TSurveyContactInfoElement;

      const result = validateElementResponse(element, ["John", "Doe", "test@example.com", "", ""], "en");
      expect(result.valid).toBe(true);
      expect(result.errors.some((e) => e.ruleId === "__implicit_email_field__")).toBe(false);
    });
  });

  describe("field-specific validation for Address", () => {
    test("should validate specific field in address element", () => {
      const element: TSurveyElement = {
        id: "address1",
        type: TSurveyElementTypeEnum.Address,
        headline: { default: "Address" },
        addressLine1: { show: true, required: false, placeholder: { default: "Address Line 1" } },
        addressLine2: { show: false, required: false, placeholder: { default: "Address Line 2" } },
        city: { show: true, required: false, placeholder: { default: "City" } },
        state: { show: true, required: false, placeholder: { default: "State" } },
        zip: { show: true, required: false, placeholder: { default: "ZIP" } },
        country: { show: true, required: false, placeholder: { default: "Country" } },
        required: false,
        validation: {
          rules: [{ id: "rule1", type: "minLength", field: "city", params: { min: 3 } }],
        },
      } as unknown as TSurveyAddressElement;

      const result = validateElementResponse(element, ["123 Main St", "", "NY", "", "", ""], "en");
      expect(result.valid).toBe(false);
    });

    test("should validate correct field value", () => {
      const element: TSurveyElement = {
        id: "address1",
        type: TSurveyElementTypeEnum.Address,
        headline: { default: "Address" },
        addressLine1: { show: true, required: false, placeholder: { default: "Address Line 1" } },
        addressLine2: { show: false, required: false, placeholder: { default: "Address Line 2" } },
        city: { show: true, required: false, placeholder: { default: "City" } },
        state: { show: true, required: false, placeholder: { default: "State" } },
        zip: { show: true, required: false, placeholder: { default: "ZIP" } },
        country: { show: true, required: false, placeholder: { default: "Country" } },
        required: false,
        validation: {
          rules: [{ id: "rule1", type: "minLength", field: "city", params: { min: 3 } }],
        },
      } as unknown as TSurveyAddressElement;

      const result = validateElementResponse(element, ["123 Main St", "", "New York", "", "", ""], "en");
      expect(result.valid).toBe(true);
    });
  });

  describe("field-specific validation for ContactInfo", () => {
    test("should validate specific field in contact info element", () => {
      const element: TSurveyElement = {
        id: "contact1",
        type: TSurveyElementTypeEnum.ContactInfo,
        headline: { default: "Contact Info" },
        firstName: { show: true, required: false, placeholder: { default: "First Name" } },
        lastName: { show: true, required: false, placeholder: { default: "Last Name" } },
        email: { show: true, required: false, placeholder: { default: "Email" } },
        phone: { show: true, required: false, placeholder: { default: "Phone" } },
        company: { show: false, required: false, placeholder: { default: "Company" } },
        required: false,
        validation: {
          rules: [{ id: "rule1", type: "minLength", field: "firstName", params: { min: 3 } }],
        },
      } as unknown as TSurveyContactInfoElement;

      const result = validateElementResponse(
        element,
        ["Jo", "Doe", "test@example.com", "1234567890", ""],
        "en"
      );
      expect(result.valid).toBe(false);
    });

    describe("field label prefix", () => {
      const buildElement = (firstNamePlaceholder: string): TSurveyElement =>
        ({
          id: "contact1",
          type: TSurveyElementTypeEnum.ContactInfo,
          headline: { default: "Contact Info" },
          firstName: { show: true, required: false, placeholder: { default: firstNamePlaceholder } },
          lastName: { show: true, required: false, placeholder: { default: "Last Name" } },
          email: { show: false, required: false, placeholder: { default: "Email" } },
          phone: { show: false, required: false, placeholder: { default: "Phone" } },
          company: { show: false, required: false, placeholder: { default: "Company" } },
          required: false,
          validation: {
            rules: [{ id: "rule1", type: "minLength", field: "firstName", params: { min: 3 } }],
          },
        }) as unknown as TSurveyContactInfoElement;

      const firstMessage = (firstNamePlaceholder: string): string | undefined => {
        const result = validateElementResponse(buildElement(firstNamePlaceholder), ["Jo", "Doe"], "en");
        expect(result.valid).toBe(false);
        return result.errors[0].message;
      };

      test("should not double the colon when the label already ends with one", () => {
        expect(firstMessage("Nombre:")).toBe("Nombre: errors.min_length");
      });

      test("should strip a trailing full-width colon", () => {
        expect(firstMessage("名前：")).toBe("名前: errors.min_length");
      });

      test("should keep a single colon for a label without one", () => {
        expect(firstMessage("First Name")).toBe("First Name: errors.min_length");
      });

      test("should omit the prefix when the label is only punctuation", () => {
        expect(firstMessage(":")).toBe("errors.min_length");
      });
    });
  });

  describe("matrix element validation rules", () => {
    test("should apply validation rules when matrix is required", () => {
      const element: TSurveyElement = {
        id: "matrix1",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "Matrix question" },
        required: true,
        shuffleOption: "none",
        rows: [
          { id: "row1", label: { default: "Row 1" } },
          { id: "row2", label: { default: "Row 2" } },
        ],
        columns: [
          { id: "col1", label: { default: "Col 1" } },
          { id: "col2", label: { default: "Col 2" } },
        ],
        validation: {
          rules: [{ id: "rule1", type: "minRowsAnswered", params: { min: 2 } }],
        },
      } as unknown as TSurveyMatrixElement;

      // Required check passes (at least 1 row), but validation rule fails (needs 2 rows)
      const result = validateElementResponse(element, { row1: "col1" }, "en");
      expect(result.valid).toBe(false);
      expect(result.errors).toHaveLength(1);
    });

    test("should apply validation rules when matrix is not required", () => {
      const element: TSurveyElement = {
        id: "matrix1",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "Matrix question" },
        required: false,
        shuffleOption: "none",
        rows: [
          { id: "row1", label: { default: "Row 1" } },
          { id: "row2", label: { default: "Row 2" } },
          { id: "row3", label: { default: "Row 3" } },
        ],
        columns: [
          { id: "col1", label: { default: "Col 1" } },
          { id: "col2", label: { default: "Col 2" } },
        ],
        validation: {
          rules: [{ id: "rule1", type: "minRowsAnswered", params: { min: 2 } }],
        },
      } as unknown as TSurveyMatrixElement;

      const result = validateElementResponse(element, { row1: "col1" }, "en");
      expect(result.valid).toBe(false);
    });

    test("should apply answerAllRows validation rule", () => {
      const element: TSurveyElement = {
        id: "matrix1",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "Matrix question" },
        required: false,
        shuffleOption: "none",
        rows: [
          { id: "row1", label: { default: "Row 1" } },
          { id: "row2", label: { default: "Row 2" } },
        ],
        columns: [
          { id: "col1", label: { default: "Col 1" } },
          { id: "col2", label: { default: "Col 2" } },
        ],
        validation: {
          rules: [{ id: "rule1", type: "answerAllRows", params: {} }],
        },
      } as unknown as TSurveyMatrixElement;

      // Only 1 row answered, should fail
      const result1 = validateElementResponse(element, { row1: "col1" }, "en");
      expect(result1.valid).toBe(false);

      // All rows answered, should pass
      const result2 = validateElementResponse(element, { row1: "col1", row2: "col2" }, "en");
      expect(result2.valid).toBe(true);
    });
  });

  // ENG-7332: the server validates against the survey as stored, the survey against the element it
  // shows. Answers name rows and choices by label, as the survey stores them.
  describe("rules read the element as the respondent was offered it", () => {
    const tripMatrix = (extraRow: Record<string, unknown>) =>
      ({
        id: "trip",
        type: TSurveyElementTypeEnum.Matrix,
        headline: { default: "How was each part of your trip?" },
        required: true,
        shuffleOption: "none",
        rows: [
          { id: "flights", label: { default: "Flights" } },
          { id: "hotel", label: { default: "Hotel" } },
          { id: "visa", label: { default: "Visa Package" }, ...extraRow },
        ],
        columns: [
          { id: "okay", label: { default: "Okay" } },
          { id: "great", label: { default: "Great" } },
        ],
        validation: { rules: [{ id: "all", type: "answerAllRows", params: {} }] },
      }) as unknown as TSurveyMatrixElement;

    const premiumOnly = {
      id: "g",
      connector: "and",
      conditions: [
        {
          id: "c",
          leftOperand: { type: "element", value: "package" },
          operator: "equals",
          rightOperand: { type: "static", value: "premium" },
        },
      ],
    };

    const everyShownRow = { Flights: "Great", Hotel: "Okay" };

    test("answerAllRows passes when every row but the Hidden one is answered", () => {
      const result = validateElementResponse(tripMatrix({ hidden: true }), everyShownRow, "en");
      expect(result).toEqual({ valid: true, errors: [] });
    });

    test("answerAllRows still fails when a shown row is unanswered", () => {
      const result = validateElementResponse(tripMatrix({ hidden: true }), { Flights: "Great" }, "en");
      expect(result.errors.map((error) => error.ruleType)).toEqual(["answerAllRows"]);
    });

    test("answerAllRows passes when an older survey also answered the Hidden row", () => {
      const answers = { ...everyShownRow, "Visa Package": "Okay" };
      expect(validateElementResponse(tripMatrix({ hidden: true }), answers, "en").valid).toBe(true);
    });

    test("answerAllRows skips the rows the not-shown record lists, and only those", () => {
      const element = tripMatrix({ showIf: premiumOnly });
      const notShown = { rows: { trip: ["visa"] } };

      expect(validateElementResponse(element, everyShownRow, "en", { notShown }).valid).toBe(true);
      // The record names another element's rows, or none: the row was shown and must be answered.
      expect(
        validateElementResponse(element, everyShownRow, "en", { notShown: { rows: { other: ["visa"] } } })
          .valid
      ).toBe(false);
      expect(validateElementResponse(element, everyShownRow, "en").valid).toBe(false);
    });

    test("rankAll passes when every choice but the Hidden one is ranked", () => {
      const element = {
        id: "priorities",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank what matters most" },
        required: true,
        shuffleOption: "none",
        choices: [
          { id: "price", label: { default: "Price" } },
          { id: "comfort", label: { default: "Comfort" } },
          { id: "visa", label: { default: "Visa Package" }, hidden: true },
        ],
        validation: { rules: [{ id: "all", type: "rankAll", params: {} }] },
      } as unknown as TSurveyRankingElement;

      expect(validateElementResponse(element, ["Price", "Comfort"], "en").valid).toBe(true);
      expect(validateElementResponse(element, ["Price"], "en").valid).toBe(false);
    });

    test("answers naming a Hidden row or choice by id are left out too, as API callers may send them", () => {
      const matrixAnswer = { flights: "great", hotel: "okay", visa: "okay" };
      expect(validateElementResponse(tripMatrix({ hidden: true }), matrixAnswer, "en").valid).toBe(true);

      const ranking = {
        id: "priorities",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank what matters most" },
        required: true,
        shuffleOption: "none",
        choices: [
          { id: "price", label: { default: "Price" } },
          { id: "comfort", label: { default: "Comfort" } },
          { id: "visa", label: { default: "Visa Package" }, hidden: true },
        ],
        validation: { rules: [{ id: "all", type: "rankAll", params: {} }] },
      } as unknown as TSurveyRankingElement;
      expect(validateElementResponse(ranking, ["price", "comfort", "visa"], "en").valid).toBe(true);
    });

    test("a required ranking or matrix answered only with what it does not offer reads as unanswered", () => {
      const ranking = {
        id: "priorities",
        type: TSurveyElementTypeEnum.Ranking,
        headline: { default: "Rank what matters most" },
        required: true,
        shuffleOption: "none",
        choices: [
          { id: "price", label: { default: "Price" } },
          { id: "comfort", label: { default: "Comfort" } },
          { id: "visa", label: { default: "Visa Package" }, hidden: true },
        ],
        validation: { rules: [{ id: "all", type: "rankAll", params: {} }] },
      } as unknown as TSurveyRankingElement;

      for (const answer of [["visa"], ["Visa Package"]]) {
        const result = validateElementResponse(ranking, answer, "en");
        expect(result.errors.map((error) => error.ruleId)).toEqual(["required"]);
      }
      const hiddenOnly: Record<string, string>[] = [
        { "Visa Package": "Okay" },
        { Flights: "", "Visa Package": "Okay" },
      ];
      for (const answer of hiddenOnly) {
        const matrixResult = validateElementResponse(tripMatrix({ hidden: true }), answer, "en");
        expect(matrixResult.errors.map((error) => error.ruleId)).toContain("required");
      }
      // One shown row rated is an answer; "Answer all rows" is the rule that asks for the rest.
      const oneShownRow = validateElementResponse(
        tripMatrix({ hidden: true }),
        { Flights: "Great", "Visa Package": "Okay" },
        "en"
      );
      expect(oneShownRow.errors.map((error) => error.ruleId)).toEqual(["all"]);

      // Not required: an answer with nothing offered in it is no answer, which is allowed.
      const optional = { ...ranking, required: false } as TSurveyRankingElement;
      expect(validateElementResponse(optional, ["visa"], "en").valid).toBe(true);
    });

    test("selection rules count only the options offered, as the survey does", () => {
      const element = {
        id: "extras",
        type: TSurveyElementTypeEnum.MultipleChoiceMulti,
        headline: { default: "Which extras did you use?" },
        required: false,
        shuffleOption: "none",
        choices: [
          { id: "lounge", label: { default: "Lounge" } },
          { id: "spa", label: { default: "Spa" } },
          { id: "visa", label: { default: "Visa Package" }, hidden: true },
        ],
        validation: { rules: [{ id: "min", type: "minSelections", params: { min: 2 } }] },
      } as unknown as TSurveyElement;

      expect(validateElementResponse(element, ["Lounge", "Visa Package"], "en").valid).toBe(false);
      expect(validateElementResponse(element, ["Lounge", "Spa"], "en").valid).toBe(true);
    });

    test("an answer naming a Hidden choice stays a known choice", () => {
      // A respondent who picked "Visa Package" before it was hidden keeps a valid answer.
      const element = {
        id: "package",
        type: TSurveyElementTypeEnum.MultipleChoiceSingle,
        headline: { default: "Which package did you book?" },
        required: true,
        shuffleOption: "none",
        choices: [
          { id: "standard", label: { default: "Standard" } },
          { id: "visa", label: { default: "Visa Package" }, hidden: true },
        ],
      } as unknown as TSurveyElement;

      expect(validateElementResponse(element, "Visa Package", "en")).toEqual({ valid: true, errors: [] });
      // An API caller may name it by id, which the choice check accepts too.
      expect(validateElementResponse(element, "visa", "en")).toEqual({ valid: true, errors: [] });
    });
  });

  describe("unknown validation rule type", () => {
    test("should handle unknown rule type gracefully", () => {
      const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
      const element: TSurveyElement = {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: false,
        inputType: "text",
        charLimit: 0,
        validation: {
          rules: [{ id: "rule1", type: "unknown" as any, params: {} }],
        },
      } as unknown as TSurveyOpenTextElement;

      const result = validateElementResponse(element, "test", "en");
      expect(result.valid).toBe(true);
      expect(consoleSpy).toHaveBeenCalled();
      consoleSpy.mockRestore();
    });
  });
});

describe("validateBlockResponses", () => {
  test("should return empty error map when all elements are valid", () => {
    const elements: TSurveyElement[] = [
      {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question 1" },
        required: false,
        inputType: "text",
        charLimit: 0,
      } as TSurveyOpenTextElement,
      {
        id: "text2",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question 2" },
        required: false,
        inputType: "text",
        charLimit: 0,
      } as TSurveyOpenTextElement,
    ];

    const responses: TResponseData = {
      text1: "value1",
      text2: "value2",
    };

    const result = validateBlockResponses(elements, responses, "en");
    expect(Object.keys(result)).toHaveLength(0);
  });

  test("should return error map with invalid elements", () => {
    const elements: TSurveyElement[] = [
      {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question 1" },
        required: true,
        inputType: "text",
        charLimit: 0,
      } as TSurveyOpenTextElement,
      {
        id: "text2",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question 2" },
        required: false,
        inputType: "text",
        charLimit: 0,
      } as TSurveyOpenTextElement,
    ];

    const responses: TResponseData = {
      text1: "",
      text2: "value2",
    };

    const result = validateBlockResponses(elements, responses, "en");
    expect(Object.keys(result)).toHaveLength(1);
    const text1Errors = result.text1;
    expect(text1Errors).toBeDefined();
    expect(text1Errors?.length).toBeGreaterThan(0);
  });

  test("should handle missing responses", () => {
    const elements: TSurveyElement[] = [
      {
        id: "text1",
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Question" },
        required: true,
        inputType: "text",
        charLimit: 0,
      } as TSurveyOpenTextElement,
    ];

    const responses: TResponseData = {};

    const result = validateBlockResponses(elements, responses, "en");
    expect(Object.keys(result)).toHaveLength(1);
    expect(result.text1).toBeDefined();
  });
});

describe("getFirstErrorMessage", () => {
  test("should return first error message for element", () => {
    const errorMap = {
      text1: [
        { ruleId: "rule1", ruleType: "minLength" as const, message: "First error" },
        { ruleId: "rule2", ruleType: "maxLength" as const, message: "Second error" },
      ],
    };

    const message = getFirstErrorMessage(errorMap, "text1");
    expect(message).toBe("First error");
  });

  test("should return undefined when element has no errors", () => {
    const errorMap = {
      text1: [{ ruleId: "rule1", ruleType: "minLength" as const, message: "Error" }],
    };

    const message = getFirstErrorMessage(errorMap, "text2");
    expect(message).toBeUndefined();
  });

  test("should return undefined when error map is empty", () => {
    const errorMap = {};
    const message = getFirstErrorMessage(errorMap, "text1");
    expect(message).toBeUndefined();
  });
});
