import { solarYearPillarVi } from "@/lib/tuvi-solar-year-pillar-vi";

type Props = {
  /** Tiêu đề phụ (vd. Tử Vi Nam Phái) — hiển thị nhỏ dưới tiêu đề chính. */
  chartTitle?: string;
  fullName: string;
  birthYear: number | null;
  birthDateText: string;
  birthYearDetailText?: string | null;
  birthMonthDetailText?: string | null;
  birthDayDetailText?: string | null;
  birthHourText: string;
  genderText?: string | null;
  amDuongText?: string | null;
  /** Tuổi / mốc xem (đã format sẵn từ trang). */
  ageLine?: string | null;
  /** Năm dương đang xem (niên hiện tại). */
  viewingYear?: number | null;
  menhDisplay: string;
  cucDisplay: string;
  thanCuText?: string | null;
  menhChuText?: string | null;
  thanChuText?: string | null;
  /** Dòng phụ: can chi, ngũ hành niên, v.v. */
  tagline?: string | null;
  lunarYearText?: string | null;
  className?: string;
};

function dash(s: string | null | undefined): string {
  const t = (s ?? "").trim();
  return t.length > 0 ? t : "—";
}

function withoutDebugText(s: string | null | undefined): string {
  return (s ?? "")
    .split(/\n+/)
    .map((x) => x.trim())
    .filter(Boolean)
    .filter((x) => !/nam[_\s-]*phai|pdf|ruleset|typescript|engine|majorStarEngineMode/i.test(x))
    .join(" · ");
}

function cleanCucDisplay(s: string | null | undefined): string {
  const raw = s ?? "";
  const rawMatch = /(Kim|Mộc|Moc|Thủy|Thuy|Hỏa|Hoa|Thổ|Tho)\s+[^·,;:\n]*?Cục/i.exec(raw);
  if (rawMatch?.[0]) return dash(rawMatch[0]);

  const text = withoutDebugText(s);
  const match = /(Kim|Mộc|Moc|Thủy|Thuy|Hỏa|Hoa|Thổ|Tho)\s+[^·,;:\n]*?Cục/i.exec(text);
  return dash(match?.[0] ?? "");
}

function cleanMenhDisplay(s: string | null | undefined): string {
  const text = withoutDebugText(s);
  const compact = text.split(/\s+[—–-]\s+|·/)[0]?.trim();
  return dash(compact || text);
}

function datePartsFromBirthText(text: string, birthYear: number | null): { year: string; month: string; day: string } {
  const year = birthYear != null ? String(birthYear) : "—";
  const normalized = text.trim();
  const iso = /(\d{4})-(\d{1,2})-(\d{1,2})/.exec(normalized);
  if (iso) return { year: iso[1], month: iso[2], day: iso[3] };

  const vi = /(\d{1,2})\s+tháng\s+(\d{1,2})/i.exec(normalized);
  if (vi) return { year, month: vi[2], day: vi[1] };

  const slash = /(\d{1,2})[/-](\d{1,2})[/-](\d{2,4})/.exec(normalized);
  if (slash) return { year: slash[3].length === 2 ? `20${slash[3]}` : slash[3], month: slash[2], day: slash[1] };

  return { year, month: "—", day: "—" };
}

type FieldTone = "ink" | "red" | "blue" | "green" | "violet" | "muted";

const VALUE_TONE_CLASS: Readonly<Record<FieldTone, string>> = {
  ink: "text-[#1a2f4d]",
  red: "text-[#7f2a22]",
  blue: "text-[#1a3d5c]",
  green: "text-[#1d5c42]",
  violet: "text-[#4a3a6b]",
  muted: "text-[color:var(--tuvi-chart-ink-muted)]",
};

function CenterField({ label, value, tone = "ink" }: { label: string; value: string; tone?: FieldTone }) {
  return (
    <div className="ctkp-tuvi-center-field center-row">
      <dt className="ctkp-tuvi-center-field__label">{label}</dt>
      <dd className={`ctkp-tuvi-center-field__value m-0 ${VALUE_TONE_CLASS[tone]}`}>{value}</dd>
    </div>
  );
}

