// ============================================================
// BLOG — latest posts from medium.com/beymann-capital
// Fetched client-side via rss2json (no CORS, no backend needed).
// ============================================================

const MEDIUM_FEED_URL = 'https://medium.com/feed/beymann-capital';
const RSS2JSON_ENDPOINT =
  'https://api.rss2json.com/v1/api.json?rss_url=' + encodeURIComponent(MEDIUM_FEED_URL);

const stripHtml = (html) => {
  const tmp = document.createElement('div');
  tmp.innerHTML = html || '';
  return (tmp.textContent || tmp.innerText || '').replace(/\s+/g, ' ').trim();
};

const Blog = () => {
  const { t } = useI18n();
  const [posts, setPosts] = React.useState(null);
  const scrollerRef = React.useRef(null);
  const [arrows, setArrows] = React.useState({ left: false, right: false });

  React.useEffect(() => {
    let cancelled = false;
    fetch(RSS2JSON_ENDPOINT)
      .then(r => r.json())
      .then(data => {
        if (cancelled) return;
        if (data.status !== 'ok' || !Array.isArray(data.items)) {
          throw new Error(data.message || 'Bad feed response');
        }
        setPosts(data.items.slice(0, 6));
      })
      .catch(err => {
        console.warn('Blog feed unavailable:', err.message);
        if (!cancelled) setPosts([]);
      });
    return () => { cancelled = true; };
  }, []);

  // Track scroll position to enable/disable the carousel arrows. The
  // carousel is manual — arrows only appear when there's something to
  // scroll to in that direction.
  React.useEffect(() => {
    const el = scrollerRef.current;
    if (!el) return;
    const update = () => {
      const overflow = el.scrollWidth > el.clientWidth + 1;
      setArrows({
        left: overflow && el.scrollLeft > 4,
        right: overflow && el.scrollLeft + el.clientWidth < el.scrollWidth - 4,
      });
    };
    update();
    el.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      el.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [posts]);

  const scrollByOne = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    const item = el.querySelector('.blog-item');
    const step = item ? item.getBoundingClientRect().width + 32 : el.clientWidth * 0.4;
    el.scrollBy({ left: dir * step, behavior: 'smooth' });
  };

  // While loading: keep the section in the DOM so layout doesn't jump.
  // If the feed loaded successfully but returned zero posts, OR if it failed,
  // hide the section entirely so we never show a broken/empty block.
  if (posts && posts.length === 0) return null;

  return (
    <section style={{
      padding: '120px 48px 60px', background: 'var(--ink-2)', position: 'relative',
    }}>
      <SectionHeader
        eye={t('blog.eyebrow')}
        title={t('blog.title')}
        sub={t('blog.sub')}
      />
      <div style={{ maxWidth: 1200, margin: '0 auto', position: 'relative' }}>
        <div
          ref={scrollerRef}
          className="blog-scroller"
          style={{
            display: 'flex', gap: 32,
            overflowX: 'auto',
            scrollSnapType: 'x proximity',
            scrollBehavior: 'smooth',
            paddingBottom: 8,
          }}
        >
          {(posts || Array.from({ length: 6 })).map((p, i) => (
            <div key={p?.guid || p?.link || i} className="blog-item">
              <BlogCard post={p} />
            </div>
          ))}
        </div>
        <CarouselArrow dir="left"  show={arrows.left}  onClick={() => scrollByOne(-1)} />
        <CarouselArrow dir="right" show={arrows.right} onClick={() => scrollByOne(1)} />
      </div>
      <div style={{ maxWidth: 1200, margin: '48px auto 0', textAlign: 'left' }}>
        <a
          href="https://www.medium.com/beymann-capital/"
          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('blog.readAll')}
          <span aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
};

const CarouselArrow = ({ dir, show, onClick }) => {
  const { t } = useI18n();
  return (
  <button
    type="button"
    onClick={onClick}
    aria-label={dir === 'left' ? t('blog.prev') : t('blog.next')}
    aria-hidden={!show}
    tabIndex={show ? 0 : -1}
    style={{
      position: 'absolute',
      [dir === 'left' ? 'left' : 'right']: -20,
      top: '50%',
      transform: 'translateY(-50%)',
      width: 48, height: 48, borderRadius: 999,
      background: 'var(--ink-3)',
      border: '1px solid var(--border-strong)',
      color: 'var(--fg)',
      cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      opacity: show ? 1 : 0,
      pointerEvents: show ? 'auto' : 'none',
      transition: 'opacity 200ms var(--ease-out), background 200ms var(--ease-out)',
      zIndex: 2,
      boxShadow: '0 6px 24px rgba(0,0,0,.4)',
    }}
    onMouseEnter={e => { e.currentTarget.style.background = 'var(--ink-4)'; }}
    onMouseLeave={e => { e.currentTarget.style.background = 'var(--ink-3)'; }}
  >
    <span className="material-symbols-rounded" style={{ fontSize: 24 }}>
      {dir === 'left' ? 'chevron_left' : 'chevron_right'}
    </span>
  </button>
  );
};

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

  if (!post) {
    return <div className="blog-card blog-card--skeleton" style={{ ...cardStyle, minHeight: 360 }} />;
  }

  const excerptFull = stripHtml(post.description);
  const excerpt = excerptFull.length > 160 ? excerptFull.slice(0, 160) + '…' : excerptFull;

  return (
    <a
      href={post.link}
      target="_blank"
      rel="noopener noreferrer"
      className="blog-card"
      style={cardStyle}
      onMouseEnter={e => {
        e.currentTarget.style.transform = 'translateY(-3px)';
        e.currentTarget.style.borderColor = 'var(--border-strong)';
      }}
      onMouseLeave={e => {
        e.currentTarget.style.transform = 'translateY(0)';
        e.currentTarget.style.borderColor = 'var(--border)';
      }}
    >
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
        <h3 style={{
          fontFamily: 'RH Phonic', fontWeight: 700,
          fontSize: 20, lineHeight: 1.25, letterSpacing: '-.005em',
          margin: 0, color: 'var(--fg)',
        }}>{post.title}</h3>
        <p style={{
          margin: 0, fontSize: 14, color: 'var(--fg-muted)',
          lineHeight: 1.55, overflow: 'hidden',
          display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
        }}>{excerpt}</p>
        <div style={{
          marginTop: 'auto', paddingTop: 8,
          fontSize: 12, color: 'var(--gold-400)', letterSpacing: '.12em',
          textTransform: 'uppercase', fontFamily: 'RH Phonic', fontWeight: 500,
        }}>{t('blog.readArticle')}</div>
      </div>
    </a>
  );
};

Object.assign(window, { Blog, BlogCard, CarouselArrow });
