// 22K — i18n (PT / EN).
//
// How the language is chosen, in order:
//   1. ?lang=pt|en in the URL (this browser tab only — handy for sharing/testing)
//   2. the visitor's manual choice in the header toggle (saved in localStorage)
//   3. country from Cloudflare (cookie "22k_country", set by functions/_middleware.js):
//      BR → Português, anywhere else → English
//   4. fallback when there is no cookie (local dev): browser time zone
//
// Usage in components:  tr("nav.work")  ·  const lang = useLang()
// Data (projects, testimonials, deliverables) keeps the PT source in
// hifi-tokens.jsx; the English versions live in EN_DATA below.

(function () {
  const STORE_KEY = "22k-lang";
  const SESSION_KEY = "22k-lang-url";
  const BR_TIMEZONES = [
    "America/Sao_Paulo", "America/Araguaina", "America/Bahia", "America/Belem",
    "America/Boa_Vista", "America/Campo_Grande", "America/Cuiaba", "America/Eirunepe",
    "America/Fortaleza", "America/Maceio", "America/Manaus", "America/Noronha",
    "America/Porto_Velho", "America/Recife", "America/Rio_Branco", "America/Santarem",
  ];
  const valid = (l) => l === "pt" || l === "en";

  function readCookie(name) {
    const m = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
    return m ? decodeURIComponent(m[1]) : "";
  }

  function detect() {
    try {
      const q = new URLSearchParams(window.location.search).get("lang");
      if (valid(q)) { try { sessionStorage.setItem(SESSION_KEY, q); } catch (e) {} return q; }
    } catch (e) {}
    try { const s = sessionStorage.getItem(SESSION_KEY); if (valid(s)) return s; } catch (e) {}
    try { const s = localStorage.getItem(STORE_KEY); if (valid(s)) return s; } catch (e) {}
    const country = readCookie("22k_country");
    if (country) return country.toUpperCase() === "BR" ? "pt" : "en";
    try {
      const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
      if (tz) return BR_TIMEZONES.indexOf(tz) !== -1 ? "pt" : "en";
    } catch (e) {}
    return /^pt-br/i.test(navigator.language || "") ? "pt" : "en";
  }

  let current = detect();
  const listeners = new Set();
  document.documentElement.lang = current === "pt" ? "pt-BR" : "en";

  function setLang(l) {
    if (!valid(l) || l === current) return;
    current = l;
    try { localStorage.setItem(STORE_KEY, l); } catch (e) {}
    try { sessionStorage.removeItem(SESSION_KEY); } catch (e) {}
    document.documentElement.lang = l === "pt" ? "pt-BR" : "en";
    listeners.forEach((fn) => fn(l));
  }

  window.getLang = () => current;
  window.setLang = setLang;
  window.__subscribeLang = (fn) => { listeners.add(fn); return () => listeners.delete(fn); };
})();

