// NewsCarousel — home-page mixed feed: endorsements + videos, sorted by date.
// Fetches /api/endorsements and /videos.json in parallel, normalises into a
// uniform item shape, sorts by date descending, shows top 12.

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

function newsRelativeTime(dateStr) {
  if (!dateStr) return null;
  var diff = Date.now() - new Date(dateStr).getTime();
  var days = Math.floor(diff / 86400000);
  if (days < 1) return 'today';
  if (days === 1) return '1 day ago';
  if (days < 30) return days + ' days ago';
  var months = Math.floor(days / 30);
  if (months === 1) return '1 month ago';
  return months + ' months ago';
}

function newsAvatarColor(title, accent) {
  var palette = [accent, '#5ac8d6', '#a8d65a', '#e86a8a', '#8a7ae8'];
  var h = 0;
  for (var i = 0; i < (title || '').length; i++) h = (h * 31 + title.charCodeAt(i)) & 0xfffff;
  return palette[h % palette.length];
}

function NewsCard({ item, accent }) {
  var [hover, setHover] = React.useState(false);
  var color = newsAvatarColor(item.title, accent);

  return (
    <a
      href={item.link || '#'}
      target={item.link ? '_blank' : undefined}
      rel="noopener noreferrer"
      style={{
        display: 'block', textDecoration: 'none',
        width: 280, flexShrink: 0, scrollSnapAlign: 'start',
        background: '#0d0d0f',
        border: '1px solid ' + (hover && item.link ? accent + '40' : '#1f1f23'),
        borderRadius: 4,
        transform: hover && item.link ? 'translateY(-2px)' : 'translateY(0)',
        transition: 'border-color .18s, transform .18s, box-shadow .18s',
        boxShadow: hover && item.link ? '0 4px 20px ' + accent + '10' : 'none',
        overflow: 'hidden',
        cursor: item.link ? 'pointer' : 'default',
      }}
      onMouseEnter={function() { setHover(true); }}
      onMouseLeave={function() { setHover(false); }}
    >
      {/* 16:9 image */}
      <div style={{ position: 'relative', paddingTop: '56.25%', background: color + '12', overflow: 'hidden' }}>
        {item.image ? (
          <img
            src={item.image}
            alt={item.title}
            onError={function(e) { e.target.style.display = 'none'; }}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', transition: 'opacity .2s', opacity: hover ? 0.85 : 0.7 }}
          />
        ) : (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 48, height: 48, borderRadius: '50%', background: color + '30', border: '1px solid ' + color + '50', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: color }}>
              {(item.title || '?')[0].toUpperCase()}
            </div>
          </div>
        )}
        {/* Badge */}
        <div style={{
          position: 'absolute', top: 8, left: 8,
          fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase',
          background: 'rgba(10,10,12,0.82)', color: item.kind === 'video' ? '#5ac8d6' : accent,
          padding: '2px 7px', borderRadius: 2,
          border: '1px solid ' + (item.kind === 'video' ? '#5ac8d640' : accent + '40'),
          backdropFilter: 'blur(4px)',
        }}>
          {item.kind}
        </div>
      </div>

      {/* Text */}
      <div style={{ padding: '12px 14px 14px' }}>
        <div style={{
          fontSize: 12, color: '#e4e4e7', lineHeight: 1.45, fontWeight: 500,
          marginBottom: 4,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>
          {item.title}
        </div>
        {item.badge && (
          <div style={{ fontSize: 11, color: '#52525b', letterSpacing: '0.04em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 4 }}>
            {item.badge}
          </div>
        )}
        {item.snippet && (
          <div style={{ fontSize: 11, color: '#71717a', lineHeight: 1.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.snippet}
          </div>
        )}
        {item.date && (
          <div style={{ fontSize: 10, color: '#3f3f46', marginTop: 10, letterSpacing: '0.06em' }}>
            {newsRelativeTime(item.date)}
          </div>
        )}
      </div>
    </a>
  );
}

function NewsCarouselSkeleton() {
  return (
    <div style={{ width: 280, flexShrink: 0, background: '#0d0d0f', border: '1px solid #1f1f23', borderRadius: 4, overflow: 'hidden' }}>
      <div style={{ paddingTop: '56.25%', background: '#1f1f23', opacity: 0.5 }} />
      <div style={{ padding: '12px 14px 14px' }}>
        {[80, 60, 40].map(function(w, i) {
          return <div key={i} style={{ height: 10, background: '#1f1f23', borderRadius: 2, marginBottom: 8, width: w + '%', opacity: 0.6 }} />;
        })}
      </div>
    </div>
  );
}

function NewsCarousel({ accent, onNavigate }) {
  accent = accent || '#e8a84a';

  var [items, setItems]   = React.useState([]);
  var [loading, setLoading] = React.useState(true);
  var [fetchedAt, setFetchedAt] = React.useState(null);
  var [linkHoverW, setLinkHoverW] = React.useState(null);
  var [linkHoverE, setLinkHoverE] = React.useState(null);

  React.useEffect(function() {
    var p1 = fetch(API_BASE + '/api/endorsements')
      .then(function(r) { return r.json(); })
      .then(function(j) { return (j.data || []).filter(function(it) { return it.person || it.snippet; }); })
      .catch(function() { return []; });

    var p2 = fetch('/videos.json')
      .then(function(r) { return r.json(); })
      .catch(function() { return {}; });

    Promise.all([p1, p2]).then(function(results) {
      var endorsements = results[0];
      var vdata = results[1];
      var news = vdata.news || [];

      var normalised = [];

      endorsements.forEach(function(it) {
        normalised.push({
          kind: 'endorsement',
          id: it.id,
          title: it.person || 'Endorsement',
          snippet: it.snippet ? it.snippet.slice(0, 120) : '',
          image: it.photo || null,
          date: it.date || null,
          link: it.link || null,
          badge: it.handle || it.role || null,
        });
      });

      news.forEach(function(v) {
        normalised.push({
          kind: 'video',
          id: v.id,
          title: v.title,
          snippet: '',
          image: 'https://img.youtube.com/vi/' + v.id + '/hqdefault.jpg',
          date: v.date || null,
          link: 'https://youtu.be/' + v.id,
          badge: 'video',
        });
      });

      normalised.sort(function(a, b) {
        if (!a.date && !b.date) return 0;
        if (!a.date) return 1;
        if (!b.date) return -1;
        return a.date < b.date ? 1 : -1;
      });

      setItems(normalised.slice(0, 12));
      setFetchedAt(Date.now());
      setLoading(false);
    }).catch(function() { setLoading(false); });
  }, []);

  var updatedAgo = fetchedAt ? newsRelativeTime(new Date(fetchedAt).toISOString()) : null;

  return (
    <section style={{ borderTop: '1px solid #1f1f23', background: '#0a0a0c' }}>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: 'clamp(48px,8vh,72px) clamp(20px,5vw,32px) clamp(64px,10vh,80px)' }}>

        {/* Header row */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 'clamp(24px,4vh,36px)' }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#52525b', textTransform: 'uppercase', marginBottom: 10 }}>§ recent</div>
            <h2 style={{ fontSize: 'clamp(26px,5.5vw,44px)', fontWeight: 400, color: '#fafafa', letterSpacing: '-0.02em', lineHeight: 1, margin: 0, fontFamily: 'inherit' }}>Recent</h2>
            <div style={{ fontSize: 13, color: '#71717a', marginTop: 6 }}>Videos and endorsements as they land.{updatedAgo ? ' Updated ' + updatedAgo + '.' : ''}</div>
          </div>
          <div style={{ display: 'flex', gap: 16 }}>
            <button
              onClick={function() { onNavigate && onNavigate('watch'); }}
              onMouseEnter={function() { setLinkHoverW(true); }}
              onMouseLeave={function() { setLinkHoverW(false); }}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: linkHoverW ? accent : '#52525b', transition: 'color .15s' }}
            >
              watch →
            </button>
            <button
              onClick={function() { onNavigate && onNavigate('endorsements'); }}
              onMouseEnter={function() { setLinkHoverE(true); }}
              onMouseLeave={function() { setLinkHoverE(false); }}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: linkHoverE ? accent : '#52525b', transition: 'color .15s' }}
            >
              endorsements →
            </button>
          </div>
        </div>

        <div style={{ borderBottom: '1px solid #1f1f23', marginBottom: 'clamp(24px,4vh,32px)' }} />

        {/* Carousel */}
        {loading ? (
          <div className="video-scroll" style={{ display: 'flex', gap: 12, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 12 }}>
            {[0, 1, 2, 3].map(function(i) { return <NewsCarouselSkeleton key={i} />; })}
          </div>
        ) : items.length === 0 ? (
          <div style={{ color: '#52525b', fontSize: 13, letterSpacing: '0.06em' }}>No recent content yet.</div>
        ) : (
          <div className="video-scroll" style={{ display: 'flex', gap: 12, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 12, alignItems: 'flex-start' }}>
            {items.map(function(item) {
              return <NewsCard key={item.kind + '-' + item.id} item={item} accent={accent} />;
            })}
          </div>
        )}
      </div>
    </section>
  );
}

window.NewsCarousel = NewsCarousel;
