'use client';

import { type ReactNode } from 'react';

import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

export interface ResponsiveTab {
  id: string;
  label: string;
  content: ReactNode;
  badge?: string | number;
}

interface ResponsiveTabsProps {
  tabs: ResponsiveTab[];
  value: string;
  onValueChange: (value: string) => void;
}

/**
 * Tabs that collapse to a native <Select> on phone-sized viewports.
 * Above sm: TabsList renders. At/below sm: a Select dropdown replaces the tab strip.
 */
export function ResponsiveTabs({ tabs, value, onValueChange }: ResponsiveTabsProps) {
  return (
    <Tabs value={value} onValueChange={onValueChange}>
      {/* Mobile: select dropdown */}
      <div className="sm:hidden">
        <Select value={value} onValueChange={onValueChange}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {tabs.map((tab) => (
              <SelectItem key={tab.id} value={tab.id}>
                <span className="flex items-center gap-1.5">
                  {tab.label}
                  {tab.badge !== undefined && tab.badge !== null && (
                    <span className="text-xs text-muted-foreground">({tab.badge})</span>
                  )}
                </span>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Desktop / tablet: tab strip */}
      <TabsList className="hidden sm:flex">
        {tabs.map((tab) => (
          <TabsTrigger key={tab.id} value={tab.id} className="gap-1.5">
            {tab.label}
            {tab.badge !== undefined && tab.badge !== null && (
              <Badge variant="secondary" className="px-1.5 py-0 text-xs">
                {tab.badge}
              </Badge>
            )}
          </TabsTrigger>
        ))}
      </TabsList>

      {tabs.map((tab) => (
        <TabsContent key={tab.id} value={tab.id} className="mt-4">
          {tab.content}
        </TabsContent>
      ))}
    </Tabs>
  );
}
