import type { FortuneTone, TieuVanSectionView } from "@/lib/tuvi-fortune-view-model";

const FOCUS_ORDER = ["career", "wealth", "relationship", "health"] as const;

type FocusKey = (typeof FOCUS_ORDER)[number];

const SHORT_TITLE_VI: Record<FocusKey, string> = {
  career: "Công việc",
  wealth: "Tài lộc",
  relationship: "Tình cảm",
  health: "Sức khỏe",
};

const PLACEHOLDER_SUMMARY_VI: Record<FocusKey, string> = {
  career:
    "Khối tiểu vận chuyên sâu cho Quan lộc sẽ được làm đầy khi có thêm dữ liệu niên. Tạm thời đối chiếu ô Quan lộc ở tab Luận cung.",
  wealth:
    "Tài lộc niên cần neo ô Tài bạch và sao lưu — nội dung đang dùng tầng tổng quan từ lá đã ghi; không để trống mục.",
  relationship:
    "Nhân duyên trong năm gợi mở từ lá và các ô Phu thê / Nô bộc; xem tab Luận cung để bám cung cụ thể.",
  health:
    "Sức khỏe trong tiểu vận nên đối chiếu ô Tật ách; đây là khung tham khảo, không thay cho khám chữa.",
};

function toneLabelVi(tone: FortuneTone): string {
  if (tone === "good") return "Thuận";
  if (tone === "caution") return "Thận trọng";
  return "Ổn định";
}

function oneLineHeadlineSummary(view: TieuVanSectionView): string {
  const single = view.overview.replace(/\s+/g, " ").trim();
  if (single.length > 0) return single.length > 220 ? `${single.slice(0, 217)}…` : single;
  const h = view.headline.replace(/\s+/g, " ").trim();
  if (h.length > 0) return h.length > 220 ? `${h.slice(0, 217)}…` : h;
  return `Niên ${view.year} — mở tab Luận cung và Lá số để bám cung chi tiết theo năm xem.`;
}

function tonePillClass(tone: FortuneTone): string {
  if (tone === "good") return "bg-emerald-950/55 text-emerald-100/95 ring-emerald-600/35";
  if (tone === "caution") return "bg-rose-950/50 text-rose-100/92 ring-rose-600/35";
  return "bg-amber-950/45 text-amber-50/95 ring-amber-600/32";
}

function toneStripeClass(tone: FortuneTone): string {
  if (tone === "good") return "bg-emerald-500/75";
  if (tone === "caution") return "bg-rose-500/70";
  return "bg-[#c9a15d]/85";
}

function normalizeFocusCards(view: TieuVanSectionView): {
  key: FocusKey;
  title: string;
  tone: FortuneTone;
  content: string;
}[] {
  return FOCUS_ORDER.map((key) => {
    const found = view.focusCards.find((c) => c.key === key);
    const raw = (found?.content ?? "").replace(/\s+/g, " ").trim();
    const content = raw.length > 0 ? raw : PLACEHOLDER_SUMMARY_VI[key];
    const clipped = content.length > 320 ? `${content.slice(0, 317)}…` : content;
    return {
      key,
      title: SHORT_TITLE_VI[key],
      tone: found?.tone ?? "mixed",
      content: clipped,
    };
  });
}

function normalizeAdviceLines(raw: string[]): string[] {
  const lines = raw.map((s) => s.trim()).filter(Boolean);
  if (lines.length > 0) return lines;
  return [
    "Ưu tiên một số việc quan trọng mỗi quý; tránh dàn trải khi chưa có thêm lớp tiểu vận chi tiết.",
    "Đối chiếu Đại vận hiện tại để hiểu bối cảnh mười năm, rồi mới kết luận việc lớn trong năm.",
    "Xem ô liên quan trên Lá số (Quan lộc, Tài bạch, Phu thê, Tật ách) để củng cố từng mục bên trên.",
  ];
}

type Props = {
  view: TieuVanSectionView;
  onGoLaSo?: () => void;
};

