// Hero section with live countdown, animated background, market ticker
const { useState, useEffect, useRef } = React;

function Ticker() {
  const items = [
    { sym: 'TX 臺指期', px: '21,480', chg: '+156', pct: '+0.73%', up: true },
    { sym: 'MTX 小臺', px: '21,478', chg: '+154', pct: '+0.72%', up: true },
    { sym: 'TE 電子期', px: '1,584.2', chg: '+12.4', pct: '+0.79%', up: true },
    { sym: 'TF 金融期', px: '1,865.0', chg: '-4.5', pct: '-0.24%', up: false },
    { sym: 'SPY US', px: '582.34', chg: '+2.18', pct: '+0.38%', up: true },
    { sym: 'ES E-Mini', px: '5,842.25', chg: '+18.50', pct: '+0.32%', up: true },
    { sym: 'NQ Nasdaq', px: '20,418.75', chg: '+88.25', pct: '+0.43%', up: true },
    { sym: 'CL 原油', px: '73.82', chg: '-0.54', pct: '-0.73%', up: false },
    { sym: 'GC 黃金', px: '2,684.40', chg: '+12.80', pct: '+0.48%', up: true },
    { sym: 'BTC 比特幣', px: '98,420', chg: '+1,240', pct: '+1.28%', up: true },
  ];
  const doubled = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {doubled.map((it, i) => (
          <span className="ticker-item" key={i}>
            <span className="sym">{it.sym}</span>
            <span className="px">{it.px}</span>
            <span className={`chg ${it.up ? 'up' : 'down'}`}>
              {it.up ? '▲' : '▼'} {it.chg} {it.pct}
            </span>
          </span>
        ))}
      </div>
    </div>
  );
}

function Countdown({ target }) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  const d = Math.floor(diff / 86400000);
  const h = Math.floor((diff % 86400000) / 3600000);
  const m = Math.floor((diff % 3600000) / 60000);
  const s = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, '0');
  return (
    <div className="countdown">
      <div className="countdown-label">
        <span className="title">距離開賽倒數</span>
        <span className="status"><span className="pulse"></span>報名開放中</span>
      </div>
      <div className="countdown-grid">
        <div className="cd-cell"><div className="cd-val">{pad(d)}</div><div className="cd-unit">DAYS · 天</div></div>
        <div className="cd-cell"><div className="cd-val">{pad(h)}</div><div className="cd-unit">HOURS · 時</div></div>
        <div className="cd-cell"><div className="cd-val">{pad(m)}</div><div className="cd-unit">MINS · 分</div></div>
        <div className="cd-cell"><div className="cd-val">{pad(s)}</div><div className="cd-unit">SECS · 秒</div></div>
      </div>
      <div className="cd-foot">
        <span>活動期間</span>
        <span className="period">2026.05.01 — 2026.07.31</span>
      </div>
    </div>
  );
}

function HeroBg({ variant, mouse }) {
  const tx = (mouse.x - 0.5) * 20;
  const ty = (mouse.y - 0.5) * 20;

  if (variant === 'chart') {
    // Animated line chart
    const [phase, setPhase] = useState(0);
    useEffect(() => {
      const id = setInterval(() => setPhase(p => p + 1), 80);
      return () => clearInterval(id);
    }, []);
    const points = Array.from({ length: 40 }, (_, i) => {
      const x = (i / 39) * 100;
      const y = 50 + Math.sin((i + phase * 0.3) * 0.4) * 12 + Math.cos((i + phase * 0.15) * 0.2) * 8 + i * 0.3;
      return `${x},${100 - y}`;
    }).join(' ');
    return (
      <div className="hero-bg" style={{ transform: `translate3d(${tx}px,${ty}px,0)` }}>
        <svg viewBox="0 0 100 100" preserveAspectRatio="none">
          <defs>
            <linearGradient id="lg1" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#D4AF37" stopOpacity="0.25" />
              <stop offset="100%" stopColor="#D4AF37" stopOpacity="0" />
            </linearGradient>
            <pattern id="grd" width="5" height="5" patternUnits="userSpaceOnUse">
              <path d="M 5 0 L 0 0 0 5" fill="none" stroke="rgba(255,255,255,0.04)" strokeWidth="0.1"/>
            </pattern>
          </defs>
          <rect width="100" height="100" fill="url(#grd)" />
          <polygon points={`0,100 ${points} 100,100`} fill="url(#lg1)" />
          <polyline points={points} fill="none" stroke="#D4AF37" strokeWidth="0.3" opacity="0.7" />
        </svg>
      </div>
    );
  }

  if (variant === 'particles') {
    const dots = Array.from({ length: 60 }, (_, i) => ({
      cx: (i * 137.5) % 100,
      cy: (i * 73.3) % 100,
      r: 0.15 + (i % 5) * 0.08,
      op: 0.1 + (i % 4) * 0.15,
    }));
    return (
      <div className="hero-bg" style={{ transform: `translate3d(${tx}px,${ty}px,0)` }}>
        <svg viewBox="0 0 100 100" preserveAspectRatio="none">
          <radialGradient id="rg1" cx="30%" cy="30%" r="60%">
            <stop offset="0%" stopColor="#1C2E4E" />
            <stop offset="100%" stopColor="#0A1428" />
          </radialGradient>
          <rect width="100" height="100" fill="url(#rg1)" />
          {dots.map((d, i) => (
            <circle key={i} cx={d.cx} cy={d.cy} r={d.r} fill="#D4AF37" opacity={d.op}>
              <animate attributeName="opacity" values={`${d.op};${d.op * 0.3};${d.op}`} dur={`${3 + i % 4}s`} repeatCount="indefinite" />
            </circle>
          ))}
        </svg>
      </div>
    );
  }

  if (variant === 'radial') {
    return (
      <div className="hero-bg" style={{ transform: `translate3d(${tx}px,${ty}px,0)` }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at 20% 40%, rgba(91,158,255,0.15), transparent 50%), radial-gradient(ellipse at 80% 60%, rgba(212,175,55,0.18), transparent 55%)'
        }} />
      </div>
    );
  }

  // default: grid
  return (
    <div className="hero-bg" style={{ transform: `translate3d(${tx * 0.5}px,${ty * 0.5}px,0)` }}>
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ opacity: 0.6 }}>
        <defs>
          <pattern id="heroGrid" width="4" height="4" patternUnits="userSpaceOnUse">
            <path d="M 4 0 L 0 0 0 4" fill="none" stroke="rgba(91,158,255,0.06)" strokeWidth="0.08"/>
          </pattern>
          <radialGradient id="heroGlow" cx="70%" cy="30%" r="50%">
            <stop offset="0%" stopColor="rgba(212,175,55,0.18)" />
            <stop offset="100%" stopColor="rgba(212,175,55,0)" />
          </radialGradient>
        </defs>
        <rect width="100" height="100" fill="url(#heroGrid)" />
        <rect width="100" height="100" fill="url(#heroGlow)" />
      </svg>
    </div>
  );
}

