import { Col, DangerNote, Note, Properties, Row, WarningNote } from '../../../components/mdx'
import { Tag } from '../../../components/Tag'
import { TimelineContainer } from '../../../components/TimelineContainer'
import { TimelineHeader } from '../../../components/TimelineHeader'
import { TimelineBody } from '../../../components/TimelineBody'
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '../../../components/ui/card'
import { UpBubbleIcon } from '../../../components/icons/UpBubbleIcon'
import { ThumbUpIcon } from '../../../components/icons/ThumbUpIcon'
import { EmailBubbleIcon } from '../../../components/icons/EmailBubbleIcon'
import { BentoCoinIcon } from '../../../components/icons/BentoCoinIcon'
import { SectionTitle } from '../../../components/SectionTitle'
import ClipboardButton from '../../../components/ui/ClipboardButton'
import { Code } from '../../../components/Code'
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"
import { Collapsable } from '../../../components/MDXCollapsible'
import CodeSample from '../../../components/CodeSample'
import { ArrowIcon } from '../../../components/icons/ArrowIcon'
import Link from 'next/link'
import { GuideLinkCards } from '../../../components/GuideLinks'

export const exampleFile = 'nextjs-guide-examples'
export const metadata = {
  title: 'NextJs SDK Guide',
  description:
    "Today, we'll explore integrating the NextJs SDK from Bento.",
}

# Bento NextJs Guide

This guide will help you implement Bento into your NextJs applications, regardless of your development experience.


<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
  <GuideLinkCards
    icon={UpBubbleIcon}
    title="Getting Started"
    links={[
      { label: 'Installation', href: '#installation' },
      { label: 'Basic Setup', href: '#basic-setup' },
    ]}
  />

  <GuideLinkCards
    icon={ThumbUpIcon}
    title="Beginner Guide"
    links={[
      { label: 'Page View Tracking', href: '#page-view-tracking' },
      { label: 'User Identification', href: '#user-identification' },
      { label: 'Event Tracking', href: '#event-tracking' },
    ]}
  />

  <GuideLinkCards
    icon={EmailBubbleIcon}
    title="Intermediate Guide"
    links={[
      { label: 'Server-Side Integration', href: '#server-side-integration' },
      { label: 'Advanced Configuration', href: '#advanced-configuration' },
      { label: 'TypeScript Support', href: '#typescript-support' },
    ]}
  />

  <GuideLinkCards
    icon={BentoCoinIcon}
    title="Advanced Guide"
    links={[
      { label: 'Custom Events', href: '#custom-events' },
      { label: 'Best Practices', href: '#best-practices' },
    ]}
  />
</div>

### Reference
<div className={'flex flex-col gap-y-1 mb-8'}>
  <div><span className={'text-xl text-violet-500'}>#</span> [API Reference](#api-reference)</div>
  <div><span className={'text-xl text-violet-500'}>#</span> [Troubleshooting](#troubleshooting)</div>
  <div><span className={'text-xl text-violet-500'}>#</span> [FAQ](#faq)</div>
</div>

<SectionTitle title={'Getting Started'}/>

