// Watchlist / history view

const Watchlist = ({ onOpen, mode = 'watchlist', watchlist, onToggleWatch, history }) => {
  const [filter, setFilter] = React.useState('all');
  const [sort, setSort] = React.useState('score');

  // Both watchlist and history come exclusively from coins the user has actually analyzed.
  // No more fictional seed list — empty state means empty.
  const realHistory = Array.isArray(history) ? history : [];
  let baseItems;
  if (mode === 'history') {
    baseItems = realHistory;
  } else {
    const watched = watchlist instanceof Set ? watchlist : new Set();
    baseItems = realHistory.filter(it => watched.has(it.ticker));
  }

  // Real history coins don't have a tone/score until AI has run on them.
  // Treat undefined fields gracefully.
  const toneOf = (it) => {
    if (it.tone) return it.tone;
    const v = (it.verdict || '').toLowerCase();
    if (v.includes('strong buy') || v === 'buy') return 'green';
    if (v.includes('avoid')) return 'red';
    if (v.includes('caution') || v.includes('watch')) return 'amber';
    return null;
  };
  const mcOf = (it) => it.mc != null ? it.mc : (it.marketCap != null ? it.marketCap : null);
  const changeOf = (it) => it.change != null ? it.change : (it.change24h != null ? it.change24h : null);

  const filtered = baseItems.filter(it => {
    const t = toneOf(it);
    if (filter === 'buy') return t === 'green';
    if (filter === 'watch') return t === 'amber';
    if (filter === 'avoid') return t === 'red';
    return true;
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sort === 'score')  return (b.score || 0) - (a.score || 0);
    if (sort === 'change') return (changeOf(b) || 0) - (changeOf(a) || 0);
    if (sort === 'mc')     return (mcOf(b) || 0) - (mcOf(a) || 0);
    if (sort === 'ticker') return (a.ticker || '').localeCompare(b.ticker || '');
    return 0;
  });

  const isEmpty = sorted.length === 0;

  return (
    <div style={{ flex: 1, overflowY: 'auto' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '32px 36px 60px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <Badge tone="purple" size="sm">{mode === 'history' ? 'HISTORY' : 'WATCHLIST'}</Badge>
            <h1 style={{ fontFamily: 'var(--serif)', fontSize: 36, fontWeight: 400, margin: '10px 0 4px', letterSpacing: -0.5 }}>
              {mode === 'history' ? 'What you’ve looked at' : 'Coins on the radar'}
            </h1>
            <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>
              {sorted.length} of {baseItems.length} tokens · sorted by {sort}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              style={{
                background: 'rgba(28,21,48,0.6)', color: 'var(--ink-2)',
                border: '1px solid var(--line-2)', borderRadius: 2,
                padding: '7px 10px', fontSize: 12, fontWeight: 500,
                fontFamily: 'inherit', outline: 'none',
              }}>
              <option value="score">Score</option>
              <option value="change">24h Δ</option>
              <option value="mc">Market Cap</option>
              <option value="ticker">Ticker</option>
            </select>
            <div style={{ display: 'flex', gap: 6 }}>
              {[
                { k: 'all', label: 'All' },
                { k: 'buy', label: 'Buy', tone: 'green' },
                { k: 'watch', label: 'Watch', tone: 'amber' },
                { k: 'avoid', label: 'Avoid', tone: 'red' },
              ].map(t => (
                <button key={t.k} onClick={() => setFilter(t.k)}
                  className={'ob ob-sm' + (filter === t.k ? ' ob-active' : '')}
                  style={{ borderColor: filter === t.k ? 'var(--purple-glow)' : 'var(--line-2)', color: filter === t.k ? 'var(--ink)' : 'var(--ink-3)' }}
                >{t.label}</button>
              ))}
            </div>
          </div>
        </div>

        {isEmpty ? (
          <Card padding={48} style={{ textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 3, margin: '0 auto 16px',
              background: 'rgba(124,77,255,0.10)', border: '1px solid var(--line-2)',
              display: 'grid', placeItems: 'center', color: 'var(--purple-glow)',
            }}>
              <Icon name={mode === 'history' ? 'history' : 'star'} size={24} />
            </div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--ink)', marginBottom: 6 }}>
              {mode === 'history' ? 'No history yet' : 'Watchlist is empty'}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', maxWidth: 380, margin: '0 auto' }}>
              {mode === 'history'
                ? 'Coins you analyze will show up here.'
                : 'Star coins from the report screen to track them here.'}
            </div>
          </Card>
        ) : (
          <Card padding={0} style={{ overflow: 'hidden' }}>
            <div style={{
              display: 'grid', gridTemplateColumns: '60px 1.5fr 1fr 1fr 1fr 1fr 0.8fr 36px 28px',
              padding: '12px 18px', borderBottom: '1px solid var(--line)',
              fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600,
            }}>
              <span>Score</span>
              <span>Token</span>
              <span>Verdict</span>
              <span style={{ textAlign: 'right' }}>Market Cap</span>
              <span style={{ textAlign: 'right' }}>24h Δ</span>
              <span>Trend</span>
              <span>Age</span>
              <span></span>
              <span></span>
            </div>
            {sorted.map((it, i) => {
              const watched = watchlist instanceof Set && watchlist.has(it.ticker);
              return (
                <div key={it.ticker} style={{
                  display: 'grid', gridTemplateColumns: '60px 1.5fr 1fr 1fr 1fr 1fr 0.8fr 36px 28px',
                  padding: '14px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
                  alignItems: 'center', textAlign: 'left', width: '100%',
                  transition: 'background 0.12s', cursor: 'pointer',
                }}
                onClick={() => onOpen && onOpen(it)}
                onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(168,130,255,0.04)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <div>
                    {it.score != null
                      ? <ScoreRing score={it.score} size={40} stroke={3.5} animate={false} />
                      : <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-4)' }}>—</span>}
                  </div>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>${it.ticker}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{it.name || ''}</div>
                  </div>
                  <div>
                    {it.verdict
                      ? <Badge tone={toneOf(it) === 'green' ? 'green' : toneOf(it) === 'red' ? 'red' : 'amber'} size="sm">{it.verdict}</Badge>
                      : <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>not analyzed</span>}
                  </div>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 13, textAlign: 'right', color: 'var(--ink-2)' }}>
                    {mcOf(it) != null ? window.fmtUsd(mcOf(it)) : '—'}
                  </span>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 13, textAlign: 'right', fontWeight: 600,
                    color: changeOf(it) == null ? 'var(--ink-4)' : changeOf(it) >= 0 ? 'var(--green)' : 'var(--red)' }}>
                    {changeOf(it) == null ? '—' : window.fmtPct(changeOf(it))}
                  </span>
                  <div style={{ height: 32 }}>
                    {changeOf(it) != null && (
                      <Sparkline
                        data={genMiniChart(changeOf(it), it.ticker)}
                        width={120} height={32}
                        tone={changeOf(it) >= 0 ? (toneOf(it) === 'green' ? 'green' : 'purple') : 'red'}
                        showArea={false}
                      />
                    )}
                  </div>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-3)' }}>{it.age || '—'}</span>
                  <button
                    onClick={(e) => { e.stopPropagation(); onToggleWatch && onToggleWatch(it); }}
                    title={watched ? 'Remove from watchlist' : 'Add to watchlist'}
                    style={{
                      color: watched ? 'var(--purple-glow)' : 'var(--ink-4)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      padding: 4, borderRadius: 2,
                      transition: 'color 0.15s, background 0.15s',
                    }}
                    onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(168,130,255,0.10)'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
                    <Icon name="star" size={14} />
                  </button>
                  <span style={{ color: 'var(--ink-3)', display: 'flex', justifyContent: 'flex-end' }}>
                    <Icon name="arrow-right" size={14} />
                  </span>
                </div>
              );
            })}
          </Card>
        )}
      </div>
    </div>
  );
};

function genMiniChart(direction, seedKey) {
  // Deterministic mini chart so the spark line doesn't reshuffle on every render.
  let s = 0;
  for (let i = 0; i < (seedKey || '').length; i++) s = (s * 31 + seedKey.charCodeAt(i)) & 0xffff;
  if (s === 0) s = 7;
  const rand = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
  const pts = 24;
  const arr = [];
  let v = 50;
  for (let i = 0; i < pts; i++) {
    const trend = (direction / 100) * (i / pts) * 30;
    v = 50 + trend + (Math.sin(i * 0.9) * 4) + (rand() - 0.5) * 5;
    arr.push(v);
  }
  return arr;
}

window.Watchlist = Watchlist;
