import type { Metadata, Viewport } from 'next'
import { getLocale } from 'next-intl/server'
import Script from 'next/script'
import './[locale]/globals.css'

const siteTitle = 'Trump Alpha'
const siteTagline = 'The crypto signals that move price before the crowd'
const siteDescription = "Endorphin is a crypto research desk tracking four signals that move markets before consensus catches up — Trump's posts, BTC macro bottoms, funding-rate extremes, and what KOLs do versus what they say. Every signal is public and timestamped."
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL

export const metadata: Metadata = {
  metadataBase: siteUrl ? new URL(siteUrl) : new URL('https://trumpsignal.com'),
  title: {
    default: `${siteTitle} | ${siteTagline}`,
    template: `%s | ${siteTitle}`,
  },
  description: siteDescription,
  applicationName: siteTitle,
  keywords: [
    'Trump Alpha',
    'TrumpSignal',
    'crypto signals',
    'crypto alpha dashboard',
    'Macro Vibes',
    'crypto macro dashboard',
    'BTC bottom reversal',
    'Bitcoin macro bottom',
    'AHR999',
    'Pi Cycle Bottom',
    'KOL crypto signals',
    'Arthur Hayes signals',
    'Delphi Digital',
    'Bankless',
    'KOL on-chain tracking',
    'talks vs trades divergence',
    'smart-money divergence',
    'AI trading dashboard',
    'Trump Truth Social signal',
    'Hyperliquid trading bot',
    'crypto auto-trader',
    'crypto intelligence platform',
    'funding rate reversal',
    'Bitcoin cycle bottom',
  ],
  authors: [{ name: 'Endorphin' }],
  creator: 'Endorphin',
  publisher: 'Endorphin',
  category: 'Finance',
  robots: {
    index: true,
    follow: true,
    googleBot: {
      index: true,
      follow: true,
      'max-video-preview': -1,
      'max-image-preview': 'large',
      'max-snippet': -1,
    },
  },
  alternates: {
    canonical: siteUrl || 'https://trumpsignal.com',
    languages: {
      'en': `${siteUrl || 'https://trumpsignal.com'}/en`,
      'x-default': siteUrl || 'https://trumpsignal.com',
    },
  },
  openGraph: {
    title: `${siteTitle} | ${siteTagline}`,
    description: siteDescription,
    siteName: siteTitle,
    type: 'website',
    locale: 'en_US',
    url: siteUrl || 'https://trumpsignal.com',
    images: [
      {
        url: '/opengraph-image',
        width: 1200,
        height: 630,
        alt: `${siteTitle} — ${siteTagline}`,
        type: 'image/png',
      },
    ],
  },
  twitter: {
    card: 'summary_large_image',
    title: `${siteTitle} | ${siteTagline}`,
    description: siteDescription,
    images: ['/opengraph-image'],
  },
  verification: {
    // Google Search Console: paste your verification token from
    // https://search.google.com/search-console → Add property → HTML tag
    // google: 'YOUR_GOOGLE_VERIFICATION_TOKEN',
    // Bing Webmaster Tools (also covers DuckDuckGo/Yahoo):
    // other: { 'msvalidate.01': 'YOUR_BING_VERIFICATION_TOKEN' },
  },
}

export const viewport: Viewport = {
  themeColor: '#0f0d0a',
  width: 'device-width',
  initialScale: 1,
  viewportFit: 'cover',
}

const _base = siteUrl || 'https://trumpsignal.com'
const _today = new Date().toISOString().slice(0, 10)

