// Saladin Thần số — Numerology engine (Pythagoras method)
// Reference: momo.vn/blog/than-so-hoc-khoa-hoc-kham-pha-ban-than-thong-qua-nhung-con-so

// ─────────────────────────────────────────────────────────────
// Pythagoras alphabet (A=1...I=9, J=1...R=9, S=1...Z=8)
// ─────────────────────────────────────────────────────────────
const PYTH_TABLE = {
  A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, I: 9,
  J: 1, K: 2, L: 3, M: 4, N: 5, O: 6, P: 7, Q: 8, R: 9,
  S: 1, T: 2, U: 3, V: 4, W: 5, X: 6, Y: 7, Z: 8,
};

const VOWELS = new Set(['A', 'E', 'I', 'O', 'U']);
const MASTER_NUMBERS = new Set([11, 22, 33]);

// ─────────────────────────────────────────────────────────────
// Strip Vietnamese diacritics → uppercase ASCII letters only
// Đ → D, ô → O, ả → A, etc.
// ─────────────────────────────────────────────────────────────
function normalizeVietnamese(input) {
  if (!input) return '';
  return input
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')   // remove combining diacritics
    .replace(/đ/g, 'd')
    .replace(/Đ/g, 'D')
    .toUpperCase()
    .replace(/[^A-Z]/g, '');           // keep only A-Z
}

// ─────────────────────────────────────────────────────────────
// Sum digits of a number
// ─────────────────────────────────────────────────────────────
function sumDigits(n) {
  return String(n).split('').reduce((s, d) => s + parseInt(d, 10), 0);
}

// ─────────────────────────────────────────────────────────────
// Reduce a number to single digit, preserving Master Numbers
// reduceNumber(28) → 1
// reduceNumber(29) → 2  (2+9=11 → keep)... actually 11 is master so stop
// ─────────────────────────────────────────────────────────────
function reduceNumber(n) {
  let current = Math.abs(n);
  while (current > 9) {
    if (MASTER_NUMBERS.has(current)) return current;
    current = sumDigits(current);
  }
  return current;
}

// ─────────────────────────────────────────────────────────────
// Convert letter → Pythagoras digit (returns 0 if not a letter)
// ─────────────────────────────────────────────────────────────
function letterValue(ch) {
  return PYTH_TABLE[ch] || 0;
}

// ─────────────────────────────────────────────────────────────
// Sum all letters of a normalized name
// ─────────────────────────────────────────────────────────────
function sumLetters(name, filter) {
  const letters = normalizeVietnamese(name).split('');
  return letters.reduce((sum, ch) => {
    if (filter && !filter(ch)) return sum;
    return sum + letterValue(ch);
  }, 0);
}

// ─────────────────────────────────────────────────────────────
// 1. LIFE PATH from DOB (most important)
// Phương pháp: cộng day + month + year riêng từng phần, rút gọn từng phần,
// rồi cộng tổng và rút gọn lần cuối. Giữ master numbers.
// ─────────────────────────────────────────────────────────────
function calcLifePath(dob) {
  // dob can be Date object or 'YYYY-MM-DD' string
  let d, m, y;
  if (typeof dob === 'string') {
    const parts = dob.split('-');
    y = parseInt(parts[0], 10);
    m = parseInt(parts[1], 10);
    d = parseInt(parts[2], 10);
  } else {
    d = dob.getDate();
    m = dob.getMonth() + 1;
    y = dob.getFullYear();
  }
  const dPart = reduceNumber(d);
  const mPart = reduceNumber(m);
  const yPart = reduceNumber(y);
  return reduceNumber(dPart + mPart + yPart);
}

// ─────────────────────────────────────────────────────────────
// 2. DESTINY from full name (all letters)
// ─────────────────────────────────────────────────────────────
function calcDestiny(fullName) {
  return reduceNumber(sumLetters(fullName));
}

// ─────────────────────────────────────────────────────────────
// 3. PERSONALITY from consonants
// ─────────────────────────────────────────────────────────────
function calcPersonality(fullName) {
  return reduceNumber(sumLetters(fullName, (ch) => !VOWELS.has(ch)));
}

// ─────────────────────────────────────────────────────────────
// 4. SOUL URGE from vowels
// ─────────────────────────────────────────────────────────────
function calcSoulUrge(fullName) {
  return reduceNumber(sumLetters(fullName, (ch) => VOWELS.has(ch)));
}

// ─────────────────────────────────────────────────────────────
// 5. PERSONAL YEAR for given year (default: current)
// = birth month + birth day + year (reduce)
// ─────────────────────────────────────────────────────────────
function calcPersonalYear(dob, year) {
  let d, m;
  if (typeof dob === 'string') {
    const parts = dob.split('-');
    m = parseInt(parts[1], 10);
    d = parseInt(parts[2], 10);
  } else {
    d = dob.getDate();
    m = dob.getMonth() + 1;
  }
  const y = year || new Date().getFullYear();
  return reduceNumber(reduceNumber(d) + reduceNumber(m) + reduceNumber(y));
}

// ─────────────────────────────────────────────────────────────
// Convenience: all 5 numbers
// ─────────────────────────────────────────────────────────────
function calculateAll(input) {
  const { name, dob } = input;
  return {
    lifePath: calcLifePath(dob),
    destiny: calcDestiny(name),
    personality: calcPersonality(name),
    soulUrge: calcSoulUrge(name),
    personalYear: calcPersonalYear(dob),
  };
}

