import { createElement } from "react";
import { describe, expect, test } from "vitest";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import {
  Body,
  Head,
  Html,
  Section,
  Tailwind,
  Text,
  render,
  renderAccountDeletedEmail,
  renderAccountDeletionEmail,
  renderAttachmentExportFailedEmail,
  renderAttachmentExportReadyEmail,
  renderEmailCustomizationPreviewEmail,
  renderEmbedSurveyPreviewEmail,
  renderFollowUpEmail,
  renderForgotPasswordEmail,
  renderInviteAcceptedEmail,
  renderInviteEmail,
  renderLinkSurveyEmail,
  renderMemberRetentionNoticeEmail,
  renderNewEmailVerification,
  renderPasswordResetNotifyEmail,
  renderResponseFinishedEmail,
  renderSsoRecoveryFactorsRemovedEmail,
  renderSsoSignInHintEmail,
  renderSurveyRetentionNoticeEmail,
  renderVerificationEmail,
} from "../index";
import { exampleData } from "./example-data";
import { t } from "./mock-translate";

// `elements` is pre-processed by the web app rather than by the template, so the
// preview fixture does not carry it. Keep a minimal stand-in here.
const responseFinishedElements = [
  {
    element: "What did you like most?",
    response: "The customer service was excellent!",
    type: TSurveyElementTypeEnum.OpenText,
  },
];

// Render every email with the legal props supplied. The imprint/privacy footer is a
// conditional branch of the shared chrome, so leaving them out would hide anything that
// only goes wrong once that branch renders.
const legal = exampleData.legalProps;

const renderers: [string, () => Promise<string>][] = [
  [
    "renderVerificationEmail",
    () => renderVerificationEmail({ ...exampleData.verificationEmail, ...legal, t }),
  ],
  [
    "renderForgotPasswordEmail",
    () => renderForgotPasswordEmail({ ...exampleData.forgotPasswordEmail, ...legal, t }),
  ],
  [
    "renderAccountDeletionEmail",
    () => renderAccountDeletionEmail({ ...exampleData.deleteAccountEmail, ...legal, t }),
  ],
  [
    "renderNewEmailVerification",
    () => renderNewEmailVerification({ ...exampleData.newEmailVerification, ...legal, t }),
  ],
  ["renderPasswordResetNotifyEmail", () => renderPasswordResetNotifyEmail({ ...legal, t })],
  ["renderAccountDeletedEmail", () => renderAccountDeletedEmail({ ...legal, t })],
  [
    "renderSsoRecoveryFactorsRemovedEmail",
    () =>
      renderSsoRecoveryFactorsRemovedEmail({
        ...exampleData.ssoRecoveryFactorsRemovedEmail,
        ...legal,
        t,
      }),
  ],
  [
    "renderSsoSignInHintEmail",
    () => renderSsoSignInHintEmail({ ...exampleData.ssoSignInHintEmail, ...legal, t }),
  ],
  [
    "renderSurveyRetentionNoticeEmail",
    () => renderSurveyRetentionNoticeEmail({ ...exampleData.surveyRetentionNoticeEmail, ...legal, t }),
  ],
  [
    "renderAttachmentExportReadyEmail",
    () => renderAttachmentExportReadyEmail({ ...exampleData.attachmentExportReadyEmail, ...legal, t }),
  ],
  [
    "renderAttachmentExportFailedEmail",
    () => renderAttachmentExportFailedEmail({ ...exampleData.attachmentExportFailedEmail, ...legal, t }),
  ],
  [
    "renderMemberRetentionNoticeEmail",
    () => renderMemberRetentionNoticeEmail({ ...exampleData.memberRetentionNoticeEmail, ...legal, t }),
  ],
  ["renderInviteEmail", () => renderInviteEmail({ ...exampleData.inviteEmail, ...legal, t })],
  [
    "renderInviteAcceptedEmail",
    () => renderInviteAcceptedEmail({ ...exampleData.inviteAcceptedEmail, ...legal, t }),
  ],
  [
    "renderLinkSurveyEmail",
    () => renderLinkSurveyEmail({ ...exampleData.linkSurveyEmail, logoUrl: "", ...legal, t }),
  ],
  [
    "renderEmbedSurveyPreviewEmail",
    () => renderEmbedSurveyPreviewEmail({ ...exampleData.embedSurveyPreviewEmail, ...legal, t }),
  ],
  [
    "renderResponseFinishedEmail",
    () =>
      renderResponseFinishedEmail({
        ...exampleData.responseFinishedEmail,
        elements: responseFinishedElements,
        ...legal,
        t,
      }),
  ],
  [
    "renderEmailCustomizationPreviewEmail",
    () =>
      renderEmailCustomizationPreviewEmail({ ...exampleData.emailCustomizationPreviewEmail, ...legal, t }),
  ],
  ["renderFollowUpEmail", () => renderFollowUpEmail({ ...exampleData.followUpEmail, ...legal, t })],
];

