'use client'

import React, { useState } from 'react'
import { cn } from '@/lib/utils'

/**
 * Tabs Components for MDX Documentation
 * 
 * Mintlify-compatible tab components for organizing content.
 */

interface TabProps {
  title: string
  children: React.ReactNode
  className?: string
}

interface TabsProps {
  children: React.ReactNode
  defaultValue?: string
  className?: string
}

// Context for sharing tab state
interface TabsContextValue {
  activeTab: string
  setActiveTab: (tab: string) => void
}

const TabsContext = React.createContext<TabsContextValue | null>(null)

export function Tab({ children, className }: TabProps) {
  // Tab content is rendered by Tabs parent
  return <div className={className}>{children}</div>
}

export function Tabs({ children, defaultValue, className }: TabsProps) {
  // Extract tab titles and content from children
  const tabs: { title: string; content: React.ReactNode }[] = []
  
  React.Children.forEach(children, (child) => {
    if (React.isValidElement<TabProps>(child) && child.type === Tab) {
      tabs.push({
        title: child.props.title,
        content: child.props.children,
      })
    }
  })
  
  const [activeTab, setActiveTab] = useState(defaultValue || tabs[0]?.title || '')
  
  const activeContent = tabs.find(tab => tab.title === activeTab)?.content
  
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div className={cn('my-4', className)}>
        {/* Tab headers */}
        <div className="flex border-b border-border overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.title}
              type="button"
              onClick={() => setActiveTab(tab.title)}
              className={cn(
                'px-4 py-2 text-sm font-medium whitespace-nowrap transition-colors',
                'hover:text-foreground',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50',
                'border-b-2 -mb-px',
                activeTab === tab.title
                  ? 'border-primary text-foreground'
                  : 'border-transparent text-muted-foreground'
              )}
            >
              {tab.title}
            </button>
          ))}
        </div>
        
        {/* Tab content */}
        <div className="pt-4">
          {activeContent}
        </div>
      </div>
    </TabsContext.Provider>
  )
}
