// Endorsements tab — eCash section, sourced live from Notion via /api/endorsements.

const API_BASE = (typeof window !== 'undefined' && window.location.hostname === 'localhost') ? '' : 'https://ecash.onrender.com';
// Cards mimic Telegram's link-preview pattern: left accent bar, source label ("X (formerly Twitter)"),
// photo floats top-right, author + tweet body flow as a single text block underneath.
// The whole card is a link to the source.

const FILTER_TYPES = ['All', 'Tweet', 'Quote', 'Video', 'Article', 'Podcast'];
const DC_FILTER_TYPES = ['All', 'Tweet', 'Video', 'Article', 'Nostr', 'Podcast'];

// Source label — what shows at the very top of the card, like "X (formerly Twitter)" in TG.
function sourceLabel(item) {
  switch (item.type) {
    case 'Tweet':   return 'X (formerly Twitter)';
    case 'Video':   return 'YouTube';
    case 'Podcast': return item.source || 'Podcast';
    case 'Nostr':   return 'Nostr';
    case 'Link':
      if (item.link) {
        try { return new URL(item.link).hostname.replace(/^www\./, ''); } catch (e) { return 'Link'; }
      }
      return 'Link';
    case 'Article':
      if (item.source) return item.source;
      if (item.link) {
        try { return new URL(item.link).hostname.replace(/^www\./, ''); } catch (e) { return 'Article'; }
      }
      return 'Article';
    case 'Quote':   return null;
    default:        return null;
  }
}

// Resolve a photo URL from whatever signals the item provides.
// Priority: explicit photo field → Twitter avatar via unavatar.io → YouTube video thumbnail.
function resolvePhoto(item) {
  if (item.photo) return item.photo;
  if (item.handle) {
    var handle = item.handle.replace(/^@/, '').trim();
    if (handle) return 'https://unavatar.io/twitter/' + handle;
  }
  if (item.type === 'Video' && item.link) {
    var m = item.link.match(/(?:youtube\.com\/(?:live|watch|embed)\/|youtu\.be\/)([A-Za-z0-9_-]{11})/);
    if (!m) m = item.link.match(/[?&]v=([A-Za-z0-9_-]{11})/);
    if (m) return 'https://img.youtube.com/vi/' + m[1] + '/mqdefault.jpg';
  }
  return null;
}

// Build the author intro line the way X/Telegram does:
//   "Freedom Monk τ∇ (@freedom_monk) on X"
function authorIntro(item) {
  if (!item) return '';
  var parts = [];
  if (item.person) parts.push(item.person);
  if (item.handle) parts.push('(' + item.handle + ')');
  if (item.type === 'Tweet') parts.push('on X');
  return parts.join(' ');
}

function EndorsementCard({ item, accent }) {
  var [hover, setHover] = React.useState(false);
  var sourceText = sourceLabel(item);
  var isLink = !!item.link;
  var photo = resolvePhoto(item);

  // Strip pic.twitter.com URLs and trailing whitespace from snippet (X auto-appends them).
  var body = (item.snippet || '').replace(/https?:\/\/pic\.twitter\.com\/\S+/g, '').trim();
  var intro = authorIntro(item);

  // If there's literally nothing to show besides a label, don't render an empty card.
  if (!intro && !body && !photo) return null;

  var cardStyle = {
    display: 'block',
    textDecoration: 'none',
    width: 360,
    height: 260,
    flexShrink: 0,
    scrollSnapAlign: 'start',
    position: 'relative',
    overflow: 'hidden',
    background: '#0d0d0f',
    border: '1px solid ' + (hover && isLink ? accent + '55' : '#1f1f23'),
    borderLeft: '3px solid ' + (hover && isLink ? accent : accent + 'a0'),
    borderRadius: 4,
    padding: '14px 18px 16px',
    transition: 'border-color .18s, box-shadow .18s, transform .18s',
    boxShadow: hover && isLink ? '0 4px 24px ' + accent + '12' : 'none',
    transform: hover && isLink ? 'translateY(-2px)' : 'translateY(0)',
    cursor: isLink ? 'pointer' : 'default',
  };

  var content = (
    <React.Fragment>
      {sourceText && (
        <div style={{
          fontSize: 12, color: accent, marginBottom: 10,
          fontWeight: 500, letterSpacing: '0.01em',
        }}>
          {sourceText}
        </div>
      )}

      {/* Photo floats top-right; text flows around it */}
      {photo && (
        <img
          src={photo}
          alt={item.person || ''}
          onError={function(e) { e.target.style.display = 'none'; }}
          style={{
            float: 'right',
            width: item.type === 'Video' ? 120 : 76,
            height: item.type === 'Video' ? 68 : 76,
            marginLeft: 14, marginBottom: 8,
            borderRadius: 4,
            objectFit: 'cover',
            border: '1px solid #1f1f23',
            background: '#0a0a0c',
          }}
        />
      )}

      {/* Author intro line — bolder, slightly bigger than body */}
      {intro && (
        <div style={{
          color: '#fafafa', fontWeight: 500,
          fontSize: 14, lineHeight: 1.45,
          marginBottom: body ? 6 : 0,
          wordBreak: 'break-word',
        }}>
          {intro}
        </div>
      )}

      {/* Tweet body — flows around the float */}
      {body && (
        <div style={{
          fontSize: 13, color: '#d4d4d8', lineHeight: 1.6,
          whiteSpace: 'pre-wrap', wordBreak: 'break-word',
        }}>
          {body}
        </div>
      )}

      {/* If only a role exists (e.g. Quote type without snippet) */}
      {!body && !intro && item.role && (
        <div style={{ fontSize: 13, color: '#a1a1aa', lineHeight: 1.5 }}>
          {item.role}
        </div>
      )}

      {/* Clear the float so the card sizes correctly */}
      <div style={{ clear: 'both' }} />

      {/* Bottom fade — masks overflowing text */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: 48,
        background: 'linear-gradient(to bottom, transparent, #0d0d0f)',
        pointerEvents: 'none',
      }} />
    </React.Fragment>
  );

  if (isLink) {
    return (
      <a
        href={item.link}
        target="_blank"
        rel="noopener noreferrer"
        style={cardStyle}
        onMouseEnter={function() { setHover(true); }}
        onMouseLeave={function() { setHover(false); }}
      >
        {content}
      </a>
    );
  }
  return <div style={cardStyle}>{content}</div>;
}

