"use client"

/**
 * 教材模块内联 Error Boundary。
 *
 * 用于包裹独立数据区块（章节树、内容区、知识点区、图谱区），
 * 隔离故障域，避免单点错误导致整个阅读器白屏。
 */

import { Component, type ReactNode } from "react"
import { AlertCircle } from "lucide-react"
import { Button } from "@/shared/components/ui/button"

interface TextbookSectionErrorBoundaryProps {
  children: ReactNode
  /** 自定义降级 UI 标题 */
  fallbackTitle?: string
  /** 自定义降级 UI 描述 */
  fallbackDescription?: string
  /** 重试按钮文案 */
  retryLabel?: string
}

interface TextbookSectionErrorBoundaryState {
  hasError: boolean
}

export class TextbookSectionErrorBoundary extends Component<
  TextbookSectionErrorBoundaryProps,
  TextbookSectionErrorBoundaryState
> {
  constructor(props: TextbookSectionErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(): TextbookSectionErrorBoundaryState {
    return { hasError: true }
  }

  handleReset = (): void => {
    this.setState({ hasError: false })
  }

  render(): ReactNode {
    if (this.state.hasError) {
      // 默认值为空字符串，强制调用方传入 i18n 文案
      const title = this.props.fallbackTitle ?? ""
      const description = this.props.fallbackDescription ?? ""
      const retryLabel = this.props.retryLabel ?? ""
      return (
        // 任意值 min-h-[200px]：错误降级 UI 最小高度，保证视觉占位
        <div className="flex h-full min-h-[200px] flex-col items-center justify-center gap-3 p-6 text-center">
          <AlertCircle className="h-8 w-8 text-muted-foreground" />
          {title && (
            <p className="text-sm font-medium text-foreground">{title}</p>
          )}
          {description && (
            <p className="text-xs text-muted-foreground">{description}</p>
          )}
          {retryLabel && (
            <Button size="sm" variant="outline" onClick={this.handleReset}>
              {retryLabel}
            </Button>
          )}
        </div>
      )
    }

    return this.props.children
  }
}
