import { useState } from 'react';
import { ChevronRight, Copy, Check } from 'lucide-react';
import { Streamdown } from 'streamdown';
import { code } from '@streamdown/code';

interface Props {
  title: string;
  content: string;
}

/** Ensure every newline becomes a visible paragraph break in markdown */
function ensureLineBreaks(text: string): string {
  return text.split('\n').join('\n\n');
}

function formatSize(len: number): string {
  if (len < 1024) return `${len} chars`;
  return `${(len / 1024).toFixed(1)} KB`;
}

export default function BlobyTextCard({ title, content }: Props) {
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleCopy = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch { /* clipboard not available */ }
  };

  return (
    <div className="my-2 rounded-xl border border-border/30 overflow-hidden">
      {/* Header */}
      <div
        onClick={() => setExpanded((v) => !v)}
        className="flex items-center gap-2.5 px-3.5 py-2.5 bg-white/[0.03] hover:bg-white/[0.05] transition-colors cursor-pointer select-none"
      >
        <ChevronRight
          className={`h-3.5 w-3.5 text-muted-foreground/50 shrink-0 transition-transform duration-200 ${expanded ? 'rotate-90' : ''}`}
        />
        <span className="text-[13px] font-medium text-foreground/80 truncate min-w-0">
          {title}
        </span>
        <div className="flex items-center gap-2 ml-auto shrink-0">
          <span className="text-[11px] text-muted-foreground/35 tabular-nums">
            {formatSize(content.length)}
          </span>
          <button
            onClick={handleCopy}
            className="p-1 rounded-md hover:bg-white/[0.08] text-muted-foreground/40 hover:text-muted-foreground/70 transition-colors"
            title="Copy text"
          >
            {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
          </button>
        </div>
      </div>

      {/* Collapsible content */}
      {expanded && (
        <div
          className="border-t border-border/15 max-h-[500px] overflow-y-auto px-4 py-3 text-sm leading-relaxed prose prose-sm prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
        >
          <Streamdown
            mode="static"
            plugins={{ code }}
            controls={{ code: { copy: true, download: false } }}
            shikiTheme={['github-dark', 'github-dark']}
            lineNumbers={false}
          >
            {ensureLineBreaks(content)}
          </Streamdown>
        </div>
      )}
    </div>
  );
}