describe.each(renderers)("%s", (_name, renderEmail) => {
  test("returns a complete standalone HTML document", async () => {
    const html = await renderEmail();

    expect(html).toMatch(/^<!DOCTYPE html/i);
    expect(html).toContain("</html>");
  });

  test("resolves every translation key instead of leaking raw keys", async () => {
    const html = await renderEmail();

    expect(html).not.toMatch(/\b(?:emails|common)\.[a-z0-9_]+/);
  });

  test("inlines Tailwind utilities as styles rather than shipping class names", async () => {
    const html = await renderEmail();

    // Mail clients ignore stylesheets, so `<Tailwind>` has to inline the utilities.
    // Assert the shape, not the design tokens: `justify-center` on the shared body has
    // no react-email default equivalent, so seeing it inline proves the Tailwind pass
    // ran, and re-tuning the chrome's spacing or sizing cannot churn this test.
    expect(html).toContain("justify-content:center");
    expect(html).not.toMatch(/class="[^"]*\bmax-w-[a-z0-9]/);
  });
});

describe("translation threading", () => {
  test("passes interpolation values through to the rendered copy", async () => {
    const html = await renderForgotPasswordEmail({
      verifyLink: exampleData.forgotPasswordEmail.verifyLink,
      linkValidityInMinutes: 30,
      t,
    });

    expect(html).toContain("The link is valid for 30 minutes.");
  });

  test("interpolates caller data into the notification copy", async () => {
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      responseCount: 15,
      elements: responseFinishedElements,
      t,
    });

    expect(html).toContain(exampleData.responseFinishedEmail.survey.name);
    // The response that triggered the notification is not "more", so the CTA counts 14.
    expect(html).toContain("View 14 more responses");
  });

  test("falls back to the summary CTA when this is the only response", async () => {
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      responseCount: 1,
      elements: responseFinishedElements,
      t,
    });

    expect(html).toContain("View survey summary");
    expect(html).not.toContain("more responses");
  });

  test("points both opt-out links at the account notifications page", async () => {
    const { WEBAPP_URL, survey, organization, workspaceId } = exampleData.responseFinishedEmail;
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      elements: responseFinishedElements,
      t,
    });

    expect(html).toContain(
      `${WEBAPP_URL}/account/settings/notifications?type=alert&amp;elementId=${survey.id}`
    );
    expect(html).toContain(
      `${WEBAPP_URL}/account/settings/notifications?type=unsubscribedOrganizationIds&amp;elementId=${organization.id}`
    );
    expect(html).not.toContain(`/workspaces/${workspaceId}/settings/notifications`);
    expect(html).toContain(`${WEBAPP_URL}/workspaces/${workspaceId}/surveys/${survey.id}/responses`);
  });
});

describe("Signature response", () => {
  const signatureUrl = "/storage/ws1/private/surveys/s1/elements/e1/signature--fid--abc.png";
  const elements = [
    { element: "Please sign", response: signatureUrl, type: TSurveyElementTypeEnum.Signature },
  ];

  test("the response notification names the signature without carrying its link", async () => {
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      elements,
      t,
    });

    expect(html).toContain("Link to the signature is not included for data privacy reasons");
    expect(html).not.toContain("signature--fid--abc");
  });

  test("the follow-up email does not carry the link either", async () => {
    const html = await renderFollowUpEmail({
      ...exampleData.followUpEmail,
      responseData: elements,
      t,
    });

    expect(html).toContain("Link to the signature is not included for data privacy reasons");
    expect(html).not.toContain("signature--fid--abc");
  });
});

describe("survey retention notice", () => {
  const notice = exampleData.surveyRetentionNoticeEmail;

  test("opens by naming only the policy whose list the email carries", async () => {
    const responsesOnly = await renderSurveyRetentionNoticeEmail({
      ...notice,
      archivedSurveys: [],
      ...legal,
      t,
    });
    const surveysOnly = await renderSurveyRetentionNoticeEmail({
      ...notice,
      responseDeletions: [],
      ...legal,
      t,
    });
    const both = await renderSurveyRetentionNoticeEmail({ ...notice, ...legal, t });

    expect(responsesOnly).toContain("Acme automatically deletes responses after a set time. The following");
    expect(responsesOnly).not.toContain("archives surveys");
    expect(surveysOnly).toContain("Acme automatically archives surveys");
    expect(surveysOnly).not.toContain("deletes responses");
    expect(both).toContain("deletes responses after a set time and archives surveys");
  });
});

