import type { ReactNode, Ref } from "react";
import { cx } from "../../utils";

/** `FoxAlert`와 같은 다섯 계열이다 — 시안이 두 컴포넌트에 같은 축을 쓴다. */
export type FoxHelperTextType =
  | "default"
  | "information"
  | "success"
  | "warning"
  | "danger";

export interface FoxHelperTextProps {
  /** 글자색과 아이콘이 여기서 갈린다. */
  type?: FoxHelperTextType;
  /** 보여 줄 문구. */
  message: ReactNode;
  /**
   * 아이콘을 그릴지. 시안은 다섯 계열 모두 아이콘을 달지만, 글자만 필요한 자리가 있어
   * 끌 수 있게 둔다 — 폼 컴포넌트의 헬퍼가 지금 아이콘 없이 쓰이는 자리가 많다
   * (`FoxInput.messageIcon`이 선택값인 것과 같은 사정).
   */
  showIcon?: boolean;
  /** 참이면 렌더하지 않는다(DOM에 남지 않는다). */
  hidden?: boolean;
  /**
   * 입력의 `aria-describedby`가 가리킬 값. 폼 옆에 놓을 때 넘겨서 이어 준다 —
   * 이어 주지 않으면 화면에만 보이고 소리로는 전달되지 않는다.
   */
  id?: string;
  /** 배치 조정용. 모양이 달라야 하면 여기 말고 `type`을 쓴다. */
  className?: string;
  ref?: Ref<HTMLParagraphElement>;
}

/** `Record`로 고정해 계열을 추가하면 항목 누락이 타입 에러가 되게 한다. */
const TYPE_CLASS: Record<FoxHelperTextType, string> = {
  default: "fox-helper-text--default",
  information: "fox-helper-text--information",
  success: "fox-helper-text--success",
  warning: "fox-helper-text--warning",
  danger: "fox-helper-text--danger",
};

/**
 * 계열이 정하는 아이콘. 글리프는 `FoxAlert`와 같은 것을 쓰고 **굵기만 다르다** —
 * 알럿은 `duotone`, 여기는 `regular`다(시안 확인).
 */
const TYPE_ICON: Record<FoxHelperTextType, ReactNode> = {
  default: <i className="fox-ico fox-ico-ChatDots" aria-hidden="true" />,
  information: <i className="fox-ico fox-ico-Info" aria-hidden="true" />,
  success: <i className="fox-ico fox-ico-CheckCircle" aria-hidden="true" />,
  warning: <i className="fox-ico fox-ico-Warning" aria-hidden="true" />,
  danger: <i className="fox-ico fox-ico-Prohibit" aria-hidden="true" />,
};

/**
 * @fox 헬퍼 텍스트. 입력 아래 한 줄로 붙는 안내·오류 문구다.
 *
 * 상태를 갖지 않는다 — 어떤 계열로 보일지는 호출부가 정한다.
 *
 * TODO(폼 통합, 적용 후 이 문단 삭제): 폼 컴포넌트 여섯 곳(`FoxInput`·`FoxTextArea`·
 * `FoxEmail`·`FoxPhoneNumber`·`FoxAddress`의 `__message`, `FoxSelect`의 `__hint`)이
 * 아직 각자 그린다. 이걸로 모으는 절차와 주의점은 `@fox/styles/_fox-helper-text.scss`
 * 상단에 적어 두었다 — `FoxSelect`만 간격과 오류 아이콘 색이 달라지므로 확인이 필요하다.
 *
 * 상호작용이 없어 `"use client"`가 아니다 — 서버 컴포넌트로 렌더된다.
 *
 * ⚠️ 스타일은 이 파일이 import하지 않는다 — 호스트 앱이 `@use "@fox/styles/components"`
 * (또는 개별 파티셜)로 한 번 불러와야 한다.
 */
export function FoxHelperText({
  type = "default",
  message,
  showIcon = true,
  hidden = false,
  id,
  className,
  ref,
}: FoxHelperTextProps) {
  if (hidden) {
    return null;
  }

  return (
    <p
      ref={ref}
      id={id}
      className={cx("fox-helper-text", TYPE_CLASS[type], className)}
    >
      {showIcon ? (
        <span className="fox-helper-text__icon" aria-hidden="true">
          {TYPE_ICON[type]}
        </span>
      ) : null}
      <span className="fox-helper-text__message">{message}</span>
    </p>
  );
}
