/* 모모, 테리 — content data (씨엘피아 토들러 프로그램 · 1~2세) */

const THEMES = {
  brand: { name: '모모·테리', primary: '#56abe6', strong: '#357fc4', soft: '#a6d4f2', tint: '#e6f3fc', tint2: '#f1f8fd', accent: '#82c247', bg: '#eef5fb', ink: '#27384a', muted: '#7c92a8', line: '#dceaf6' },
  mint:  { name: '새싹 그린', primary: '#5fbf86', strong: '#3f9c66', soft: '#aadcbe', tint: '#e6f6ec', tint2: '#f0faf3', accent: '#f0b94a', bg: '#eef8f1', ink: '#26413a', muted: '#7ba491', line: '#dcefe2' },
  coral: { name: '복숭아 코랄', primary: '#f0826a', strong: '#d65f48', soft: '#f4b3a2', tint: '#fdeee9', tint2: '#fef5f1', accent: '#f6c560', bg: '#fbf4f0', ink: '#42302a', muted: '#a88c84', line: '#f5e7e0' },
  grape: { name: '포도 보라', primary: '#7c5cc4', strong: '#5e3fa6', soft: '#b89fe0', tint: '#efe9fa', tint2: '#f6f2fc', accent: '#f5a8c8', bg: '#f4f1f8', ink: '#2c2440', muted: '#8a82a0', line: '#ece7f4' },
};

/* pastel card backgrounds */
const PASTELS = [
  { bg: '#e3f0fb', fg: '#3d7fbf' }, // momo blue
  { bg: '#e8f3d8', fg: '#6f9a36' }, // terry green
  { bg: '#fdeecb', fg: '#bd8a2a' }, // yellow
  { bg: '#fce6ef', fg: '#c2537f' }, // pink
  { bg: '#e0f3ef', fg: '#3f9c86' }, // mint
  { bg: '#efe6fb', fg: '#7a5bb8' }, // soft purple
];

const CHARS = {
  모모: { img: () => 'assets/momo.png', age: '만 1세', en: 'MOMO', tag: '물방울 친구', color: '#56abe6',
          desc: '처음 만나는 세상, 사랑받으며 자라는 모모', keywords: ['순수함', '안정감', '호기심', '사랑', '시작'] },
  테리: { img: () => 'assets/terry.png', age: '만 2세', en: 'TERRY', tag: '새싹 친구', color: '#82c247',
          desc: '스스로 해보는 세상, 탐험하며 자라는 테리', keywords: ['탐색', '자신감', '성장', '도전', '확장'] },
};

const CATEGORIES = [
  { id: 'bond',   icon: '🩵', name: '정서·애착', desc: '안정감 속에서 마음 키우기' },
  { id: 'sense',  icon: '🤲', name: '신체·감각', desc: '오감으로 만나는 세상' },
  { id: 'explore',icon: '🔍', name: '탐색·인지', desc: '스스로 발견하는 즐거움' },
  { id: 'talk',   icon: '💬', name: '언어·소통', desc: '말과 표정으로 주고받기' },
  { id: 'social', icon: '🤝', name: '사회관계', desc: '친구와 함께 자라기' },
  { id: 'habit',  icon: '🍼', name: '생활습관', desc: '하루의 작은 약속들' },
];

const RECOMMENDED = [
  { tag: 'STEP1', meta: '만 1세 · 1차시', title: '사랑해 우리 모모', cat: 0 },
  { tag: 'STEP2', meta: '만 2세 · 2차시', title: '스스로 척척 테리', cat: 1 },
  { tag: '확장수업', meta: '1~2세 · 영상', title: '뽀송뽀송 손 씻기', cat: 2 },
  { tag: 'STEP1', meta: '만 2세 · 1차시', title: '오감으로 만나요', cat: 4 },
];

/* materials page */
const TOPICS = ['첫 인사', '애착·정서', '오감탐색', '몸놀이', '생활습관', '사회관계'];
const DOWNLOAD_KINDS = ['가이드북', '월간', '주간', '일간'];
const DOWNLOAD_KIND_ICONS = { 가이드북: '📘', 월간: '🗓️', 주간: '📅', 일간: '☀️' };

async function fetchContentByStep(step) {
  const { data, error } = await window.supabaseClient
    .from('contents')
    .select('*')
    .eq('type', '수업지원자료')
    .eq('step', step)
    .eq('status', 'published')
    .order('created_at', { ascending: false })
    .limit(1);
  if (error) { console.error(error); return null; }
  return (data && data[0]) || null;
}

async function fetchContentByStepAndTrack(step, track) {
  const { data, error } = await window.supabaseClient
    .from('contents')
    .select('*')
    .eq('type', '수업지원자료')
    .eq('step', step)
    .eq('track', track)
    .eq('status', 'published')
    .order('created_at', { ascending: false })
    .limit(1);
  if (error) { console.error(error); return null; }
  return (data && data[0]) || null;
}

async function fetchWeeklyPlan(contentId) {
  const [{ data: activities, error: e1 }, { data: chapters, error: e2 }] = await Promise.all([
    window.supabaseClient.from('content_week_activities').select('*').eq('content_id', contentId).order('week').order('slot'),
    window.supabaseClient.from('content_week_chapters').select('*').eq('content_id', contentId).order('week').order('slot'),
  ]);
  if (e1) console.error(e1);
  if (e2) console.error(e2);
  const weeks = [1, 2, 3, 4].map((week) => ({
    week: week + '주차',
    activities: (activities || []).filter((a) => a.week === week).map((a) => ({ who: a.who, badge: a.badge, title: a.title, sub: a.sub })),
    chapters: (chapters || []).filter((c) => c.week === week).map((c) => ({ no: c.no, title: c.title, sub: c.sub, time: c.time })),
  }));
  return weeks.filter((w) => w.activities.length || w.chapters.length);
}

async function fetchContentDownloads(contentId) {
  const { data, error } = await window.supabaseClient
    .from('content_downloads').select('*').eq('content_id', contentId);
  if (error) { console.error(error); return []; }
  return (data || []).map((d) => ({ kind: d.kind, file_url: d.file_url, file_label: d.file_label }));
}

async function fetchFamilyExtras(contentId) {
  const [{ data: family, error: e1 }, { data: videos, error: e2 }] = await Promise.all([
    window.supabaseClient.from('content_family_items').select('*').eq('content_id', contentId).order('slot'),
    window.supabaseClient.from('content_videos').select('*').eq('content_id', contentId).order('slot'),
  ]);
  if (e1) console.error(e1);
  if (e2) console.error(e2);
  return {
    family: (family || []).map((f) => ({ label: f.label, title: f.title, kind: f.kind, vol: f.vol, sub: f.sub, pastel: f.pastel })),
    videos: (videos || []).map((v) => ({ title: v.title, tag: v.tag, sub: v.sub, pastel: v.pastel })),
  };
}

Object.assign(window, { THEMES, PASTELS, CHARS, CATEGORIES, RECOMMENDED, TOPICS, DOWNLOAD_KINDS, DOWNLOAD_KIND_ICONS, fetchContentByStep, fetchContentByStepAndTrack, fetchWeeklyPlan, fetchFamilyExtras, fetchContentDownloads });
