/* Single-page Conecta.rugby — all sections from conecta.rugby in one document.
   Reuses Icons, Ecosystem, Tweaks, AppScreens from sibling files. */

/* ─── Extra icons used by this page ─── */
const ExtraIcons = {
  play: (props) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...props}>
      <path d="M8 5 L19 12 L8 19 Z" />
    </svg>
  ),
  whistle: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M3 12 a6 6 0 0 0 12 0 v-2 h7 v-2 h-9 a4 4 0 0 0 -4 -2 a6 6 0 0 0 -6 6 z" />
      <circle cx="9" cy="12" r="1.5" fill="currentColor" />
    </svg>
  ),
  shield: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M12 3 L20 6 V12 C20 16 16 20 12 21 C8 20 4 16 4 12 V6 Z" />
    </svg>
  ),
  women: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <circle cx="12" cy="6" r="3" />
      <path d="M12 9 V21 M9 17 H15 M8 14 L16 14" />
    </svg>
  ),
  child: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <circle cx="12" cy="6" r="2.5" />
      <path d="M8 21 V14 H16 V21 M10 14 V11 C10 10 11 9.5 12 9.5 C13 9.5 14 10 14 11 V14" />
    </svg>
  ),
  phone: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M5 4 H9 L11 9 L8.5 10.5 C9.5 13 11 14.5 13.5 15.5 L15 13 L20 15 V19 C20 20 19 21 18 21 C10.5 21 3 13.5 3 6 C3 5 4 4 5 4 Z" />
    </svg>
  ),
  user: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <circle cx="12" cy="8" r="3.5" />
      <path d="M5 21 C5 16.5 8 14 12 14 C16 14 19 16.5 19 21" />
    </svg>
  ),
  ext: (props) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M14 4 H20 V10 M20 4 L11 13 M9 5 H5 V19 H19 V15" />
    </svg>
  ),
};

const VIMEO_OEMBED_ENDPOINT = 'https://vimeo.com/api/oembed.json';

// Pegá acá la URL pública o "unlisted" completa de cada video de Vimeo.
// Si querés que el título y la duración salgan desde Vimeo, dejá vacíos `title` y `dur`.
const VIMEO_VIDEO_SOURCES = [
  { cat: 'TÉCNICA', title: 'Ruck: progresión', dur: '', tone: 'gold', url: 'https://vimeo.com/896166680' },
  { cat: 'PASE', title: 'Atrapar y pasar - 05', dur: '', tone: 'sky', url: 'https://vimeo.com/856540891' },
  { cat: 'FORMACIÓN', title: 'Punto de encuentro ofensivo - 05', dur: '', tone: 'gold', url: 'https://vimeo.com/871201902' },
  { cat: 'PASE', title: 'Atrapar y pasar - 06', dur: '', tone: 'sky', url: 'https://vimeo.com/856561151' },
  { cat: 'PASE', title: 'Atrapar y pasar lanzado', dur: '', tone: 'neutral', url: 'https://vimeo.com/939110003' },
  { cat: 'TACKLE', title: 'Tackle: Aproximación e impacto', dur: '', tone: 'gold', url: 'https://vimeo.com/945794399' },
];

const formatVideoDuration = (seconds) => {
  if (!Number.isFinite(seconds) || seconds <= 0) return '';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
};

const extractVimeoEmbedSrc = (html) => {
  const match = typeof html === 'string' ? html.match(/src="([^"]+)"/i) : null;
  return match ? match[1].replace(/&amp;/g, '&') : '';
};

const buildVideoModalSrc = (src) => {
  if (!src) return '';
  try {
    const url = new URL(src);
    url.searchParams.set('autoplay', '1');
    url.searchParams.set('title', '0');
    url.searchParams.set('byline', '0');
    url.searchParams.set('portrait', '0');
    return url.toString();
  } catch (_error) {
    return src;
  }
};

const loadVimeoVideo = async (video) => {
  if (!video.url) return { ...video };

  try {
    const response = await fetch(
      `${VIMEO_OEMBED_ENDPOINT}?url=${encodeURIComponent(video.url)}&width=640`,
      { headers: { Accept: 'application/json' } }
    );

    if (!response.ok) {
      throw new Error(`oEmbed ${response.status}`);
    }

    const data = await response.json();
    return {
      ...video,
      title: video.title || data.title || 'Video Vimeo',
      dur: video.dur || formatVideoDuration(data.duration),
      thumbnail: data.thumbnail_url || '',
      author: data.author_name || '',
      authorUrl: data.author_url || '',
      embedSrc: extractVimeoEmbedSrc(data.html),
      videoUrl: video.url,
      loadError: false,
    };
  } catch (error) {
    console.error('No se pudo cargar el video de Vimeo:', video.url, error);
    return {
      ...video,
      videoUrl: video.url,
      loadError: true,
    };
  }
};

