import type { Horoscope } from "@/lib/tuvi/horoscope";
import { cn } from "@/lib/utils";

/**
 * Horoscope panel — shows decadal / yearly / age-han / monthly summary
 * plus Vietnamese traditional hạn (Tam Tai / Kim Lâu / Hoàng Ốc / fixed).
 *
 * Pure server component (no state). Consumer should pass a precomputed
 * Horoscope from `buildHoroscope(input, forDate)`.
 */
export function HoroscopePanel({ horo }: { horo: Horoscope }) {
  return (
    <section className="border-stroke-subtle bg-bg-elevated/40 mx-auto mt-10 max-w-5xl rounded-2xl border p-5 lg:p-7">
      <header className="mb-5 flex flex-wrap items-baseline justify-between gap-2">
        <h2 className="font-display text-ink-primary text-xl font-semibold lg:text-2xl">
          Đại vận · Lưu niên · Hạn truyền thống
        </h2>
        <p className="text-ink-muted text-xs">
          Tính cho ngày <span className="text-ink-secondary font-medium">{horo.forDate}</span> ·
          Tuổi mụ <span className="text-ink-secondary font-medium">{horo.age}</span> · Cầm tinh{" "}
          <span className="text-ink-secondary font-medium">{horo.birthBranch}</span>
        </p>
      </header>

      {/* Period quick cards */}
      <div className="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <PeriodCard label="Đại Hạn" period={horo.decadal} accent="gold" />
        <PeriodCard label="Lưu Niên" period={horo.yearly} accent="emerald" />
        <PeriodCard label="Tiểu Hạn" period={horo.ageHan} accent="sky" />
        <PeriodCard label="Lưu Nguyệt" period={horo.monthly} accent="rose" />
      </div>

      {/* Decadal timeline */}
      <div className="mb-7">
        <h3 className="text-ink-secondary mb-3 text-sm font-semibold tracking-wide uppercase">
          Bảng đại vận trọn đời
        </h3>
        <div className="border-stroke-subtle/60 overflow-hidden rounded-lg border">
          <div className="grid grid-cols-2 gap-px bg-stone-800/60 sm:grid-cols-3 lg:grid-cols-4">
            {horo.decadalTimeline.map((e) => (
              <div
                key={`${e.ageFrom}-${e.earthlyBranch}`}
                className={cn(
                  "flex flex-col gap-0.5 px-3 py-2.5 text-xs",
                  e.isCurrent
                    ? "bg-brand-gold/15 ring-brand-gold/40 ring-1 ring-inset"
                    : "bg-bg-base/60"
                )}
              >
                <div className="flex items-center justify-between">
                  <span
                    className={cn(
                      "font-display text-sm font-semibold",
                      e.isCurrent ? "text-brand-gold" : "text-ink-primary"
                    )}
                  >
                    {e.ageFrom}–{e.ageTo}
                  </span>
                  <span className="text-ink-muted">
                    {e.heavenlyStem} {e.earthlyBranch}
                  </span>
                </div>
                <span className={cn(e.isCurrent ? "text-ink-primary" : "text-ink-secondary")}>
                  {e.palaceName}
                </span>
              </div>
            ))}
          </div>
        </div>
        <p className="text-ink-muted mt-2 text-xs">
          Cell tô vàng = đại vận hiện tại. Mỗi đại vận trải dài 10 năm tuổi mụ.
        </p>
      </div>

      {/* Vietnamese traditional hạn */}
      <div>
        <h3 className="text-ink-secondary mb-3 text-sm font-semibold tracking-wide uppercase">
          Hạn truyền thống năm{" "}
          <span className="text-ink-primary">
            {horo.yearly.heavenlyStem} {horo.yearly.earthlyBranch}
          </span>
        </h3>
        <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
          <HanCard
            title="Tam Tai"
            tone={
              horo.hanVn.tamTai.active
                ? horo.hanVn.tamTai.position === 2
                  ? "danger"
                  : "warn"
                : "calm"
            }
            heading={horo.hanVn.tamTai.active ? horo.hanVn.tamTai.label : "Không phạm"}
            body={
              horo.hanVn.tamTai.active
                ? `Năm ${horo.yearly.earthlyBranch} thuộc dải Tam Tai của tuổi ${horo.birthBranch}. Vị trí: ${horo.hanVn.tamTai.position}/3.`
                : `Tuổi ${horo.birthBranch} năm nay không nằm trong dải Tam Tai.`
            }
          />
          <HanCard
            title="Kim Lâu"
            tone={horo.hanVn.kimLau.active ? "danger" : "calm"}
            heading={horo.hanVn.kimLau.active ? horo.hanVn.kimLau.label : "Không phạm"}
            body={
              horo.hanVn.kimLau.active
                ? `Tuổi ${horo.age} (mụ) phạm Kim Lâu ${horo.hanVn.kimLau.kind}. Tránh dựng vợ gả chồng, cất nhà mới trong năm.`
                : `Tuổi ${horo.age} (mụ) không phạm chu kỳ Kim Lâu (mod 9 ∉ {1,3,6,8}).`
            }
          />
          <HanCard
            title="Hoàng Ốc"
            tone={horo.hanVn.hoangOc.good ? "calm" : "warn"}
            heading={horo.hanVn.hoangOc.label}
            body={
              horo.hanVn.hoangOc.good
                ? `Cát — tuổi này thuận cho việc xây cất sửa chữa nhà cửa.`
                : `Hung — kiêng động thổ cất nóc trong năm; nếu bắt buộc nên mượn tuổi.`
            }
          />
          {horo.hanVn.fixed.map((f) => (
            <HanCard
              key={f.name}
              title={f.name}
              tone={f.active ? (f.name === "Thái Tuế" ? "warn" : "danger") : "calm"}
              heading={f.active ? `Phạm — ${f.branch}` : `An — ${f.branch}`}
              body={
                f.active
                  ? f.name === "Thái Tuế"
                    ? "Trùng Thái Tuế — năm tuổi, dễ động chuyện thị phi, sức khoẻ giảm sút. Lễ giải sao đầu năm."
                    : f.name === "Tang Môn"
                      ? "Tang Môn chiếu — đề phòng đại tang, ốm đau gia đạo. Hạn chế đi viếng."
                      : "Tuế Phá xung Thái Tuế — kỵ khởi sự lớn (cưới hỏi, mua nhà), dễ đổ vỡ."
                  : `Không phạm — chi sinh không trùng vị trí ${f.name} năm nay.`
              }
            />
          ))}
        </div>
      </div>

      <p className="text-ink-muted mt-5 text-[11px] leading-relaxed">
        ⚠ Hạn truyền thống là tham khảo dân gian. Đại vận / Lưu niên dựa trên Tử Vi Đẩu Số (iztro
        engine). Khi quyết định việc lớn (cưới hỏi, mua nhà, khai trương) nên kết hợp luận giải lá
        số + ngày giờ riêng.
      </p>
    </section>
  );
}