<div className={'ml-4'}>
  <TimelineContainer>
    <TimelineHeader title={'Package Installation'} number={'1'}/>
    <TimelineBody>
      ## Installation

      Install the Bento Next.js SDK in your project:

      <CodeSample exampleFile={exampleFile} exampleKey="install_npm"  />

      For server-side integration capabilities, also install:

      <CodeSample exampleFile={exampleFile} exampleKey="install_node"  />
    </TimelineBody>

    <TimelineHeader title={'Environment Configuration'} number={'2'}/>
    <TimelineBody>
      ## Basic Setup

      Add your Bento credentials to your environment variables:

      <CodeSample exampleFile={exampleFile} exampleKey="basic_setup"  />

      You can find your keys in your [Bento Team Settings](https://app.bentonow.com/account/teams). Click
      `Your Private API Keys` and generate a key set if needed.
    </TimelineBody>

    <TimelineHeader title={'Client Setup'} number={'3'}/>
    <TimelineBody>
      Configure the analytics component in your app layout:

      **For Next.js 13+ (App Router):**

      <CodeSample exampleFile={exampleFile} exampleKey="client_setup"  />

      **For Next.js 12 (Pages Router):**

      <CodeSample exampleFile={exampleFile} exampleKey="client_pages_router_setup"  />
</TimelineBody>
</TimelineContainer>
</div>

<SectionTitle title={'Beginner Guide'}/>

## Page View Tracking

Page views are automatically tracked when you include the Bento analytics components. The SDK handles route changes and sends view events to Bento.

### How It Works

The SDK uses Next.js routing hooks to detect navigation:
- **App Router (13+)**: Uses `usePathname()` to detect route changes
- **Pages Router (12)**: Uses `router.events` to listen for navigation

### Manual Implementation

If you need more control over page view tracking:

**App Router:**

<CodeSample exampleFile={exampleFile} exampleKey="simple_page_view_app"  />

**Pages Router:**
<CodeSample exampleFile={exampleFile} exampleKey="simple_page_view_pages"  />

## User Identification

Identify users to connect their actions across sessions and devices:

### Dynamic User Identification

<CodeSample exampleFile={exampleFile} exampleKey="dynamic_user_identification"  />

### Manual Identification

<CodeSample exampleFile={exampleFile} exampleKey="manual_user_identification"  />

## Event Tracking

Track custom events to understand user behavior and trigger workflows:

### Basic Event Tracking

<CodeSample exampleFile={exampleFile} exampleKey="basic_event_tracking"  />

### React Hook for Event Tracking

<CodeSample exampleFile={exampleFile} exampleKey="react_hook_for_event_tracking"  />

<CodeSample exampleFile={exampleFile} exampleKey="react_hook_for_event_tracking_usage"  />

<SectionTitle title={'Intermediate Guide'}/>

## Server-Side Integration

For server-side event tracking and subscriber management, use the Node SDK:

### Server-Side Configuration

<CodeSample exampleFile={exampleFile} exampleKey="server_side_configuration"  />

### API Route Examples

<CodeSample exampleFile={exampleFile} exampleKey="api_route_examples_app_router"  />

<CodeSample exampleFile={exampleFile} exampleKey="api_route_examples_pages_router"  />

## Advanced Configuration

### Custom Script Loading

For more control over when and how the Bento script loads:

<CodeSample exampleFile={exampleFile} exampleKey="custom_script_loading"  />

### Conditional Loading

Load Bento only in production or for specific user segments:

<CodeSample exampleFile={exampleFile} exampleKey="conditional_loading_for_segments"  />

<CodeSample exampleFile={exampleFile} exampleKey="conditional_loading_for_production"  />

## TypeScript Support

The SDK includes full TypeScript support with proper type definitions:

### Type Definitions

<CodeSample exampleFile={exampleFile} exampleKey="type_definitions"  />

### Typed Event Tracking

<CodeSample exampleFile={exampleFile} exampleKey="typed_event_tracking"  />

<CodeSample exampleFile={exampleFile} exampleKey="typed_event_tracking_usage"  />

<SectionTitle title={'Advanced Guide'}/>

## Custom Events

### E-commerce Events

<CodeSample exampleFile={exampleFile} exampleKey="ecommerce_events"  />


### User Lifecycle Events

<CodeSample exampleFile={exampleFile} exampleKey="user_progression_events"  />

<CodeSample exampleFile={exampleFile} exampleKey="user_feature_events"  />


## Best Practices

### Performance Optimization

1. **Lazy Load Analytics**: Only load Bento when needed
2. **Batch Events**: Group related events when possible
3. **Debounce Tracking**: Prevent spam from rapid user actions

<CodeSample exampleFile={exampleFile} exampleKey="debounced_tracking"  />

### Error Handling

<CodeSample exampleFile={exampleFile} exampleKey="error_handling"  />


<SectionTitle title={'API Reference'}/>

### Client-Side Methods

| Method                            | Description        | Example                                         |
|-----------------------------------|--------------------|-------------------------------------------------|
| `window.bento.view()`             | Track page view    | `window.bento.view()`                           |
| `window.bento.identify(email)`    | Identify user      | `window.bento.identify('user@example.com')`     |
| `window.bento.track(event, data)` | Track custom event | `window.bento.track('signup', { plan: 'pro' })` |
| `window.bento.tag(tag)`           | Add tag to user    | `window.bento.tag('premium_user')`              |

### Components

| Component              | Props                                  | Description            |
|------------------------|----------------------------------------|------------------------|
| `BentoAnalytics`       | `siteUuid: string, userEmail?: string` | App Router analytics   |
| `BentoLegacyAnalytics` | `siteUuid: string, userEmail?: string` | Pages Router analytics |

### Hooks

| Hook                      | Parameters           | Returns | Description                |
|---------------------------|----------------------|---------|----------------------------|
| `useBentoAnalytics`       | `userEmail?: string` | `void`  | App Router page tracking   |
| `useBentoLegacyAnalytics` | `userEmail?: string` | `void`  | Pages Router page tracking |

<SectionTitle title={'Troubleshooting'}/>

#### Common Issues

| Issue                    | Solution                                                           |
|--------------------------|--------------------------------------------------------------------|
| **Script not loading**   | Check `NEXT_PUBLIC_BENTO_SITE_ID` is set and accessible in browser |
| **Events not tracking**  | Ensure `window.bento` exists before calling methods                |
| **TypeScript errors**    | Import types from `@bentonow/bento-nextjs-sdk/types`               |
| **Hydration mismatches** | Use `dynamic` imports with `ssr: false` for client-only components |

#### Debugging

<CodeSample exampleFile={exampleFile} exampleKey="debugging"  />

<SectionTitle title={'FAQ'}/>

<Accordion type="single" collapsible>
  <AccordionItem value="item-1">
    <AccordionTrigger>Can I use this with App Router and Pages Router simultaneously?</AccordionTrigger>
    <AccordionContent>
      No, choose the appropriate component for your routing system. Use `BentoAnalytics` for App Router (Next.js 13+) and `BentoLegacyAnalytics` for Pages Router (Next.js 12).
    </AccordionContent>
  </AccordionItem>

  <AccordionItem value="item-2">
    <AccordionTrigger>How do I handle user logout?</AccordionTrigger>
    <AccordionContent>
      When users log out, pass an empty string to the `userEmail` prop or call `window.bento.identify('')` to clear the user identification.
    </AccordionContent>
  </AccordionItem>

  <AccordionItem value="item-3">
    <AccordionTrigger>Is the SDK compatible with React Strict Mode?</AccordionTrigger>
    <AccordionContent>
      Yes, the SDK is designed to work with React Strict Mode. Event handlers are properly debounced to prevent duplicate tracking during development.
    </AccordionContent>
  </AccordionItem>

  <AccordionItem value="item-4">
    <AccordionTrigger>Can I customize the script loading strategy?</AccordionTrigger>
    <AccordionContent>
      Yes, you can use the underlying Next.js `Script` component with different strategies. The default `afterInteractive` works for most cases, but you can use `lazyOnload` for better performance or `beforeInteractive` for critical tracking.
    </AccordionContent>
  </AccordionItem>

  <AccordionItem value="item-5">
    <AccordionTrigger>How do I track events from server components?</AccordionTrigger>
    <AccordionContent>
      Server components can't directly call client-side tracking methods. Instead, use server actions with the Node SDK or pass data to client components that handle the tracking.

      <CodeSample exampleFile={exampleFile} exampleKey="server_component"  />

      <CodeSample exampleFile={exampleFile} exampleKey="client_component"  />
  </AccordionContent>
</AccordionItem>
</Accordion>