/* Technical Analysis widgets */

function candleTimes(n) {
  const candles = (window.MOCK.CANDLES || []).slice(-n);
  if (candles.length === n && candles[0] && candles[0].t) return candles.map(c => c.t);
  const now = Date.now(), step = 86400000;
  return Array.from({ length: n }, (_, i) => now - (n - 1 - i) * step);
}

const { useEffect: useEffectTA, useRef: useRefTA } = React;

// TradingView Advanced Chart — drawing toolbar, indicators, real timeframes.
function TVAdvancedChart({ symbol = 'BINANCE:BTCUSDT.P', interval = 'D' }) {
  const boxRef = useRefTA(null);

  useEffectTA(() => {
    const box = boxRef.current;
    if (!box) return;
    box.innerHTML = '';

    const widgetEl = document.createElement('div');
    widgetEl.className = 'tradingview-widget-container__widget';
    widgetEl.style.height = 'calc(100% - 28px)';
    widgetEl.style.width = '100%';

    const copy = document.createElement('div');
    copy.className = 'tradingview-widget-copyright';
    copy.innerHTML = '<a href="https://www.tradingview.com/symbols/BINANCE-BTCUSDT.P/" rel="noopener nofollow" target="_blank"><span class="blue-text">BTCUSDT.P chart</span></a><span class="trademark"> by TradingView</span>';

    const script = document.createElement('script');
    script.src = 'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js';
    script.type = 'text/javascript';
    script.async = true;
    script.text = JSON.stringify({
      autosize: true,
      symbol,
      interval,
      timezone: 'Etc/UTC',
      theme: 'dark',
      style: '1',
      locale: 'en',
      backgroundColor: '#1c1f28',
      gridColor: 'rgba(42, 46, 56, 0.45)',
      hide_side_toolbar: false,
      hide_top_toolbar: false,
      hide_legend: false,
      hide_volume: false,
      allow_symbol_change: true,
      save_image: true,
      withdateranges: true,
      calendar: false,
      hide_date_ranges: false,
      support_host: 'https://www.tradingview.com',
    });

    box.appendChild(widgetEl);
    box.appendChild(copy);
    box.appendChild(script);

    return () => { box.innerHTML = ''; };
  }, [symbol, interval]);

  return <div ref={boxRef} className="tradingview-widget-container" style={{ height: '100%', width: '100%' }} />;
}

// === HERO: BTC main chart =================================================
function W_BTCHero() {
  const m = window.MOCK;
  const lastC = m.last.c;
  const chg = m.dayChangePct;
  const up = chg >= 0;
  // The price and day change come from Binance spot daily candles (snapshot.js). If that fetch failed
  // the server substitutes generated sample candles, so do not call the figures live.
  const sample = m.CANDLES_SOURCE === 'fallback';

  return (
    <div className="card" style={{ gridColumn: 'span 12' }}>
      <div className="card-h" style={{ alignItems: 'flex-start' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                width: 26, height: 26, borderRadius: 6,
                background: 'linear-gradient(135deg, var(--gold), oklch(0.55 0.13 60))',
                display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12,
                color: 'var(--bg-base)', fontFamily: 'var(--font-mono)'
              }}>₿</div>
              <div>
                <div style={{ fontWeight: 600, letterSpacing: '0.02em' }}>BTC / USDT</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-4)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Bitcoin · Binance spot</div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginLeft: 18 }}>
              <span className="mono" style={{ fontSize: 26, fontWeight: 600 }}>${window.fmtUSD(lastC)}</span>
              <span className={"mono " + (up ? 'up' : 'down')} style={{ fontSize: 13.5, fontWeight: 500 }}>
                {window.fmtSigned(m.dayChange, 0)} · {window.fmtSigned(chg, 2)}%
              </span>
              {sample ? (
                <span className="chip neutral" style={{ marginLeft: 6 }} title="Binance candles could not be fetched, so these figures are generated sample data, not market prices">
                  sample data
                </span>
              ) : (
                <span className="chip neutral" style={{ marginLeft: 6 }}>
                  <span className="pulse" /> &nbsp;live
                </span>
              )}
            </div>
          </div>
        </div>
        <span className="tag">TradingView · draw · fib · indicators</span>
      </div>

      <div className="card-b tv-hero" style={{ paddingTop: 8, paddingBottom: 10 }}>
        <TVAdvancedChart symbol="BINANCE:BTCUSDT.P" interval="D" />
      </div>
    </div>
  );
}