/* ─── NAV (extended links) ─── */
const ConectaNav = ({ active, onNav }) => {
  const [compact, setCompact] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setCompact(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { id: 'noticias', label: 'Noticias' },
    { id: 'videoteca', label: 'Videoteca' },
    { id: 'staff', label: 'Staff' },
    { id: 'contacto', label: 'Contacto' },
  ];

  return (
    <>
      <nav className={`nav ${compact ? 'compact' : ''}`}>
        <div className="nav__brand" onClick={() => { window.location.href = '/'; }}>
          <div className="nav__brand-mark">
            <img src="assets/conecta-rugby-mark.png" alt="" />
          </div>
          <div className="nav__brand-text">
            <div className="nav__brand-name">Conecta<span>.</span>rugby</div>
            <div className="nav__brand-tag">UN PROGRAMA DE LA UAR</div>
          </div>
        </div>

        <div className="nav__links">
          {links.map(l => (
            <div
              key={l.id}
              className={`nav__link ${active === l.id ? 'active' : ''}`}
              onClick={() => onNav(l.id)}
            >{l.label}</div>
          ))}
        </div>

        <a href="https://app.conecta.rugby/login?redirect=%2F" className="nav__login">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ width: 14, height: 14 }}>
            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
            <polyline points="10 17 15 12 10 7" />
            <line x1="15" y1="12" x2="3" y2="12" />
          </svg>
          <span>Ingresar</span>
        </a>

        <button className="nav__burger" onClick={() => setMobileOpen(true)}>
          <Icons.menu style={{ width: 18, height: 18 }} />
        </button>
      </nav>

      <div className={`mobile-menu ${mobileOpen ? 'open' : ''}`}>
        <button
          onClick={() => setMobileOpen(false)}
          style={{
            position: 'absolute', top: 20, right: 20,
            width: 40, height: 40, borderRadius: 999,
            border: '1px solid var(--hairline-strong)', background: 'transparent',
            color: 'var(--ink)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
          <Icons.close style={{ width: 18, height: 18 }} />
        </button>
        {links.map(l => (
          <div key={l.id} className="nav__link"
            onClick={() => { onNav(l.id); setMobileOpen(false); }}>{l.label}</div>
        ))}
        <a href="https://app.conecta.rugby/login?redirect=%2F" className="nav__login nav__login--mobile" onClick={() => setMobileOpen(false)}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ width: 16, height: 16 }}>
            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
            <polyline points="10 17 15 12 10 7" />
            <line x1="15" y1="12" x2="3" y2="12" />
          </svg>
          <span>Ingresar</span>
        </a>
      </div>
    </>
  );
};

/* ─── HERO ─── */
const ConectaHero = ({ onNav, onAppClick }) => (
  <section data-section="inicio" data-screen-label="01 Inicio" className="hero" id="inicio">
    <div className="hero__inner">
      <div className="hero__copy">
        <div className="eyebrow reveal">PROGRAMA UAR · ARGENTINA</div>
        <h1 className="hero__title reveal">
          Conecta<span className="dot">.</span>
          <span className="rugby">rugby</span>
        </h1>
        <p className="hero__sub reveal">
          Programa de capacitación de la Unión Argentina de Rugby.
        </p>
        <p className="hero__small reveal">
          Una plataforma <strong style={{ color: 'var(--ink)' }}>gratuita y federal</strong> de
          formación, gestión y desarrollo para entrenadores, referees, jugadores
          y dirigentes de todo el país.
        </p>
        <div className="hero__ctas reveal">
          <button className="btn btn--primary btn--lg" onClick={() => onNav('cursos')}>
            Hacer cursos
            <Icons.arrow style={{ width: 16, height: 16 }} />
          </button>
          <button className="btn btn--ghost btn--lg" onClick={() => onNav('programa')}>
            Descubre más
          </button>
        </div>
      </div>

      <div className="reveal">
        <Ecosystem size="hero" onAppClick={onAppClick} />
      </div>
    </div>

    <div className="hero__meta">
      <div className="hero__meta-item">
        <span className="dot"></span>
        ECOSISTEMA OPERATIVO · 24 UNIONES PROVINCIALES
      </div>
      <div className="hero__scroll">
        SCROLL
        <div className="hero__scroll-line"></div>
      </div>
      <div className="hero__meta-item">
        v.2026.04 / RELEASE FEDERAL
      </div>
    </div>
  </section>
);

