/* ═══════════════════════════════════════════════════════════════════════════
   PATRIMONI I RECURSOS — page bundle.

   Loads AFTER shared/components/{Nav,Footer,TweaksPanel}.jsx, so the shared
   components are available on `window`. We alias them locally for JSX use.

   ┌─────────────────────────────────────────────────────────────────────────┐
   │  CMS / HEADLESS INTEGRATION                                               │
   │  Sections fed by editorial collections use EsbartData.useCollection       │
   │  (shared/cms-data.js) and are flagged with a «DYNAMIC · CMS» banner        │
   │  naming the REST endpoint and the expected shape. Data goes live per       │
   │  collection at F1/F3; the seed arrays here are the migrated fallback       │
   │  content and the canonical schema.                                         │
   └─────────────────────────────────────────────────────────────────────────┘
   ═══════════════════════════════════════════════════════════════════════════ */

const { useState, useEffect, useMemo, useRef } = React;

/* Shared components (defined by the scripts loaded before this bundle) */
const EsbartNav = window.EsbartNav;
const EsbartFooter = window.EsbartFooter;
const EsbartTweaksPanel = window.EsbartTweaksPanel;

/* Global tweak seed (accent hue + type scale) — persisted via platform EditMode */
const ESBART_TWEAKS = /*EDITMODE-BEGIN*/{
  "accentHue": 350,
  "typeScale": 1
}/*EDITMODE-END*/;
window.ESBART_TWEAKS = ESBART_TWEAKS;

/* ───────────────────────────────────────────────────────────────────────────
   CMS DATA LAYER: shared/cms-data.js (window.EsbartData, ADR-06 D3).
   Paths WITHOUT /api/v1 (the module adds the base); the seed arrays here are
   the migrated fallback content and the canonical shape each map() must yield.
   Exposicions is LIVE (F1); danses is LIVE (F3). Still seeded: publicacions
   (GO-LIVE(post-F4), deferred by the client 2026-07-12 until the CMS content
   is curated).
   ─────────────────────────────────────────────────────────────────────────── */

const LOCALE = { ca: "ca-ES", es: "es-ES", en: "en-GB" };
function fmtDate(iso, lang) {
  try {
    return new Date(iso).toLocaleDateString(LOCALE[lang] || "ca-ES", { day: "numeric", month: "long", year: "numeric" });
  } catch (e) { return iso; }
}

/* ───────────────────────────────────────────────────────────────────────────
   Silhouette — line-art decoration injected from an SVG asset (mirrors Sobre).
   ─────────────────────────────────────────────────────────────────────────── */
function Silhouette({ src }) {
  const ref = useRef(null);
  useEffect(() => {
    let cancelled = false;
    fetch(src).then((r) => r.text()).then((txt) => {
      if (cancelled || !ref.current) return;
      ref.current.innerHTML = txt;
      const svg = ref.current.querySelector('svg');
      if (svg) {
        svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
        svg.setAttribute('aria-hidden', 'true');
      }
    }).catch(() => {});
    return () => { cancelled = true; };
  }, [src]);
  return <div ref={ref} className="pk-silhouette" aria-hidden="true"></div>;
}

/* Small inline icons */
const Arrow = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
    <path d="M5 12h14M13 6l6 6-6 6" />
  </svg>
);
const SearchIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
    <circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" />
  </svg>
);

/* ═══════════════════════════════════════════════════════════════════════════
   STRINGS — CA / ES / EN   (page-specific; merged with shared nav+footer dict)
   The `danses`, `publicacions`, `exposicions` arrays are the CMS seed/fallback.
   ═══════════════════════════════════════════════════════════════════════════ */
