'use client';

import { ExternalLink } from 'lucide-react';

import { cn } from '@djangocfg/ui-core/lib';

import type { ChatSource } from '../types';

export interface SourcesProps {
  sources: ChatSource[];
  layout?: 'inline' | 'grid';
  maxVisible?: number;
  onClick?: (source: ChatSource) => void;
  className?: string;
}

export function Sources({ sources, layout = 'inline', maxVisible, onClick, className }: SourcesProps) {
  if (!sources?.length) return null;
  const visible = maxVisible ? sources.slice(0, maxVisible) : sources;
  const remaining = maxVisible ? Math.max(0, sources.length - maxVisible) : 0;

  return (
    <div
      className={cn(
        'mt-2 flex flex-wrap gap-1.5',
        layout === 'grid' && 'grid grid-cols-2',
        className,
      )}
    >
      {visible.map((s, i) => {
        const handle = onClick ? () => onClick(s) : undefined;
        const Tag = handle ? 'button' : 'a';
        const props = handle
          ? ({ type: 'button', onClick: handle } as const)
          : ({ href: s.url, target: '_blank', rel: 'noopener noreferrer' } as const);
        return (
          <Tag
            key={`${s.url}-${i}`}
            {...props}
            className="inline-flex max-w-full items-center gap-1 rounded-md border border-border bg-background/60 px-2 py-1 text-xs text-foreground/80 hover:bg-accent hover:text-foreground"
            title={s.snippet ?? s.title}
          >
            <span className="truncate">{s.title || s.url}</span>
            <ExternalLink aria-hidden className="size-3 shrink-0 opacity-60" />
          </Tag>
        );
      })}
      {remaining > 0 ? (
        <span className="inline-flex items-center rounded-md border border-dashed border-border px-2 py-1 text-xs text-muted-foreground">
          +{remaining}
        </span>
      ) : null}
    </div>
  );
}
