// Triplicity · Little Stars — KIDS internationalisation (中文 / English)
// A lightweight language layer for the kids flow. The interpretation TEXT flips
// by swapping window.INTERPRETATIONS between the zh + en JSON files (preloaded
// in app-kids.jsx). UI chrome flips via kt('中文') lookups. Data labels (planet
// / sign names, roles, house taglines) flip by swapping the window.* maps that
// chart-data.jsx's planetView() reads, then rebuilding the derived chart data.

// Current language — read at render time by kt()/kpick()/klang().
window.KID_LANG = window.KID_LANG || 'zh';
function klang(){ return window.KID_LANG || 'zh'; }
function kpick(zh, en){ return klang() === 'en' ? en : zh; }

const KidLangCtx = React.createContext({ lang:'zh', setLang:()=>{} });
function useKidLang(){ return React.useContext(KidLangCtx); }

// ── Chinese → English UI dictionary ─────────────────────────────────────────
// Keyed by the exact Chinese string used in the components. kt() returns the
// Chinese unchanged in zh mode, or the English value in en mode.
const KID_T = {
  // brand
  '親子星盤':'Little Stars',
  // steps — eyebrows / headings
  'STEP ONE · 孩子的資料':'STEP ONE · ABOUT YOUR CHILD',
  'STEP TWO · 出生資訊':'STEP TWO · BIRTH DETAILS',
  '免費親子星盤 · FREE BIRTH CHART':'FREE BIRTH CHART',
  'STEP 01 OF 03 · 出生資訊':'STEP 01 OF 03 · BIRTH DETAILS',
  'STEP 02 OF 03 · 出生資訊':'STEP 02 OF 03 · BIRTH DETAILS',
  '先記住\n孩子的名字':"First, remember\nyour child's name",
  '先讓星空\n記住孩子的名字':"Let the stars\nremember your child's name",
  '先為孩子建立\n小星星檔案':"Create your child's\nlittle star profile",
  '孩子\n來到世界那一刻':'The moment\nyour child arrived',
  '孩子來到\n世界的那一刻':'The moment your\nchild came into the world',
  '天空正為\n孩子排好位置':'The sky is setting\nplaces for your child',
  '這份星空圖，是為你的孩子而畫的。':'This star map is drawn just for your child.',
  '星盤不是預言，而是一種更溫柔地認識孩子的方式。我們先從孩子的小資料開始。':"A birth chart isn't a prophecy — it's a gentler way of getting to know your child. Let's start with a few small details.",
  '星盤不是預言，也不是替孩子定型':"A birth chart is not a prediction, and it does not define your child.",
  '孩子不是一本需要被改寫的書，\n而是一片需要被理解的星空。':"Your child is not a book to be rewritten,\nbut a sky waiting to be understood.",
  '時間越準確，星空圖就越貼近他。':'The more precise the time, the closer the star map is to them.',
  '出生的日期、時間與地點，決定了天空當時的模樣。越準確，孩子的星空圖就越貼近他。':"The date, time and place of birth decide what the sky looked like then. The more accurate, the closer your child's star map will be.",
  '我們會用出生資料計算太陽、月亮、上升與宮位，畫出孩子來到世界那一刻的星空。':"We'll use the birth details to calculate the Sun, Moon, Rising sign and houses, then draw the sky from the moment your child arrived.",
  '我們正在計算每一顆星星的位置，為孩子畫出獨一無二的星空圖。只要一會兒。':"We're calculating the position of every star to draw a one-of-a-kind star map for your child. Just a moment.",
  '正在畫出孩子的星空':"Drawing your child's sky",
  'SOFT NOTE':'SOFT NOTE',
  // steps — fields / buttons
  '孩子的稱呼':"Child's name",
  '例如：小星':'e.g. Star',
  '性別':'Gender',
  '家長電郵':"Parent's email",
  '接收報告的電郵':'Email to receive the report',
  '把星空圖寄給你':"We'll email you the star map",
  '下一步':'Next',
  '繼續':'Continue',
  '繼續填寫出生資料':'Continue to birth details',
  '🤍 資料只用來繪製星盤，安心保密':'🤍 Details are only used to draw the chart — kept private.',
  '出生日期':'Birth date',
  '出生時間':'Birth time',
  '出生地點':'Birth place',
  '不確定':'Not sure',
  '開始輸入城市…':'Start typing a city…',
  '香港 · Hong Kong':'Hong Kong',
  '例如：香港 / 台北 / London':'e.g. Hong Kong / Taipei / London',
  '✦ 不記得確切時間也沒關係，我們會用中午為他估算。':"✦ Don't recall the exact time? No problem — we'll estimate using midday.",
  '繪製中…':'Drawing…',
  '畫出星空':'Draw the sky',
  '畫出孩子的星空':"Draw your child's sky",
  '請填寫孩子的稱呼。':"Please enter your child's name.",
  '請填寫有效的電郵地址。':'Please enter a valid email address.',
  '請選擇出生日期。':'Please choose the birth date.',
  '請選擇出生時間，或點「不確定」。':'Please choose a birth time, or select "Not sure".',
  '請從清單中選擇出生城市。':'Please choose a birth city from the list.',
  '人機驗證未通過，請再試一次。':'Verification did not pass. Please try again.',
  '女孩':'Girl', '男孩':'Boy', '還不確定':'Not sure yet', '暫未確定':'Not decided yet', '不便透露':'Prefer not to say',
  // step status lines
  '正在收集孩子的星光…':"Gathering your child's starlight…",
  '排好天空的位置…':'Placing the sky…',
  '畫出每顆小行星…':'Drawing each little planet…',
  '連起星座的線…':'Connecting the constellations…',
  '完成孩子的星空圖！':"Your child's star map is ready!",
  // result — section titles (cnTitle)
  '點亮孩子的三顆星':"Your Child's Big Three",
  '守護孩子的小天使':"Your Child's Guardian Star",
  '行星星座解讀':'Planets in Signs',
  '天賦星群':'Star Clusters',
  '元素氣質':'Elements & Temperament',
  '天生特質':'Soul Type',
  '生活重心':'Life Focus',
  '十二個生活面向':'Twelve Life Areas',
  // result — chrome
  '孩子的三顆星 · THE BIG THREE':'THE BIG THREE',
  '太陽是孩子天生的性格，月亮是他的情緒與安全感，上升是別人初次見到的他——這三顆星，是認識小小宇宙的起點。':"The Sun is your child's natural character, the Moon their emotions and security, the Rising the first thing others see — these three stars are the starting point for knowing their little universe.",
  '天賦星群':'Star Cluster',  // duplicate key note: same as section; tag reuse
  '解鎖看更多':'Unlock to see more',
  '完整版':'Full',
  '免費':'Free',
  '解鎖完整解讀':'Unlock full reading',
  'FREE PREVIEW · 免費預覽':'FREE PREVIEW',
  '下載 PDF':'Download PDF',
  '更多 · MORE':'MORE',
  '《個人星盤書》':'The Birth Chart Book',
  '親子占星課程':'Parent-Child Astrology Course',
  '隨時升級 · 解鎖更多':'Upgrade anytime · unlock more',
  '深度報告 · A4 PDF':'Deep report · A4 PDF',
  '行星報告 · A4 PDF':'Planet report · A4 PDF',
  '解鎖 ✦':'Unlock ✦',
  '分享給家人':'Share', '收藏':'Save',
  '已收藏':'Saved',
  '星盤連結已複製，可以貼給家人。':'Chart link copied. You can send it to family.',
  '請複製瀏覽器網址分享給家人。':'Please copy the browser URL to share with family.',
  '已收藏此星盤，網址亦已複製。':'Chart saved, and the URL was copied too.',
  '已收藏此星盤。':'Chart saved.',
  'Safari 及手機瀏覽器暫不支援 PDF 下載；其他電腦版瀏覽器可正常下載。':'PDF download is not supported in Safari or mobile browsers yet. Please use another desktop browser.',
  '隨時升級 · 解鎖更多':'Upgrade anytime · unlock more',
  // tier badges / chips
  '解讀':'Reading', '深度':'Deep',
  // free upgrade banner + pricing
  '升級 $128 · 解鎖完整親子解讀：天賦星群 · 元素氣質 · 12 個生活面向的相處建議 →':'Upgrade to $128 · unlock the full reading: star clusters · elements · parenting tips for 12 life areas →',
  '解鎖完整親子解讀 · UNLOCK FULL READING':'UNLOCK FULL READING',
  '升級完整親子解讀 · UPGRADE TO FULL':'UPGRADE TO FULL',
  '最受歡迎':'Most popular',
  '立即解鎖':'Unlock now',
  '套用':'Apply',
  '輸入優惠碼':'Enter promo code',
  '優惠碼無效，請再確認。':'Invalid promo code — please check again.',
  // tier cards
  '行星星座解讀':'Planets in Signs',
  '完整親子解讀':'Full Reading',
  '守護孩子的小天使（個人守護星）':"Your child's guardian star (chart ruler)",
  '13 顆行星的完整解讀':'Full reading of all 13 planets',
  '太陽 · 月亮 · 上升詳細說明':'Sun · Moon · Rising in detail',
  '適合陪孩子一起讀的 PDF':'A PDF to read with your child',
  '$78 的全部內容':'Everything in $78',
  '你已擁有的 $78 全部內容':'Everything you already have in $78',
  '守護星所在宮位的深入解讀':"Deep reading of the guardian star's house",
  '元素 · 模式 · 天生氣質分析':'Element · modality · temperament analysis',
  '12 個生活面向的相處建議':'Parenting tips across 12 life areas',
  '可收藏的深度 PDF 報告':'A keepsake deep-dive PDF report',
  // promo
  '由 Rubie 為你準備 · MORE FROM TRIPLICITY':'CURATED BY RUBIE · MORE FROM TRIPLICITY',
  '想將孩子的星盤化為珍藏？':'Turn your child\u2019s chart into a keepsake?',
  '由 Rubie 根據孩子的星盤親筆撰寫，全彩精裝 150 頁——送禮或自用的終極占星珍藏。':'Hand-written by Rubie from your child\u2019s chart — a 150-page full-colour hardcover, the ultimate astrology keepsake to gift or keep.',
  '了解《個人星盤書》':'Explore the Birth Chart Book',
  '150 頁深度解讀':'150 pages of depth', '全彩精裝實體書':'Full-colour hardcover', '占星師親筆撰寫':'Written by the astrologer', '個人化封面設計':'Personalised cover',
  '想親手看懂孩子的星盤？':'Want to read your child\u2019s chart yourself?',
  'Rubie 親授——從零開始學會解讀孩子的星盤，成為最懂孩子內心世界的爸媽。':'Taught by Rubie — learn to read your child\u2019s chart from scratch and become the parent who understands their inner world best.',
  '了解親子占星課程':'Explore the course',
  '親子占星專修':'Parent-child focus', '實際案例教學':'Real case studies', '無需占星基礎':'No prior astrology needed', '終身回看課程':'Lifetime access',
  // paid — energy / elements / modalities
  '元素氣質 · ELEMENTS':'ELEMENTS',
  '做事節奏 · MODALITIES':'MODALITIES',
  '天生特質 · SOUL TYPE':'SOUL TYPE',
  '個人守護星 · CHART RULER':'CHART RULER',
  '標記的，是上方「天賦星群」裡集中發光的星星與生活面向——孩子的天賦，特別在這裡聚在一起。':'The marked stars and life areas are the ones glowing together in the "Star Clusters" above — where your child\u2019s gifts especially gather.',
  // elements labels
  '火':'Fire','土':'Earth','風':'Air','水':'Water',
  '熱情 · 行動':'Warmth · action','踏實 · 穩定':'Grounded · steady','好奇 · 靈活':'Curious · flexible','細膩 · 感受':'Sensitive · feeling',
  '開創':'Cardinal','穩定':'Fixed','彈性':'Mutable',
  '最突出':'Strongest','平衡':'Balanced','較少':'Lower',
  // hemispheres
  '外向 · 探索世界':'Outward · exploring','內向 · 安心做自己':'Inward · at ease','主動 · 帶頭':'Active · leading','回應 · 重視關係':'Responsive · relational',
  '生活重心':'Life Focus',
  // chart ruler
  '守護星住在第 {n} 宮':'Guardian star in House {n}',
  '示意文字 · 實際守護星解讀稍後提供':'Sample text · full guardian-star reading coming soon',
  '示意文字 · 實際守護星宮位解讀稍後提供':'Sample text · full guardian-star house reading coming soon',
  // tier head titles handled via kt with {name}
  '免費預覽 · A GLIMPSE OF THEIR SKY':'A GLIMPSE OF THEIR SKY',
  // ── PDF report chrome ──
  '親子星盤報告':'BIRTH CHART REPORT',
  '親子星盤 · TRIPLICITY LITTLE STARS':'LITTLE STARS · TRIPLICITY',
  '親子星盤':'Little Stars',
  '陪孩子一起看的星空圖':'A star map to explore together',
  'TRIPLICITY · LITTLE STARS · 親子星盤':'TRIPLICITY · LITTLE STARS',
  '返回':'Back',
  'PDF 預覽':'PDF preview',
  '正在生成 PDF...':'Generating PDF...',
  'PDF 工具仍在載入中，請稍後再試。':'PDF tools are still loading. Please try again shortly.',
  'PDF 生成失敗，請返回原頁面再試一次。':'PDF generation failed. Please return to the original page and try again.',
  'PDF 生成失敗，請稍後再試。':'PDF generation failed. Please try again later.',
  '貼身的小行星':'Personal Planets',
  '深層的行星':'Outer Planets & Points',
  '完整親子解讀':'Full Reading',
  '守護星資料準備中。':'Guardian-star data is being prepared.',
  '每張星盤都有一顆「帶頭的星」——上升星座的守護星。它像守護孩子的小天使，把自己的特質，輕輕染上孩子看世界與向前走的方式。':'Every chart has a "leading star" — the ruler of the Rising sign. Like a guardian angel, it gently colours how your child sees the world and moves forward.',
  '個人守護星 · CHART RULER':'CHART RULER',
  '太陽是孩子天生的性格，月亮是他的情緒與安全感，上升是別人初次見到的他——這三顆星，是認識孩子的起點。':"The Sun is your child's natural character, the Moon their emotions and security, the Rising the first self others meet — these three stars are the starting point for knowing them.",
  '元素氣質 · 天生特質':'Elements · Soul Type',
  '天生特質 · SOUL TYPE':'SOUL TYPE',
  '天賦星群 · 生活重心':'Star Clusters · Life Focus',
  'WHERE THEY SHINE':'WHERE THEY SHINE',
  '天賦星群 · STAR CLUSTERS':'STAR CLUSTERS',
  '生活重心 · LIFE FOCUS':'LIFE FOCUS',
  '每個生活面向，都有一顆星座在背後輕輕影響著孩子在那裡的樣子。':'Each area of life has a sign quietly shaping how your child shows up there.',
  '✦ 天賦星群':'✦ Star cluster',
  '行星星座解讀 · PLANET-IN-SIGN':'PLANET-IN-SIGN',
  '完整親子解讀 · FULL READING':'FULL READING',
  // site nav
  '首頁':'Home','關於我們':'About','課程介紹':'Courses','學員分享':'Students','免費星盤':'Free Chart',
  '免費資源':'Free Resources','服務一覽':'Services','會員計劃':'Membership','占星產品':'Shop',
  '占星館':'ASTROLOGY','登入學習平台':'Log in','探索課程':'Explore courses',
};
function kt(zh){
  if (klang() !== 'en') return zh;
  return (KID_T[zh] !== undefined) ? KID_T[zh] : zh;
}
// Always-English lookup (used for the bilingual generation page, regardless of lang).
function kten(zh){ return (KID_T[zh] !== undefined) ? KID_T[zh] : zh; }
// Multi-line: render a kt string that may contain \n as <br/>-separated lines.
function KML({ children }){
  const s = String(children || '');
  const parts = s.split('\n');
  return parts.map((line,i)=> i===0 ? line : [React.createElement('br',{key:'br'+i}), line]);
}