/* ─── PROGRAMA — what it is + audiences + stats ─── */
const ConectaPrograma = () => (
  <section data-section="programa" data-screen-label="02 Programa" id="programa" className="what">
    <div className="container">
      <div className="what__grid">
        <div>
          <div className="eyebrow reveal">PROGRAMA UAR</div>
          <h2 className="section-title reveal">Capacitación, gestión y desarrollo en una sola plataforma.</h2>

          <div className="what__copy reveal" style={{ marginTop: 8 }}>
            <p>
              <strong style={{ color: 'var(--ink)' }}>Conecta Rugby</strong> es la
              estrategia de formación de la UAR: un ecosistema digital que pone a
              disposición de clubes y uniones cursos online, herramientas de gestión
              de partidos y seguimiento de alto rendimiento.
            </p>
          </div>
        </div>

        <div className="what__copy reveal">
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 12,
            marginTop: 8,
          }}>
            {[
              ['Entrenadores', 'cuerpo médico y preparadores físicos'],
              ['Referees', 'oficiales de desarrollo'],
              ['Managers', 'y dirigentes de club'],
              ['Jugadores', 'desde infantiles hasta primera'],
              ['Administrativos', 'de clubes y uniones'],
              ['Centros de rugby', 'staff UAR y referentes'],
            ].map(([t, s]) => (
              <div key={t} style={{
                display: 'flex', alignItems: 'flex-start', gap: 12,
                padding: '14px 16px',
                borderRadius: 12,
                border: '1px solid var(--hairline)',
                background: 'rgba(0, 22, 32,0.3)',
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: 7,
                  background: 'rgba(200, 146, 17,0.12)',
                  color: 'var(--accent)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0, marginTop: 1,
                }}>
                  <Icons.check style={{ width: 12, height: 12 }} />
                </div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 600, fontFamily: 'var(--font-display)' }}>{t}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', marginTop: 2, fontFamily: 'var(--font-gotham)' }}>{s}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="reveal" style={{ marginTop: 64 }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 0,
          border: '1px solid var(--hairline)',
          borderRadius: 'var(--radius-lg)',
          overflow: 'hidden',
          background: 'rgba(0, 22, 32,0.35)',
        }} className="stats-grid">
          {[
            { n: '+100.000', l: 'Jugadores registrados por año', tag: 'CORE · BD UAR' },
            { n: '+4.000', l: 'Usuarios por semana en Partidos', tag: 'PARTIDOS' },
            { n: '+100.000', l: 'Cursos aprobados', tag: 'CURSOS' },
            { n: '+500', l: 'Jugadores en academias', tag: 'ALTO RENDIMIENTO' },
          ].map((s, i) => (
            <div key={s.l} style={{
              padding: '32px 28px',
              borderRight: i < 3 ? '1px solid var(--hairline)' : 'none',
              position: 'relative',
            }} className="stat-cell">
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10,
                color: 'var(--accent)', letterSpacing: '0.18em',
                marginBottom: 14,
              }}>{s.tag}</div>
              <div style={{
                fontFamily: 'var(--font-display)', fontWeight: 700,
                fontSize: 'clamp(32px, 4vw, 44px)',
                letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--ink)',
              }}>{s.n}</div>
              <div style={{
                fontSize: 12, color: 'var(--ink-dim)',
                letterSpacing: '0.04em',
                marginTop: 10, fontFamily: 'var(--font-gotham)',
              }}>{s.l}</div>
            </div>
          ))}
        </div>
        <style>{`
          @media (max-width: 880px) {
            .stats-grid { grid-template-columns: 1fr 1fr !important; }
            .stat-cell:nth-child(2) { border-right: none !important; }
            .stat-cell:nth-child(1), .stat-cell:nth-child(2) { border-bottom: 1px solid var(--hairline); }
          }
          @media (max-width: 540px) {
            .stats-grid { grid-template-columns: 1fr !important; }
            .stat-cell { border-right: none !important; }
            .stat-cell:not(:last-child) { border-bottom: 1px solid var(--hairline); }
          }
        `}</style>
      </div>
    </div>
  </section>
);

