/**
 * M11 版本 diff 预览组件
 *
 * 在 version-history-drawer 中弹出，对比选中版本与当前文档的差异。
 * 调用 lib/document-diff.ts 的纯函数计算 diff，渲染为彩色段落。
 */
"use client";

import { useMemo } from "react";
import { useTranslations } from "next-intl";
import { X } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import {
  computeDocumentDiff,
  summarizeDiff,
} from "../lib/document-diff";
import type { LessonPlanDocument } from "../types";
import type { LessonPlanVersion } from "../types";

interface Props {
  open: boolean;
  onClose: () => void;
  selectedVersion: LessonPlanVersion | null;
  currentDoc: LessonPlanDocument;
}

export function VersionDiffViewer({
  open,
  onClose,
  selectedVersion,
  currentDoc,
}: Props) {
  const t = useTranslations("lessonPreparation");

  const diffSegments = useMemo(() => {
    if (!selectedVersion) return [];
    const versionContent = selectedVersion.content as unknown as LessonPlanDocument;
    return computeDocumentDiff(versionContent, currentDoc);
  }, [selectedVersion, currentDoc]);

  const summary = useMemo(() => summarizeDiff(diffSegments), [diffSegments]);

  if (!open || !selectedVersion) return null;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("version.diff.title", { versionNo: selectedVersion.versionNo })}
        className="bg-surface rounded-lg shadow-xl w-[900px] max-h-[85vh] flex flex-col"
      >
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b border-outline-variant">
            <div>
              <h3 className="font-title-md">
                {t("version.diff.title", { versionNo: selectedVersion.versionNo })}
              </h3>
              <p className="text-xs text-on-surface-variant mt-1">
                {t("version.diff.summary", {
                  added: summary.added,
                  removed: summary.removed,
                  unchanged: summary.unchanged,
                })}
              </p>
            </div>
            <Button variant="ghost" size="sm" onClick={onClose} aria-label={t("action.close")}>
              <X className="w-4 h-4" aria-hidden="true" />
            </Button>
          </div>
          <div className="flex-1 overflow-y-auto p-4 font-mono text-sm">
            {diffSegments.length === 0 ? (
              <p className="text-on-surface-variant text-center py-8">
                {t("version.diff.noChanges")}
              </p>
            ) : (
              <pre className="whitespace-pre-wrap">
                {diffSegments.map((seg, idx) => {
                  const prefix = seg.type === "added" ? "+ " : seg.type === "removed" ? "- " : "  ";
                  const colorClass =
                    seg.type === "added"
                      ? "bg-success-container/30 text-success"
                      : seg.type === "removed"
                        ? "bg-error-container/30 text-error"
                        : "text-on-surface-variant";
                  return (
                    <div key={idx} className={`px-2 py-0.5 ${colorClass}`}>
                      {prefix}
                      {seg.content}
                    </div>
                  );
                })}
              </pre>
            )}
          </div>
          <div className="p-4 border-t border-outline-variant flex justify-end gap-2">
            <Button variant="outline" size="sm" onClick={onClose}>
              {t("action.close")}
            </Button>
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}