function EnsoMark({ className = "" }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 120 120"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden
    >
      <path
        d="M62 22c-26 2-40 28-32 52 6 18 28 28 48 20 22-10 28-36 12-54-10-12-28-18-44-14-8 2-14 8-18 16"
        stroke="#2a2118"
        strokeWidth="3.2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** Canonical chart UI: trung cung — bố cục cổ thư / enso / cột Nho trang trí. */
export function TuViCenterProfile({
  chartTitle = "TỬ VI NAM PHÁI",
  fullName,
  birthYear,
  birthDateText,
  birthYearDetailText,
  birthMonthDetailText,
  birthDayDetailText,
  birthHourText,
  genderText,
  amDuongText,
  ageLine,
  viewingYear,
  menhDisplay,
  cucDisplay,
  thanCuText,
  menhChuText,
  thanChuText,
  tagline,
  lunarYearText,
  className = "",
}: Props) {
  const vYear = viewingYear != null && Number.isFinite(viewingYear) ? viewingYear : null;
  const parts = datePartsFromBirthText(birthDateText, birthYear);
  const cleanMenh = cleanMenhDisplay(menhDisplay);
  const cleanCuc = cleanCucDisplay(cucDisplay);
  const cleanTagline = withoutDebugText(tagline);
  const chartTitleClean = dash(withoutDebugText(chartTitle));
  const amDuong = dash(amDuongText ?? genderText);
  const yearDisplay = dash(birthYearDetailText ?? parts.year);
  const monthDisplay = dash(birthMonthDetailText ?? parts.month);
  const dayDisplay = dash(birthDayDetailText ?? parts.day);
  const thanCuDisplay = dash(thanCuText);
  const namHanDisplay = solarYearPillarVi(vYear);
  const amDuongRich =
    [amDuong, lunarYearText?.trim()].filter((x) => x && x.length > 0).join(" · ") || amDuong;

  const subtitle =
    chartTitleClean && chartTitleClean !== "LÁ SỐ TỬ VI" && !/^lá\s*số\s*tử\s*vi$/i.test(chartTitleClean) ?
      chartTitleClean
    : null;

  const footerBits = cleanTagline
    ? cleanTagline
        .split(/\s*[·•|]\s*|\s*;\s*/)
        .map((x) => x.trim())
        .filter(Boolean)
        .slice(0, 4)
    : [];

  return (
    <div className={["ctkp-tuvi-center-profile relative flex min-w-0 flex-col lg:h-full lg:min-h-0", className].join(" ")}>
      <div className="ctkp-tuvi-center-block ctkp-tuvi-center-block--classic relative z-0 flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-visible rounded-none p-2 shadow-none sm:p-2.5 lg:min-h-0">
        <EnsoMark className="ctkp-tuvi-center-enso pointer-events-none absolute right-[6%] top-1/2 z-[1] w-[min(38%,10rem)] max-w-[180px] -translate-y-1/2 opacity-[0.08] sm:right-[8%]" />

        <div className="ctkp-tuvi-center-shell relative z-[2] min-h-0 min-w-0 flex-1 lg:pr-14">
          <div className="ctkp-tuvi-center-main min-w-0 flex flex-col overflow-x-hidden text-left">
            <header className="ctkp-tuvi-center-head shrink-0 pb-1.5">
              <p className="ctkp-tuvi-center-kicker font-ctkp-serif text-[9px] font-semibold uppercase tracking-[0.22em] text-[#8b3228] sm:text-[10px]">
                CỔ THƯ KỲ TỊCH
              </p>
              <h2 className="ctkp-tuvi-center-sheet-title mt-0.5 font-ctkp-serif text-[1.02rem] font-extrabold leading-tight tracking-[0.06em] text-[#1a6b3c] sm:text-[1.08rem]">
                LÁ SỐ TỬ VI
              </h2>
              {subtitle ?
                <p className="mt-0.5 font-ctkp-serif text-[10px] font-semibold uppercase tracking-[0.14em] text-[color:var(--tuvi-chart-ink-muted)]">
                  {subtitle}
                </p>
              : null}
              {ageLine?.trim() ?
                <p className="mt-0.5 font-ctkp-serif text-[9px] font-medium leading-snug text-[color:var(--tuvi-chart-ink-muted)]">
                  {ageLine.trim()}
                </p>
              : null}
              <div className="ctkp-tuvi-center-divider ctkp-tuvi-center-divider--compact" aria-hidden />
            </header>

            <div className="center-info-grid">
              <section className="center-section ctkp-tuvi-center-section">
                <p className="ctkp-tuvi-center-section__title font-ctkp-serif text-[9px] font-bold uppercase tracking-[0.12em] text-[#4a3828]">
                  Thông tin sinh
                </p>
                <dl className="ctkp-tuvi-center-dl m-0 space-y-0 p-0">
                  <CenterField label="Họ tên" value={fullName.trim() ? fullName : "—"} tone="blue" />
                  <CenterField label="Năm sinh" value={yearDisplay} tone="ink" />
                  <CenterField label="Tháng" value={monthDisplay} tone="ink" />
                  <CenterField label="Ngày sinh" value={dayDisplay} tone="ink" />
                  <CenterField label="Giờ sinh" value={dash(birthHourText)} tone="ink" />
                </dl>
              </section>

              <section className="center-section ctkp-tuvi-center-section">
                <p className="ctkp-tuvi-center-section__title font-ctkp-serif text-[9px] font-bold uppercase tracking-[0.12em] text-[#4a3828]">
                  Luận mệnh
                </p>
                <dl className="ctkp-tuvi-center-dl m-0 space-y-0 p-0">
                  <CenterField label="Năm hạn" value={namHanDisplay} tone="red" />
                  <CenterField label="Âm dương" value={amDuongRich} tone="blue" />
                  <CenterField label="Mệnh" value={cleanMenh} tone="green" />
                  <CenterField label="Cục" value={cleanCuc} tone="green" />
                  <CenterField label="Mệnh chủ" value={dash(menhChuText)} tone="blue" />
                  <CenterField label="Thân chủ" value={dash(thanChuText)} tone="blue" />
                  <CenterField label="Thân cư" value={thanCuDisplay} tone="violet" />
                </dl>
              </section>
            </div>

            {footerBits.length > 0 ?
              <div className="mt-2 shrink-0 pt-1 text-center">
                {footerBits.map((line, i) => (
                  <p
                    key={`${line}-${i}`}
                    className={`font-ctkp-serif text-[10px] font-semibold leading-snug ${
                      i === 0 ? "text-[#7f2a22]" : i === 1 ? "text-[#7f2a22]" : "text-[#1a3d5c]"
                    }`}
                  >
                    {line}
                  </p>
                ))}
              </div>
            : null}
          </div>

          <aside
            className="ctkp-tuvi-center-oracle pointer-events-none absolute right-0 top-1/2 z-[3] hidden -translate-y-1/2 flex-col items-center justify-center gap-2 lg:flex"
            aria-hidden
          >
            <div
              className="ctkp-tuvi-center-oracle-vert select-none text-[1.05rem] font-semibold leading-[1.35] tracking-[0.18em] text-[#7a2820]"
              lang="zh-Hant"
              style={{
                writingMode: "vertical-rl",
                fontFamily: '"Noto Serif CJK SC","Songti SC","SimSun","STSong",serif',
              }}
            >
              古書奇籍
            </div>
            <div className="ctkp-tuvi-center-seal flex h-[44px] w-[44px] shrink-0 items-center justify-center border-2 border-[#9a2a22] bg-[rgba(255,248,240,0.88)] text-center font-serif text-[14px] font-bold leading-none text-[#7a1e18] opacity-[0.88]">
              <span lang="zh-Hant">古籍</span>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}