const PATRI_CA = {
  pageTitle: "Patrimoni i Recursos · Esbart Català de Dansaires",
  heroEyebrow: "Repertori · Documentació · Publicacions · Exposicions",
  heroTitle: ["El ", "patrimoni", " viu de la ", "dansa", " catalana"],
  heroLead: "Més de cent anys de recerca, recuperació i conservació del patrimoni immaterial de Catalunya: danses, arxius, biblioteca, publicacions i exposicions a l'abast de tothom.",
  heroStats: [
    { num: "1908", label: "Inici de l'arxiu documental" },
    { num: "8", label: "Exposicions de producció pròpia" },
    { num: "+100", label: "Anys de fons fotogràfic" },
  ],
  heroScroll: "Descobreix",

  // 1 — Repertori
  repEyebrow: "Repertori de danses tradicionals",
  repTitle: ["Danses ", "ballades", " i ", "recuperades"],
  repSub: "Un registre extens de danses catalanes ballades al llarg de la nostra història, junt amb les que l'Esbart ha reconstruït i tornat a la vida. Cerca per nom o població.",
  repSearchPh: "Cerca una dansa o població…",
  repFilters: [
    { id: "all", label: "Totes" },
    { id: "ballada", label: "Ballades" },
    { id: "recuperada", label: "Recuperades" },
  ],
  repCountLabel: "danses",
  repEmpty: "Cap dansa coincideix amb la cerca.",
  repShowingOf: "Es mostren {shown} de {total}",
  repLoadMore: "Carrega'n més",
  repTypeLabels: { ballada: "Ballada", recuperada: "Recuperada", catalogada: "Catalogada" },
  repMore: "Explora el repertori complet",
  danses: [
    { id: "d1", type: "ballada", name: "Cavallets Cotoners — Toc d'Inici", town: "Barcelona", region: "Barcelonès", desc: "La primera notícia documentada dels cavallets a Barcelona data de 1424, dins del Llibre de les Solemnitats de Barcelona." },
    { id: "d2", type: "ballada", name: "Ball de Carnestoltes", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "Es ballava al Prat fins a mitjan segle XIX; després caigué en desús fins a la represa a inicis del segle XX." },
    { id: "d3", type: "ballada", name: "Ball de Nans", town: "Les Planes d'Hostoles", region: "Garrotxa", desc: "A Catalunya hi ha diversos balls de nans, la majoria formats al llarg del segle XIX, cadascun amb coreografia pròpia." },
    { id: "d4", type: "ballada", name: "Ball del Punxonet", town: "Tortosa", region: "Baix Ebre", desc: "Pren el nom del gest dels balladors en aixecar el dit índex de cada mà mentre ballen." },
    { id: "d5", type: "recuperada", name: "Ball de Nyacres", town: "Roses", region: "Alt Empordà", desc: "Els pescadors de la badia de Roses la ballaven a la platja, marcant el ritme amb el so de les petxines (nyacres) a tall de castanyoles." },
    { id: "d6", type: "recuperada", name: "Ball Pla d'Olot", town: "Olot", region: "La Garrotxa", desc: "El 1994 Montserrat Garrich i Lluís Puig en recopilaren informació editada i inèdita a l'Aula de Dansa Tradicional." },
    { id: "d7", type: "recuperada", name: "La Ratolinesa", town: "Sant Julià de Vilatorta", region: "Osona", desc: "Fins ben entrat el segle XX es ballava la tarda del diumenge de Carnaval a Sant Julià de Vilatorta." },
    { id: "d8", type: "recuperada", name: "Ball del Tortell", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "Dansa recuperada per l'Esbart dins la tasca de reconstrucció del patrimoni coreogràfic local." },
  ],

  // 1b — Cronologia d'actuacions
  croEyebrow: "Historial d'actuacions",
  croTitle: ["Més d'un segle ", "d'actuacions", ", any a ", "any"],
  croSub: "El registre de les actuacions documentades de l'Esbart: on es va ballar, per quin motiu i amb quin programa. Tria una dècada i un any per resseguir-lo.",
  croStat: " actuacions documentades des de ",
  croProgram: "Programa",
  croEmpty: "Ara mateix no es pot mostrar aquest any. Torna-ho a provar més tard.",

  // 2 — Centre de documentació
  cdEyebrow: "Centre de Documentació",
  cdTitle: ["Un ", "arxiu", " i una ", "biblioteca", " de dansa catalana"],
  cdLead: "Tota la documentació, l'estudi i la recerca de l'entitat constitueixen el fons documental de l'Esbart, organitzat en dos grans apartats: l'arxiu i la biblioteca. Tots dos són de consulta pública i gratuïta, amb cita convinguda.",
  cdImgCaption: "La Casa dels Entremesos · seu de l'Esbart",
  cdCatalog: "Catàleg en línia",
  cdGroups: [
    {
      id: "arxiu", num: "01", title: "Arxiu",
      intro: "Organitzat el 1941 per voluntat d'Aureli Capmany a partir d'un projecte de 1910. Reuneix manuscrits, treballs de camp, fotografies, gràfics coreogràfics i buidats de premsa.",
      blocks: [
        { h: "Arxiu Aureli Capmany", items: ["Fitxer toponímic", "Fitxer gràfic", "Fitxer musical", "Fitxer calendari", "Fitxer de descripció de danses"] },
        { h: "Arxiu de dansa tradicional catalana", items: ["Fotografies", "Manuscrits", "Buidats de premsa", "Altres documents"] },
      ],
    },
    {
      id: "biblioteca", num: "02", title: "Biblioteca",
      intro: "Neix el 1926 per interès de Joan Amades, aleshores president, per posar a l'abast dels socis els materials publicats sobre dansa tradicional catalana i el seu context: indumentària, cançó, costums i festes.",
      blocks: [
        { h: "Seccions", items: ["Impresos (monografies, articles)", "Videoteca", "Fonoteca"] },
        { h: "Col·leccions especials", items: ["Història dels esbarts dansaires", "Biografies rellevants per a la dansa", "Publicacions periòdiques"] },
      ],
    },
    {
      id: "fons", num: "03", title: "Fons documental",
      intro: "Tota la documentació produïda per l'entitat des de la fundació, el 1908, amb ordenació cronològica de cada sèrie.",
      blocks: [
        { h: "Arxiu històric", items: ["Llibres d'actes", "Correspondència", "Documentació econòmica", "Memòries anuals i d'activitats"] },
        { h: "Altres fons", items: ["Arxiu fotogràfic (1908–avui)", "Arxiu de programes i cartells", "Fons ECD · Recull de premsa"] },
      ],
    },
    {
      id: "musical", num: "04", title: "Arxiu musical",
      intro: "La dansa catalana ha comptat amb grans instrumentadors i compositors que li han conferit una riquesa musical gairebé única dins la cultura popular. Des del 1908, l'Esbart ha recopilat i arxivat una gran quantitat de música de dansa, fet que el converteix en un dels arxius musicals de dansa catalana més rics i variats.",
      blocks: [
        { h: "Mestres i compositors", items: ["Mestre Font", "Bosch Humet", "Josep i Joaquim Serra", "Pujol", "Tomàs", "Cohí i Grau", "Albert"] },
        { h: "Tasca de recuperació musical", items: ["Transcripció de balls i danses", "Harmonització", "Instrumentació", "Conjunts instrumentals diversos"] },
      ],
    },
  ],

  // 3 — Inventari Danses Vives
  dvEyebrow: "Inventari de Danses Vives de Catalunya",
  dvTitle: ["Documentar ", "el que avui es balla", " als carrers i places"],
  dvBody: [
    "Amb el suport de la Direcció General de Cultura Popular, l'Institut Ramon Muntaner i el patrocini de La Caixa, l'Esbart impulsa l'Inventari de danses vives de Catalunya (IPCIDV).",
    "Seguint els criteris de l'Inventari del Patrimoni Etnològic de Catalunya, l'objectiu és inventariar tots els balls i danses que es ballen al país al llarg del calendari festiu anual.",
  ],
  dvCollab: "Hi podeu col·laborar balladors, mestres de dansa i mantenidors, aportant dades, imatges o informació sobre un ball.",
  dvBtn: "Visita dansesvives.cat",
  dvBtn2: "Com col·laborar",

  // 4 — Publicacions
  pubEyebrow: "Publicacions i investigacions",
  pubTitle: ["Un segle ", "publicant", " sobre la dansa"],
  pubSub: "Des de 1908, l'Esbart ha editat nombroses obres sobre dansa tradicional catalana. Una selecció del catàleg complet (1908–2023).",
  pubCatalog: "Catàleg complet de publicacions (PDF)",
  pubAwardLabel: "Premi Rafel Tudó",
  publicacions: [
    { id: "p1", title: "Aureli Capmany. La dansa i l'Esbart Català de Dansaires", author: "Montserrat Garrich (et al.)", year: "2018", format: "Llibre", desc: "Aproximació a la vida i obra del folklorista barceloní. Conté dos textos inèdits d'Aureli Capmany. Edició pels 150 anys del seu naixement." },
    { id: "p2", title: "Bastons! Història del Ball de Bastons a Vilafranca del Penedès", author: "Antoni Ribas Beltran", year: "2019", format: "Llibre", award: true, desc: "Colles, músiques, coreografies i relació de balladors a Vilafranca. Obra guanyadora del V Premi Rafel Tudó." },
    { id: "p3", title: "Apel·les Mestres, artista complet i home polièdric", author: "Montserrat Garrich", year: "2012", format: "Llibre", desc: "Biografia, bibliografia, discografia i obres inèdites de l'artista barceloní, amb els textos de l'exposició de 2012." },
    { id: "p4", title: "Aportacions a l'estudi de la dansa catalana", author: "Montserrat Garrich (Ed.)", year: "2008", format: "Llibre", desc: "Recull de les comunicacions presentades a la jornada Aportacions a la dansa catalana de 2004." },
    { id: "p5", title: "Aportacions a la dansa catalana 2009 · 2014 · 2020", author: "Diversos autors", year: "2009–2020", format: "Sèrie", desc: "Reculls de les comunicacions presentades a les jornades dels respectius anys." },
  ],
  presEyebrow: "Presentacions",
  presBody: "Nascuda el 1998 pel norantè aniversari de l'entitat, Presentacions difon novetats editorials sobre ball i dansa —pròpies o de tercers— mitjançant trameses informatives i actes a la seu social amb autors i editors.",
  aportEyebrow: "Aportacions a la dansa catalana",
  aportBody: "Espai per donar veu i difondre qualsevol aspecte relacionat amb la dansa tradicional. L'Esbart l'organitza cada cinc anys; la participació, com a ponent o públic, és oberta i gratuïta.",
  aportEditions: ["2004", "2009", "2014", "2020"],
  aportCta: "La jornada, a Activitats",

  // 5 — Exposicions
  expEyebrow: "Exposicions i materials divulgatius",
  expTitle: ["Vuit ", "exposicions", " per recórrer la nostra història"],
  expSub: "Totes es cedeixen a entitats, administracions i biblioteques sense cost (llevat del transport), amb muntatge autònom i ràpid.",
  expFilters: [
    { id: "propia", label: "Producció pròpia" },
    { id: "collab", label: "Col·laboracions" },
  ],
  // `href` → pàgina de detall. Al go-live, tota exposició publicada en tindrà
  // (derivat de l'id de l'API); al prototip només les dues amb mock.
  exposicions: [
    { id: "e1", kind: "propia", year: "2009", title: "Esbart Català de Dansaires 1908–2008: cent anys d'història" },
    { id: "e2", kind: "propia", year: "2012", title: "Apel·les Mestres, artista complet i home polièdric" },
    { id: "e3", kind: "propia", year: "2013", title: "Cavallets… endavant! Els Cavallets Cotoners de Barcelona" },
    { id: "e4", kind: "propia", year: "2015", title: "Joan Amades a l'Esbart. Soci i president", href: "Exposicio.html?mock=antiga" },
    { id: "e5", kind: "propia", year: "2016", title: "De pagès a típic. 100 anys dels vestits de l'Esbart" },
    { id: "e6", kind: "propia", year: "2018", title: "Aureli Capmany. La dansa i l'Esbart Català de Dansaires" },
    { id: "e7", kind: "propia", year: "2019", title: "110 imatges per 110 anys", href: "Exposicio.html" },
    { id: "e8", kind: "propia", year: "2020", title: "Coreografia archeologica" },
    { id: "e9", kind: "collab", year: "2014", title: "Setmana tràgica · Coordinadora de centres d'estudi i IRMU" },
    { id: "e10", kind: "collab", year: "2019", title: "Espai i festa: la transformació festiva de l'espai urbà" },
    { id: "e11", kind: "collab", year: "2021", title: "Octaves. La festa de Corpus als barris i viles de Barcelona" },
  ],
  expCede: "Cedir una exposició",

  // 6 — Vestuari
  vesEyebrow: "Vestuari, imatges i eines",
  vesTitle: ["El ", "vestuari", " de l'Esbart, des de 1913"],
  vesLead: "Al voltant de cada dansa catalana hi conflueixen circumstàncies socials, econòmiques i d'espai que n'han condicionat sempre la forma —i, molt especialment, el vestit.",
  vesIntro: [
    "Per això el vestuari canvia d'un ball a un altre i, fins i tot, dins d'un mateix ball. En una sola dansa hi poden conviure balladors amb vestits rics —gambeto i sabates— al costat d'altres amb espardenyes i robes més senzilles; i balladores amb vestits blancs i mantellines al costat de companyes amb indumentària modesta.",
    "La diferència es fa especialment visible en el vestit de les dones: mentre unes llueixen faldilles de tapisseria i cossos de vellut, altres vesteixen el brocat. No és caprici, sinó el reflex fidel de la condició social i de l'estatus de cada personatge.",
  ],
  vesFacets: [
    { h: "Segons la condició social", b: "L'estatus marca el vestit: des del gambeto, les sabates i el brocat dels més benestants fins a les espardenyes i les robes senzilles de qui tenia menys." },
    { h: "Segons la zona geogràfica", b: "Cada territori té el seu accent. A muntanya, per exemple, hi són típiques les caputxes, les samarres de be i les faldilles llargues de llana." },
    { h: "Segons el tipus de dansa", b: "Algunes danses tenen vestuari propi i inconfusible: els balls de nans, les moixigangues, les rentadores, les disfressades, les gitanes, els balls de bastons o les danses de cort." },
  ],
  vesOrigin: [
    "El vestuari de l'Esbart Català de Dansaires va néixer el 1913. Es basa en models que van de mitjan segle XVIII fins a les darreries del XIX.",
    "Cada dansa té el seu propi vestuari i cada dansaire vesteix un pèl diferent, tal com ho feia tothom en el seu temps: a la seva manera, però amb una mateixa coherència d'època.",
  ],
  vesOriginEyebrow: "Origen · des de 1913",
  vesCreditLabel: "Fons de referència",
  vesMuseuCredit: "Alguns models són reproduccions fidels de peces autèntiques conservades al Museu Tèxtil i d'Indumentària de Barcelona.",
  vesLexEyebrow: "El lèxic del vestuari",
  vesLexLead: "Un breu glossari de les peces i els complements que donen forma —i nom— a la indumentària de les danses.",
  vesLex: [
    { label: "Complements de la indumentària", items: [
      { t: "Cap-grossos (nans)", d: "Figures de cartó-pedra amb el cap desproporcionat que es vesteixen damunt del cos a les danses de nans." },
      { t: "Cintes i mocadors", d: "Tires de roba de colors i mocadors que articulen danses com el ball de cintes." },
      { t: "Davantals i mocadors de pit", d: "Peces de la indumentària femenina que protegeixen i, alhora, ornamenten el vestit." },
      { t: "Bastons i espases", d: "Estris rituals dels balls de bastons i de les danses d'espases." },
      { t: "Mantons", d: "Grans xals, sovint brodats, que cobreixen les espatlles de les balladores." },
    ] },
    { label: "Peces que ens distingeixen", items: [
      { t: "Morratxes", d: "Ampolles de vidre de diversos brocs per ruixar aigua perfumada en danses cerimonials." },
      { t: "Ret i mitenes", d: "La ret recull els cabells; les mitenes són guants de blonda sense dits." },
      { t: "Gambeto", d: "Abric llarg amb caputxa, propi de l'home benestant del segle XIX." },
      { t: "Faixes", d: "Llarga banda de roba enrotllada a la cintura, sovint vermella o morada." },
      { t: "Barretines", d: "El gorro de llana vermell o morat, símbol de la indumentària catalana." },
    ] },
  ],

  // 7 — Serveis
  srvEyebrow: "Serveis del Centre de Documentació",
  srvTitle: ["Un servei ", "obert a tothom", " i per a tothom"],
  srvSub: "A partir dels fons documentals, l'Esbart ofereix serveis de consulta, assessorament i suport a la recerca i la docència.",
  serveis: [
    { h: "Consulta", b: "Consulta gratuïta a tots els fons documentals, amb cita prèvia amb la Vocalia d'Arxiu i Biblioteca." },
    { h: "Assessorament", b: "A mitjans, centres educatius, administracions, entitats i estudiants de tots els nivells." },
    { h: "Servei bibliogràfic", b: "Localització de documentació publicada o inèdita sobre dansa tradicional catalana a Catalunya." },
    { h: "Servei de reproducció", b: "Reproducció de documentació segons la normativa interna de l'entitat." },
    { h: "Dipòsit de documentació", b: "Acollida de materials bibliogràfics i documentals sobre dansa, música, cançó i festes." },
    { h: "Reconstrucció de balls", b: "Assessorament, descripcions coreogràfiques i partitures per a la reconstrucció de danses." },
    { h: "Ensenyament", b: "Recursos i acompanyament a mestres i professors de qualsevol nivell educatiu." },
    { h: "Jornades i congressos", b: "Organització per encàrrec de jornades, congressos i taules rodones sobre dansa." },
  ],

  // CTA
  ctaEyebrow: "Arxiu i Biblioteca de Dansa Tradicional",
  ctaTitle: ["Vols ", "consultar", " els nostres fons?"],
  ctaLead: "La consulta és pública i gratuïta, amb cita convinguda. Escriu-nos i et posarem en contacte amb la Vocalia d'Arxiu i Biblioteca.",
  ctaBtn1: "Contacta amb el Centre",
  ctaBtn2: "Catàleg en línia",
};