function Hero({ heroBg }) {
  const targetDate = new Date('2026-05-01T09:00:00+08:00').getTime();
  const [mouse, setMouse] = useState({ x: 0.5, y: 0.5 });

  useEffect(() => {
    const handle = (e) => {
      setMouse({ x: e.clientX / window.innerWidth, y: e.clientY / window.innerHeight });
    };
    window.addEventListener('mousemove', handle);
    return () => window.removeEventListener('mousemove', handle);
  }, []);

  // live-updating stats
  const [participants, setParticipants] = useState(12847);
  const [volume, setVolume] = useState(8.42);
  useEffect(() => {
    const id = setInterval(() => {
      setParticipants(p => p + Math.floor(Math.random() * 3));
      setVolume(v => +(v + Math.random() * 0.02).toFixed(2));
    }, 2500);
    return () => clearInterval(id);
  }, []);

  return (
    <>
      <Ticker />
      <section className="hero">
        <HeroBg variant={heroBg} mouse={mouse} />
        <div className="deco-corner tr"></div>
        <div className="deco-corner bl"></div>
        <div className="money-layer">
          <MoneyGoldCoin size="lg" className="money-coin-1 money-float-a" />
          <MoneyBill size="lg" className="money-coin-2 money-float-b" />
          <MoneyBag size="md" className="money-coin-3 money-float-c" />
        </div>
        <div className="shell hero-inner">
          <div className="fade-in">
            <span className="eyebrow"><span className="dot"></span>TELLUSTEK · 2026 CHARITY FUTURES CHAMPIONSHIP</span>
            <h1 className="h1">
              <span className="accent">百萬</span>獎金<br/>
              慈善期貨<br/>
              交易王大賽
              <span className="small">WHERE EVERY TRADE BUILDS A BETTER TOMORROW</span>
            </h1>
            <p className="hero-sub">
              全台最大規模的慈善期貨交易競賽。與來自各地的一般散戶投資人同場競技，檢驗你的交易策略。
              冠軍獨得新台幣 100 萬元，賽事淨手續費收入 100% 捐贈社福機構。
            </p>
            <div className="hero-meta">
              <div className="m-item">
                <div className="m-label">冠軍獎金</div>
                <div className="m-value num">NT$ 1,000,000</div>
              </div>
              <div className="m-item">
                <div className="m-label">賽期</div>
                <div className="m-value">3 個月</div>
              </div>
              <div className="m-item">
                <div className="m-label">參賽資格</div>
                <div className="m-value">一般散戶</div>
              </div>
            </div>
            <div className="hero-ctas">
              <button className="btn btn-gold btn-lg">立即報名 · FREE ENTRY →</button>
              <button className="btn btn-ghost btn-lg">觀看活動說明</button>
            </div>
          </div>
          <div className="fade-in" style={{ animationDelay: '0.15s' }}>
            <Countdown target={targetDate} />
          </div>
        </div>

        <div className="shell">
          <div className="hero-stats">
            <div className="hs-cell">
              <div className="hs-label">預計參賽人數</div>
              <div className="hs-value num">{participants.toLocaleString()}<span className="unit">人</span></div>
              <div className="hs-trend">↗ 即時報名中</div>
            </div>
            <div className="hs-cell">
              <div className="hs-label">總獎金池</div>
              <div className="hs-value num">3,000,000<span className="unit">元</span></div>
              <div className="hs-trend">得獎名額 50 位</div>
            </div>
            <div className="hs-cell">
              <div className="hs-label">歷屆交易總量</div>
              <div className="hs-value num">{volume.toFixed(2)}<span className="unit">億口</span></div>
              <div className="hs-trend">↗ 累積 5 屆</div>
            </div>
            <div className="hs-cell">
              <div className="hs-label">公益捐贈</div>
              <div className="hs-value num">100<span className="unit">%</span></div>
              <div className="hs-trend">淨手續費全額捐贈</div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