// ── UI strings: key → [pt, en] ─────────────────────────────────────────
const I18N_STRINGS = {
  "meta.home":        ["22K — Produtora de cinema publicitário", "22K — Advertising film production"],
  "meta.project":     ["22K — Projeto", "22K — Project"],

  "nav.work":         ["Trabalhos", "Work"],
  "nav.about":        ["Sobre", "About"],
  "nav.contact":      ["Contato", "Contact"],
  "cta.book":         ["Agende agora", "Book now"],

  "hero.portfolio":   ["Ver portfólio", "View portfolio"],
  "hero.scroll":      ["Role", "Scroll"],
  "hero.pause":       ["Pausar reel", "Pause reel"],
  "hero.play":        ["Tocar reel", "Play reel"],

  "about.side":       ["O que fazemos", "What we do"],
  "about.tag":        ["Sobre", "About"],
  "about.manifesto":  [
    "SOMOS UMA PRODUTORA DE CINEMA ARQUITETÔNICO. TRABALHAMOS PARA MARCAS QUE QUEREM DIZER ALGO — E AJUDAMOS A DIZER MELHOR, COM FILME, RITMO E DIREÇÃO.",
    "WE ARE AN ARCHITECTURAL FILM PRODUCTION COMPANY. WE WORK FOR BRANDS THAT HAVE SOMETHING TO SAY — AND HELP THEM SAY IT BETTER, THROUGH FILM, RHYTHM AND DIRECTION.",
  ],

  "dir.label":        ["Direção", "Direction"],
  "dir.kicker":       ["Nota", "Note"],
  "dir.title":        ["A CASA PRIMEIRO. CÂMERA DEPOIS.", "THE HOME FIRST. THE CAMERA SECOND."],
  "dir.body":         [
    "Antes de planejar planos, lemos o projeto: a luz pensada pelo arquiteto, a curva do corredor, o silêncio dos ambientes. O filme nasce de uma decupagem que respeita o que já existe.",
    "Before planning a single shot, we read the project: the light the architect designed, the curve of the corridor, the silence of each room. The film is born from a shot breakdown that respects what is already there.",
  ],
  "cap.label":        ["Captação", "Capture"],
  "cap.kicker":       ["Bastidor", "Behind the scenes"],
  "cap.title":        ["DO SOLO AO DRONE. UMA ÚNICA GRAMÁTICA.", "FROM GROUND TO DRONE. ONE SINGLE GRAMMAR."],
  "cap.body":         [
    "Pilotos ANAC, Inspire 3 e licenças para zona urbana. Mas o que importa é a continuidade: o mesmo olhar que filma o detalhe da soleira filma a fachada vista do céu.",
    "ANAC-certified pilots, Inspire 3 and permits for urban airspace. But what matters is continuity: the same eye that films the detail of a threshold films the façade seen from the sky.",
  ],

  "creds.title":      ["Em boa companhia", "In good company"],
  "testimonials.title": ["Depoimentos", "Testimonials"],
  "portfolio.title":  ["Portfólio", "Portfolio"],
  "portfolio.all":    ["Ver todos →", "View all →"],
  "deliv.title":      ["Entregáveis", "Deliverables"],
  "deliv.soon":       ["em breve", "soon"],

  "contact.reach":    ["Reach out", "Reach out"],
  "contact.title1":   ["VAMOS", "LET'S"],
  "contact.title2":   ["FILMAR", "SHOOT"],
  "contact.body":     [
    "Atendemos incorporadoras, escritórios de arquitetura e marcas premium em São Paulo, Rio e Lisboa. Conte sobre o empreendimento e desenhamos o filme.",
    "We work with real estate developers, architecture firms and premium brands in São Paulo, Rio and Lisbon. Tell us about your project and we'll design the film.",
  ],
  "contact.direct":   ["Direto", "Direct"],
  "form.name":        ["Nome", "Name"],
  "form.email":       ["E-mail", "Email"],
  "form.company":     ["Empresa / incorporadora", "Company / developer"],
  "form.phone":       ["Telefone", "Phone"],
  "form.message":     ["Conte sobre o projeto", "Tell us about the project"],
  "form.send":        ["Enviar mensagem", "Send message"],
  "form.sending":     ["Enviando…", "Sending…"],
  "form.received":    ["Recebido", "Received"],
  "form.thanks":      ["Obrigado. Recebemos sua mensagem e retornaremos em breve.", "Thank you. We've received your message and will get back to you soon."],
  "form.error":       ["Erro ao enviar — escreva para", "Couldn't send — email us at"],
  "form.subject":     ["Novo contato", "New contact"],
  "form.siteName":    ["site 22K", "22K website"],

  "footer.tagline":   ["Produtora de cinema publicitário.", "Advertising film production company."],
  "footer.navigate":  ["Navegar", "Navigate"],
  "footer.social":    ["Sociais", "Social"],
  "footer.cities":    ["Cidades", "Cities"],
  "footer.lisbon":    ["Lisboa · PT", "Lisbon · PT"],
  "footer.citiesLine": ["São Paulo · Rio · Lisboa", "São Paulo · Rio · Lisbon"],

  "case.project":     ["Projeto", "Project"],
  "case.back":        ["← Voltar aos trabalhos", "← Back to work"],
  "case.watch":       ["Assista", "Watch"],
  "case.videoSoon":   ["Vídeo em breve", "Video coming soon"],
  "case.about":       ["Sobre o filme", "About the film"],
  "case.client":      ["Cliente", "Client"],
  "case.delivery":    ["Entrega", "Deliverable"],
  "case.location":    ["Local", "Location"],
  "case.year":        ["Ano", "Year"],
  "case.descSoon":    ["Descrição em breve.", "Description coming soon."],
  "case.more":        ["Mais projetos", "More projects"],
};

