'use client';
import { useEffect, useState } from 'react';

/**
 * Khởi động MSW browser worker trong development.
 * Block render cho đến khi worker ready để tránh race condition
 * (requests gửi trước khi MSW sẵn sàng sẽ bị passthrough → "Failed to fetch").
 */
const MSWProvider = ({ children }: { children: React.ReactNode }) => {
  // Production: render ngay (NODE_ENV !== 'development' → ready = true)
  // Development: chờ worker.start() xong rồi mới render
  const [ready, setReady] = useState(process.env.NODE_ENV !== 'development');

  useEffect(() => {
    if (process.env.NODE_ENV !== 'development') return;
    import('@/mocks/browser')
      .then(({ worker }) =>
        worker.start({
          onUnhandledRequest: 'bypass',
          quiet: true,
        }),
      )
      .then(() => setReady(true))
      .catch((err) => {
        console.error('[MSW] Failed to start worker:', err);
        setReady(true); // vẫn render dù worker fail
      });
  }, []);

  if (!ready) return null;
  return <>{children}</>;
};

export default MSWProvider;
