// Masonry-style card grid for case studies — now with real video thumbnails + lightbox player
function CasesGrid({ cases }) {
  const [active, setActive] = React.useState(null); // {yt, title, vimeoThumb}

  // ESC to close + body scroll lock
  React.useEffect(() => {
    if (!active) return;
    const onKey = (e) => { if (e.key === 'Escape') setActive(null); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [active]);

  return (
    <section data-mf="section" style={{
      background: '#0A0608',
      padding: '64px 44px',
    }}>
      <div data-mf="cases-grid-main" style={{
        maxWidth: 1280, margin: '0 auto',
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 18,
      }}>
        {cases.map((c, i) => (
          <CaseCard key={c.idx} c={c} i={i} onOpen={() => setActive(c)} />
        ))}
      </div>

      {active && <VideoLightbox c={active} onClose={() => setActive(null)}/>}
    </section>
  );
}
window.CasesGrid = CasesGrid;

function VideoLightbox({ c, onClose }) {
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.92)',
      backdropFilter: 'blur(12px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 200, padding: 24,
    }}>
      <button onClick={onClose} style={{
        position: 'absolute', top: 22, right: 24,
        width: 44, height: 44, borderRadius: '50%',
        background: 'rgba(255,255,255,0.08)',
        border: '1px solid rgba(255,255,255,0.18)',
        color: '#fff', fontSize: 22, cursor: 'pointer', lineHeight: 1,
      }}>×</button>

      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(1100px, 100%)',
        display: 'flex', flexDirection: 'column', gap: 16,
      }}>
        <div style={{
          aspectRatio: '16/9',
          borderRadius: 20, overflow: 'hidden',
          boxShadow: '0 40px 120px rgba(0,0,0,0.8), 0 0 80px rgba(232,18,60,0.2)',
          border: '1px solid rgba(255,255,255,0.12)',
          background: '#000',
        }}>
          {c.yt ? (
            <iframe
              src={`https://www.youtube-nocookie.com/embed/${c.yt}?autoplay=1&rel=0&modestbranding=1&playsinline=1`}
              title={c.title}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
              referrerPolicy="strict-origin-when-cross-origin"
              style={{ width: '100%', height: '100%', border: 0 }}
            />
          ) : c.vimeoThumb ? (
            // No vimeo embed URL available — show the thumbnail with a hint to watch on source
            <div style={{
              position: 'relative', width: '100%', height: '100%',
              background: `url(${c.vimeoThumb}) center/cover no-repeat`,
              display: 'flex', alignItems: 'flex-end', justifyContent: 'center', padding: 40,
            }}>
              <div style={{
                background: 'rgba(0,0,0,0.72)', color: '#fff',
                padding: '14px 22px', borderRadius: 14,
                fontSize: 14, textAlign: 'center', maxWidth: 560,
              }}>
                Video available on source site — embed not publicly shareable.
              </div>
            </div>
          ) : null}
        </div>
        <div style={{
          color: '#fff', fontFamily: 'Poppins', fontWeight: 700,
          fontSize: 18, textAlign: 'center', letterSpacing: '-0.01em',
        }}>{c.title}</div>
      </div>
    </div>
  );
}

