"use client";

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

export type FoxTableCellAlign = "start" | "center" | "end";

export interface FoxTableCellProps {
  children?: ReactNode;
  /** 참이면 `<th>`가 된다. 머리행 안에서는 주지 않아도 행이 채운다. */
  head?: boolean;
  align?: FoxTableCellAlign;
  colSpan?: number;
  rowSpan?: number;
  /** 열 너비. `<col>` 없이 한 칸만 잡을 때 쓴다. */
  width?: string | number;
  /**
   * 모바일에서 칸 앞에 붙는 열 이름. `list` 표가 카드로 접히면 머리행이 사라져서,
   * 이 값이 없으면 무슨 값인지 알 수 없다.
   */
  label?: string;
  /** 참이면 렌더하지 않는다(DOM에 남지 않는다). */
  hidden?: boolean;
  /** 배치 조정용. */
  className?: string;

  /** FoxTableRow가 채운다 — 머리행인지. 직접 넘기지 않는다. */
  inHead?: boolean;
}

const ALIGN_CLASS: Record<FoxTableCellAlign, string> = {
  start: "fox-table-cell--start",
  center: "fox-table-cell--center",
  end: "fox-table-cell--end",
};

/**
 * @fox 표의 칸. 머리칸이면 `<th>`, 아니면 `<td>`다.
 *
 * 본문 행에 놓인 머리칸은 그 줄의 이름이라 `scope="row"`가 붙는다 — 시안 basic 표의 첫
 * 열이 그렇다. 머리행 안이면 열 이름이라 `scope="col"`이다.
 *
 * ⚠️ 스타일은 이 파일이 import하지 않는다 — 호스트 앱이 `@use "@fox/styles/components"`
 * (또는 개별 파티셜)로 한 번 불러와야 한다.
 */
export function FoxTableCell({
  children,
  head,
  align,
  colSpan,
  rowSpan,
  width,
  label,
  hidden = false,
  className,
  inHead = false,
}: FoxTableCellProps) {
  if (hidden) {
    return null;
  }

  const isHead = head ?? inHead;
  const Tag = isHead ? "th" : "td";

  return (
    <Tag
      className={cx(
        "fox-table-cell",
        isHead ? "fox-table-cell--head" : "fox-table-cell--body",
        align && ALIGN_CLASS[align],
        className
      )}
      scope={isHead ? (inHead ? "col" : "row") : undefined}
      colSpan={colSpan}
      rowSpan={rowSpan}
      style={width === undefined ? undefined : { inlineSize: width }}
    >
      {/* 카드로 접혔을 때만 보인다 — 표로 있을 때는 머리행이 이미 같은 말을 한다. */}
      {label && <span className="fox-table-cell__label">{label}</span>}
      <span className="fox-table-cell__content">{children}</span>
    </Tag>
  );
}
