// ui_kits/website/Videos.jsx
//
// Bilingual video data + components used on the homepage and on each
// section page. Videos point at YouTube — we use the lightweight thumbnail
// URL pattern (img.youtube.com/vi/<id>/...) so we don't pull the player
// until the user clicks Play. Click → lightbox overlay with the embed.
//
// Channel: https://www.youtube.com/@top_naturaltips
//
// When you're ready to pull live from YouTube, swap SAMPLE_VIDEOS for a
// fetch against the YouTube Data API (or a Ghost custom field that stores
// the videoId per article).

// Each video carries an optional `id` (the YouTube `?v=...` value).
// While `id` is null, the card renders a branded placeholder thumbnail and
// clicks open the channel. Drop in real IDs to switch over.
const SAMPLE_VIDEOS = [
  {
    id: null, category: 'Health', duration: '4:12',
    date: { es: '14 mayo, 2026', en: 'May 14, 2026' },
    title: { es: 'El protocolo del hielo en la nuca — paso a paso',
             en: 'The Ice-on-the-Nape Protocol, Step by Step' },
    desc:  { es: 'Dos minutos, un punto específico, y por qué el nervio vago lo cambia todo.',
             en: 'Two minutes, one specific point, and why the vagus nerve changes everything.' },
  },
  {
    id: null, category: 'Nutrition', duration: '6:45',
    date: { es: '11 mayo, 2026', en: 'May 11, 2026' },
    title: { es: 'Cómo preparar té de cúrcuma con biodisponibilidad real',
             en: 'How to Brew Turmeric Tea with Real Bioavailability' },
    desc:  { es: 'La regla de pimienta + grasa, y por qué casi todas las recetas la rompen.',
             en: 'The pepper + fat rule, and why most recipes break it.' },
  },
  {
    id: null, category: 'Beauty', duration: '3:28',
    date: { es: '7 mayo, 2026', en: 'May 7, 2026' },
    title: { es: 'Mascarilla de miel: cinco ingredientes, diez minutos',
             en: 'Honey Mask: Five Ingredients, Ten Minutes' },
    desc:  { es: 'Filmado en tiempo real para que veas exactamente qué cantidades.',
             en: 'Filmed in real time so you can see exactly the proportions.' },
  },
  {
    id: null, category: 'Exercise', duration: '5:02',
    date: { es: '3 mayo, 2026', en: 'May 3, 2026' },
    title: { es: 'Caminar hacia atrás: la forma correcta',
             en: 'Walking Backwards: The Correct Form' },
    desc:  { es: 'Dónde poner la mirada, cómo balancear los brazos, por qué cinco minutos basta.',
             en: 'Where to look, how to swing the arms, why five minutes is enough.' },
  },
  {
    id: null, category: 'Health', duration: '12:18',
    date: { es: '28 abril, 2026', en: 'Apr 28, 2026' },
    title: { es: 'Conversación con la Dra. Reyes sobre el sueño profundo',
             en: 'A Conversation with Dr. Reyes on Deep Sleep' },
    desc:  { es: 'Lo que la fisiología nos enseña sobre las horas antes de medianoche.',
             en: 'What physiology teaches us about the hours before midnight.' },
  },
  {
    id: null, category: 'Nutrition', duration: '7:33',
    date: { es: '24 abril, 2026', en: 'Apr 24, 2026' },
    title: { es: 'Manzana + chocolate oscuro: el experimento de una semana',
             en: 'Apple + Dark Chocolate: A One-Week Experiment' },
    desc:  { es: 'Probé el protocolo durante siete días. Los resultados — y lo que no esperaba.',
             en: 'I ran the protocol for seven days. The results — and what I didn\'t expect.' },
  },
];

const CHANNEL_URL = 'https://www.youtube.com/@top_naturaltips';

const ytThumb   = (id) => id ? `https://i.ytimg.com/vi/${id}/hqdefault.jpg` : null;
const ytWatch   = (id) => id ? `https://www.youtube.com/watch?v=${id}` : CHANNEL_URL;
const ytEmbed   = (id) => `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&modestbranding=1`;

// Parse a duration string like "4:12" or "1:02:30" into seconds.
function durationToSeconds(d) {
  if (!d) return 0;
  const parts = String(d).split(':').map(n => parseInt(n, 10) || 0);
  if (parts.length === 2) return parts[0] * 60 + parts[1];
  if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  return 0;
}

