import { useEffect, useRef } from 'react';
import { config } from '../../config';
import { useAuthStore } from '../../auth/auth-store';
import 'swagger-ui-dist/swagger-ui.css';

export default function SwaggerPage() {
  const containerRef = useRef<HTMLDivElement>(null);
  const token = useAuthStore((s) => s.accessToken);

  useEffect(() => {
    let cancelled = false;

    import('swagger-ui-dist/swagger-ui-bundle').then((mod) => {
      const SwaggerUIBundle = mod.default || mod;
      if (cancelled || !containerRef.current || typeof SwaggerUIBundle !== 'function') return;
      SwaggerUIBundle({
        url: `${config.apiBaseUrl}/api-docs`,
        domNode: containerRef.current,
        requestInterceptor: (req: { headers: Record<string, string> }) => {
          if (token) {
            req.headers['Authorization'] = `Bearer ${token}`;
          }
          return req;
        },
      });
    });

    return () => { cancelled = true; };
  }, [token]);

  return (
    <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '1rem 1.5rem' }}>
      <h2 style={{ marginBottom: '1rem' }}>API Documentation</h2>
      <div ref={containerRef} />
    </div>
  );
}
