/* global React, NAV_LINKS, HERO_PHOTOS, FEATURES, NUMBERS, MEMBERS, LINKS, BIBLIOTECA, BIBLIOTECA_CATEGORIES_EN, NEWS,
   PACODE_LANG, tr, trDate, localize, localHref, langHref,
   PacodeLogo, BalloonSvg, GridPattern, ConfettiTiles, Eyebrow,
   SectionHeader, PlaceholderMedia, NewsItem, MemberAvatar, MemberLink */

/* ============================================================
   pacode: sections
   ============================================================ */

/* The toggle is a link to this same page in the other language. The href
   is refreshed on click so it keeps the section the visitor scrolled to. */
function LangToggle() {
  const other = PACODE_LANG === "en" ? "pt" : "en";
  return (
    <a
      className="pc-lang"
      href={langHref(other)}
      hrefLang={other === "en" ? "en" : "pt-br"}
      lang={other === "en" ? "en" : "pt-br"}
      aria-label={tr("Switch to English", "Mudar para português")}
      onClick={(e) => {e.currentTarget.href = langHref(other);}}>
      <span className={PACODE_LANG === "pt" ? "is-on" : ""}>PT</span>
      <span aria-hidden="true">/</span>
      <span className={PACODE_LANG === "en" ? "is-on" : ""}>EN</span>
    </a>);

}

function TopBar({ base = "" }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const home = localHref(base);
  return (
    <header className={`pc-topbar${menuOpen ? " is-menu-open" : ""}`} data-screen-label="topbar">
      <div className="pc-topbar__brand">
        <a href={`${home}#`} aria-label={tr("pacode, início", "pacode, home")}>
          <img src="assets/pacode-logo.png" alt="pacode" />
        </a>
        <img className="pc-topbar__ufpb" src="assets/ufpb-logo.png" alt={tr("Universidade Federal da Paraíba", "Federal University of Paraíba")} />
      </div>
      <nav className="pc-topbar__nav" aria-label={tr("Seções do site", "Site sections")}>
        {NAV_LINKS.map((l) =>
        <a key={l.id} href={`${home}#${l.id}`} onClick={() => setMenuOpen(false)}>{l.label}</a>
        )}
      </nav>
      <div className="pc-topbar__right">
        <LangToggle />
        <a href={localHref("participar.html")} className="pc-topbar__cta">
          {tr("Participar", "Join")}
          <span aria-hidden="true">↗</span>
        </a>
        <button
          className="pc-topbar__menu"
          aria-expanded={menuOpen}
          aria-label={menuOpen ? tr("Fechar menu", "Close menu") : tr("Abrir menu", "Open menu")}
          onClick={() => setMenuOpen((o) => !o)}>
          <span aria-hidden="true">{menuOpen ? "×" : "☰"}</span>
        </button>
      </div>
    </header>);

}

/* Photos advance on their own every 5s. The arrows jump and restart the
   timer. Rotation pauses while keyboard focus is on the arrows and never
   starts for visitors who asked for reduced motion. */
function HeroGallery() {
  const n = HERO_PHOTOS.length;
  const [i, setI] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [lap, setLap] = React.useState(0);

  React.useEffect(() => {
    if (paused || n < 2) return undefined;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return undefined;
    const t = setInterval(() => setI((x) => (x + 1) % n), 5000);
    return () => clearInterval(t);
  }, [paused, n, lap]);

  const go = (d) => {
    setI((x) => (x + d + n) % n);
    setLap((v) => v + 1);
  };

  return (
    <figure className="pc-hero__photo">
      <div className="pc-hero__frame">
        {HERO_PHOTOS.map((f, k) =>
        <img
          key={f.src}
          src={f.src}
          alt={k === i ? f.alt : ""}
          aria-hidden={k !== i}
          className={k === i ? "is-on" : ""}
          style={{ objectPosition: `${f.positionX || "50%"} ${f.position}` }} />
        )}
      </div>
      <figcaption className="pc-hero__bar">
        <span className="pc-hero__caption" aria-live={paused ? "polite" : "off"}>
          <b>{tr(`Foto ${i + 1} de ${n}`, `Photo ${i + 1} of ${n}`)}</b>
          {HERO_PHOTOS[i].caption}
          {paused ? null : <i className="pc-hero__progress" key={`${i}-${lap}`} />}
        </span>
        <div
          className="pc-hero__nav"
          onFocus={(e) => {if (e.target.matches(":focus-visible")) setPaused(true);}}
          onBlur={() => setPaused(false)}>
          <button type="button" aria-label={tr("Foto anterior", "Previous photo")} onClick={() => go(-1)}>←</button>
          <button type="button" aria-label={tr("Próxima foto", "Next photo")} onClick={() => go(1)}>→</button>
        </div>
      </figcaption>
    </figure>);

}

