// ============================================================
// THE PLAYBOOK. Reference pages from /content, presented like
// the Journal: a row of cards that scroll as a carousel.
//
// FIXED list. To add a page, drop the HTML in /content and add
// an entry here (href + title + desc + thumb).
// ============================================================

// Per-page thumbnails. Small inline SVGs of a representative pattern
// from the destination page. Colors mirror the SVG palette on those
// pages: bullish green #4BDE80; continuation muted via --fg-muted.

const ThumbThreeWhiteSoldiers = () => {
  const g = '#4BDE80';
  return (
    <svg viewBox="0 0 120 90" style={{ width: '100%', height: '100%', display: 'block' }}
         role="img" aria-label="Three White Soldiers candlestick pattern">
      <line stroke={g} strokeWidth="3" strokeLinecap="round" x1="30" y1="48" x2="30" y2="72" />
      <rect fill={g} x="23" y="52" width="14" height="18" rx="1.5" />
      <line stroke={g} strokeWidth="3" strokeLinecap="round" x1="60" y1="38" x2="60" y2="62" />
      <rect fill={g} x="53" y="42" width="14" height="18" rx="1.5" />
      <line stroke={g} strokeWidth="3" strokeLinecap="round" x1="90" y1="28" x2="90" y2="52" />
      <rect fill={g} x="83" y="32" width="14" height="18" rx="1.5" />
    </svg>
  );
};

const ThumbFlagLoose = () => {
  const c = 'var(--fg-muted)';
  const guide = 'var(--fg-dim)';
  return (
    <svg viewBox="0 0 200 100" style={{ width: '100%', height: '100%', display: 'block' }}
         role="img" aria-label="Flag (loose) chart pattern">
      <line stroke={guide} strokeWidth="1" strokeDasharray="3 3" x1="50" y1="30" x2="165" y2="40" />
      <line stroke={guide} strokeWidth="1" strokeDasharray="3 3" x1="70" y1="48" x2="165" y2="58" />
      <polyline fill="none" stroke={c} strokeWidth="2.25" strokeLinejoin="round" strokeLinecap="round"
                points="10,82 30,74 50,30 70,48 90,34 110,52 130,38 150,55 165,40 180,15 190,8" />
      <circle fill={c} cx="50" cy="30" r="2.5" />
      <circle fill={c} cx="165" cy="40" r="2.5" />
    </svg>
  );
};

const ThumbLingo = () => {
  const gold = 'var(--gold-400)';
  const muted = 'var(--fg-dim)';
  return (
    <svg viewBox="0 0 200 120" style={{ width: '100%', height: '100%', display: 'block' }}
         role="img" aria-label="Trading glossary">
      <rect fill={gold} x="20" y="20" width="78" height="9" rx="2.5" />
      <rect fill={muted} x="20" y="38" width="160" height="6" rx="3" />
      <rect fill={muted} x="20" y="50" width="120" height="6" rx="3" />
      <rect fill={gold} x="20" y="76" width="62" height="9" rx="2.5" />
      <rect fill={muted} x="20" y="94" width="160" height="6" rx="3" />
      <rect fill={muted} x="20" y="106" width="96" height="6" rx="3" />
    </svg>
  );
};

const CONTENT_ITEMS = [
  {
    href: '/content/candlesticks.html',
    title: 'Candlestick patterns',
    desc: 'A visual reference to the candlestick patterns traders watch for, what each one looks like and what it typically signals.',
    thumb: <ThumbThreeWhiteSoldiers />,
  },
  {
    href: '/content/chart-patterns.html',
    title: 'Chart patterns',
    desc: 'A visual reference to the chart patterns traders watch for, what each one looks like and what it typically signals.',
    thumb: <ThumbFlagLoose />,
  },
  {
    href: '/content/lingo.html',
    title: 'Trading lingo',
    desc: 'An essential glossary of MNQ futures and day-trading terms, from rollover and margin to order flow, VWAP, and risk.',
    thumb: <ThumbLingo />,
  },
];

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

  // 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);
    };
  }, []);

  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' });
  };

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

  return (
    <section style={{
      padding: '64px 48px 32px', background: 'transparent', position: 'relative',
    }}>
      <SectionHeader
        eye={t('content.eyebrow')}
        title={t('content.title')}
        sub={t('content.sub')}
        titleSize="clamp(28px,3.2vw,44px)"
      />
      <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',
            // paddingTop + matching negative marginTop reserves room for the
            // hover translateY(-3px) without shifting cards down (overflow-x:auto
            // computes overflow-y to auto, which would otherwise clip the top).
            paddingTop: 8, marginTop: -8, paddingBottom: 8,
          }}
        >
          {CONTENT_ITEMS.map((item, i) => (
            <div key={item.href || i} className="blog-item">
              <ContentCard item={item} />
            </div>
          ))}
        </div>
        <CarouselArrow dir="left"  show={arrows.left}  onClick={() => scrollByOne(-1)} />
        <CarouselArrow dir="right" show={arrows.right} onClick={() => scrollByOne(1)} />
      </div>
    </section>
  );
};

const ContentCard = ({ item }) => {
  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)',
  };

  return (
    <a
      href={item.href}
      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)';
      }}
    >
      {item.thumb && (
        <div style={{
          background: 'var(--ink-2)',
          borderBottom: '1px solid var(--border)',
          padding: 24,
          height: 160,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          {item.thumb}
        </div>
      )}
      <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)',
        }}>{item.title}</h3>
        <p style={{
          margin: 0, fontSize: 14, color: 'var(--fg-muted)',
          lineHeight: 1.55, overflow: 'hidden',
          display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
        }}>{item.desc}</p>
        <div style={{
          marginTop: 'auto', paddingTop: 8,
          fontSize: 12, color: 'var(--gold-400)', letterSpacing: '.12em',
          textTransform: 'uppercase', fontFamily: 'RH Phonic', fontWeight: 500,
        }}>{t('content.cta')}</div>
      </div>
    </a>
  );
};

Object.assign(window, { Content, ContentCard });