const PATRI_ES = {
  pageTitle: "Patrimonio y Recursos · Esbart Català de Dansaires",
  heroEyebrow: "Repertorio · Documentación · Publicaciones · Exposiciones",
  heroTitle: ["El ", "patrimonio", " vivo de la ", "danza", " catalana"],
  heroLead: "Más de cien años de investigación, recuperación y conservación del patrimonio inmaterial de Cataluña: danzas, archivos, biblioteca, publicaciones y exposiciones al alcance de todos.",
  heroStats: [
    { num: "1908", label: "Inicio del archivo documental" },
    { num: "8", label: "Exposiciones de producción propia" },
    { num: "+100", label: "Años de fondo fotográfico" },
  ],
  heroScroll: "Descubre",
  repEyebrow: "Repertorio de danzas tradicionales",
  repTitle: ["Danzas ", "bailadas", " y ", "recuperadas"],
  repSub: "Un amplio registro de danzas catalanas bailadas a lo largo de nuestra historia, junto a las que el Esbart ha reconstruido. Busca por nombre o población.",
  repSearchPh: "Busca una danza o población…",
  repFilters: [
    { id: "all", label: "Todas" },
    { id: "ballada", label: "Bailadas" },
    { id: "recuperada", label: "Recuperadas" },
  ],
  repCountLabel: "danzas",
  repEmpty: "Ninguna danza coincide con la búsqueda.",
  repShowingOf: "Se muestran {shown} de {total}",
  repLoadMore: "Cargar más",
  repTypeLabels: { ballada: "Bailada", recuperada: "Recuperada", catalogada: "Catalogada" },
  repMore: "Explora el repertorio completo",
  danses: [
    { id: "d1", type: "ballada", name: "Cavallets Cotoners — Toc d'Inici", town: "Barcelona", region: "Barcelonès", desc: "La primera noticia documentada de los caballitos en Barcelona data de 1424, en el Llibre de les Solemnitats." },
    { id: "d2", type: "ballada", name: "Ball de Carnestoltes", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "Se bailaba en El Prat hasta mediados del siglo XIX; cayó en desuso hasta su recuperación a inicios del XX." },
    { id: "d3", type: "ballada", name: "Ball de Nans", town: "Les Planes d'Hostoles", region: "Garrotxa", desc: "En Cataluña hay varios bailes de enanos, la mayoría formados en el siglo XIX, cada uno con coreografía propia." },
    { id: "d4", type: "ballada", name: "Ball del Punxonet", town: "Tortosa", region: "Baix Ebre", desc: "Toma su nombre del gesto de levantar el dedo índice de cada mano mientras se baila." },
    { id: "d5", type: "recuperada", name: "Ball de Nyacres", town: "Roses", region: "Alt Empordà", desc: "Los pescadores de la bahía de Roses la bailaban en la playa, marcando el ritmo con conchas (nyacres) a modo de castañuelas." },
    { id: "d6", type: "recuperada", name: "Ball Pla d'Olot", town: "Olot", region: "La Garrotxa", desc: "En 1994 Montserrat Garrich y Lluís Puig recopilaron información editada e inédita en el Aula de Danza Tradicional." },
    { id: "d7", type: "recuperada", name: "La Ratolinesa", town: "Sant Julià de Vilatorta", region: "Osona", desc: "Hasta bien entrado el siglo XX se bailaba la tarde del domingo de Carnaval." },
    { id: "d8", type: "recuperada", name: "Ball del Tortell", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "Danza recuperada por el Esbart en su labor de reconstrucción del patrimonio coreográfico local." },
  ],
  croEyebrow: "Historial de actuaciones",
  croTitle: ["Más de un siglo ", "de actuaciones", ", año a ", "año"],
  croSub: "El registro de las actuaciones documentadas del Esbart: dónde se bailó, por qué motivo y con qué programa. Elige una década y un año para recorrerlo.",
  croStat: " actuaciones documentadas desde ",
  croProgram: "Programa",
  croEmpty: "Ahora mismo no se puede mostrar este año. Inténtalo de nuevo más tarde.",
  cdEyebrow: "Centro de Documentación",
  cdTitle: ["Un ", "archivo", " y una ", "biblioteca", " de danza catalana"],
  cdLead: "Toda la documentación, el estudio y la investigación de la entidad constituyen el fondo documental del Esbart, organizado en dos grandes apartados: el archivo y la biblioteca. Ambos son de consulta pública y gratuita, con cita previa.",
  cdImgCaption: "La Casa dels Entremesos · sede del Esbart",
  cdCatalog: "Catálogo en línea",
  cdGroups: [
    { id: "arxiu", num: "01", title: "Archivo", intro: "Organizado en 1941 por voluntad de Aureli Capmany a partir de un proyecto de 1910. Reúne manuscritos, trabajos de campo, fotografías, gráficos coreográficos y vaciados de prensa.", blocks: [
      { h: "Archivo Aureli Capmany", items: ["Fichero toponímico", "Fichero gráfico", "Fichero musical", "Fichero calendario", "Fichero de descripción de danzas"] },
      { h: "Archivo de danza tradicional catalana", items: ["Fotografías", "Manuscritos", "Vaciados de prensa", "Otros documentos"] },
    ] },
    { id: "biblioteca", num: "02", title: "Biblioteca", intro: "Nace en 1926 por interés de Joan Amades, entonces presidente, para acercar a los socios los materiales publicados sobre danza tradicional catalana y su contexto: indumentaria, canción, costumbres y fiestas.", blocks: [
      { h: "Secciones", items: ["Impresos (monografías, artículos)", "Videoteca", "Fonoteca"] },
      { h: "Colecciones especiales", items: ["Historia de los esbarts dansaires", "Biografías relevantes para la danza", "Publicaciones periódicas"] },
    ] },
    { id: "fons", num: "03", title: "Fondo documental", intro: "Toda la documentación producida por la entidad desde su fundación, en 1908, con ordenación cronológica de cada serie.", blocks: [
      { h: "Archivo histórico", items: ["Libros de actas", "Correspondencia", "Documentación económica", "Memorias anuales y de actividades"] },
      { h: "Otros fondos", items: ["Archivo fotográfico (1908–hoy)", "Archivo de programas y carteles", "Fondo ECD · Recopilación de prensa"] },
    ] },
    { id: "musical", num: "04", title: "Archivo musical", intro: "La danza catalana ha contado con grandes instrumentadores y compositores que le han conferido una riqueza musical casi única dentro de la cultura popular. Desde 1908, el Esbart ha recopilado y archivado una gran cantidad de música de danza, lo que lo convierte en uno de los archivos musicales de danza catalana más ricos y variados.", blocks: [
      { h: "Maestros y compositores", items: ["Maestro Font", "Bosch Humet", "Josep y Joaquim Serra", "Pujol", "Tomàs", "Cohí i Grau", "Albert"] },
      { h: "Labor de recuperación musical", items: ["Transcripción de bailes y danzas", "Armonización", "Instrumentación", "Conjuntos instrumentales diversos"] },
    ] },
  ],
  dvEyebrow: "Inventario de Danzas Vivas de Cataluña",
  dvTitle: ["Documentar ", "lo que hoy se baila", " en calles y plazas"],
  dvBody: [
    "Con el apoyo de la Dirección General de Cultura Popular, el Instituto Ramon Muntaner y el patrocinio de La Caixa, el Esbart impulsa el Inventario de danzas vivas de Cataluña (IPCIDV).",
    "Siguiendo los criterios del Inventario del Patrimonio Etnológico de Cataluña, el objetivo es inventariar todos los bailes y danzas que se bailan en el país a lo largo del calendario festivo anual.",
  ],
  dvCollab: "Pueden colaborar bailadores, maestros de danza y mantenedores, aportando datos, imágenes o información sobre un baile.",
  dvBtn: "Visita dansesvives.cat",
  dvBtn2: "Cómo colaborar",
  pubEyebrow: "Publicaciones e investigaciones",
  pubTitle: ["Un siglo ", "publicando", " sobre la danza"],
  pubSub: "Desde 1908, el Esbart ha editado numerosas obras sobre danza tradicional catalana. Una selección del catálogo completo (1908–2023).",
  pubCatalog: "Catálogo completo de publicaciones (PDF)",
  pubAwardLabel: "Premio Rafel Tudó",
  publicacions: [
    { id: "p1", title: "Aureli Capmany. La danza y el Esbart Català de Dansaires", author: "Montserrat Garrich (et al.)", year: "2018", format: "Libro", desc: "Aproximación a la vida y obra del folklorista barcelonés. Contiene dos textos inéditos. Edición por los 150 años de su nacimiento." },
    { id: "p2", title: "Bastons! Historia del Ball de Bastons en Vilafranca del Penedès", author: "Antoni Ribas Beltran", year: "2019", format: "Libro", award: true, desc: "Cuadrillas, músicas, coreografías y relación de bailadores. Obra ganadora del V Premio Rafel Tudó." },
    { id: "p3", title: "Apel·les Mestres, artista completo y hombre poliédrico", author: "Montserrat Garrich", year: "2012", format: "Libro", desc: "Biografía, bibliografía, discografía y obras inéditas del artista barcelonés, con los textos de la exposición de 2012." },
    { id: "p4", title: "Aportaciones al estudio de la danza catalana", author: "Montserrat Garrich (Ed.)", year: "2008", format: "Libro", desc: "Recopilación de las comunicaciones presentadas en la jornada Aportaciones a la danza catalana de 2004." },
    { id: "p5", title: "Aportaciones a la danza catalana 2009 · 2014 · 2020", author: "Varios autores", year: "2009–2020", format: "Serie", desc: "Recopilaciones de las comunicaciones presentadas en las jornadas de los respectivos años." },
  ],
  presEyebrow: "Presentaciones",
  presBody: "Nacida en 1998 por el nonagésimo aniversario, Presentaciones difunde novedades editoriales sobre danza —propias o de terceros— mediante envíos informativos y actos en la sede con autores y editores.",
  aportEyebrow: "Aportaciones a la danza catalana",
  aportBody: "Espacio para dar voz y difundir cualquier aspecto relacionado con la danza tradicional. El Esbart lo organiza cada cinco años; la participación, como ponente o público, es abierta y gratuita.",
  aportEditions: ["2004", "2009", "2014", "2020"],
  aportCta: "La jornada, en Actividades",
  expEyebrow: "Exposiciones y materiales divulgativos",
  expTitle: ["Ocho ", "exposiciones", " para recorrer nuestra historia"],
  expSub: "Todas se ceden a entidades, administraciones y bibliotecas sin coste (salvo el transporte), con montaje autónomo y rápido.",
  expFilters: [
    { id: "propia", label: "Producción propia" },
    { id: "collab", label: "Colaboraciones" },
  ],
  exposicions: [
    { id: "e1", kind: "propia", year: "2009", title: "Esbart Català de Dansaires 1908–2008: cien años de historia" },
    { id: "e2", kind: "propia", year: "2012", title: "Apel·les Mestres, artista completo y hombre poliédrico" },
    { id: "e3", kind: "propia", year: "2013", title: "Cavallets… endavant! Los Cavallets Cotoners de Barcelona" },
    { id: "e4", kind: "propia", year: "2015", title: "Joan Amades en el Esbart. Socio y presidente", href: "Exposicio.html?mock=antiga" },
    { id: "e5", kind: "propia", year: "2016", title: "De payés a típico. 100 años de los trajes del Esbart" },
    { id: "e6", kind: "propia", year: "2018", title: "Aureli Capmany. La danza y el Esbart Català de Dansaires" },
    { id: "e7", kind: "propia", year: "2019", title: "110 imágenes por 110 años", href: "Exposicio.html" },
    { id: "e8", kind: "propia", year: "2020", title: "Coreografia archeologica" },
    { id: "e9", kind: "collab", year: "2014", title: "Setmana tràgica · Coordinadora de centros de estudio e IRMU" },
    { id: "e10", kind: "collab", year: "2019", title: "Espai i festa: la transformación festiva del espacio urbano" },
    { id: "e11", kind: "collab", year: "2021", title: "Octaves. La fiesta de Corpus en los barrios y villas de Barcelona" },
  ],
  expCede: "Ceder una exposición",
  vesEyebrow: "Vestuario, imágenes y herramientas",
  vesTitle: ["El ", "vestuario", " del Esbart, desde 1913"],
  vesLead: "En torno a cada danza catalana confluyen circunstancias sociales, económicas y de espacio que siempre han condicionado su forma —y, muy especialmente, el vestido.",
  vesIntro: [
    "Por eso el vestuario cambia de un baile a otro e, incluso, dentro de un mismo baile. En una sola danza pueden convivir bailadores con trajes ricos —gambeto y zapatos— junto a otros con alpargatas y ropas más sencillas; y bailadoras con vestidos blancos y mantillas junto a compañeras con indumentaria modesta.",
    "La diferencia se hace especialmente visible en el vestido de las mujeres: mientras unas lucen faldas de tapicería y cuerpos de terciopelo, otras visten el brocado. No es capricho, sino el reflejo fiel de la condición social y del estatus de cada personaje.",
  ],
  vesFacets: [
    { h: "Según la condición social", b: "El estatus marca el vestido: desde el gambeto, los zapatos y el brocado de los más acomodados hasta las alpargatas y las ropas sencillas de quien tenía menos." },
    { h: "Según la zona geográfica", b: "Cada territorio tiene su acento. En la montaña, por ejemplo, son típicas las capuchas, las zamarras de piel de oveja y las faldas largas de lana." },
    { h: "Según el tipo de danza", b: "Algunas danzas tienen vestuario propio e inconfundible: los bailes de enanos, las moixigangas, las lavanderas, las disfrazadas, las gitanas, los bailes de bastones o las danzas de corte." },
  ],
  vesOrigin: [
    "El vestuario del Esbart Català de Dansaires nació en 1913. Se basa en modelos que van de mediados del siglo XVIII hasta finales del XIX.",
    "Cada danza tiene su propio vestuario y cada bailador viste un poco distinto, tal como lo hacía todo el mundo en su tiempo: a su manera, pero con una misma coherencia de época.",
  ],
  vesOriginEyebrow: "Origen · desde 1913",
  vesCreditLabel: "Fondo de referencia",
  vesMuseuCredit: "Algunos modelos son reproducciones fieles de piezas auténticas conservadas en el Museo Textil y de Indumentaria de Barcelona.",
  vesGalleryCaps: [
    "Capas y mantillas en la plaza",
    "Vestido de corte y brocado",
    "Brocado amarillo y barretina",
    "Camisa de rayas y pañuelo",
    "Fajas y cuerpos blancos",
    "Disfrazadas en danza nocturna",
    "Delantales y fajas de color",
  ],
  vesLexEyebrow: "El léxico del vestuario",
  vesLexLead: "Un breve glosario de las piezas y los complementos que dan forma —y nombre— a la indumentaria de las danzas.",
  vesLex: [
    { label: "Complementos de la indumentaria", items: [
      { t: "Cabezudos (enanos)", d: "Figuras de cartón-piedra con la cabeza desproporcionada que se visten sobre el cuerpo en las danzas de enanos." },
      { t: "Cintas y pañuelos", d: "Tiras de tela de colores y pañuelos que articulan danzas como el baile de cintas." },
      { t: "Delantales y pañuelos de pecho", d: "Piezas de la indumentaria femenina que protegen y, a la vez, adornan el vestido." },
      { t: "Bastones y espadas", d: "Útiles rituales de los bailes de bastones y de las danzas de espadas." },
      { t: "Mantones", d: "Grandes chales, a menudo bordados, que cubren los hombros de las bailadoras." },
    ] },
    { label: "Piezas que nos distinguen", items: [
      { t: "Morratxes", d: "Botellas de vidrio de varios picos para rociar agua perfumada en danzas ceremoniales." },
      { t: "Redecilla y mitones", d: "La redecilla recoge el cabello; los mitones son guantes de blonda sin dedos." },
      { t: "Gambeto", d: "Abrigo largo con capucha, propio del hombre acomodado del siglo XIX." },
      { t: "Fajas", d: "Larga banda de tela enrollada a la cintura, a menudo roja o morada." },
      { t: "Barretinas", d: "El gorro de lana rojo o morado, símbolo de la indumentaria catalana." },
    ] },
  ],
  srvEyebrow: "Servicios del Centro de Documentación",
  srvTitle: ["Un servicio ", "abierto a todos", " y para todos"],
  srvSub: "A partir de los fondos documentales, el Esbart ofrece servicios de consulta, asesoramiento y apoyo a la investigación y la docencia.",
  serveis: [
    { h: "Consulta", b: "Consulta gratuita a todos los fondos documentales, con cita previa con la Vocalía de Archivo y Biblioteca." },
    { h: "Asesoramiento", b: "A medios, centros educativos, administraciones, entidades y estudiantes de todos los niveles." },
    { h: "Servicio bibliográfico", b: "Localización de documentación publicada o inédita sobre danza tradicional catalana en Cataluña." },
    { h: "Servicio de reproducción", b: "Reproducción de documentación según la normativa interna de la entidad." },
    { h: "Depósito de documentación", b: "Acogida de materiales bibliográficos y documentales sobre danza, música, canción y fiestas." },
    { h: "Reconstrucción de bailes", b: "Asesoramiento, descripciones coreográficas y partituras para la reconstrucción de danzas." },
    { h: "Enseñanza", b: "Recursos y acompañamiento a maestros y profesores de cualquier nivel educativo." },
    { h: "Jornadas y congresos", b: "Organización por encargo de jornadas, congresos y mesas redondas sobre danza." },
  ],
  ctaEyebrow: "Archivo y Biblioteca de Danza Tradicional",
  ctaTitle: ["¿Quieres ", "consultar", " nuestros fondos?"],
  ctaLead: "La consulta es pública y gratuita, con cita previa. Escríbenos y te pondremos en contacto con la Vocalía de Archivo y Biblioteca.",
  ctaBtn1: "Contacta con el Centro",
  ctaBtn2: "Catálogo en línea",
};

