/**
 * 局部 ErrorBoundary
 *
 * 用于工作台/卡片/对话等子区域，发生渲染错误时只降级当前块，
 * 不会让整个页面白屏。错误仍然上报到 error_logs。
 */

import { ReactNode } from "react";
import { ErrorBoundary } from "./ErrorBoundary";
import { Button } from "@/components/ui/button";
import { AlertTriangle, RefreshCcw } from "lucide-react";

interface Props {
  children: ReactNode;
  /** 错误上下文标签，便于在 error_logs 中定位 */
  scope: string;
  /** 自定义错误标题，默认 "此区域加载失败" */
  title?: string;
  /** 容器额外类名 */
  className?: string;
}

export function SectionErrorBoundary({ children, scope, title = "此区域加载失败", className }: Props) {
  return (
    <ErrorBoundary
      scope={scope}
      fallback={(err, reset) => (
        <div
          className={
            "rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm " +
            (className ?? "")
          }
          role="alert"
        >
          <div className="flex items-start gap-3">
            <AlertTriangle className="h-5 w-5 text-destructive shrink-0 mt-0.5" />
            <div className="flex-1 min-w-0">
              <p className="font-medium text-foreground">{title}</p>
              <p className="text-muted-foreground mt-1 break-words">
                {err.message || "未知错误，已自动记录"}
              </p>
            </div>
            <Button size="sm" variant="outline" onClick={reset} className="shrink-0">
              <RefreshCcw className="h-3.5 w-3.5 mr-1" />
              重试
            </Button>
          </div>
        </div>
      )}
    >
      {children}
    </ErrorBoundary>
  );
}
