/* ============================================================
   HARAMBEE — animation engine + bilingual i18n
   Engine reproduced from the reference "Mostar city" spec.
   ============================================================ */
(function () {
  "use strict";

  /* ---------- Bilingual dictionary (RO / EN) ---------- */
  const I18N = {
    ro: {
      logo: "Asociația de Business a Românilor din Kenya",
      logo_short: "Români în Kenya",
      nav_intro: "Intro", nav_benefits: "Beneficii", nav_members: "Membri", nav_contact: "Contact",
      b1_kicker: "Comunitate", b1_title: "Rețea de contacte",
      b1_body: "O rețea profesională solidă, cu legături către parteneri locali și internaționali, prin întâlniri lunare.",
      b2_kicker: "Juridic", b2_title: "Suport juridic",
      b2_body: "Sprijin pentru înregistrarea afacerilor și consiliere privind reglementările locale, reducând riscurile legislative.",
      b3_kicker: "Vizibilitate", b3_title: "Promovare",
      b3_body: "Târguri, conferințe și evenimente care cresc vizibilitatea și atrag clienți și investitori.",
      b4_kicker: "Piața locală", b4_title: "Resurse locale",
      b4_body: "O sursă de încredere despre piața locală, tendințele economice și oportunitățile de afaceri.",
      b5_kicker: "Parteneriate", b5_title: "Colaborare",
      b5_body: "Parteneriate strategice și costuri reduse prin partajarea resurselor între membri.",
      b6_kicker: "Fiscal", b6_title: "Avantaje fiscale",
      b6_body: "Consultanță fiscală și un liant informațional cu autoritățile, precum KRA, pentru optimizarea taxelor.",
      intro_body: "Asociația de Business a Românilor din Kenya sprijină antreprenorii și profesioniștii români stabiliți în Kenya — prin networking, schimb de experiență, promovare și acces la resurse utile.",
      tag_1: "Networking", tag_2: "Suport juridic", tag_3: "Made in Romania",
      bridge_h: "Puntea dintre două lumi.",
      bridge_p: "Asociația leagă antreprenoriatul românesc de piața kenyană, într-o comunitate construită pe inițiativă, seriozitate și sprijin reciproc.",
      fact_1: "Anul înființării", fact_2: "Membri fondatori",
      bazaar_h: "Împreună creștem mai repede.",
      bazaar_p: "Rolul Asociației este să ajute afacerile românești să se adapteze pieței locale și să se extindă rapid și sustenabil în Kenya.",
      cta_member: "Devino membru",
      gallery_h: "Două lumi, o comunitate.",
      contact_label: "Contact", footer_members_link: "Vezi membrii →", footer_home_link: "← Pagina principală",
      footer_contact_link: "Trimite un mesaj →",
      footer_fine: "© 2026 Asociația de Business a Românilor din Kenya. Toate drepturile rezervate.",
      /* members page */
      members_h: "Membrii noștri",
      members_intro: "Comunitatea noastră este formată din antreprenori, investitori și profesioniști români activi în Kenya, care împărtășesc valori comune: inițiativă, seriozitate și dorința de a construi afaceri durabile.",
      members_back: "← Înapoi la membri",
      member_notfound: "Membrul nu a fost găsit.",
      member_role_label: "Rol", member_business_label: "Afacere",
      /* contact page */
      contact_h: "Contactează-ne",
      contact_intro: "Ai o întrebare, vrei să devii membru sau propui o colaborare? Scrie-ne mai jos — răspundem cât mai curând.",
      contact_quick_h: "Contact direct",
      form_name: "Nume", form_name_ph: "Numele tău",
      form_email: "Email", form_email_ph: "adresa@exemplu.com",
      form_reason: "Motivul contactării", form_reason_ph: "Alege un motiv",
      reason_member: "Devino membru", reason_partner: "Parteneriat / Colaborare",
      reason_press: "Presă / Media", reason_general: "Întrebare generală", reason_other: "Altele",
      form_message: "Mesaj", form_message_ph: "Scrie-ne mesajul tău…",
      form_submit: "Trimite mesajul", form_sending: "Se trimite…",
      form_success: "Mesajul tău a fost trimis. Îți vom răspunde cât mai curând.",
      form_error: "A apărut o eroare. Te rugăm încearcă din nou sau scrie-ne direct la info@romanian-business-club.org.",
      form_invalid: "Te rugăm completează corect toate câmpurile."
    },
    en: {
      logo: "Business Association of Romanians in Kenya",
      logo_short: "Romanians in Kenya",
      nav_intro: "Intro", nav_benefits: "Benefits", nav_members: "Members", nav_contact: "Contact",
      b1_kicker: "Community", b1_title: "Network of contacts",
      b1_body: "A solid professional network, with links to local and international partners, through monthly meetings.",
      b2_kicker: "Legal", b2_title: "Legal support",
      b2_body: "Help registering your business and guidance on local regulations, reducing legal risk.",
      b3_kicker: "Visibility", b3_title: "Promotion",
      b3_body: "Fairs, conferences and events that raise visibility and attract clients and investors.",
      b4_kicker: "Local market", b4_title: "Local resources",
      b4_body: "A trusted source on the local market, economic trends and business opportunities.",
      b5_kicker: "Partnerships", b5_title: "Collaboration",
      b5_body: "Strategic partnerships and lower costs by sharing resources between members.",
      b6_kicker: "Tax", b6_title: "Tax advantages",
      b6_body: "Tax advice and an information bridge to authorities such as KRA, to optimise your taxes.",
      intro_body: "The Business Association of Romanians in Kenya supports Romanian entrepreneurs and professionals based in Kenya — through networking, shared experience, promotion and access to useful resources.",
      tag_1: "Networking", tag_2: "Legal support", tag_3: "Made in Romania",
      bridge_h: "The bridge between two worlds.",
      bridge_p: "The association links Romanian enterprise to the Kenyan market, in a community built on initiative, integrity and mutual support.",
      fact_1: "Year founded", fact_2: "Founding members",
      bazaar_h: "Together we grow faster.",
      bazaar_p: "The association's role is to help Romanian businesses adapt to the local market and expand quickly and sustainably in Kenya.",
      cta_member: "Become a member",
      gallery_h: "Two worlds, one community.",
      contact_label: "Contact", footer_members_link: "See our members →", footer_home_link: "← Home",
      footer_contact_link: "Send a message →",
      footer_fine: "© 2026 Business Association of Romanians in Kenya. All rights reserved.",
      /* members page */
      members_h: "Our members",
      members_intro: "Our community is made up of Romanian entrepreneurs, investors, and professionals active in Kenya, all sharing the same core values: initiative, integrity, and a long-term vision.",
      members_back: "← Back to members",
      member_notfound: "Member not found.",
      member_role_label: "Role", member_business_label: "Business",
      /* contact page */
      contact_h: "Contact us",
      contact_intro: "Have a question, want to become a member, or propose a partnership? Write to us below — we'll get back to you soon.",
      contact_quick_h: "Direct contact",
      form_name: "Name", form_name_ph: "Your name",
      form_email: "Email", form_email_ph: "you@example.com",
      form_reason: "Reason for contacting", form_reason_ph: "Choose a reason",
      reason_member: "Become a member", reason_partner: "Partnership / Collaboration",
      reason_press: "Press / Media", reason_general: "General inquiry", reason_other: "Other",
      form_message: "Message", form_message_ph: "Write your message…",
      form_submit: "Send message", form_sending: "Sending…",
      form_success: "Your message has been sent. We'll get back to you soon.",
      form_error: "Something went wrong. Please try again or email us directly at info@romanian-business-club.org.",
      form_invalid: "Please fill in all fields correctly."
    }
  };

  const STORAGE_KEY = "harambee_lang";
  const root = document.documentElement;

  function currentLang() {
    return I18N[root.lang] ? root.lang : (localStorage.getItem(STORAGE_KEY) || "ro");
  }

  function applyLang(lang) {
    if (!I18N[lang]) lang = "ro";
    const dict = I18N[lang];
    root.lang = lang;
    document.querySelectorAll("[data-i18n]").forEach(function (el) {
      const key = el.getAttribute("data-i18n");
      if (dict[key] != null) el.textContent = dict[key];
    });
    document.querySelectorAll("[data-i18n-ph]").forEach(function (el) {
      const key = el.getAttribute("data-i18n-ph");
      if (dict[key] != null) el.setAttribute("placeholder", dict[key]);
    });
    document.querySelectorAll(".lang-label").forEach(function (el) {
      el.textContent = lang.toUpperCase();
    });
    document.querySelectorAll(".language-switcher").forEach(function (btn) {
      btn.setAttribute("aria-label", lang === "ro" ? "Schimbă limba (RO)" : "Change language (EN)");
    });
    try { localStorage.setItem(STORAGE_KEY, lang); } catch (e) {}
    document.dispatchEvent(new CustomEvent("harambee:langchange", { detail: { lang: lang } }));
  }

  function initLang() {
    applyLang(currentLang());
    document.querySelectorAll(".language-switcher").forEach(function (btn) {
      btn.addEventListener("click", function () {
        applyLang(root.lang === "ro" ? "en" : "ro");
      });
    });
  }

  /* expose for members.js */
  window.HARAMBEE = { i18n: I18N, applyLang: applyLang, currentLang: currentLang };

  /* ---------- Animation engine ---------- */
  function initEngine() {
    const section = document.querySelector(".cinema-scroll");
    if (!section) return;

    const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)");

    let targetMouseX = 0, targetMouseY = 0, mouseX = 0, mouseY = 0;
    let targetScroll = 0, smoothScroll = 0;
    let initialized = false, rafPending = false;

    const clamp = (v, min, max) => Math.min(max === undefined ? 1 : max, Math.max(min === undefined ? 0 : min, v));
    const smoothstep = (e0, e1, v) => { const x = clamp((v - e0) / (e1 - e0)); return x * x * (3 - 2 * x); };
    const lerp = (a, b, t) => a + (b - a) * t;
    const segmentInOut = (s, a, b, c, d) => {
      const enter = smoothstep(a, b, s), exit = smoothstep(c, d, s);
      return { enter: enter, exit: exit, active: enter * (1 - exit) };
    };
    const getScrollDistance = () =>
      clamp(-section.getBoundingClientRect().top, 0, section.offsetHeight - window.innerHeight);

    const setVar = (k, v) => root.style.setProperty(k, v);

    function requestTick() {
      if (!rafPending) { rafPending = true; requestAnimationFrame(update); }
    }

    function update() {
      rafPending = false;
      targetScroll = getScrollDistance();
      if (!initialized || reduceMotion.matches) { smoothScroll = targetScroll; initialized = true; }
      else { smoothScroll = lerp(smoothScroll, targetScroll, 0.19); }
      if (Math.abs(smoothScroll - targetScroll) < 0.08) smoothScroll = targetScroll;

      mouseX = lerp(mouseX, targetMouseX, 0.12);
      mouseY = lerp(mouseY, targetMouseY, 0.12);

      const frame2 = segmentInOut(smoothScroll, 560, 900, 1300, 1620);
      const frame3 = segmentInOut(smoothScroll, 1760, 2140, 2540, 2700);
      const progress = clamp(smoothScroll / 2700);
      const introExit = smoothstep(90, 650, smoothScroll);
      const blurActive = clamp(frame2.active + frame3.active);
      const frame2Opacity = frame2.active * (1 - frame3.enter);
      const splitDrift = Math.pow(frame2.enter, 1.5);
      const panel2Opacity = frame2.active * (1 - frame2.exit);
      const panel3Opacity = frame3.active * (1 - frame3.exit);
      const backScale = 0.76 + progress * 0.2 + frame2.enter * 0.18 + frame3.enter * 0.16;
      const sharedHeroY = progress * -74;
      const sharedHeroScale = progress * 0.23;

      const rmX = reduceMotion.matches ? 0 : mouseX;
      const rmY = reduceMotion.matches ? 0 : mouseY;
      setVar("--mx", rmX.toFixed(4));
      setVar("--my", rmY.toFixed(4));

      setVar("--back-opacity", String(1 - frame2.active * 0.06));
      setVar("--back-x", (mouseX * -12) + "px");
      setVar("--back-y", (mouseY * -4) + "px");
      setVar("--back-scale", String(backScale));
      setVar("--four-y", (10 + progress * 10) + "vh");
      setVar("--four-scale", String(0.78 + progress * 0.16));
      setVar("--bazaar-y", (20 - progress * 8) + "vh");
      setVar("--blur-px", (blurActive * 8) + "px");
      setVar("--back-brightness", String(1 - blurActive * 0.255));
      setVar("--bazaar-blur-px", (frame2.active * 8) + "px");
      setVar("--bazaar-brightness", String(1 - frame2.active * 0.255 - frame3.active * 0.06));
      setVar("--bazaar-saturation", String(1 + frame3.active * 0.18));
      setVar("--shade-opacity", "1");
      setVar("--shade-z", frame2.active > 0.02 ? "2" : "0");
      setVar("--shade-top-alpha", String(blurActive * 0.465));
      setVar("--shade-mid-alpha", String(blurActive * 0.42));
      setVar("--shade-bottom-alpha", String(blurActive * 0.51));

      setVar("--title-y", (introExit * -210) + "px");
      setVar("--title-scale", String(1 - introExit * 0.08));
      setVar("--title-opacity", String(1 - introExit));

      setVar("--bridge-x", "calc(-50% + " + (mouseX * 18) + "px)");
      setVar("--bridge-y", (mouseY * 8 + sharedHeroY - frame2.exit * 760) + "px");
      setVar("--bridge-bottom", (5 - frame2.enter * 13) + "vh");
      setVar("--bridge-width", (67.2 + frame2.enter * 37.8) + "vw");
      setVar("--bridge-scale", String(1.02 + sharedHeroScale + frame2.exit * 0.46));

      setVar("--split-left-x", "calc(-50% + " + (-splitDrift * 46) + "vw + " + (mouseX * 22) + "px)");
      setVar("--split-left-y", (mouseY * 10 + sharedHeroY - splitDrift * 180) + "px");
      setVar("--split-left-scale", String(1 + sharedHeroScale + frame2.enter * 0.74));
      setVar("--split-right-x", "calc(-50% + " + (splitDrift * 46) + "vw + " + (mouseX * 22) + "px)");
      setVar("--split-right-y", (mouseY * 10 + sharedHeroY - splitDrift * 180) + "px");
      setVar("--split-right-scale", String(1 + sharedHeroScale + frame2.enter * 0.74));

      setVar("--frame2-opacity", String(frame2Opacity));
      setVar("--frame2-x", "calc(-50% + " + (mouseX * 10) + "px)");
      setVar("--frame2-y", "calc(-50% + " + (mouseY * 8 - frame2.exit * 150) + "px)");
      setVar("--frame2-scale", String(1.06 + frame2.enter * 0.08 + frame2.exit * 0.08));

      setVar("--intro-copy-y", (introExit * 90) + "px");
      setVar("--intro-copy-opacity", String(1 - introExit));
      setVar("--panel2-opacity", String(panel2Opacity));
      setVar("--panel2-y", "calc(-50% + " + (-frame2.exit * 86 + (1 - frame2.enter) * 58) + "px)");
      setVar("--panel3-opacity", String(panel3Opacity));
      setVar("--panel3-y", "calc(-50% + " + (-frame3.exit * 86 + (1 - frame3.enter) * 58) + "px)");

      if (Math.abs(smoothScroll - targetScroll) > 0.08 ||
          Math.abs(mouseX - targetMouseX) > 0.001 ||
          Math.abs(mouseY - targetMouseY) > 0.001) {
        requestTick();
      }
    }

    /* ---------- Listeners ---------- */
    window.addEventListener("scroll", requestTick, { passive: true });
    window.addEventListener("resize", requestTick);
    window.addEventListener("pointermove", function (e) {
      targetMouseX = e.clientX / window.innerWidth - 0.5;
      targetMouseY = e.clientY / window.innerHeight - 0.5;
      requestTick();
    }, { passive: true });

    requestTick();
  }

  /* ---------- Boot ---------- */
  function boot() { initLang(); initEngine(); }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
  else boot();
})();