const PATRI_EN = {
  pageTitle: "Heritage & Resources · Esbart Català de Dansaires",
  heroEyebrow: "Repertoire · Archive · Publications · Exhibitions",
  heroTitle: ["The living ", "heritage", " of ", "Catalan dance"],
  heroLead: "Over a century of research, recovery and preservation of Catalonia's intangible heritage: dances, archives, library, publications and exhibitions open to everyone.",
  heroStats: [
    { num: "1908", label: "Start of the document archive" },
    { num: "8", label: "In-house exhibitions" },
    { num: "+100", label: "Years of photographic holdings" },
  ],
  heroScroll: "Discover",
  repEyebrow: "Traditional dance repertoire",
  repTitle: ["Danced ", "& ", "recovered", " dances"],
  repSub: "An extensive register of Catalan dances performed throughout our history, alongside those the Esbart has reconstructed. Search by name or town.",
  repSearchPh: "Search a dance or town…",
  repFilters: [
    { id: "all", label: "All" },
    { id: "ballada", label: "Danced" },
    { id: "recuperada", label: "Recovered" },
  ],
  repCountLabel: "dances",
  repEmpty: "No dance matches your search.",
  repShowingOf: "Showing {shown} of {total}",
  repLoadMore: "Load more",
  repTypeLabels: { ballada: "Danced", recuperada: "Recovered", catalogada: "Catalogued" },
  repMore: "Explore the full repertoire",
  danses: [
    { id: "d1", type: "ballada", name: "Cavallets Cotoners — Opening", town: "Barcelona", region: "Barcelonès", desc: "The first documented record of the cavallets in Barcelona dates to 1424, in the Book of Solemnities of Barcelona." },
    { id: "d2", type: "ballada", name: "Ball de Carnestoltes", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "Danced in El Prat until the mid-19th century; it then fell into disuse until its revival in the early 20th century." },
    { id: "d3", type: "ballada", name: "Ball de Nans", town: "Les Planes d'Hostoles", region: "Garrotxa", desc: "Catalonia has several dwarf dances, mostly formed during the 19th century, each with its own choreography." },
    { id: "d4", type: "ballada", name: "Ball del Punxonet", town: "Tortosa", region: "Baix Ebre", desc: "Named after the dancers' gesture of raising the index finger of each hand while dancing." },
    { id: "d5", type: "recuperada", name: "Ball de Nyacres", town: "Roses", region: "Alt Empordà", desc: "Fishermen of the bay of Roses danced it on the beach, keeping time with shells (nyacres) used as castanets." },
    { id: "d6", type: "recuperada", name: "Ball Pla d'Olot", town: "Olot", region: "La Garrotxa", desc: "In 1994 Montserrat Garrich and Lluís Puig gathered published and unpublished material at the Traditional Dance classroom." },
    { id: "d7", type: "recuperada", name: "La Ratolinesa", town: "Sant Julià de Vilatorta", region: "Osona", desc: "Well into the 20th century it was danced on the afternoon of Carnival Sunday." },
    { id: "d8", type: "recuperada", name: "Ball del Tortell", town: "El Prat de Llobregat", region: "Baix Llobregat", desc: "A dance recovered by the Esbart as part of its work reconstructing local choreographic heritage." },
  ],
  croEyebrow: "Performance history",
  croTitle: ["Over a century ", "of performances", ", year by ", "year"],
  croSub: "The record of the Esbart's documented performances: where they danced, on what occasion and with which programme. Pick a decade and a year to browse it.",
  croStat: " performances documented since ",
  croProgram: "Programme",
  croEmpty: "This year can't be shown right now. Please try again later.",
  cdEyebrow: "Documentation Centre",
  cdTitle: ["An ", "archive", " and a ", "library", " of Catalan dance"],
  cdLead: "All the entity's documentation, study and research make up the Esbart's holdings, organised into two main sections: the archive and the library. Both are open to the public, free of charge, by appointment.",
  cdImgCaption: "La Casa dels Entremesos · seat of the Esbart",
  cdCatalog: "Online catalogue",
  cdGroups: [
    { id: "arxiu", num: "01", title: "Archive", intro: "Organised in 1941 by Aureli Capmany, building on a 1910 project. It gathers manuscripts, fieldwork, photographs, choreographic diagrams and press clippings.", blocks: [
      { h: "Aureli Capmany Archive", items: ["Place-name file", "Graphic file", "Music file", "Calendar file", "Dance description file"] },
      { h: "Catalan traditional dance archive", items: ["Photographs", "Manuscripts", "Press clippings", "Other documents"] },
    ] },
    { id: "biblioteca", num: "02", title: "Library", intro: "Founded in 1926 by Joan Amades, then president, to give members access to published materials on Catalan traditional dance and its context: costume, song, customs and festivals.", blocks: [
      { h: "Sections", items: ["Print (monographs, articles)", "Video library", "Sound library"] },
      { h: "Special collections", items: ["History of the esbarts", "Key biographies in dance", "Periodical publications"] },
    ] },
    { id: "fons", num: "03", title: "Documentary holdings", intro: "All the documentation produced by the entity since its founding in 1908, with each series ordered chronologically.", blocks: [
      { h: "Historical archive", items: ["Minute books", "Correspondence", "Financial records", "Annual & activity reports"] },
      { h: "Other holdings", items: ["Photographic archive (1908–today)", "Programmes & posters archive", "ECD holdings · Press collection"] },
    ] },
    { id: "musical", num: "04", title: "Music archive", intro: "Catalan dance has been served by great arrangers and composers who gave it a musical richness almost unique within popular culture. Since 1908 the Esbart has compiled and archived a vast amount of dance music, making it one of the richest and most varied Catalan dance music archives.", blocks: [
      { h: "Masters & composers", items: ["Mestre Font", "Bosch Humet", "Josep & Joaquim Serra", "Pujol", "Tomàs", "Cohí i Grau", "Albert"] },
      { h: "Musical recovery work", items: ["Transcription of dances", "Harmonisation", "Instrumentation", "Varied instrumental ensembles"] },
    ] },
  ],
  dvEyebrow: "Inventory of Living Dances of Catalonia",
  dvTitle: ["Documenting ", "what is danced today", " in streets and squares"],
  dvBody: [
    "With support from the Directorate-General for Popular Culture, the Ramon Muntaner Institute and La Caixa, the Esbart leads the Inventory of Living Dances of Catalonia (IPCIDV).",
    "Following the criteria of the Ethnological Heritage Inventory of Catalonia, the goal is to catalogue every dance performed across the country throughout the annual festive calendar.",
  ],
  dvCollab: "Dancers, dance masters and custodians can contribute data, images or information about a dance.",
  dvBtn: "Visit dansesvives.cat",
  dvBtn2: "How to contribute",
  pubEyebrow: "Publications & research",
  pubTitle: ["A century ", "publishing", " on dance"],
  pubSub: "Since 1908 the Esbart has published numerous works on Catalan traditional dance. A selection from the full catalogue (1908–2023).",
  pubCatalog: "Full publications catalogue (PDF)",
  pubAwardLabel: "Rafel Tudó Award",
  publicacions: [
    { id: "p1", title: "Aureli Capmany. Dance and the Esbart Català de Dansaires", author: "Montserrat Garrich (et al.)", year: "2018", format: "Book", desc: "A study of the life and work of the Barcelona folklorist. Includes two unpublished texts. Issued for the 150th anniversary of his birth." },
    { id: "p2", title: "Bastons! History of the Ball de Bastons in Vilafranca del Penedès", author: "Antoni Ribas Beltran", year: "2019", format: "Book", award: true, desc: "Stick-dance groups, music, choreography and dancers. Winner of the V Rafel Tudó Award." },
    { id: "p3", title: "Apel·les Mestres, a complete and many-sided artist", author: "Montserrat Garrich", year: "2012", format: "Book", desc: "Biography, bibliography, discography and unpublished works of the Barcelona artist, with the 2012 exhibition texts." },
    { id: "p4", title: "Contributions to the study of Catalan dance", author: "Montserrat Garrich (Ed.)", year: "2008", format: "Book", desc: "A collection of the papers presented at the 2004 Contributions to Catalan Dance symposium." },
    { id: "p5", title: "Contributions to Catalan Dance 2009 · 2014 · 2020", author: "Various authors", year: "2009–2020", format: "Series", desc: "Collections of the papers presented at the symposia of the respective years." },
  ],
  presEyebrow: "Presentations",
  presBody: "Born in 1998 for the entity's 90th anniversary, Presentations shares new dance publications —its own and others'— through information mailings and events at the headquarters with authors and editors.",
  aportEyebrow: "Contributions to Catalan dance",
  aportBody: "A space to give voice to and share any aspect of traditional dance. The Esbart organises it every five years; participation, as speaker or audience, is open and free.",
  aportEditions: ["2004", "2009", "2014", "2020"],
  aportCta: "The gathering, in Activities",
  expEyebrow: "Exhibitions & outreach materials",
  expTitle: ["Eight ", "exhibitions", " to walk through our history"],
  expSub: "All are loaned to organisations, public bodies and libraries free of charge (except transport), with quick, self-contained assembly.",
  expFilters: [
    { id: "propia", label: "In-house" },
    { id: "collab", label: "Collaborations" },
  ],
  exposicions: [
    { id: "e1", kind: "propia", year: "2009", title: "Esbart Català de Dansaires 1908–2008: a hundred years of history" },
    { id: "e2", kind: "propia", year: "2012", title: "Apel·les Mestres, a complete and many-sided artist" },
    { id: "e3", kind: "propia", year: "2013", title: "Cavallets… onward! The Cavallets Cotoners of Barcelona" },
    { id: "e4", kind: "propia", year: "2015", title: "Joan Amades at the Esbart. Member and president", href: "Exposicio.html?mock=antiga" },
    { id: "e5", kind: "propia", year: "2016", title: "From peasant to typical. 100 years of the Esbart's costumes" },
    { id: "e6", kind: "propia", year: "2018", title: "Aureli Capmany. Dance and the Esbart Català de Dansaires" },
    { id: "e7", kind: "propia", year: "2019", title: "110 images for 110 years", href: "Exposicio.html" },
    { id: "e8", kind: "propia", year: "2020", title: "Coreografia archeologica" },
    { id: "e9", kind: "collab", year: "2014", title: "Tragic Week · Coordinator of study centres & IRMU" },
    { id: "e10", kind: "collab", year: "2019", title: "Space and festival: the festive transformation of urban space" },
    { id: "e11", kind: "collab", year: "2021", title: "Octaves. The Corpus festival in Barcelona's quarters and towns" },
  ],
  expCede: "Loan an exhibition",
  vesEyebrow: "Costume, images & tools",
  vesTitle: ["The Esbart's ", "costume", ", since 1913"],
  vesLead: "Around every Catalan dance there converge social, economic and spatial circumstances that have always shaped its form —and, above all, its dress.",
  vesIntro: [
    "That is why the costume changes from one dance to another, and even within a single dance. In one dance you may find dancers in rich attire —gambeto and shoes— alongside others in espadrilles and plainer clothes; and women in white dresses and mantillas next to companions in modest dress.",
    "The difference is clearest in the women's dress: while some wear tapestry skirts and velvet bodices, others wear brocade. It is no whim, but a faithful reflection of each character's social standing and status.",
  ],
  vesFacets: [
    { h: "By social standing", b: "Status shaped the dress: from the gambeto, shoes and brocade of the well-off to the espadrilles and simple clothes of those with less." },
    { h: "By geographic area", b: "Each territory has its own accent. In the mountains, for instance, hoods, sheepskin jackets and long woollen skirts are typical." },
    { h: "By type of dance", b: "Some dances have their own unmistakable costume: the dwarf dances, the moixigangues, the washerwomen, the masqueraders, the gypsies, the stick dances or the court dances." },
  ],
  vesOrigin: [
    "The Esbart Català de Dansaires' costume was born in 1913. It draws on models from the mid-18th to the late 19th century.",
    "Each dance has its own costume and each dancer dresses a little differently, just as everyone did in their day: in their own way, yet with a shared sense of period.",
  ],
  vesOriginEyebrow: "Origin · since 1913",
  vesCreditLabel: "Reference collection",
  vesMuseuCredit: "Some models are faithful reproductions of authentic pieces held at the Textile and Clothing Museum of Barcelona.",
  vesGalleryCaps: [
    "Capes and mantillas in the square",
    "Court costume and brocade",
    "Yellow brocade and barretina",
    "Striped shirt and kerchief",
    "Sashes and white bodices",
    "Masked figures in a night dance",
    "Aprons and coloured sashes",
  ],
  vesLexEyebrow: "The costume lexicon",
  vesLexLead: "A brief glossary of the pieces and accessories that give shape —and name— to the dances' attire.",
  vesLex: [
    { label: "Costume accessories", items: [
      { t: "Big-heads (dwarfs)", d: "Papier-mâché figures with oversized heads worn over the body in the dwarf dances." },
      { t: "Ribbons & kerchiefs", d: "Coloured fabric strips and kerchiefs that drive dances such as the ribbon dance." },
      { t: "Aprons & chest kerchiefs", d: "Pieces of the women's costume that both protect and adorn the dress." },
      { t: "Sticks & swords", d: "Ritual implements of the stick dances and the sword dances." },
      { t: "Shawls", d: "Large, often embroidered shawls draped over the dancers' shoulders." },
    ] },
    { label: "Pieces that set us apart", items: [
      { t: "Morratxes", d: "Multi-spouted glass flasks for sprinkling scented water in ceremonial dances." },
      { t: "Hairnet & mittens", d: "The net gathers the hair; the mittens are fingerless lace gloves." },
      { t: "Gambeto", d: "A long hooded overcoat, typical of the well-to-do 19th-century man." },
      { t: "Sashes", d: "A long band of cloth wound at the waist, often red or purple." },
      { t: "Barretinas", d: "The red or purple woollen cap, the emblem of Catalan dress." },
    ] },
  ],
  srvEyebrow: "Documentation Centre services",
  srvTitle: ["A service ", "open to all", ", for all"],
  srvSub: "Drawing on its holdings, the Esbart offers consultation, advice and support for research and teaching.",
  serveis: [
    { h: "Consultation", b: "Free consultation of all holdings, by appointment with the Archive & Library officer." },
    { h: "Advice", b: "For media, schools, public bodies, organisations and students of every level." },
    { h: "Bibliographic service", b: "Locating published or unpublished documentation on Catalan traditional dance in Catalonia." },
    { h: "Reproduction service", b: "Reproduction of documentation according to the entity's internal rules." },
    { h: "Document deposit", b: "Hosting bibliographic and documentary materials on dance, music, song and festivals." },
    { h: "Dance reconstruction", b: "Advice, choreographic descriptions and scores for reconstructing dances." },
    { h: "Teaching", b: "Resources and support for teachers at any educational level." },
    { h: "Symposia & congresses", b: "Commissioned organisation of symposia, congresses and round tables on dance." },
  ],
  ctaEyebrow: "Traditional Dance Archive & Library",
  ctaTitle: ["Want to ", "consult", " our holdings?"],
  ctaLead: "Consultation is public and free, by appointment. Write to us and we'll connect you with the Archive & Library officer.",
  ctaBtn1: "Contact the Centre",
  ctaBtn2: "Online catalogue",
};

