/**
 * Đặt tên — phân tích tên theo Thần Số Học và độ ngắn / âm điệu.
 *
 * Vì thuật toán phong-thuỷ tên Hán-Nôm (số nét bộ thủ) cần dữ liệu lớn
 * không phù hợp client, ta dùng tiếp cận thực dụng:
 *   1. Tổng số ký tự alphabet → reduce 1-9 (lấy ý nghĩa Pythagore)
 *   2. Số nguyên âm (soul urge)
 *   3. Số phụ âm (personality)
 *   4. Phân tích âm điệu — ngắn/dài, vần, dễ đọc
 *   5. So với năm sinh để gợi ý hợp/không
 */

import { lifePath, expressionNumber, soulUrge, NUMBER_MEANINGS } from "@/lib/numerology";
import { elementFromYear, type Element } from "@/lib/feng-shui/colors";

const VOWELS_VN = new Set(["a", "ă", "â", "e", "ê", "i", "o", "ô", "ơ", "u", "ư", "y"]);

function normalize(s: string): string {
  return s
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/đ/gi, "d")
    .toLowerCase();
}

function syllableCount(name: string): number {
  // VN names — tách theo space, lấy số "tiếng"
  return name.trim().split(/\s+/).filter(Boolean).length;
}

function vowelCount(name: string): number {
  return [...name.toLowerCase()].filter((c) => VOWELS_VN.has(c)).length;
}

/** Personality number — Pythagore consonants (lượt bỏ nguyên âm). */
function personalityNumber(fullName: string): number {
  const norm = normalize(fullName).replace(/[^a-z]/g, "");
  let sum = 0;
  for (const ch of norm) {
    if (VOWELS_VN.has(ch)) continue;
    sum += ((ch.charCodeAt(0) - 97) % 9) + 1;
  }
  while (sum > 9 && ![11, 22, 33].includes(sum)) {
    sum = sum
      .toString()
      .split("")
      .reduce((s, d) => s + parseInt(d, 10), 0);
  }
  return sum;
}

function rhythmScore(name: string): { score: number; reason: string } {
  const sy = syllableCount(name);
  const vow = vowelCount(name);
  const len = name.replace(/\s/g, "").length;

  if (sy === 0 || len === 0) return { score: 0, reason: "Tên rỗng." };

  if (sy === 1) {
    return {
      score: 18,
      reason: "Tên 1 tiếng — gọn nhưng cảm giác hụt hẫng, ít dùng cho người Việt.",
    };
  }
  if (sy === 2) {
    return {
      score: 22,
      reason: "Tên 2 tiếng (họ + tên) — ngắn, mạnh mẽ, phù hợp công ty và cá nhân hành động.",
    };
  }
  if (sy === 3) {
    return {
      score: 25,
      reason: "Tên 3 tiếng — chuẩn mực Việt Nam, cân bằng âm thanh và ý nghĩa.",
    };
  }
  if (sy === 4) {
    return {
      score: 22,
      reason: "Tên 4 tiếng — sang trọng nhưng dài, cần âm điệu hài hoà.",
    };
  }
  return {
    score: 16,
    reason: `Tên ${sy} tiếng — quá dài, khó nhớ và khó gọi.`,
  };
}

const ELEMENT_HINT: Record<Element, string> = {
  Kim: "Mệnh Kim hợp tên có âm sắc gọn, sắc bén (chữ T, S, K, X, B). Nên có ít nhất 1 chữ thuộc Thuỷ (Đ, M, N, V) — Kim sinh Thuỷ.",
  Mộc: "Mệnh Mộc hợp tên dạng phát triển (chữ G, K, Q, C). Nên có chữ thuộc Thuỷ (M, N, V) — Thuỷ sinh Mộc.",
  Thuỷ: "Mệnh Thuỷ hợp tên mềm mại, uyển chuyển (chữ B, P, M, V, H). Nên có chữ Kim (S, T, X) — Kim sinh Thuỷ.",
  Hoả: "Mệnh Hoả hợp tên nồng nhiệt, mạnh (chữ Đ, L, T, N, D). Nên có chữ Mộc (G, C, K, Q) — Mộc sinh Hoả.",
  Thổ: "Mệnh Thổ hợp tên vững chắc, an định (chữ A, Y, U, O, I, B). Nên có chữ Hoả (Đ, L, T, N) — Hoả sinh Thổ.",
};

