import { splitPalaceBranchDisplay, type TuViPalaceView } from "@/lib/tuvi-chart-view-model";

import { TUVI_BOARD_FOCUS_PALACE_KEYS } from "./tuvi-chart-layout";
import { TuViPalaceStarLayers } from "./TuViPalaceStarLayers";

function palaceTooltip(p: TuViPalaceView): string {
  const bits: string[] = [];
  if (p.stageLabel) bits.push(p.stageLabel);
  const first = p.majorStars[0]?.name;
  if (first) bits.push(first);
  const b = splitPalaceBranchDisplay(p.branch);
  return bits.length > 0 ? bits.slice(0, 3).join(" · ") : `${p.name} · ${b.vi}`;
}

export type TuViPalaceCardTier = "menh" | "than" | "focus" | "default";

export function tierForPalaceView(p: TuViPalaceView): TuViPalaceCardTier {
  if (p.key === "menh") return "menh";
  if (p.bodyMarker) return "than";
  if (TUVI_BOARD_FOCUS_PALACE_KEYS.has(p.key)) return "focus";
  return "default";
}

type Props = {
  palace: TuViPalaceView;
  indexOneBased: number;
  selected?: boolean;
  onSelect?: (key: string) => void;
  tier?: TuViPalaceCardTier;
  className?: string;
};

/** Một dòng — trái can / tháng mốc, phải tràng sinh; luôn cùng chiều cao. */
/** Footer một dòng — cỡ chữ 10px */
const FOOTER_H = 18;

export function TuViPalaceCard({
  palace: cell,
  indexOneBased,
  selected = false,
  onSelect,
  tier: tierProp,
  className = "",
}: Props) {
  const tier = tierProp ?? tierForPalaceView(cell);
  const majorCount = cell.majorStars?.length ?? 0;
  const minorCount = cell.minorStars?.length ?? 0;
  const hasAnyStar = majorCount > 0 || minorCount > 0;
  const headingId = `tuvi-palace-${cell.key}-title`;

  const tip = palaceTooltip(cell);
  const selectLabel = `Chọn cung ${cell.name} (${indexOneBased}/12)`;
  const branchParts = splitPalaceBranchDisplay(cell.branch);
  const overlayMarkers = cell.tuanTrietMarkers ?? [];
  const hasTuan = overlayMarkers.includes("tuan");
  const hasTriet = overlayMarkers.includes("triet");
  const stageTrim = (cell.stageLabel ?? "").trim();
  const stemTrim = (cell.stem ?? "").trim();

  const branchShort = (branchParts.vi || "—").trim();
  const palaceTitleUpper = cell.name.trim().toUpperCase();
  const headerRight = cell.ageMark != null ? String(cell.ageMark) : String(indexOneBased);

  return (
    <div
      data-tuvi-palace-key={cell.key}
      data-tuvi-palace-name={cell.name}
      data-tuvi-palace-branch={branchParts.vi}
      data-tuvi-major-count={majorCount}
      data-tuvi-minor-count={minorCount}
      data-tuvi-tier={tier}
      data-tuvi-palace-focus={selected ? "selected" : "quiet"}
      title={tip}
      aria-label={onSelect ? selectLabel : undefined}
      aria-pressed={onSelect ? selected : undefined}
      aria-labelledby={onSelect ? undefined : headingId}
      onClick={() => onSelect?.(cell.key)}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onSelect?.(cell.key);
        }
      }}
      role={onSelect ? "button" : "group"}
      tabIndex={onSelect ? 0 : undefined}
      className={[
        "ctkp-tuvi-palace-surface ctkp-tuvi-palace--print group relative box-border flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden px-1.5 py-[5px] outline-none",
        "text-[color:var(--tuvi-chart-ink)]",
        selected ? "z-[2]" : "",
        "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[#5c4a2a]/55 focus-visible:ring-offset-0",
        className,
      ].join(" ")}
    >
      {hasTuan ?
        <span
          className="pointer-events-none absolute left-0.5 top-0.5 z-[3] max-w-[2.2rem] truncate font-ctkp-serif text-[7.5px] font-semibold leading-none tracking-wide text-[color:var(--tuvi-chart-ink)]"
          aria-hidden
        >
          Tuần
        </span>
      : null}
      {hasTriet ?
        <span
          className="pointer-events-none absolute bottom-[22px] right-0.5 z-[3] max-w-[2.2rem] truncate font-ctkp-serif text-[7.5px] font-semibold leading-none tracking-wide text-[color:var(--tuvi-chart-ink)]"
          aria-hidden
        >
          Triệt
        </span>
      : null}

      <header
        className="ctkp-tuvi-palace-print-header relative z-[1] grid w-full shrink-0 grid-cols-[minmax(0,0.9fr)_minmax(0,1.4fr)_minmax(0,0.7fr)] items-center gap-0.5 border-b border-[color:var(--tuvi-chart-border-soft)] pb-0.5"
        style={{ minHeight: 26 }}
      >
        <p className="min-w-0 truncate text-left font-ctkp-serif text-[12px] font-semibold leading-none text-[color:var(--tuvi-chart-ink)]">
          {branchShort}
        </p>
        <h3
          id={headingId}
          className="min-w-0 truncate text-center font-ctkp-serif text-[12px] font-semibold leading-none tracking-wide text-[color:var(--tuvi-chart-ink)]"
        >
          <span className="inline-block max-w-full truncate align-bottom" title={cell.name}>
            {palaceTitleUpper}
            {cell.bodyMarker ?
              <span className="font-semibold text-[color:var(--tuvi-chart-blue-ink)]"> · THÂN</span>
            : null}
          </span>
        </h3>
        <p
          className="min-w-0 truncate text-right font-ctkp-serif text-[12px] tabular-nums font-semibold leading-none text-[color:var(--tuvi-chart-weak)]"
          aria-label={cell.ageMark != null ? `Tuổi mở đại hạn ${cell.ageMark}` : `Thứ tự ${indexOneBased}`}
        >
          {headerRight}
        </p>
      </header>

      <div className="ctkp-tuvi-palace-body relative z-0 mt-0.5 flex min-h-0 w-full min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-auto pb-0">
        {!hasAnyStar ?
          <div className="flex min-h-0 flex-1 flex-col">
            <div className="shrink-0 px-0.5 text-center font-ctkp-serif text-[15px] font-bold leading-[1.2] text-[color:var(--tuvi-chart-ink-muted)]">
              —
            </div>
            <p className="mt-0.5 text-center font-ctkp-serif text-[12px] leading-[1.25] text-[color:var(--tuvi-chart-ink-muted)]">
              Chưa an sao
            </p>
          </div>
        : (
          <TuViPalaceStarLayers
            majorStars={cell.majorStars}
            minorStars={cell.minorStars}
            palaceBranchVi={branchParts.vi}
          />
        )}
      </div>

      <footer
        className="ctkp-tuvi-palace-print-footer relative z-[1] mt-auto flex w-full shrink-0 items-center justify-between gap-1 border-t border-[color:var(--tuvi-chart-border-soft)] pt-0.5 font-ctkp-serif text-[10px] font-normal leading-none text-[color:var(--tuvi-chart-ink-muted)]"
        style={{ minHeight: FOOTER_H }}
      >
        <span className="min-w-0 flex-1 truncate text-left" title={stemTrim ? "Can (thiên can) ô" : undefined}>
          {stemTrim || "\u00a0"}
        </span>
        <span className="min-w-0 max-w-[55%] truncate text-right" title={stageTrim ? "Tràng sinh" : undefined}>
          {stageTrim || "\u00a0"}
        </span>
      </footer>
    </div>
  );
}
