// Slim featured-content carousel — 4 slides (endorsement slide is conditional on API data), rotates every 8s, pauses on hover.

const API_BASE = (typeof window !== 'undefined' && window.location.hostname === 'localhost') ? '' : 'https://ecash.onrender.com';

function FeaturedCarousel({ accent = '#e8a84a', onScrollToBalance, onNavigate }) {
  const [idx, setIdx]           = React.useState(0);
  const [paused, setPaused]     = React.useState(false);
  const [featured, setFeatured] = React.useState([]);
  const scIdxRef = React.useRef(Math.floor(Math.random() * window.ECASH_CONSTANTS.SIDECHAINS.length));

  React.useEffect(() => {
    fetch(API_BASE + '/api/endorsements')
      .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
      .then(j => setFeatured((j.data || []).filter(e => e.featured)))
      .catch(() => {});
  }, []);

  const slides = React.useMemo(() => {
    const result = [];

    if (featured.length > 0) {
      const e = featured[Math.floor(Math.random() * featured.length)];
      result.push({
        key: 'endorsement',
        render: (accent) => (
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.18em', color: '#52525b', textTransform: 'uppercase', marginBottom: 6 }}>endorsed by</div>
            <div style={{ fontSize: 'clamp(13px,2.5vw,15px)', color: '#e4e4e7', lineHeight: 1.5, marginBottom: 4 }}>
              "{(e.snippet || '').slice(0, 120)}{e.snippet && e.snippet.length > 120 ? '…' : ''}"
            </div>
            <div style={{ fontSize: 11, color: '#71717a' }}>{e.person}{e.role ? ` · ${e.role}` : ''}</div>
          </div>
        ),
      });
    }

    result.push({
      key: 'airdrop',
      render: (accent) => (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.18em', color: '#52525b', textTransform: 'uppercase', marginBottom: 6 }}>1:1 airdrop</div>
            <div style={{ fontSize: 'clamp(14px,2.8vw,18px)', color: '#e4e4e7', lineHeight: 1.4 }}>
              Hold BTC? You'll receive eCash 1:1 on fork day.
            </div>
          </div>
          {onScrollToBalance && (
            <button
              onClick={onScrollToBalance}
              style={{
                background: 'transparent', border: `1px solid ${accent}`,
                color: accent, padding: '8px 16px', fontFamily: 'inherit',
                fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
                cursor: 'pointer', borderRadius: 3, flexShrink: 0,
              }}
            >
              Check your balance →
            </button>
          )}
        </div>
      ),
    });

    const sc = window.ECASH_CONSTANTS.SIDECHAINS[scIdxRef.current];
    result.push({
      key: 'sidechain-' + sc.slug,
      render: (accent) => (
        <div>
          <div style={{ fontSize: 10, letterSpacing: '0.18em', color: '#52525b', textTransform: 'uppercase', marginBottom: 6 }}>
            sidechain spotlight · // {sc.slug}
          </div>
          <div style={{ fontSize: 'clamp(14px,2.8vw,18px)', color: '#e4e4e7', lineHeight: 1.4, marginBottom: 4 }}>
            {sc.name} — {sc.desc}
          </div>
          {onNavigate && (
            <button
              onClick={() => onNavigate('sidechains')}
              style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.12em',
                textTransform: 'uppercase', color: '#52525b', padding: 0,
              }}
              onMouseEnter={e => e.target.style.color = accent}
              onMouseLeave={e => e.target.style.color = '#52525b'}
            >
              all sidechains →
            </button>
          )}
        </div>
      ),
    });

    result.push({
      key: 'node',
      render: (accent) => (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.18em', color: '#52525b', textTransform: 'uppercase', marginBottom: 6 }}>run a node</div>
            <div style={{ fontSize: 'clamp(14px,2.8vw,18px)', color: '#e4e4e7', lineHeight: 1.4 }}>
              Download BitWindow → run an eCash node
            </div>
          </div>
          {onNavigate && (
            <button
              onClick={() => onNavigate('download')}
              style={{
                background: 'transparent', border: `1px solid #3f3f46`,
                color: '#a1a1aa', padding: '8px 16px', fontFamily: 'inherit',
                fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
                cursor: 'pointer', borderRadius: 3, flexShrink: 0,
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = accent; e.currentTarget.style.color = accent; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = '#3f3f46'; e.currentTarget.style.color = '#a1a1aa'; }}
            >
              Get BitWindow →
            </button>
          )}
        </div>
      ),
    });

    return result;
  }, [featured]);

  React.useEffect(() => {
    if (paused || slides.length === 0) return;
    const id = setInterval(() => setIdx(i => (i + 1) % slides.length), 8000);
    return () => clearInterval(id);
  }, [paused, slides.length]);

  React.useEffect(() => {
    if (slides.length > 0) setIdx(i => Math.min(i, slides.length - 1));
  }, [slides.length]);

  if (slides.length === 0) return null;

  const safeIdx = idx % slides.length;
  const slide   = slides[safeIdx];

  const arrowBtn = {
    background: 'transparent', border: 'none', cursor: 'pointer',
    color: '#52525b', fontSize: 20, padding: '0 6px', flexShrink: 0,
    fontFamily: 'inherit', transition: 'color .15s', lineHeight: 1,
  };

  return (
    <div
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      style={{
        borderTop: '1px solid #1f1f23',
        borderBottom: '1px solid #1f1f23',
        background: '#0a0a0c',
        padding: 'clamp(16px,3vh,22px) clamp(20px,5vw,32px)',
      }}
    >
      <div style={{ maxWidth: 880, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 14 }}>
        <button
          onClick={() => setIdx(i => (i - 1 + slides.length) % slides.length)}
          style={arrowBtn}
          onMouseEnter={e => e.target.style.color = accent}
          onMouseLeave={e => e.target.style.color = '#52525b'}
        >‹</button>

        <div style={{ flex: 1, minWidth: 0 }}>
          {slide.render(accent)}
        </div>

        <button
          onClick={() => setIdx(i => (i + 1) % slides.length)}
          style={arrowBtn}
          onMouseEnter={e => e.target.style.color = accent}
          onMouseLeave={e => e.target.style.color = '#52525b'}
        >›</button>
      </div>

      <div style={{ maxWidth: 880, margin: '10px auto 0', display: 'flex', justifyContent: 'center', gap: 6 }}>
        {slides.map((s, i) => (
          <button
            key={s.key}
            onClick={() => setIdx(i)}
            style={{
              width: 6, height: 6, borderRadius: '50%', padding: 0, border: 'none',
              cursor: 'pointer', background: i === safeIdx ? accent : '#27272a',
              transition: 'background .2s',
            }}
          />
        ))}
      </div>
    </div>
  );
}

window.FeaturedCarousel = FeaturedCarousel;
