// Hero dashboard + ticker strip
function HeroChart() {
  const { t, localeTag } = useLandingI18n();
  const [pts, setPts] = React.useState(() => {
    // Seed with a realistic-ish upward curve
    const n = 80;
    const arr = [];
    let v = 100;
    for (let i = 0; i < n; i++) {
      v += (Math.random() - 0.35) * 1.6 + 0.2;
      arr.push(Math.max(80, v));
    }
    return arr;
  });

  React.useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) return;
    const id = setInterval(() => {
      setPts(prev => {
        const next = prev.slice(1);
        const last = prev[prev.length - 1];
        const nv = Math.max(80, last + (Math.random() - 0.4) * 1.4 + 0.25);
        next.push(nv);
        return next;
      });
    }, 900);
    return () => clearInterval(id);
  }, []);

  const W = 520, H = 180, PAD = 8;
  const min = Math.min(...pts), max = Math.max(...pts);
  const range = max - min || 1;
  const x = i => PAD + (i / (pts.length - 1)) * (W - PAD * 2);
  const y = v => H - PAD - ((v - min) / range) * (H - PAD * 2);
  const path = pts.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(2)} ${y(v).toFixed(2)}`).join(' ');
  const area = `${path} L ${x(pts.length - 1).toFixed(2)} ${H - PAD} L ${x(0).toFixed(2)} ${H - PAD} Z`;
  const lastY = y(pts[pts.length - 1]);
  const lastX = x(pts.length - 1);

  const current = pts[pts.length - 1];
  const start = pts[0];
  const gain = ((current - start) / start) * 100;

  return (
    <>
      <div className="dash__head">
        <div>
          <div className="dash__label">Portfolio value · last 12 months</div>
          <div className="dash__value num">€<TickingNumber value={248_340 + (current - 100) * 520} decimals={0} localeTag={localeTag} /></div>
          <div className="dash__delta gain">▲ €<TickingNumber value={34_218 + (current - 100) * 400} decimals={0} localeTag={localeTag} /> <span className="muted">({gain.toFixed(2)}%)</span></div>
        </div>
        <div className="dash__live"><span className="dash__live-dot"/> Live</div>
      </div>
      <svg className="dash__chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" aria-label={t('Portfolio curve showing {{gain}}% growth', { gain: gain.toFixed(1) })}>
        <defs>
          <linearGradient id="chartFill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#0A0A0A" stopOpacity="0.10"/>
            <stop offset="100%" stopColor="#0A0A0A" stopOpacity="0"/>
          </linearGradient>
          <pattern id="gridPat" x="0" y="0" width="52" height="45" patternUnits="userSpaceOnUse">
            <path d="M 52 0 L 0 0 0 45" fill="none" stroke="#F0F0F0" strokeWidth="1"/>
          </pattern>
        </defs>
        <rect width={W} height={H} fill="url(#gridPat)"/>
        <path d={area} fill="url(#chartFill)"/>
        <path d={path} fill="none" stroke="#0A0A0A" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx={lastX} cy={lastY} r="3.5" fill="#0A0A0A"/>
        <circle cx={lastX} cy={lastY} r="7" fill="#0A0A0A" opacity="0.15">
          <animate attributeName="r" values="5;12;5" dur="2s" repeatCount="indefinite"/>
          <animate attributeName="opacity" values="0.3;0;0.3" dur="2s" repeatCount="indefinite"/>
        </circle>
      </svg>
      <div className="dash__footer">
        <div className="dash__cell">
          <div className="dash__cell-label">Equities</div>
          <div className="dash__cell-val num">€142,890</div>
        </div>
        <div className="dash__cell">
          <div className="dash__cell-label">Crypto</div>
          <div className="dash__cell-val num">€38,102</div>
        </div>
        <div className="dash__cell">
          <div className="dash__cell-label">Property</div>
          <div className="dash__cell-val num">€67,348</div>
        </div>
      </div>
    </>
  );
}

function TickingNumber({ value, decimals = 0, localeTag = 'en-US' }) {
  const [n, setN] = React.useState(0);
  const target = React.useRef(value);
  target.current = value;
  React.useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) { setN(value); return; }
    let raf, t0;
    const start = n;
    const dur = 800;
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / dur);
      const ease = 1 - Math.pow(1 - p, 3);
      setN(start + (target.current - start) * ease);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return n.toLocaleString(localeTag, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
}

function TickerStrip() {
  const { t } = useLandingI18n();
  const items = [
    { sym: 'AAPL', price: '184.21', chg: '+1.24%', pos: true },
    { sym: 'BTC-EUR', price: '62,481', chg: '+2.88%', pos: true },
    { sym: 'SPY', price: '527.40', chg: '+0.18%', pos: true },
    { sym: 'EURUSD', price: '1.0842', chg: '−0.12%', pos: false },
    { sym: 'NVDA', price: '904.18', chg: '+3.40%', pos: true },
    { sym: 'TSLA', price: '178.32', chg: '−1.21%', pos: false },
    { sym: 'ETH-EUR', price: '3,214', chg: '+1.04%', pos: true },
    { sym: 'MSFT', price: '419.61', chg: '+0.44%', pos: true },
    { sym: 'VWCE', price: '118.44', chg: '+0.62%', pos: true },
    { sym: 'GBPEUR', price: '1.1732', chg: '+0.08%', pos: true },
    { sym: 'GOOG', price: '164.02', chg: '−0.35%', pos: false },
    { sym: 'GC=F', price: '2,398.10', chg: '+0.92%', pos: true },
  ];
  const double = [...items, ...items];
  return (
    <div className="ticker" aria-label={t('Live market ticker')}>
      <div className="ticker__track">
        {double.map((t, i) => (
          <span className="ticker__item" key={i}>
            <span className="ticker__sym">{t.sym}</span>
            <span className="ticker__price">{t.price}</span>
            <span className={'ticker__chg ' + (t.pos ? 'gain' : 'loss')}>{t.chg}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function HeroDash() {
  const { t } = useLandingI18n();
  return (
    <div className="dash">
      <div className="dash__bar">
        <div className="dash__dots">
          <span className="dash__dot"/><span className="dash__dot"/><span className="dash__dot"/>
        </div>
        <div className="dash__path">fortec.app / portfolio</div>
        <div className="dash__live"><span className="dash__live-dot"/>Live</div>
      </div>
      <div className="dash__body">
        <HeroChart/>
      </div>
      <TickerStrip/>
      <div className="signal">
        <div className="signal__icon"><IBrain size={16}/></div>
        <div style={{flex:1}}>
          <div className="signal__label">AI signal · NVDA</div>
          <div className="signal__txt">{t('Model ensemble flags a regime change. Consider trimming 15%.')}</div>
          <div className="signal__conf">{t('Confidence 0.82 · 3 of 7 models agree')}</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HeroDash, HeroChart, TickerStrip, TickingNumber });
