// ============================================================
// X FEED — featured posts from x.com/beymanncapital
// Rendered as custom cards (NOT X's iframe embed) so they can match
// the "From our desk." article boxes exactly (var(--ink-3)). X's own
// embed paints its card inside a cross-origin iframe we can't restyle,
// so we fetch the tweet data ourselves and draw the card.
//
// Data comes from FixTweet (api.fxtwitter.com): free, no API key, and
// CORS-open (Access-Control-Allow-Origin: *), unlike X's own endpoint.
// Images/video stream from X's CDN (pbs/video.twimg.com) directly.
//
// These are FIXED tweets, not auto-latest: to refresh, edit TWEET_URLS
// (paste each post's "Copy link" URL).
// ============================================================

const TWEET_URLS = [
  'https://x.com/Beymanncapital/status/2057917737805156543',
  'https://x.com/Beymanncapital/status/2057595680886321407',
  'https://x.com/Beymanncapital/status/1953835727118111219',
  'https://x.com/samhickmann/status/2043839872906199265',
  
];

const X_HANDLE = 'beymanncapital';
const X_PROFILE_URL = 'https://x.com/' + X_HANDLE;
const FX_API = 'https://api.fxtwitter.com/status/';
const X_LOGO_PATH =
  'M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z';

const tweetIdFromUrl = (url) => (String(url).match(/status\/(\d+)/) || [])[1];

const fmtTweetDate = (ts, lang) => {
  if (!ts) return '';
  try {
    return new Date(ts * 1000).toLocaleDateString(lang || 'en', {
      month: 'short', day: 'numeric', year: 'numeric',
    });
  } catch (e) { return ''; }
};

const XFeed = () => {
  const { t, lang } = useI18n();
  // null = loading; otherwise an array aligned to TWEET_URLS where each
  // entry is the tweet object or null (that one failed to load).
  const [tweets, setTweets] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    Promise.all(TWEET_URLS.map((url) => {
      const id = tweetIdFromUrl(url);
      if (!id) return Promise.resolve(null);
      return fetch(FX_API + id)
        .then((r) => r.json())
        .then((d) => (d && d.tweet ? d.tweet : null))
        .catch(() => null);
    })).then((results) => {
      if (!cancelled) setTweets(results);
    });
    return () => { cancelled = true; };
  }, []);

  const loaded = tweets !== null;
  const noneLoaded = loaded && !tweets.some(Boolean);

  return (
    <section className="x-section" style={{ background: 'var(--ink-1)', position: 'relative' }}>
      <SectionHeader eye={t('x.eyebrow')} title={t('x.title')} sub={t('x.sub')} />
      <div style={{ maxWidth: 1280, margin: '0 auto', minHeight: loaded ? undefined : 360 }}>
        {noneLoaded ? (
          <XFallback t={t} />
        ) : (
          <div className="x-grid">
            {(tweets || TWEET_URLS).map((tw, i) => (
              <div key={i}>
                <XTweetCard tweet={loaded ? tw : null} loading={!loaded} t={t} lang={lang} />
              </div>
            ))}
          </div>
        )}
      </div>
      <div style={{ maxWidth: 1200, margin: '48px auto 0', textAlign: 'left' }}>
        <a
          href={X_PROFILE_URL}
          target="_blank"
          rel="noopener noreferrer"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            color: 'var(--gold-400)', textDecoration: 'none',
            fontFamily: 'RH Phonic', fontSize: 13, fontWeight: 500,
            letterSpacing: '.16em', textTransform: 'uppercase',
            transition: 'gap 200ms var(--ease-out)',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.gap = '14px'; }}
          onMouseLeave={(e) => { e.currentTarget.style.gap = '10px'; }}
        >
          {t('x.follow')}
          <span aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
};

const X_CARD_STYLE = {
  width: '100%', background: 'var(--ink-3)', border: '1px solid var(--border)',
  borderRadius: 12, overflow: 'hidden', display: 'flex', flexDirection: 'column',
  color: 'inherit', textDecoration: 'none',
  transition: 'transform 200ms var(--ease-out), border-color 200ms var(--ease-out)',
};

