"use client";

/**
 * 草稿恢复弹窗组件（ai14）
 *
 * 进入考试页时检测到 IDB 中有未完成草稿时弹出
 * 询问用户是否恢复上次作答
 */

import { useEffect, useRef } from "react";
import { cn } from "@/lib/exam-types";

export interface DraftRecoveryProps {
  /** 是否检测到草稿 */
  hasDraft: boolean;
  /** 恢复草稿回调 */
  onRestore: () => void;
  /** 丢弃草稿回调 */
  onDiscard: () => void;
}

export function DraftRecovery({
  hasDraft,
  onRestore,
  onDiscard,
}: DraftRecoveryProps): JSX.Element | null {
  const restoreRef = useRef<HTMLButtonElement>(null);

  // 弹窗打开时聚焦恢复按钮
  useEffect(() => {
    if (hasDraft && restoreRef.current) {
      restoreRef.current.focus();
    }
  }, [hasDraft]);

  // ESC 键关闭（等同于丢弃）
  useEffect(() => {
    if (!hasDraft) return;
    const onKey = (e: KeyboardEvent): void => {
      if (e.key === "Escape") {
        onDiscard();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [hasDraft, onDiscard]);

  if (!hasDraft) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-labelledby="draft-recovery-title"
    >
      <div
        className={cn(
          "mx-md w-full max-w-md rounded-lg border border-rule bg-paper p-xl shadow-card",
        )}
      >
        <h2 id="draft-recovery-title" className="font-serif text-xl text-ink">
          发现未完成的草稿
        </h2>
        <p className="mt-sm text-sm text-ink-muted">
          系统检测到您上次有未完成的作答记录。是否恢复之前的答案？
        </p>
        <div className="mt-xl flex justify-end gap-sm">
          <button
            type="button"
            onClick={onDiscard}
            className={cn(
              "rounded border border-rule px-lg py-sm text-sm text-ink-muted",
              "hover:bg-paper transition-colors",
            )}
            aria-label="丢弃草稿，重新开始"
          >
            丢弃
          </button>
          <button
            ref={restoreRef}
            type="button"
            onClick={onRestore}
            className={cn(
              "rounded bg-accent px-lg py-sm text-sm text-paper",
              "hover:bg-accent-hover transition-colors",
            )}
            aria-label="恢复上次作答的草稿"
          >
            恢复
          </button>
        </div>
      </div>
    </div>
  );
}
