import type { TuViStarView } from "@/lib/tuvi-chart-view-model";
import {
  normalizeStarLabelForUi,
  splitPalaceStarsForRender,
} from "@/lib/tuvi-palace-star-buckets";
import { resolveTuViStarKey, sortStarsForDisplay, tuViStarPolarityUi } from "@/lib/tuvi-star-classification";
import type { StarTone } from "@/lib/tuvi-star-classification";

const STAR_STATUS_BY_BRANCH: Readonly<Record<string, Readonly<Record<string, string>>>> = {
  suu: { thai_duong: "Đ", thai_am: "Đ" },
  thin: { tu_vi: "V", thien_tuong: "V" },
  mao: { thien_co: "M", cu_mon: "M" },
};

const WEALTH_LIKE_KEYS = new Set([
  "loc_ton",
  "hoa_loc",
  "hoa_quyen",
  "hoa_khoa",
  "thien_quy",
  "thien_khoi",
  "thien_viet",
  "thai_phu",
  "thien_quan",
  "thien_phuc",
  "thien_duc",
  "an_quang",
  "duong_phu",
  "quoc_an",
  "tam_thai",
  "phong_cao",
  "thien_tho",
  "dao_hoa",
  "hong_loan",
  "thien_hy",
  "thien_y",
  "luu_loc_ton",
  "luu_hoa_loc",
]);

const HARMFUL_KEYS = new Set([
  "that_sat",
  "pha_quan",
  "liem_trinh",
  "tham_lang",
  "cu_mon",
  "kinh_duong",
  "da_la",
  "hoa_tinh",
  "linh_tinh",
  "dia_khong",
  "dia_kiep",
  "kiep_sat",
  "tue_pha",
  "tang_mon",
  "bach_ho",
  "pha_toai",
  "thien_khoc",
  "thien_khong",
  "dia_vong",
  "luu_ha",
  "luu_kinh_duong",
  "luu_da_la",
  "luu_phuc_binh",
  "luu_thien_khoc",
  "luu_thien_hu",
  "luu_hoa_ky",
  "luu_tang_mon",
  "luu_bach_ho",
  "thien_thuong",
  "thien_su",
  "hoa_ky",
]);

function normalizeBranchKey(branchVi?: string): string {
  return (branchVi ?? "")
    .trim()
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/đ/g, "d")
    .replace(/\s+/g, "_");
}

function statusForStar(starKey: string, palaceBranchVi?: string): string | undefined {
  const k = resolveTuViStarKey(starKey) ?? starKey;
  return STAR_STATUS_BY_BRANCH[normalizeBranchKey(palaceBranchVi)]?.[k];
}

function tuHoaShortVi(t: NonNullable<TuViStarView["tuHoa"]>): string {
  switch (t) {
    case "hoa_loc":
      return "Lộc";
    case "hoa_quyen":
      return "Quyền";
    case "hoa_khoa":
      return "Khoa";
    case "hoa_ky":
      return "Kỵ";
    default:
      return "";
  }
}

type LineTone = "red" | "green" | "amber" | "ink";

function lineToneForStar(starKey: string, tone: StarTone, status?: string): LineTone {
  const k = resolveTuViStarKey(starKey) ?? starKey;
  if (status === "H" || (k === "thai_duong" && status === "Đ")) return "red";
  if (HARMFUL_KEYS.has(k)) return "red";
  if (status === "M" || status === "V") return "green";
  if (WEALTH_LIKE_KEYS.has(k)) return "amber";
  const p = tuViStarPolarityUi(k);
  if (p === "bad") return "red";
  if (p === "good") return "green";
  if (tone === "good") return "green";
  if (tone === "bad") return "red";
  return "ink";
}

const LINE_TONE: Readonly<Record<LineTone, string>> = {
  red: "text-[color:var(--tuvi-chart-vermilion)]",
  green: "text-[color:var(--tuvi-chart-good)]",
  amber: "text-[color:var(--tuvi-chart-orange)]",
  ink: "text-[color:var(--tuvi-chart-ink)]",
};

function mainStarTone(starKey: string): LineTone {
  const k = resolveTuViStarKey(starKey) ?? starKey;
  const p = tuViStarPolarityUi(k);
  if (p === "bad") return "red";
  if (p === "good") return "green";
  return "ink";
}

function cungStarLineLabel(star: TuViStarView, palaceBranchVi?: string): string {
  const name = normalizeStarLabelForUi(star);
  const k = resolveTuViStarKey(star.key) ?? star.key;
  const st = statusForStar(k, palaceBranchVi);
  return st ? `${name} (${st})` : name;
}

