"use client";

/**
 * Tử Vi Số · ChartWithOverlay
 *
 * Client wrapper around ChartGrid that lets the user toggle different
 * "an lưu" overlays:
 *   - None: only static chart
 *   - Đại vận: 10-year period palace names rotated to current decadal
 *   - Tiểu hạn: 1-year palace names rotated to age branch
 *   - Lưu niên: 1-year palace names rotated to year branch
 *   - Lưu nguyệt: 1-month palace names rotated to month branch
 *
 * iztro returns `period.palaceNames` as a 12-entry array starting at the
 * cell where Lưu Mệnh anchors (`period.index` is the branch index, Dần=0).
 * We rotate that array onto our static branch grid using BRANCH_ORDER.
 */

import { useState } from "react";
import { ChartGrid } from "./chart-grid";
import type { Chart } from "@/lib/tuvi/engine";
import type { Horoscope, HoroscopePeriod } from "@/lib/tuvi/horoscope";
import { cn } from "@/lib/utils";

const BRANCH_ORDER = [
  "Dần",
  "Mão",
  "Thìn",
  "Tỵ",
  "Ngọ",
  "Mùi",
  "Thân",
  "Dậu",
  "Tuất",
  "Hợi",
  "Tý",
  "Sửu",
] as const;

type OverlayMode = "none" | "decadal" | "ageHan" | "yearly" | "monthly";

const OPTIONS: Array<{
  key: OverlayMode;
  label: string;
  hint: string;
  accent: "gold" | "emerald" | "sky" | "rose" | undefined;
}> = [
  { key: "none", label: "Không", hint: "Chỉ lá số gốc", accent: undefined },
  { key: "decadal", label: "Đại vận", hint: "An lưu đại vận (10 năm)", accent: "gold" },
  { key: "ageHan", label: "Tiểu hạn", hint: "An lưu tiểu hạn theo tuổi", accent: "sky" },
  { key: "yearly", label: "Lưu niên", hint: "An lưu năm xem", accent: "emerald" },
  { key: "monthly", label: "Lưu nguyệt", hint: "An lưu tháng xem", accent: "rose" },
];

/**
 * Map period.palaceNames (12-entry array, position 0 = at branch Dần)
 * to a branch-keyed lookup. iztro guarantees the array is in
 * BRANCH_ORDER (Dần-first) regardless of period.index.
 */
function buildBranchMap(period: HoroscopePeriod): Record<string, string> {
  const map: Record<string, string> = {};
  for (let i = 0; i < BRANCH_ORDER.length; i++) {
    const palace = period.palaceNames[i];
    if (palace) {
      // Strip "Cung " prefix if present, keep only the palace name
      const clean = palace.replace(/^Cung\s+/i, "");
      map[BRANCH_ORDER[i]] = clean;
    }
  }
  return map;
}

export function ChartWithOverlay({ chart, horo }: { chart: Chart; horo: Horoscope }) {
  const [mode, setMode] = useState<OverlayMode>("none");

  const opt = OPTIONS.find((o) => o.key === mode)!;
  let overlay:
    | {
        label: string;
        accent: "gold" | "emerald" | "sky" | "rose";
        branchMap: Record<string, string>;
      }
    | undefined;
  if (mode !== "none" && opt.accent) {
    const period =
      mode === "decadal"
        ? horo.decadal
        : mode === "ageHan"
          ? horo.ageHan
          : mode === "yearly"
            ? horo.yearly
            : horo.monthly;
    overlay = {
      label: opt.label,
      accent: opt.accent,
      branchMap: buildBranchMap(period),
    };
  }

  // Header info for current overlay
  const periodInfo: Record<
    OverlayMode,
    { stem: string; branch: string; mutagen: string[] } | null
  > = {
    none: null,
    decadal: {
      stem: horo.decadal.heavenlyStem,
      branch: horo.decadal.earthlyBranch,
      mutagen: horo.decadal.mutagen,
    },
    ageHan: {
      stem: horo.ageHan.heavenlyStem,
      branch: horo.ageHan.earthlyBranch,
      mutagen: horo.ageHan.mutagen,
    },
    yearly: {
      stem: horo.yearly.heavenlyStem,
      branch: horo.yearly.earthlyBranch,
      mutagen: horo.yearly.mutagen,
    },
    monthly: {
      stem: horo.monthly.heavenlyStem,
      branch: horo.monthly.earthlyBranch,
      mutagen: horo.monthly.mutagen,
    },
  };
  const cur = periodInfo[mode];

  return (
    <div>
      {/* Toggle bar */}
      <div className="border-stroke-subtle bg-bg-elevated/40 mb-3 rounded-xl border p-2">
        <div className="flex flex-wrap items-center gap-1.5">
          <span className="text-ink-muted px-2 text-[11px] tracking-[0.18em] uppercase">
            An lưu:
          </span>
          {OPTIONS.map((o) => {
            const active = o.key === mode;
            const accentCls = active
              ? o.accent === "gold"
                ? "bg-brand-gold/20 ring-brand-gold/50 text-brand-gold"
                : o.accent === "emerald"
                  ? "bg-emerald-500/20 ring-emerald-500/50 text-emerald-200"
                  : o.accent === "sky"
                    ? "bg-sky-500/20 ring-sky-500/50 text-sky-200"
                    : o.accent === "rose"
                      ? "bg-rose-500/20 ring-rose-500/50 text-rose-200"
                      : "bg-bg-base/80 ring-stroke-subtle/60 text-ink-primary"
              : "bg-transparent ring-stroke-subtle/40 text-ink-secondary hover:text-ink-primary hover:bg-bg-base/40";
            return (
              <button
                key={o.key}
                type="button"
                onClick={() => setMode(o.key)}
                title={o.hint}
                className={cn(
                  "rounded-lg px-3 py-1.5 text-xs font-medium ring-1 transition ring-inset",
                  accentCls
                )}
              >
                {o.label}
              </button>
            );
          })}
        </div>

        {cur ? (
          <div className="text-ink-muted mt-2 px-2 text-[11px] leading-snug">
            <span className="text-ink-secondary font-medium">
              {cur.stem} {cur.branch}
            </span>{" "}
            · Hóa Lộc <span className="text-emerald-300">{cur.mutagen[0] || "—"}</span> · Quyền{" "}
            <span className="text-sky-300">{cur.mutagen[1] || "—"}</span> · Khoa{" "}
            <span className="text-amber-300">{cur.mutagen[2] || "—"}</span> · Kỵ{" "}
            <span className="text-rose-300">{cur.mutagen[3] || "—"}</span>
          </div>
        ) : (
          <div className="text-ink-muted mt-2 px-2 text-[11px]">
            Chọn 1 chu kỳ để an lưu cung lên lá số (Lưu Mệnh, Lưu Tài, …).
          </div>
        )}
      </div>

      <ChartGrid chart={chart} overlay={overlay} />
    </div>
  );
}