// ─────────────────────────────────────────────────────────────
// Vietnamese names for each number
// ─────────────────────────────────────────────────────────────
const NUMBER_NAMES = {
  1: 'Người Tiên Phong',
  2: 'Người Hòa Giải',
  3: 'Người Sáng Tạo',
  4: 'Người Xây Dựng',
  5: 'Người Tự Do',
  6: 'Người Nuôi Dưỡng',
  7: 'Người Tìm Tòi',
  8: 'Người Quyền Lực',
  9: 'Người Phục Vụ',
  11: 'Bậc Thầy Trực Giác',
  22: 'Kiến Trúc Sư Vĩ Đại',
  33: 'Bậc Thầy Của Tình Yêu',
};

// One-liner definitions (for poster + result quick view)
const NUMBER_TAGLINES = {
  1: 'Khởi xướng, độc lập, lãnh đạo, tự lực.',
  2: 'Trực giác, nhạy cảm, ngoại giao, cân bằng.',
  3: 'Truyền đạt, hài hước, lạc quan, nghệ thuật.',
  4: 'Thực tế, kỷ luật, logic, đáng tin cậy.',
  5: 'Phiêu lưu, thay đổi, thông minh, đa tài.',
  6: 'Trách nhiệm, yêu thương, gia đình, hàn gắn.',
  7: 'Trí tuệ, phân tích, tìm tòi, tâm linh.',
  8: 'Tài chính, kinh doanh, thực thi, thành công.',
  9: 'Nhân ái, hoàn thiện, từ bi, tầm nhìn lớn.',
  11: 'Trực giác siêu phàm, linh cảm, sứ mệnh truyền cảm hứng.',
  22: 'Tầm nhìn vĩ đại, biến giấc mơ thành hiện thực.',
  33: 'Tình yêu vô điều kiện, dạy dỗ và chữa lành.',
};

// Color theme mapping (semantic — used by poster + result cards)
const NUMBER_COLORS = {
  1: 'navy',      // primary
  2: 'sage',      // tertiary
  3: 'warning',   // yellow accent
  4: 'teal',      // secondary
  5: 'navy',
  6: 'sage',
  7: 'navy',
  8: 'teal',
  9: 'warning',
  11: 'master',
  22: 'master',
  33: 'master',
};

// ─────────────────────────────────────────────────────────────
// SHARE: utm builder
// ─────────────────────────────────────────────────────────────
function buildShareUrl(channel, options) {
  const opts = options || {};
  const base = 'https://saladin.vn/than-so';
  const params = new URLSearchParams({
    utm_source: channel || 'direct',
    utm_medium: 'social',
    utm_campaign: 'share-result-2026',
  });
  if (opts.id) params.set('id', opts.id);
  if (opts.lifePath) params.set('lp', String(opts.lifePath));
  return `${base}?${params.toString()}`;
}

// ─────────────────────────────────────────────────────────────
// Localized banner state helpers
// ─────────────────────────────────────────────────────────────
const BANNER_KEY = 'saladin-banner-dismissed-until';
const BANNER_DISMISS_MS = 7 * 24 * 60 * 60 * 1000; // 7 days

function shouldShowBanner() {
  try {
    const ts = localStorage.getItem(BANNER_KEY);
    return !ts || parseInt(ts, 10) < Date.now();
  } catch (e) {
    return true;
  }
}

function dismissBanner() {
  try {
    localStorage.setItem(BANNER_KEY, String(Date.now() + BANNER_DISMISS_MS));
  } catch (e) {}
}

// ─────────────────────────────────────────────────────────────
// Analytics (stub — wire to GA4/Mixpanel in production)
// ─────────────────────────────────────────────────────────────
function trackEvent(eventName, props) {
  if (typeof window === 'undefined') return;
  // Production: window.gtag('event', eventName, props)
  // Production: window.mixpanel.track(eventName, props)
  if (window.__SALADIN_DEBUG__) {
    console.log('[analytics]', eventName, props);
  }
}

// ─────────────────────────────────────────────────────────────
// Export to window for cross-file access (no-build prototype)
// ─────────────────────────────────────────────────────────────
window.SaladinNumerology = {
  normalizeVietnamese,
  reduceNumber,
  calcLifePath,
  calcDestiny,
  calcPersonality,
  calcSoulUrge,
  calcPersonalYear,
  calculateAll,
  NUMBER_NAMES,
  NUMBER_TAGLINES,
  NUMBER_COLORS,
  buildShareUrl,
  shouldShowBanner,
  dismissBanner,
  trackEvent,
};

// Self-test (logs to console when __SALADIN_DEBUG__ = true)
if (typeof window !== 'undefined' && window.__SALADIN_DEBUG__) {
  console.assert(calcLifePath('1990-10-28') === 3, 'Life Path 28/10/1990 should be 3');
  console.assert(reduceNumber(11) === 11, 'Master 11 preserved');
  console.assert(reduceNumber(22) === 22, 'Master 22 preserved');
  console.assert(normalizeVietnamese('Nguyễn Văn Á') === 'NGUYENVANA', 'VN normalize');
  console.log('[numerology] self-tests passed');
}
