'use client'

import { useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import './landing.css'

/* Scroll-reveal hook */
function useReveal() {
  const ref = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const root = ref.current
    if (!root) return
    const els = root.querySelectorAll<HTMLElement>('.lp-reveal')
    const io = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            e.target.classList.add('in')
            io.unobserve(e.target)
          }
        }
      },
      { threshold: 0.12, rootMargin: '0px 0px -40px 0px' },
    )
    els.forEach((el) => io.observe(el))
    return () => io.disconnect()
  }, [])
  return ref
}

/* Ticking clock for the terminal header (looks alive) */
function useClock() {
  const [t, setT] = useState<string>('')
  useEffect(() => {
    const tick = () => {
      const d = new Date()
      setT(d.toISOString().replace('T', ' ').slice(0, 19) + ' UTC')
    }
    tick()
    const id = setInterval(tick, 1000)
    return () => clearInterval(id)
  }, [])
  return t
}

export default function LandingPage() {
  const rootRef = useReveal()
  const clock = useClock()

  return (
    <div className="lp-root" ref={rootRef}>
      <div className="lp-mesh" aria-hidden />
      <div className="lp-grid" aria-hidden />

      <nav className="lp-nav">
        <div className="lp-nav-inner">
          <Link href="/" className="lp-logo">
            <span className="lp-logo-dot" />
            Trump Alpha
          </Link>
          <Link href="/en" className="lp-nav-cta">
            Launch Dashboard
            <span className="lp-arrow">→</span>
          </Link>
        </div>
      </nav>

      <div className="lp-wrap">
        {/* ---------- HERO ---------- */}
        <section className="lp-hero">
          <div className="lp-live-badge">
            <span className="lp-live-dot" />
            Reading @realDonaldTrump on Truth Social · right now
          </div>

          <h1 className="lp-h1">
            Trump posts at 3am.<br />
            The bot trades at&nbsp;
            <span className="strike">
              <span className="grad">3:00:02</span>
            </span>
            .
          </h1>

          <p className="lp-sub">
            Every Truth Social post is scraped, scored by AI, and turned into a
            Hyperliquid position — in under three seconds. You sleep. It doesn&rsquo;t.
          </p>

          <div className="lp-ctas">
            <Link href="/en" className="lp-btn lp-btn-primary">
              Launch Dashboard
              <span className="lp-arrow">→</span>
            </Link>
            <a href="#engine" className="lp-btn lp-btn-secondary">
              Watch the engine
            </a>
          </div>

          {/* Ticker strip */}
          <div className="lp-ticker" aria-hidden>
            <div className="lp-ticker-track">
              {[0, 1].map((k) => (
                <div key={k} style={{ display: 'flex', gap: 48 }}>
                  <TickerItem asset="BTC" kind="buy"  text="Post scored 82 · AUTO-LONG fired" />
                  <TickerItem asset="ETH" kind="hold" text="Below user confidence floor · skipped" />
                  <TickerItem asset="BTC" kind="sell" text="Signal SHORT · TP/SL armed" />
                  <TickerItem asset="ETH" kind="buy"  text="Post scored 74 · AUTO-LONG fired" />
                  <TickerItem asset="BTC" kind="hold" text="Outside active window · standing by" />
                  <TickerItem asset="ETH" kind="sell" text="Signal SHORT · position opened" />
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ---------- THE ENGINE (terminal block) ---------- */}
        <section id="engine" className="lp-section" style={{ paddingTop: 60 }}>
          <div className="lp-reveal" style={{ maxWidth: 640 }}>
            <div className="lp-eyebrow">The engine, running</div>
            <h2 className="lp-h2">
              No mock-ups. No dashboards in a marketing deck.
            </h2>
            <p className="lp-lead">
              This is what the signal engine actually does, every time Trump posts.
              Scrape. Score. Decide. Execute.
            </p>
          </div>

          {/* Terminal */}
          <div className="lp-term lp-reveal">
            <div className="lp-term-head">
              <span className="dot" />
              <span className="meta-live">LIVE</span>
              <span className="sep">│</span>
              <span>trumpsignal.engine</span>
              <span className="sep">│</span>
              <span>src=<span className="meta-amber">truthsocial.com/@realDonaldTrump</span></span>
              <span className="spacer" />
              <span suppressHydrationWarning>{clock}</span>
            </div>

            <div className="lp-term-body">
              <TermRow
                isNew
                ts="−02m"
                text="BITCOIN is the FUTURE of money. America will LEAD the world in crypto. BIG things coming very soon. ENJOY!"
                verdict={{ cls: 'LONG', asset: 'BTC', conf: 82, action: 'AUTO-LONG · 3× isolated · $50' }}
              />
              <TermRow
                ts="−14m"
                text="Massive new TARIFFS on China coming — they have RIPPED OFF the USA for decades. No more!"
                verdict={{ cls: 'SHORT', asset: 'BTC', conf: 71, action: 'AUTO-SHORT · 3× isolated · $50' }}
              />
              <TermRow
                ts="−38m"
                text="Crooked Joe and the Radical Left Lunatics are destroying our beautiful country. SAD!"
                verdict={{ cls: 'NOISE', skip: 'off-topic · below confidence floor' }}
              />
              <TermRow
                ts="−01h"
                text="The Fed must CUT rates NOW. The economy cannot afford their stupidity any longer!"
                verdict={{ cls: 'LONG', asset: 'BTC', conf: 64, action: 'AUTO-LONG · 3× isolated · $50' }}
              />
              <TermRow
                ts="−02h"
                text="Crypto is the FUTURE. No More War on Crypto! America FIRST!"
                verdict={{ cls: 'LONG', asset: 'BTC', conf: 78, action: 'skipped · daily budget cap hit' }}
                soft
              />
            </div>

            <div className="lp-term-foot">
              <span>
                tail -f /var/log/engine <span className="lp-term-cursor" />
              </span>
              <span className="tail">posts analysed: 1,247 · uptime 99.8%</span>
            </div>
          </div>

          {/* Stat strip */}
          <div className="lp-stats lp-reveal">
            <Stat value="<3" suffix="s" label="Post → position" sub="scrape · score · sign · send" />
            <Stat value="24/7" label="Always on" sub="unless you say otherwise" />
            <Stat value="$0" label="Fee from us" sub="you pay Hyperliquid, not me" />
            <Stat value="6" label="Safety layers" sub="TP · SL · hold · budget · window · isolation" />
          </div>

          <p
            className="lp-reveal"
            style={{
              marginTop: 18, fontSize: 12, color: 'var(--lp-ink-4)',
              textAlign: 'center', fontFamily: 'Geist Mono, monospace',
            }}
          >
            Posts shown are examples in Trump&rsquo;s style — your actual feed is live from the dashboard.
          </p>
        </section>

        {/* ---------- PRESS / HEADLINES ---------- */}
        <section className="lp-section" style={{ paddingTop: 80 }}>
          <div className="lp-reveal" style={{ maxWidth: 680 }}>
            <div className="lp-eyebrow">Headlines you can Google</div>
            <h2 className="lp-h2">
              The market already trades every Trump post.
            </h2>
            <p className="lp-lead">
              Big wallets have been scoring eight-figure moves on his Truth Social
              activity for two years. This bot won&rsquo;t give you their edge —
              it just gives you their speed.
            </p>
          </div>

          <div className="lp-press">
            {/* Big card — the $6.8M trader story */}
            <a
              className="lp-news lp-news-big lp-reveal"
              href="https://www.newsbreak.com/raw-story-2096750/4286876592634-that-s-the-maga-playbook-crypto-trade-made-moments-before-trump-post-raises-eyebrows"
              target="_blank"
              rel="noopener noreferrer"
            >
              <div className="lp-news-big-figure">
                <span className="tag">verified · on-chain</span>
                <div className="num">+$6.8M</div>
                <div className="subnum">50× leverage · same-day close</div>
              </div>
              <div className="lp-news-big-body">
                <div className="lp-news-head">
                  <span className="lp-news-outlet">Raw Story · NewsBreak</span>
                  <span className="lp-news-date">Mar 2025</span>
                </div>
                <h3 className="lp-news-headline">
                  Anonymous whale placed a 50× leveraged BTC/ETH bet minutes before
                  Trump&rsquo;s crypto-reserve post — cashed out the same day.
                </h3>
              </div>
              <span className="lp-news-arrow">↗</span>
            </a>

            <a
              className="lp-news lp-reveal"
              href="https://www.cnbc.com/2025/03/02/trump-announces-strategic-crypto-reserve-including-bitcoin-solana-xrp-and-more.html"
              target="_blank"
              rel="noopener noreferrer"
            >
              <span className="lp-news-arrow">↗</span>
              <div className="lp-news-head">
                <span className="lp-news-outlet">CNBC</span>
                <span className="lp-news-date">Mar 2&nbsp;2025</span>
              </div>
              <h3 className="lp-news-headline">
                Trump&rsquo;s Truth Social post confirming a Strategic Crypto
                Reserve sent Bitcoin from $84k to $91k overnight.
              </h3>
              <div className="lp-news-stat">
                <span className="n up">+8.2%</span>
                <span className="l">BTC · 24 hours<br />one Truth Social post</span>
              </div>
            </a>

            <a
              className="lp-news lp-reveal"
              href="https://www.aljazeera.com/news/2025/3/4/trump-announces-us-crypto-reserve-what-it-is-and-why-it-matters"
              target="_blank"
              rel="noopener noreferrer"
            >
              <span className="lp-news-arrow">↗</span>
              <div className="lp-news-head">
                <span className="lp-news-outlet">Al Jazeera</span>
                <span className="lp-news-date">Mar 4&nbsp;2025</span>
              </div>
              <h3 className="lp-news-headline">
                Ethereum spiked more than 10% alongside Bitcoin as the reserve
                announcement rippled across every major alt.
              </h3>
              <div className="lp-news-stat">
                <span className="n up">+10%+</span>
                <span className="l">ETH · same window<br />BTC, SOL, XRP followed</span>
              </div>
            </a>

            <a
              className="lp-news lp-reveal"
              href="https://www.coindesk.com/markets/2026/04/20/five-times-president-trump-made-a-statement-that-moved-bitcoin-and-why-it-might-happen-again-this-week"
              target="_blank"
              rel="noopener noreferrer"
            >
              <span className="lp-news-arrow">↗</span>
              <div className="lp-news-head">
                <span className="lp-news-outlet">CoinDesk</span>
                <span className="lp-news-date">Apr 20&nbsp;2026</span>
              </div>
              <h3 className="lp-news-headline">
                Five separate times a single Trump statement moved BTC within
                minutes — and why it keeps happening.
              </h3>
              <div className="lp-news-stat">
                <span className="n">5×</span>
                <span className="l">documented cases<br />BTC moved in minutes</span>
              </div>
            </a>

            <a
              className="lp-news lp-reveal"
              href="https://time.com/7263869/donald-trump-crypto-reserve-summit-bitcoin/"
              target="_blank"
              rel="noopener noreferrer"
            >
              <span className="lp-news-arrow">↗</span>
              <div className="lp-news-head">
                <span className="lp-news-outlet">TIME</span>
                <span className="lp-news-date">Mar 2025</span>
              </div>
              <h3 className="lp-news-headline">
                Senator Schiff calls for an SEC investigation into possible
                insider trading around Trump&rsquo;s market-moving posts.
              </h3>
              <div className="lp-news-stat">
                <span className="n">SEC</span>
                <span className="l">investigation requested<br />by a U.S. senator</span>
              </div>
            </a>
          </div>

          <p className="lp-press-note lp-reveal">
            Not our claims — their headlines. Click any card to read the source.
          </p>
        </section>

        {/* ---------- WHY IT WORKS ---------- */}
        <section className="lp-section">
          <div className="lp-reveal" style={{ maxWidth: 640 }}>
            <div className="lp-eyebrow">Why bother</div>
            <h2 className="lp-h2">
              Trump moves markets. You can&rsquo;t outrun him manually.
            </h2>
            <p className="lp-lead">
              He posts at any hour, in any mood. By the time you see it, the move
              is half over. The bot doesn&rsquo;t blink. That&rsquo;s the whole pitch.
            </p>
          </div>

          <div className="lp-why">
            <WhyCard
              n="01"
              t="Your rules, not ours"
              d="Your leverage, your position size, your TP/SL, your daily cap, your active hours. The bot only does what your config says."
            />
            <WhyCard
              n="02"
              t="Isolated margin, always"
              d="Every open uses Hyperliquid isolated margin. A bad trade can&rsquo;t drain your other positions or your whole account."
            />
            <WhyCard
              n="03"
              t="Nothing held overnight"
              d="Every position force-closes after 60 minutes. No waking up to a liquidation from a post you missed."
            />
            <WhyCard
              n="04"
              t="Your keys stay yours"
              d="Non-custodial. The Hyperliquid API key can open and close — it cannot withdraw. We never see your MetaMask."
            />
          </div>
        </section>

        {/* ---------- FINAL CTA ---------- */}
        <section className="lp-cta-final lp-reveal">
          <h2 className="lp-h2" style={{ margin: '0 auto 24px', maxWidth: 780 }}>
            Stop refreshing Truth Social.<br />
            <span className="grad" style={{ fontWeight: 700 }}>
              Go do literally anything else.
            </span>
          </h2>
          <p className="lp-lead" style={{ margin: '0 auto 40px', textAlign: 'center' }}>
            2 minutes to set up. Free. Bring your own Hyperliquid account. If you
            don&rsquo;t like it, disconnect — nothing to cancel.
          </p>
          <div className="lp-ctas">
            <Link href="/en" className="lp-btn lp-btn-primary">
              Launch Dashboard
              <span className="lp-arrow">→</span>
            </Link>
          </div>
        </section>
      </div>

      <footer className="lp-foot">
        <p className="lp-disclaimer">
          TrumpSignal is an experimental tool. Crypto perp trading is extremely
          high-risk; you can lose more than you deposit. Past signals are not
          predictions of future results. Not affiliated with Truth Social, Trump
          Media &amp; Technology Group, or Donald J. Trump. Trade at your own risk.
        </p>
        <div style={{ marginTop: 16 }}>
          <span>© {new Date().getFullYear()} TrumpSignal</span>
          <Link href="/en/privacy">Privacy</Link>
          <Link href="/en/terms">Terms</Link>
          <Link href="/en/contact">Contact</Link>
        </div>
      </footer>
    </div>
  )
}

/* ---------- Terminal row ---------- */
function TermRow({
  isNew,
  ts,
  text,
  verdict,
  soft,
}: {
  isNew?: boolean
  ts: string
  text: string
  verdict:
    | { cls: 'LONG' | 'SHORT'; asset: string; conf: number; action: string }
    | { cls: 'NOISE'; skip: string }
  soft?: boolean
}) {
  const cls = verdict.cls
  const valClass = cls === 'LONG' ? 'long' : cls === 'SHORT' ? 'short' : 'skip'
  return (
    <div className={`lp-term-row${isNew ? ' new' : ''}`}>
      <div className="lp-term-meta">
        <span className="handle">@realDonaldTrump</span>
        <span>·</span>
        <span className="ts">{ts}</span>
        <span>·</span>
        <span>truthsocial</span>
      </div>
      <p className="lp-term-quote">{text}</p>
      <div className="lp-term-verdict">
        <span className="seg">
          <span className="k">cls</span>
          <span className={`v ${valClass}`}>{cls}</span>
        </span>
        {'asset' in verdict && (
          <>
            <span className="seg">
              <span className="k">asset</span>
              <span className="v amber">{verdict.asset}</span>
            </span>
            <span className="seg">
              <span className="k">conf</span>
              <span className="bar">
                <span
                  className="bar-fill"
                  style={{ width: `${verdict.conf}%` }}
                />
              </span>
              <span className="v">{verdict.conf}</span>
            </span>
            <span className="seg">
              <span className="k">action</span>
              <span className={`v ${soft ? '' : 'amber'}`}>{verdict.action}</span>
            </span>
          </>
        )}
        {'skip' in verdict && (
          <span className="seg">
            <span className="k">reason</span>
            <span className="v skip">{verdict.skip}</span>
          </span>
        )}
      </div>
    </div>
  )
}

/* ---------- Small components ---------- */
function TickerItem({ asset, kind, text }: { asset: string; kind: 'buy' | 'sell' | 'hold'; text: string }) {
  return (
    <div className="lp-ticker-item">
      <span className={`tag ${kind}`}>{kind.toUpperCase()}</span>
      <span style={{ color: 'var(--lp-ink-2)' }}>{asset}</span>
      <span>·</span>
      <span>{text}</span>
    </div>
  )
}

function Stat({ value, suffix, label, sub }: { value: string; suffix?: string; label: string; sub?: string }) {
  return (
    <div className="lp-stat">
      <div className="lp-stat-val">
        {value}
        {suffix && <span className="suffix">{suffix}</span>}
      </div>
      <div className="lp-stat-lbl">{label}</div>
      {sub && <div className="lp-stat-sub">{sub}</div>}
    </div>
  )
}

function WhyCard({ n, t, d }: { n: string; t: string; d: string }) {
  return (
    <div className="lp-why-card lp-reveal">
      <div className="num">{n}</div>
      <h4>{t}</h4>
      <p>{d}</p>
    </div>
  )
}