function tr(key) {
  const entry = I18N_STRINGS[key];
  if (!entry) return key;
  return getLang() === "en" ? entry[1] : entry[0];
}

// Re-renders the calling component whenever the language changes.
function useLang() {
  const [lang, setL] = React.useState(getLang());
  React.useEffect(() => window.__subscribeLang(setL), []);
  return lang;
}

// ── English versions of the data in hifi-tokens.jsx ───────────────────
const EN_DATA = {
  projects: {
    "tom": {
      kind: "Event film", local: "Rio de Janeiro waterfront",
      desc: "Widely shared as the most expensive development in Brazil, TOM demanded communication that matched its singularity on Rio's waterfront. Our approach was to portray a less obvious kind of sophistication, connecting exclusivity to life's simplest pleasures by the sea: feet in the water, the sunrise, time to read, contact with nature and sports like surfing and running.\n\nLong before quiet luxury became a trend, the film was already heading in that direction, through naturalistic cinematography, organic light, visual breathing room and a delicate, mysterious look at everyday life. With a minimalist, contemplative aesthetic, we set out to create a sophistication proportional to the development, without excess, only through atmosphere, time and visual sensitivity.",
    },
    "canto-mar": {
      kind: "Film + drone", local: "Between Ipanema and Copacabana",
      desc: "Built literally between Ipanema and Copacabana, Canto Mar had its greatest narrative asset in its own location. Through aerial footage, drones and graphics integrated into the edit, we turned this unique trait into a clear, sophisticated visual language.\n\nFootage of the neighborhood was woven in to convey the rhythm, buzz and cultural atmosphere of the area. With an aesthetic built on collage, visual breathing room, passe-partout framing and contemporary editing, we developed a film with national and international appeal, able to connect architecture, city and lifestyle.",
    },
    "grand-thai": {
      kind: "Launch film",
      desc: "Inspired by the great resorts of Thailand, Grand Thai was developed around a visual language focused on immersion and the project's sensory atmosphere. The interviews were staged in settings aligned with the development's key visuals, exploring warm tones, visual breathing room and a contemplative aesthetic.\n\nThe edit blends original footage, archival images, VFX and AI-generated elements, creating a fluid narrative that transports viewers into the world of the development. Conducted in a documentary style, the interviews reveal, in a light and human way, the creative process of the architects, engineers and professionals involved in the project. The film was produced both as a full-length version and as 30-second TV spots, keeping aesthetic and narrative consistency across every deliverable.",
    },
    "rio-open": {
      kind: "Brand activation",
      desc: "\"Great achievements begin at home.\" At a time when tennis has taken a central place in high-end developments, the partnership between Tegra and Rio Open came about naturally. The film's challenge was to bring two worlds together, the real estate product and the world of the courts, in a single narrative.\n\nWith cinematic language and a fictional feel, the film opens almost like a silent thriller, building tension and curiosity during the tournament break. Gradually, the story reveals something simple and everyday: the routine of a family that lives tennis naturally, as part of the lifestyle the development offers. Through elegant cinematography, visual breathing room and an unexpected narrative structure, we turned a real estate film into an experience with the atmosphere of cinema.",
    },
    "singular": {
      kind: "Launch film",
      desc: "Inspired by the landscape legacy of Burle Marx, the SINGULAR film was built on the idea of translating sensitivity, form and sophistication into audiovisual language. We had special access to the Burle Marx studio to capture part of the creative process of the renowned landscape architects involved in the project, bringing audiences closer to the conceptual essence of the development.\n\nIn a documentary style, we interviewed architects, engineers, designers and members of the developer's team to reveal, from the inside out, the thinking, care and curation behind every detail. Through elegant editing, full of visual breathing room and a contemplative atmosphere, the film seeks to convey not only quality and good taste, but also the creative heart that drives the project.",
    },
    "taman": {
      kind: "Corporate film",
      desc: "TAMAN is a project that flirts with fiction to portray the unique lifestyle of the Flamengo neighborhood. Through scenes staged with actors, we explored everyday moments that are part of local life: the morning run, the summer swim, Sundays with family and the constant relationship between city, nature and well-being.\n\nIn the edit, these scenes blend with documentary-style interviews with the professionals behind the development, creating a more human, intimate and emotional narrative. The result is a film that turns architecture into experience and brings audiences closer to the real atmosphere of the project.",
    },
    "costa-niemeyer": {
      kind: "Launch film",
      desc: "COSTA NIEMEYER starts from the meeting of two rhythms of the city: the calm landscape of Avenida Niemeyer and the energy of Leblon, just minutes away. Inspired by benchmark coastal destinations around the world, the film presents an effortless way of living, where comfort, location and quality of life become the development's main differentiators.\n\nTo translate this concept, we combined aerial footage of the area, interviews with the project's creators, voice-over and visual resources that bring together architectural renderings, artificial intelligence and motion design. The narrative highlights both the surroundings and the architecture, turning the project's attributes into a clear, desirable and contemporary visual experience.",
    },
    "chateau-jardin": {
      kind: "Launch film",
      desc: "CHÂTEAU JARDIN was conceived to translate classically inspired architecture through a contemporary lens. Guided by the concept \"inspired by the classic, designed for the future\", the film presents the development as a rare address in Cidade Jardim, surrounded by greenery, infrastructure and strategic connections, where sophistication, well-being and permanence go hand in hand.\n\nThe execution combines AI-generated imagery, 3D architectural renderings and refined motion design to build a visual world inspired by l'art de vivre. From the French gardens to the finishing details, every element was designed to express the project's attributes with elegance and precision, turning conceptual references into a visual narrative that sparks desire and reinforces the development's exclusive positioning.",
    },
    "riio": {
      kind: "Launch film",
      desc: "RIIO BY PIERO LISSONI is born from the meeting of two striking identities: the elegance of Italian design and the vibrancy of Rio's landscape. Inspired by the Amalfi Coast and contemporary Italian architecture, the film presents the development as a new way of living in Barra da Tijuca — combining sophistication, leisure, security and a privileged relationship with the Avenida Lúcio Costa waterfront.\n\nTo translate this concept, we built a narrative that connects Italy and Brazil through a symbolic ocean crossing, guided by an Italian voice-over and supported by aerial footage, archival material with Piero Lissoni and scenes created with artificial intelligence. The combination of cinematic language and architectural visualization creates an aspirational experience that reinforces the project's exclusive character and the rarity of occupying one of the last plots on the avenue.",
    },
    "nova-vivere": {
      kind: "Launch film",
      desc: "NOVA VIVERE starts from the idea that great urban transformations begin with the way we choose to live. Inspired by revitalization movements seen in neighborhoods around the world, the film presents the development as part of a new moment for Lapa — where urban renewal, infrastructure and quality of life open up new ways of inhabiting the city.\n\nTo shape this concept, we developed a visual narrative built from illustrations that come to life and evolve into architectural renderings through artificial intelligence. This transition from sketch to space turns the very act of designing into language, creating a visual experience that connects urban transformation with a desire for the future.",
    },
  },
  testimonials: [
    { quote: "In a real estate market where everything looks the same, 22K manages to do the hardest thing: create soul, identity and an authorial aesthetic that elevate any project.", role: "Creative Director · Script" },
    { quote: "Working with 22K is always a special experience. Beyond their extreme professionalism, they have a sensitive, creative and very precise eye for translating an architectural concept into a narrative full of emotion. They're sensational!" },
    { quote: "22K has been a great strategic partner. A production company that adapts quickly to budgets, and above all to the technological and visual solutions our projects need." },
    { quote: "What set working with 22K apart was the partnership and commitment at every stage of the project, always agile and open to building everything together with us. The result exceeded our expectations and we certainly want to repeat the experience on new projects." },
  ],
  deliverables: [
    {
      bucket: "Film & launch",
      items: [
        { title: "Launch film",   desc: "Corporate film from 60s to 3min — concept, shot breakdown, capture and post-production." },
        { title: "Signature tour", desc: "Cinematic walkthrough of the show apartment or model unit, in one continuous movement." },
        { title: "Manifesto",     desc: "Concept film that translates the development's positioning into a visual narrative." },
      ],
    },
    {
      bucket: "Technical capture",
      items: [
        { title: "Drone",               desc: "Aerial footage with ANAC-certified pilots, Inspire 3 and flight permits for urban areas." },
        { title: "Architecture film",   desc: "Documentation of the project in partnership with the architecture firm — façade, ambience and detail." },
        { title: "Hyperlapse & timelapse", desc: "Recording the build from groundbreaking to completion, or the light shifting through the day." },
      ],
    },
    {
      bucket: "Sales & social",
      items: [
        { title: "Broker film",  desc: "Sales content for sales stands, on-site teams and B2B channels." },
        { title: "Social cuts",  desc: "9:16, 1:1 and 16:9 versions for Instagram, YouTube and paid media." },
        { title: "3D tour",      desc: "3D modeling and animation of the development for pre-launch phases." },
      ],
    },
  ],
};