/* ─── CONECTA — three apps section ─── */
const ConectaApps = ({ onAppClick }) => {
  const apps = [
    { id: 'partidos', tag: 'APP 01', title: 'Partidos', text: 'Más de 1.000 partidos por semana administrados de forma digital: ficha electrónica, disciplina, incidencias y bienestar del jugador.' },
    { id: 'cursos', tag: 'APP 02', title: 'Coaching', text: 'Plataforma central de formación continua para jugadores, entrenadores y referís de toda Sudamérica. +50 cursos activos, contenidos UAR y World Rugby.' },
    { id: 'rendimiento', tag: 'APP 03', title: 'Alto Rendimiento', text: 'Seguimiento del jugador en academias y centros nacionales. 25 academias, +500 jugadores y +80 profesionales.' },
  ];

  return (
    <section data-section="cursos" data-screen-label="03 Conecta Rugby" id="cursos" className="eco-section">
      <div className="container">
        <div className="eco-section__head">
          <div className="eyebrow reveal" style={{ justifyContent: 'center', display: 'inline-flex' }}>APLICACIONES</div>
          <h2 className="section-title reveal">El ecosistema Conecta Rugby</h2>
          <p className="section-lead reveal">
            Tres aplicaciones que comparten el mismo Core. Hacé clic para acceder
            a la plataforma o descargar la app.
          </p>
        </div>

        <div className="eco-stage">
          <div className="eco-stage__left reveal">
            {[apps[0]].map(a => (
              <div key={a.id} className="eco-app-card" onClick={() => onAppClick(a.id)}>
                <div className="eco-app-card__head">
                  <span className="eco-app-card__dot"></span>
                  <span className="eco-app-card__tag">{a.tag}</span>
                </div>
                <div className="eco-app-card__title">
                  {a.title}
                  <span className="eco-app-card__arrow">
                    <Icons.arrow style={{ width: 12, height: 12 }} />
                  </span>
                </div>
                <div className="eco-app-card__text">{a.text}</div>
              </div>
            ))}
          </div>

          <div className="eco-stage__viz reveal">
            <Ecosystem size="big" onAppClick={onAppClick} />
          </div>

          <div className="eco-stage__right reveal">
            {apps.slice(1).map(a => (
              <div key={a.id} className="eco-app-card" onClick={() => onAppClick(a.id)}>
                <div className="eco-app-card__head">
                  <span className="eco-app-card__dot"></span>
                  <span className="eco-app-card__tag">{a.tag}</span>
                </div>
                <div className="eco-app-card__title">
                  {a.title}
                  <span className="eco-app-card__arrow">
                    <Icons.arrow style={{ width: 12, height: 12 }} />
                  </span>
                </div>
                <div className="eco-app-card__text">{a.text}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="eco-mobile-cards" style={{ marginTop: 32 }}>
          <style>{`
            .eco-mobile-cards { display: none; }
            @media (max-width: 980px) {
              .eco-mobile-cards { display: grid; gap: 14px; grid-template-columns: 1fr; }
            }
          `}</style>
          {apps.map(a => (
            <div key={a.id} className="eco-app-card" onClick={() => onAppClick(a.id)}>
              <div className="eco-app-card__head">
                <span className="eco-app-card__dot"></span>
                <span className="eco-app-card__tag">{a.tag}</span>
              </div>
              <div className="eco-app-card__title">
                {a.title}
                <span className="eco-app-card__arrow">
                  <Icons.arrow style={{ width: 12, height: 12 }} />
                </span>
              </div>
              <div className="eco-app-card__text">{a.text}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ─── NEWS card placeholder image (striped SVG) ─── */
const NewsImg = ({ tone = 'gold', label = 'PRENSA UAR', src = '', alt = '' }) => {
  if (src) {
    return (
      <div className="news-card__media">
        <img className="news-card__image" src={src} alt={alt} loading="lazy" />
        <div className="news-card__image-label">{label}</div>
      </div>
    );
  }

  const c1 = tone === 'gold' ? 'rgba(200,146,17,0.18)' : tone === 'sky' ? 'rgba(106,170,228,0.18)' : 'rgba(255,255,255,0.06)';
  const c2 = tone === 'gold' ? 'rgba(200,146,17,0.04)' : tone === 'sky' ? 'rgba(106,170,228,0.04)' : 'rgba(255,255,255,0.02)';
  return (
    <div style={{
      width: '100%', aspectRatio: '16/10',
      background: `repeating-linear-gradient(135deg, ${c1} 0 8px, ${c2} 8px 16px)`,
      borderBottom: '1px solid var(--hairline)',
      position: 'relative',
      display: 'flex', alignItems: 'flex-end', padding: '14px 16px',
    }}>
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 10,
        letterSpacing: '0.18em', color: tone === 'gold' ? 'var(--accent)' : tone === 'sky' ? 'var(--celeste)' : 'var(--ink-mute)',
        background: 'rgba(0,22,32,0.7)', padding: '6px 10px', borderRadius: 4,
        border: '1px solid var(--hairline)',
      }}>{label}</div>
    </div>
  );
};

/* ─── INTRO / MANIFESTO — texto destacado del programa ─── */
const ConectaIntro = () => (
  <section data-section="intro" data-screen-label="00 Intro" id="intro" className="intro intro--first">
    <div className="container">
      <div className="intro__grid">
        <aside className="intro__rail reveal">
          <div className="intro__rail-label">PROGRAMA UAR</div>
          <div className="intro__rail-num">2026</div>
          <div className="intro__rail-line" />
          <div className="intro__rail-meta">
            Capacitación<br />
            federal y gratuita
          </div>
        </aside>

        <div className="intro__copy">
          <div className="eyebrow reveal">EL PROGRAMA</div>
          <h2 className="intro__lede reveal">
            Un programa <em>absolutamente gratuito</em> con una amplia oferta de
            <span className="intro__hl"> cursos, clínicas, talleres y charlas</span> para
            que los clubes de todo el país alcancen una mayor autonomía.
          </h2>

          <p className="intro__body reveal">
            Con esta iniciativa, desde la UAR vamos a acompañar a todas las
            personas que colaboran en las Uniones y los Clubes para que sigan
            potenciando su desarrollo y así continuar con el
            <strong> fortalecimiento del rugby de base</strong>.
          </p>

          <div className="intro__sign reveal">— Unión Argentina de Rugby</div>
        </div>
      </div>
    </div>
  </section>
);

/* ─── NOTICIAS — featured + grid ─── */
const ConectaNoticias = () => {
  const featured = [
    {
      tag: 'CONECTA RUGBY',
      date: '05-11-25',
      title: 'Conecta Rugby se renueva: una nueva plataforma y la actualización de capacitaciones para 2026',
      tone: 'gold',
      image: 'news_images/conecta_rugby_se_renueva.jpeg',
      url: 'https://uar.com.ar/conecta-rugby-se-renueva-una-nueva-plataforma-y-la-actualizacion-de-capacitaciones-para-2026/',
    },
    {
      tag: 'REGLAMENTO',
      date: '17-02-25',
      title: 'Cambios de leyes 2025',
      tone: 'sky',
      image: 'news_images/cambio_de_leyes.jpg',
      url: 'https://uar.com.ar/cambios-de-leyes-2025/',
    },
    {
      tag: 'COACHING',
      date: '04-01-22',
      title: 'Siempre conectados, y creciendo',
      tone: 'gold',
      image: 'news_images/siempre_conectados_y_creciendo.jpeg',
      url: 'https://uar.com.ar/siempre-conectados-y-creciendo/',
    },
  ];

  return (
    <section data-section="noticias" data-screen-label="01 Noticias" id="noticias" className="news">
      <div className="container">
        <div className="how__head">
          <div>
            <div className="eyebrow reveal">NOTICIAS</div>
            <h2 className="section-title reveal">Últimas novedades del programa.</h2>
          </div>
          <p className="section-lead reveal">
            Reglamento, capacitación, alto rendimiento y desarrollo: todo lo que
            está pasando en Conecta Rugby y la UAR.
          </p>
        </div>

        {/* Featured row */}
        <div className="news__featured reveal">
          {featured.map((n, i) => (
            <a key={i} className="news-card news-card--featured" href={n.url} target="_blank" rel="noreferrer">
              <NewsImg tone={n.tone} label={n.tag} src={n.image} alt={n.title} />
              <div className="news-card__body">
                <div className="news-card__meta">
                  <span>{n.tag}</span>
                  <span>·</span>
                  <span>{n.date}</span>
                </div>
                <div className="news-card__title">{n.title}</div>
                <div className="news-card__cta">
                  Leer nota <Icons.arrow style={{ width: 12, height: 12 }} />
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ─── VIDEOTECA ─── */
const VideoModal = ({ video, onClose }) => {
  React.useEffect(() => {
    if (!video) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [video, onClose]);

  const embedSrc = video ? buildVideoModalSrc(video.embedSrc) : '';
  return (
    <div className={`modal-backdrop ${video ? 'open' : ''}`} onClick={onClose}>
      <div className="modal modal--video" onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__head-title">
            <div className="modal__head-icon"><ExtraIcons.play style={{ width: 18, height: 18 }} /></div>
            <div>
              <div className="modal__head-name">{video?.title || 'Video Vimeo'}</div>
              <div className="modal__head-tag">{video?.cat || 'VIMEO'}</div>
            </div>
          </div>
          <button className="modal__close" onClick={onClose}>
            <Icons.close style={{ width: 16, height: 16 }} />
          </button>
        </div>

        <div className="modal__body">
          {video && (
            <div className="video-modal">
              <div className="video-modal__frame">
                <iframe
                  src={embedSrc}
                  title={video.title || 'Video Vimeo'}
                  allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media; web-share"
                  allowFullScreen
                  referrerPolicy="strict-origin-when-cross-origin"
                />
              </div>

              <div className="video-modal__meta">
                <div className="video-modal__eyebrow">{video.cat || 'VIMEO'}</div>
                <div className="video-modal__title">{video.title || 'Video Vimeo'}</div>
                <div className="video-modal__info">
                  {video.dur && <span>{video.dur}</span>}
                  {video.author && <span>{video.author}</span>}
                  {video.videoUrl && (
                    <a href={video.videoUrl} target="_blank" rel="noreferrer" className="video-modal__link">
                      Abrir en Vimeo <ExtraIcons.ext style={{ width: 12, height: 12 }} />
                    </a>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const ConectaVideoteca = () => {
  const [videos, setVideos] = React.useState(VIMEO_VIDEO_SOURCES);
  const [activeVideo, setActiveVideo] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;

    Promise.all(VIMEO_VIDEO_SOURCES.map(loadVimeoVideo)).then((items) => {
      if (!cancelled) setVideos(items);
    });

    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <>
      <section data-section="videoteca" data-screen-label="02 Videoteca" id="videoteca" className="vidlib">
        <div className="container">
          <div className="how__head">
            <div>
              <div className="eyebrow reveal">VIDEOTECA</div>
              <h2 className="section-title reveal">Aprender mirando.</h2>
            </div>
            <p className="section-lead reveal">
              Una biblioteca de contenidos UAR y World Rugby para entrenadores,
              referís y jugadores. Acceso libre y federal.
            </p>
          </div>

          <div className="vidlib__grid reveal">
            {videos.map((v, i) => {
              const canEmbed = Boolean(v.embedSrc);
              const hasUrl = Boolean(v.videoUrl || v.url);
              const href = v.videoUrl || v.url || '#videoteca';
              const cta = canEmbed ? 'Ver video' : hasUrl ? 'Abrir en Vimeo' : 'Configurar video';

              return (
                <a
                  key={i}
                  className={`vid-card ${!canEmbed && !hasUrl ? 'vid-card--disabled' : ''}`}
                  href={href}
                  target={hasUrl && !canEmbed ? '_blank' : undefined}
                  rel={hasUrl ? 'noreferrer' : undefined}
                  onClick={(e) => {
                    if (canEmbed) {
                      e.preventDefault();
                      setActiveVideo(v);
                      return;
                    }
                    if (!hasUrl) e.preventDefault();
                  }}
                  aria-disabled={!canEmbed && !hasUrl}
                >
                  <div className="vid-card__thumb">
                    {v.thumbnail ? (
                      <img className="vid-card__image" src={v.thumbnail} alt="" loading="lazy" />
                    ) : (
                      <NewsImg tone={v.tone} label={v.cat} />
                    )}
                    {v.thumbnail && <div className="vid-card__label">{v.cat}</div>}
                    <div className="vid-card__play">
                      <ExtraIcons.play style={{ width: 18, height: 18, marginLeft: 2 }} />
                    </div>
                    {v.dur && <div className="vid-card__dur">{v.dur}</div>}
                  </div>
                  <div className="vid-card__body">
                    <div className="vid-card__title">{v.title}</div>
                    <div className="vid-card__cta">
                      {cta} <Icons.arrow style={{ width: 12, height: 12 }} />
                    </div>
                  </div>
                </a>
              );
            })}
          </div>
        </div>
      </section>

      <VideoModal video={activeVideo} onClose={() => setActiveVideo(null)} />
    </>
  );
};

/* ─── STAFF ─── */
const ConectaStaff = () => {
  const team = [
    { name: 'Martín Gaitán', role: 'Coordinador', area: 'Conecta Rugby · UAR' },
    { name: 'Sergio Abbate', role: 'Secretario Técnico', area: 'Conecta Rugby · UAR' },
    { name: 'Ramiro Fiat', role: 'Desarrollo', area: 'Conecta Rugby · UAR' },
    { name: 'Rodrigo Zapata Icart', role: 'Rugby infantil', area: 'Conecta Rugby · UAR' },
    { name: 'José Rubino', role: 'Rugby femenino', area: 'Conecta Rugby · UAR' },
    { name: 'Alejandro Moreira', role: 'Scrum', area: 'Conecta Rugby · UAR' },
  ];

  return (
    <section data-section="staff" data-screen-label="03 Staff" id="staff" className="staff">
      <div className="container">
        <div className="how__head">
          <div>
            <div className="eyebrow reveal">EQUIPO</div>
            <h2 className="section-title reveal">El equipo detrás de Conecta Rugby.</h2>
          </div>
          <p className="section-lead reveal">
            Referentes que sostienen el programa día a día: coordinación,
            secretaría técnica, desarrollo, rugby infantil, rugby femenino y scrum.
          </p>
        </div>

        <div className="staff__grid reveal">
          {team.map((m, i) => (
            <div key={i} className="staff-card">
              <div className="staff-card__avatar">
                <ExtraIcons.user style={{ width: 28, height: 28 }} />
              </div>
              <div className="staff-card__num">M · {String(i + 1).padStart(2, '0')}</div>
              <div className="staff-card__name">{m.name}</div>
              <div className="staff-card__role">{m.role}</div>
              <div className="staff-card__area">{m.area}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ─── CONTACTO ─── */
const ConectaContacto = () => {
  const [form, setForm] = React.useState({ nombre: '', email: '', area: '', mensaje: '' });
  const [errors, setErrors] = React.useState({});
  const [submitError, setSubmitError] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);

  const set = (k) => (e) => {
    setForm(f => ({ ...f, [k]: e.target.value }));
    setSubmitError('');
  };

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.nombre.trim()) errs.nombre = 'Requerido';
    if (!form.email.trim()) errs.email = 'Requerido';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = 'Email inválido';
    if (!form.area) errs.area = 'Seleccione un área';
    if (!form.mensaje.trim()) errs.mensaje = 'Requerido';
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    setSubmitError('');
    setSending(true);

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.nombre,
          email: form.email,
          destino: form.area,
          message: form.mensaje,
        }),
      });
      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data.ok) {
        const serverErrors = data.errors || {};
        const mappedErrors = {};
        if (serverErrors.name) mappedErrors.nombre = serverErrors.name;
        if (serverErrors.email) mappedErrors.email = serverErrors.email;
        if (serverErrors.destino) mappedErrors.area = serverErrors.destino;
        if (serverErrors.message) mappedErrors.mensaje = serverErrors.message;
        setErrors(mappedErrors);
        setSubmitError(data.message || 'No se pudo enviar el mensaje. Intentá de nuevo.');
        return;
      }

      setSent(true);
    } catch (_error) {
      setSubmitError('No se pudo enviar el mensaje. Revisá la conexión e intentá de nuevo.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section data-section="contacto" data-screen-label="04 Contacto" id="contacto" className="contact">
      <div className="container">
        <div className="how__head">
          <div>
            <div className="eyebrow reveal">CONTACTO</div>
            <h2 className="section-title reveal">Envíe su <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>mensaje</em>.</h2>
          </div>
          <p className="section-lead reveal">
            Rellene el formulario y nos pondremos en contacto a la brevedad.
            Para consultas urgentes, también puede escribirnos directamente a las áreas indicadas.
          </p>
        </div>

        <div className="contact__grid">
          <div className="contact__form-wrap reveal">
            {sent ? (
              <div className="form__success">
                <div className="form__success-icon">
                  <Icons.check style={{ width: 24, height: 24 }} />
                </div>
                <h3 style={{ margin: 0, fontSize: 22 }}>Mensaje enviado</h3>
                <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-dim)' }}>
                  Gracias, {form.nombre.split(' ')[0]}. Te respondemos a la brevedad.
                </p>
              </div>
            ) : (
              <form className="form" onSubmit={submit} noValidate>
                {submitError && <div className="form__error">{submitError}</div>}
                <div className="form__row">
                  <div className={`field ${errors.nombre ? 'error' : ''}`}>
                    <label>Nombre <span className="req">*</span></label>
                    <input type="text" value={form.nombre} onChange={set('nombre')} placeholder="Tu nombre" disabled={sending} />
                    {errors.nombre && <div className="field__err">{errors.nombre}</div>}
                  </div>
                  <div className={`field ${errors.email ? 'error' : ''}`}>
                    <label>Email <span className="req">*</span></label>
                    <input type="email" value={form.email} onChange={set('email')} placeholder="tu@email.com" disabled={sending} />
                    {errors.email && <div className="field__err">{errors.email}</div>}
                  </div>
                </div>
                <div className={`field ${errors.area ? 'error' : ''}`}>
                  <label>Área <span className="req">*</span></label>
                  <select value={form.area} onChange={set('area')} disabled={sending}>
                    <option value="">Seleccione área...</option>
                    <option value="capacitacion">Capacitación · Cursos</option>
                    <option value="desarrollo">Desarrollo</option>
                    <option value="infantil">Rugby Infantil</option>
                    <option value="femenino">Rugby Femenino</option>
                    <option value="referees">Referees</option>
                    <option value="rendimiento">Alto Rendimiento</option>
                  </select>
                  {errors.area && <div className="field__err">{errors.area}</div>}
                </div>
                <div className={`field ${errors.mensaje ? 'error' : ''}`}>
                  <label>Mensaje <span className="req">*</span></label>
                  <textarea value={form.mensaje} onChange={set('mensaje')} placeholder="Contanos en qué podemos ayudarte" disabled={sending} />
                  {errors.mensaje && <div className="field__err">{errors.mensaje}</div>}
                </div>
                <button type="submit" className="btn btn--primary btn--lg" style={{ justifySelf: 'start' }} disabled={sending}>
                  {sending ? 'Enviando...' : 'Enviar mensaje'}
                  {!sending && <Icons.arrow style={{ width: 16, height: 16 }} />}
                </button>
              </form>
            )}
          </div>

          <aside className="contact__side reveal">
            <div className="contact__side-title">Datos directos</div>
            <div className="contact__info-card">
              <div className="contact__info-icon">
                <Icons.mail style={{ width: 18, height: 18 }} />
              </div>
              <div>
                <div className="contact__info-lbl">EMAIL</div>
                <div className="contact__info-val">conecta@uar.com.ar</div>
              </div>
            </div>
            <div className="contact__info-card">
              <div className="contact__info-icon">
                <Icons.pin style={{ width: 18, height: 18 }} />
              </div>
              <div>
                <div className="contact__info-lbl">SEDE</div>
                <div className="contact__info-val">Dardo Rocha 2950</div>
                <div className="contact__info-val" style={{ marginTop: 4 }}>B1640FTR Martínez · Buenos Aires</div>
              </div>
            </div>
            <div className="contact__info-card">
              <div className="contact__info-icon">
                <Icons.globe style={{ width: 18, height: 18 }} />
              </div>
              <div>
                <div className="contact__info-lbl">PLATAFORMA</div>
                <div className="contact__info-val">app.conecta.rugby</div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
};

/* ─── FOOTER ─── */
const ConectaFooter = () => (
  <footer className="footer footer--full">
    <div className="container" style={{ width: '100%' }}>
      <div className="footer__top">
        <div className="footer__brand-block">
          <div className="footer__brand">
            <img src="assets/conecta-rugby-mark.png" alt="" />
            <div>
              <div style={{ fontWeight: 800, color: 'var(--ink)', fontSize: 16 }}>
                Conecta<span style={{ color: 'var(--accent)' }}>.</span>rugby
              </div>
              <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 4 }}>
                Programa UAR · {new Date().getFullYear()}
              </div>
            </div>
          </div>
          <p style={{
            fontSize: 13.5, color: 'var(--ink-mute)', lineHeight: 1.6,
            marginTop: 18, maxWidth: 320,
          }}>
            Programa de capacitación, gestión y desarrollo de la Unión Argentina
            de Rugby. Gratuito y federal.
          </p>
        </div>

        <div className="footer__cols">
          <div>
            <div className="footer__col-title">Secciones</div>
            <a className="footer__link" href="#noticias">Noticias</a>
            <a className="footer__link" href="#videoteca">Videoteca</a>
            <a className="footer__link" href="#staff">Staff</a>
            <a className="footer__link" href="#contacto">Contacto</a>
          </div>
          <div>
            <div className="footer__col-title">Plataforma</div>
            <a className="footer__link" href="#contacto">app.conecta.rugby <ExtraIcons.ext style={{ width: 11, height: 11, marginLeft: 4, verticalAlign: -1 }} /></a>
            <a className="footer__link" href="#contacto">uar.com.ar <ExtraIcons.ext style={{ width: 11, height: 11, marginLeft: 4, verticalAlign: -1 }} /></a>
          </div>
          <div>
            <div className="footer__col-title">Contacto</div>
            <a className="footer__link" href="#contacto">conecta@uar.com.ar</a>
            <a className="footer__link" href="#contacto">Dardo Rocha 2950, Martínez · Buenos Aires</a>
          </div>
        </div>
      </div>

      <div className="footer__bottom">
        <div>{new Date().getFullYear()} © <strong style={{ color: 'var(--ink-dim)' }}>Unión Argentina de Rugby</strong></div>
        <div className="footer__links">
          <span className="footer__link">Términos</span>
          <span className="footer__link">Privacidad</span>
          <span className="footer__link">Accesibilidad</span>
        </div>
      </div>
    </div>
  </footer>
);

/* ─── APP MODAL — for accessing the three apps ─── */
const AppModal = ({ appId, onClose }) => {
  const meta = {
    partidos: { title: 'Partidos', tag: 'APP 01 · GESTIÓN', Icon: Icons.partidos, Screen: PartidosScreen },
    cursos: { title: 'Cursos', tag: 'APP 02 · CAPACITACIÓN', Icon: Icons.cursos, Screen: CursosScreen },
    rendimiento: { title: 'Alto Rendimiento', tag: 'APP 03 · DESARROLLO', Icon: Icons.rendimiento, Screen: RendimientoScreen },
  };

  React.useEffect(() => {
    if (!appId) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [appId, onClose]);

  const m = appId && meta[appId];
  return (
    <div className={`modal-backdrop ${appId ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__head-title">
            {m && (
              <>
                <div className="modal__head-icon"><m.Icon style={{ width: 18, height: 18 }} /></div>
                <div>
                  <div className="modal__head-name">{m.title}</div>
                  <div className="modal__head-tag">{m.tag}</div>
                </div>
              </>
            )}
          </div>
          <button className="modal__close" onClick={onClose}>
            <Icons.close style={{ width: 16, height: 16 }} />
          </button>
        </div>
        <div className="modal__body">
          {m && <AccessScreen appId={appId} PreviewScreen={m.Screen} IconCmp={m.Icon} />}
        </div>
      </div>
    </div>
  );
};

/* ─── ROOT APP ─── */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "amarillo"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = {
  amarillo: { name: 'Amarillo UAR',  hex: '#c89211', soft: '#e2c771' },
  celeste:  { name: 'Celeste UAR',   hex: '#6aaae4', soft: '#94b3de' },
  amarilloSoft: { name: 'Amarillo soft', hex: '#e2c771', soft: '#f0dca0' },
  celesteSoft:  { name: 'Celeste soft',  hex: '#94b3de', soft: '#b8cce8' },
};

const ConectaApp = () => {
  const [active, setActive] = React.useState('noticias');
  const [modalApp, setModalApp] = React.useState(null);
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useReveal();

  React.useEffect(() => {
    const opt = ACCENT_OPTIONS[tweaks.accentColor] || ACCENT_OPTIONS.amarillo;
    document.documentElement.style.setProperty('--accent', opt.hex);
    document.documentElement.style.setProperty('--accent-soft', opt.soft);
  }, [tweaks.accentColor]);

  React.useEffect(() => {
    const sections = document.querySelectorAll('[data-section]');
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) setActive(e.target.dataset.section);
      });
    }, { rootMargin: '-40% 0px -50% 0px', threshold: 0 });
    sections.forEach(s => io.observe(s));
    return () => io.disconnect();
  }, []);

  const handleNav = (id) => {
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  return (
    <div className="app">
      <ConectaNav active={active} onNav={handleNav} />

      <ConectaIntro />
      <ConectaNoticias />
      <ConectaVideoteca />
      <ConectaStaff />
      <ConectaContacto />
      <ConectaFooter />

      <AppModal appId={modalApp} onClose={() => setModalApp(null)} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Color de acento">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {Object.entries(ACCENT_OPTIONS).map(([k, v]) => (
              <button
                key={k}
                onClick={() => setTweak('accentColor', k)}
                style={{
                  aspectRatio: 1,
                  borderRadius: 12,
                  border: tweaks.accentColor === k ? `2px solid ${v.hex}` : '1px solid rgba(255,255,255,0.12)',
                  background: 'rgba(0, 22, 32,0.4)',
                  cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  position: 'relative',
                }}
                title={v.name}
              >
                <div style={{
                  width: '60%', height: '60%',
                  borderRadius: '50%',
                  background: `radial-gradient(circle at 30% 30%, ${v.soft}, ${v.hex})`,
                  boxShadow: tweaks.accentColor === k ? `0 0 20px ${v.hex}88` : 'none',
                }} />
              </button>
            ))}
          </div>
          <div style={{ marginTop: 12, fontSize: 11, opacity: 0.6, textAlign: 'center' }}>
            {ACCENT_OPTIONS[tweaks.accentColor]?.name}
          </div>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<ConectaApp />);
