/* eslint-disable */
// Case content. Each case has a `pt` and `en` block for localized strings,
// plus a few shared fields (year, hue) that don't translate.
const CASE_CONTENT = {
  'velo-clube': {
    year: '2024', hue: 210,
    pt: {
      title: 'Velo Clube',
      tagline: 'O Velo Clube carrega em seu manto o orgulho de uma tradição que nunca se apaga.',
      client: 'Velo Clube', role: 'Identidade Visual', scope: 'Brand · Kit · Comunicação',
      approach: 'O branco traz a elegância, o dourado representa a glória, e o verde mantém viva a essência que move gerações. Essa camisa é mais do que um uniforme, é o símbolo de um novo capítulo.',
      outcome: 'Em 2026, o Velo Clube escreve um novo capítulo de sua história ao disputar, pela primeira vez, uma competição nacional: a Série D do Campeonato Brasileiro. Este conceito nasce desse marco histórico, traduzindo em cada detalhe a tradição do clube, a força de suas raízes e a ambição de quem entra em campo para construir um novo legado.',
      disclaimer: 'Projeto conceitual criado exclusivamente para estudo, sem fins comerciais\ne sem qualquer vínculo oficial com as marcas ou clubes apresentados.',
    },
    en: {
      title: 'Velo Clube',
      tagline: 'Velo Clube carries on its shirt the pride of a tradition that never fades.',
      client: 'Velo Clube', role: 'Visual Identity', scope: 'Brand · Kit · Communication',
      approach: 'White brings elegance, gold represents glory, and green keeps alive the essence that moves generations. This shirt is more than a kit — it\'s the symbol of a new chapter.',
      outcome: 'In 2026, Velo takes the field in its first national competition, the Brasileirão Série D. With that in mind, I set out to propose a design born from its roots, reflecting the strength of those arriving to make history.',
      disclaimer: 'Conceptual project created exclusively for portfolio purposes — non-commercial, with no official affiliation with the brands or clubs shown.',
    },
  },
  'inter': {
    year: '2025', hue: 38,
    pt: {
      title: 'Inter de Limeira',
      tagline: 'A Inter de Limeira carrega em seu manto o peso da tradição e a glória de quem nasceu para vencer. Pensando nisso, desenvolvi um concept design para o terceiro uniforme da equipe, inspirado no legado da comunidade italiana muito presente na cidade e já homenageada em uniformes anteriores.',
      client: 'A.A. Internacional Limeira', role: 'Concept Design', scope: 'Terceiro uniforme',
      approach: 'O preto traduz elegância e poder. O dourado simboliza a nobreza e as conquistas que marcaram gerações.',
      outcome: '',
    },
    en: {
      title: 'Inter de Limeira',
      tagline: 'Inter de Limeira carries on its shirt the weight of tradition and the glory of those born to win. With that in mind, I developed a concept design for the team\'s third kit, inspired by the legacy of the Italian community deeply present in the city and already honored in previous kits.',
      client: 'A.A. Internacional Limeira', role: 'Concept Design', scope: 'Third kit',
      approach: 'Black speaks of elegance and power. Gold stands for the nobility and the titles that marked generations.',
      outcome: '',
    },
  },
  'mevo': {
    year: '2026', hue: 340,
    pt: {
      title: 'Mevo',
      tagline: 'Construção de uma presença de marca consistente em diferentes pontos de contato.\n\nCom a expansão da Mevo e de suas soluções em saúde, surgiu a necessidade de traduzir a marca de forma consistente em diferentes canais, públicos e momentos de interação.',
      client: 'Mevo', role: 'Identidade Visual · Direção de Arte', scope: 'Marca · Sistema · Comunicação',
      approach: 'O projeto teve como foco fortalecer a presença da Mevo por meio de uma comunicação visual mais coesa, reconhecível e alinhada aos atributos da marca.',
      outcome: '',
    },
    en: {
      title: 'Mevo',
      tagline: 'Building a consistent brand presence across different touchpoints.\n\nAs Mevo and its health solutions expanded, the brand needed to be translated consistently across channels, audiences and moments of interaction.',
      client: 'Mevo', role: 'Visual Identity · Art Direction', scope: 'Brand · System · Communication',
      approach: 'The project focused on strengthening Mevo\'s presence through a more cohesive, recognizable visual communication, aligned with the brand\'s attributes.',
      outcome: '',
    },
  },
  'portuguesa': {
    year: '2024', hue: 6,
    pt: {
      title: 'Portuguesa',
      tagline: 'Linha de uniformes em homenagem à tradição lusitana do clube — listras, brasão e tipografia recuperada dos anos 70.',
      client: 'Portuguesa Santista', role: 'Kit Design', scope: 'Uniforme · Heritage',
      approach: 'Pesquisa em arquivo, recuperação de tipografia da época e releitura das listras tradicionais com tecido e acabamento contemporâneos.',
      outcome: 'Camisa esgotada na pré-venda, com forte engajamento da torcida histórica.',
    },
    en: {
      title: 'Portuguesa',
      tagline: 'Kit collection honoring the club\'s Lusitanian tradition — stripes, crest and typography recovered from the 70s.',
      client: 'Portuguesa Santista', role: 'Kit Design', scope: 'Kit · Heritage',
      approach: 'Archive research, recovery of period typography and a fresh take on the traditional stripes with contemporary fabric and finishing.',
      outcome: 'Sold out in pre-sale, with strong engagement from the longtime fanbase.',
    },
  },
  'padel': {
    year: '2025', hue: 145,
    pt: {
      title: 'Padel',
      tagline: 'Direção editorial para conteúdo sobre o esporte que mais cresce no Brasil — fotografia, layout e tipografia em sintonia com a quadra.',
      client: 'Editorial Independente', role: 'Editorial · Direção', scope: 'Print · Digital',
      approach: 'Tipografia condensada para títulos, mono para dados de partida e estatística, fotografia em ângulos baixos com foco no movimento.',
      outcome: 'Edição zero impressa em tiragem limitada e uma versão digital responsiva.',
    },
    en: {
      title: 'Padel',
      tagline: 'Editorial direction for content on Brazil\'s fastest-growing sport — photography, layout and typography in tune with the court.',
      client: 'Independent Editorial', role: 'Editorial · Direction', scope: 'Print · Digital',
      approach: 'Condensed typography for headlines, mono for match data and statistics, low-angle photography focused on movement.',
      outcome: 'A limited-print zero issue and a responsive digital version.',
    },
  },
  'g3x': {
    year: '2025', hue: 240,
    pt: {
      title: 'G3X',
      tagline: 'Marca pessoal de atleta — equilíbrio entre presença individual e linguagem de equipe.',
      client: 'G3X / Atleta', role: 'Personal Brand', scope: 'Logo · Aplicações',
      approach: 'Monograma geométrico de alta legibilidade em pequenas escalas, sistema cromático sóbrio e paleta secundária ajustável por colaboração.',
      outcome: 'Marca aplicada em chuteira, uniforme de treino, conteúdo digital e produtos licenciados.',
    },
    en: {
      title: 'G3X',
      tagline: 'Personal athlete brand — balancing individual presence with team language.',
      client: 'G3X / Athlete', role: 'Personal Brand', scope: 'Logo · Applications',
      approach: 'A geometric monogram with high legibility at small scales, a sober color system and a secondary palette tunable per collaboration.',
      outcome: 'Applied across boots, training kit, digital content and licensed products.',
    },
  },
  'baseball': {
    year: '2024', hue: 0,
    pt: {
      title: 'River Plate 2018',
      tagline: 'Identidade para time amador de baseball paulista — uniforme, escudo e linguagem visual.',
      client: 'Time Independente', role: 'Team Identity', scope: 'Crest · Uniforme',
      approach: 'A ilustração retrata o título conquistado em 2018 sobre o seu maior rival, o Boca Juniors.',
      outcome: '',
    },
    en: {
      title: 'River Plate 2018',
      tagline: 'Identity for an amateur São Paulo baseball team — kit, crest and visual language.',
      client: 'Independent Team', role: 'Team Identity', scope: 'Crest · Kit',
      approach: 'The illustration depicts the 2018 title won over their biggest rival, Boca Juniors.',
      outcome: '',
    },
  },
  'cblol': {
    year: '2022', hue: 200,
    pt: {
      title: 'CBLOL X Nike 2022',
      tagline: 'Conceito de uniformes Nike para as equipes do CBLOL — um sistema único aplicado à identidade de cada organização.',
      client: 'Projeto conceitual', role: 'Kit Design', scope: 'Uniformes · Esports',
      approach: 'Cada organização recebe uma identidade visual própria dentro de um sistema unificado para a liga. O design é desenvolvido considerando as características, cores e linguagem de cada equipe, com padronagens, elementos gráficos e posicionamento dos patrocínios pensados especificamente para cada organização, mantendo a unidade e o reconhecimento da competição como um todo.',
      outcome: '',
    },
    en: {
      title: 'CBLOL X Nike 2022',
      tagline: 'A Nike kit concept for the CBLOL teams — one system applied across each organization\'s identity.',
      client: 'Concept project', role: 'Kit Design', scope: 'Kits · Esports',
      approach: 'Each organization gets its own visual identity within a unified system for the league. The design considers the traits, colors and language of every team, with patterns, graphic elements and sponsor placement designed specifically for each organization, while preserving the unity and recognition of the competition as a whole.',
      outcome: '',
    },
  },
  'gym': {
    year: '2023', hue: 30,
    pt: {
      title: 'Stone',
      tagline: 'Campanhas internas educativas sobre saúde mental e alimentação saudável, em parceria com a Stone.',
      client: 'Stone', role: 'Campanhas internas', scope: 'Direção de arte · Conteúdo',
      approach: 'Projetos desenvolvidos pela Vitta em parceria com a Stone para a divulgação de campanhas internas educativas sobre os temas: saúde mental e alimentação saudável. O objetivo principal das ações foi conscientizar os colaboradores sobre a importância dos temas e os mecanismos de apoio que a empresa dispõe.',
      outcome: '',
      disclaimer: 'Direção de arte: Nicollas Monteiro\nDireção de conteúdo: Leandro Silva',
    },
    en: {
      title: 'Stone',
      tagline: 'Internal educational campaigns on mental health and healthy eating, in partnership with Stone.',
      client: 'Stone', role: 'Internal campaigns', scope: 'Art direction · Content',
      approach: 'Projects developed by Vitta in partnership with Stone for the dissemination of internal educational campaigns on the themes: mental health and healthy eating. The main objective of the campaigns was to make employees aware of the importance of the themes and the support mechanisms that the company has.',
      outcome: '',
      disclaimer: 'Art direction: Nicollas Monteiro\nContent direction: Leandro Silva',
    },
  },
  'mirassol': {
    year: '2025', hue: 70,
    pt: {
      title: 'Mirassol',
      tagline: 'Campanha visual para o acesso histórico do clube — fotografia, tipografia e cor amarela como protagonista.',
      client: 'Mirassol FC', role: 'Campanha', scope: 'Direção · Print · Social',
      approach: 'A Copa do Mundo é o momento em que o futebol brasileiro volta a inspirar o mundo. Mais do que uma competição, ela representa a esperança renovada a cada geração, o orgulho de nossas origens e a certeza de que o esporte continua sendo uma das maiores expressões da identidade do país.\n\nInspirada nesse sentimento, a colaboração entre Mirassol e Pelé celebra o primeiro raio de sol que anuncia um novo dia. Presente em toda a camisa, o grafismo em forma de raios simboliza o nascimento de novas histórias, a força que vem do interior e a luz que acompanha aqueles que acreditam que o futebol brasileiro sempre pode voltar a brilhar.',
      outcome: 'Mais do que uma homenagem ao maior jogador de todos os tempos, este projeto propõe um encontro entre legado e futuro. O amarelo representa a paixão que atravessa gerações, enquanto os raios de sol traduzem a esperança, a alegria e a criatividade que tornaram o futebol brasileiro uma referência mundial.\n\nDo interior paulista para o mundo, Mirassol e Pelé compartilham uma mesma mensagem: toda grande história começa com o nascer de um novo dia. E, enquanto houver uma bola rolando nas ruas, sempre haverá uma nova geração pronta para escrever o próximo capítulo do futebol brasileiro.',
    },
    en: {
      title: 'Mirassol',
      tagline: 'Visual campaign for the club\'s historic promotion — photography, typography and yellow as the lead.',
      client: 'Mirassol FC', role: 'Campaign', scope: 'Direction · Print · Social',
      approach: 'Symbolic photography in countryside settings, impactful condensed typography, color system anchored on the club\'s yellow.',
      outcome: 'Campaign published across billboards, social media and official materials.',
    },
  },
};