const PATRI_STRINGS = { ca: PATRI_CA, es: PATRI_ES, en: PATRI_EN };

/* ═══════════════════════════════════════════════════════════════════════════
   SECTIONS
   ═══════════════════════════════════════════════════════════════════════════ */

function Hero({ t }) {
  return (
    <header className="pk-hero" id="inici">
      <div className="pk-hero__bg" aria-hidden="true"></div>
      <Silhouette src="assets/ecd-silhouette.svg" />
      <div className="wrap">
        <div className="pk-hero__eyebrow">{t.heroEyebrow}</div>
        <h1 className="pk-hero__title">
          {t.heroTitle[0]}<em>{t.heroTitle[1]}</em>{t.heroTitle[2]}<em>{t.heroTitle[3]}</em>{t.heroTitle[4]}
        </h1>
        <p className="pk-hero__lead">{t.heroLead}</p>
        <div className="pk-hero__meta">
          {t.heroStats.map((s, i) => (
            <div key={i} className="pk-hero__meta-item">
              <div className="pk-hero__meta-num">{s.num}</div>
              <div className="pk-hero__meta-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="pk-hero__scroll" aria-hidden="true">{t.heroScroll}</div>
    </header>
  );
}

/* ╔═══════════════════════════════════════════════════════════════════════════╗
   ║  DYNAMIC · CMS — DANCE REPERTOIRE                                          ║
   ║  Endpoint : GET /api/v1/danses?lang={lang}&type={all|ballada|recuperada}  ║
   ║             &q={query}                                                     ║
   ║  Item     : { id, type:'ballada'|'recuperada'|null, name, town, region,  ║
   ║             desc } — null type renders as «Catalogada» (the CMS's own    ║
   ║             label for dances documented but neither danced nor recovered).║
   ║  Notes    : The public endpoint returns the whole published repertoire in ║
   ║             one page (default size=500 > 312 dances), so search & type    ║
   ║             filtering stay client-side — instant, no debounce needed.     ║
   ╚═══════════════════════════════════════════════════════════════════════════╝ */
function RepertoriSection({ t, lang }) {
  const { items: danses, live } = window.EsbartData.useCollection(`danses?lang=${lang}`, t.danses, {
    map: (j) => j.items.map((d) => ({
      id: String(d.id),
      type: d.type,
      name: String(d.name || ""),
      town: d.town || "",
      region: d.region || "",
      desc: d.desc || "",
    })),
  });
  const [filter, setFilter] = useState("all");
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return danses.filter((d) =>
      (filter === "all" || d.type === filter) &&
      (!q || d.name.toLowerCase().includes(q) || (d.town || "").toLowerCase().includes(q) || (d.region || "").toLowerCase().includes(q))
    );
  }, [danses, filter, query]);

  // Only the first batches are PAINTED (312 published dances would mean an
  // endless scroll); search/filter keep working over the whole repertoire,
  // and changing them restarts the window.
  const REP_PAGE = 6;
  const [shown, setShown] = useState(REP_PAGE);
  useEffect(() => { setShown(REP_PAGE); }, [filter, query, lang]);
  const visible = filtered.length > shown ? filtered.slice(0, shown) : filtered;

  return (
    <section className="pk-section pk-section--cream" id="repertori">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.repEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">
              {t.repTitle[0]}<em>{t.repTitle[1]}</em>{t.repTitle[2]}<em>{t.repTitle[3]}</em>
            </h2>
            <p className="pk-head__sub">{t.repSub}</p>
          </div>
        </div>

        <div className="pk-toolbar">
          <div className="pk-chips">
            {t.repFilters.map((f) => (
              <button key={f.id} className={`pk-chip ${filter === f.id ? "is-active" : ""}`} onClick={() => setFilter(f.id)}>
                {f.label}
              </button>
            ))}
          </div>
          <div className="pk-search">
            <SearchIcon />
            <input type="search" value={query} placeholder={t.repSearchPh} onChange={(e) => setQuery(e.target.value)} aria-label={t.repSearchPh} />
          </div>
        </div>

        <div className="pk-count" style={{ marginBottom: 18 }}>{filtered.length} {t.repCountLabel}</div>

        {filtered.length === 0 ? (
          <div className="pk-empty">{t.repEmpty}</div>
        ) : (
          <div className="pk-grid pk-grid--3" data-live={live ? "1" : undefined}>
            {visible.map((d) => (
              <article key={d.id} className="pk-card">
                <div className="pk-card__index">{t.repTypeLabels[d.type] || t.repTypeLabels.catalogada}</div>
                <h3 className="pk-card__title">{d.name}</h3>
                <div className="pk-card__meta"><span>{d.town}</span><span>{d.region}</span></div>
                {d.desc && <p className="pk-card__body">{d.desc}</p>}
              </article>
            ))}
          </div>
        )}

        {filtered.length > shown && (
          <div className="pk-loadmore">
            <span className="pk-loadmore__count">{t.repShowingOf.replace("{shown}", visible.length).replace("{total}", filtered.length)}</span>
            <button type="button" className="btn ghost" onClick={() => setShown((s) => s + REP_PAGE)}>{t.repLoadMore}</button>
          </div>
        )}

        <div style={{ marginTop: 44 }}>
          {/* Deep archive of documented dances/works lives in the online catalogue */}
          <a href="Cataleg.html" className="btn ghost">{t.repMore}</a>
        </div>
      </div>
    </section>
  );
}

/* ╔═══════════════════════════════════════════════════════════════════════════╗
   ║  SECTION 1b · CRONOLOGIA D'ACTUACIONS — LIVE (F3)                          ║
   ║  Facet    : GET /actuacions/years → { years:[{ year, count }] } desc.      ║
   ║  List     : GET /actuacions?year=&size=100&lang= (max/year is 49 ≤ 100).  ║
   ║  Item     : { codi, iso, poblacio, lloc, motiu, director, seccions[],     ║
   ║             danses:[{ name, slug, free }] } — vocabulary terms are legacy ║
   ║             Catalan proper nouns (INT-6 exempt); dansa names localise.    ║
   ║  Seeds    : the real facet plus the latest year's programme, frozen       ║
   ║             2026-07-12 (INT-1/INT-11: real data, never invented).         ║
   ╚═══════════════════════════════════════════════════════════════════════════╝ */

const CRO_YEARS = [
  [2016,1],[2015,1],[2010,30],[2009,29],[2008,49],[2007,30],[2006,16],[2005,25],[2004,28],[2003,23],[2002,18],[2001,26],
  [2000,23],[1999,15],[1998,22],[1997,23],[1996,18],[1995,19],[1994,18],[1993,17],[1992,5],[1991,12],[1990,20],[1989,14],
  [1988,7],[1987,16],[1986,12],[1985,8],[1984,11],[1983,9],[1982,5],[1981,7],[1980,8],[1979,8],[1978,11],[1977,11],
  [1976,7],[1975,4],[1974,6],[1973,8],[1972,11],[1971,9],[1970,7],[1969,11],[1968,9],[1967,9],[1966,14],[1965,11],
  [1964,11],[1963,8],[1962,8],[1961,5],[1960,12],[1959,6],[1958,9],[1957,5],[1956,5],[1955,7],[1954,5],[1953,11],
  [1952,8],[1951,4],[1950,9],[1949,5],[1948,8],[1937,3],[1936,11],[1935,10],[1934,9],[1933,7],[1932,11],[1931,4],
  [1930,7],[1928,4],[1927,3],[1925,4],[1924,4],[1923,14],[1922,24],[1921,16],[1920,18],[1919,20],[1918,13],[1917,9],
  [1916,19],[1915,7],[1914,8],[1913,20],[1912,18],[1911,17],[1910,5],[1909,6],[1908,3],
].map(([year, count]) => ({ year, count }));

const CRO_SEED_ACTS = {
  2016: [{
    codi: 1173, iso: "2016-02-13", poblacio: "Barcelona. Ciutat Vella", lloc: "Sant Jaume",
    motiu: "Festes de Santa Eulàlia", director: "Gómez Soriano, Joan", seccions: ["Cos de dansa"],
    danses: [
      { name: "Les Danses de Tortosa", slug: "danses-de-tortosa", free: false },
      { name: "Ball de les Pedretes", slug: "pedretes", free: false },
      { name: "Ball de Bastons", slug: "bastons-52", free: false },
      { name: "Ball del Roser", slug: "roser", free: false },
      { name: "Ball de Bastons", slug: "bastons-47", free: false },
      { name: "Ball de Bastons", slug: "bastons-53", free: false },
      { name: "L' Entrada de Ball", slug: "entrada-de-ball", free: false },
      { name: "Ballet", slug: "ballet-165", free: false },
      { name: "El Tricoté", slug: "tricote", free: false },
      { name: "Ball de Garlandes", slug: "garlandes", free: false },
      { name: "Ball Pla", slug: "pla-164", free: false },
    ],
  }],
};

function CronologiaSection({ t, lang }) {
  const { items: years } = window.EsbartData.useCollection("actuacions/years", CRO_YEARS, { map: (j) => j.years });
  const [decade, setDecade] = useState(null);
  const [year, setYear] = useState(null);

  const decades = useMemo(() => [...new Set(years.map((y) => Math.floor(y.year / 10) * 10))], [years]);
  const dec = decades.includes(decade) ? decade : decades[0];
  const decYears = years.filter((y) => Math.floor(y.year / 10) * 10 === dec);
  const sel = decYears.some((y) => y.year === year) ? year : decYears[0]?.year;

  const { items: acts, live } = window.EsbartData.useCollection(
    `actuacions?year=${sel}&size=100&lang=${lang}`, CRO_SEED_ACTS[sel] ?? [], { map: (j) => j.items });

  // Honest hero stat: both numbers are derived from the facet, never typed in.
  const total = years.reduce((s, y) => s + y.count, 0);
  const first = years.length ? years[years.length - 1].year : "";

  return (
    <section className="pk-section pk-section--bone" id="cronologia">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.croEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">
              {t.croTitle[0]}<em>{t.croTitle[1]}</em>{t.croTitle[2]}<em>{t.croTitle[3]}</em>
            </h2>
            <p className="pk-head__sub">{t.croSub}</p>
          </div>
        </div>

        <div className="pk-count" style={{ marginBottom: 18 }}>
          {total.toLocaleString(LOCALE[lang] || "ca-ES")}{t.croStat}{first}
        </div>
        <div className="pk-chips cro-decades">
          {decades.map((d) => (
            <button key={d} className={`pk-chip ${d === dec ? "is-active" : ""}`}
                    onClick={() => { setDecade(d); setYear(null); }}>
              {d}–{String(d + 9).slice(-2)}
            </button>
          ))}
        </div>
        <div className="pk-chips cro-years">
          {decYears.map((y) => (
            <button key={y.year} className={`pk-chip ${y.year === sel ? "is-active" : ""}`}
                    onClick={() => setYear(y.year)}>
              {y.year} · {y.count}
            </button>
          ))}
        </div>

        {acts.length === 0 ? (
          <div className="pk-empty">{t.croEmpty}</div>
        ) : (
          <ol className="cro-list" data-live={live ? "1" : undefined}>
            {acts.map((a) => (
              <li key={a.codi} className="cro-item">
                <time className="cro-item__date" dateTime={a.iso || undefined}>
                  {a.iso ? fmtDate(a.iso, lang) : ""}
                </time>
                <div className="cro-item__body">
                  <h3 className="cro-item__title">{a.motiu || a.lloc || a.poblacio}</h3>
                  <div className="cro-item__meta">
                    {[a.poblacio, a.lloc, a.director].filter(Boolean).map((m, i) => <span key={i}>{m}</span>)}
                  </div>
                  {a.danses.length > 0 && (
                    <p className="cro-item__danses">
                      <span className="cro-item__label">{t.croProgram}</span>
                      {a.danses.map((d) => d.name).filter(Boolean).join(" · ")}
                    </p>
                  )}
                </div>
              </li>
            ))}
          </ol>
        )}
      </div>
    </section>
  );
}

/* ─── Acordió únic (shared/components/Accordion.jsx) ─────────────────── */
const EsbartAccordion = window.EsbartAccordion;

function CentreDocSection({ t }) {
  return (
    <section className="pk-section pk-section--paper" id="centre">
      <div className="wrap">
        <div className="pk-feature" style={{ marginBottom: 80 }}>
          <div className="pk-feature__media">
            {/* STATIC asset — swap for a CMS media field if the seat photo becomes editable */}
            <img src="assets/casa-dels-entremesos.jpg" alt={t.cdImgCaption} />
            <div className="pk-feature__caption"></div>
          </div>
          <div className="pk-feature__text">
            <div className="pk-feature__kicker">{t.cdEyebrow}</div>
            <h2 className="pk-feature__title">
              {t.cdTitle[0]}<em>{t.cdTitle[1]}</em>{t.cdTitle[2]}<em>{t.cdTitle[3]}</em>{t.cdTitle[4]}
            </h2>
            <div className="pk-feature__body"><p>{t.cdLead}</p></div>
            <div className="pk-feature__actions">
              <a href="Cataleg.html" className="btn ghost">{t.cdCatalog}</a>
            </div>
          </div>
        </div>

        <EsbartAccordion
          idPrefix="cd"
          items={t.cdGroups.map((g) => ({
            id: g.id,
            num: g.num,
            title: g.title,
            content: (
              <>
                <p className="pk-card__body" style={{ maxWidth: "62ch", marginBottom: 28, fontSize: 16 }}>{g.intro}</p>
                <div className="pk-grid pk-grid--2">
                  {g.blocks.map((b, i) => (
                    <div key={i}>
                      <h4 className="pk-doc-blockh">{b.h}</h4>
                      <ul className="pk-doc-list">
                        {b.items.map((it, j) => <li key={j}>{it}</li>)}
                      </ul>
                    </div>
                  ))}
                </div>
              </>
            ),
          }))}
        />
      </div>
    </section>
  );
}

function DansesVivesSection({ t }) {
  return (
    <section className="pk-section pk-section--dark" id="danses-vives">
      <div className="wrap">
        <div className="pk-feature pk-feature--flip">
          <div className="pk-feature__media">
            <img src="assets/g-sardana.jpg" alt="" />
          </div>
          <div className="pk-feature__text">
            <div className="pk-feature__kicker">{t.dvEyebrow}</div>
            <h2 className="pk-feature__title">
              {t.dvTitle[0]}<em>{t.dvTitle[1]}</em>{t.dvTitle[2]}
            </h2>
            <div className="pk-feature__body">
              {t.dvBody.map((p, i) => <p key={i}>{p}</p>)}
              <p style={{ color: "var(--gold-soft)" }}>{t.dvCollab}</p>
            </div>
            <div className="pk-feature__actions">
              {/* External project site (static link) */}
              <a href="https://www.dansesvives.cat/" target="_blank" rel="noopener" className="btn light">{t.dvBtn}</a>
              <a href="Participa.html#contacte" className="btn outline-light">{t.dvBtn2}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ╔═══════════════════════════════════════════════════════════════════════════╗
   ║  DYNAMIC · CMS — PUBLICATIONS                                              ║
   ║  Endpoint : GET /api/v1/publicacions?lang={lang}                          ║
   ║  Item     : { id, title, author, year, format, desc, award?:boolean }     ║
   ╚═══════════════════════════════════════════════════════════════════════════╝ */
function PublicacionsSection({ t, lang }) {
  // GO-LIVE(post-F4): deferred by the client (2026-07-12) — the imported CMS
  // drafts are miscategorized/incomplete and need his curation first.
  const { items: pubs } = window.EsbartData.useCollection(`publicacions?lang=${lang}`, t.publicacions, { enabled: false });
  return (
    <section className="pk-section pk-section--bone" id="publicacions">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.pubEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">{t.pubTitle[0]}<em>{t.pubTitle[1]}</em>{t.pubTitle[2]}</h2>
            <p className="pk-head__sub">{t.pubSub}</p>
          </div>
        </div>

        <div className="pk-grid pk-grid--3">
          {pubs.map((p) => (
            <article key={p.id} className="pk-card">
              <div className="pk-card__meta"><span>{p.year}</span><span>{p.format}</span></div>
              <h3 className="pk-card__title">{p.title}</h3>
              <div className="pk-card__index" style={{ textTransform: "none", letterSpacing: ".04em" }}>{p.author}</div>
              <p className="pk-card__body">{p.desc}</p>
              {p.award && <span className="pk-award-flag">★ {t.pubAwardLabel}</span>}
            </article>
          ))}
        </div>

        <div style={{ marginTop: 40 }}>
          {/* DYNAMIC · CMS — catalogue PDF asset (GET /api/v1/assets/publicacions-pdf).
             Currently points at the live published PDF. */}
          <a href="https://www.esbartcatala.org/doc/3032/Publicacions%201908-2023%20Actualitzat.pdf" target="_blank" rel="noopener" className="btn ghost">{t.pubCatalog}</a>
        </div>

        <div className="pk-twin" style={{ marginTop: 72 }}>
          <div className="pk-twin__col">
            <div className="pk-head__eyebrow">{t.presEyebrow}</div>
            <p className="pk-card__body" style={{ fontSize: 16 }}>{t.presBody}</p>
          </div>
          <div className="pk-twin__col">
            <div className="pk-head__eyebrow">{t.aportEyebrow}</div>
            <p className="pk-card__body" style={{ fontSize: 16, marginBottom: 18 }}>{t.aportBody}</p>
            <div className="pk-pills">
              {t.aportEditions.map((y) => <span key={y} className="pk-pill">{y}</span>)}
            </div>
            <div style={{ marginTop: 22 }}>
              <a className="btn ghost" href="Activitats.html#aportacions">{t.aportCta}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* LIVE since F1: GET /exposicions feeds both filter chips; t.exposicions
   stays as the eternal fallback (INT-1). The live rows are the client's
   transcription of this same list, so only `data-live` tells the E2E harness
   which one painted. Only exhibitions with an immersive page get an href
   (no click without a destination — client rule); live ids are CMS slugs. */
const EXPO_HREFS = {
  "exposicio-110-imatges-per-110-anys-2019": "Exposicio.html",
  "exposicio-joan-amades-a-l-esbart-catala-de-dansaires-soci-i-president-2015": "Exposicio.html?mock=antiga",
};
function ExposicionsSection({ t, lang }) {
  const { items: expos, live } = window.EsbartData.useCollection(
    `exposicions?lang=${lang}&size=50`,
    t.exposicions,
    { map: (j) => j.items.map((e) => ({
        id: e.id, kind: e.kind, year: String(e.iso || "").slice(0, 4),
        title: e.title, href: EXPO_HREFS[e.id],
      })).sort((a, b) => a.year.localeCompare(b.year)) }
  );
  const [kind, setKind] = useState("propia");
  const list = expos.filter((e) => e.kind === kind);
  return (
    <section className="pk-section pk-section--paper" id="exposicions">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.expEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">{t.expTitle[0]}<em>{t.expTitle[1]}</em>{t.expTitle[2]}</h2>
            <p className="pk-head__sub">{t.expSub}</p>
          </div>
        </div>

        <div className="pk-toolbar">
          <div className="pk-chips">
            {t.expFilters.map((f) => (
              <button key={f.id} className={`pk-chip ${kind === f.id ? "is-active" : ""}`} onClick={() => setKind(f.id)}>{f.label}</button>
            ))}
          </div>
          <a href="Participa.html#contacte" className="pk-card__link">{t.expCede} <Arrow /></a>
        </div>

        <ol className="pk-explist" data-live={live ? "1" : undefined}>
          {list.map((e) => (
            <li key={e.id}>
              {/* Només és clicable si té pàgina de detall (cap clic sense destí) */}
              {e.href ? (
                <a className="pk-exprow pk-exprow--link" href={e.href}>
                  <span className="pk-exprow__year">{e.year}</span>
                  <span className="pk-exprow__title">{e.title} <Arrow /></span>
                </a>
              ) : (
                <div className="pk-exprow">
                  <span className="pk-exprow__year">{e.year}</span>
                  <span className="pk-exprow__title">{e.title}</span>
                </div>
              )}
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

function VestuariSection({ t }) {
  /* Gallery images are STATIC site assets today; when a media library exists,
     replace `imgs` with a CMS media collection. The strip is a hover-pausing,
     full-bleed auto marquee — mirrors the Home gallery vocabulary. */
  const imgs = [
    "assets/g-capes.jpg",
    "assets/g-yellow.jpg",
    "assets/g-circle.jpg",
    "assets/g-night.jpg",
    "assets/g-court.jpg",
    "assets/g-couple.jpg",
    "assets/g-couple2.jpg",
    "assets/g-sardana.jpg",
  ];
  const row = [...imgs, ...imgs]; // duplicate set → seamless -50% marquee loop

  return (
    <section className="pk-section pk-section--bone" id="vestuari">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.vesEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">{t.vesTitle[0]}<em>{t.vesTitle[1]}</em>{t.vesTitle[2]}</h2>
            <p className="pk-head__sub">{t.vesLead}</p>
          </div>
        </div>

        <div className="ves-prose">
          {t.vesIntro.map((p, i) => <p key={i}>{p}</p>)}
        </div>

        <div className="pk-grid pk-grid--3 ves-facets">
          {t.vesFacets.map((f, i) => (
            <article key={i} className="pk-card">
              <div className="pk-card__index">{String(i + 1).padStart(2, "0")}</div>
              <h3 className="pk-card__title" style={{ fontSize: 20 }}>{f.h}</h3>
              <p className="pk-card__body">{f.b}</p>
            </article>
          ))}
        </div>
      </div>

      {/* ── Origin — dark editorial band: image strip + text ─────────────── */}
      <div className="ves-origin">
        <div className="ves-marquee" aria-hidden="true">
          <div className="ves-marquee__row">
            {row.map((src, i) => (
              <div key={i} className="ves-marquee__item" style={{ backgroundImage: `url(${src})` }}></div>
            ))}
          </div>
        </div>
        <div className="wrap ves-origin__inner">
          <div className="ves-origin__eyebrow">{t.vesOriginEyebrow}</div>
          <div className="ves-origin__grid">
            <p className="ves-origin__statement">{t.vesOrigin[0]}</p>
            <div className="ves-origin__aside">
              <p className="ves-origin__support">{t.vesOrigin[1]}</p>
              <div className="ves-origin__credit">
                <span className="ves-origin__credit-label">{t.vesCreditLabel}</span>
                <span className="ves-origin__credit-text">{t.vesMuseuCredit}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="wrap">
        {/* ── Lexicon — glossari (acordió de consulta, plegat per defecte) ─ */}
        <div className="ves-lex">
          <div className="ves-lex__head">
            <div className="ves-lex__eyebrow">{t.vesLexEyebrow}</div>
            <p className="ves-lex__lead">{t.vesLexLead}</p>
          </div>
          <EsbartAccordion
            idPrefix="lex"
            items={t.vesLex.map((g, gi) => ({
              id: "lex-" + gi,
              title: g.label,
              content: (
                <dl className="ves-lex__list">
                  {g.items.map((it, ii) => (
                    <div key={ii} className="ves-lex__row">
                      <dt className="ves-lex__term">{it.t}</dt>
                      <dd className="ves-lex__def">{it.d}</dd>
                    </div>
                  ))}
                </dl>
              ),
            }))}
          />
        </div>
      </div>
    </section>
  );
}

function ServeisSection({ t }) {
  return (
    <section className="pk-section pk-section--paper" id="serveis">
      <div className="wrap">
        <div className="pk-head">
          <div className="pk-head__eyebrow">{t.srvEyebrow}</div>
          <div className="pk-head__grid">
            <h2 className="pk-head__title">{t.srvTitle[0]}<em>{t.srvTitle[1]}</em>{t.srvTitle[2]}</h2>
            <p className="pk-head__sub">{t.srvSub}</p>
          </div>
        </div>
        <div className="pk-grid pk-grid--4">
          {t.serveis.map((s, i) => (
            <article key={i} className="pk-card">
              <div className="pk-card__index">{String(i + 1).padStart(2, "0")}</div>
              <h3 className="pk-card__title" style={{ fontSize: 20 }}>{s.h}</h3>
              <p className="pk-card__body">{s.b}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function CtaBand({ t }) {
  return (
    <section className="pk-cta" id="contacte-centre">
      <div className="wrap">
        <div className="pk-cta__eyebrow">{t.ctaEyebrow}</div>
        <h2 className="pk-cta__title">{t.ctaTitle[0]}<em>{t.ctaTitle[1]}</em>{t.ctaTitle[2]}</h2>
        <p className="pk-cta__lead">{t.ctaLead}</p>
        <div className="pk-cta__actions">
          <a href="Participa.html#contacte" className="btn light">{t.ctaBtn1}</a>
          <a href="Cataleg.html" className="btn outline-light">{t.ctaBtn2}</a>
        </div>
      </div>
    </section>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   APP
   ═══════════════════════════════════════════════════════════════════════════ */
/* ─── Sub-navegació de pàgina (shared/components/Subnav.jsx) ──────────── */
const EsbartSubnav = window.EsbartSubnav;
const PATRI_SUBNAV = {
  ca: [
    { id: "repertori", label: "Repertori" },
    { id: "cronologia", label: "Cronologia" },
    { id: "centre", label: "Centre de documentació" },
    { id: "danses-vives", label: "Danses Vives" },
    { id: "publicacions", label: "Publicacions" },
    { id: "exposicions", label: "Exposicions" },
    { id: "vestuari", label: "Vestuari" },
    { id: "serveis", label: "Serveis" },
  ],
  es: [
    { id: "repertori", label: "Repertorio" },
    { id: "cronologia", label: "Cronología" },
    { id: "centre", label: "Centro de documentación" },
    { id: "danses-vives", label: "Danses Vives" },
    { id: "publicacions", label: "Publicaciones" },
    { id: "exposicions", label: "Exposiciones" },
    { id: "vestuari", label: "Vestuario" },
    { id: "serveis", label: "Servicios" },
  ],
  en: [
    { id: "repertori", label: "Repertoire" },
    { id: "cronologia", label: "Chronology" },
    { id: "centre", label: "Documentation centre" },
    { id: "danses-vives", label: "Danses Vives" },
    { id: "publicacions", label: "Publications" },
    { id: "exposicions", label: "Exhibitions" },
    { id: "vestuari", label: "Costumes" },
    { id: "serveis", label: "Services" },
  ],
};

function App() {
  const { lang, setLang, t } = window.EsbartI18n.useI18n(PATRI_STRINGS);
  const tweaks = window.EsbartTweaks.useTweaks();
  const [heroMode] = useState(false); // editorial hero on cream → light nav

  useEffect(() => { if (t.pageTitle) document.title = t.pageTitle; }, [lang, t]);

  return (
    <>
      <EsbartNav lang={lang} setLang={setLang} t={t} heroMode={heroMode} current="patrimoni" />
      <main id="main-content" tabIndex={-1}>
        <Hero t={t} />
        <EsbartSubnav items={PATRI_SUBNAV[lang] || PATRI_SUBNAV.ca} />
        <RepertoriSection t={t} lang={lang} />
        <CronologiaSection t={t} lang={lang} />
        <CentreDocSection t={t} />
        <DansesVivesSection t={t} />
        <PublicacionsSection t={t} lang={lang} />
        <ExposicionsSection t={t} lang={lang} />
        <VestuariSection t={t} />
        <ServeisSection t={t} />
        <CtaBand t={t} />
      </main>
      <EsbartFooter t={t} />
      <EsbartTweaksPanel {...tweaks} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