function CaseCard({ c, i, onOpen }) {
  const variant = c.isBig ? 'big' : c.isMRR ? 'mrr' : (i % 7 === 3) ? 'dark' : 'default';
  const styles = {
    big:    { bg: '#E8123C', border: 'transparent', accentColor: '#FFE5EB', titleColor: '#fff', subColor: 'rgba(255,255,255,0.88)' },
    mrr:    { bg: '#1C0810', border: 'rgba(232,18,60,0.35)', accentColor: '#FFD166', titleColor: '#fff', subColor: 'rgba(255,255,255,0.65)' },
    dark:   { bg: '#000', border: 'rgba(255,255,255,0.08)', accentColor: '#E8123C', titleColor: '#fff', subColor: 'rgba(255,255,255,0.6)' },
    default:{ bg: '#120609', border: 'rgba(255,255,255,0.08)', accentColor: '#E8123C', titleColor: '#fff', subColor: 'rgba(255,255,255,0.65)' },
  }[variant];

  // Clean subline
  let actionClean = c.action || '';
  if (c.amount) {
    const esc = c.amount.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    actionClean = actionClean.replace(new RegExp('\\s*\\$?' + esc.replace(/^\$/, '') + '\\b', 'gi'), '');
    const moMatch = c.amount.match(/^\$?([\d,.]+[KMkm]?)(?:\/Mo|\/Month)?$/i);
    if (moMatch) {
      const num = moMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      actionClean = actionClean.replace(new RegExp('\\s*\\$' + num + '\\/(Mo|Month)\\b', 'gi'), '');
    }
  }
  if (c.timeframe) {
    const esc = c.timeframe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    actionClean = actionClean.replace(new RegExp('\\s*(in\\s+)?' + esc + '\\b', 'gi'), '');
  }
  actionClean = actionClean
    .replace(/&\s*Hit\s*$/i, '')
    .replace(/\s+(to|in|from|by|for|of|and|&|->|→)\s*$/i, '')
    .replace(/\s*-\>\s*$/g, '')
    .replace(/\s+/g, ' ')
    .replace(/^\s*(to|from|in|and|&|->)\s+/i, '')
    .trim();
  if (actionClean.length < 4 || /^(closed|added|scaled|went)$/i.test(actionClean)) actionClean = '';

  const hasVideo = !!(c.yt || c.vimeoThumb);
  // Start with hqdefault — always exists. maxresdefault returns a gray 120x90
  // placeholder as a 200 for videos lacking a maxres frame (so onError won't fire).
  const thumb = c.yt
    ? `https://img.youtube.com/vi/${c.yt}/hqdefault.jpg`
    : c.vimeoThumb || null;

  return (
    <article onClick={hasVideo ? onOpen : undefined} style={{
      position: 'relative',
      background: styles.bg,
      border: `1px solid ${styles.border}`,
      borderRadius: 22,
      overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      transition: 'transform 200ms ease, border-color 200ms ease',
      cursor: hasVideo ? 'pointer' : 'default',
    }}
    onMouseEnter={e => {
      e.currentTarget.style.transform = 'translateY(-3px)';
      if (variant !== 'big') e.currentTarget.style.borderColor = 'rgba(232,18,60,0.5)';
      const pb = e.currentTarget.querySelector('[data-play-btn]');
      if (pb) pb.style.transform = 'translate(-50%, -50%) scale(1.08)';
    }}
    onMouseLeave={e => {
      e.currentTarget.style.transform = 'translateY(0)';
      e.currentTarget.style.borderColor = styles.border;
      const pb = e.currentTarget.querySelector('[data-play-btn]');
      if (pb) pb.style.transform = 'translate(-50%, -50%) scale(1)';
    }}
    >
      {/* Thumbnail header */}
      {hasVideo && (
        <div style={{
          position: 'relative',
          aspectRatio: '16/10',
          background: '#000',
          overflow: 'hidden',
          borderBottom: `1px solid ${variant === 'big' ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.06)'}`,
        }}>
          <img
            src={thumb}
            alt={c.title || c.name}
            width={480} height={360}
            loading="lazy" decoding="async"
            style={{
              width: '100%', height: '100%', objectFit: 'cover', display: 'block',
              // hqdefault is 480x360 with letterbox bars at top/bottom (~45px each).
              // Scale up + slight vertical offset hides them while keeping face centered.
              transform: c.yt ? 'scale(1.35)' : 'none',
              transformOrigin: 'center center',
            }}
            onError={(e) => {
              if (c.yt && !e.currentTarget.dataset.fallback) {
                e.currentTarget.dataset.fallback = '1';
                e.currentTarget.src = `https://img.youtube.com/vi/${c.yt}/mqdefault.jpg`;
              }
            }}
          />
          {/* Dark gradient for legibility of floating chips */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(0,0,0,0.25) 0%, rgba(0,0,0,0.05) 40%, rgba(0,0,0,0.55) 100%)',
            pointerEvents: 'none',
          }}/>
          {/* Play button */}
          <div data-play-btn style={{
            position: 'absolute', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 56, height: 56, borderRadius: '50%',
            background: 'rgba(232,18,60,0.96)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 10px 30px rgba(0,0,0,0.55), 0 0 0 6px rgba(255,255,255,0.08)',
            transition: 'transform 220ms ease',
          }}>
            <div style={{
              width: 0, height: 0,
              borderLeft: '16px solid #fff',
              borderTop: '11px solid transparent',
              borderBottom: '11px solid transparent',
              marginLeft: 4,
            }}/>
          </div>
          {/* Top-right meta badge */}
          <div style={{
            position: 'absolute', top: 12, right: 12,
            padding: '5px 10px', borderRadius: 8,
            background: 'rgba(0,0,0,0.62)',
            backdropFilter: 'blur(6px)',
            border: '1px solid rgba(255,255,255,0.14)',
            fontFamily: 'Poppins', fontWeight: 800,
            fontSize: 10, letterSpacing: '0.14em', color: '#fff',
            textTransform: 'uppercase',
          }}>
            {variant === 'big' ? '$100K+' :
             variant === 'mrr' ? 'Recurring' :
             c.isFast ? 'Fast Win' :
             'Case Study'}
          </div>
        </div>
      )}

      {/* Body */}
      <div style={{
        padding: hasVideo ? '20px 22px 22px' : 28,
        display: 'flex', flexDirection: 'column',
        flex: 1,
      }}>
        <div style={{ position: 'relative', flex: 1 }}>
          {/* No thumbnail? Show the category label at top */}
          {!hasVideo && (
            <div style={{
              display: 'inline-block',
              fontSize: 10, letterSpacing: '0.18em', fontWeight: 700,
              color: variant === 'big' ? 'rgba(255,255,255,0.9)' : styles.accentColor,
              textTransform: 'uppercase', marginBottom: 14,
            }}>
              {variant === 'big' ? '$100K+ Case' :
               variant === 'mrr' ? 'Recurring Revenue' :
               c.isFast ? 'Fast Win' :
               'Case Study'}
            </div>
          )}

          {c.amount ? (
            <div style={{
              fontFamily: 'Poppins', fontWeight: 800,
              fontSize: variant === 'big' ? 52 : 40,
              lineHeight: 0.95, letterSpacing: '-0.025em',
              color: styles.titleColor, marginBottom: 10,
              wordBreak: 'break-word',
            }}>
              {c.amount}
            </div>
          ) : (
            <div style={{
              fontFamily: 'Poppins', fontWeight: 800,
              fontSize: 30, lineHeight: 1,
              color: styles.titleColor, marginBottom: 10,
            }}>
              {c.name}
            </div>
          )}

          <div style={{
            fontSize: 14, lineHeight: 1.45,
            color: styles.subColor, fontWeight: 500,
          }}>
            {c.amount
              ? (actionClean ? `${c.name} — ${actionClean}` : c.name)
              : (actionClean || c.name)}
          </div>
        </div>

        {/* Bottom meta */}
        <div style={{
          marginTop: 18, paddingTop: 14,
          borderTop: `1px solid ${variant === 'big' ? 'rgba(255,255,255,0.22)' : 'rgba(255,255,255,0.08)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            fontSize: 12, fontWeight: 600,
            color: variant === 'big' ? 'rgba(255,255,255,0.9)' : 'rgba(255,255,255,0.7)',
          }}>
            <div style={{
              width: 26, height: 26, borderRadius: '50%',
              background: variant === 'big' ? 'rgba(0,0,0,0.22)' : 'linear-gradient(135deg, #E8123C 0%, #5A0A24 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 10, fontWeight: 800, color: '#fff',
            }}>{(c.name || '?').split(/[\s&]+/).map(s => s[0]).join('').slice(0, 2).toUpperCase()}</div>
            {c.timeframe && (
              <span style={{ fontSize: 11, letterSpacing: '0.04em' }}>in {c.timeframe}</span>
            )}
          </div>
          <span style={{
            fontSize: 12, fontWeight: 700, letterSpacing: '0.06em',
            color: variant === 'big' ? 'rgba(255,255,255,0.95)' : 'rgba(232,18,60,0.85)',
            textTransform: 'uppercase',
          }}>{hasVideo ? 'Watch →' : '→'}</span>
        </div>
      </div>
    </article>
  );
}
window.CaseCard = CaseCard;