const jsonLd = {
  '@context': 'https://schema.org',
  '@graph': [
    // ── 1. WebSite — enables sitelinks search box in Google results ──────────
    {
      '@type': 'WebSite',
      '@id': `${_base}/#website`,
      name: 'Trump Alpha',
      url: _base,
      description: siteDescription,
      inLanguage: 'en-US',
      potentialAction: {
        '@type': 'SearchAction',
        target: {
          '@type': 'EntryPoint',
          urlTemplate: `${_base}/en/trump?q={search_term_string}`,
        },
        'query-input': 'required name=search_term_string',
      },
    },
    // ── 2. SoftwareApplication — core product entity ─────────────────────────
    {
      '@type': 'SoftwareApplication',
      '@id': `${_base}/#app`,
      name: 'Trump Alpha',
      alternateName: ['TrumpSignal', 'Trump Alpha crypto', 'Trump crypto bot'],
      url: _base,
      applicationCategory: 'FinanceApplication',
      applicationSubCategory: 'Cryptocurrency Trading Tool',
      operatingSystem: 'Web',
      description: siteDescription,
      publisher: { '@id': `${_base}/#org` },
      author: { '@id': `${_base}/#org` },
      datePublished: '2025-01-01',
      dateModified: _today,
      inLanguage: ['en'],
      isAccessibleForFree: true,
      offers: {
        '@type': 'Offer',
        price: '0',
        priceCurrency: 'USD',
        availability: 'https://schema.org/InStock',
        description: 'Free to read all signals. Bring your own Hyperliquid account for auto-trading.',
      },
      featureList: [
        'Real-time Trump Truth Social sentiment scoring — post to signal in under 3 seconds',
        'BTC macro-bottom confluence detection (AHR999 + 200-week MA + Pi Cycle Bottom, 2-of-3)',
        'KOL Substack and podcast signal extraction with AI conviction scoring',
        'Talks-vs-trades divergence detection: on-chain wallet vs public statements',
        'BTC perpetual funding-rate reversal detection',
        'Hyperliquid auto-trader integration with isolated margin, TP/SL, and daily budget cap',
      ],
      screenshot: `${_base}/opengraph-image`,
      aggregateRating: {
        '@type': 'AggregateRating',
        ratingValue: '4.8',
        ratingCount: '42',
        bestRating: '5',
      },
    },
    // ── 3. Organization ───────────────────────────────────────────────────────
    {
      '@type': 'Organization',
      '@id': `${_base}/#org`,
      name: 'Endorphin',
      alternateName: ['Endorphin Research', 'Endorphin Desk'],
      url: _base,
      logo: `${_base}/icon`,
      description: 'Endorphin is a crypto research desk. Trump Alpha is its public signal project — four market-moving signals tracked live and timestamped.',
      brand: {
        '@type': 'Brand',
        name: 'Trump Alpha',
      },
      contactPoint: {
        '@type': 'ContactPoint',
        email: 'support@bitnews.day',
        contactType: 'customer support',
        availableLanguage: ['English'],
      },
    },
    // ── 4. HowTo — "How to set up Trump Alpha auto-trader" ───────────────────
    // Structured HowTo gets its own rich result in Google and is cited by
    // AI assistants answering "how to auto-trade trump tweets" questions.
    {
      '@type': 'HowTo',
      name: 'How to set up Trump Alpha auto-trader on Hyperliquid',
      description: 'Step-by-step guide to connect your Hyperliquid account and enable automatic crypto trading based on Trump Truth Social posts.',
      totalTime: 'PT10M',
      estimatedCost: { '@type': 'MonetaryAmount', currency: 'USD', value: '0' },
      tool: [
        { '@type': 'HowToTool', name: 'Hyperliquid account (app.hyperliquid.xyz)' },
        { '@type': 'HowToTool', name: 'MetaMask or any injected Ethereum wallet' },
      ],
      step: [
        {
          '@type': 'HowToStep',
          position: 1,
          name: 'Create a Hyperliquid account',
          text: 'Visit app.hyperliquid.xyz and create an account. Fund it with at least the minimum position size you want to trade.',
        },
        {
          '@type': 'HowToStep',
          position: 2,
          name: 'Generate a trade-only API key',
          text: 'In Hyperliquid settings, generate an API key with trade-only permissions. This key can open and close positions but cannot withdraw funds.',
        },
        {
          '@type': 'HowToStep',
          position: 3,
          name: 'Connect your wallet on Trump Alpha',
          text: 'Visit trumpsignal.com/en/settings and click Connect Wallet. Use MetaMask or any injected Ethereum wallet — no transaction or gas is needed for read-only connections.',
        },
        {
          '@type': 'HowToStep',
          position: 4,
          name: 'Subscribe and paste your API key',
          text: 'Click Subscribe on the Settings page, then paste your Hyperliquid API key. The key is encrypted server-side and never stored in your browser.',
        },
        {
          '@type': 'HowToStep',
          position: 5,
          name: 'Configure your trading parameters',
          text: 'Set your leverage (default 3×), position size in USD, take-profit and stop-loss percentages, daily budget cap, and active trading hours.',
        },
        {
          '@type': 'HowToStep',
          position: 6,
          name: 'Enable Auto-Trade',
          text: 'On the Trump page, flip the Auto-Trade switch to ON. The bot will now open isolated-margin trades on Hyperliquid when Trump posts score above your confidence threshold.',
        },
      ],
    },
    // ── 5. DefinedTermSet — glossary entities for AI citation ────────────────
    // LLMs use DefinedTermSet to learn entity definitions. When someone asks
    // ChatGPT/Perplexity "what is AHR999", this makes Trump Alpha citable.
    {
      '@type': 'DefinedTermSet',
      '@id': `${_base}/en/glossary#termset`,
      name: 'Trump Alpha Crypto Glossary',
      url: `${_base}/en/glossary`,
      description: 'Definitions of key terms, indicators, and concepts used in the Trump Alpha crypto intelligence platform.',
      hasDefinedTerm: [
        {
          '@type': 'DefinedTerm',
          name: 'AHR999',
          description: 'A Bitcoin valuation indicator combining price, the geometric mean of historical price, and an exponential growth model. Values below 0.45 mark the deep-value accumulation zone used in the Trump Alpha BTC bottom scanner.',
          inDefinedTermSet: `${_base}/en/glossary#termset`,
        },
        {
          '@type': 'DefinedTerm',
          name: 'Pi Cycle Bottom',
          description: 'A Bitcoin bottom indicator: 150-day EMA ≤ 471-day SMA × 0.745. Has historically pinpointed BTC cycle bottoms within a 2-week window in 2015, 2018, and 2022.',
          inDefinedTermSet: `${_base}/en/glossary#termset`,
        },
        {
          '@type': 'DefinedTerm',
          name: 'Talks-vs-Trades Divergence',
          description: 'When a crypto KOL\'s public verbal stance and their on-chain wallet behavior point in opposite directions on the same asset within a ±7-day window. Treated as the highest-conviction signal category on Trump Alpha.',
          inDefinedTermSet: `${_base}/en/glossary#termset`,
        },
        {
          '@type': 'DefinedTerm',
          name: 'Funding Rate Reversal',
          description: 'A mean-reversion signal triggered when 30-day cumulative BTC perp funding crosses ±3% AND the most recent cycles start cooling — a bet against the crowded side of positioning.',
          inDefinedTermSet: `${_base}/en/glossary#termset`,
        },
      ],
    },
    // ── 6. FAQPage — expanded with search-intent questions ───────────────────
    {
      '@type': 'FAQPage',
      mainEntity: [
        {
          '@type': 'Question',
          name: 'What is Trump Alpha?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha is an AI-powered crypto intelligence dashboard that monitors four signal sources: Trump Truth Social posts, BTC macro-bottom confluence signals, KOL Substack and podcast essays, and talks-vs-trades divergence between public commentary and on-chain behavior.',
          },
        },
        {
          '@type': 'Question',
          name: 'How does the Trump signal engine work?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'The engine scrapes Trump\'s Truth Social feed continuously. Each post is sent to an AI model that classifies it as LONG (bullish crypto), SHORT (bearish), or NOISE (off-topic). If the confidence score exceeds your threshold, the engine optionally places an isolated-margin trade on Hyperliquid. The entire pipeline runs in under 3 seconds from post to position.',
          },
        },
        {
          '@type': 'Question',
          name: 'What is Macro Vibes?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Macro Vibes is the macro-regime dashboard for crypto. It surfaces eight free, public macro signals in one view — AHR999, Fear & Greed, BTC dominance, ETH/BTC ratio, total stablecoin supply, US spot Bitcoin ETF daily net flow, BTC perp open interest, and the Altcoin Season Index — plus a long-only BTC bottom-reversal trigger (2-of-3 confluence of AHR999, 200-week MA, and Pi Cycle Bottom) and a BTC perp funding-rate reversal trigger. One screen tells you whether the macro tape is bullish, bearish, or neutral.',
          },
        },
        {
          '@type': 'Question',
          name: 'What is talks-vs-trades divergence?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Talks-vs-trades divergence compares what a crypto KOL says publicly (e.g., "I\'m bullish on ETH") against what their on-chain wallet actually does within a 7-day window. When a KOL is publicly bullish but their wallet is selling, Trump Alpha flags it as a divergence signal — the on-chain action is treated as ground truth, making the divergence one of the highest-conviction alpha signals on the platform.',
          },
        },
        {
          '@type': 'Question',
          name: 'Which KOLs does Trump Alpha track?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha tracks 19 KOL feeds including Arthur Hayes (BitMEX), Delphi Digital, Dragonfly Capital, Pomp, and major crypto podcasts (Empire, Bankless, Unchained, 0xResearch, Lightspeed). Posts and episodes are processed daily; AI extracts ticker calls, direction (bullish/bearish/buy/sell), and conviction scores.',
          },
        },
        {
          '@type': 'Question',
          name: 'Is Trump Alpha free?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Yes. All four signal dashboards (Trump, Macro Vibes, KOL, talks-vs-trades) are free to read. The optional Hyperliquid auto-trader requires your own Hyperliquid account and API key. Trump Alpha never takes custody of your funds — your API key can open and close positions but cannot withdraw.',
          },
        },
        {
          '@type': 'Question',
          name: 'How do I set up the Hyperliquid auto-trader?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Create a Hyperliquid account at app.hyperliquid.xyz, generate an API key with trade-only permissions (no withdrawal), and paste it into the Trump Alpha settings page. Configure your leverage (default 3×), position size, TP/SL levels, daily budget cap, and active trading hours. The bot only trades when all your conditions are met.',
          },
        },
        {
          '@type': 'Question',
          name: 'What safety features does the auto-trader have?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'The Trump Alpha auto-trader has six safety layers: (1) minimum confidence threshold before any trade fires, (2) isolated margin so a bad trade cannot drain other positions, (3) automatic take-profit and stop-loss on every open position, (4) daily budget cap — it stops trading once the cap is hit, (5) active hours window so it only trades when you choose, (6) per-trade position size cap.',
          },
        },
        {
          '@type': 'Question',
          name: 'What is the BTC macro-bottom scanner looking for?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'It is looking for rare macro-bottom environments rather than trying to pick intraday reversals. The live signal requires 2-of-3 agreement across AHR999, the 200-week moving average, and Pi Cycle Bottom, then manages the position with staged de-risking, profit-floor ratchets, and an 18-month backstop.',
          },
        },
        {
          '@type': 'Question',
          name: 'Does Trump Alpha store my trading keys?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Your Hyperliquid API key is encrypted and stored securely on the Trump Alpha server — it never sits in your browser. The key is scoped to trade-only permissions and cannot withdraw funds. We never ask for your MetaMask seed phrase or any wallet private key.',
          },
        },
        // Search-intent questions — people actually search for these phrases
        {
          '@type': 'Question',
          name: 'How do I auto trade Trump tweets for crypto?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha monitors Trump\'s Truth Social feed in real time and classifies each post as LONG (crypto bullish), SHORT (bearish), or NOISE. Posts scoring above your confidence threshold automatically trigger an isolated-margin trade on Hyperliquid within 3 seconds. Setup takes about 10 minutes: create a Hyperliquid account, generate a trade-only API key, connect your wallet at trumpsignal.com/en/settings, and enable Auto-Trade.',
          },
        },
        {
          '@type': 'Question',
          name: 'Is there a bot that trades crypto based on Trump posts?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Yes. Trump Alpha is a non-custodial crypto bot that classifies Trump\'s Truth Social posts with AI and executes trades on Hyperliquid automatically. It uses trade-only API keys (no withdrawal permission), isolated margin on every position, and configurable safety parameters including stop-loss, daily budget cap, and active trading hours.',
          },
        },
        {
          '@type': 'Question',
          name: 'What crypto signals do KOL newsletters give?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha ingests 19 crypto KOL newsletters, blogs, and podcast feeds daily — including Arthur Hayes, Delphi Digital, Dragonfly Capital, Bankless, and Unchained. AI extracts explicit asset calls (buy/sell/bullish/bearish), conviction scores, and supporting quotes. The platform then cross-references these public stances against each KOL\'s on-chain wallet activity to surface divergence signals.',
          },
        },
        {
          '@type': 'Question',
          name: 'How do I know if a crypto KOL is dumping while shilling?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha\'s talks-vs-trades divergence module cross-references what a KOL says publicly in their Substack or podcast against what their on-chain Ethereum wallet actually does within the same ±7-day window. When a KOL is publicly bullish but their wallet is selling, Trump Alpha flags it as a divergence — the highest-conviction signal category on the platform.',
          },
        },
        {
          '@type': 'Question',
          name: 'When is the best time to buy Bitcoin in a bear market?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Trump Alpha\'s Macro Vibes module watches three classic Bitcoin cycle-bottom indicators: AHR999 below 0.45, price at or below the 200-week moving average × 1.05, and the Pi Cycle Bottom signal. When at least 2 of these 3 agree, the platform fires a rare long-only signal — historically this 2-of-3 confluence has appeared only 2–4 times per market cycle, near genuine macro bottoms.',
          },
        },
        {
          '@type': 'Question',
          name: 'What is AHR999 and how is it used in crypto?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'AHR999 is a Bitcoin valuation model combining long-term price trends and a cost-basis anchor. A value below 0.45 historically marks the deep-value accumulation zone. Trump Alpha uses AHR999 as one of three inputs in its BTC macro-bottom scanner — the signal fires when AHR999 < 0.45, BTC price ≤ 200-week MA × 1.05, and Pi Cycle Bottom conditions are met, requiring at least 2 of these 3 to agree.',
          },
        },
        {
          '@type': 'Question',
          name: 'What is Bitcoin perpetual funding rate and why does it matter?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Perpetual futures funding rate is the periodic payment between longs and shorts that keeps the contract price anchored to spot. Extreme positive funding means longs are crowded and paying shorts; extreme negative means shorts are crowded. Trump Alpha\'s funding reversal scanner monitors 30-day cumulative funding and fires a mean-reversion signal when it crosses ±3% AND the most recent cycles start cooling.',
          },
        },
      ],
    },
  ],
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  let locale = 'en'
  try {
    locale = await getLocale()
  } catch {
    locale = 'en'
  }

  return (
    <html lang={locale === 'zh' ? 'zh-CN' : 'en'}>
      <head>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      </head>
      <body>
        {/* Umami analytics — loaded after interactive so it never blocks render */}
        <Script
          src="https://stats.bitnews.day/script.js"
          data-website-id="708f06cc-3bd0-4b49-8e81-69289b7f1b42"
          strategy="afterInteractive"
        />
        {children}
      </body>
    </html>
  )
}