function PeriodCard({
  label,
  period,
  accent,
}: {
  label: string;
  period: { heavenlyStem: string; earthlyBranch: string; mutagen: string[] };
  accent: "gold" | "emerald" | "sky" | "rose";
}) {
  const ring = {
    gold: "ring-brand-gold/40",
    emerald: "ring-emerald-500/40",
    sky: "ring-sky-500/40",
    rose: "ring-rose-500/40",
  }[accent];
  const accentText = {
    gold: "text-brand-gold",
    emerald: "text-emerald-300",
    sky: "text-sky-300",
    rose: "text-rose-300",
  }[accent];

  return (
    <div className={cn("bg-bg-base/60 rounded-lg p-3 ring-1 ring-inset", ring)}>
      <div className="text-ink-muted mb-1 text-[10px] font-semibold tracking-[0.18em] uppercase">
        {label}
      </div>
      <div className={cn("font-display text-base font-semibold", accentText)}>
        {period.heavenlyStem} {period.earthlyBranch}
      </div>
      <div className="text-ink-secondary mt-1 text-[11px] leading-snug">
        Tứ hóa: <span className="text-emerald-300">L</span>·{period.mutagen[0] || "—"} ·{" "}
        <span className="text-sky-300">Q</span>·{period.mutagen[1] || "—"}
      </div>
      <div className="text-ink-secondary text-[11px] leading-snug">
        <span className="text-amber-300">K</span>·{period.mutagen[2] || "—"} ·{" "}
        <span className="text-rose-300">Kỵ</span>·{period.mutagen[3] || "—"}
      </div>
    </div>
  );
}

function HanCard({
  title,
  heading,
  body,
  tone,
}: {
  title: string;
  heading: string;
  body: string;
  tone: "calm" | "warn" | "danger";
}) {
  const styles = {
    calm: "border-emerald-500/30 bg-emerald-500/5",
    warn: "border-amber-500/40 bg-amber-500/5",
    danger: "border-rose-500/40 bg-rose-500/5",
  }[tone];
  const headTone = {
    calm: "text-emerald-300",
    warn: "text-amber-300",
    danger: "text-rose-300",
  }[tone];

  return (
    <div className={cn("rounded-lg border p-3", styles)}>
      <div className="text-ink-muted mb-1 text-[10px] font-semibold tracking-[0.18em] uppercase">
        {title}
      </div>
      <div className={cn("text-sm font-semibold", headTone)}>{heading}</div>
      <p className="text-ink-secondary mt-1.5 text-xs leading-relaxed">{body}</p>
    </div>
  );
}
