import type { Metadata } from 'next'
import Link from 'next/link'

const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://trumpsignal.com'

type GlossaryTerm = {
  term: string
  abbr?: string
  category: string
  definition: string
  extra?: string
}

type GlossaryCopy = {
  title: string
  description: string
  keywords: string[]
  ogTitle: string
  ogDescription: string
  heroTitle: string
  heroSubtitle: string
  intro: string
  terms: GlossaryTerm[]
  footerLead: string
  footerContact: string
  footerMethodology: string
  footerCaseStudies: string
}

function getCopy(locale: string): GlossaryCopy {
  const isZh = false  // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json

  if (isZh) {
    return {
      title: '加密信号术语表 - Trump Alpha',
      description:
        '系统化定义 Trump Alpha 使用的核心术语，包括 AHR999、Pi Cycle Bottom、200 周均线、KOL、言行偏离、资金费率、Conviction Score、逐仓等。',
      keywords: [
        'AHR999 定义',
        'Pi Cycle Bottom 是什么',
        '200周均线',
        'KOL 是什么',
        '言行偏离',
        '资金费率',
        '逐仓',
        '加密信号术语表',
      ],
      ogTitle: 'Crypto Signals Glossary | Trump Alpha',
      ogDescription:
        'Trump Alpha 核心术语的清晰定义，适合搜索摘录、AI 引用和快速查阅。',
      heroTitle: '术语表',
      heroSubtitle: '把页面里所有关键实体和专业词说清楚',
      intro:
        '这份术语表服务两个目标：第一，帮助用户快速理解平台内的指标和信号；第二，让搜索引擎和 LLM 能稳定识别这些实体之间的关系。每个词条都尽量给出定义、上下文和在 Trump Alpha 里的具体用法。',
      terms: [
        {
          term: 'AHR999',
          category: '宏观底部指标',
          definition:
            'AHR999 是中文加密圈常用的比特币估值指标，通常结合长期趋势和成本锚来判断 BTC 是否进入深度价值区。在 Trump Alpha 里，AHR999 低于 0.45 被视为一个经典底部信号。',
          extra: '它是当前 BTC 2-of-3 周期底部扫描器中的三大输入之一。',
        },
        {
          term: 'Pi Cycle Bottom',
          category: '宏观底部指标',
          definition:
            'Pi Cycle Bottom 是一种基于长周期均线关系的比特币底部判定方法。Trump Alpha 使用的条件是 150 日 EMA 低于 471 日 SMA 乘以 0.745。',
          extra: '它也是 BTC 周期底部扫描器的三项核心输入之一。',
        },
        {
          term: '200-week Moving Average',
          category: '宏观底部指标',
          definition:
            '200 周均线是比特币最常见的超长周期趋势锚之一。历史上，多轮熊市低点都出现在这个区域附近。Trump Alpha 将价格接近或跌破该均线视为底部共振条件的一部分。',
        },
        {
          term: 'KOL',
          abbr: 'Key Opinion Leader',
          category: '平台术语',
          definition:
            '在加密语境里，KOL 指的是能持续影响市场叙事或零售情绪的分析师、基金经理、内容创作者或节目主持人。Trump Alpha 跟踪的是带有长期内容产出的 KOL，而不是只发碎片推文的账号。',
        },
        {
          term: 'Talks-vs-Trades Divergence',
          category: '平台术语',
          definition:
            '言行偏离指 KOL 公开表达的方向与链上钱包实际操作方向相反。例如公开看多 ETH，但钱包在同一周内减仓 ETH。Trump Alpha 把链上动作视作更高优先级的真实信号。',
          extra: '这是平台里信息密度最高的信号之一，因为它把公开叙事和真实仓位拆开来看。',
        },
        {
          term: 'Conviction Score',
          category: '平台术语',
          definition:
            'Conviction Score 是 AI 给每条 KOL 观点分配的强度分，范围通常在 0.0 到 1.0。分数越高，说明作者表达越明确、重复度越高，且更可能带有仓位、时间或执行语气。',
        },
        {
          term: 'Funding Rate',
          category: '衍生品术语',
          definition:
            '资金费率是永续合约用来锚定现货价格的周期性支付机制。多头付空头代表市场做多拥挤，空头付多头则代表市场做空拥挤。极端 funding 往往出现在清算前夜。',
        },
        {
          term: 'Isolated Margin',
          category: '交易术语',
          definition:
            '逐仓模式意味着每笔仓位只使用自己的保证金，不会和账户内其他持仓共用风险池。即使某笔交易被强平，也不会拖累其他持仓。',
          extra: 'Trump Alpha 的自动执行层默认按逐仓方式工作。',
        },
        {
          term: 'TP / SL',
          abbr: 'Take-Profit / Stop-Loss',
          category: '交易术语',
          definition:
            'TP 和 SL 分别表示止盈和止损条件单。Trump Alpha 的自动交易在开仓时就会挂好，而不是事后补挂。',
        },
        {
          term: 'UTXO',
          abbr: 'Unspent Transaction Output',
          category: '比特币术语',
          definition:
            'UTXO 是比特币网络中的基础记账单元。虽然 Trump Alpha 当前线上 BTC 信号不再直接使用 UTXO 花费行为，但理解 UTXO 仍有助于读懂很多经典链上研究。',
        },
        {
          term: 'Perpetual Future',
          abbr: 'Perp',
          category: '衍生品术语',
          definition:
            'Perp 是没有到期日的永续合约。它依靠资金费率和标记价格机制尽量贴近现货。Hyperliquid 就是提供 perp 交易的去中心化交易平台之一。',
        },
        {
          term: 'Substack Signal',
          category: '平台术语',
          definition:
            'Substack Signal 指从 KOL 的长文订阅、博客或深度文章中提取出的资产观点。相比短推文，这类内容通常更完整，因此更适合做高质量的观点抽取。',
        },
        {
          term: 'Capitulation',
          category: '市场术语',
          definition:
            'Capitulation 指持有者在持续亏损后集中放弃、被迫卖出的一段市场阶段。它往往出现在熊市尾声，也是 BTC 底部扫描器最希望捕捉的环境之一。',
        },
        {
          term: 'EMA',
          abbr: 'Exponential Moving Average',
          category: '技术术语',
          definition:
            'EMA 是指数移动平均线，对最近价格赋予更高权重，因此比简单均线更敏感。Trump Alpha 在 Pi Cycle Bottom 条件中使用 150 日 EMA。',
        },
      ],
      footerLead: '缺少某个词条？',
      footerContact: '联系我们',
      footerMethodology: '方法论',
      footerCaseStudies: '案例研究',
    }
  }

  return {
    title: 'Crypto Signals Glossary — AHR999, Pi Cycle Bottom, KOL Divergence',
    description:
      'Definitions of every core term used in Trump Alpha, including AHR999, Pi Cycle Bottom, 200-week moving average, KOL, talks-vs-trades divergence, funding rate, conviction score, and isolated margin.',
    keywords: [
      'AHR999 definition',
      'Pi Cycle Bottom explained',
      '200-week moving average Bitcoin',
      'what is KOL crypto',
      'talks vs trades definition',
      'funding rate crypto',
      'isolated margin perpetual',
      'crypto signal glossary',
    ],
    ogTitle: 'Crypto Signals Glossary | Trump Alpha',
    ogDescription:
      'Clear definitions of Trump Alpha’s core terms, optimized for search, AI retrieval, and fast reference.',
    heroTitle: 'Glossary',
    heroSubtitle: 'The precise meaning of every key entity and term on the platform',
    intro:
      'This glossary serves two jobs. First, it helps users understand the metrics and signal families inside Trump Alpha. Second, it gives search engines and LLMs a stable, retrieval-friendly map of the entities that appear across the product.',
    terms: [
      {
        term: 'AHR999',
        category: 'Macro-bottom metric',
        definition:
          'AHR999 is a Bitcoin valuation indicator popular in Chinese crypto research. It combines long-term trend and cost-basis style anchors to estimate whether BTC is trading in a deep-value regime. In Trump Alpha, AHR999 below 0.45 counts as one classic bottom signal.',
        extra: 'It is one of the three inputs in the live BTC 2-of-3 macro-bottom scanner.',
      },
      {
        term: 'Pi Cycle Bottom',
        category: 'Macro-bottom metric',
        definition:
          'Pi Cycle Bottom is a Bitcoin bottom framework based on long-cycle moving-average relationships. In Trump Alpha, the condition is satisfied when the 150-day EMA falls below the 471-day SMA multiplied by 0.745.',
        extra: 'It is one of the three core inputs in the BTC macro-bottom scanner.',
      },
      {
        term: '200-week Moving Average',
        category: 'Macro-bottom metric',
        definition:
          'The 200-week moving average is one of Bitcoin’s most widely watched long-term trend anchors. Many historical bear-market lows formed near this zone. Trump Alpha treats price proximity to the 200-week MA as part of BTC bottom confluence.',
      },
      {
        term: 'KOL',
        abbr: 'Key Opinion Leader',
        category: 'Platform term',
        definition:
          'In crypto, a KOL is an analyst, fund manager, host, or creator whose public views consistently influence market narrative or retail positioning. Trump Alpha emphasizes long-form KOL sources, not only short social fragments.',
      },
      {
        term: 'Talks-vs-Trades Divergence',
        category: 'Platform term',
        definition:
          'Talks-vs-trades divergence happens when a KOL’s public stance and wallet behavior point in opposite directions on the same asset. Example: a KOL publishes a bullish ETH thesis while their wallet reduces ETH exposure that same week. Trump Alpha treats the wallet move as the higher-priority truth signal.',
        extra: 'This is one of the platform’s highest-information signals because it separates narrative from actual positioning.',
      },
      {
        term: 'Conviction Score',
        category: 'Platform term',
        definition:
          'Conviction Score is the AI-generated strength score assigned to each extracted KOL view, typically ranging from 0.0 to 1.0. Higher values imply clearer language, stronger commitment, and better evidence of timing or sizing intent.',
      },
      {
        term: 'Funding Rate',
        category: 'Derivatives term',
        definition:
          'Funding rate is the periodic payment mechanism used by perpetual futures to keep contract pricing anchored to spot. If longs pay shorts, the market is long-crowded. If shorts pay longs, the market is short-crowded. Extreme readings often precede liquidation-driven reversals.',
      },
      {
        term: 'Isolated Margin',
        category: 'Trading term',
        definition:
          'Isolated margin means each trade uses its own dedicated margin rather than sharing risk with the rest of the account. If one position is liquidated, it does not automatically cascade into other positions.',
        extra: 'Trump Alpha’s execution layer is designed around isolated margin.',
      },
      {
        term: 'TP / SL',
        abbr: 'Take-Profit / Stop-Loss',
        category: 'Trading term',
        definition:
          'TP and SL are conditional exit orders for profit-taking and loss control. Trump Alpha’s auto-trader attaches both at entry rather than after the position is already open.',
      },
      {
        term: 'UTXO',
        abbr: 'Unspent Transaction Output',
        category: 'Bitcoin term',
        definition:
          'UTXO is the fundamental accounting unit of the Bitcoin network. Trump Alpha’s live BTC signal no longer relies directly on UTXO-spend behavior, but the concept still matters for interpreting classic on-chain research.',
      },
      {
        term: 'Perpetual Future',
        abbr: 'Perp',
        category: 'Derivatives term',
        definition:
          'A perp is a futures contract with no expiry date. It stays open until the trader closes it or gets liquidated, while funding rate and mark-price mechanisms help keep it close to spot. Hyperliquid is one example of a perp venue.',
      },
      {
        term: 'Substack Signal',
        category: 'Platform term',
        definition:
          'A Substack signal is an extracted asset view taken from a KOL’s long-form essay, newsletter, or blog post. These sources usually contain fuller reasoning than short posts and therefore produce more retrieval-friendly signal data.',
      },
      {
        term: 'Capitulation',
        category: 'Market term',
        definition:
          'Capitulation is the stage of a drawdown when holders finally give up and sell into weakness. It often appears near the end of a bear market and is one of the environments the BTC bottom scanner is designed to detect.',
      },
      {
        term: 'EMA',
        abbr: 'Exponential Moving Average',
        category: 'Technical term',
        definition:
          'EMA is a moving average that gives more weight to recent price data than older data. Trump Alpha uses the 150-day EMA inside the Pi Cycle Bottom condition.',
      },
    ],
    footerLead: 'Missing a term?',
    footerContact: 'Contact us',
    footerMethodology: 'Methodology',
    footerCaseStudies: 'Case Studies',
  }
}