const XTweetCard = ({ tweet, loading, t, lang }) => {
  if (loading) {
    return <div className="x-card--skeleton" style={{ ...X_CARD_STYLE, minHeight: 360 }} />;
  }
  // Loaded but this one failed — keep the row full with a tap-through card.
  if (!tweet) {
    return (
      <a
        href={X_PROFILE_URL} target="_blank" rel="noopener noreferrer"
        style={{ ...X_CARD_STYLE, minHeight: 360, alignItems: 'center', justifyContent: 'center', gap: 14, padding: 24 }}
      >
        <svg viewBox="0 0 24 24" width="26" height="26" fill="var(--gold-400)" aria-hidden="true"><path d={X_LOGO_PATH} /></svg>
        <span style={{ color: 'var(--gold-400)', fontFamily: 'RH Phonic', fontSize: 12, letterSpacing: '.14em', textTransform: 'uppercase' }}>
          {t('x.readPost')} →
        </span>
      </a>
    );
  }

  const all = (tweet.media && tweet.media.all) || [];
  const video = all.find((m) => m.type === 'video' || m.type === 'gif');
  const photo = all.find((m) => m.type === 'photo');
  const thumbUrl = photo ? photo.url : (video ? video.thumbnail_url : null);

  const hover = (on) => (e) => {
    e.currentTarget.style.transform = on ? 'translateY(-3px)' : 'translateY(0)';
    e.currentTarget.style.borderColor = on ? 'var(--border-strong)' : 'var(--border)';
  };

  return (
    <div style={X_CARD_STYLE} onMouseEnter={hover(true)} onMouseLeave={hover(false)}>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', flex: 1 }}>
          <p style={{
            flex: 1, minWidth: 0, margin: 0, fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.5,
            whiteSpace: 'pre-wrap', overflow: 'hidden',
            display: '-webkit-box', WebkitLineClamp: 6, WebkitBoxOrient: 'vertical',
          }}>{tweet.text}</p>
          {thumbUrl && (
            <a
              href={tweet.url || X_PROFILE_URL} target="_blank" rel="noopener noreferrer"
              aria-label="View media on X"
              style={{ position: 'relative', flexShrink: 0, display: 'block', width: 88, height: 88 }}
            >
              <img src={thumbUrl} alt="" loading="lazy"
                style={{ width: 88, height: 88, objectFit: 'cover', borderRadius: 8, display: 'block' }} />
              {video && !photo && (
                <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ width: 28, height: 28, borderRadius: 999, background: 'rgba(0,0,0,.55)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="#fff" aria-hidden="true"><path d="M8 5v14l11-7z" /></svg>
                  </span>
                </span>
              )}
            </a>
          )}
        </div>
      </div>

      <a
        href={tweet.url || X_PROFILE_URL} target="_blank" rel="noopener noreferrer"
        style={{
          marginTop: 'auto', padding: '12px 16px', borderTop: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          textDecoration: 'none',
        }}
      >
        <span style={{ fontSize: 12, color: 'var(--fg-dim)' }}>{fmtTweetDate(tweet.created_timestamp, lang)}</span>
        <span style={{ fontSize: 12, color: 'var(--gold-400)', fontFamily: 'RH Phonic', fontWeight: 500, letterSpacing: '.12em', textTransform: 'uppercase' }}>
          {t('x.readPost')} →
        </span>
      </a>
    </div>
  );
};

// Shown only if none of the tweets load (FixTweet down / all unavailable).
const XFallback = ({ t }) => (
  <a
    href={X_PROFILE_URL}
    target="_blank"
    rel="noopener noreferrer"
    style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
      textAlign: 'center', textDecoration: 'none', color: 'var(--fg)',
      background: 'var(--ink-3)', border: '1px solid var(--border)',
      borderRadius: 12, padding: '48px 32px', maxWidth: 600, margin: '0 auto',
      transition: 'border-color 200ms var(--ease-out), transform 200ms var(--ease-out)',
    }}
    onMouseEnter={e => {
      e.currentTarget.style.borderColor = 'var(--border-strong)';
      e.currentTarget.style.transform = 'translateY(-3px)';
    }}
    onMouseLeave={e => {
      e.currentTarget.style.borderColor = 'var(--border)';
      e.currentTarget.style.transform = 'translateY(0)';
    }}
  >
    <svg viewBox="0 0 24 24" width="28" height="28" fill="var(--gold-400)" aria-hidden="true">
      <path d={X_LOGO_PATH} />
    </svg>
    <span style={{
      fontFamily: 'Martina Plantijn', fontStyle: 'italic',
      fontSize: 19, color: 'var(--fg-muted)', lineHeight: 1.5,
    }}>{t('x.fallback')}</span>
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      color: 'var(--gold-400)', fontFamily: 'RH Phonic', fontSize: 13, fontWeight: 500,
      letterSpacing: '.16em', textTransform: 'uppercase',
    }}>
      @{X_HANDLE}
      <span aria-hidden="true">→</span>
    </span>
  </a>
);

Object.assign(window, { XFeed, XTweetCard, XFallback });
