// ─── Color-소개팅 · 데이터 상수 + API 어댑터 ─────────────────────
const TIERS = ['diamond', 'black', 'red', 'blue', 'yellow', 'white'];
const TIER_LABEL = {
  diamond: '다이아몬드', black: '블랙', red: '레드',
  blue: '블루', yellow: '옐로', white: '화이트',
};
const TIER_RANK = { diamond: 6, black: 5, red: 4, blue: 3, yellow: 2, white: 1 };

const PAYMENT_SERVICES = {
  'premium-match': { name: '프리미엄 매칭', price: 30000, color: '#e23a2e' },
  'rematch-guarantee': { name: '재매칭 보장권', price: 50000, color: '#2f6cf6' },
  'vip-concierge': { name: 'VIP 컨시어지', price: 150000, color: '#161412' },
  'profile-boost': { name: '프로필 부스터', price: 9900, color: '#f5c419' },
  'tier-review': { name: '등급 재심사', price: 15000, color: '#c8b8ff' },
};

// 백엔드에서 받아온 회원 데이터를 prototype 화면이 기대하는 형태로 정규화
const _daysSince = (iso) => {
  if (!iso) return 0;
  const t = new Date(iso).getTime();
  return Math.max(0, Math.floor((Date.now() - t) / (24 * 60 * 60 * 1000)));
};

const normalizeMember = (m) => {
  if (!m) return null;
  const id = m.memberCode || String(m._id);
  return {
    ...m,
    id,
    _id: String(m._id || ''),
    job: `${m.role} · ${m.company}`,
    maritalStatus: m.maritalStatus ?? '미혼',
    daysAgo: _daysSince(m.createdAt),
    matchTry: m.matchTry ?? 0,
    matchSuccess: m.matchSuccess ?? 0,
    matchFail: m.matchFail ?? 0,
    matchOngoing: m.matchOngoing ?? 0,
    totalPaid: m.totalPaid ?? 0,
    payments: m.payments ?? [],
    prefTier: m.prefTier ?? [],
    prefMbti: m.prefMbti ?? [],
    prefAge: Array.isArray(m.prefAge) && m.prefAge.length === 2 ? m.prefAge : [26, 32],
    prefAgeOpen: Boolean(m.prefAgeOpen),
    prefRegionOpen: Boolean(m.prefRegionOpen),
    intro: m.intro ?? '',
    ideal: m.ideal ?? '',
    message: m.message ?? '',
    photos: m.photos ?? [],
    tier: m.tier ?? 'white',
    workplace: m.workplace ?? '',
  };
};

// 초기값 — MOCK_MEMBERS는 비어있고, 관리자 로그인 후 API로 채워진다
const MOCK_MEMBERS = [];
// 차트는 디자인 유지를 위해 더미 시드 (대시보드 화면 깨짐 방지)
const MATCH_HISTORY = [
  { week: 'W18', applies: 0, matches: 0 },
  { week: 'W19', applies: 0, matches: 0 },
  { week: 'W20', applies: 0, matches: 0 },
  { week: 'W21', applies: 0, matches: 0 },
  { week: 'W22', applies: 0, matches: 0 },
  { week: 'W23', applies: 0, matches: 0 },
  { week: 'W24', applies: 0, matches: 0 },
  { week: 'W25', applies: 0, matches: 0 },
];

Object.assign(window, {
  TIERS, TIER_LABEL, TIER_RANK, MOCK_MEMBERS, MATCH_HISTORY, PAYMENT_SERVICES,
  normalizeMember,
  /** 관리자 CSV 다운로드 (UTF-8 BOM) */
  downloadMembersCsv(members, fileBase = 'members') {
    if (!Array.isArray(members) || members.length === 0) return;
    const headers = ['memberCode', 'name', 'age', 'gender', 'tier', 'job', 'region', 'workplace', 'mbti', 'contact', 'kakao', 'insta', 'createdAt'];
    const esc = (v) => {
      const s = v == null ? '' : String(v);
      if (/[",\r\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
      return s;
    };
    const lines = [headers.join(',')];
    for (const m of members) {
      const gender = m.gender === 'M' ? '남' : m.gender === 'F' ? '여' : (m.gender || '');
      const job = m.job || `${m.role || ''} · ${m.company || ''}`;
      const code = m.id || m.memberCode || '';
      lines.push([
        code, m.name, m.age, gender, m.tier || 'white', job, m.region || '', m.workplace || '',
        m.mbti || '', m.contact || '', m.kakao || '', m.insta || '',
        m.createdAt ? new Date(m.createdAt).toISOString() : '',
      ].map(esc).join(','));
    }
    const blob = new Blob([`\uFEFF${lines.join('\n')}`], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    const safe = String(fileBase).replace(/[^\w\-가-힣]/g, '_').slice(0, 80);
    a.href = url;
    a.download = `color-sogaeting-${safe}-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  },
});
