// 22K — CMS layer. Runs after i18n.jsx and hifi-tokens.jsx, before any component renders.
//
// content.js (served by functions/content.js from Sanity, with a static snapshot as
// fallback) sets window.__CMS__. Here it replaces the defaults that live in
// hifi-tokens.jsx / i18n.jsx IN PLACE (same arrays, same objects), so nothing else
// in the site needs to know where the content came from. Anything the Studio leaves
// empty keeps its default; with no CMS data at all the site renders exactly as before.
//
// SITE holds the small bits of config that used to be hard-coded in components.

const SITE = {
  leadEmail: "info@22k.film",
  careersEmail: "carreira@22k.com.br",
  instagram: "",
  vimeo: "",
  linkedin: "",
  legalLine: "© 2026 22K Filmes · CNPJ 22.022.220/0001-22",
  reel: "assets/hero-reel.mp4",
  logos: [1, 2, 3, 4, 5].map((n) => `assets/Credenciais/${n}.jpg`),
};

(function applyCms() {
  const C = window.__CMS__;
  if (!C) return;
  try {
    // ── UI texts: key -> [pt, en]; an empty field keeps the current value
    Object.keys(C.strings || {}).forEach((k) => {
      const [pt, en] = C.strings[k] || [];
      const cur = I18N_STRINGS[k];
      if (!cur) return; // unknown key: the code never asks for it
      I18N_STRINGS[k] = [pt || cur[0], en || cur[1]];
    });

    // ── Projects
    if ((C.projects || []).length) {
      const en = {};
      const next = C.projects.map((p) => {
        const { en: e, ...pt } = p;
        en[p.slug] = e || {};
        return pt;
      });
      PROJECTS.splice(0, PROJECTS.length, ...next);
      EN_DATA.projects = en;
    }

    // ── Testimonials
    if ((C.testimonials || []).length) {
      TESTIMONIALS.splice(0, TESTIMONIALS.length, ...C.testimonials.map(({ en, ...pt }) => pt));
      EN_DATA.testimonials = C.testimonials.map((t) => t.en || {});
    }

    // ── Deliverables
    if ((C.deliverables || []).length) {
      DELIVERABLES.splice(0, DELIVERABLES.length, ...C.deliverables.map(({ en, ...pt }) => pt));
      EN_DATA.deliverables = C.deliverables.map((d) => d.en || {});
    }

    // ── Settings, images
    const s = C.settings || {};
    ["leadEmail", "careersEmail", "instagram", "vimeo", "linkedin", "legalLine", "reel"].forEach((k) => {
      if (s[k]) SITE[k] = s[k];
    });
    if ((s.logos || []).length) SITE.logos = s.logos;
    if (s.dir) STILLS.dir = s.dir;
    if (s.cap) STILLS.cap = s.cap;
    (s.deliverableImages || []).forEach((u, i) => { if (u) STILLS.deliverables[i] = u; });
  } catch (e) {
    console.warn("[22K] CMS content could not be applied, using defaults.", e);
  }
})();

window.SITE = SITE;