// Localized views of the data. PT returns the source untouched.
function localProjects() {
  if (getLang() !== "en") return PROJECTS;
  return PROJECTS.map((p) => ({ ...p, ...(EN_DATA.projects[p.slug] || {}) }));
}
function localTestimonials() {
  if (getLang() !== "en") return TESTIMONIALS;
  return TESTIMONIALS.map((t, i) => ({ ...t, ...(EN_DATA.testimonials[i] || {}) }));
}
function localDeliverables() {
  if (getLang() !== "en") return DELIVERABLES;
  return DELIVERABLES.map((col, ci) => {
    const en = EN_DATA.deliverables[ci] || {};
    return {
      ...col,
      bucket: en.bucket || col.bucket,
      items: col.items.map((it, i) => ({ ...it, ...((en.items || [])[i] || {}) })),
    };
  });
}

// ── Header toggle: EN | PT ─────────────────────────────────────────────
function LangToggle({ color = "currentColor" }) {
  const lang = useLang();
  const option = (code, label) => {
    const active = lang === code;
    return (
      <button
        type="button"
        onClick={() => setLang(code)}
        aria-pressed={active}
        aria-label={label}
        style={{
          background: "none", border: "none", padding: "6px 2px", margin: 0,
          color, cursor: active ? "default" : "pointer",
          fontFamily: "'Helvetica Neue', Helvetica, sans-serif",
          fontSize: 11, letterSpacing: "0.14em",
          fontWeight: active ? 600 : 500,
          opacity: active ? 1 : 0.45,
          transition: "opacity .2s",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.opacity = "1"; }}
        onMouseLeave={(e) => { e.currentTarget.style.opacity = active ? "1" : "0.45"; }}
      >
        {code.toUpperCase()}
      </button>
    );
  };
  return (
    <div role="group" aria-label="Idioma / Language" style={{ display: "flex", alignItems: "center", gap: 8, color }}>
      {option("en", "English")}
      <span aria-hidden="true" style={{ fontSize: 11, opacity: 0.35 }}>|</span>
      {option("pt", "Português")}
    </div>
  );
}

Object.assign(window, {
  I18N_STRINGS, EN_DATA, tr, useLang, LangToggle,
  localProjects, localTestimonials, localDeliverables,
});