export type NameAnalysis = {
  fullName: string;
  syllables: number;
  letters: number;
  vowels: number;
  expression: number;
  expressionMeaning: string;
  soul: number;
  soulMeaning: string;
  personality: number;
  personalityMeaning: string;
  rhythm: { score: number; reason: string };
  element?: Element;
  elementHint?: string;
  lifePathMatch?: { lifePath: number; expression: number; match: "tốt" | "trung" | "kỵ" };
  syllableBreakdown: Array<{ syllable: string; vowels: number; consonants: number; sum: number }>;
  pros: string[];
  cons: string[];
  suggestions: string[];
  totalScore: number; // 0-100
  rating: "Rất tốt" | "Tốt" | "Bình thường" | "Cần xem lại";
};

export function analyzeName(
  fullName: string,
  birth?: { year: number; month: number; day: number }
): NameAnalysis | null {
  const trimmed = fullName.trim();
  if (trimmed.length < 2) return null;

  const norm = normalize(trimmed);
  const expression = expressionNumber(trimmed);
  const soul = soulUrge(trimmed);
  const personality = personalityNumber(trimmed);
  const rhythm = rhythmScore(trimmed);

  // Per-syllable breakdown
  const syllableBreakdown = trimmed
    .split(/\s+/)
    .filter(Boolean)
    .map((sy) => {
      const n = normalize(sy);
      const vowels = [...n].filter((c) => VOWELS_VN.has(c)).length;
      const consonants = [...n].filter((c) => /[a-z]/.test(c) && !VOWELS_VN.has(c)).length;
      return { syllable: sy, vowels, consonants, sum: vowels + consonants };
    });

  let element: Element | undefined;
  let elementHint: string | undefined;
  let lifePathMatch: NameAnalysis["lifePathMatch"];

  if (birth) {
    element = elementFromYear(birth.year);
    elementHint = ELEMENT_HINT[element];
    const lp = lifePath(birth.year, birth.month, birth.day);
    // Match nếu cùng modulo / sinh / khắc nhau
    let match: "tốt" | "trung" | "kỵ" = "trung";
    if (lp === expression) match = "tốt";
    else if ((lp + expression) % 9 === 0) match = "kỵ";
    else match = "trung";
    lifePathMatch = { lifePath: lp, expression, match };
  }

  // Tổng điểm: rhythm (25) + expression goodness (25) + soul goodness (25) + lifePath match (25)
  const numToScore = (n: number): number => {
    // Master numbers cao điểm; 9, 8, 6, 3, 1 cao
    if ([11, 22, 33].includes(n)) return 25;
    const map: Record<number, number> = {
      1: 22,
      2: 18,
      3: 22,
      4: 18,
      5: 20,
      6: 22,
      7: 18,
      8: 22,
      9: 24,
    };
    return map[n] ?? 18;
  };

  const expScore = numToScore(expression);
  const soulScore = numToScore(soul);
  const matchScore = lifePathMatch?.match === "tốt" ? 25 : lifePathMatch?.match === "kỵ" ? 8 : 18;

  const totalScore = Math.round(rhythm.score + expScore + soulScore + matchScore);

  let rating: NameAnalysis["rating"] = "Bình thường";
  if (totalScore >= 85) rating = "Rất tốt";
  else if (totalScore >= 70) rating = "Tốt";
  else if (totalScore >= 55) rating = "Bình thường";
  else rating = "Cần xem lại";

  // ───── Pros & Cons ─────
  const pros: string[] = [];
  const cons: string[] = [];

  if ([11, 22, 33].includes(expression))
    pros.push(`Số biểu cảm ${expression} là MASTER NUMBER — năng lượng đặc biệt mạnh.`);
  else if ([1, 3, 6, 8, 9].includes(expression))
    pros.push(`Số biểu cảm ${expression} mạnh — ${NUMBER_MEANINGS[expression]?.title}.`);
  else if ([4, 7, 2].includes(expression))
    cons.push(`Số biểu cảm ${expression} hơi yếu — ${NUMBER_MEANINGS[expression]?.title}.`);

  if (lifePathMatch?.match === "tốt")
    pros.push(`Tên cộng hưởng tốt với Số chủ đạo ${lifePathMatch.lifePath} — lực đẩy thuận chiều.`);
  if (lifePathMatch?.match === "kỵ")
    cons.push(`Tên kỵ với Số chủ đạo ${lifePathMatch.lifePath} — lực cản tinh tế trên đường đời.`);

  if (rhythm.score >= 22) pros.push("Âm điệu cân đối, dễ đọc dễ nhớ.");
  if (rhythm.score < 18) cons.push("Âm điệu lệch — quá ngắn hoặc quá dài.");

  if (syllableBreakdown.length === 1) cons.push("Tên 1 tiếng — ít gặp ở Việt Nam.");

  const totalLetters = norm.replace(/[^a-z]/g, "").length;
  const totalVowels = vowelCount(trimmed);
  if (totalLetters > 0) {
    const ratio = totalVowels / totalLetters;
    if (ratio > 0.55) cons.push("Quá nhiều nguyên âm — âm thanh dễ nhão, thiếu sắc bén.");
    else if (ratio < 0.3) cons.push("Quá ít nguyên âm — khó đọc, gãy tiếng.");
    else if (ratio >= 0.4 && ratio <= 0.5) pros.push("Tỉ lệ nguyên âm / phụ âm cân bằng (~45%).");
  }

  // ───── Suggestions ─────
  const suggestions: string[] = [];
  if (lifePathMatch?.match === "kỵ" && totalScore < 70) {
    suggestions.push(
      "Cân nhắc đổi 1 trong 2 tên đệm sao cho Số biểu cảm trở thành 1, 3, 6, 8 hoặc 9."
    );
  }
  if (element === "Hoả" && norm.includes("th")) {
    suggestions.push("Mệnh Hoả có tên chứa 'Th' (thuộc Thuỷ) — cân nhắc thay tên đệm.");
  }
  if (element === "Thuỷ" && norm.includes("h ") && totalScore < 70) {
    // weak heuristic, kept as friendly suggestion
    suggestions.push("Mệnh Thuỷ — thử thêm tên đệm có chữ M, V, B (cùng Thuỷ) để cộng hưởng.");
  }
  if (syllableBreakdown.length >= 5) {
    suggestions.push("Tên 5 tiếng trở lên hơi dài — bỏ bớt một tên đệm để gọn hơn.");
  }
  if (suggestions.length === 0 && totalScore >= 70) {
    suggestions.push("Tên đã ổn — chỉ cần chú ý chọn ngày đặt tên / khai sinh hợp tuổi.");
  } else if (suggestions.length === 0) {
    suggestions.push(
      "Tên không có lỗi rõ rệt nhưng cũng không nổi bật — thử biến thể có Số biểu cảm khác."
    );
  }

  return {
    fullName: trimmed,
    syllables: syllableCount(trimmed),
    letters: norm.replace(/[^a-z]/g, "").length,
    vowels: vowelCount(trimmed),
    expression,
    expressionMeaning: NUMBER_MEANINGS[expression]?.title ?? "",
    soul,
    soulMeaning: NUMBER_MEANINGS[soul]?.title ?? "",
    personality,
    personalityMeaning: NUMBER_MEANINGS[personality]?.title ?? "",
    rhythm,
    element,
    elementHint,
    lifePathMatch,
    syllableBreakdown,
    pros,
    cons,
    suggestions,
    totalScore,
    rating,
  };
}
