"use client";

import * as React from "react";

import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Typography } from "@/components/ui/typography";
import {
  LEGAL_CONTENT,
  LEGAL_LAST_UPDATED,
  type LegalDocumentType,
} from "./legal-content";

interface LegalDialogProps {
  type: LegalDocumentType;
  /** Trigger label — defaults to the localized document link label. */
  children?: React.ReactNode;
  triggerClassName?: string;
}

/**
 * Reusable Terms & Conditions / Privacy Policy dialog.
 * Renders an inline link-styled trigger (inherits the surrounding font size)
 * that opens a scrollable modal — usable anywhere in the app:
 *
 *   <LegalDialog type="terms" />
 *   <LegalDialog type="privacy">custom label</LegalDialog>
 */
export function LegalDialog({
  type,
  children,
  triggerClassName,
}: LegalDialogProps) {
  const { t, formatDate, language } = useTranslation();
  const doc = LEGAL_CONTENT[language][type];

  return (
    <Dialog>
      <DialogTrigger
        type="button"
        className={cn(
          "inline cursor-pointer text-primary-blue underline underline-offset-2 hover:opacity-80",
          triggerClassName,
        )}
      >
        {children ?? t(`legal.${type}LinkLabel`)}
      </DialogTrigger>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{doc.title}</DialogTitle>
          <DialogDescription>
            {t("legal.lastUpdated", {
              date: formatDate(new Date(LEGAL_LAST_UPDATED), language, {
                dateStyle: "long",
              }),
            })}
          </DialogDescription>
        </DialogHeader>
        {/* The body owns the scroll now — no local max-h, which would compete
            with the popup's own cap and leave dead space below the text. */}
        <DialogBody className="flex flex-col gap-4 overscroll-contain pe-2">
          {doc.sections.map((section) => (
            <section key={section.heading} className="flex flex-col gap-1">
              <Typography as="h4" variant="body" className="font-medium">
                {section.heading}
              </Typography>
              <Typography as="p" variant="body" color="secondary">
                {section.body}
              </Typography>
            </section>
          ))}
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
}