// YouTube classifies videos ≤ 60s as Shorts.
function isShortVideo(v) {
  return v && v.id && durationToSeconds(v.duration) > 0 && durationToSeconds(v.duration) <= 60;
}

// Branded placeholder thumbnail: tinted gradient keyed off the video's
// category, with a YouTube glyph + tiny channel handle in the corner.
const CAT_TINT = {
  Health:    { from: '#1F4F40', to: '#3D7A66' },
  Nutrition: { from: '#7A4A18', to: '#C99B5E' },
  Beauty:    { from: '#5C3A56', to: '#B19CD9' },
  Exercise:  { from: '#A24B2C', to: '#E89373' },
};

function PlaceholderThumb({ category, small }) {
  const tint = CAT_TINT[category] || CAT_TINT.Health;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: `linear-gradient(135deg, ${tint.from} 0%, ${tint.to} 100%)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      overflow: 'hidden',
    }}>
      {/* soft radial accent */}
      <div style={{
        position: 'absolute', width: '160%', height: '160%',
        top: '-30%', left: '-30%',
        background: 'radial-gradient(circle at 30% 30%, rgba(255,255,255,0.18), transparent 55%)',
      }}/>
      {/* YouTube glyph watermark */}
      <svg width={small ? 40 : 64} height={small ? 28 : 46} viewBox="0 0 24 17" fill="rgba(255,255,255,0.20)" aria-hidden="true" style={{ position: 'absolute', top: small ? 8 : 14, left: small ? 8 : 14 }}>
        <path d="M22.54 2.92a2.78 2.78 0 0 0-1.95-2C18.88.5 12 .5 12 .5s-6.88 0-8.59.42a2.78 2.78 0 0 0-1.95 2A29 29 0 0 0 1 8.5a29 29 0 0 0 .46 5.58 2.78 2.78 0 0 0 1.95 2C5.12 16.5 12 16.5 12 16.5s6.88 0 8.59-.42a2.78 2.78 0 0 0 1.95-2A29 29 0 0 0 23 8.5a29 29 0 0 0-.46-5.58zM9.75 12V5l6 3.5z"/>
      </svg>
    </div>
  );
}

// ---------- Lightbox overlay ----------------------------------------------

function VideoLightbox({ video, onClose }) {
  const tr = useT();
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', h);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  if (!video) return null;

  return (
    <div
      role="dialog" aria-modal="true"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(15,15,15,0.86)',
        backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '32px',
      }}>
      <div onClick={(e) => e.stopPropagation()}
           style={{ position: 'relative', width: '100%', maxWidth: 1080 }}>
        <button onClick={onClose} aria-label="Close"
          style={{
            position: 'absolute', top: -44, right: 0,
            background: 'transparent', border: 'none', color: '#fff',
            fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
          }}>
          <span style={{ fontSize: 22, lineHeight: 1 }}>×</span> Close
        </button>
        <div style={{
          position: 'relative',
          width: isShortVideo(video) ? 'min(420px, 100%)' : '100%',
          margin: isShortVideo(video) ? '0 auto' : 0,
          aspectRatio: isShortVideo(video) ? '9 / 16' : '16 / 9',
          borderRadius: 12, overflow: 'hidden',
          boxShadow: '0 30px 80px rgba(0,0,0,0.5)',
          background: '#000',
        }}>
          <iframe
            src={ytEmbed(video.id)}
            title={video.title.es || video.title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }}
          />
        </div>
        <div style={{
          marginTop: 16, color: 'rgba(255,255,255,0.85)',
          fontFamily: 'var(--font-sans)', fontSize: 14,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
        }}>
          <span style={{ fontFamily: 'var(--font-serif)', fontSize: 18, fontStyle: 'italic', color: '#fff' }}>
            {pickLang(video.title)}
          </span>
          <a href={ytWatch(video.id)} target="_blank" rel="noopener"
             style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'none' }}>
            {tr('videos.watchOn')} →
          </a>
        </div>
      </div>
    </div>
  );
}

// Helper available to non-React callers (pickLang is also in BlogGrid).
function pickLang(value, lang) {
  if (!value) return '';
  if (typeof value === 'object' && (value.es !== undefined || value.en !== undefined)) {
    const L = lang || (typeof document !== 'undefined' ? document.documentElement.getAttribute('lang') : null) || I18N_DEFAULT_LANG;
    return value[L] ?? value[I18N_DEFAULT_LANG] ?? '';
  }
  return value;
}

// ---------- Cards & thumbnails --------------------------------------------

const videoStyles = {
  card: {
    cursor: 'pointer',
    display: 'flex', flexDirection: 'column',
  },
  thumb: {
    position: 'relative', aspectRatio: '16 / 9',
    overflow: 'hidden', borderRadius: 12,
    background: '#1F4F40',
    transition: 'transform 240ms var(--ease-out)',
  },
  thumbImg: { width: '100%', height: '100%', objectFit: 'cover' },
  playButton: {
    position: 'absolute', inset: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    pointerEvents: 'none',
  },
  playCircle: {
    width: 64, height: 64, borderRadius: '50%',
    background: 'rgba(255,255,255,0.92)',
    color: 'var(--brand-leaf-deep)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: '0 10px 28px rgba(0,0,0,0.35)',
    transition: 'transform 220ms var(--ease-out)',
  },
  duration: {
    position: 'absolute', bottom: 10, right: 10,
    padding: '3px 8px', borderRadius: 6,
    background: 'rgba(15,15,15,0.78)', color: '#fff',
    fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
    letterSpacing: '0.02em',
  },
  meta: {
    fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: '#767574', marginTop: 14,
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 18, lineHeight: 1.3,
    color: '#383838', margin: '6px 0 0',
  },
  desc: {
    fontFamily: 'var(--font-sans)', fontSize: 13.5, lineHeight: 1.55,
    color: '#525150', margin: '8px 0 0',
  },
};

function VideoThumb({ video, onPlay, hover }) {
  return (
    <div style={{
      ...videoStyles.thumb,
      transform: hover ? 'scale(1.01)' : 'none',
    }} onClick={() => onPlay && onPlay(video)}>
      {video.id ? (
        <img src={ytThumb(video.id)} alt="" style={videoStyles.thumbImg}
             onError={(e) => { e.currentTarget.style.opacity = 0; }}/>
      ) : (
        <PlaceholderThumb category={video.category}/>
      )}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(15,15,15,0) 50%, rgba(15,15,15,0.55) 100%)',
      }}/>
      <div style={videoStyles.playButton}>
        <div style={{
          ...videoStyles.playCircle,
          transform: hover ? 'scale(1.08)' : 'scale(1)',
        }}>
          <PlayIcon size={28}/>
        </div>
      </div>
      <div style={videoStyles.duration}>{video.duration}</div>
    </div>
  );
}

function VideoCard({ video, onPlay, size = 'md' }) {
  const lang = React.useContext(LangContext);
  const tr = useT();
  const [hover, setHover] = React.useState(false);

  const isSm = size === 'sm';

  return (
    <article
      style={videoStyles.card}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={() => onPlay && onPlay(video)}
    >
      <VideoThumb video={video} onPlay={onPlay} hover={hover}/>
      <div style={{ ...videoStyles.meta, marginTop: isSm ? 10 : 14 }}>
        {tr('cat.' + video.category)} · {pickLang(video.date, lang)}
      </div>
      <h4 style={{ ...videoStyles.title, fontSize: isSm ? 16 : 18 }}>
        {pickLang(video.title, lang)}
      </h4>
      {!isSm && video.desc && (
        <p style={videoStyles.desc}>{pickLang(video.desc, lang)}</p>
      )}
    </article>
  );
}

// ---------- Homepage video block (split: featured + recent list) -----------

const blockStyles = {
  section: { background: '#fff', padding: '88px 0 96px' },
  inner: { maxWidth: 1200, margin: '0 auto', padding: '0 32px' },
  head: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 36, gap: 24 },
  grid: { display: 'grid', gridTemplateColumns: '7fr 5fr', gap: 48, alignItems: 'flex-start' },
  featuredBody: { padding: '0 4px' },
  featuredTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 28, lineHeight: 1.2,
    color: 'var(--color-fg-strong)', margin: '20px 0 10px',
    textWrap: 'balance',
  },
  featuredDesc: {
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.6,
    color: 'var(--color-fg)', margin: '0 0 18px',
    textWrap: 'pretty',
  },
  featuredMeta: {
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
  sideHead: {
    fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700,
    letterSpacing: '0.18em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)', margin: '0 0 18px',
    paddingBottom: 12, borderBottom: '1px solid var(--color-divider)',
  },
  sideList: { display: 'flex', flexDirection: 'column', gap: 20 },
  sideItem: { display: 'grid', gridTemplateColumns: '160px 1fr', gap: 16, alignItems: 'flex-start', cursor: 'pointer' },
  sideThumb: { position: 'relative', aspectRatio: '16 / 9', borderRadius: 8, overflow: 'hidden', background: '#1F4F40' },
  sideTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 15, lineHeight: 1.3,
    color: 'var(--color-fg-strong)', margin: '4px 0 0',
  },
  sideMeta: {
    fontFamily: 'var(--font-sans)', fontSize: 10.5, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
};

// ---------- Shorts row (portrait 9:16 thumbnails) ------------------------

const shortsStyles = {
  wrap: {
    marginTop: 56,
    paddingTop: 36,
    borderTop: '1px solid var(--color-divider)',
  },
  head: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
    marginBottom: 22, gap: 16,
  },
  headLeft: { display: 'flex', alignItems: 'center', gap: 14 },
  badge: {
    display: 'inline-block',
    padding: '4px 10px', borderRadius: 4,
    background: '#FF0033', color: '#fff',
    fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 10,
    letterSpacing: '0.18em',
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 22, color: 'var(--color-fg-strong)',
    margin: 0,
  },
  allLink: {
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)', textDecoration: 'none',
  },
  row: {
    display: 'grid',
    gridTemplateColumns: 'repeat(6, 1fr)',
    gap: 16,
    alignItems: 'flex-start',
  },
  card: {
    cursor: 'pointer',
    display: 'flex', flexDirection: 'column',
  },
  thumb: {
    position: 'relative', aspectRatio: '9 / 16',
    overflow: 'hidden', borderRadius: 10,
    background: '#1F4F40',
    transition: 'transform 240ms var(--ease-out)',
  },
  thumbImg: { width: '100%', height: '100%', objectFit: 'cover' },
  duration: {
    position: 'absolute', bottom: 8, right: 8,
    padding: '2px 6px', borderRadius: 4,
    background: 'rgba(15,15,15,0.78)', color: '#fff',
    fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 600,
  },
  playOverlay: {
    position: 'absolute', inset: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    pointerEvents: 'none',
  },
  playCircle: {
    width: 44, height: 44, borderRadius: '50%',
    background: 'rgba(255,255,255,0.92)', color: 'var(--brand-leaf-deep)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: '0 8px 20px rgba(0,0,0,0.35)',
    transition: 'transform 220ms var(--ease-out)',
  },
  cardTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 13.5, lineHeight: 1.35,
    color: 'var(--color-fg-strong)',
    margin: '10px 0 0',
    display: '-webkit-box',
    WebkitLineClamp: 2,
    WebkitBoxOrient: 'vertical',
    overflow: 'hidden',
  },
};

function ShortsCard({ video, onPlay }) {
  const lang = React.useContext(LangContext);
  const [hover, setHover] = React.useState(false);
  return (
    <article
      style={shortsStyles.card}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={() => onPlay && onPlay(video)}
    >
      <div style={{ ...shortsStyles.thumb, transform: hover ? 'scale(1.02)' : 'none' }}>
        {video.id ? (
          <img src={ytThumb(video.id)} alt="" style={shortsStyles.thumbImg}
               onError={(e) => { e.currentTarget.style.opacity = 0; }}/>
        ) : (
          <PlaceholderThumb category={video.category} small/>
        )}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 65%, rgba(0,0,0,0.45))' }}/>
        <div style={shortsStyles.playOverlay}>
          <div style={{ ...shortsStyles.playCircle, transform: hover ? 'scale(1.1)' : 'scale(1)' }}>
            <PlayIcon size={18}/>
          </div>
        </div>
        <div style={shortsStyles.duration}>{video.duration}</div>
      </div>
      <h5 style={shortsStyles.cardTitle}>{pickLang(video.title, lang)}</h5>
    </article>
  );
}

function VideoSideItem({ video, onPlay }) {
  const tr = useT();
  const lang = React.useContext(LangContext);
  const [hover, setHover] = React.useState(false);
  return (
    <div style={blockStyles.sideItem}
         onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
         onClick={() => onPlay && onPlay(video)}>
      <div style={{ ...blockStyles.sideThumb, transform: hover ? 'scale(1.01)' : 'none', transition: 'transform 220ms var(--ease-out)' }}>
        {video.id ? (
          <img src={ytThumb(video.id)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
        ) : (
          <PlaceholderThumb category={video.category} small/>
        )}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 60%, rgba(0,0,0,0.45))' }}/>
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: '50%',
            background: 'rgba(255,255,255,0.92)', color: 'var(--brand-leaf-deep)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'transform 220ms var(--ease-out)',
            transform: hover ? 'scale(1.12)' : 'scale(1)',
          }}>
            <PlayIcon size={16}/>
          </div>
        </div>
        <div style={{
          position: 'absolute', bottom: 6, right: 6,
          padding: '2px 6px', borderRadius: 4,
          background: 'rgba(15,15,15,0.78)', color: '#fff',
          fontFamily: 'var(--font-mono)', fontSize: 10,
        }}>{video.duration}</div>
      </div>
      <div>
        <div style={blockStyles.sideMeta}>
          {tr('cat.' + video.category)} · {pickLang(video.date, lang)}
        </div>
        <h5 style={blockStyles.sideTitle}>{pickLang(video.title, lang)}</h5>
      </div>
    </div>
  );
}

function HomeVideoBlock() {
  const tr = useT();
  const [playing, setPlaying] = React.useState(null);
  const [, forceRender] = React.useReducer(x => x + 1, 0);
  const lang = React.useContext(LangContext);

  // Re-render when youtube-feed.js swaps SAMPLE_VIDEOS with real data
  React.useEffect(() => {
    const onUpdate = () => forceRender();
    window.addEventListener('youtube-feed-updated', onUpdate);
    return () => window.removeEventListener('youtube-feed-updated', onUpdate);
  }, []);

  // If we have a real YouTube ID, open the lightbox; otherwise jump to the
  // channel so users never land on a black/blank embed.
  const handlePlay = (v) => {
    if (v && v.id) setPlaying(v);
    else window.open(CHANNEL_URL, '_blank', 'noopener');
  };

  // Separate Shorts (≤60s) from long-form videos. The main grid renders
  // only long-form; Shorts appear in their own row below.
  const longForm = SAMPLE_VIDEOS.filter(v => !isShortVideo(v));
  const shorts   = SAMPLE_VIDEOS.filter(v =>  isShortVideo(v));

  // If we have real long-form videos, use them. Otherwise fall back to the
  // full list (placeholders, or a channel that's only Shorts).
  const main = longForm.length > 0 ? longForm : SAMPLE_VIDEOS;
  const [featured, ...rest] = main;
  const recent = rest.slice(0, 3);

  return (
    <section style={blockStyles.section}>
      <div style={blockStyles.inner}>
        <div style={blockStyles.head}>
          <div>
            <div className="eyebrow">{tr('videos.eyebrow')}</div>
            <h2 className="section-title" style={{ marginTop: 8 }}>{tr('videos.title')}</h2>
            <p className="section-sub" style={{ marginTop: 10 }}>{tr('videos.sub')}</p>
          </div>
          <a className="btn btn--secondary" href={CHANNEL_URL} target="_blank" rel="noopener">
            {tr('videos.subscribe')} <ArrowRight size={16}/>
          </a>
        </div>

        <div style={blockStyles.grid}>
          {/* Featured video on the left */}
          <div>
            <VideoCard video={featured} onPlay={handlePlay} size="md"/>
          </div>

          {/* Recent list on the right */}
          <div>
            <div style={blockStyles.sideHead}>{tr('videos.recent')}</div>
            <div style={blockStyles.sideList}>
              {recent.map((v, i) => <VideoSideItem key={v.id || `placeholder-${i}`} video={v} onPlay={handlePlay}/>)}
            </div>
          </div>
        </div>

        {/* Shorts row — only renders if we have real Shorts data */}
        {shorts.length > 0 && (
          <div style={shortsStyles.wrap}>
            <div style={shortsStyles.head}>
              <div style={shortsStyles.headLeft}>
                <span style={shortsStyles.badge}>SHORTS</span>
                <h3 style={shortsStyles.title}>{tr('videos.shortsTitle')}</h3>
              </div>
              <a href={CHANNEL_URL + '/shorts'} target="_blank" rel="noopener" style={shortsStyles.allLink}>
                {tr('videos.shortsAll')} →
              </a>
            </div>
            <div style={shortsStyles.row}>
              {shorts.slice(0, 6).map((v, i) => (
                <ShortsCard key={v.id || `short-${i}`} video={v} onPlay={handlePlay}/>
              ))}
            </div>
          </div>
        )}
      </div>

      {playing && <VideoLightbox video={playing} onClose={() => setPlaying(null)}/>}
    </section>
  );
}

// ---------- Section page: featured video strip ----------------------------

const sectionVidStyles = {
  section: { background: '#fff', padding: '40px 0 8px' },
  inner: { maxWidth: 1200, margin: '0 auto', padding: '0 32px' },
  card: {
    display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 36,
    alignItems: 'center',
    padding: '28px',
    borderRadius: 18,
    border: '1px solid var(--color-divider)',
    background: '#fff',
  },
  thumbWrap: { borderRadius: 12, overflow: 'hidden' },
  body: { paddingRight: 8 },
  eyebrow: {
    fontFamily: 'var(--font-sans)', fontWeight: 700,
    fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 30, lineHeight: 1.15,
    color: 'var(--color-fg-strong)',
    margin: '10px 0 14px',
    textWrap: 'balance',
  },
  desc: {
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.6,
    color: 'var(--color-fg)', margin: 0,
    textWrap: 'pretty',
  },
  cta: { marginTop: 22, display: 'inline-flex', alignItems: 'center', gap: 8 },
};

function SectionVideo({ section }) {
  const tr = useT();
  const lang = React.useContext(LangContext);
  const [playing, setPlaying] = React.useState(null);
  const [hover, setHover] = React.useState(false);
  const [, forceRender] = React.useReducer(x => x + 1, 0);

  React.useEffect(() => {
    const onUpdate = () => forceRender();
    window.addEventListener('youtube-feed-updated', onUpdate);
    return () => window.removeEventListener('youtube-feed-updated', onUpdate);
  }, []);

  const palette = (window.SECTION_PALETTE || {})[section] || { strong: '#1F4F40', accent: '#6FA98C' };

  // Find the most recent video for this section (fallback to first)
  const v = SAMPLE_VIDEOS.find(v => v.category === section) || SAMPLE_VIDEOS[0];
  if (!v) return null;

  const handlePlay = (video) => {
    if (video && video.id) setPlaying(video);
    else window.open(CHANNEL_URL, '_blank', 'noopener');
  };

  return (
    <section style={sectionVidStyles.section}>
      <div style={sectionVidStyles.inner}>
        <div style={{ ...sectionVidStyles.card, borderColor: palette.accent + '55' }}>
          <div style={sectionVidStyles.thumbWrap}
               onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
            <VideoThumb video={v} onPlay={handlePlay} hover={hover}/>
          </div>
          <div style={sectionVidStyles.body}>
            <div style={{ ...sectionVidStyles.eyebrow, color: palette.strong }}>
              {tr('videos.sectionEyebrow')} · {tr('cat.' + section)}
            </div>
            <h3 style={sectionVidStyles.title}>{pickLang(v.title, lang)}</h3>
            {v.desc && <p style={sectionVidStyles.desc}>{pickLang(v.desc, lang)}</p>}
            <button className="btn btn--primary" style={sectionVidStyles.cta} onClick={() => handlePlay(v)}>
              <PlayIcon size={16}/> {tr('videos.sectionCta')} <span style={{ opacity: 0.6, fontFamily: 'var(--font-mono)' }}>{v.duration}</span>
            </button>
          </div>
        </div>
      </div>

      {playing && <VideoLightbox video={playing} onClose={() => setPlaying(null)}/>}
    </section>
  );
}

Object.assign(window, {
  SAMPLE_VIDEOS,
  CHANNEL_URL,
  VideoCard,
  VideoLightbox,
  HomeVideoBlock,
  SectionVideo,
  isShortVideo,
});
