# Next.js

To integrate Preo Widget with Next.js, you'll need to add the Preo JavaScript SDK and configure your application to handle web components properly.

## App Router (Next.js 13+)

For Next.js applications using the App Router, create a client component wrapper:

1. Create a new file `app/components/PreoWidget.tsx`:

```typescript
'use client';

import { useEffect } from 'react';

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'preo-storefront': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & {
        'sdk-id': string;
      }, HTMLElement>;
    }
  }
}

export default function PreoWidget({ sdkId }: { sdkId: string }) {
  useEffect(() => {
    // Load the Preo SDK script
    const script = document.createElement('script');
    script.src = 'https://edge.preo.cloud/c/components@0.6/components.umd.js';
    script.async = true;
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return <preo-storefront sdk-id={sdkId}></preo-storefront>;
}
```

2. Use the component in your pages:

```jsx
import PreoWidget from '@/components/PreoWidget';

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to our store</h1>
      <PreoWidget sdkId="your-sdk-id-here" />
    </div>
  );
}
```

## Pages Router (Legacy)

For Next.js applications using the Pages Router:

1. Add the Preo SDK script to your `_document.tsx` or `_document.js`:

```jsx
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html>
      <Head>
        <script
          src="https://edge.preo.cloud/c/components@0.6/components.umd.js"
          async
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
```

2. Create a component wrapper to handle the web component:

```jsx
import { useEffect, useRef } from 'react';

export default function PreoWidget({ sdkId }) {
  const containerRef = useRef(null);

  useEffect(() => {
    // Ensure the web component is defined before rendering
    if (typeof window !== 'undefined' && containerRef.current) {
      containerRef.current.innerHTML = `<preo-storefront sdk-id="${sdkId}"></preo-storefront>`;
    }
  }, [sdkId]);

  return <div ref={containerRef} />;
}
```

## Dynamic Import (Alternative)

For better performance and code splitting, you can dynamically import the Preo SDK:

```jsx
import dynamic from 'next/dynamic';

const PreoWidget = dynamic(() => import('./PreoWidget'), {
  ssr: false,
  loading: () => <p>Loading storefront...</p>
});

export default function Page() {
  return <PreoWidget sdkId="your-sdk-id-here" />;
}
```

With these configurations, you can now use the Preo widget throughout your Next.js application.
