'use client'

import React from 'react'
import Link from 'next/link'

type Props = {
  children: React.ReactNode
  fallback?: React.ReactNode
}

type State = {
  hasError: boolean
}

export class ClientErrorBoundary extends React.Component<Props, State> {
  state: State = { hasError: false }

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

  componentDidCatch(error: Error) {
    console.error('ClientErrorBoundary caught error:', error)
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback

      return (
        <section className="container mx-auto px-4 py-12">
          <div className="rounded-2xl border border-border bg-card p-6 text-center shadow-sm">
            <h2 className="mb-2 text-xl font-bold">تعذر تحميل هذا الجزء من الصفحة</h2>
            <p className="mb-4 text-muted-foreground">
              حدث خطأ في أحد مكونات الواجهة. تم عزل الخطأ حتى يستمر الموقع بالعمل.
            </p>
            <div className="flex items-center justify-center gap-3">
              <button
                type="button"
                onClick={() => this.setState({ hasError: false })}
                className="rounded-lg bg-secondary px-4 py-2 font-semibold text-secondary-foreground"
              >
                إعادة المحاولة
              </button>
              <Link
                href="/"
                className="rounded-lg border border-border px-4 py-2 font-semibold"
              >
                العودة للرئيسية
              </Link>
            </div>
          </div>
        </section>
      )
    }

    return this.props.children
  }
}
