import { type ReactNode, type CSSProperties, type MouseEvent } from 'react';
import { useTrk } from './TrkContext';

/**
 * 쇼케이스 추적 ID 시스템
 * 각 쇼케이스 항목에 고유 ID를 부여하여:
 * 1. 호버 시 툴팁으로 ID 노출
 * 2. "ID 복사 모드"에서 클릭 시 클립보드 복사
 * 3. URL hash 딥링크 (#trk=TRK-BADGE-critical-sm) 지원
 */
interface TrkProps {
  id: string;
  children: ReactNode;
  className?: string;
  style?: CSSProperties;
  /** 인라인 요소로 렌더할지 여부 (기본: block) */
  inline?: boolean;
}

export function Trk({ id, children, className = '', style, inline = false }: TrkProps) {
  const { copyMode, activeId } = useTrk();
  const isActive = activeId === id;

  const handleClick = async (e: MouseEvent) => {
    if (!copyMode) return;
    e.preventDefault();
    e.stopPropagation();
    try {
      await navigator.clipboard.writeText(id);
      const el = e.currentTarget as HTMLElement;
      el.dataset.copied = 'true';
      setTimeout(() => delete el.dataset.copied, 800);
    } catch {
      // clipboard API 미지원 시 무시
    }
  };

  const Wrapper = inline ? 'span' : 'div';

  return (
    <Wrapper
      data-trk={id}
      className={`trk-item ${isActive ? 'trk-active' : ''} ${copyMode ? 'trk-copyable' : ''} ${className}`}
      style={style}
      title={id}
      onClick={handleClick}
    >
      {children}
    </Wrapper>
  );
}

export function TrkSectionHeader({
  id,
  title,
  description,
}: {
  id: string;
  title: string;
  description?: string;
}) {
  return (
    <div data-trk={id} className="mb-4">
      <div className="flex items-baseline gap-2">
        <h2 className="text-xl font-bold text-heading">{title}</h2>
        <code className="text-[10px] text-hint font-mono">{id}</code>
      </div>
      {description && <p className="text-xs text-hint mt-1">{description}</p>}
    </div>
  );
}
