"use client";

import * as React from "react";

import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";
import { Typography } from "@/components/ui/typography";
import { LegalDialog } from "./LegalDialog";

const PLACEHOLDER_PATTERN = /(\{terms\}|\{privacy\})/;

interface LegalConsentProps {
  /**
   * Dictionary key of the consent sentence. The sentence must contain
   * `{terms}` / `{privacy}` placeholders — they are replaced with links
   * that open the corresponding LegalDialog. Defaults to the sign-in wording;
   * pass a different key to reuse this elsewhere (e.g. a sign-up form).
   */
  messageKey?: string;
  className?: string;
}

/**
 * "By signing in, you agree to our Terms & Conditions and Privacy Policy."
 * with both documents opening as dialogs. Reusable anywhere in the app:
 *
 *   <LegalConsent />
 *   <LegalConsent messageKey="legal.signupConsent" />
 */
export function LegalConsent({
  messageKey = "legal.consent",
  className,
}: LegalConsentProps) {
  const { t } = useTranslation();
  const parts = t(messageKey).split(PLACEHOLDER_PATTERN);

  return (
    <Typography
      as="p"
      variant="caption"
      color="secondary"
      className={cn("text-center", className)}
    >
      {parts.map((part, index) => {
        if (part === "{terms}") return <LegalDialog key={index} type="terms" />;
        if (part === "{privacy}")
          return <LegalDialog key={index} type="privacy" />;
        return <React.Fragment key={index}>{part}</React.Fragment>;
      })}
    </Typography>
  );
}
