import * as React from 'react';
import { cn } from '../../lib/utils';

/**
 * Tiny no-dep Tabs primitive. Doesn't need Radix for our use case —
 * just tracks the active tab via state and re-renders the matching
 * panel. ARIA roles are set so screen readers parse it as tabs.
 */

interface TabsContextValue {
  value: string;
  setValue: (v: string) => void;
}
const TabsContext = React.createContext<TabsContextValue | null>(null);

export function Tabs({
  defaultValue,
  value: valueProp,
  onValueChange,
  className,
  children,
}: {
  defaultValue?: string;
  value?: string;
  onValueChange?: (v: string) => void;
  className?: string;
  children: React.ReactNode;
}): React.JSX.Element {
  const [internal, setInternal] = React.useState(defaultValue ?? '');
  const value = valueProp ?? internal;
  const setValue = React.useCallback(
    (v: string) => {
      if (valueProp === undefined) setInternal(v);
      onValueChange?.(v);
    },
    [valueProp, onValueChange],
  );
  return (
    <TabsContext.Provider value={{ value, setValue }}>
      <div className={cn('flex flex-col gap-3', className)}>{children}</div>
    </TabsContext.Provider>
  );
}

export function TabsList({ className, children }: { className?: string; children: React.ReactNode }): React.JSX.Element {
  return (
    <div
      role="tablist"
      className={cn(
        'inline-flex h-9 items-center justify-start gap-1 rounded-md border border-(--color-border) bg-(--color-surface) p-1',
        className,
      )}
    >
      {children}
    </div>
  );
}

export function TabsTrigger({ value, className, children }: { value: string; className?: string; children: React.ReactNode }): React.JSX.Element {
  const ctx = React.useContext(TabsContext);
  if (!ctx) throw new Error('TabsTrigger must be used within Tabs');
  const active = ctx.value === value;
  return (
    <button
      role="tab"
      aria-selected={active}
      onClick={() => ctx.setValue(value)}
      className={cn(
        'inline-flex h-7 items-center justify-center rounded px-3 text-sm font-medium transition-colors',
        active
          ? 'bg-(--color-canvas) text-(--color-fg) shadow-sm'
          : 'text-(--color-fg-muted) hover:text-(--color-fg)',
        className,
      )}
    >
      {children}
    </button>
  );
}

export function TabsContent({ value, className, children }: { value: string; className?: string; children: React.ReactNode }): React.JSX.Element | null {
  const ctx = React.useContext(TabsContext);
  if (!ctx) throw new Error('TabsContent must be used within Tabs');
  if (ctx.value !== value) return null;
  return (
    <div role="tabpanel" className={cn('focus-visible:outline-none', className)}>
      {children}
    </div>
  );
}
