"use client"

import React, { createContext, useContext, useState, useEffect } from "react"

type Language = "ko" | "en"

interface LanguageContextType {
  language: Language
  setLanguage: (lang: Language) => void
  t: (key: string) => string
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined)

// Translation dictionary
const translations: Record<Language, Record<string, string>> = {
  ko: {
    // Header
    "header.season": "Season 2",
    "header.openSource": "Open Source",
    "header.tooltip.openSource": "AI 기반 주식 분석 및 매매 시스템 • MIT License",
    "header.startDate": "시작: 2025.09.29",
    "header.updated": "업데이트",
    "header.realtimeUpdate": "실시간 업데이트",
    "header.dashboard": "대시보드",
    "header.aiDecisions": "AI 보유 분석",
    "header.trading": "거래 내역",
    "header.watchlist": "관심 종목",
    "header.insights": "인사이트",
    "header.tooltip.github": "GitHub 저장소",
    "header.tooltip.telegram": "텔레그램 채널",
    "header.tooltip.theme": "테마 전환",

    // Loading
    "loading.text": "데이터 로딩 중...",

    // Tables
    "table.realPortfolio": "실전투자 포트폴리오",
    "table.simulator": "프리즘 시뮬레이터",
    "table.stock": "종목",
    "table.stockName": "종목명",
    "table.sector": "섹터",
    "table.quantity": "수량",
    "table.avgPrice": "평균단가",
    "table.currentPrice": "현재가",
    "table.buyPrice": "매수가",
    "table.targetPrice": "목표가",
    "table.stopLoss": "손절가",
    "table.profitRate": "수익률",
    "table.profitAmount": "평가손익",
    "table.totalValue": "평가금액",
    "table.holdingDays": "보유일",
    "table.period": "기간",
    "table.weight": "비중",
    "table.unknown": "알 수 없음",

    // Metrics Cards - Real Trading
    "metrics.realTrading": "실전투자 (Season 2)",
    "metrics.realTotalAssets": "실전 총 자산",
    "metrics.realHoldingsProfit": "실전 보유종목 평가손익",
    "metrics.realProfitDist": "실전 포트폴리오 손익 분포",
    "metrics.startAmount": "시작금액",
    "metrics.deposit": "예수금",
    "metrics.stocks": "개 종목",
    "metrics.assetsDesc": "평가금액 + 예수금",
    "metrics.holdingsProfitDesc": "현재 보유중인 종목의 손익",
    "metrics.excludeRealized": "실현손익 제외",
    "metrics.profitDistDesc": "현재 보유 종목 수익/손실 현황",
    "metrics.cashAndStability": "현금 & 포트폴리오 안정성",
    "metrics.cashRatio": "현금 비율",
    "metrics.investmentRatio": "투자 비율",
    "metrics.cashStabilityDesc": "예수금 및 투자 비중",
    "metrics.fullyInvested": "전액 투자중",
    "metrics.wins": "승",
    "metrics.losses": "패",
    "metrics.breakEven": "보합",
    "metrics.totalStocks": "총",
    "metrics.winRate": "승률",

    // Metrics Cards - Simulator
    "metrics.simulator": "프리즘 시뮬레이터",
    "metrics.simSoldProfit": "시뮬레이터 매도종목 누적수익률",
    "metrics.simAvgHoldingDays": "시뮬레이터 평균 보유기간",
    "metrics.simCurrentProfit": "시뮬레이터 보유종목 누적수익률",
    "metrics.waitingSell": "매도 대기중",
    "metrics.onlyHolding": "현재 보유만 존재",
    "metrics.updateOnSell": "매도 시 업데이트",
    "metrics.soldProfitDesc": "매도 완료한 종목 수익률 합계",
    "metrics.sold": "매도",
    "metrics.soldBasis": "건 매도 기준",
    "metrics.needStrategy": "보유 전략 확인 필요",
    "metrics.avgHoldingDesc": "매도까지 평균 소요 기간",
    "metrics.holding": "보유",
    "metrics.avgProfit": "평균",
    "metrics.slotUsage": "슬롯 사용률",
    "metrics.currentProfitDesc": "현재 보유 종목 수익률 합계",
    "metrics.started": "시작",
    "metrics.elapsed": "일 경과",

    // Operating Costs
    "costs.title": "프로젝트 운영 비용 투명 공개",
    "costs.description": "오픈소스 프로젝트의 지속 가능한 운영을 위해 전월 비용을 공개합니다",
    "costs.serverHosting": "서버 호스팅",
    "costs.basis": "기준",
    "costs.perMonth": "/ 월",
    "costs.year": "년",
    "costs.month": "월",
    "costs.helpQuestion": "이 프로젝트가 도움이 되셨나요?",
    "costs.sponsorDesc": "GitHub Sponsor를 통해 프로젝트의 지속 가능한 개발을 지원해주세요",
    "costs.becomeSponsor": "스폰서 되기",

    // Badges
    "badge.realTrading": "실전투자",
    "badge.aiSimulation": "AI 시뮬레이션",
    "badge.season2": "Season 2",
    "badge.koreanInvestment": "한국투자증권",

    // Date/Time
    "date.year": "년",
    "date.month": "월",
    "date.day": "일",

    // Common
    "common.won": "원",
    "common.krw": "₩",
    "common.percent": "%",
    "common.days": "일",
    "common.trades": "건",
    "common.shares": "주",
    "common.other": "기타",
    "common.unclassified": "미분류",
    "metrics.totalReturn": "누적 수익률",
    "metrics.avgReturn": "평균 수익률",
    "metrics.avgHoldingDays": "평균 보유일",
    "metrics.totalTrades": "총 거래",

    // Charts
    "chart.prismReturn": "프리즘 시뮬레이터 (누적 실현)",
    "chart.returnComparisonKospi": "수익률 비교 (KOSPI 기준)",
    "chart.returnComparisonKosdaq": "수익률 비교 (KOSDAQ 기준)",
    "chart.returnComparisonSP500": "수익률 비교 (S&P 500 기준)",
    "chart.returnComparisonNasdaq": "수익률 비교 (NASDAQ 기준)",
    "chart.market": "시장",
    "chart.prism": "프리즘",
    "chart.return": "수익률",
    "chart.index": "지수",

    // Market Selector
    "market.kr": "한국",
    "market.us": "미국",
    "market.selector.title": "시장 선택",
    "market.us.realTrading": "미국 실전투자",
    "market.us.simulator": "미국 시뮬레이터",
    "market.us.season": "Season 1",

    // Stock Detail Modal
    "modal.stockDetail": "종목 상세",
    "modal.close": "닫기",
    "modal.currentPrice": "현재가",
    "modal.profitRate": "수익률",
    "modal.holdingInfo": "보유 정보",
    "modal.holdingQuantity": "보유 수량",
    "modal.avgBuyPrice": "평균 매입가",
    "modal.evaluationAmount": "평가 금액",
    "modal.evaluationPL": "평가 손익",
    "modal.portfolioWeight": "포트폴리오 비중",
    "modal.tradingInfo": "매매 정보",
    "modal.buyDate": "매수일",
    "modal.buyPrice": "매수가",
    "modal.targetPrice": "목표가",
    "modal.stopLossPrice": "손절가",
    "modal.riskRewardRatio": "손익비",
    "modal.expectedReturn": "목표 수익",
    "modal.expectedLoss": "예상 손실",
    "modal.holdingDays": "보유 일수",
    "modal.lastUpdate": "최근 업데이트",
    "modal.aiTradingScenario": "AI 매매 시나리오",
    "modal.buyDecision": "매수 결정",
    "modal.maxPortfolioSize": "최대 포트폴리오 규모",
    "modal.keyPriceLevels": "주요 가격대",
    "modal.sellTriggers": "매도 트리거",
    "modal.holdConditions": "보유 조건",
    "modal.portfolioContext": "포트폴리오 맥락",
    "modal.basicInfo": "기본 정보",
    "modal.buyInfo": "매수 정보",
    "modal.currentStatus": "현재 상태",
    "modal.targetStopLoss": "목표가/손절가",
    "modal.investmentPeriod": "투자 기간",
    "modal.investmentRationale": "투자 근거",
    "modal.tradingScenarios": "매매 시나리오",
    "modal.keyLevels": "주요 레벨",
    "modal.portfolioAnalysis": "포트폴리오 분석",
    "modal.valuationAnalysis": "밸류에이션 분석",
    "modal.sectorOutlook": "업종 전망",
    "modal.marketCondition": "시장 상황",
    "modal.primarySupport": "1차 지지선",
    "modal.secondarySupport": "2차 지지선",
    "modal.primaryResistance": "1차 저항선",
    "modal.secondaryResistance": "2차 저항선",
    "modal.volumeBaseline": "거래량 베이스라인",
    "modal.primarySupportShort": "1차 지지",
    "modal.secondarySupportShort": "2차 지지",
    "modal.primaryResistanceShort": "1차 저항",
    "modal.secondaryResistanceShort": "2차 저항",
    "modal.buyScore": "매수점수",

    // AI Decisions Page
    "aiDecisions.title": "AI 보유 분석",
    "aiDecisions.description": "AI가 분석한 현재 보유 종목의 매도 여부 판단",
    "aiDecisions.lastAnalysis": "최근 분석",
    "aiDecisions.sell": "매도",
    "aiDecisions.hold": "보유",
    "aiDecisions.confidence": "확신도",
    "aiDecisions.technicalTrend": "기술적 추세",
    "aiDecisions.volumeAnalysis": "거래량 분석",
    "aiDecisions.marketCondition": "시장 상황",
    "aiDecisions.timeFactor": "시간 요소",
    "aiDecisions.portfolioAdjustment": "포트폴리오 조정",
    "aiDecisions.portfolioAdjustmentNeeded": "포트폴리오 조정 필요",
    "aiDecisions.maintainStrategy": "현재 전략 유지",
    "aiDecisions.newTargetPrice": "신규 목표가",
    "aiDecisions.newStopLoss": "신규 손절가",
    "aiDecisions.urgency": "긴급도",
    "aiDecisions.reason": "사유",
    "aiDecisions.noData": "분석 데이터가 없습니다",
    "aiDecisions.pageDescription": "보유 종목에 대한 AI의 일일 판단 기록",
    "aiDecisions.totalAnalysis": "총",
    "aiDecisions.recordsCount": "건의 분석",
    "aiDecisions.totalAnalysisRecords": "총 분석 기록",
    "aiDecisions.records": "건",
    "aiDecisions.allHoldDecisions": "모두 보유 유지 판단",
    "aiDecisions.adjustmentNeeded": "조정 필요",
    "aiDecisions.portfolioRebalanceRecommended": "포트폴리오 재조정 권고",
    "aiDecisions.analyzedStocksCount": "분석 종목 수",
    "aiDecisions.stocksCount": "개",
    "aiDecisions.cumulativeBasis": "누적 종목 기준",
    "aiDecisions.analysisCount": "개 분석",
    "aiDecisions.holdMaintain": "보유 유지",
    "aiDecisions.analysisTime": "분석 시각",
    "aiDecisions.analysisPricePoint": "분석 시점 가격",
    "aiDecisions.aiJudgementBasis": "AI 판단 근거",
    "aiDecisions.analysisSummary": "분석 요약",
    "aiDecisions.marketImpact": "시장 영향",
    "aiDecisions.timeFactor2": "시간 요인",
    "aiDecisions.portfolioAdjustmentSection": "포트폴리오 조정",
    "aiDecisions.newTargetPriceHistory": "신규 목표가 이력",
    "aiDecisions.newStopLossHistory": "신규 손절가 이력",
    "aiDecisions.noAnalysisDataYet": "아직 AI 보유 분석 내역이 없습니다.",

    // Trading History Page
    "trading.title": "거래 내역",
    "trading.description": "매매 완료 종목 분석 및 AI 시나리오 비교",
    "trading.totalTrades": "총 거래",
    "trading.totalProfit": "총 손익",
    "trading.avgProfit": "평균 수익률",
    "trading.avgHoldingDays": "평균 보유",
    "trading.avgHoldingDaysShort": "평균 보유일",
    "trading.sellDate": "매도일",
    "trading.buyDate": "매수일",
    "trading.buyPrice": "매수가",
    "trading.sellPrice": "매도가",
    "trading.profitRate": "수익률",
    "trading.holdingDays": "보유일",
    "trading.holdingPeriod": "보유기간",
    "trading.filters": "필터",
    "trading.all": "전체",
    "trading.profit": "수익",
    "trading.loss": "손실",
    "trading.scenario": "시나리오",
    "trading.noData": "아직 거래 내역이 없습니다.",
    "trading.times": "회",
    "trading.winRate": "승률",
    "trading.detailedHistory": "거래 상세 내역",
    "trading.aiTargetPrice": "AI 목표가",
    "trading.targetAchievementRate": "목표 달성률",
    "trading.aiInvestmentRationale": "AI 투자 근거",
    "trading.aiScenarioDetails": "AI 매매 시나리오 상세",
    "trading.pastMarketCondition": "당시 시장 상황",
    "trading.tradeCount": "건 거래",
    "trading.completedTrades": "매매 완료 건수",
    "trading.winningTradeRatio": "수익 거래 비율",
    "trading.avgPerformancePerTrade": "거래당 평균 성과",
    "trading.daysFromBuyToSell": "매수 후 매도까지",
    "trading.bestTrade": "최고 수익 거래",
    "trading.worstTrade": "최저 수익 거래",
    "trading.sectorPerformanceTop3": "섹터별 수익률 TOP 3",
    "trading.periodPerformance": "투자기간별 성과",
    "trading.daysHeld": "일 보유",
    "trading.avgWinRate": "평균 수익률",
    "trading.avgLossRate": "평균 손실률",
    "trading.winningTradesAvg": "건 수익 거래 평균",
    "trading.losingTradesAvg": "건 손실 거래 평균",
    "trading.profitFactor": "Profit Factor",
    "trading.profitFactorDesc": "총수익 ÷ 총손실 (1 이상이면 수익)",
    "trading.riskRewardRatio": "손익비",
    "trading.riskRewardDesc": "평균수익 ÷ 평균손실",
    "trading.maxWinStreak": "최대 연승",
    "trading.maxWinStreakDesc": "연속 수익 거래 기록",
    "trading.consecutive": "연속",
    "trading.avgWinShort": "평균수익",
    "trading.avgLossShort": "평균손실",
    "trading.tradeCountShort": "건",
    "trading.mdd": "MDD",
    "trading.mddDesc": "최대 낙폭 (고점 대비 최대 하락)",
    "trading.alpha": "알파 (Alpha)",
    "trading.alphaDesc": "시장 대비 초과 수익률",
    "trading.beta": "베타 (Beta)",
    "trading.betaDesc": "시장 대비 변동성 (1 = 시장과 동일)",
    "trading.sharpeRatio": "샤프 비율",
    "trading.sharpeDesc": "위험 조정 수익률 (높을수록 좋음)",
    "trading.informationRatio": "정보 비율",
    "trading.informationRatioDesc": "추적 오차 대비 초과 수익",
    "trading.riskAdjustedMetrics": "위험조정 성과 지표",
    "trading.dataPeriod": "데이터 기간",
    // Tooltip explanations
    "trading.profitFactorTooltip": "총 수익금액을 총 손실금액으로 나눈 값입니다. 수익 거래로 번 금액이 손실 거래로 잃은 금액의 몇 배인지를 나타냅니다.",
    "trading.profitFactorGood": "✓ 1.5 이상: 우수 (수익이 손실의 1.5배)",
    "trading.profitFactorNeutral": "• 1.0~1.5: 보통 (수익이 손실보다 큼)",
    "trading.profitFactorBad": "✗ 1.0 미만: 주의 (손실이 수익보다 큼)",
    "trading.riskRewardTooltip": "평균 수익률을 평균 손실률로 나눈 값입니다. 한 번 이길 때 평균적으로 버는 금액이 질 때 잃는 금액의 몇 배인지를 나타냅니다.",
    "trading.riskRewardGood": "✓ 2.0 이상: 우수 (이익이 손실의 2배)",
    "trading.riskRewardNeutral": "• 1.0~2.0: 보통 (이익이 손실보다 큼)",
    "trading.riskRewardBad": "✗ 1.0 미만: 주의 (손실이 이익보다 큼)",
    "trading.mddTooltip": "최대 낙폭(Maximum Drawdown). 투자 기간 중 고점에서 저점까지 가장 크게 하락한 폭입니다. 최악의 상황에서 얼마나 손실을 볼 수 있는지를 보여줍니다.",
    "trading.mddGood": "✓ 10% 이하: 우수 (안정적인 운용)",
    "trading.mddNeutral": "• 10%~20%: 보통 (일반적인 변동성)",
    "trading.mddBad": "✗ 20% 초과: 주의 (높은 변동성)",
    "trading.alphaTooltip": "시장(KOSPI) 수익률을 초과하는 수익률입니다. 펀드매니저의 실력을 나타내는 대표적 지표로, 시장 대비 얼마나 더 (또는 덜) 벌었는지를 보여줍니다.",
    "trading.alphaGood": "✓ 양수(+): 시장을 이김 (시장보다 우수한 성과)",
    "trading.alphaBad": "✗ 음수(-): 시장에 짐 (시장보다 부진한 성과)",
    "trading.betaTooltip": "시장 대비 변동성을 나타냅니다. 시장이 1% 움직일 때 포트폴리오가 얼마나 움직이는지를 보여줍니다.",
    "trading.betaLow": "◐ 1 미만: 낮은 변동성 (시장보다 안정적)",
    "trading.betaNeutral": "• 1.0: 시장과 동일한 변동성",
    "trading.betaHigh": "◐ 1 초과: 높은 변동성 (시장보다 공격적)",
    "trading.sharpeTooltip": "위험 대비 수익률을 나타냅니다. 무위험 수익률(예금 이자 등)을 초과하는 수익을 얼마나 적은 위험으로 달성했는지를 보여줍니다.",
    "trading.sharpeGood": "✓ 1.0 이상: 우수 (위험 대비 높은 수익)",
    "trading.sharpeNeutral": "• 0~1.0: 보통 (양호한 수준)",
    "trading.sharpeBad": "✗ 0 미만: 주의 (무위험 자산보다 못함)",
    "trading.irTooltip": "벤치마크(KOSPI) 대비 초과수익을 추적오차(변동성)로 나눈 값입니다. 일관성 있게 시장을 이기는지를 평가합니다.",
    "trading.irGood": "✓ 0.5 이상: 우수 (일관되게 시장 초과)",
    "trading.irNeutral": "• 0~0.5: 보통 (약간의 초과수익)",
    "trading.irBad": "✗ 0 미만: 주의 (시장 대비 부진)",

    // Watchlist Page
    "watchlist.title": "관심 종목",
    "watchlist.description": "AI가 분석한 투자 후보 종목 (최근 1개월)",
    "watchlist.totalStocks": "전체 종목",
    "watchlist.stocksCount": "개",
    "watchlist.highestScore": "최고 점수",
    "watchlist.avgScore": "평균 점수",
    "watchlist.recentWeek": "최근 7일",
    "watchlist.scoreUnit": "점",
    "watchlist.entry": "진입",
    "watchlist.watch": "미진입",
    "watchlist.entryChecklist": "진입 체크리스트",
    "watchlist.rejectionReason": "미진입 사유",
    "watchlist.reason": "사유",
    "watchlist.analyzedDate": "분석일",
    "watchlist.buyScore": "매수 점수",
    "watchlist.currentPrice": "현재가",
    "watchlist.targetPrice": "목표가",
    "watchlist.stopLoss": "손절가",
    "watchlist.tradingRationale": "매매 근거",
    "watchlist.noData": "아직 관심 종목이 없습니다.",
    "watchlist.mostPromising": "가장 유망한 종목",
    "watchlist.outOf10": "10점 만점 기준",
    "watchlist.recentlyAnalyzed": "최근 분석 종목",
    "watchlist.sectorDistributionTop3": "섹터별 분포 TOP 3",
    "watchlist.analyses": "개 분석",
    "watchlist.aiAnalysisDetails": "AI 분석 상세",
    "watchlist.copyToClipboard": "클립보드 복사",
    "watchlist.lastMonthAnalysis": "최근 1개월 분석",
    "watchlist.decision": "결정",
    "watchlist.stocksUnit": "개 종목",

    // Trading Insights Page
    "insights.title": "매매 인사이트",
    "insights.description": "트리거 성과 분석, AI 매매 원칙, 교훈, 축적 직관",
    "insights.category.performance": "성과 분석",
    "insights.category.wisdom": "매매 인사이트",
    "insights.principles": "범용 원칙",
    "insights.principlesDescription": "모든 매매에 적용되는 핵심 원칙",
    "insights.journal": "매매일지",
    "insights.journalDescription": "매매 완료 후 AI가 작성한 상세 기록",
    "insights.intuitions": "축적 직관",
    "insights.intuitionsDescription": "반복 패턴에서 추출된 장기 인사이트",
    "insights.summary.totalPrinciples": "총 원칙",
    "insights.summary.highPriority": "고우선순위",
    "insights.summary.avgProfit": "평균 수익률",
    "insights.summary.totalTrades": "총 거래",
    "insights.summary.totalIntuitions": "총 직관",
    "insights.summary.avgConfidence": "평균 신뢰도",
    "insights.priority.high": "높음",
    "insights.priority.medium": "중간",
    "insights.priority.low": "낮음",
    "insights.scope.universal": "범용",
    "insights.scope.sector": "섹터별",
    "insights.scope.market": "시장별",
    "insights.condition": "조건",
    "insights.action": "행동",
    "insights.reason": "근거",
    "insights.confidence": "신뢰도",
    "insights.supportingTrades": "지지 거래",
    "insights.situationAnalysis": "상황 분석",
    "insights.judgmentEvaluation": "판단 평가",
    "insights.lessons": "교훈",
    "insights.patternTags": "패턴 태그",
    "insights.oneLine": "한줄 요약",
    "insights.category": "카테고리",
    "insights.insight": "인사이트",
    "insights.successRate": "성공률",
    "insights.supportingTrades": "뒷받침 거래",
    "insights.noData": "아직 매매 인사이트 데이터가 없습니다.",
    "insights.noPrinciples": "아직 추출된 원칙이 없습니다.",
    "insights.noJournal": "아직 기록된 매매일지가 없습니다.",
    "insights.noIntuitions": "아직 축적된 직관이 없습니다.",
    "insights.layer": "레이어",
    "insights.holdingDays": "보유일",
    "insights.profitRate": "수익률",
    "insights.tradeDate": "거래일",

    // Performance Analysis (Trigger Performance Tracking)
    "insights.performance.title": "트리거 성과 분석",
    "insights.performance.description": "분석 종목의 7/14/30일 후 가격 변화 추적",
    "insights.performance.overview": "추적 현황",
    "insights.performance.total": "총 추적",
    "insights.performance.completed": "완료",
    "insights.performance.pending": "대기",
    "insights.performance.inProgress": "추적중",
    "insights.performance.traded": "매매",
    "insights.performance.watched": "미진입",
    "insights.performance.triggerType": "미진입 종목의 트리거 유형별 성과",
    "insights.performance.rrAnalysis": "손익비 구간별 분석",
    "insights.performance.missedOpportunities": "놓친 기회",
    "insights.performance.missedOpportunitiesDesc": "미진입했는데 30일 후 10% 이상 상승한 종목",
    "insights.performance.avoidedLosses": "회피한 손실",
    "insights.performance.avoidedLossesDesc": "미진입해서 피한 30일 후 10% 이상 하락 종목",
    "insights.performance.recommendations": "데이터 기반 권고",
    "insights.performance.avgReturn": "평균 수익률",
    "insights.performance.winRate": "승률",
    "insights.performance.count": "건",
    "insights.performance.7day": "7일",
    "insights.performance.14day": "14일",
    "insights.performance.30day": "30일",
    "insights.performance.tradedRate": "매매율",
    "insights.performance.range": "구간",
    "insights.performance.noData": "아직 성과 추적 데이터가 없습니다.",
    "insights.performance.noDataHint": "매매 분석 후 7일 이상 경과 시 데이터가 수집됩니다.",
    "insights.performance.skipReason": "스킵 사유",
    "insights.performance.day7": "7일",
    "insights.performance.day14": "14일",
    "insights.performance.day30": "30일",
    "insights.performance.allAvg": "전체 평균",
    "insights.performance.watchedAvg": "미진입 평균",
    // Tooltip translations
    "insights.performance.tooltip.completed": "분석 후 30일이 경과하여 추적이 완료된 종목",
    "insights.performance.tooltip.pending": "분석 후 7일이 아직 안 된 종목 (추적 대기)",
    "insights.performance.tooltip.inProgress": "7일~30일 사이로 추적 진행 중인 종목",
    "insights.performance.tooltip.traded": "분석 후 실제로 매수한 종목 수",
    "insights.performance.tooltip.watched": "분석 후 매수하지 않고 미진입한 종목 수",
    "insights.performance.tooltip.dayReturn": "분석일로부터 N일 후 평균 수익률 (완료된 추적 기준)",
    "insights.performance.tooltip.winRate": "30일 후 수익(+)인 종목 비율",
    "insights.performance.tooltip.tradedRate": "해당 트리거에서 매매로 이어진 비율",

    // Trigger Reliability Card
    "insights.triggerReliability.title": "트리거 신뢰도",
    "insights.triggerReliability.description": "어떤 신호를 더 믿을 수 있는가? 분석 정확도 + 실매매 + 원칙 교차 분석",
    "insights.triggerReliability.bestTrigger": "최고 신뢰 트리거",
    "insights.triggerReliability.grade": "등급",
    "insights.triggerReliability.analysisAccuracy": "분석 정확도",
    "insights.triggerReliability.actualTrading": "실매매 성과",
    "insights.triggerReliability.principles": "관련 원칙",
    "insights.triggerReliability.recommendation": "추천",
    "insights.triggerReliability.tracked": "추적",
    "insights.triggerReliability.completed": "완료",
    "insights.triggerReliability.trades": "매매",
    "insights.triggerReliability.winRate": "승률",
    "insights.triggerReliability.avgReturn": "평균수익률",
    "insights.triggerReliability.profitFactor": "PF",
    "insights.triggerReliability.noData": "아직 트리거 신뢰도 데이터가 없습니다.",
    "insights.triggerReliability.gradeA": "높은 신뢰도",
    "insights.triggerReliability.gradeB": "양호",
    "insights.triggerReliability.gradeC": "주의 필요",
    "insights.triggerReliability.gradeD": "데이터 부족",
    "insights.triggerReliability.miniBadge": "최고 신뢰 트리거",
    "insights.triggerReliability.viewDetails": "상세보기",

    // Footer
    "footer.description": "AI 기반 주식 분석 및 매매 시스템",
    "footer.openSource": "완전 오픈소스 무료 프로젝트 • MIT License",
    "footer.features": "주요 기능",
    "footer.feature1": "12개 AI 에이전트 협업 분석",
    "footer.feature2": "급등주 자동 포착 & 리포트",
    "footer.feature3": "매매 시뮬레이션 & 자동매매",
    "footer.feature4": "실시간 성과 대시보드",
    "footer.links": "바로가기",
    "footer.sourceCode": "소스코드 & 이슈 관리",
    "footer.telegramDesc": "급등주 & 분석 리포트",
    "footer.stars": "10주 만에 250+ Stars 달성",
    "footer.disclaimer": "⚠️ 본 시스템에서 제공하는 분석 정보는 투자 참고용이며, 투자 권유를 목적으로 하지 않습니다. 모든 투자 결정과 그에 따른 손익은 투자자 본인의 책임입니다.",
  },
  en: {
    // Header
    "header.season": "Season 2",
    "header.openSource": "Open Source",
    "header.tooltip.openSource": "AI-powered Stock Analysis & Trading System • MIT License",
    "header.startDate": "Start: 2025.09.29",
    "header.updated": "Updated",
    "header.realtimeUpdate": "Real-time Update",
    "header.dashboard": "Dashboard",
    "header.aiDecisions": "AI Holdings",
    "header.trading": "Trades",
    "header.watchlist": "Watchlist",
    "header.insights": "Insights",
    "header.tooltip.github": "GitHub Repository",
    "header.tooltip.telegram": "Telegram Channel",
    "header.tooltip.theme": "Toggle Theme",

    // Loading
    "loading.text": "Loading data...",

    // Tables
    "table.realPortfolio": "Real Trading Portfolio",
    "table.simulator": "Prism Simulator",
    "table.stock": "Stock",
    "table.stockName": "Stock Name",
    "table.sector": "Sector",
    "table.quantity": "Qty",
    "table.avgPrice": "Avg Price",
    "table.currentPrice": "Current",
    "table.buyPrice": "Buy Price",
    "table.targetPrice": "Target",
    "table.stopLoss": "Stop Loss",
    "table.profitRate": "Return",
    "table.profitAmount": "P&L",
    "table.totalValue": "Value",
    "table.holdingDays": "Days",
    "table.period": "Period",
    "table.weight": "Weight",
    "table.unknown": "Unknown",

    // Metrics Cards - Real Trading
    "metrics.realTrading": "Real Trading (Season 2)",
    "metrics.realTotalAssets": "Real Total Assets",
    "metrics.realHoldingsProfit": "Real Holdings P&L",
    "metrics.realProfitDist": "Real Profit Distribution",
    "metrics.startAmount": "Start Amount",
    "metrics.deposit": "Cash",
    "metrics.stocks": " stocks",
    "metrics.assetsDesc": "Holdings + Cash",
    "metrics.holdingsProfitDesc": "Current holdings P&L",
    "metrics.excludeRealized": "Unrealized only",
    "metrics.profitDistDesc": "Profit/Loss breakdown",
    "metrics.cashAndStability": "Cash & Portfolio Stability",
    "metrics.cashRatio": "Cash Ratio",
    "metrics.investmentRatio": "Investment Ratio",
    "metrics.cashStabilityDesc": "Cash balance & allocation",
    "metrics.fullyInvested": "Fully invested",
    "metrics.wins": "W",
    "metrics.losses": "L",
    "metrics.breakEven": "Even",
    "metrics.totalStocks": "Total",
    "metrics.winRate": "Win Rate",

    // Metrics Cards - Simulator
    "metrics.simulator": "Prism Simulator",
    "metrics.simSoldProfit": "Sim Sold Total Return",
    "metrics.simAvgHoldingDays": "Sim Avg Holding Days",
    "metrics.simCurrentProfit": "Sim Current Holdings Return",
    "metrics.waitingSell": "Awaiting sale",
    "metrics.onlyHolding": "Only holdings exist",
    "metrics.updateOnSell": "Updates on sale",
    "metrics.soldProfitDesc": "Total return from sold stocks",
    "metrics.sold": "sold",
    "metrics.soldBasis": " sold basis",
    "metrics.needStrategy": "Review strategy",
    "metrics.avgHoldingDesc": "Avg days until sale",
    "metrics.holding": "holding",
    "metrics.avgProfit": "Avg",
    "metrics.slotUsage": "Slot usage",
    "metrics.currentProfitDesc": "Total return from current holdings",
    "metrics.started": "Started",
    "metrics.elapsed": "d elapsed",

    // Operating Costs
    "costs.title": "Project Operating Costs Transparency",
    "costs.description": "Disclosing last month's costs for sustainable open-source operations",
    "costs.serverHosting": "Server Hosting",
    "costs.basis": "as of",
    "costs.perMonth": "/ mo",
    "costs.year": "",
    "costs.month": "",
    "costs.helpQuestion": "Has this project helped you?",
    "costs.sponsorDesc": "Support sustainable development via GitHub Sponsor",
    "costs.becomeSponsor": "Become a Sponsor",

    // Badges
    "badge.realTrading": "Real Trading",
    "badge.aiSimulation": "AI Simulation",
    "badge.season2": "Season 2",
    "badge.koreanInvestment": "Korea Investment & Securities",

    // Date/Time
    "date.year": "-",
    "date.month": "-",
    "date.day": "",

    // Common
    "common.won": "KRW",
    "common.krw": "₩",
    "common.percent": "%",
    "common.days": "d",
    "common.trades": "trades",
    "common.shares": " shares",
    "common.other": "Others",
    "common.unclassified": "Unclassified",
    "metrics.totalReturn": "Total Return",
    "metrics.avgReturn": "Avg Return",
    "metrics.avgHoldingDays": "Avg Days",
    "metrics.totalTrades": "Total Trades",

    // Charts
    "chart.prismReturn": "Prism Simulator (Realized)",
    "chart.returnComparisonKospi": "Return Comparison (KOSPI)",
    "chart.returnComparisonKosdaq": "Return Comparison (KOSDAQ)",
    "chart.returnComparisonSP500": "Return Comparison (S&P 500)",
    "chart.returnComparisonNasdaq": "Return Comparison (NASDAQ)",
    "chart.market": "Market",
    "chart.prism": "Prism",
    "chart.return": "Return",
    "chart.index": "Index",

    // Market Selector
    "market.kr": "Korea",
    "market.us": "US",
    "market.selector.title": "Select Market",
    "market.us.realTrading": "US Real Trading",
    "market.us.simulator": "US Simulator",
    "market.us.season": "Season 1",

    // Stock Detail Modal
    "modal.stockDetail": "Stock Details",
    "modal.close": "Close",
    "modal.currentPrice": "Current Price",
    "modal.profitRate": "Return",
    "modal.holdingInfo": "Holding Info",
    "modal.holdingQuantity": "Quantity",
    "modal.avgBuyPrice": "Avg Buy Price",
    "modal.evaluationAmount": "Valuation",
    "modal.evaluationPL": "P&L",
    "modal.portfolioWeight": "Portfolio Weight",
    "modal.tradingInfo": "Trading Info",
    "modal.buyDate": "Buy Date",
    "modal.buyPrice": "Buy Price",
    "modal.targetPrice": "Target",
    "modal.stopLossPrice": "Stop Loss",
    "modal.riskRewardRatio": "Risk/Reward Ratio",
    "modal.expectedReturn": "Expected Return",
    "modal.expectedLoss": "Expected Loss",
    "modal.holdingDays": "Days Held",
    "modal.lastUpdate": "Last Update",
    "modal.aiTradingScenario": "AI Trading Scenario",
    "modal.buyDecision": "Buy Decision",
    "modal.maxPortfolioSize": "Max Portfolio Size",
    "modal.keyPriceLevels": "Key Price Levels",
    "modal.sellTriggers": "Sell Triggers",
    "modal.holdConditions": "Hold Conditions",
    "modal.portfolioContext": "Portfolio Context",
    "modal.basicInfo": "Basic Info",
    "modal.buyInfo": "Buy Info",
    "modal.currentStatus": "Current Status",
    "modal.targetStopLoss": "Target/Stop Loss",
    "modal.investmentPeriod": "Investment Period",
    "modal.investmentRationale": "Investment Rationale",
    "modal.tradingScenarios": "Trading Scenarios",
    "modal.keyLevels": "Key Levels",
    "modal.portfolioAnalysis": "Portfolio Analysis",
    "modal.valuationAnalysis": "Valuation Analysis",
    "modal.sectorOutlook": "Sector Outlook",
    "modal.marketCondition": "Market Condition",
    "modal.primarySupport": "Primary Support",
    "modal.secondarySupport": "Secondary Support",
    "modal.primaryResistance": "Primary Resistance",
    "modal.secondaryResistance": "Secondary Resistance",
    "modal.volumeBaseline": "Volume Baseline",
    "modal.primarySupportShort": "1st Support",
    "modal.secondarySupportShort": "2nd Support",
    "modal.primaryResistanceShort": "1st Resistance",
    "modal.secondaryResistanceShort": "2nd Resistance",
    "modal.buyScore": "Buy Score",

    // AI Decisions Page
    "aiDecisions.title": "AI Holdings Analysis",
    "aiDecisions.description": "AI analysis of current holdings for sell/hold decisions",
    "aiDecisions.lastAnalysis": "Last Analysis",
    "aiDecisions.sell": "Sell",
    "aiDecisions.hold": "Hold",
    "aiDecisions.confidence": "Confidence",
    "aiDecisions.technicalTrend": "Technical Trend",
    "aiDecisions.volumeAnalysis": "Volume Analysis",
    "aiDecisions.marketCondition": "Market Condition",
    "aiDecisions.timeFactor": "Time Factor",
    "aiDecisions.portfolioAdjustment": "Portfolio Adjustment",
    "aiDecisions.portfolioAdjustmentNeeded": "Portfolio Adjustment Needed",
    "aiDecisions.maintainStrategy": "Maintain Current Strategy",
    "aiDecisions.newTargetPrice": "New Target Price",
    "aiDecisions.newStopLoss": "New Stop Loss",
    "aiDecisions.urgency": "Urgency",
    "aiDecisions.reason": "Reason",
    "aiDecisions.noData": "No analysis data available",
    "aiDecisions.pageDescription": "Daily AI analysis records for held stocks",
    "aiDecisions.totalAnalysis": "Total",
    "aiDecisions.recordsCount": " analyses",
    "aiDecisions.totalAnalysisRecords": "Total Analysis Records",
    "aiDecisions.records": " records",
    "aiDecisions.allHoldDecisions": "All hold decisions",
    "aiDecisions.adjustmentNeeded": "Adjustment needed",
    "aiDecisions.portfolioRebalanceRecommended": "Portfolio rebalance recommended",
    "aiDecisions.analyzedStocksCount": "Analyzed Stocks Count",
    "aiDecisions.stocksCount": " stocks",
    "aiDecisions.cumulativeBasis": "Cumulative basis",
    "aiDecisions.analysisCount": " analyses",
    "aiDecisions.holdMaintain": "Hold Maintain",
    "aiDecisions.analysisTime": "Analysis time",
    "aiDecisions.analysisPricePoint": "Analysis price point",
    "aiDecisions.aiJudgementBasis": "AI Judgement Basis",
    "aiDecisions.analysisSummary": "Analysis Summary",
    "aiDecisions.marketImpact": "Market Impact",
    "aiDecisions.timeFactor2": "Time Factor",
    "aiDecisions.portfolioAdjustmentSection": "Portfolio Adjustment",
    "aiDecisions.newTargetPriceHistory": "New Target Price History",
    "aiDecisions.newStopLossHistory": "New Stop Loss History",
    "aiDecisions.noAnalysisDataYet": "No AI holding analysis data yet.",

    // Trading History Page
    "trading.title": "Trading History",
    "trading.description": "Completed trade analysis & AI scenario comparison",
    "trading.totalTrades": "Total Trades",
    "trading.totalProfit": "Total P&L",
    "trading.avgProfit": "Avg Return",
    "trading.avgHoldingDays": "Avg Holding",
    "trading.avgHoldingDaysShort": "Avg Days",
    "trading.sellDate": "Sell Date",
    "trading.buyDate": "Buy Date",
    "trading.buyPrice": "Buy Price",
    "trading.sellPrice": "Sell Price",
    "trading.profitRate": "Return",
    "trading.holdingDays": "Days",
    "trading.holdingPeriod": "Holding Period",
    "trading.filters": "Filters",
    "trading.all": "All",
    "trading.profit": "Profit",
    "trading.loss": "Loss",
    "trading.scenario": "Scenario",
    "trading.noData": "No trading history yet.",
    "trading.times": " trades",
    "trading.winRate": "Win Rate",
    "trading.detailedHistory": "Detailed History",
    "trading.aiTargetPrice": "AI Target",
    "trading.targetAchievementRate": "Target Achievement",
    "trading.aiInvestmentRationale": "AI Investment Rationale",
    "trading.aiScenarioDetails": "AI Trading Scenario Details",
    "trading.pastMarketCondition": "Market Condition at Time",
    "trading.tradeCount": " trades",
    "trading.completedTrades": "Completed trades",
    "trading.winningTradeRatio": "Winning trade ratio",
    "trading.avgPerformancePerTrade": "Avg performance per trade",
    "trading.daysFromBuyToSell": "Days from buy to sell",
    "trading.bestTrade": "Best Trade",
    "trading.worstTrade": "Worst Trade",
    "trading.sectorPerformanceTop3": "Sector Performance TOP 3",
    "trading.periodPerformance": "Period Performance",
    "trading.daysHeld": " days held",
    "trading.avgWinRate": "Avg Win",
    "trading.avgLossRate": "Avg Loss",
    "trading.winningTradesAvg": " winning trades avg",
    "trading.losingTradesAvg": " losing trades avg",
    "trading.profitFactor": "Profit Factor",
    "trading.profitFactorDesc": "Total profit ÷ Total loss (>1 = profitable)",
    "trading.riskRewardRatio": "Risk/Reward",
    "trading.riskRewardDesc": "Avg win ÷ Avg loss",
    "trading.maxWinStreak": "Max Win Streak",
    "trading.maxWinStreakDesc": "Consecutive winning trades",
    "trading.consecutive": " in a row",
    "trading.avgWinShort": "Avg Win",
    "trading.avgLossShort": "Avg Loss",
    "trading.tradeCountShort": "",
    "trading.mdd": "MDD",
    "trading.mddDesc": "Maximum Drawdown (Peak to trough decline)",
    "trading.alpha": "Alpha",
    "trading.alphaDesc": "Excess return vs market",
    "trading.beta": "Beta",
    "trading.betaDesc": "Volatility vs market (1 = same as market)",
    "trading.sharpeRatio": "Sharpe Ratio",
    "trading.sharpeDesc": "Risk-adjusted return (higher is better)",
    "trading.informationRatio": "Information Ratio",
    "trading.informationRatioDesc": "Excess return per tracking error",
    "trading.riskAdjustedMetrics": "Risk-Adjusted Metrics",
    "trading.dataPeriod": "Data Period",
    // Tooltip explanations
    "trading.profitFactorTooltip": "Total profit divided by total loss. Shows how many times your winners exceed your losers in absolute terms.",
    "trading.profitFactorGood": "✓ Above 1.5: Excellent (Profits are 1.5x losses)",
    "trading.profitFactorNeutral": "• 1.0-1.5: Average (Profits exceed losses)",
    "trading.profitFactorBad": "✗ Below 1.0: Warning (Losses exceed profits)",
    "trading.riskRewardTooltip": "Average winning trade divided by average losing trade. Shows how much you win on average compared to how much you lose.",
    "trading.riskRewardGood": "✓ Above 2.0: Excellent (Wins are 2x losses)",
    "trading.riskRewardNeutral": "• 1.0-2.0: Average (Wins exceed losses)",
    "trading.riskRewardBad": "✗ Below 1.0: Warning (Losses exceed wins)",
    "trading.mddTooltip": "Maximum Drawdown. The largest peak-to-trough decline during the investment period. Shows your worst-case scenario loss.",
    "trading.mddGood": "✓ Below 10%: Excellent (Stable management)",
    "trading.mddNeutral": "• 10%-20%: Average (Normal volatility)",
    "trading.mddBad": "✗ Above 20%: Warning (High volatility)",
    "trading.alphaTooltip": "Excess return above the market (KOSPI). A key measure of investment skill - shows how much more (or less) you earned compared to the market.",
    "trading.alphaGood": "✓ Positive (+): Beating the market",
    "trading.alphaBad": "✗ Negative (-): Underperforming the market",
    "trading.betaTooltip": "Measures volatility relative to the market. Shows how much your portfolio moves when the market moves 1%.",
    "trading.betaLow": "◐ Below 1: Lower volatility (More stable than market)",
    "trading.betaNeutral": "• 1.0: Same volatility as market",
    "trading.betaHigh": "◐ Above 1: Higher volatility (More aggressive than market)",
    "trading.sharpeTooltip": "Risk-adjusted return. Shows how much excess return (above risk-free rate like savings interest) you achieved per unit of risk taken.",
    "trading.sharpeGood": "✓ Above 1.0: Excellent (High return for risk taken)",
    "trading.sharpeNeutral": "• 0-1.0: Average (Acceptable level)",
    "trading.sharpeBad": "✗ Below 0: Warning (Worse than risk-free assets)",
    "trading.irTooltip": "Excess return over benchmark (KOSPI) divided by tracking error. Evaluates how consistently you beat the market.",
    "trading.irGood": "✓ Above 0.5: Excellent (Consistently beats market)",
    "trading.irNeutral": "• 0-0.5: Average (Slight outperformance)",
    "trading.irBad": "✗ Below 0: Warning (Underperforming market)",

    // Watchlist Page
    "watchlist.title": "Watchlist",
    "watchlist.description": "AI-analyzed investment candidates (Last 1 month)",
    "watchlist.totalStocks": "Total Stocks",
    "watchlist.stocksCount": " stocks",
    "watchlist.highestScore": "Highest Score",
    "watchlist.avgScore": "Avg Score",
    "watchlist.recentWeek": "Last 7 days",
    "watchlist.scoreUnit": " pts",
    "watchlist.entry": "Entry",
    "watchlist.watch": "No Entry",
    "watchlist.entryChecklist": "Entry Checklist",
    "watchlist.rejectionReason": "Rejection Reason",
    "watchlist.reason": "Reason",
    "watchlist.analyzedDate": "Analyzed",
    "watchlist.buyScore": "Buy Score",
    "watchlist.currentPrice": "Current",
    "watchlist.targetPrice": "Target",
    "watchlist.stopLoss": "Stop Loss",
    "watchlist.tradingRationale": "Trading Rationale",
    "watchlist.noData": "No watchlist items yet.",
    "watchlist.mostPromising": "Most promising stock",
    "watchlist.outOf10": "Out of 10",
    "watchlist.recentlyAnalyzed": "Recently analyzed",
    "watchlist.sectorDistributionTop3": "Sector Distribution TOP 3",
    "watchlist.analyses": " analyses",
    "watchlist.aiAnalysisDetails": "AI Analysis Details",
    "watchlist.copyToClipboard": "Copy to Clipboard",
    "watchlist.lastMonthAnalysis": "Last month analysis",
    "watchlist.decision": "Decision",
    "watchlist.stocksUnit": " stocks",

    // Trading Insights Page
    "insights.title": "Trading Insights",
    "insights.description": "Trigger performance analysis, AI trading principles, lessons, and accumulated intuitions",
    "insights.category.performance": "Performance Analysis",
    "insights.category.wisdom": "Trading Wisdom",
    "insights.principles": "Universal Principles",
    "insights.principlesDescription": "Core principles applicable to all trades",
    "insights.journal": "Trading Journal",
    "insights.journalDescription": "Detailed records written by AI after trade completion",
    "insights.intuitions": "Accumulated Intuitions",
    "insights.intuitionsDescription": "Long-term insights extracted from repeated patterns",
    "insights.summary.totalPrinciples": "Total Principles",
    "insights.summary.highPriority": "High Priority",
    "insights.summary.avgProfit": "Avg Profit",
    "insights.summary.totalTrades": "Total Trades",
    "insights.summary.totalIntuitions": "Total Intuitions",
    "insights.summary.avgConfidence": "Avg Confidence",
    "insights.priority.high": "High",
    "insights.priority.medium": "Medium",
    "insights.priority.low": "Low",
    "insights.scope.universal": "Universal",
    "insights.scope.sector": "Sector",
    "insights.scope.market": "Market",
    "insights.condition": "Condition",
    "insights.action": "Action",
    "insights.reason": "Reason",
    "insights.confidence": "Confidence",
    "insights.supportingTrades": "Supporting Trades",
    "insights.situationAnalysis": "Situation Analysis",
    "insights.judgmentEvaluation": "Judgment Evaluation",
    "insights.lessons": "Lessons",
    "insights.patternTags": "Pattern Tags",
    "insights.oneLine": "One-line Summary",
    "insights.category": "Category",
    "insights.insight": "Insight",
    "insights.successRate": "Success Rate",
    "insights.supportingTrades": "Supporting Trades",
    "insights.noData": "No trading insights data available yet.",
    "insights.noPrinciples": "No principles extracted yet.",
    "insights.noJournal": "No trading journal entries yet.",
    "insights.noIntuitions": "No intuitions accumulated yet.",
    "insights.layer": "Layer",
    "insights.holdingDays": "Holding Days",
    "insights.profitRate": "Profit Rate",
    "insights.tradeDate": "Trade Date",

    // Performance Analysis
    "insights.performance.title": "Trigger Performance Analysis",
    "insights.performance.description": "Track 7/14/30 day price changes of analyzed stocks",
    "insights.performance.overview": "Tracking Status",
    "insights.performance.total": "Total Tracked",
    "insights.performance.completed": "Completed",
    "insights.performance.pending": "Pending",
    "insights.performance.inProgress": "In Progress",
    "insights.performance.traded": "Traded",
    "insights.performance.watched": "Watched",
    "insights.performance.triggerType": "Watched Stocks by Trigger Type",
    "insights.performance.rrAnalysis": "Risk/Reward Threshold Analysis",
    "insights.performance.missedOpportunities": "Missed Opportunities",
    "insights.performance.avoidedLosses": "Avoided Losses",
    "insights.performance.recommendations": "Data-Driven Recommendations",
    "insights.performance.avgReturn": "Avg Return",
    "insights.performance.winRate": "Win Rate",
    "insights.performance.count": "Count",
    "insights.performance.significant": "Statistically Significant",
    "insights.performance.notSignificant": "Not Significant",
    "insights.performance.noData": "No performance tracking data yet",
    "insights.performance.noDataHint": "Data will be available once stock tracking completes",
    "insights.performance.tradedRate": "Trade Rate",
    "insights.performance.day7": "7D",
    "insights.performance.day14": "14D",
    "insights.performance.day30": "30D",
    "insights.performance.range": "Range",
    "insights.performance.allAvg": "All Avg",
    "insights.performance.watchedAvg": "Watched Avg",
    "insights.performance.skipReason": "Skip Reason",
    "insights.performance.analyzedPrice": "Analyzed Price",
    "insights.performance.trackedPrice": "Tracked Price",
    "insights.performance.returnRate": "Return",
    // Tooltip translations
    "insights.performance.tooltip.completed": "Stocks with 30 days passed since analysis (tracking complete)",
    "insights.performance.tooltip.pending": "Stocks with less than 7 days since analysis (awaiting tracking)",
    "insights.performance.tooltip.inProgress": "Stocks between 7-30 days since analysis (tracking in progress)",
    "insights.performance.tooltip.traded": "Number of stocks actually purchased after analysis",
    "insights.performance.tooltip.watched": "Number of stocks watched without purchasing after analysis",
    "insights.performance.tooltip.dayReturn": "Average return N days after analysis (based on completed tracking)",
    "insights.performance.tooltip.winRate": "Percentage of stocks with positive return after 30 days",
    "insights.performance.tooltip.tradedRate": "Percentage of this trigger type that led to actual trades",

    // Trigger Reliability Card
    "insights.triggerReliability.title": "Trigger Reliability",
    "insights.triggerReliability.description": "Which signals can you trust? Cross-analysis of accuracy, trading, and principles",
    "insights.triggerReliability.bestTrigger": "Best Trigger",
    "insights.triggerReliability.grade": "Grade",
    "insights.triggerReliability.analysisAccuracy": "Analysis Accuracy",
    "insights.triggerReliability.actualTrading": "Actual Trading",
    "insights.triggerReliability.principles": "Related Principles",
    "insights.triggerReliability.recommendation": "Recommendation",
    "insights.triggerReliability.tracked": "Tracked",
    "insights.triggerReliability.completed": "Completed",
    "insights.triggerReliability.trades": "Trades",
    "insights.triggerReliability.winRate": "Win Rate",
    "insights.triggerReliability.avgReturn": "Avg Return",
    "insights.triggerReliability.profitFactor": "PF",
    "insights.triggerReliability.noData": "No trigger reliability data available yet.",
    "insights.triggerReliability.gradeA": "High Confidence",
    "insights.triggerReliability.gradeB": "Good",
    "insights.triggerReliability.gradeC": "Caution",
    "insights.triggerReliability.gradeD": "Insufficient Data",
    "insights.triggerReliability.miniBadge": "Most Reliable Trigger",
    "insights.triggerReliability.viewDetails": "View Details",

    // Footer
    "footer.description": "AI-powered Stock Analysis & Trading System",
    "footer.openSource": "Fully Open Source & Free • MIT License",
    "footer.features": "Key Features",
    "footer.feature1": "12 AI Agents Collaborative Analysis",
    "footer.feature2": "Automated Surge Stock Detection & Reports",
    "footer.feature3": "Trading Simulation & Auto Trading",
    "footer.feature4": "Real-time Performance Dashboard",
    "footer.links": "Quick Links",
    "footer.sourceCode": "Source Code & Issues",
    "footer.telegramDesc": "Surge Stocks & Analysis Reports",
    "footer.stars": "250+ Stars in 10 weeks",
    "footer.disclaimer": "⚠️ The analysis information provided by this system is for reference only and is not intended as investment advice. All investment decisions and resulting profits/losses are the sole responsibility of the investor.",
  },
}

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const [language, setLanguageState] = useState<Language>("ko")

  // Load language from localStorage on mount
  useEffect(() => {
    const stored = localStorage.getItem("language") as Language
    if (stored === "ko" || stored === "en") {
      setLanguageState(stored)
    }
  }, [])

  // Save language to localStorage when it changes
  const setLanguage = (lang: Language) => {
    setLanguageState(lang)
    localStorage.setItem("language", lang)
  }

  // Translation function
  const t = (key: string): string => {
    return translations[language][key] || key
  }

  return (
    <LanguageContext.Provider value={{ language, setLanguage, t }}>
      {children}
    </LanguageContext.Provider>
  )
}

export function useLanguage() {
  const context = useContext(LanguageContext)
  if (context === undefined) {
    throw new Error("useLanguage must be used within a LanguageProvider")
  }
  return context
}