// ── English data maps (swapped into window.* in en mode) ────────────────────
const KID_SIGN_EN = { Aries:'Aries', Taurus:'Taurus', Gemini:'Gemini', Cancer:'Cancer',
  Leo:'Leo', Virgo:'Virgo', Libra:'Libra', Scorpio:'Scorpio', Sagittarius:'Sagittarius',
  Capricorn:'Capricorn', Aquarius:'Aquarius', Pisces:'Pisces' };
const KID_PLANET_EN_MAP = { Sun:'Sun', Moon:'Moon', Mercury:'Mercury', Venus:'Venus', Mars:'Mars',
  Jupiter:'Jupiter', Saturn:'Saturn', Uranus:'Uranus', Neptune:'Neptune', Pluto:'Pluto',
  Chiron:'Chiron', 'North Node':'North Node', 'South Node':'South Node', Ascendant:'Rising', MC:'MC' };
const KID_HOUSE_TAGLINE_EN = {
  1:'Self & Character', 2:'Security & Having', 3:'Learning & Expression', 4:'Home & Belonging',
  5:'Play & Creating', 6:'Routine & Habits', 7:'Friends & Relating', 8:'Feeling & Trust',
  9:'Exploring & Belief', 10:'Aspiration & Approval', 11:'Community & Dreams', 12:'Inner World & Imagination',
};
const KID_PLANET_ROLE_EN = {
  Sun:'Core Character · Who They Naturally Are',
  Moon:'Their Emotions & Need for Security',
  Ascendant:'The First Self Others Meet',
  Mercury:'How They Think & Express',
  Venus:'Tastes & How They Show Love',
  Mars:'Drive & Little Temper',
  Jupiter:'Gifts & Room to Grow',
  Saturn:'Lessons to Practise Slowly',
  Uranus:'Their One-of-a-Kind Spark',
  Neptune:'Imagination & the World of Dreams',
  Pluto:'Inner Resilience',
  Chiron:'Tender Spots & Healing Gifts',
  'North Node':'The Direction They Want to Grow Toward',
  'South Node':'Skills They Were Born Knowing',
};
function kidRoleLabel(p){
  if (klang() === 'en') return KID_PLANET_ROLE_EN[p.name] || p.role || '';
  return (window.KID_PLANET_ROLE && window.KID_PLANET_ROLE[p.cn]) || p.role || '';
}
function kidHouseTag(h){
  return klang()==='en' ? (KID_HOUSE_TAGLINE_EN[h] || '') : (window.KID_HOUSE_TAGLINE && window.KID_HOUSE_TAGLINE[h] || '');
}
// suffix-aware sign label: "天秤座" in zh, "Libra" in en (no 座)
function kidSignSuffix(signNoSuffix, signFull){ return klang()==='en' ? signFull : (signNoSuffix + '座'); }

