// Landing screen — paste CA or pick from a live trending/search dropdown.

const Landing = ({ onAnalyze }) => {
  const [ca, setCa] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const [results, setResults] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [activeIdx, setActiveIdx] = React.useState(-1);
  const inputRef = React.useRef(null);
  const wrapRef = React.useRef(null);
  const debounceRef = React.useRef(0);
  const reqIdRef = React.useRef(0);

  const fetchTrending = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    const id = ++reqIdRef.current;
    try {
      const items = await window.fetchTrendingSolana();
      if (id !== reqIdRef.current) return;
      setResults(items);
    } catch (e) {
      if (id !== reqIdRef.current) return;
      setError('Trending list unavailable. Type a token name or paste a contract.');
      setResults([]);
    } finally {
      if (id === reqIdRef.current) setLoading(false);
    }
  }, []);

  const fetchSearch = React.useCallback(async (q) => {
    setLoading(true);
    setError(null);
    const id = ++reqIdRef.current;
    try {
      const items = await window.searchDexTokens(q);
      if (id !== reqIdRef.current) return;
      setResults(items);
    } catch (e) {
      if (id !== reqIdRef.current) return;
      setError('Search failed. Try again.');
      setResults([]);
    } finally {
      if (id === reqIdRef.current) setLoading(false);
    }
  }, []);

  React.useEffect(() => { inputRef.current?.focus(); }, []);

  // Debounced search-or-trending whenever query changes (and dropdown is open)
  React.useEffect(() => {
    if (!open) return;
    window.clearTimeout(debounceRef.current);
    const q = ca.trim();
    if (q === '') {
      fetchTrending();
      return;
    }
    // If a full base58 mint is pasted, skip the dropdown — caller can submit directly
    if (window.SOLANA_CA_RE.test(q)) {
      setResults([]);
      return;
    }
    debounceRef.current = window.setTimeout(() => fetchSearch(q), 250);
    return () => window.clearTimeout(debounceRef.current);
  }, [ca, open, fetchTrending, fetchSearch]);

  // Click-outside closes the dropdown
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  const submit = (preset) => {
    const value = preset || ca.trim();
    if (!value) return;
    setOpen(false);
    setActiveIdx(-1);
    onAnalyze(value);
  };

  const onKeyDown = (e) => {
    if (e.key === 'Escape') { setOpen(false); return; }
    if (!open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) { setOpen(true); return; }
    if (open && results.length > 0) {
      if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIdx(i => Math.min(results.length - 1, i + 1)); return; }
      if (e.key === 'ArrowUp')   { e.preventDefault(); setActiveIdx(i => Math.max(0, i - 1)); return; }
      if (e.key === 'Enter') {
        if (activeIdx >= 0 && activeIdx < results.length) { e.preventDefault(); submit(results[activeIdx].ca); return; }
      }
    }
    if (e.key === 'Enter') submit();
  };

  return (
    <div style={{
      flex: 1, overflowY: 'auto',
      display: 'flex', flexDirection: 'column',
      justifyContent: 'flex-start', alignItems: 'center',
      minHeight: '100%',
    }}>
      <div style={{
        width: '100%', maxWidth: 880,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        padding: '140px 40px 40px', textAlign: 'center',
        position: 'relative',
      }}>
        <h1 style={{
          fontFamily: 'var(--serif)', fontWeight: 400,
          fontSize: 60, lineHeight: 1.05, letterSpacing: -1,
          margin: '0 0 18px', maxWidth: 760,
        }}>
          Drop the CA.<br />
          <em style={{ color: 'var(--purple-glow)', fontStyle: 'italic' }}>I'll tell you if it's cooked.</em>
        </h1>
        <p style={{
          maxWidth: 540, fontSize: 15, color: 'var(--ink-3)',
          margin: 0, lineHeight: 1.6,
        }}>
          Drop any Solana contract. Live chart, real-time market data, and an AI
          read on whether it's worth playing — or whether it's a dead-cap rug.
        </p>

        {/* CA input + dropdown */}
        <div ref={wrapRef} style={{ width: '100%', maxWidth: 720, marginTop: 36, position: 'relative' }}>
          <div style={{
            position: 'relative',
            background: 'rgba(15,10,24,0.55)',
            border: '1px solid var(--purple)',
            borderRadius: 3,
            padding: 6,
            boxShadow: '0 0 0 4px rgba(124,77,255,0.10)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
              <div style={{ paddingLeft: 18, color: 'var(--purple-glow)', display: 'flex', alignItems: 'center' }}>
                <Icon name="search" size={18} />
              </div>
              <input
                ref={inputRef}
                value={ca}
                onChange={e => { setCa(e.target.value); setActiveIdx(-1); if (!open) setOpen(true); }}
                onFocus={() => setOpen(true)}
                onKeyDown={onKeyDown}
                placeholder="Paste contract or search a Solana token…"
                style={{
                  flex: 1, minWidth: 0,
                  background: 'transparent', border: 'none', outline: 'none',
                  fontFamily: 'var(--mono)', fontSize: 15, color: 'var(--ink)',
                  padding: '20px 18px', letterSpacing: 0,
                  textAlign: 'left',
                }}
              />
              <button onClick={() => submit()} className="ob ob-lg" style={{
                height: 48, padding: '0 28px', margin: 4,
                fontSize: 14, letterSpacing: 0.3,
              }}>
                Analyze
              </button>
            </div>
          </div>

          {/* Dropdown */}
          {open && (
            <div style={{
              position: 'absolute', top: 'calc(100% + 8px)', left: 0, right: 0,
              background: 'rgba(15,10,24,0.95)',
              backdropFilter: 'blur(16px) saturate(160%)',
              WebkitBackdropFilter: 'blur(16px) saturate(160%)',
              border: '1px solid var(--line-2)', borderRadius: 3,
              boxShadow: '0 30px 80px -20px rgba(0,0,0,0.6), 0 0 0 1px rgba(168,130,255,0.08)',
              maxHeight: 420, overflowY: 'auto',
              zIndex: 50, textAlign: 'left',
              animation: 'fadeUp 0.18s ease',
            }}>
              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '10px 14px', borderBottom: '1px solid var(--line)',
                fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--ink-3)',
                textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600,
              }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span style={{
                    width: 6, height: 6, borderRadius: 99,
                    background: loading ? 'var(--amber)' : 'var(--green)',
                    animation: loading ? 'pulseDot 0.8s ease infinite' : 'pulseDot 1.6s ease infinite',
                  }} />
                  {ca.trim() === '' ? 'Trending on Solana' : `Search · "${ca.trim().slice(0, 24)}"`}
                </span>
                <span>{loading ? 'loading…' : `${results.length} result${results.length === 1 ? '' : 's'}`}</span>
              </div>

              {error && (
                <div style={{ padding: '14px 14px', fontSize: 12, color: 'var(--amber)' }}>{error}</div>
              )}

              {!error && results.length === 0 && !loading && (
                <div style={{ padding: '20px 14px', fontSize: 12, color: 'var(--ink-3)' }}>
                  {window.SOLANA_CA_RE.test(ca.trim())
                    ? 'Looks like a contract address — press Enter to analyze.'
                    : 'No matches. Try a different ticker or paste a contract.'}
                </div>
              )}

              {results.map((row, i) => {
                const active = i === activeIdx;
                return (
                  <button
                    key={row.ca}
                    onMouseDown={(e) => { e.preventDefault(); submit(row.ca); }}
                    onMouseEnter={() => setActiveIdx(i)}
                    style={{
                      width: '100%', display: 'grid',
                      gridTemplateColumns: '36px 1fr auto auto',
                      alignItems: 'center', gap: 12,
                      padding: '10px 14px',
                      background: active ? 'rgba(168,130,255,0.08)' : 'transparent',
                      borderTop: i === 0 ? 'none' : '1px solid var(--line)',
                      borderLeft: active ? '2px solid var(--purple)' : '2px solid transparent',
                      textAlign: 'left',
                      transition: 'background 0.12s, border-color 0.12s',
                    }}
                  >
                    <span style={{
                      width: 30, height: 30, borderRadius: 2, overflow: 'hidden',
                      background: 'rgba(124,77,255,0.10)',
                      display: 'grid', placeItems: 'center',
                      color: 'var(--purple-glow)', fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 700,
                    }}>
                      {row.imageUrl
                        ? <img src={row.imageUrl} alt="" loading="lazy" style={{ width: 30, height: 30, objectFit: 'cover' }} onError={(e) => { e.currentTarget.style.display = 'none'; }} />
                        : (row.ticker || '?').slice(0, 2)}
                    </span>
                    <span style={{ minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                        <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--ink)' }}>${row.ticker}</span>
                        <span style={{ fontSize: 12, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.name}</span>
                      </div>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-4)', marginTop: 2 }}>
                        {row.ca ? `${row.ca.slice(0, 6)}…${row.ca.slice(-4)}` : ''}
                        {row.dexId ? <span style={{ marginLeft: 8, color: 'var(--ink-3)' }}>· {row.dexId}</span> : null}
                      </div>
                    </span>
                    <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-2)', textAlign: 'right' }}>
                      {row.priceUsd != null ? formatPrice(row.priceUsd) : '—'}
                    </span>
                    <span style={{
                      fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 600,
                      color: row.change24h == null ? 'var(--ink-3)' : (row.change24h >= 0 ? 'var(--green)' : 'var(--red)'),
                      minWidth: 60, textAlign: 'right',
                    }}>
                      {row.change24h == null ? '—' : window.fmtPct(row.change24h)}
                    </span>
                  </button>
                );
              })}
            </div>
          )}

          <div style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--mono)', letterSpacing: 0.5 }}>
            Solana · press Enter to analyze · ↑ ↓ to pick from list
          </div>
        </div>
      </div>
    </div>
  );
};

function formatPrice(n) {
  if (n >= 1) return '$' + n.toFixed(4);
  if (n >= 0.01) return '$' + n.toFixed(5);
  if (n >= 0.0001) return '$' + n.toFixed(7);
  return '$' + n.toExponential(2);
}

window.Landing = Landing;