function EndorsementSkeleton() {
  return (
    <div style={{
      background: '#0d0d0f', border: '1px solid #1f1f23',
      borderLeft: '3px solid #1f1f23',
      borderRadius: 4, padding: '14px 18px 16px', width: 360, height: 260, flexShrink: 0, overflow: 'hidden',
    }}>
      <div style={{ height: 11, width: '40%', background: '#1f1f23', borderRadius: 2, marginBottom: 14, opacity: 0.6 }} />
      <div style={{ float: 'right', width: 76, height: 76, background: '#1f1f23', borderRadius: 4, marginLeft: 14, marginBottom: 8, opacity: 0.5 }} />
      <div style={{ height: 12, width: '70%', background: '#1f1f23', borderRadius: 2, marginBottom: 8, opacity: 0.6 }} />
      {[90, 80, 70, 50].map(function(w, i) {
        return <div key={i} style={{ height: 10, background: '#1f1f23', borderRadius: 2, marginBottom: 8, width: w + '%', opacity: 0.5 }} />;
      })}
      <div style={{ clear: 'both' }} />
    </div>
  );
}

function EndorsementsTab({ accent }) {
  accent = accent || '#e8a84a';

  var [items, setItems] = React.useState([]);
  var [loading, setLoading] = React.useState(true);
  var [filter, setFilter] = React.useState('All');

  var [dcItems, setDcItems] = React.useState([]);
  var [dcLoading, setDcLoading] = React.useState(true);
  var [dcFilter, setDcFilter] = React.useState('All');

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

  React.useEffect(function() {
    fetch('/drivechain-endorsements.json')
      .then(function(r) { return r.json(); })
      .then(function(data) {
        var valid = data.filter(function(it) {
          return it.snippet || it.person || it.role;
        });
        setDcItems(valid);
        setDcLoading(false);
      })
      .catch(function() { setDcLoading(false); });
  }, []);

  var filtered = filter === 'All' ? items : items.filter(function(e) { return e.type === filter; });
  var dcFiltered = dcFilter === 'All' ? dcItems : dcItems.filter(function(e) { return e.type === dcFilter; });

  return (
    <main style={{ position: 'relative', maxWidth: 1100, margin: '0 auto', padding: 'clamp(120px,18vh,160px) clamp(20px,5vw,32px) clamp(80px,12vh,120px)' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#52525b', textTransform: 'uppercase', marginBottom: 14 }}>§ endorsements</div>
      <h1 style={{ fontSize: 'clamp(28px,6vw,48px)', fontWeight: 400, color: '#fafafa', letterSpacing: '-0.02em', lineHeight: 1.1, margin: '0 0 8px', fontFamily: 'inherit' }}>Endorsements</h1>
      <div style={{ fontSize: 14, color: '#71717a', marginTop: 8, fontFamily: 'inherit' }}>What Bitcoiners, researchers, and builders are saying about eCash.</div>
      <div style={{ borderBottom: '1px solid #1f1f23', margin: 'clamp(24px,5vh,40px) 0' }} />

      {/* Filter bar */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 'clamp(20px,3vh,28px)' }}>
        {FILTER_TYPES.map(function(t) {
          var active = filter === t;
          var count = t === 'All' ? items.length : items.filter(function(e) { return e.type === t; }).length;
          return (
            <button key={t} onClick={function() { setFilter(t); }} style={{
              background: active ? accent + '18' : 'transparent',
              border: '1px solid ' + (active ? accent : '#27272a'),
              color: active ? accent : '#71717a',
              padding: '5px 10px', fontFamily: 'inherit', fontSize: 10,
              letterSpacing: '0.1em', textTransform: 'lowercase',
              cursor: 'pointer', borderRadius: 3,
              transition: 'border-color .15s, color .15s',
            }}>
              {t.toLowerCase()} ({count})
            </button>
          );
        })}
      </div>

      {/* eCash carousel */}
      {loading ? (
        <div className="video-scroll" style={{ display: 'flex', gap: 14, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 12 }}>
          {[0, 1, 2].map(function(i) { return <EndorsementSkeleton key={i} />; })}
        </div>
      ) : filtered.length === 0 ? (
        <div style={{ color: '#52525b', fontSize: 13, letterSpacing: '0.06em' }}>
          {items.length === 0 ? 'No endorsements yet — check back soon.' : 'No endorsements match this filter.'}
        </div>
      ) : (
        <div className="video-scroll" style={{ display: 'flex', gap: 14, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 12 }}>
          {filtered.map(function(item) {
            return <EndorsementCard key={item.id} item={item} accent={accent} />;
          })}
        </div>
      )}

      {/* ── Drivechain Archive ────────────────────────────────────────── */}
      <div style={{ borderBottom: '1px solid #1f1f23', margin: 'clamp(48px,8vh,72px) 0' }} />

      <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#52525b', textTransform: 'uppercase', marginBottom: 14 }}>§ drivechain archive</div>
      <h2 style={{ fontSize: 'clamp(20px,4vw,32px)', fontWeight: 400, color: '#fafafa', letterSpacing: '-0.01em', lineHeight: 1.2, margin: '0 0 8px', fontFamily: 'inherit' }}>
        Drivechain Endorsements
      </h2>
      <div style={{ fontSize: 14, color: '#71717a', marginBottom: 'clamp(20px,3vh,28px)', fontFamily: 'inherit' }}>
        Historical archive of BIP 300/301 support across the Bitcoin community, collected from 2018–2024.
      </div>

      {/* Drivechain filter bar */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 'clamp(20px,3vh,28px)' }}>
        {DC_FILTER_TYPES.map(function(t) {
          var active = dcFilter === t;
          var count = t === 'All' ? dcItems.length : dcItems.filter(function(e) { return e.type === t; }).length;
          if (count === 0 && t !== 'All') return null;
          return (
            <button key={t} onClick={function() { setDcFilter(t); }} style={{
              background: active ? accent + '18' : 'transparent',
              border: '1px solid ' + (active ? accent : '#27272a'),
              color: active ? accent : '#71717a',
              padding: '5px 10px', fontFamily: 'inherit', fontSize: 10,
              letterSpacing: '0.1em', textTransform: 'lowercase',
              cursor: 'pointer', borderRadius: 3,
              transition: 'border-color .15s, color .15s',
            }}>
              {t.toLowerCase()} ({count})
            </button>
          );
        })}
      </div>

      {/* Drivechain carousel — 2-row grid, scrolls horizontally */}
      {dcLoading ? (
        <div className="video-scroll" style={{ display: 'grid', gridTemplateRows: 'repeat(2, 260px)', gridAutoFlow: 'column', gridAutoColumns: 360, gap: 14, overflowX: 'auto', paddingBottom: 12 }}>
          {[0,1,2,3,4,5].map(function(i) { return <EndorsementSkeleton key={i} />; })}
        </div>
      ) : dcFiltered.length === 0 ? (
        <div style={{ color: '#52525b', fontSize: 13, letterSpacing: '0.06em' }}>No endorsements match this filter.</div>
      ) : (
        <div className="video-scroll" style={{ display: 'grid', gridTemplateRows: 'repeat(2, 260px)', gridAutoFlow: 'column', gridAutoColumns: 360, gap: 14, overflowX: 'auto', paddingBottom: 12 }}>
          {dcFiltered.map(function(item) {
            return <EndorsementCard key={item.id} item={item} accent={accent} />;
          })}
        </div>
      )}
    </main>
  );
}

window.EndorsementsTab = EndorsementsTab;