// === EMA stack — shows price vs each key EMA ============================
function W_EMAStack() {
  const m = window.MOCK;
  const price = m.last.c;
  const e50 = m.EMA50[m.EMA50.length-1];
  const e200 = m.EMA200[m.EMA200.length-1];
  let stackKind = 'neutral', stackLabel = 'Mixed stack';
  if (price && e50 && e200) {
    if (price > e50 && e50 > e200) { stackKind = 'bull'; stackLabel = 'Bullish stack'; }
    else if (price < e50 && e50 < e200) { stackKind = 'bear'; stackLabel = 'Bearish stack'; }
  }
  const rows = [
    { name: 'EMA 20 daily',  v: m.EMA20[m.EMA20.length-1],   note: 'short trend' },
    { name: 'EMA 50 weekly', v: e50,                         note: 'primary support', gold: true },
    { name: 'EMA 100 daily', v: m.EMA100[m.EMA100.length-1], note: 'mid-term' },
    { name: 'EMA 200 daily', v: e200,                        note: 'structural' },
  ];
  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-h">
        <CardTitle topic="ema-stack">EMA Stack</CardTitle>
        <span className={"chip " + stackKind}><span className="chip-dot" /> {stackLabel}</span>
      </div>
      <div className="card-b">
        {rows.map((r, i) => {
          const diff = ((price - r.v) / r.v) * 100;
          const above = price >= r.v;
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1fr auto auto',
              alignItems: 'center', gap: 12, padding: '8px 0',
              borderBottom: i < rows.length - 1 ? '1px solid var(--border-soft)' : 'none'
            }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 8, height: 8, borderRadius: 2,
                    background: r.gold ? 'var(--gold)' : above ? 'var(--bull)' : 'var(--bear)'
                  }} />
                  <span style={{ fontSize: 12.5, color: 'var(--text)' }}>{r.name}</span>
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--text-4)', marginLeft: 16, marginTop: 1 }}>{r.note}</div>
              </div>
              <div className="num" style={{ color: 'var(--text-2)' }}>${window.fmtUSD(r.v)}</div>
              <div className={"num " + (above ? 'up' : 'down')} style={{ minWidth: 56, textAlign: 'right' }}>
                {above ? '+' : ''}{diff.toFixed(2)}%
              </div>
            </div>
          );
        })}
        {(() => {
          const gc = window.MOCK.goldCross;
          if (!gc) return null;
          const isBull = gc.active;
          return (
            <div style={{ marginTop: 10, padding: '8px 10px', background: isBull ? 'var(--gold-bg)' : 'var(--bear-bg)', borderRadius: 6,
                          fontSize: 11.5, color: 'var(--text-2)', lineHeight: 1.5 }}>
              <span style={{ color: isBull ? 'var(--gold)' : 'var(--bear)', fontWeight: 600 }}>
                {isBull ? 'Golden Cross active' : 'Death Cross active'}
              </span>{' '}
              — EMA 50 {isBull ? 'above' : 'below'} EMA 200 for {gc.sessionsSince} sessions.
            </div>
          );
        })()}
      </div>
    </div>
  );
}

// === RSI widget ==========================================================
function W_RSI() {
  const m = window.MOCK;
  const rsi = m.RSI14.slice(-90);
  const cur = rsi[rsi.length - 1];
  let zone = 'neutral', chipKind = 'neutral';
  if (cur > 70) { zone = 'overbought'; chipKind = 'bear'; }
  else if (cur < 30) { zone = 'oversold'; chipKind = 'bull'; }

  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-h">
        <CardTitle topic="rsi">RSI 14 — Daily</CardTitle>
        <span className={"chip " + chipKind}><span className="chip-dot" /> {zone}</span>
      </div>
      <div className="card-b">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
          <span className="mono" style={{ fontSize: 28, fontWeight: 600 }}>{cur.toFixed(1)}</span>
          <span style={{ fontSize: 11, color: 'var(--text-3)' }}>of 100</span>
        </div>
        <RSIPanel values={rsi} times={candleTimes(rsi.length)} />
        <div style={{ marginTop: 4, fontSize: 11.5, color: 'var(--text-3)' }}>
          Divergence: no confirmed read
        </div>
      </div>
    </div>
  );
}

// === MACD widget =========================================================
function W_MACD() {
  const m = window.MOCK;
  const ln = m.MACD.line.slice(-90), sg = m.MACD.signal.slice(-90), hs = m.MACD.hist.slice(-90);
  const lastLine = ln[ln.length-1], lastSig = sg[sg.length-1];
  const cross = lastLine > lastSig ? 'bullish cross' : 'bearish cross';
  const k = lastLine > lastSig ? 'bull' : 'bear';

  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-h">
        <CardTitle topic="macd">MACD — Weekly</CardTitle>
        <span className={"chip " + k}><span className="chip-dot" /> {cross}</span>
      </div>
      <div className="card-b">
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>
          <span>MACD <span style={{ color: 'var(--info)' }}>{lastLine.toFixed(0)}</span></span>
          <span>Signal <span style={{ color: 'var(--gold)' }}>{lastSig.toFixed(0)}</span></span>
          <span>Hist <span style={{ color: hs[hs.length-1] >= 0 ? 'var(--bull)' : 'var(--bear)' }}>{window.fmtSigned(hs[hs.length-1], 0)}</span></span>
        </div>
        <MACDPanel data={{ line: ln, signal: sg, hist: hs }} times={candleTimes(ln.length)} />
        <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--text-2)' }}>
          {window.MOCK.macdExpandCount > 0
            ? `Histogram expanding for ${window.MOCK.macdExpandCount} session${window.MOCK.macdExpandCount !== 1 ? 's' : ''} — ${hs[hs.length-1] >= 0 ? 'bullish' : 'bearish'} momentum building.`
            : 'Histogram contracting — momentum fading.'}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { W_BTCHero, W_EMAStack, W_RSI, W_MACD });