window.CASE_CONTENT = CASE_CONTENT;

// Per-case image sets. Each case follows the same shape order: half · half · full · half-tall · half-tall.
// Drop matching files into `assets/cases/<id>/` (header.png + 01..05.png) — they swap in automatically.
// Until the files exist, the gallery falls back to themed placeholders in the same layout.
function makeGallery(id) {
  return {
    banner: `assets/cases/${id}/header.png`,
    gallery: [
      { src: `assets/cases/${id}/01.png`, shape: 'half' },
      { src: `assets/cases/${id}/02.png`, shape: 'half' },
      { src: `assets/cases/${id}/03.png`, shape: 'full' },
      { src: `assets/cases/${id}/04.png`, shape: 'half-tall' },
      { src: `assets/cases/${id}/05.png`, shape: 'half-tall' },
    ],
  };
}

const CASE_IMAGES = {
  'cblol': {
    banner: 'assets/cases/cblol/header.png',
    gallery: [
      { src: 'assets/cases/cblol/02.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/03.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/05.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/04.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/06.png', shape: 'full', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/07.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/01.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/09.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/08.png', shape: 'half', ratio: '1400 / 788' },
      { src: 'assets/cases/cblol/10.png', shape: 'full', ratio: '1400 / 788' },
    ],
  },
  // velo-clube: explicit layout —
  // header (1velo) · full row (2velo) · 2×2 grid (3·4·5·6velo) · full row (7velo)
  'velo-clube': {
    banner: 'assets/cases/velo-clube/header.png',
    gallery: [
      { src: 'assets/cases/velo-clube/01.png', shape: 'full' },
      { src: 'assets/cases/velo-clube/02.png?v=2', shape: 'half' },
      { src: 'assets/cases/velo-clube/03.png', shape: 'half' },
      { src: 'assets/cases/velo-clube/04.png', shape: 'half' },
      { src: 'assets/cases/velo-clube/05.png', shape: 'half' },
      { src: 'assets/cases/velo-clube/06.png', shape: 'half' },
      { src: 'assets/cases/velo-clube/07.png', shape: 'half' },
      { src: 'assets/cases/velo-clube/08.png', shape: 'full' },
    ],
  },
  // Future cases — file paths reserved. Drop images into `assets/cases/<id>/` to activate.
  // To opt-in for placeholders (instead of broken-image until images arrive),
  // comment out the entry below — the gallery will render themed placeholders in the same layout.
  'inter': { banner: 'assets/cases/inter/header.png', gallery: [ { src: 'assets/cases/inter/03.png', shape: 'half', ratio: '1 / 1' }, { src: 'assets/cases/inter/04.png', shape: 'half', ratio: '1 / 1', breakAfter: true }, { src: 'assets/cases/inter/05.png', shape: 'half', ratio: '1043 / 1276' }, { src: 'assets/cases/inter/06.png', shape: 'half', ratio: '1043 / 1276' }, { src: 'assets/cases/inter/07.png', shape: 'full', ratio: '1670 / 939' } ] },
  // 'mevo':       makeGallery('mevo'),
  // 'portuguesa': makeGallery('portuguesa'),
  // 'padel':      makeGallery('padel'),
  // 'g3x':        makeGallery('g3x'),
  // 'gym':        makeGallery('gym'),
  // mirassol: wide hero/closer use the two panoramic shots (06, 05); portraits & squares fill the middle
  'mirassol': {
    banner: 'assets/cases/mirassol/header.png',
    gallery: [
      { src: 'assets/cases/mirassol/06.png', shape: 'full' },
      { src: 'assets/cases/mirassol/01.png', shape: 'half-tall' },
      { src: 'assets/cases/mirassol/04.png', shape: 'half-tall' },
      { src: 'assets/cases/mirassol/03.png', shape: 'half' },
      { src: 'assets/cases/mirassol/02.png', shape: 'half' },
      { src: 'assets/cases/mirassol/05.png', shape: 'full' },
    ],
  },
  // mevo: ordem numérica 01→14, diagramação do print (02 ao lado do par empilhado 03+04)
  'mevo': {
    banner: 'assets/cases/mevo/header.png',
    bannerPosition: 'center 26%',
    gallery: [
      { src: 'assets/cases/mevo/01.jpg', shape: 'full', ratio: '1815 / 976' },
      { src: 'assets/cases/mevo/02.jpg', shape: 'half', ratio: '881 / 976' },
      { stack: ['assets/cases/mevo/03.jpg', 'assets/cases/mevo/04.jpg'], shape: 'half', ratio: '881 / 976' },
      { src: 'assets/cases/mevo/05.jpg', shape: 'full', ratio: '1806 / 1203' },
      { src: 'assets/cases/mevo/06.jpg', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/mevo/07.jpg', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/mevo/08.jpg', shape: 'half', ratio: '88 / 100' },
      { src: 'assets/cases/mevo/09.jpg', shape: 'half', ratio: '88 / 100' },
      { src: 'assets/cases/mevo/10.jpg', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/mevo/11.jpg', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/mevo/12.jpg', shape: 'half', ratio: '881 / 798' },
      { src: 'assets/cases/mevo/13.jpg', shape: 'half', ratio: '881 / 798' },
      { src: 'assets/cases/mevo/14.jpg', shape: 'full', ratio: '1788 / 830' },
    ],
  },
  'gym': {
    banner: 'assets/cases/gym/header.png',
    gallery: [
      { src: 'assets/cases/gym/g1.png', shape: 'full', ratio: '16 / 9' },
      { src: 'assets/cases/gym/g2.png', shape: 'half', ratio: '16 / 9' },
      { src: 'assets/cases/gym/g3.png', shape: 'half', ratio: '16 / 9' },
      { src: 'assets/cases/gym/g4.png', shape: 'full', ratio: '16 / 9' },
      { src: 'assets/cases/gym/g6.png', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/gym/g7.png', shape: 'half', ratio: '89 / 100' },
      { src: 'assets/cases/gym/g5.png', shape: 'full', ratio: '2550 / 1000' },
    ],
  },
};
window.CASE_IMAGES = CASE_IMAGES;
window.makeCaseGallery = makeGallery;

// Localized UI strings for the case page chrome.
const CASE_COPY = {
  pt: {
    contact: 'Contato',
    back: 'Voltar ao início',
    client: 'Cliente', year: 'Ano', role: 'Papel', scope: 'Escopo',
    approach: 'Abordagem', outcome: 'Resultado',
    next: 'Próximo projeto',
    notFound: 'Projeto não encontrado.',
  },
  en: {
    contact: 'Contact',
    back: 'Back to home',
    client: 'Client', year: 'Year', role: 'Role', scope: 'Scope',
    approach: 'Approach', outcome: 'Outcome',
    next: 'Next project',
    notFound: 'Project not found.',
  },
};

// Shape pattern that the placeholder gallery uses — mirrors the real layout (2 · 1 full · 2).
const PLACEHOLDER_SHAPES = ['half', 'half', 'full', 'half-tall', 'half-tall'];

function CaseBanner({ data, images, lang }) {
  if (images && images.banner) {
    return (
      <div className="case-banner">
        <img src={images.banner} alt={`${data[lang].title} · header`} style={images.bannerPosition ? { objectPosition: images.bannerPosition } : undefined} />
      </div>
    );
  }
  return (
    <div className="case-banner">
      <PlaceholderMedia title={`${data[lang].title} · header`} hue={data.hue} tone={0.32} />
    </div>
  );
}

function CaseHero({ data, hasBanner, lang, copy }) {
  const t = data[lang];
  return (
    <section className={`container case-hero${hasBanner ? ' has-banner' : ''}`}>
      <a className="case-back" href="/">
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M7.5 2.5L4 6l3.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        {copy.back}
      </a>
      <h1 className="case-title reveal">{t.title}</h1>
      <div className="case-tagline reveal">{t.tagline.split(/\n{2,}/).map((para, i) => <p key={i} style={{margin: i ? '0.7em 0 0' : 0}}>{para}</p>)}</div>
      <div className="case-meta reveal">
        <div><b>{t.client}</b></div>
        <div><b>{t.role}</b></div>
        <div><b>{t.scope}</b></div>
      </div>
    </section>
  );
}

function CaseSection({ label, title, children, flush }) {
  return (
    <div className="container">
      <section className={`case-section${flush ? ' flush' : ''}`}>
        <div className="reveal">{label && <h3>{label}</h3>}</div>
        <div className="reveal">
          {title && <p style={{ fontWeight: 500 }}>{title}</p>}
          {children}
        </div>
      </section>
    </div>
  );
}

function CaseGallery({ data, lang, items }) {
  return (
    <div className="container">
      <div className="case-gallery">
        {items.map((it, i) => {
          const shape = it.shape || 'half';
          if (it.placeholder) {
            return (
              <div key={i} className={`item reveal ${shape}`} style={{ ['--i']: i }}>
                <PlaceholderMedia
                  title={`${data[lang].title} · ${String(it.idx ?? i + 1).padStart(2, '0')}`}
                  hue={(data.hue + i * 28) % 360}
                  tone={0.28 + (i % 3) * 0.07}
                />
              </div>
            );
          }
          if (it.stack) {
            return (
              <div key={i} className={`item stack reveal ${shape}`} style={{ ['--i']: i, aspectRatio: it.ratio || undefined }}>
                {it.stack.map((s, j) => (
                  <div className="cell" key={j}><img src={s} alt={`${data[lang].title} · ${i + 1}.${j + 1}`} loading="lazy" /></div>
                ))}
              </div>
            );
          }
          return (
            <div key={i} className={`item reveal ${shape}`} style={{ ['--i']: i, aspectRatio: it.ratio || undefined }}>
              <img src={it.src} alt={`${data[lang].title} · ${String(i + 1).padStart(2, '0')}`} loading="lazy" />
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CaseNext({ currentId, lang, copy }) {
  const list = window.PROJECTS;
  const idx = list.findIndex(p => p.id === currentId);
  const next = list[(idx + 1) % list.length];
  const nextData = CASE_CONTENT[next.id];
  const nextTitle = nextData ? nextData[lang].title : next.title;
  return (
    <div className="container">
      <section className="case-next">
        <a className="case-next-link" href={`/${next.slug || next.id}`}>
          <div className="case-next-info">
            <div className="case-next-label">{copy.next}</div>
            <span className="case-next-title">
              {nextTitle}
              <span className="arrow-lg"><ArrowIcon size={20} /></span>
            </span>
          </div>
          <div className="case-next-thumb">
            {next.img
              ? <img src={next.img} alt={nextTitle} loading="lazy" />
              : <PlaceholderMedia title={nextTitle} hue={nextData ? nextData.hue : 220} tone={0.3} />}
          </div>
        </a>
      </section>
    </div>
  );
}

function CaseApp() {
  const [tweaks, setTweak] = useTweaks({
    accent: 'white', font: 'inter', density: 'cozy', lang: 'pt',
  });

  React.useEffect(() => { applyAccent(tweaks.accent); }, [tweaks.accent]);
  React.useEffect(() => { applyType(tweaks.font); }, [tweaks.font]);
  React.useEffect(() => { applyDensity(tweaks.density); }, [tweaks.density]);

  useReveal();

  const params = new URLSearchParams(window.location.search);
  const pathSlug = window.location.pathname.replace(/^\/+|\/+$/g, '').replace(/\.html$/, '');
  const bySlug = (window.PROJECTS || []).find(p => (p.slug || p.id) === pathSlug);
  const id = (bySlug && bySlug.id) || params.get('id') || 'velo-clube';
  React.useEffect(() => {
    const p = (window.PROJECTS || []).find(x => x.id === id);
    if (!p) return;
    const clean = '/' + (p.slug || p.id);
    if (window.location.pathname !== clean || window.location.search) window.history.replaceState(null, '', clean + window.location.hash);
    document.title = p.title + ' · Nicollas Monteiro';
    let c = document.querySelector('link[rel="canonical"]');
    if (!c) { c = document.createElement('link'); c.rel = 'canonical'; document.head.appendChild(c); }
    c.href = 'https://nicollasmonteiro.com' + clean;
  }, [id]);
  const data = CASE_CONTENT[id];
  const images = CASE_IMAGES[id];
  const lang = tweaks.lang;
  const copy = CASE_COPY[lang] || CASE_COPY.pt;

  if (!data) {
    return <div style={{ padding: 80, textAlign: 'center' }}>{copy.notFound}</div>;
  }

  const toggleLang = () => setTweak('lang', lang === 'pt' ? 'en' : 'pt');

  // Build the gallery item list — either real images or placeholders matching the same layout.
  const galleryAll = (images && images.gallery)
    ? images.gallery
    : PLACEHOLDER_SHAPES.map((shape, i) => ({ shape, placeholder: true, idx: i + 1 }));

  // Split at the 'full' item: pieces above and below it bracket the "Approach" section.
  const markIdx = galleryAll.findIndex(it => it.breakAfter);
  const fullIdx = markIdx >= 0 ? markIdx : galleryAll.findIndex(it => it.shape === 'full');
  const splitIdx = fullIdx >= 0 ? fullIdx + 1 : galleryAll.length;
  const galleryTop    = galleryAll.slice(0, splitIdx);
  const galleryBottom = galleryAll.slice(splitIdx);
  const t = data[lang];

  return (
    <div data-screen-label={`Case · ${t.title}`}>
      <Header lang={lang} onToggleLang={toggleLang} copy={copy} />
      <CaseBanner data={data} images={images} lang={lang} />
      <CaseHero data={data} hasBanner={!!(images && images.banner)} lang={lang} copy={copy} />
      {galleryTop.length > 0 && (
        <CaseGallery data={data} lang={lang} items={galleryTop} />
      )}
      {t.approach && (
        <CaseSection label={copy.approach}>
          {t.approach.split(/\n{2,}/).map((para, i) => <p key={i}>{para}</p>)}
        </CaseSection>
      )}
      {galleryBottom.length > 0 && (
        <CaseGallery data={data} lang={lang} items={galleryBottom} />
      )}
      {(t.outcome || t.disclaimer) && (
        <CaseSection label={null}>
          {t.outcome && t.outcome.split(/\n{2,}/).map((para, i) => <p key={i}>{para}</p>)}
          {t.disclaimer && <p className="case-disclaimer">{t.disclaimer}</p>}
        </CaseSection>
      )}
      <CaseNext currentId={id} lang={lang} copy={copy} />
      <Footer />
    </div>
  );
}

// Header mirrors the index page — Instagram, language toggle, contact CTA.
function Header({ lang, onToggleLang, copy }) {
  const scrolled = (window.useScrolled ? window.useScrolled(20) : false);
  return (
    <header className={`topnav${scrolled ? ' scrolled' : ''}`}>
      <div className="topnav-inner">
        <a href="/" className="logo" aria-label="Início">
          <img src="assets/logo-nm.png" alt="Nicolas Monteiro" />
        </a>
        <nav className="nav-actions">
          <a className="nav-icon" href="#" aria-label="Instagram">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <rect x="1" y="1" width="12" height="12" rx="3" stroke="currentColor" strokeWidth="1.3" />
              <circle cx="7" cy="7" r="2.6" stroke="currentColor" strokeWidth="1.3" />
              <circle cx="10.4" cy="3.6" r="0.8" fill="currentColor" />
            </svg>
          </a>
          <button
            className="nav-lang"
            data-lang={lang}
            onClick={onToggleLang}
            aria-label="Idioma">
            <span className="nav-lang-thumb" />
            <span className="nav-lang-opt" data-v="pt">PT</span>
            <span className="nav-lang-opt" data-v="en">EN</span>
          </button>
          <a className="nav-cta" href="/#contact">{copy.contact}</a>
        </nav>
      </div>
    </header>
  );
}

function Footer() {
  return (
    <div className="container">
      <div className="footer-bar">
        <span>© 2026 — Nicollas Monteiro</span>
        <span>São Paulo / Worldwide</span>
      </div>
    </div>
  );
}

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