describe("SSO sign-in hint", () => {
  test("names every provider the account signs in with and links to the login page", async () => {
    const html = await renderSsoSignInHintEmail({
      providerNames: ["Microsoft", "Acme SSO"],
      loginLink: "https://app.formbricks.com/auth/login",
      t,
    });

    expect(html).toContain(">Microsoft<");
    expect(html).toContain(">Acme SSO<");
    expect(html).toContain('href="https://app.formbricks.com/auth/login"');
  });

  test("sends the reader to their administrator, with no login button, when no provider is offered", async () => {
    const html = await renderSsoSignInHintEmail({
      providerNames: [],
      loginLink: "https://app.formbricks.com/auth/login",
      t,
    });

    expect(html).toContain("Contact your administrator to get access again.");
    expect(html).not.toContain("https://app.formbricks.com/auth/login");
    expect(html).not.toContain("You sign in with:");
  });
});

describe("legal footer", () => {
  test("renders imprint and privacy links only when the legal props are supplied", async () => {
    const withLegal = await renderVerificationEmail({
      ...exampleData.verificationEmail,
      ...legal,
      t,
    });
    const withoutLegal = await renderVerificationEmail({ ...exampleData.verificationEmail, t });

    expect(withLegal).toContain(legal.imprintUrl);
    expect(withLegal).toContain(legal.privacyUrl);
    expect(withLegal).toContain(legal.imprintAddress);
    // The links need readable labels, not the translation keys behind them.
    expect(withLegal).toContain(">Imprint<");
    expect(withLegal).toContain(">Privacy Policy<");
    expect(withoutLegal).not.toContain(legal.imprintUrl);
    expect(withoutLegal).not.toContain(legal.privacyUrl);
    expect(withoutLegal).not.toContain(legal.imprintAddress);
  });
});

describe("custom branding", () => {
  test("response-finished notification falls back to the Formbricks logo when no organization logo is set", async () => {
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      elements: responseFinishedElements,
      t,
    });

    expect(html).toContain('data-testid="default-logo-image"');
    expect(html).not.toContain('data-testid="logo-image"');
  });

  test("response-finished notification renders the organization's custom logo when set", async () => {
    const customLogoUrl = "https://example.com/custom-logo.png";
    const html = await renderResponseFinishedEmail({
      ...exampleData.responseFinishedEmail,
      elements: responseFinishedElements,
      logoUrl: customLogoUrl,
      t,
    });

    expect(html).toContain('data-testid="logo-image"');
    expect(html).toContain(customLogoUrl);
    expect(html).not.toContain('data-testid="default-logo-image"');
  });
});

describe("logo centering (ENG-2438)", () => {
  // Outlook's Word rendering engine implements neither `margin: auto` nor `rem` units, so the
  // logo's own `mx-auto` / `w-60` classes buy it nothing there: it lands left-aligned at its
  // natural size. Centering has to come from the wrapping cell's `align` attribute, and the
  // width from the image's `width` attribute, both of which Word does honor. These assert the
  // rendered markup rather than the classes, because the classes were already "correct".
  const logoCell = (html: string, testId: string): string => {
    const cell = new RegExp(
      `<td\\b[^>]*>(?:\\s*<a\\b[^>]*>)?\\s*<img\\b[^>]*data-testid="${testId}"[^>]*>`,
      "u"
    ).exec(html);
    if (!cell) throw new Error(`no <td> directly wrapping [data-testid="${testId}"]`);
    return cell[0];
  };

  test("the default logo sits in a center-aligned cell and carries a pixel width", async () => {
    const html = await renderEmailCustomizationPreviewEmail({
      ...exampleData.emailCustomizationPreviewEmail,
      logoUrl: undefined,
      ...legal,
      t,
    });
    const cell = logoCell(html, "default-logo-image");

    expect(cell).toContain('align="center"');
    expect(cell).toContain('width="240"');
    // The attribute mirrors `w-60`; if the class moves and the constant does not, Outlook
    // silently goes back to rendering the logo at its natural size.
    expect(cell).toContain("width:15rem");
    // The modern-client centering path must survive alongside it.
    expect(cell).toContain("margin-left:auto");
  });

  test("a custom logo sits in a center-aligned cell and carries a pixel width", async () => {
    const html = await renderEmailCustomizationPreviewEmail({
      ...exampleData.emailCustomizationPreviewEmail,
      logoUrl: "https://example.com/custom-logo.png",
      ...legal,
      t,
    });
    const cell = logoCell(html, "logo-image");

    expect(cell).toContain('align="center"');
    expect(cell).toContain('width="320"');
    expect(cell).toContain("width:20rem"); // mirrors `w-80`, see above
    expect(cell).toContain("margin-left:auto");
  });

  test("the centered logo cell is part of the shared chrome, not one email", async () => {
    const html = await renderInviteEmail({ ...exampleData.inviteEmail, ...legal, t });

    expect(logoCell(html, "default-logo-image")).toContain('align="center"');
  });
});