export function generateMetadata({
  params: { locale },
}: {
  params: { locale: string }
}): Metadata {
  const copy = getCopy(locale)

  return {
    title: copy.title,
    description: copy.description,
    keywords: copy.keywords,
    openGraph: {
      title: copy.ogTitle,
      description: copy.ogDescription,
    },
    alternates: {
      canonical: `${siteUrl}/${locale}/glossary`,
      languages: {
        en: `${siteUrl}/en/glossary`,
        'x-default': `${siteUrl}/en/glossary`,
      },
    },
  }
}

const CATEGORY_COLOR: Record<string, string> = {
  'Macro-bottom metric': '#a78bfa',
  '宏观底部指标': '#a78bfa',
  'Platform term': '#f5a524',
  '平台术语': '#f5a524',
  'Trading term': '#22c55e',
  '交易术语': '#22c55e',
  'Derivatives term': '#60a5fa',
  '衍生品术语': '#60a5fa',
  'Bitcoin term': '#fb923c',
  '比特币术语': '#fb923c',
  'Market term': '#f87171',
  '市场术语': '#f87171',
  'Technical term': '#94a3b8',
  '技术术语': '#94a3b8',
}

export default function GlossaryPage({ params: { locale } }: { params: { locale: string } }) {
  const copy = getCopy(locale)
  const categories = Array.from(new Set(copy.terms.map(t => t.category)))

  return (
    <div className="page" style={{ maxWidth: 760 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">{copy.heroTitle}</h1>
          <p className="page-sub">{copy.heroSubtitle}</p>
        </div>
      </div>

      <p style={{
        fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.7,
        marginBottom: 20, fontStyle: 'italic',
      }}>
        {copy.intro}
      </p>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
        {categories.map(cat => (
          <span key={cat} style={{
            fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
            textTransform: 'uppercase', fontFamily: 'monospace',
            padding: '4px 10px', borderRadius: 999,
            background: `color-mix(in srgb, ${CATEGORY_COLOR[cat] ?? '#888'} 12%, transparent)`,
            color: CATEGORY_COLOR[cat] ?? '#888',
            border: `1px solid color-mix(in srgb, ${CATEGORY_COLOR[cat] ?? '#888'} 25%, transparent)`,
          }}>
            {cat}
          </span>
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {copy.terms.map((term) => (
          <div
            key={term.term}
            id={term.term.toLowerCase().replace(/[^a-z0-9]+/g, '-')}
            className="card"
            style={{ padding: '20px 24px' }}
            itemScope
            itemType="https://schema.org/DefinedTerm"
          >
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
              <h2
                itemProp="name"
                style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink)', margin: 0, flex: '1 1 auto' }}
              >
                {term.term}
              </h2>
              <span style={{
                fontSize: 10, fontWeight: 700, letterSpacing: '0.07em',
                textTransform: 'uppercase', fontFamily: 'monospace',
                padding: '3px 8px', borderRadius: 4, flexShrink: 0,
                background: `color-mix(in srgb, ${CATEGORY_COLOR[term.category] ?? '#888'} 12%, transparent)`,
                color: CATEGORY_COLOR[term.category] ?? '#888',
              }}>
                {term.category}
              </span>
            </div>

            {term.abbr && (
              <p style={{ fontSize: 12, color: 'var(--ink-4)', margin: '4px 0 0', fontStyle: 'italic' }}>
                {term.abbr}
              </p>
            )}

            <p
              itemProp="description"
              style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.7, margin: '10px 0 0' }}
            >
              {term.definition}
            </p>

            {term.extra && (
              <p style={{
                fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.65,
                margin: '8px 0 0', paddingLeft: 12,
                borderLeft: `2px solid ${CATEGORY_COLOR[term.category] ?? 'var(--amber)'}`,
              }}>
                {term.extra}
              </p>
            )}
          </div>
        ))}
      </div>

      <div className="card" style={{ padding: '20px 24px', marginTop: 12 }}>
        <p style={{ fontSize: 13, color: 'var(--ink-4)', lineHeight: 1.6, margin: 0 }}>
          {copy.footerLead}{' '}
          <Link href={`/${locale}/contact`} style={{ color: 'var(--amber)' }}>{copy.footerContact}</Link>.
          {' '}{locale === 'zh' ? '另见：' : 'See also:'}{' '}
          <Link href={`/${locale}/methodology`} style={{ color: 'var(--amber)' }}>{copy.footerMethodology}</Link>
          {' '}·{' '}
          <Link href={`/${locale}/case-studies`} style={{ color: 'var(--amber)' }}>{copy.footerCaseStudies}</Link>.
        </p>
      </div>
    </div>
  )
}