function Hero() {
  return (
    <section className="pc-hero" data-screen-label="01 hero">
      <div className="pc-hero__left">
        <div className="pc-hero__titlebox">
          <h1 className="pc-hero__title">
            {PACODE_LANG === "en" ?
            <>
                <span>UFPB's</span>
                <span><em>competitive</em></span>
                <span>programming</span>
                <span>community</span>
              </> :

            <>
                <span>comunidade de</span>
                <span>programação</span>
                <span><em>competitiva</em></span>
                <span>da UFPB</span>
              </>
            }
          </h1>
        </div>
        <div>
          <p className="pc-hero__lead">
            {tr(
              "Aulas semanais, contests internos e preparação para as principais competições de programação do Brasil e do mundo.",
              "Weekly classes, internal contests and training for the main programming competitions in Brazil and around the world."
            )}
          </p>
          <dl className="pc-hero__meta">
            <div>
              <dt>{tr("Sede", "Based at")}</dt>
              <dd>{tr("CI, João Pessoa (PB)", "CI, João Pessoa, Brazil")}</dd>
            </div>
            <div>
              <dt>{tr("Aulas", "Classes")}</dt>
              <dd>{tr("Sextas, 08h", "Fridays, 8 a.m.")}</dd>
            </div>
            <div>
              <dt>{tr("Desde", "Since")}</dt>
              <dd>2024</dd>
            </div>
            <div>
              <dt>Instagram</dt>
              <dd><a href="https://www.instagram.com/pacodeufpb/">@pacodeufpb</a></dd>
            </div>
          </dl>
        </div>
      </div>
      <HeroGallery />
    </section>);

}

function Sobre() {
  return (
    <section className="pc-section" id="sobre" data-screen-label="02 sobre">
      <SectionHeader
        eyebrow={tr("Sobre o pacode", "About pacode")}
        title={tr("Aulas, competições e a tradição da UFPB.", "Classes, contests and the UFPB tradition.")}
        lead={tr(
          "O pacode é a comunidade de programação competitiva do Centro de Informática da Universidade Federal da Paraíba. Nosso objetivo é preparar alunos para se destacarem nas principais competições de programação do Brasil e do mundo.",
          "pacode is the competitive programming community of the Informatics Center (CI) at the Federal University of Paraíba (UFPB), in João Pessoa, Brazil. Our goal is to prepare students to stand out in the main programming competitions in Brazil and around the world."
        )}
        action={{ label: tr("Ler a história completa", "Read the full history"), href: "historia.html" }} />
      
      <div className="pc-grid-4">
        {FEATURES.map((f, i) =>
        <article className="pc-card pc-reveal" key={i} style={{ transitionDelay: `${i * 80}ms` }}>
            <PlaceholderMedia label={`${tr("imagem", "image")}: ${f.tag.toLowerCase()}`} src={f.image} alt={f.imageAlt} />
            <span style={{ fontFamily: "var(--pc-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--pc-blue)" }}>○ {f.tag}</span>
            <h3>{f.title}</h3>
            <p>{f.body}</p>
          </article>
        )}
      </div>
    </section>);

}