export function TuViTieuVanPanel({ view, onGoLaSo }: Props) {
  const summaryLine = oneLineHeadlineSummary(view);
  const cards = normalizeFocusCards(view);
  const adviceLines = normalizeAdviceLines(view.advice);

  return (
    <section
      className="relative overflow-hidden rounded-2xl border border-[var(--ctkp-border-gold-strong)] bg-[linear-gradient(165deg,rgba(14,18,32,0.96),rgba(5,7,14,0.99))] shadow-[inset_0_1px_0_rgba(212,175,55,0.1),0_24px_48px_rgba(0,0,0,0.42)]"
      aria-label="Tiểu vận — bảng xem năm"
    >
      <div
        className="pointer-events-none absolute inset-0 opacity-[0.06]"
        style={{
          backgroundImage:
            "radial-gradient(ellipse 70% 45% at 18% -10%, rgba(201,161,93,0.85), transparent 50%)",
        }}
        aria-hidden
      />

      {/* Dashboard header */}
      <div className="relative border-b border-[#d4af37]/12 px-5 py-5 sm:px-7 sm:py-6">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
          <div className="min-w-0">
            <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.32em] text-[#d4af37]/72">
              Tiểu vận · một năm một vòng
            </p>
            <div className="mt-2 flex flex-wrap items-baseline gap-3">
              <span className="font-ctkp-serif text-5xl font-medium tabular-nums tracking-tight text-[#f5ead8] sm:text-6xl">
                {view.year}
              </span>
              <span className="hidden font-ctkp-serif text-sm text-slate-500 sm:inline">năm xem</span>
            </div>
            <p
              className="mt-4 line-clamp-1 font-sans text-base leading-snug text-slate-200/95 sm:text-[17px]"
              title={summaryLine}
            >
              {summaryLine}
            </p>
          </div>
          <div className="flex shrink-0 flex-col gap-2 rounded-xl border border-[#d4af37]/14 bg-black/25 px-4 py-3 sm:min-w-[200px]">
            <div className="flex items-center justify-between gap-3 font-sans text-[12px] text-slate-500">
              <span>Tuổi xem</span>
              <span className="font-ctkp-serif text-[13px] text-[#e8dcc4]">{view.ageLabel?.trim() || "—"}</span>
            </div>
            <div className="h-px bg-[#d4af37]/10" />
            <div className="flex items-start justify-between gap-3 font-sans text-[12px] text-slate-500">
              <span className="shrink-0 pt-0.5">Đại vận</span>
              <span className="text-right font-ctkp-serif text-[12px] leading-snug text-[#e8dcc4]">
                {view.palaceName?.trim() || "Chưa neo — xem tab Đại vận"}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Engine Tiểu vận (deterministic) */}
      <div className="relative border-b border-[#d4af37]/12 px-5 py-5 sm:px-7 sm:py-6">
        <h2 className="font-ctkp-serif text-[11px] uppercase tracking-[0.2em] text-[#d4af37]/58">Luận tiểu vận (engine)</h2>
        {view.annualPeriodProse?.prose?.trim() ?
          <div className="mt-4 space-y-3">
            {view.annualPeriodProse.title?.trim() ?
              <h3 className="font-ctkp-serif text-lg text-[#f0e6bc]">{view.annualPeriodProse.title}</h3>
            : null}
            <p className="ctkp-tuvi-text-body whitespace-pre-wrap font-sans text-[14px] leading-relaxed text-slate-200/95">
              {view.annualPeriodProse.prose}
            </p>
            {view.annualPeriodProse.warnings.length > 0 ?
              <p className="font-sans text-[12px] leading-relaxed text-slate-500">
                {view.annualPeriodProse.warnings.join(" · ")}
              </p>
            : null}
          </div>
        : <p className="mt-4 font-sans text-[13px] text-slate-500">Chưa có bài luận Tiểu vận từ engine.</p>}
      </div>

      {/* Focus grid — 2×2 dashboard */}
      <div className="relative px-5 py-5 sm:px-7 sm:py-6">
        <div className="mb-4 flex items-center justify-between gap-2">
          <h2 className="font-ctkp-serif text-[11px] uppercase tracking-[0.2em] text-[#d4af37]/58">Bốn trụ năm</h2>
          <span className="font-sans text-[11px] text-slate-600">Công việc · Tài · Tình · Khỏe</span>
        </div>
        <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          {cards.map((c) => (
            <li
              key={c.key}
              className="relative flex overflow-hidden rounded-xl border border-[#d4af37]/12 bg-[linear-gradient(125deg,rgba(22,26,40,0.94),rgba(10,12,20,0.97))] shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"
            >
              <div className={`w-1 shrink-0 ${toneStripeClass(c.tone)}`} aria-hidden />
              <div className="min-w-0 flex-1 p-4 sm:p-4">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <h3 className="font-ctkp-serif text-base text-[#f0e6bc]">{c.title}</h3>
                  <span
                    className={`inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 font-ctkp-serif text-[10px] uppercase tracking-[0.12em] ring-1 ${tonePillClass(c.tone)}`}
                  >
                    <span className="h-1 w-1 rounded-full bg-current opacity-85" aria-hidden />
                    {toneLabelVi(c.tone)}
                  </span>
                </div>
                <p
                  className="ctkp-tuvi-text-body mt-3 line-clamp-4 font-sans text-[13px] leading-relaxed text-slate-400"
                  title={c.content}
                >
                  {c.content}
                </p>
              </div>
            </li>
          ))}
        </ul>
      </div>

      {/* Advice strip */}
      <div className="relative border-t border-[#d4af37]/12 px-5 py-5 sm:px-7 sm:py-6">
        <h2 className="font-ctkp-serif text-[11px] uppercase tracking-[0.2em] text-[#d4af37]/58">Chỉ dẫn năm</h2>
        <ul className="mt-4 grid gap-2 sm:grid-cols-1">
          {adviceLines.map((line, i) => (
            <li
              key={`${i}-${line.slice(0, 24)}`}
              className="flex gap-3 rounded-lg border border-white/[0.06] bg-black/22 px-3 py-2.5"
            >
              <span
                className="mt-2 h-1 w-1 shrink-0 rounded-full bg-[#d4af37]/65"
                aria-hidden
              />
              <span className="font-sans text-[13px] leading-relaxed text-slate-300/95">{line}</span>
            </li>
          ))}
        </ul>
      </div>

      <p className="relative border-t border-[#d4af37]/10 px-5 py-4 font-sans text-[12px] text-slate-500 sm:px-7">
        Mở{" "}
        {onGoLaSo ?
          <button
            type="button"
            onClick={onGoLaSo}
            className="font-ctkp-serif text-[#e8d9a8] underline underline-offset-2 decoration-[#d4af37]/45 hover:decoration-[#d4af37]/65"
          >
            Lá số
          </button>
        : <span className="text-[#e8d9a8]/92">Lá số</span>}
        {" "}để đối chiếu cung; tab Luận cung cho từng ô.
      </p>
    </section>
  );
}