describe("follow-up email direction", () => {
  test("marks the follow-up body and the response/variable/hidden-field text for automatic direction detection", async () => {
    const html = await renderFollowUpEmail({
      ...exampleData.followUpEmail,
      body: "<p>شكرا لملاحظاتك! لقد استلمنا ردك وسنراجعه قريبا.</p>",
      ...legal,
      t,
    });

    // The follow-up body is per-survey authored content in any script, so it gets
    // dir="auto" rather than a hard rtl/ltr — this is the element from the bug report.
    expect(html).toMatch(/<div dir="auto">[\s\S]*?شكرا لملاحظاتك/);
    // Response element labels, variable name/value and hidden-field id/value all carry
    // their own dir="auto" too, since each can hold independently-directioned content.
    expect(html.match(/dir="auto"/g)?.length).toBeGreaterThanOrEqual(6);
  });

  test("keeps an LTR-embedded run (a URL) intact inside RTL variable content", async () => {
    const mixedValue = "شكرا على الرابط https://example.com/survey/123 وملاحظاتك";
    const html = await renderFollowUpEmail({
      ...exampleData.followUpEmail,
      variables: [{ id: "var-1", name: "Link", type: "text", value: mixedValue }],
      ...legal,
      t,
    });

    // dir="auto" lets the mail client's bidi algorithm keep the LTR URL readable; the
    // server must not reorder or otherwise mangle the raw text.
    expect(html).toContain(mixedValue);
  });

  test("marks the open-text response value for automatic direction detection", async () => {
    const html = await renderFollowUpEmail({
      ...exampleData.followUpEmail,
      responseData: [
        {
          element: "ما أكثر ما أعجبك؟",
          response: "كانت خدمة العملاء ممتازة!",
          type: TSurveyElementTypeEnum.OpenText,
        },
      ],
      ...legal,
      t,
    });

    // The value is rendered by renderEmailResponseValue rather than by the template, so a
    // dir="auto" on the label alone would leave the answer under it resolved as LTR.
    expect(html).toMatch(/<p[^>]*dir="auto"[^>]*>كانت خدمة العملاء ممتازة!<\/p>/);
  });

  test("lets the card alignment follow the direction of each element", async () => {
    const html = await renderFollowUpEmail({ ...exampleData.followUpEmail, ...legal, t });

    // dir="auto" only sets `direction`; an inherited `text-align:left` from the card would still
    // pin RTL paragraphs to the left edge. The card uses `text-start`, which resolves per element.
    // Asserting the declaration also proves the email Tailwind engine compiles the utility.
    expect(html).toContain("text-align:start");
    expect(html).not.toContain("text-align:left");
  });

  test("renders LTR follow-ups exactly as before", async () => {
    const html = await renderFollowUpEmail({ ...exampleData.followUpEmail, ...legal, t });

    expect(html).toContain(exampleData.followUpEmail.responseData[0].element);
    expect(html).toContain(exampleData.followUpEmail.variables[0].value);
    expect(html).toContain(exampleData.followUpEmail.hiddenFields[0].value);
  });
});

describe("Tailwind render engine", () => {
  // `react-email`'s own `Tailwind` component — not anything configured in this package — decides
  // which Tailwind version compiles the template classes. Pin that contract: these utilities
  // exist only in v4, so a downgrade would drop the declarations silently.
  test("compiles Tailwind v4 utilities", async () => {
    const html = await render(
      createElement(
        Tailwind,
        null,
        createElement(
          Html,
          null,
          createElement(Head, null),
          createElement(
            Body,
            null,
            createElement(
              Section,
              { className: "inset-shadow-sm shadow-xs" },
              createElement(Text, { className: "text-shadow-lg" }, "v4")
            )
          )
        )
      )
    );

    expect(html).toContain("text-shadow:");
    expect(html).toContain("box-shadow:inset");
  });
});