// ── Apply a language: swap maps + interpretations, rebuild derived data ──────
let _KID_ZH_MAPS = null;
function kidApplyLang(lang){
  if (!_KID_ZH_MAPS){
    _KID_ZH_MAPS = {
      SIGN_ZH: window.SIGN_ZH, PLANET_ZH: window.PLANET_ZH,
      PLANET_ROLE: window.PLANET_ROLE, HOUSE_TAGLINE: window.HOUSE_TAGLINE,
    };
  }
  window.KID_LANG = lang;
  if (lang === 'en'){
    window.SIGN_ZH = KID_SIGN_EN;
    window.PLANET_ZH = KID_PLANET_EN_MAP;
    window.PLANET_ROLE = KID_PLANET_ROLE_EN;
    window.HOUSE_TAGLINE = KID_HOUSE_TAGLINE_EN;
  } else {
    window.SIGN_ZH = _KID_ZH_MAPS.SIGN_ZH;
    window.PLANET_ZH = _KID_ZH_MAPS.PLANET_ZH;
    window.PLANET_ROLE = _KID_ZH_MAPS.PLANET_ROLE;
    window.HOUSE_TAGLINE = _KID_ZH_MAPS.HOUSE_TAGLINE;
  }
  // swap interpretation text (preloaded by app-kids.jsx)
  if (window.KID_INTERP && window.KID_INTERP[lang]) {
    window.INTERP = window.KID_INTERP[lang];
    window.INTERPRETATIONS = window.KID_INTERP[lang];
  }
  // rebuild the decorated chart data so cn/signZh/role/interp text refresh
  if (window.ccRebuildCurrentChart) window.ccRebuildCurrentChart();
  else {
    window.buildDerivedChartData?.();
    window.buildChartRuler?.();
  }
}

