/* global React */
const DICT = {
  ko: {
    // Nav
    home: '홈', market: '마켓', portfolio: '포트폴리오', live: '라이브',
    search: '검색', notifications: '알림', settings: '설정',
    profile: '프로필', myProfile: '내 프로필', notifySettings: '알림 설정',
    help: '도움말', logout: '로그아웃', backHome: '← 홈으로',
    backPortfolio: '← 포트폴리오로', backMarket: '마켓',
    closeBtn: '닫기',
    // Home
    title24h: '24시간 글로벌 자산 시장',
    subtitle24h: 'RWA, 토큰화 주식·채권, 온체인 수익형 자산을 한 화면에',
    rwaIndex: 'CRIV 종합지수 · 실시간',
    vol24Assets: (vol, n) => `24시간 거래대금 ${vol} · 편입자산 ${n}종`,
    hotAssets: '오늘의 강세 종목', hotSub: '거래대금이 늘고 가격 변동이 큰 자산',
    viewAll: '전체 보기 →', viewAllShort: '전체 →',
    premiumTitle: '토큰 ↔ 기초자산 가격차',
    premiumSub: '토큰 가격이 기초자산 대비 얼마나 벌어져 있는지 보여드려요',
    underlyingVs: (name) => `기초자산 ${name} 대비`,
    signals: '시장 시그널', signalsSub: '시스템이 포착한 주요 변화와 이벤트',
    liveLink: '라이브 →',
    yieldTitle: '배당형 자산', yieldSub: '보유만으로 분배금이 발생하는 온체인 자산',
    annualYield: '연환산 수익률', riskPill: (r) => `리스크 ${r}`,
    liveTalk: '지금 라이브 토크', liveTalkSub: '투자자들이 실시간으로 의견을 나누는 중',
    chatRoom: '채팅방 →',
    sevAlert: '경보', sevWatch: '주목', sevInfo: '안내', justNow: '방금 전',
    premium: '프리미엄', discount: '디스카운트', parity: '패리티',
    marketClosed: '휴장', marketEnded: '장 종료', regular: '정규장', preMarket: '프리마켓', afterHours: '애프터',
    krRegion: '🇰🇷 한국', usRegion: '🇺🇸 미국',
    // Market
    marketTitle: '마켓',
    marketSub: (n) => `총 ${n}종 · 24시간 거래소 가중평균 기준`,
    catAll: '전체', catStock: '주식형', catETF: 'ETF형', catBond: '채권형', catYield: '수익형', catCommodity: '원자재형',
    sortVol: '거래량 많은 순', sortGain: '많이 오른 순', sortLoss: '많이 내린 순',
    sortPremHi: '프리미엄 높은 순', sortPremLo: '실제보다 싼 순',
    countSuffix: (n) => `${n}개`,
    vsUnderlying: '기초자산 대비', vol24h: '24h 거래량',
    // Detail
    notFoundAsset: '해당 자산을 찾을 수 없습니다.',
    watched: '관심종목 등록됨', addWatch: '관심종목 추가',
    vsUnderlyingDelta: (name, pct, label) => `기초자산 ${name} 대비 ${pct} ${label}`,
    refPriceLine: (ref, tok) => `기초가 $${ref} · 토큰가 $${tok}`,
    minus3pctDisc: '−3% 디스카운트', parity0: '패리티', plus3pctPrem: '+3% 프리미엄',
    stat24Vol: '24시간 거래대금', stat30Avg: (s) => `30일 평균 대비 ${s}`,
    liquidity: '유동성', score: (s) => `스코어 ${s}/100`,
    risk: '리스크', issuer: '발행사', chainSuffix: (c) => `${c} 체인`,
    tabChart: '차트', tabCompare: '기초자산 비교', tabVenues: '거래소',
    tabLiquidity: '유동성', tabIssuer: '발행사·담보', tabRisk: '리스크', tabChat: '토론',
    priceChart: '가격 차트', last60candles: '최근 60 캔들 · 1시간 봉',
    tokenVsUnderlying: '토큰 vs 기초자산 가격',
    tokenVsHint: '두 가격이 가까울수록 차익거래가 효율적으로 작동하고 있어요',
    tokenLabel: (sym) => `토큰 ${sym}`,
    weightedAvg24h: '24시간 거래소 가중평균',
    underlyingLabel: (name) => `기초자산 ${name}`,
    referenceClose: '레퍼런스 마켓 종가',
    diffLine: (pct, usd) => `차이 ${pct} · $${usd}`,
    bigGapHint: '평소 대비 가격차가 크게 벌어진 상태예요. 차익거래 기회일 수 있지만, 진입 전 유동성과 환매 조건을 점검하세요.',
    stableHint: '기초자산과 근접한 가격대에서 안정적으로 거래되고 있어요.',
    venuesTitle: '주요 거래소',
    venuesRef: (p) => `기준가 $${p} · 거래소별 체결가`,
    venuesShareSub: '24시간 거래대금 점유율 기준',
    liquidityMetrics: '유동성 지표',
    liquidityScoreLabel: '유동성 스코어',
    of100: (label) => `100점 만점 · ${label}`,
    slip10k: '$10K 체결 슬리피지', slip100k: '$100K 체결 슬리피지', avgSpread: '평균 스프레드',
    estimate: '추정치', last24h: '최근 24시간',
    issuerCollateral: '발행사 · 담보 구조',
    custodian: '수탁기관', chainEmit: '발행 체인', redeemable: '환매 가능 여부', kycReq: 'KYC 요구',
    can: '가능', cannot: '불가', required: '필수', notRequired: '불필요',
    porLatest: '최신 준비금 증명(PoR)',
    porDetail: '담보 비율 100.2% · 2026-05-10 검증',
    riskBreakdown: '리스크 분해',
    discussion: '토론',
    me: '나', justNowChat: '방금',
    // Portfolio
    myPortfolio: '내 포트폴리오',
    portfolioSub: (n) => `${n}종 보유 · 수동 입력 데이터 기준`,
    totalValue: '총 평가자산',
    cumulPnl: '누적 손익', dayPnl: '금일 손익',
    weightedRisk: '가중 리스크',
    riskLow: '낮음', riskMid: '중간', riskHigh: '높음',
    allocation: '자산 배분', basedOnValue: '평가금액 기준',
    allocationByClassUSD: '자산군별 USD 평가금액 비중',
    holdings: '보유 종목', addHolding: '+ 종목 추가',
    watchlist: '관심종목', watchlistSub: '즐겨찾기로 등록한 종목',
    addHoldingTitle: '종목 추가',
    addHoldingPickHint: '보유한 자산을 선택하세요',
    addHoldingInputHint: '수량과 평균 매수가를 입력하세요',
    buyInfoTitle: (sym) => `${sym} 매수 정보 입력`,
    searchSymbol: '종목명 또는 심볼 검색',
    noResults: '검색 결과가 없어요',
    currentPrice: '현재가',
    qtyHeld: '보유 수량', avgCost: '평균 매수가 (USD)',
    buyDate: '매수 일자',
    buyVenue: (n) => `구매 거래소 · 활성마켓 ${n}곳`,
    totalCost: '총 매수금액',
    prev: '이전', addToPortfolio: '포트폴리오에 추가',
    tokenUnit: '토큰',
    periodPnl: '기간 손익',
    addedToast: (sym, qty) => `${sym} ${qty}토큰 추가됨`,
    // Holding detail
    holdingNotFound: '보유 종목을 찾을 수 없습니다.',
    myPosition: '내 포지션', marketDetail: '마켓 상세 →',
    evalValue: '평가금액', evalPnl: '평가손익', acqValue: '취득가액',
    qtyTimesPrice: (q, p) => `${q} 토큰 × $${p}`,
    sinceBuy: '매수일 이후 추이',
    costToNow: (c, n) => `취득가 $${c} → 현재 $${n}`,
    heldDuration: '보유 기간', daysSuffix: (d) => `${d}일`,
    positionInfo: '포지션 정보',
    buyDateLabel: '매수 일자', heldQty: '보유 수량', avgBuy: '평균 매수가',
    nowPrice: '현재가', purchaseVenue: '구매 거래소', assetClass: '자산 분류',
    yieldAnalysis: '수익률 분석',
    cumulYield: '누적 수익률', annYield: '연환산 수익률',
    pnlUSD: '손익 (USD)', pnlKRW: '손익 (KRW)',
    change24Label: '24시간 변동',
    costBasis: (p) => `취득가 $${p}`,
    // Live
    liveTitle: '라이브',
    liveSub: '실시간 토론, 시장 이벤트, 투자자 인사이트를 한 곳에서',
    allFeed: '전체 피드', systemFeed: '시스템 피드', generalRoom: '전체 대화방',
    roomPriceLabel: '현재가', roomPremiumLabel: '프리미엄', roomChangeLabel: '24h',
    roomHeader: (sym) => `${sym} 토론방`,
    roomHeaderSub: '실시간 가격·시그널을 보면서 의견을 나누세요',
    systemFeedSub: '시스템이 자동으로 감지한 시장 이벤트',
    generalRoomSub: '종목과 무관한 시장 전반에 대한 자유로운 토론',
    chatPlaceholderAll: '시장에 대한 의견을 공유해보세요',
    chatPlaceholderRoom: (label) => `${label} 토론방에 메시지`,
    sendBtn: '전송',
    system: '시스템',
    minsAgo: (m) => `${m}분 전`,
    activeRooms: '활발한 토론방',
    activeRoomsSub: '최근 30분 메시지 빈도 기준',
    participantsCount: (n) => `${n}명 참여`,
    // Settings
    settingsTitle: '설정', settingsSub: '프로필과 알림 환경을 관리하세요',
    avatarColor: '아바타 컬러', avatarImage: '프로필 이미지',
    uploadImage: '이미지 업로드', removeImage: '이미지 제거',
    saveChanges: '변경사항 저장', saved: '✓ 저장됨', revert: '되돌리기',
    preferences: '환경설정',
    baseCurrency: '기준 통화', baseCurrencySub: '평가금액 표시에 사용됩니다',
    priceAlerts: '가격 알림', priceAlertsSub: '관심종목이 설정한 가격에 도달하면 알림',
    marketOpenAlerts: '시장 개장 알림', marketOpenSub: '한국·미국 시장 개장 5분 전 알림',
    chatAlerts: '라이브 채팅 알림', chatAlertsSub: '멘션과 새 메시지',
    language: '언어', languageSub: '인터페이스 표시 언어',
    nickname: '닉네임', email: '이메일', password: '비밀번호',
    login: '로그인', signup: '가입하기', signupCta: '가입하고 시작하기',
    loginTitle: 'CRIV에 로그인', signupTitle: '계정 만들기',
    loginSub: '토큰화 자산을 한 화면에서 관리하세요',
    signupSub: '몇 가지 정보만 입력하면 시작할 수 있어요',
    noAccount: '계정이 없으신가요?', hasAccount: '이미 계정이 있나요?',
    or: '또는', continueGoogle: 'Google로 계속하기', continueApple: 'Apple로 계속하기',
    // Search
    searchPlaceholder: '종목, 발행사, 섹터 검색',
    searchEmpty: '검색 결과가 없습니다',
    // Notifications panel
    notifTitle: '알림', alertPill: '알림',
  },
  en: {
    home: 'Home', market: 'Market', portfolio: 'Portfolio', live: 'Live',
    search: 'Search', notifications: 'Notifications', settings: 'Settings',
    profile: 'Profile', myProfile: 'My profile', notifySettings: 'Alert settings',
    help: 'Help', logout: 'Sign out', backHome: '← Back to home',
    backPortfolio: '← Back to portfolio', backMarket: 'Market',
    closeBtn: 'Close',
    title24h: '24-hour global asset market',
    subtitle24h: 'RWA, tokenized stocks & bonds, on-chain yield in one view',
    rwaIndex: 'CRIV composite index · Live',
    vol24Assets: (vol, n) => `24h volume ${vol} · ${n} assets tracked`,
    hotAssets: "Today's movers", hotSub: 'Assets with rising volume and price action',
    viewAll: 'View all →', viewAllShort: 'All →',
    premiumTitle: 'Token ↔ Underlying premium',
    premiumSub: 'See how far token prices diverge from their underlyings',
    underlyingVs: (name) => `vs underlying ${name}`,
    signals: 'Market signals', signalsSub: 'Key changes and events the system caught',
    liveLink: 'Live →',
    yieldTitle: 'Yield-bearing assets', yieldSub: 'On-chain assets that pay distributions just by holding',
    annualYield: 'Annualized yield', riskPill: (r) => `Risk ${r}`,
    liveTalk: 'Live talk right now', liveTalkSub: 'Investors are chatting in real time',
    chatRoom: 'Chat room →',
    sevAlert: 'Alert', sevWatch: 'Watch', sevInfo: 'Info', justNow: 'Just now',
    premium: 'premium', discount: 'discount', parity: 'parity',
    marketClosed: 'Closed', marketEnded: 'After close', regular: 'Regular', preMarket: 'Pre-market', afterHours: 'After hours',
    krRegion: '🇰🇷 Korea', usRegion: '🇺🇸 USA',
    marketTitle: 'Market',
    marketSub: (n) => `${n} assets · 24h volume-weighted average`,
    catAll: 'All', catStock: 'Stocks', catETF: 'ETFs', catBond: 'Bonds', catYield: 'Yield', catCommodity: 'Commodities',
    sortVol: 'Highest volume', sortGain: 'Top gainers', sortLoss: 'Top losers',
    sortPremHi: 'Highest premium', sortPremLo: 'Largest discount',
    countSuffix: (n) => `${n}`,
    vsUnderlying: 'vs underlying', vol24h: '24h volume',
    notFoundAsset: 'Asset not found.',
    watched: 'In watchlist', addWatch: 'Add to watchlist',
    vsUnderlyingDelta: (name, pct, label) => `vs underlying ${name}: ${pct} ${label}`,
    refPriceLine: (ref, tok) => `Ref $${ref} · Token $${tok}`,
    minus3pctDisc: '−3% discount', parity0: 'Parity', plus3pctPrem: '+3% premium',
    stat24Vol: '24h volume', stat30Avg: (s) => `${s} vs 30d avg`,
    liquidity: 'Liquidity', score: (s) => `Score ${s}/100`,
    risk: 'Risk', issuer: 'Issuer', chainSuffix: (c) => `${c} chain`,
    tabChart: 'Chart', tabCompare: 'Compare', tabVenues: 'Venues',
    tabLiquidity: 'Liquidity', tabIssuer: 'Issuer & collateral', tabRisk: 'Risk', tabChat: 'Discussion',
    priceChart: 'Price chart', last60candles: 'Last 60 candles · 1H',
    tokenVsUnderlying: 'Token vs underlying price',
    tokenVsHint: 'The closer the prices, the more efficient the arbitrage',
    tokenLabel: (sym) => `Token ${sym}`,
    weightedAvg24h: '24h volume-weighted',
    underlyingLabel: (name) => `Underlying ${name}`,
    referenceClose: 'Reference market close',
    diffLine: (pct, usd) => `Spread ${pct} · $${usd}`,
    bigGapHint: 'The spread is unusually wide. An arb opportunity may exist — verify liquidity and redemption terms first.',
    stableHint: 'Trading close to the underlying price.',
    venuesTitle: 'Top venues',
    venuesRef: (p) => `Ref $${p} · per-venue print`,
    venuesShareSub: 'Ranked by 24h volume share',
    liquidityMetrics: 'Liquidity metrics',
    liquidityScoreLabel: 'Liquidity score',
    of100: (label) => `out of 100 · ${label}`,
    slip10k: '$10K slippage', slip100k: '$100K slippage', avgSpread: 'Avg spread',
    estimate: 'estimate', last24h: 'last 24h',
    issuerCollateral: 'Issuer & collateral',
    custodian: 'Custodian', chainEmit: 'Issue chain', redeemable: 'Redeemable', kycReq: 'KYC required',
    can: 'Yes', cannot: 'No', required: 'Required', notRequired: 'Not required',
    porLatest: 'Latest Proof of Reserves',
    porDetail: 'Collateral ratio 100.2% · attested 2026-05-10',
    riskBreakdown: 'Risk breakdown',
    discussion: 'Discussion',
    me: 'Me', justNowChat: 'now',
    myPortfolio: 'My portfolio',
    portfolioSub: (n) => `${n} holdings · manual entry`,
    totalValue: 'Total value',
    cumulPnl: 'Total P&L', dayPnl: "Today's P&L",
    weightedRisk: 'Weighted risk',
    riskLow: 'Low', riskMid: 'Mid', riskHigh: 'High',
    allocation: 'Allocation', basedOnValue: 'by market value',
    allocationByClassUSD: 'USD value share by asset class',
    holdings: 'Holdings', addHolding: '+ Add holding',
    watchlist: 'Watchlist', watchlistSub: 'Your starred assets',
    addHoldingTitle: 'Add holding',
    addHoldingPickHint: 'Pick an asset you own',
    addHoldingInputHint: 'Enter quantity and average cost',
    buyInfoTitle: (sym) => `${sym} buy info`,
    searchSymbol: 'Search name or symbol',
    noResults: 'No results',
    currentPrice: 'Now',
    qtyHeld: 'Quantity', avgCost: 'Average cost (USD)',
    buyDate: 'Buy date',
    buyVenue: (n) => `Buy venue · ${n} active markets`,
    totalCost: 'Total cost',
    prev: 'Back', addToPortfolio: 'Add to portfolio',
    tokenUnit: 'tokens',
    periodPnl: 'Period P&L',
    addedToast: (sym, qty) => `${sym} ${qty} tokens added`,
    holdingNotFound: 'Holding not found.',
    myPosition: 'My position', marketDetail: 'Market detail →',
    evalValue: 'Market value', evalPnl: 'Unrealized P&L', acqValue: 'Cost basis',
    qtyTimesPrice: (q, p) => `${q} tokens × $${p}`,
    sinceBuy: 'Since purchase',
    costToNow: (c, n) => `Cost $${c} → Now $${n}`,
    heldDuration: 'Hold duration', daysSuffix: (d) => `${d} days`,
    positionInfo: 'Position info',
    buyDateLabel: 'Buy date', heldQty: 'Quantity', avgBuy: 'Avg buy price',
    nowPrice: 'Current price', purchaseVenue: 'Buy venue', assetClass: 'Class',
    yieldAnalysis: 'Return analysis',
    cumulYield: 'Total return', annYield: 'Annualized',
    pnlUSD: 'P&L (USD)', pnlKRW: 'P&L (KRW)',
    change24Label: '24h change',
    costBasis: (p) => `Cost basis $${p}`,
    liveTitle: 'Live',
    liveSub: 'Real-time discussion, market events, investor insight in one place',
    allFeed: 'All feed', systemFeed: 'System feed', generalRoom: 'General room',
    roomPriceLabel: 'Price', roomPremiumLabel: 'Premium', roomChangeLabel: '24h',
    roomHeader: (sym) => `${sym} room`,
    roomHeaderSub: 'Watch live price & signals while you chat',
    systemFeedSub: 'Market events the system auto-detected',
    generalRoomSub: 'Free-form market talk, any topic',
    chatPlaceholderAll: 'Share your view on the market',
    chatPlaceholderRoom: (label) => `Message ${label} room`,
    sendBtn: 'Send',
    system: 'System',
    minsAgo: (m) => `${m}m ago`,
    activeRooms: 'Active rooms',
    activeRoomsSub: 'Ranked by message frequency, last 30 min',
    participantsCount: (n) => `${n} active`,
    settingsTitle: 'Settings', settingsSub: 'Manage your profile and alerts',
    avatarColor: 'Avatar color', avatarImage: 'Profile image',
    uploadImage: 'Upload image', removeImage: 'Remove image',
    saveChanges: 'Save changes', saved: '✓ Saved', revert: 'Revert',
    preferences: 'Preferences',
    baseCurrency: 'Base currency', baseCurrencySub: 'Used for valuation display',
    priceAlerts: 'Price alerts', priceAlertsSub: 'Notify when watchlist hits target',
    marketOpenAlerts: 'Market open alerts', marketOpenSub: 'Alert 5 min before KR/US open',
    chatAlerts: 'Live chat alerts', chatAlertsSub: 'Mentions and new messages',
    language: 'Language', languageSub: 'Interface display language',
    nickname: 'Nickname', email: 'Email', password: 'Password',
    login: 'Sign in', signup: 'Sign up', signupCta: 'Create account & start',
    loginTitle: 'Sign in to CRIV', signupTitle: 'Create your account',
    loginSub: 'Manage tokenized assets in one place',
    signupSub: 'Just a few details to get started',
    noAccount: "Don't have an account?", hasAccount: 'Already have an account?',
    or: 'or', continueGoogle: 'Continue with Google', continueApple: 'Continue with Apple',
    searchPlaceholder: 'Search symbol, issuer, sector',
    searchEmpty: 'No results',
    notifTitle: 'Notifications', alertPill: 'Alert',
  },
};

function loadLang() {
  try { return localStorage.getItem('clab-lang') === 'en' ? 'en' : 'ko'; } catch (e) { return 'ko'; }
}

function makeT(lang) {
  const d = DICT[lang] || DICT.ko;
  return (k, ...args) => {
    const v = d[k] !== undefined ? d[k] : DICT.ko[k];
    if (typeof v === 'function') return v(...args);
    return v !== undefined ? v : k;
  };
}

const LangContext = React.createContext('ko');
function useT() {
  const lang = React.useContext(LangContext);
  return makeT(lang);
}
function useLang() { return React.useContext(LangContext); }

Object.assign(window, { DICT, loadLang, makeT, LangContext, useT, useLang });