function MaratonaPacode() {
  return (
    <section className="pc-section pc-section--soft" id="maratona" data-screen-label="03 maratona-pacode">
      <SectionHeader
        eyebrow="Maratona Pacode"
        title={tr("Os números da nossa competição interna.", "Our in-house contest in numbers.")}
        action={{ label: tr("Ver todas as estatísticas", "See all statistics"), href: "estatisticas.html" }} />

      <div className="pc-numbers pc-reveal">
        <div className="pc-numbers__cell is-photo has-image">
          <img src="assets/competicoes/mp1/campeao.png" alt={tr("Time campeão da primeira Maratona Pacode", "Champion team of the first Maratona Pacode")} className="pc-numbers__photo" />
        </div>
        <div className="pc-numbers__cell">
          <span className="pc-numbers__label">{NUMBERS[0].label}</span>
          <div>
            <div className="pc-numbers__value">{NUMBERS[0].value}</div>
            <div className="pc-numbers__hint">{NUMBERS[0].hint}</div>
          </div>
        </div>
        <div className="pc-numbers__cell is-photo has-image">
          <img src="assets/competicoes/mp4/campeao.png" alt={tr("Time campeão da quarta Maratona Pacode", "Champion team of the fourth Maratona Pacode")} className="pc-numbers__photo" />
        </div>
        <div className="pc-numbers__cell">
          <span className="pc-numbers__label">{NUMBERS[1].label}</span>
          <div>
            <div className="pc-numbers__value">{NUMBERS[1].value}</div>
            <div className="pc-numbers__hint">{NUMBERS[1].hint}</div>
          </div>
        </div>
        <div className="pc-numbers__cell">
          <span className="pc-numbers__label">{NUMBERS[2].label}</span>
          <div>
            <div className="pc-numbers__value">{NUMBERS[2].value}</div>
            <div className="pc-numbers__hint">{NUMBERS[2].hint}</div>
          </div>
        </div>
        <div className="pc-numbers__cell is-photo has-image">
          <img src="assets/competicoes/mp5/campeao.png" alt={tr("Time campeão da quinta Maratona Pacode", "Champion team of the fifth Maratona Pacode")} className="pc-numbers__photo" />
        </div>
        <div className="pc-numbers__cell">
          <span className="pc-numbers__label">{NUMBERS[3].label}</span>
          <div>
            <div className="pc-numbers__value">{NUMBERS[3].value}</div>
            <div className="pc-numbers__hint">{NUMBERS[3].hint}</div>
          </div>
        </div>
        <div className="pc-numbers__cell is-photo has-image">
          <img src="assets/competicoes/mp6/terceiro.png" alt={tr("Time terceiro colocado da sexta Maratona Pacode", "Third-place team of the sixth Maratona Pacode")} className="pc-numbers__photo" />
        </div>
      </div>
    </section>);

}