function starTitle(star: TuViStarView, palaceBranchVi?: string): string {
  const n = cungStarLineLabel(star, palaceBranchVi);
  const m = star.meaningShort?.trim();
  if (m) return `${n} — ${m}`;
  if (star.tuHoa) return `${n} — ${tuHoaShortVi(star.tuHoa)}`;
  return n;
}

type LayerProps = {
  majorStars: TuViStarView[];
  minorStars: TuViStarView[];
  palaceBranchVi: string;
};

/**
 * Hiển thị đầy đủ chính tinh (`majorStars` / mainStars) — mỗi sao một dòng.
 * Phụ / lưu / tứ hóa rời: hai cột; không lặp lại sao đã hiển thị ở chính tinh.
 */
export function TuViPalaceStarLayers({ majorStars, minorStars, palaceBranchVi }: LayerProps) {
  const { mainStars, minorPhu, luuStars, tuHoaStars } = splitPalaceStarsForRender(majorStars, minorStars);
  /** Chỉ phụ + lưu + tứ hóa độc lập — toàn bộ chính tinh nằm trong khối main-stars */
  const rest = sortStarsForDisplay([...minorPhu, ...luuStars, ...tuHoaStars]);

  const leftCol: TuViStarView[] = [];
  const rightCol: TuViStarView[] = [];
  rest.forEach((s, i) => {
    if (i % 2 === 0) leftCol.push(s);
    else rightCol.push(s);
  });

  const maxRows = Math.max(leftCol.length, rightCol.length);
  const rows: { left?: TuViStarView; right?: TuViStarView }[] = [];
  for (let i = 0; i < maxRows; i++) {
    rows.push({ left: leftCol[i], right: rightCol[i] });
  }

  return (
    <div
      className="ctkp-tuvi-palace-print-stars flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
      data-tuvi-layers="print"
    >
      <div className="ctkp-tuvi-palace-main-stars font-ctkp-serif" aria-label="Sao chính tinh">
        {mainStars.length === 0 ?
          <p className="text-center font-ctkp-serif text-[12px] font-medium leading-snug text-[color:var(--tuvi-chart-ink-muted)]">
            Không có chính tinh
          </p>
        : mainStars.map((star) => (
            <div
              key={star.key}
              className="ctkp-tuvi-palace-main-star-row"
              title={starTitle(star, palaceBranchVi)}
              data-tuvi-star-key={star.key}
            >
              <span className={LINE_TONE[mainStarTone(star.key)]}>{cungStarLineLabel(star, palaceBranchVi)}</span>
              {star.tuHoa ?
                <span className="text-[color:var(--tuvi-chart-orange)]"> · {tuHoaShortVi(star.tuHoa)}</span>
              : null}
            </div>
          ))
        }
      </div>

      {maxRows > 0 ?
        <div
          className="ctkp-tuvi-palace-secondary-rows mt-0.5 grid min-h-0 w-full flex-1 grid-cols-2 content-start gap-x-1.5 gap-y-0.5 font-ctkp-serif text-[12px] leading-[1.25] tracking-tight"
          aria-label="Sao phụ"
        >
          {rows.flatMap((row, i) => [
            <div key={`l-${i}`} className="min-w-0 text-left">
              {row.left ?
                <span
                  className={`block min-w-0 truncate whitespace-nowrap ${LINE_TONE[lineToneForStar(row.left.key, row.left.tone, statusForStar(row.left.key, palaceBranchVi))]}`}
                  title={starTitle(row.left, palaceBranchVi)}
                  data-tuvi-star-key={row.left.key}
                >
                  {cungStarLineLabel(row.left, palaceBranchVi)}
                  {row.left.tuHoa ?
                    <span className="text-[color:var(--tuvi-chart-orange)]"> · {tuHoaShortVi(row.left.tuHoa)}</span>
                  : null}
                </span>
              : null}
            </div>,
            <div key={`r-${i}`} className="min-w-0 text-right">
              {row.right ?
                <span
                  className={`block min-w-0 truncate whitespace-nowrap ${LINE_TONE[lineToneForStar(row.right.key, row.right.tone, statusForStar(row.right.key, palaceBranchVi))]}`}
                  title={starTitle(row.right, palaceBranchVi)}
                  data-tuvi-star-key={row.right.key}
                >
                  {cungStarLineLabel(row.right, palaceBranchVi)}
                  {row.right.tuHoa ?
                    <span className="text-[color:var(--tuvi-chart-orange)]"> · {tuHoaShortVi(row.right.tuHoa)}</span>
                  : null}
                </span>
              : null}
            </div>,
          ])}
        </div>
      : null}
    </div>
  );
}
