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

const SECTION_ORDER = ["career", "wealth", "communication"] as const;

type SectionKey = (typeof SECTION_ORDER)[number];

const SECTION_TITLE_VI: Record<SectionKey, string> = {
  career: "Công việc",
  wealth: "Tài chính",
  communication: "Giao tiếp",
};

const SECTION_FALLBACK_VI: Record<SectionKey, string> = {
  career: "Ưu tiên một việc chính; chi tiết Quan lộc xem tab Luận cung.",
  wealth: "Chi tiêu gọn — phần can chi ngày sẽ được làm rõ hơn trong bản sau.",
  communication: "Nói ngắn, rõ ý; tránh hứa hẹn vội khi chưa chắc.",
};

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

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 toneStripe(tone: FortuneTone): string {
  if (tone === "good") return "bg-emerald-500/75";
  if (tone === "caution") return "bg-rose-500/72";
  return "bg-[#c9a15d]/88";
}

function clipOneLine(s: string, max: number): string {
  const t = s.replace(/\s+/g, " ").trim();
  if (t.length <= max) return t;
  return `${t.slice(0, max - 1).trim()}…`;
}

function normalizeSections(view: NhatVanDayView): { key: SectionKey; content: string }[] {
  return SECTION_ORDER.map((key) => {
    const hit = view.sections.find((s) => s.key === key);
    const raw = (hit?.content ?? "").replace(/\s+/g, " ").trim();
    const content = raw.length > 0 ? clipOneLine(raw, 200) : SECTION_FALLBACK_VI[key];
    return { key, content };
  });
}

function splitPrioritizeAvoid(advice: string[] | undefined): { prioritize: string[]; avoid: string[] } {
  const lines = (advice ?? []).map((s) => s.trim()).filter(Boolean);
  const avoidRe = /tránh|không nên|hạn chế|đừng|chưa nên|không vội/i;
  const avoid: string[] = [];
  const prioritize: string[] = [];
  for (const line of lines) {
    if (avoidRe.test(line)) avoid.push(clipOneLine(line, 160));
    else prioritize.push(clipOneLine(line, 160));
  }
  if (prioritize.length === 0) {
    prioritize.push(
      lines[0] ? clipOneLine(lines[0], 160) : "Một việc quan trọng làm xong trước; giữ nhịp, không dàn trải.",
    );
  }
  if (avoid.length === 0) {
    avoid.push("Quyết định lớn hoặc cam kết vội khi thiếu thời gian cân nhắc.");
  }
  return {
    prioritize: prioritize.slice(0, 3),
    avoid: avoid.slice(0, 3),
  };
}

function nextDayToneDot(tone: FortuneTone): string {
  if (tone === "good") return "bg-emerald-400/85";
  if (tone === "caution") return "bg-rose-400/85";
  return "bg-amber-300/80";
}

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