// ── Toggle control (中文 / English) ─────────────────────────────────────────
function KidLangToggle({ compact = false, light = false, style }){
  const { lang, setLang } = useKidLang();
  const activeBg = light ? '#0B1A33' : 'rgba(147,166,236,0.95)';
  const activeFg = light ? '#FFFFFF' : '#0B1A33';
  const opt = (val, label) => (
    <button onClick={()=>setLang(val)} style={{
      padding: compact?'5px 11px':'6px 13px', border:0, cursor:'pointer', borderRadius:999,
      fontFamily: val==='en' ? KID.en : KID.zh, fontSize: compact?11.5:12.5, fontWeight:700, letterSpacing:'0.02em',
      background: lang===val ? activeBg : 'transparent',
      color: lang===val ? activeFg : (light ? '#6B7793' : KID.gray), transition:'all .15s', whiteSpace:'nowrap'}}>{label}</button>
  );
  return (
    <div style={{display:'inline-flex', alignItems:'center', gap:2, padding:3, borderRadius:999,
      background: light ? 'rgba(11,26,51,0.06)' : 'rgba(11,26,51,0.7)',
      border:`1px solid ${light ? 'rgba(11,26,51,0.12)' : KID.line}`, backdropFilter:'blur(6px)', ...style}}>
      {opt('zh','中文')}
      {opt('en','EN')}
    </div>
  );
}

Object.assign(window, {
  klang, kpick, kt, kten, KML, KidLangCtx, useKidLang,
  KID_SIGN_EN, KID_PLANET_EN_MAP, KID_HOUSE_TAGLINE_EN, KID_PLANET_ROLE_EN,
  kidRoleLabel, kidHouseTag, kidSignSuffix, kidApplyLang, KidLangToggle,
});
