'use client';

/**
 * ComponentEntry - single shared card used by every /design-system section.
 *
 * Renders the component name, path, description, a token-list, a11y notes,
 * a copy-paste import snippet, and a live demo with an RTL/LTR toggle.
 *
 * Tokens-only styling. All strings via the `design_system` namespace.
 */

import { useCallback, useState, type ReactNode } from 'react';
import { cn } from '@/lib/cn';
import { Button } from '@/components/ui/primitives/Button';
import { Pill } from '@/components/ui/primitives/Pill';
import { useT } from '@/lib/i18n/react';

export interface ComponentEntryProps {
  /** Display name, e.g. "Button". */
  name: string;
  /** Anchor id for deep-linking, e.g. "button-primitive". */
  id?: string;
  /** Path under src/, e.g. "src/components/ui/primitives/Button". */
  path: string;
  /** One-sentence description of the component's purpose. */
  description: string;
  /** Token names referenced by the component. */
  tokens: string[];
  /** Accessibility notes - keyboard, ARIA, focus, motion etc. */
  a11yNotes: string[];
  /** Copy-paste import snippet (TypeScript). */
  importSnippet: string;
  /** The live demo content. */
  children: ReactNode;
  /** Optional className on the wrapper. */
  className?: string;
}

/**
 * Renders a single registered component card with full metadata + live demo.
 */
export function ComponentEntry({
  name,
  id,
  path,
  description,
  tokens = [],
  a11yNotes = [],
  importSnippet,
  children,
  className,
}: ComponentEntryProps) {
  const t = useT('design_system');
  const [demoDir, setDemoDir] = useState<'rtl' | 'ltr'>('rtl');
  const [copied, setCopied] = useState(false);
  const previewId = `${id ?? name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-preview`;

  const handleCopy = useCallback(() => {
    if (typeof navigator === 'undefined' || !navigator.clipboard) return;
    void navigator.clipboard.writeText(importSnippet).then(() => {
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1500);
    });
  }, [importSnippet]);

  return (
    <article
      id={id}
      className={cn(
        'bg-surface-base flex flex-col gap-4',
        'border-border-default rounded-xl border',
        'p-5',
        'shadow-[var(--shadow-sm)]',
        className,
      )}
    >
      {/* Header */}
      <header className="flex flex-wrap items-start justify-between gap-3">
        <div className="flex min-w-0 flex-col gap-1">
          <h3 className="text-text-primary text-lg leading-[var(--line-height-tight)] font-bold">
            {name}
          </h3>
          <p
            dir={/[\u0590-\u05FF]/u.test(description) ? 'rtl' : 'ltr'}
            className="text-text-secondary text-sm leading-[var(--line-height-normal)]"
          >
            {description}
          </p>
          <p className="text-text-muted font-mono text-xs">
            <span className="me-1">{t('path_label')}:</span>
            <span dir="ltr" className="inline-block">
              {path}
            </span>
          </p>
        </div>

        {/* Direction toggle */}
        <div
          role="group"
          aria-label="direction"
          className="border-border-default inline-flex shrink-0 overflow-hidden rounded-md border"
        >
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => setDemoDir('rtl')}
            aria-pressed={demoDir === 'rtl'}
            className={cn(
              'rounded-none px-3 py-1 text-xs font-medium',
              demoDir === 'rtl'
                ? 'bg-brand-primary-600 hover:bg-brand-primary-600 text-white'
                : 'text-text-secondary hover:bg-neutral-100',
            )}
          >
            {t('rtl_label')}
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => setDemoDir('ltr')}
            aria-pressed={demoDir === 'ltr'}
            className={cn(
              'rounded-none px-3 py-1 text-xs font-medium',
              demoDir === 'ltr'
                ? 'bg-brand-primary-600 hover:bg-brand-primary-600 text-white'
                : 'text-text-secondary hover:bg-neutral-100',
            )}
          >
            {t('ltr_label')}
          </Button>
        </div>
      </header>

      {/* Live preview */}
      <section
        aria-labelledby={previewId}
        aria-label={t('preview_label')}
        dir={demoDir}
        className={cn(
          'bg-surface-raised rounded-lg',
          'border-border-default border',
          'p-5',
          'overflow-x-auto',
        )}
      >
        <span id={previewId} className="sr-only">
          {t('preview_label')} — {name}
        </span>
        {children}
      </section>

      {/* Metadata grid */}
      <div className="grid gap-4 md:grid-cols-2">
        {/* Tokens */}
        <div className="flex flex-col gap-2">
          <h4 className="text-text-secondary text-xs font-bold tracking-wide uppercase">
            {t('tokens_label')}
          </h4>
          <ul className="flex flex-wrap gap-1">
            {tokens.map((token) => (
              <li key={token}>
                <Pill tone="info" size="sm" className="font-mono" dir="ltr">
                  {token}
                </Pill>
              </li>
            ))}
          </ul>
        </div>

        {/* a11y */}
        <div className="flex flex-col gap-2">
          <h4 className="text-text-secondary text-xs font-bold tracking-wide uppercase">
            {t('a11y_label')}
          </h4>
          <ul className="text-text-secondary flex list-disc flex-col gap-1 ps-5 text-sm">
            {a11yNotes.map((note) => (
              <li key={note}>{note}</li>
            ))}
          </ul>
        </div>
      </div>

      {/* Import snippet */}
      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between">
          <h4 className="text-text-secondary text-xs font-bold tracking-wide uppercase">
            {t('import_label')}
          </h4>
          <Button variant="ghost" size="sm" onClick={handleCopy}>
            {copied ? t('copied') : t('copy_import')}
          </Button>
        </div>
        <pre
          className={cn(
            'bg-neutral-900 text-neutral-50',
            'rounded-md',
            'p-3',
            'overflow-x-auto',
            'font-mono text-xs leading-[var(--line-height-normal)]',
          )}
        >
          <code dir="ltr" className="block">
            {importSnippet}
          </code>
        </pre>
      </div>
    </article>
  );
}
