import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import ErrorBoundary from '@/components/ErrorBoundary';

/**
 * Dedicated fallback for the 3D viewer. Keeps the rest of the app usable when
 * the Canvas / WebGL scene fails to start or a model/texture load throws.
 */
function ViewerFallback({ error, info, retry }) {
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);

  const copy = () => {
    const text = `${error?.stack || String(error || '')}\n\n${info?.componentStack || ''}`;
    navigator.clipboard?.writeText(text).catch(() => {});
  };

  return (
    <div className="viewport-grid relative grid h-full min-h-[420px] place-items-center overflow-hidden rounded-2xl border border-white/[0.07] p-6 text-center">
      <div className="max-w-md">
        <span className="sim-badge mb-3 inline-flex">Viewer error</span>
        <h3 className="font-heading text-lg font-semibold text-white">The 3D workspace could not start.</h3>
        <p className="mt-2 text-sm text-slate-400">
          The rest of the application is still usable. Try restarting the viewer, or return to the dashboard.
        </p>
        <div className="mt-4 flex flex-wrap justify-center gap-2">
          <button onClick={retry} className="btn-primary">Retry Viewer</button>
          <button onClick={() => navigate('/')} className="btn-ghost">Return to Dashboard</button>
        </div>
        <div className="mt-4">
          <button onClick={() => setOpen((v) => !v)} className="text-[11px] text-slate-500 underline-offset-2 hover:text-slate-300 hover:underline">
            {open ? 'Hide technical details' : 'Show technical details'}
          </button>
          {open && import.meta.env?.DEV && (
            <div className="mt-2 text-left">
              <pre className="max-h-40 overflow-auto rounded border border-white/10 bg-black/40 p-2 text-[10px] leading-4 text-red-300">
                {error?.stack || String(error || 'Unknown error')}
              </pre>
              <button onClick={copy} className="tool-button mt-2">Copy Error Details</button>
            </div>
          )}
          {open && !import.meta.env?.DEV && (
            <p className="mt-2 text-[11px] leading-4 text-slate-500">Full technical details are hidden in production. Please contact Base44 support with the steps that triggered this error.</p>
          )}
        </div>
      </div>
    </div>
  );
}

export default function ViewerErrorBoundary({ children }) {
  return (
    <ErrorBoundary label="CoverViewer" fallback={ViewerFallback}>
      {children}
    </ErrorBoundary>
  );
}