function Conquistas() {
  const items = [
  { year: "2025", title: tr("Medalha de bronze", "Bronze medal"), sub: tr("Olimpíada Brasileira de Informática 2025", "Brazilian Olympiad in Informatics 2025"), color: "#E8B739", image: "assets/competicoes/obi2025/medalha.png", imageAlt: tr("Medalha de bronze da OBI 2025", "OBI 2025 bronze medal") },
  { year: "2025", title: tr("+100 Medalhas", "100+ Medals"), sub: tr("Olimpíada Paraibana de Informática", "Paraíba Olympiad in Informatics"), color: "#1E40AF", image: "assets/competicoes/opi2025/time.png", imageAlt: tr("Medalha de prata da OPI 2025", "OPI 2025 silver medal") },
  { year: "2024", title: tr("5 Classificações", "5 Qualifications"), sub: tr("Final Maratona SBC", "Maratona SBC Finals"), color: "#E63946", image: "assets/competicoes/sbc2015/final-time.webp", imageAlt: tr("Time na final da Maratona SBC 2015", "Team at the 2015 Maratona SBC finals") },
  { year: "2024", title: tr("Medalha de bronze", "Bronze medal"), sub: tr("Maratona Feminina de Programanção 2024", "Women's Programming Marathon 2024"), color: "#1E40AF", image: "assets/competicoes/mfp2024/bronze-larissa.png", imageAlt: tr("Larissa -Medalha de bronze da Maratona Feminina 2024", "Larissa, bronze medal at the 2024 Women's Programming Marathon") },];

  return (
    <section className="pc-section" id="conquistas" data-screen-label="04 conquistas">
      <SectionHeader
        eyebrow={tr("Conquistas", "Achievements")}
        title={tr("Resultados em competições nacionais e regionais.", "Results in national and regional competitions.")}
        lead={tr("Um recorte dos principais marcos do pacode nos últimos anos. A lista completa está na página de premiações.", "A selection of pacode's main milestones in recent years. The full list is on the awards page.")}
        action={{ label: tr("Ver todas as premiações", "See all awards"), href: "premiacoes.html" }} />
      
      <div className="pc-grid-4">
        {items.map((it, i) =>
        <article className="pc-card pc-reveal" key={i} style={{ transitionDelay: `${i * 80}ms` }}>
            <div className={`pc-card__media${it.image ? " has-image" : ""}`} style={{
            background: it.image ? undefined : `linear-gradient(180deg, ${it.color}26, ${it.color}10)`,
            borderColor: it.color
          }}>
              {it.image ? <img src={it.image} alt={it.imageAlt || ""} className="pc-card__media-img" /> : null}
              <span className="placeholder-label" style={{ color: it.color, fontWeight: 600 }}>○ {it.year}</span>
            </div>
            <span style={{ fontFamily: "var(--pc-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: it.color }}>{it.sub}</span>
            <h3>{it.title}</h3>
          </article>
        )}
      </div>
    </section>);

}

/* The home shows the first members: eight fill two rows of the grid.
   Everyone is on membros.html, with LinkedIn and results. */
const HOME_MEMBERS_LIMIT = 8;

function Membros() {
  return (
    <section className="pc-section pc-section--soft" id="membros" data-screen-label="05 membros">
      <SectionHeader
        eyebrow={tr("Equipe atual", "Current team")}
        title={tr("Conheça os membros do pacode.", "Meet the members of pacode.")}
        action={{ label: tr("Ver todos os perfis", "See all profiles"), href: "membros.html" }} />

      <div className="pc-grid-4">
        {MEMBERS.slice(0, HOME_MEMBERS_LIMIT).map((m, i) =>
        <article className="pc-member pc-reveal" key={m.slug} style={{ transitionDelay: `${i % 4 * 80}ms` }}>
            <MemberAvatar member={m} index={i} showTag />
            <div className="pc-member__body">
              <h3 className="pc-member__name">
                <a
                className="pc-member__profile"
                href={localHref(`membros.html#${m.slug}`)}
                aria-label={tr(`${m.name}, ver perfil`, `${m.name}, see profile`)}>{m.name}</a>
              </h3>
              <p className="pc-member__role">{m.role}</p>
              <MemberLink member={m} />
            </div>
          </article>
        )}
      </div>
    </section>);

}

/* Hall da Fama: reservado para uso futuro. Não apagar.
function HallFama() {
  return (
    <section className="pc-section" id="hall" data-screen-label="06 hall">
      <SectionHeader
        eyebrow="Hall da fama"
        title="Ex-membros que escreveram a história do pacode."
        lead="Capitães, coaches e fundadores que passaram pelo grupo e seguem carreira na academia, na indústria e na pesquisa."
        tag="Egressos" />

      <div className="pc-hof pc-reveal">
        <div className="pc-hof__row is-head">
          <div>Ano de saída</div>
          <div>Nome</div>
          <div>Função no pacode</div>
          <div>Hoje</div>
          <div>Destaque</div>
          <div></div>
        </div>
        {HALL.map((h, i) =>
        <div className="pc-hof__row" key={i}>
            <div className="pc-hof__year">{h.year}</div>
            <div className="pc-hof__name">{h.name}</div>
            <div className="pc-hof__role">{h.role}</div>
            <div className="pc-hof__where">{h.where}</div>
            <div className="pc-hof__highlight">{h.highlight}</div>
            <a href="#" className="pc-hof__cta" aria-label="Ver perfil">↗</a>
          </div>
        )}
      </div>
    </section>);

}
*/

function Biblioteca() {
  return (
    <section className="pc-section" id="biblioteca" data-screen-label="06 biblioteca">
      <SectionHeader
        eyebrow={tr("Biblioteca", "Library")}
        title={tr("Algoritmos e estruturas mantidos pela comunidade.", "Algorithms and data structures maintained by the community.")}
        lead={tr("Implementações revisadas pelo grupo, prontas para uso em contests. Hospedadas no GitHub e atualizadas com frequência.", "Implementations reviewed by the group and ready for contests. Hosted on GitHub and updated often.")}
        links={[
          { label: "Code-Library", href: "https://github.com/GabrielCFormiga/Code-Library", ariaLabel: tr("Abrir o repositório Code-Library no GitHub", "Open the Code-Library repository on GitHub") },
          { label: tr("Baixar PDF", "Download PDF"), href: "https://raw.githubusercontent.com/GabrielCFormiga/Code-Library/main/PDF/Library.pdf", ariaLabel: tr("Baixar a biblioteca em PDF", "Download the library as a PDF"), icon: "↓" },
        ]} />

      <div className="pc-hof pc-reveal">
        <div className="pc-hof__row is-head">
          <div>{tr("Data", "Date")}</div>
          <div>{tr("Algoritmo", "Algorithm")}</div>
          <div>{tr("Categoria", "Category")}</div>
          <div>{tr("Autor", "Author")}</div>
          <div>{tr("Descrição", "Description")}</div>
          <div></div>
        </div>
        {localize(BIBLIOTECA).map((b, i) =>
        <div className="pc-hof__row" key={i}>
            <div className="pc-hof__year">{trDate(b.date)}</div>
            <div className="pc-hof__name">{b.name}</div>
            <div className="pc-hof__role">{tr(b.category, BIBLIOTECA_CATEGORIES_EN[b.category])}</div>
            <div className="pc-hof__where">{b.author}</div>
            <div className="pc-hof__highlight">{b.description}</div>
            <a href={b.url} target="_blank" rel="noopener noreferrer" className="pc-hof__cta" aria-label={tr("Ver commit no GitHub", "View the commit on GitHub")}>↗</a>
          </div>
        )}
      </div>
    </section>);

}

/* The home shows only the latest posts: one feature plus four fills the
   grid exactly. The rest lives in blog.html. */
const HOME_NEWS_LIMIT = 5;

function Noticias() {
  return (
    <section className="pc-section pc-section--soft" id="noticias" data-screen-label="07 noticias">
      <SectionHeader
        eyebrow={tr("Notícias", "News")}
        title={tr("O que está acontecendo no pacode agora.", "What is happening at pacode right now.")}
        action={{ label: tr("Ver todas as notícias", "See all news"), href: "blog.html" }} />

      <div className="pc-news pc-reveal">
        {NEWS.slice(0, HOME_NEWS_LIMIT).map((n) =>
        <NewsItem post={n} feature={n.feature} key={n.slug} />
        )}
      </div>
    </section>);

}

function Footer() {
  return (
    <footer className="pc-footer" id="contato" data-screen-label="08 contato">
      <h2 className="pc-footer__big">
        pacode<em>.</em><br />
        ufpb / ci
      </h2>
      <div className="pc-footer__grid">
        <div className="pc-footer__col">
          <h4>{tr("Endereço", "Address")}</h4>
          <p>Centro de Informática, UFPB</p>
          <p>Rua dos Escoteiros, Mangabeira</p>
          <p>{tr("João Pessoa (PB), CEP 58055-000", "João Pessoa, PB, 58055-000, Brazil")}</p>
        </div>
        <div className="pc-footer__col">
          <h4>{tr("Contato", "Contact")}</h4>
          <a href={`mailto:${LINKS.email}`}>{LINKS.email}</a>
          <a href={LINKS.instagram}>Instagram</a>
          <a href={LINKS.youtube}>YouTube</a>
          <a href={LINKS.linkedin}>LinkedIn</a>
        </div>
        <div className="pc-footer__col">
          <h4>{tr("Links úteis", "Useful links")}</h4>
          <a href={LINKS.biblioteca}>{tr("Biblioteca de algoritmos", "Algorithm library")}</a>
          <a href="https://www.ci.ufpb.br/">{tr("Centro de Informática", "Informatics Center")}</a>
          <a href={localHref("blog.html")}>Blog</a>
          {/* <a href="https://maratona.sbc.org.br/">Maratona SBC</a> */}
          {/* <a href="#">ICPC Global</a> */}
        </div>
        <div className="pc-footer__col">
          <h4>{tr("Participar", "Join")}</h4>
          <a href={localHref("participar.html")}>{tr("Como participar", "How to join")}</a>
          <a href={LINKS.trilha}>{tr("Trilha de aprendizado", "Learning path")}</a>
          {/* <a href="#">Materiais públicos</a> */}
          {/* <a href="#">Processo seletivo</a> */}
          {/* <a href="#">Calendário de treinos</a> */}
        </div>
      </div>
      <div className="pc-footer__base">
        <span>{tr("© 2026 PACODE. TODOS OS DIREITOS RESERVADOS", "© 2026 PACODE. ALL RIGHTS RESERVED")}</span>
        <div className="pc-footer__social">
          <a href={LINKS.instagram} aria-label="Instagram">IG</a>
          <a href={LINKS.github} aria-label="GitHub">GH</a>
          <a href={LINKS.youtube} aria-label="YouTube">YT</a>
          <a href={LINKS.linkedin} aria-label="LinkedIn">IN</a>
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  TopBar, Hero, Sobre, MaratonaPacode, Conquistas, Membros, /* HallFama, */ Biblioteca, Noticias, Footer
});