export function TuViNhatVanPanel({ view, onGoLaSo }: Props) {
  const sections = normalizeSections(view);
  const { prioritize, avoid } = splitPrioritizeAvoid(view.shortAdvice);
  const headlineOne = clipOneLine(view.headline, 200);

  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="Nhật vận — xem ngày"
    >
      <div
        className="pointer-events-none absolute inset-0 opacity-[0.06]"
        style={{
          backgroundImage:
            "radial-gradient(ellipse 50% 38% at 50% -15%, rgba(201,161,93,0.35), transparent 52%)",
        }}
        aria-hidden
      />

      <div className="relative border-b border-[#d4af37]/12 px-5 py-5 sm:px-7">
        <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.32em] text-[#d4af37]/72">Hôm nay</p>
        <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div className="min-w-0">
            <p className="font-ctkp-serif text-lg leading-snug text-[#f5ead8] sm:text-xl">{view.dateLabel}</p>
            <p
              className="mt-2 line-clamp-1 font-sans text-[15px] leading-snug text-slate-200/95"
              title={headlineOne}
            >
              {headlineOne}
            </p>
          </div>
          <span
            className={`inline-flex w-fit shrink-0 items-center gap-2 rounded-full px-3 py-1.5 font-ctkp-serif text-[11px] uppercase tracking-[0.14em] ring-1 ${tonePillClass(view.tone)}`}
          >
            <span className="h-1.5 w-1.5 rounded-full bg-current opacity-85" aria-hidden />
            {toneLabelVi(view.tone)}
          </span>
        </div>
      </div>

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

      <div className="relative px-5 py-5 sm:px-7 sm:py-6">
        <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-3 sm:gap-3">
          {sections.map((s) => (
            <li
              key={s.key}
              className="flex overflow-hidden rounded-xl border border-[#d4af37]/12 bg-[linear-gradient(125deg,rgba(22,26,40,0.92),rgba(10,12,20,0.96))] shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"
            >
              <div className={`w-1 shrink-0 ${toneStripe(view.tone)}`} aria-hidden />
              <div className="min-w-0 flex-1 p-3 sm:p-3.5">
                <h3 className="font-ctkp-serif text-[13px] text-[#e8dcc4]">{SECTION_TITLE_VI[s.key]}</h3>
                <p className="mt-2 line-clamp-3 font-sans text-[12px] leading-relaxed text-slate-400" title={s.content}>
                  {s.content}
                </p>
              </div>
            </li>
          ))}
        </ul>
      </div>

      <div className="relative grid gap-3 border-t border-[#d4af37]/10 px-5 py-5 sm:grid-cols-2 sm:px-7 sm:py-6">
        <div className="rounded-xl border border-emerald-900/28 bg-emerald-950/[0.12] px-4 py-3">
          <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.2em] text-emerald-200/75">Ưu tiên</p>
          <ul className="mt-2 space-y-2">
            {prioritize.map((line, i) => (
              <li key={i} className="flex gap-2 font-sans text-[12px] leading-snug text-emerald-50/88">
                <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-emerald-400/75" aria-hidden />
                <span>{line}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="rounded-xl border border-rose-900/28 bg-rose-950/[0.1] px-4 py-3">
          <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.2em] text-rose-200/75">Nên tránh</p>
          <ul className="mt-2 space-y-2">
            {avoid.map((line, i) => (
              <li key={i} className="flex gap-2 font-sans text-[12px] leading-snug text-rose-50/88">
                <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-rose-400/75" aria-hidden />
                <span>{line}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {view.nextThreeDays && view.nextThreeDays.length > 0 ?
        <div className="border-t border-[#d4af37]/10 px-5 py-4 sm:px-7">
          <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.22em] text-[#d4af37]/55">Ba ngày kế</p>
          <ul className="mt-3 flex flex-col gap-2 sm:flex-row sm:flex-wrap">
            {view.nextThreeDays.map((d, i) => (
              <li
                key={`${d.dateLabel}-${i}`}
                className="flex min-w-0 flex-1 basis-[200px] items-start gap-2 rounded-lg border border-[#d4af37]/14 bg-black/22 px-3 py-2"
              >
                <span className={`mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full ${nextDayToneDot(d.tone)}`} aria-hidden />
                <div className="min-w-0">
                  <p className="font-ctkp-serif text-[12px] text-[#e8dcc4]">{d.dateLabel}</p>
                  <p className="line-clamp-2 font-sans text-[11px] leading-relaxed text-slate-500">{d.hint}</p>
                </div>
              </li>
            ))}
          </ul>
        </div>
      : null}

      <p className="relative border-t border-[#d4af37]/10 px-5 py-3 font-sans text-[11px] text-slate-500 sm:px-7">
        Can chi ngày đầy đủ sẽ củng cố lớp này.{" "}
        {onGoLaSo ?
          <button
            type="button"
            onClick={onGoLaSo}
            className="font-ctkp-serif text-[#e8d9a8] underline underline-offset-2 decoration-[#d4af37]/45 hover:decoration-[#d4af37]/65"
          >
            Mở lá số
          </button>
        : null}
      </p>
    </section>
  );
}
