// ====================================================================
// i18n — strings ES / 中文.  En fase 2 estas claves no cambian:
// la API real devuelve los textos de datos ya traducidos (campo lang_zh).
// ====================================================================
const STR = {
  es: {
    // chrome
    entity: "Crece by QFIN",
    monitored: "Monitoreo Activo de Inteligencia Reputacional · México",
    health: "Índice de Salud Reputacional",
    p_today: "Hoy", p_d7: "7 días", p_d30: "30 días",
    search: "Buscar mención, fuente, tema…",
    live: "EN VIVO",
    kiosk: "Modo kiosko",
    kioskExit: "Salir",
    sources: "Fuentes conectadas",
    updated: "Actualizado hace 2 min",
    // nav
    nav_summary: "Dashboard reseñas Qcrece",
    nav_mentions: "Menciones",
    nav_competitors: "Benchmark de reseñas",
    nav_collection: "Cobranza",
    nav_narratives: "Narrativas",
    nav_alerts: "Alertas",
    nav_intel: "Inteligencia",
    nav_market: "Mercado",
    // titles
    title_summary: "Resumen Analítico de Reseñas en México",
    title_competitors: "Análisis de Reseñas de Competidores",
    title_reviews: "Análisis Detallado de Reseñas del Competidor",
    // summary
    sum_desc: "Diagnóstico del estado reputacional de la marca Crece y análisis de la contaminación por la categoría de préstamos y cobranza extrajudicial.",
    kpi_risk: "Índice de Riesgo Reputacional (Hoy)",
    kpi_contam: "Nivel de Contaminación de la Categoría",
    kpi_mentions: "Total Menciones (Últimas 24 Horas)",
    kpi_alerts: "Alertas Críticas Activas",
    sentiment30: "Tendencia de Sentimiento sobre Crece · Últimos 30 días",
    positive: "Positivo (Favorable)", neutral: "Reseñas Mixtas", negative: "Negativo (Crítico)",
    negative_severe: "Negativo (Severo)", negative_mild: "Negativo (Leve)",
    contam_title: "Medidor de Contaminación de Marca",
    contam_sub: "Nivel de impacto y salpicadura de la conversación negativa de la categoría hacia Crece",
    zone_safe: "Zona Segura", zone_watch: "Vigilancia Preventiva", zone_crisis: "Crisis Reputacional",
    live_risks: "Riesgos Prioritarios Detectados",
    live_risks_sub: "Incidentes ordenados por nivel de severidad y velocidad de propagación",
    resolve: "Gestionar Caso", not_actionable: "No Accionable", view: "Ver Detalles",
    // mentions
    men_desc: "Flujo completo de menciones, filtrable por plataforma, sentimiento, tema y alcance.",
    th_source: "Fuente", th_author: "Autor", th_reach: "Alcance", th_excerpt: "Extracto",
    th_topic: "Tema", th_sentiment: "Sentimiento", th_severity: "Severidad", th_action: "Acción",
    f_platform: "Plataforma", f_sentiment: "Sentimiento", f_topic: "Tema", all: "Todas",
    f_layer: "Fuente",
    layer_comunidades: "Foros & Comunidades",
    layer_resenas: "Reseñas de Apps",
    layer_prensa: "Prensa & Regulatorio",
    results: "menciones",
    // competitors
    comp_desc: "Análisis comparativo del panorama competitivo. Monitoreo de Crece contra Kueski (referente de mercado).",
    kosher: "Club Kosher (Fintechs Reguladas)", kosher_sub: "Entidades financieras reguladas y legítimas con un sentimiento de conversación saludable",
    aztlan: "Clúster Controvertido (Riesgo Alto)", aztlan_sub: "Competidores con alta acumulación de quejas por cobranza agresiva y riesgo de contagio",
    benchmark: "Referente (Benchmark)", sov: "Cuota de Voz (Share of Voice)", complaints: "quejas cobranza",
    sov_chart: "Distribución de Cuota de Voz (Share of Voice) · Últimos 30 Días", you: "Nuestra Marca (Crece)",
    // collection
    col_desc: "Agresividad de cobranza por competidor y plataforma. Verde = limpio, rojo = extorsivo.",
    heat_title: "Heatmap de agresividad de cobranza",
    raw_complaints: "Quejas crudas clasificadas por IA",
    ai_class: "Clasificación IA",
    legend_low: "Baja", legend_high: "Extrema",
    // narratives
    narr_desc: "Evolución de los temas de conversación, feb 2025 → hoy. Volumen y tono.",
    narr_title: "Línea de tiempo de narrativas",
    vol: "Volumen", tone: "Tono",
    // alerts
    alert_desc: "Crisis emergentes ordenadas por velocidad de viralización.",
    threshold: "Umbral disparado", velocity: "Velocidad", since: "Detectada", mentions_h: "menc/h",
    // drawer
    detail: "Detalle de mención", open_post: "Abrir publicación original",
    severity: "Severidad", reach: "Alcance estimado", sentiment: "Sentimiento", platform: "Plataforma",
    ai_resp: "Respuesta propuesta por IA", ai_resp_sub: "Editable · loop de cobranza / reputación",
    regen: "Regenerar", approve: "Aprobar y enviar", copy: "Copiar",
    not_act_title: "Fuente no accionable",
    not_act_body: "Esta fuente es un medio de comunicación, no un canal propio. No se puede responder directamente. Sugerencia: reforzar comunicación positiva y monitorear difusión.",
    reinforce: "Reforzar comunicación positiva",
    actionable: "Accionable", source_type: "Tipo de fuente",
    own_channel: "Canal propio", press: "Prensa / medio", social: "Red social",
    // topics
    topic_cobranza: "Cobranza", topic_tasas: "Tasas", topic_china: "Empresa china",
    topic_ia: "IA / algoritmo", topic_fraude: "Fraude", topic_servicio: "Servicio",
    // misc
    of: "de", trend_up: "vs ayer", high: "Alta", medium: "Media", low: "Baja",
    kiosk_rotating: "Rotando cada 15 s · pantalla de oficina Shanghái",
    // ingest / loading
    ingest_btn: "Actualizar datos",
    loading_title: "Actualizando datos",
    loading_sub1: "Obteniendo reseñas de Play Store y App Store…",
    loading_sub2: "Analizando prensa, CONDUSEF y foros…",
    loading_sub3: "Motor de análisis procesando el lote completo — puede tardar 1–2 min",
    loading_sub4: "Guardando resultados y generando resúmenes…",
    loading_done: "✓ Datos actualizados. Recargando…",
    loading_err: "Error al conectar con el backend.",
    // filters & table reviews
    all_f: "Todas",
    negative_f: "Negativas",
    positive_f: "Positivas",
    neutral_f: "Neutrales",
    app_store_f: "App Store",
    play_store_f: "Play Store",
    all_stores_f: "Todas las Tiendas",
    date_from_f: "Desde",
    date_to_f: "hasta",
    back_to_comps: "← Volver a Competidores",
    page_f: "página",
    prev_f: "← Anterior",
    next_f: "Siguiente →",
    view_original_f: "Ver",
    store_label: "Tienda",
    author_label: "Autor",
    score_label: "★ Calificación",
    review_label: "Reseña",
    sentiment_label: "Sentimiento",
    severity_label: "Severidad",
    date_label: "Fecha",
    link_label: "Enlace",
    // deep research
    deep_research_btn: "Deep Research",
    deep_research_title: "Investigación Profunda",
    deep_research_sub: "Búsqueda avanzada en tiempo real sobre lo que dicen usuarios, medios y foros del periodo analizado.",
    deep_research_loading: "Investigando… rastreando la web en tiempo real. Esto puede tardar 1–3 minutos.",
    deep_research_phase1: "Conectando con motor de búsqueda profunda…",
    deep_research_phase2: "Rastreando foros, medios y tiendas…",
    deep_research_phase3: "Consolidando hallazgos del periodo…",
    deep_research_phase4: "Generando resumen de resultados…",
    deep_research_summary: "Resumen IA",
    deep_research_sources: "Fuentes encontradas",
    deep_research_query: "Query ejecutada",
    deep_research_period: "Período analizado",
    deep_research_err: "Error en Deep Research",
    deep_research_no_tavily: "Motor de búsqueda profunda no configurado. Define la clave correspondiente en el archivo .env.",
    deep_research_retry: "Reintentar",
    deep_research_new: "Nueva búsqueda",
  },
  en: {
    // chrome
    entity: "Crece by QFIN",
    monitored: "Active Reputation Intelligence Monitoring · Mexico",
    health: "Reputational Health Index",
    p_today: "Today", p_d7: "7 days", p_d30: "30 days",
    search: "Search mentions, sources, topics…",
    live: "LIVE",
    kiosk: "Kiosk mode",
    kioskExit: "Exit",
    sources: "Connected sources",
    updated: "Updated 2 min ago",
    // nav
    nav_summary: "Qcrece review dashboard",
    nav_mentions: "Mentions",
    nav_competitors: "Review benchmark",
    nav_collection: "Collection",
    nav_narratives: "Narratives",
    nav_alerts: "Alerts",
    nav_intel: "Intelligence",
    nav_market: "Market",
    // titles
    title_summary: "Analytical Review Summary in Mexico",
    title_competitors: "Competitor Review Analysis",
    title_reviews: "Detailed Competitor Review Analysis",
    // summary
    sum_desc: "Diagnosis of the reputational health of the Crece brand and analysis of category contamination from loans and extrajudicial collections.",
    kpi_risk: "Reputational Risk Index (Today)",
    kpi_contam: "Category Contamination Level",
    kpi_mentions: "Total Mentions (Last 24 Hours)",
    kpi_alerts: "Active Critical Alerts",
    sentiment30: "Sentiment Trend on Crece · Last 30 days",
    positive: "Positive (Favorable)", neutral: "Mixed Reviews", negative: "Negative (Critical)",
    negative_severe: "Negative (Severe)", negative_mild: "Negative (Mild)",
    contam_title: "Brand Contamination Gauge",
    contam_sub: "Level of impact and overflow from the category's negative conversation towards Crece",
    zone_safe: "Safe Zone", zone_watch: "Preventive Watch", zone_crisis: "Reputational Crisis",
    live_risks: "Detected Priority Risks",
    live_risks_sub: "Incidents sorted by severity level and propagation speed",
    resolve: "Resolve Case", not_actionable: "Not Actionable", view: "View Details",
    // mentions
    men_desc: "Complete stream of mentions, filterable by platform, sentiment, topic, and reach.",
    th_source: "Source", th_author: "Author", th_reach: "Reach", th_excerpt: "Excerpt",
    th_topic: "Topic", th_sentiment: "Sentiment", th_severity: "Severity", th_action: "Action",
    f_platform: "Platform", f_sentiment: "Sentiment", f_topic: "Topic", all: "All",
    f_layer: "Source",
    layer_comunidades: "Forums & Communities",
    layer_resenas: "App Reviews",
    layer_prensa: "Press & Regulatory",
    results: "mentions",
    // competitors
    comp_desc: "Comparative analysis of the competitive landscape. Monitoring Crece against Kueski (market benchmark).",
    kosher: "Kosher Club (Regulated Fintechs)", kosher_sub: "Regulated and legitimate financial entities with healthy conversation sentiment",
    aztlan: "Controversial Cluster (High Risk)", aztlan_sub: "Competitors with a high concentration of complaints for aggressive collection and spillover risk",
    benchmark: "Reference (Benchmark)", sov: "Share of Voice (SoV)", complaints: "collection complaints",
    sov_chart: "Share of Voice (SoV) Distribution · Last 30 Days", you: "Our Brand (Crece)",
    // collection
    col_desc: "Collection aggressiveness by competitor and platform. Green = clean, red = extortive.",
    heat_title: "Collection aggressiveness heatmap",
    raw_complaints: "Raw complaints classified by AI",
    ai_class: "AI Classification",
    legend_low: "Low", legend_high: "Extreme",
    // narratives
    narr_desc: "Evolution of conversation topics, Feb 2025 → today. Volume and tone.",
    narr_title: "Narratives timeline",
    vol: "Volume", tone: "Tone",
    // alerts
    alert_desc: "Emerging crises sorted by viralization speed.",
    threshold: "Triggered threshold", velocity: "Velocity", since: "Detected", mentions_h: "mentions/h",
    // drawer
    detail: "Mention detail", open_post: "Open original post",
    severity: "Severity", reach: "Estimated reach", sentiment: "Sentiment", platform: "Platform",
    ai_resp: "Proposed AI response", ai_resp_sub: "Editable · collection / reputation loop",
    regen: "Regenerate", approve: "Approve and send", copy: "Copy",
    not_act_title: "Source not actionable",
    not_act_body: "This source is a news outlet, not a self-owned channel. Direct replies are not possible. Suggestion: reinforce positive communication and monitor dissemination.",
    reinforce: "Reinforce positive communication",
    actionable: "Actionable", source_type: "Source type",
    own_channel: "Own channel", press: "Press / media", social: "Social media",
    // topics
    topic_cobranza: "Collection", topic_tasas: "Rates", topic_china: "Chinese company",
    topic_ia: "AI / algorithm", topic_fraude: "Fraud", topic_servicio: "Service",
    // misc
    of: "of", trend_up: "vs yesterday", high: "High", medium: "Medium", low: "Low",
    kiosk_rotating: "Rotating every 15s · Shanghai office screen",
    // ingest / loading
    ingest_btn: "Update data",
    loading_title: "Updating data",
    loading_sub1: "Fetching Play Store and App Store reviews…",
    loading_sub2: "Analyzing press, CONDUSEF and forums…",
    loading_sub3: "Analysis engine processing the complete batch — might take 1–2 min",
    loading_sub4: "Saving results and generating summaries…",
    loading_done: "✓ Data updated. Reloading…",
    loading_err: "Error connecting to backend.",
    // filters & table reviews
    all_f: "All",
    negative_f: "Negative",
    positive_f: "Positive",
    neutral_f: "Neutral",
    app_store_f: "App Store",
    play_store_f: "Play Store",
    all_stores_f: "All Stores",
    date_from_f: "From",
    date_to_f: "to",
    back_to_comps: "← Back to Competitors",
    page_f: "page",
    prev_f: "← Previous",
    next_f: "Next →",
    view_original_f: "View",
    store_label: "Store",
    author_label: "Author",
    score_label: "★ Rating",
    review_label: "Review",
    sentiment_label: "Sentiment",
    severity_label: "Severity",
    date_label: "Date",
    link_label: "Link",
    // deep research
    deep_research_btn: "Deep Research",
    deep_research_title: "Deep Research",
    deep_research_sub: "Advanced real-time search on what users, media, and forums say about the analyzed period.",
    deep_research_loading: "Researching… crawling the web in real-time. This might take 1–3 minutes.",
    deep_research_phase1: "Connecting to deep search engine…",
    deep_research_phase2: "Crawling forums, media, and app stores…",
    deep_research_phase3: "Consolidating period findings…",
    deep_research_phase4: "Generating summary of results…",
    deep_research_summary: "AI Summary",
    deep_research_sources: "Found sources",
    deep_research_query: "Executed query",
    deep_research_period: "Analyzed period",
    deep_research_err: "Error in Deep Research",
    deep_research_no_tavily: "Deep search engine not configured. Define corresponding key in .env file.",
    deep_research_retry: "Retry",
    deep_research_new: "New research",
  },
  zh: {
    // chrome
    entity: "Crece by QFIN",
    monitored: "墨西哥市场品牌声誉情报实时监测",
    health: "品牌声誉健康度指数",
    p_today: "今日", p_d7: "7 天", p_d30: "30 天",
    search: "搜索提及、来源、主题…",
    live: "实时",
    kiosk: "看板模式",
    kioskExit: "退出",
    sources: "已连接数据源",
    updated: "2 分钟前更新",
    // nav
    nav_summary: "总览",
    nav_mentions: "提及",
    nav_competitors: "竞争对手",
    nav_collection: "催收",
    nav_narratives: "舆论叙事",
    nav_alerts: "预警",
    nav_intel: "情报",
    nav_market: "市场",
    // titles
    title_summary: "墨西哥用户评价分析摘要",
    title_competitors: "竞争对手评价分析",
    title_reviews: "竞争对手用户评价明细分析",
    // summary
    sum_desc: "关于 Crece 品牌声誉现状的诊断，以及防范‘高利贷/非法催收’等同类竞品负面话题波及的污染分析。",
    kpi_risk: "今日品牌声誉风险指数",
    kpi_contam: "行业负面话题波及污染度",
    kpi_mentions: "24小时全网舆情提及总量",
    kpi_alerts: "当前活跃的高危舆情预警",
    sentiment30: "Crece 品牌情感趋势变化 · 最近30天",
    positive: "正面 (有利舆情)", neutral: "中性 (常规记录)", negative: "负面 (高危预警)",
    negative_severe: "负面 (极度危险)", negative_mild: "负面 (轻微)",
    contam_title: "品牌声誉受污染度仪表盘",
    contam_sub: "评估同类竞品非法催收等负面话题对 Crece 品牌声誉的影响及波及程度",
    zone_safe: "安全区域", zone_watch: "预防性监视区", zone_crisis: "声誉危机爆发区",
    live_risks: "亟需处置的优先风险点",
    live_risks_sub: "根据负面信息严重程度与全网传播扩散速度进行排序的风险事件",
    resolve: "立即介入处理", not_actionable: "无需/无法直接处置", view: "查看事件详情",
    // mentions
    men_desc: "完整提及流，可按平台、情感、主题与覆盖量筛选。",
    th_source: "来源", th_author: "作者", th_reach: "覆盖量", th_excerpt: "摘录",
    th_topic: "主题", th_sentiment: "情感", th_severity: "严重度", th_action: "操作",
    f_platform: "平台", f_sentiment: "情感", f_topic: "主题", all: "全部",
    f_layer: "数据来源",
    layer_comunidades: "论坛与社群",
    layer_resenas: "应用商店评价",
    layer_prensa: "新闻与监管",
    results: "条提及",
    // competitors
    comp_desc: "竞品舆情全景分析。重点关注本品牌 Crece 与市场标杆 Kueski 的对比数据。",
    kosher: "合规准入阵营 (合规金融科技)", kosher_sub: "持牌合规运营、声誉健康度良好的合法金融科技企业",
    aztlan: "争议高危集群 (防范传染风险)", aztlan_sub: "因暴力或不当催收导致投诉量极高的竞争对手，需防范其对整个行业声誉的负面波及",
    benchmark: "行业标杆 (Benchmark)", sov: "全网声量份额 (Share of Voice)", complaints: "条催收投诉",
    sov_chart: "全网舆情声量份额分布趋势 · 最近30天", you: "本品牌 (Crece)",
    // collection
    col_desc: "各竞品、各平台的催收激进度。绿色=干净，红色=暴力催收。",
    heat_title: "催收激进度热力图",
    raw_complaints: "AI 已分类 of 原始投诉",
    ai_class: "AI 分类",
    legend_low: "低", legend_high: "极高",
    // narratives
    narr_desc: "话题演变，2025 年 2 月至今。声量与语调。",
    narr_title: "舆论叙事时间线",
    vol: "声量", tone: "语调",
    // alerts
    alert_desc: "按传播速度排序的新兴危机。",
    threshold: "触发阈值", velocity: "速度", since: "发现于", mentions_h: "提及/小时",
    // drawer
    detail: "提及详情", open_post: "打开原始帖子",
    severity: "严重度", reach: "预估覆盖量", sentiment: "情感", platform: "平台",
    ai_resp: "AI 建议回复", ai_resp_sub: "可编辑 · 催收/声誉闭环",
    regen: "重新生成", approve: "批准并发送", copy: "复制",
    not_act_title: "来源不可操作",
    not_act_body: "该来源为新闻媒体，并非自有渠道，无法直接回复。建议：强化正面传播并监测扩散。",
    reinforce: "强化正面传播",
    actionable: "可操作", source_type: "来源类型",
    own_channel: "自有渠道", press: "新闻/媒体", social: "社交媒体",
    // topics
    topic_cobranza: "催收", topic_tasas: "利率", topic_china: "中国企业",
    topic_ia: "AI / 算法", topic_fraude: "欺诈", topic_servicio: "服务",
    of: "/", trend_up: "较昨日", high: "高", medium: "中", low: "低",
    kiosk_rotating: "每 15 秒轮播 · 上海办公室大屏",
    // ingest / loading
    ingest_btn: "更新数据",
    loading_title: "正在更新数据",
    loading_sub1: "正在获取 Play Store 和 App Store 评论…",
    loading_sub2: "正在分析新闻、CONDUSEF 与论坛…",
    loading_sub3: "分析引擎正在分析批次 — 可能需要 1–2 分钟",
    loading_sub4: "正在保存结果并生成摘要…",
    loading_done: "✓ 数据已更新，正在刷新…",
    loading_err: "无法连接到服务器。",
    // filters & table reviews
    all_f: "全部",
    negative_f: "负面/差评",
    positive_f: "正面/好评",
    neutral_f: "中性评价",
    app_store_f: "苹果应用商店 (App Store)",
    play_store_f: "谷歌应用商店 (Play Store)",
    all_stores_f: "所有应用商店",
    date_from_f: "开始日期",
    date_to_f: "结束日期",
    back_to_comps: "← 返回竞争对手列表",
    page_f: "页",
    prev_f: "← 上一页",
    next_f: "下一页 →",
    view_original_f: "查看原文",
    store_label: "应用商店",
    author_label: "用户作者",
    score_label: "★ 评分",
    review_label: "评价内容",
    sentiment_label: "情感倾向",
    severity_label: "严重程度",
    date_label: "发布时间",
    link_label: "源链接",
    // deep research
    deep_research_btn: "深度调研",
    deep_research_title: "深度调研",
    deep_research_sub: "对 2026 年 5 月用户评价、媒体报道和论坛讨论进行实时深度搜索。",
    deep_research_loading: "正在深度调研…正在实时抓取全网数据，可能需要 1–3 分钟，请耐心等待。",
    deep_research_phase1: "正在连接深度搜索引擎…",
    deep_research_phase2: "正在抓取论坛、媒体与应用商店…",
    deep_research_phase3: "正在整合 2026 年 5 月的发现…",
    deep_research_phase4: "正在生成调研结果摘要…",
    deep_research_summary: "AI 摘要",
    deep_research_sources: "找到的信息来源",
    deep_research_query: "执行的搜索词",
    deep_research_period: "分析周期",
    deep_research_err: "深度调研出错",
    deep_research_no_tavily: "深度搜索引擎未配置，请在后端配置文件中设置 API 密钥。",
    deep_research_retry: "重试",
    deep_research_new: "发起新调研",
  }
};;

const LangContext = React.createContext({ lang: "es", t: (k) => k });

function useLang() { return React.useContext(LangContext); }

// helper: pick localized value from a {es, zh} object (mock data shape)
function L(obj, lang) {
  if (obj == null) return "";
  if (typeof obj === "string") return obj;
  return obj[lang] || obj.es || "";
}

window.STR = STR;
window.LangContext = LangContext;
window.useLang = useLang;
window.L = L;
