
const { useEffect, useRef, useState } = React;

const CURRENT_LANG_APP =
  (typeof window !== "undefined" && window.location.pathname.includes("/pt/"))
    ? "pt"
    : "en";

const ASSET_BASE_APP = CURRENT_LANG_APP === "pt" ? "../" : "";
const A = (path) => {
  if (!path) return path;
  if (/^(https?:|\/\/|data:|\.\.\/|\/|#)/.test(path)) return path;
  return ASSET_BASE_APP + path;
};
if (typeof window !== "undefined") {
  window.__DSMADE_ASSET_BASE = ASSET_BASE_APP;
  window.__DSMADE_A = A;
}

const L_EN = {
  heroTitle1: "WE MADE.",
  heroTitle2: "WE LEAD.",
  heroTitle3: "MADE DIFFERENT.",
  heroLede: "Built for ambition, engineered for performance. Made connects product development with international distribution, helping high-growth businesses enter the Brazilian market.",
  heroBtn1: "About Us",
  heroBtn2: "Business",

  introScrollHint: "Scroll to expand",

  partnersGroupAffiliates: "Group\nAffiliates",
  partnersStrategicPartner: "Strategic\nPartner",

  keyAffTitle: ["DS GROUP", "BIG MOVES", "MADE SIMPLE"],
  keyAffFooterLabel: "KEY AFFILIATES",
  keyAffAccordionLumora: "Lumora distributor",

  byLumoraBy: "by",
  byLumoraSuffix: "distributor",

  byKSBy: "by",

  proofTitle: ["How", "<span class='ds-strong'>DS GROUP</span>", "adds up"],
  proofStats: [
    { label: "Years of proven expertise." },
    { label: "Annual group revenue." },
    { label: "Global trade & logistics networks." },
    { label: "Global corporate partners." },
  ],
  proofEyebrow: "HIGHLIGHT",
  proofHeadline1: "Deep roots in manufacturing,",
  proofHeadline2: "built for global scale.",

  lumoraTitle: ["Moving K-beauty", `<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> all over Brazil`],
  lumoraCards: [
    { title: "Drugstores",         lines: ["Direct distribution across major pharmacy chains. High daily foot traffic and steady volume sales."] },
    { title: "Multi-brand Stores", lines: ["Entry into department stores and premium beauty hubs. Strategic placement alongside global beauty brands."] },
    { title: "Regional Retailers", lines: ["Strong partnerships with key regional networks. Expands coverage beyond major capital cities."] },
    { title: "Trendy Local Shops", lines: ["Presence in key commercial streets and select shops. Direct exposure to trend-focused younger shoppers."] },
  ],
  lumoraLearnMore: "Learn more",
  lumoraLearnMoreAria: "Learn more about Lumora",

  ksTitle: ["Authentic K-beauty", `<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> delivered direct`, "across brazil"],
  ksLearnMore: "Learn more",
  ksLearnMoreAria: "Learn more about DS Group",
  ksOpenInstagram: "Open on Instagram",
  ksOpenInstagramAria: "Open @kscosmeticos_ofc on Instagram (opens in new tab)",

  newsroomTitle: [`<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> Moves`],
  newsroomCard1Date: "2026.08.13",
  newsroomCard1Tag: "Company News",
  newsroomCard1Title: "DS Group launches 'Lumora'",
  newsroomCard1Teaser: "DS Group has completed the acquisition and re-launched a specialized quasi-drug distributor as Lumora, scaling Brazil operations in three months and now expanding across Latin America.",
  newsroomCard2Date: "2026.08.10",
  newsroomCard2Tag: "Company News",
  newsroomCard2Title: "DS MADE Homepage Renewed",
  newsroomCard2Teaser: "DS MADE has fully renewed its corporate website to match the group's expanding global portfolio, bringing every brand story into one clearer narrative.",
  newsroomReadMore: "Read more →",
  newsroomReadFull: "Read full article",
  newsroomCta: "Learn more",
  newsroomCtaAria: "See all press releases",
  newsroomReadPressAria: "Read press release",
};

const L_PT = {
  heroTitle1: "WE MADE.",
  heroTitle2: "WE LEAD.",
  heroTitle3: "MADE DIFFERENT.",
  heroLede: "Feita para ambição, projetada para performance. A DSMADE conecta desenvolvimento de produto e distribuição internacional para acelerar negócios de alto crescimento no Brasil.",
  heroBtn1: "Sobre nós",
  heroBtn2: "Negócios",

  introScrollHint: "Role para expandir",

  partnersGroupAffiliates: "Empresas\ndo grupo",
  partnersStrategicPartner: "Parceiros\nestratégicos",

  keyAffTitle: ["GRUPO DS", "GRANDES PASSOS", "DE FORMA SIMPLES"],
  keyAffFooterLabel: "EMPRESAS DO GRUPO",
  keyAffAccordionLumora: "Lumora distribuidora",

  byLumoraBy: "pela",
  byLumoraSuffix: "distribuidora",

  byKSBy: "pela",

  proofTitle: ["O que o", "<span class='ds-strong'>GRUPO DS</span>", "representa"],
  proofStats: [
    { label: "Anos de expertise comprovada." },
    { label: "Receita anual do grupo." },
    { label: "Redes globais de comércio e logística." },
    { label: "Parceiros corporativos globais." },
  ],
  proofEyebrow: "DESTAQUE",
  proofHeadline1: "Raízes profundas na indústria,",
  proofHeadline2: "prontas para escala global.",

  lumoraTitle: ["Levando K-beauty", `<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> por todo o Brasil`],
  lumoraCards: [
    { title: "Farmácias",              lines: ["Distribuição direta nas principais redes de farmácia. Alto fluxo diário e volume de vendas consistente."] },
    { title: "Lojas multi-marca",      lines: ["Entrada em grandes magazines e hubs premium de beleza. Posicionamento estratégico ao lado de marcas globais."] },
    { title: "Varejistas regionais",   lines: ["Parcerias sólidas com redes regionais estratégicas. Expansão para além das grandes capitais."] },
    { title: "Lojas locais em alta",   lines: ["Presença nas principais ruas comerciais e lojas selecionadas. Exposição direta ao público jovem e antenado."] },
  ],
  lumoraLearnMore: "Saiba mais",
  lumoraLearnMoreAria: "Saiba mais sobre a Lumora",

  ksTitle: ["K-beauty autêntica", `<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> direto para você`, "em todo o Brasil"],
  ksLearnMore: "Saiba mais",
  ksLearnMoreAria: "Saiba mais sobre o Grupo DS",
  ksOpenInstagram: "Abrir no Instagram",
  ksOpenInstagramAria: "Abrir @kscosmeticos_ofc no Instagram (nova aba)",

  newsroomTitle: [`<span class='plane-glyph plane-glyph--paper' aria-hidden='true'><img src='${ASSET_BASE_APP}assets/paper-plane-final.png' alt='' /></span> Movimentos`],
  newsroomCard1Date: "13.08.2026",
  newsroomCard1Tag: "Notícias da Empresa",
  newsroomCard1Title: "Grupo DS lança 'Lumora'",
  newsroomCard1Teaser: "O Grupo DS concluiu a aquisição e relançou uma distribuidora especializada em produtos correlatos como Lumora, escalando as operações no Brasil em três meses e agora expandindo por toda a América Latina.",
  newsroomCard2Date: "10.08.2026",
  newsroomCard2Tag: "Notícias da Empresa",
  newsroomCard2Title: "Site da DS MADE renovado",
  newsroomCard2Teaser: "A DSMADE renovou completamente seu site institucional para refletir o portfólio global em expansão do grupo, reunindo cada história de marca em uma narrativa mais clara.",
  newsroomReadMore: "Ler mais →",
  newsroomReadFull: "Ler artigo completo",
  newsroomCta: "Ver todas",
  newsroomCtaAria: "Ver todas as notícias",
  newsroomReadPressAria: "Ler comunicado",
};

const L = CURRENT_LANG_APP === "pt" ? L_PT : L_EN;

function DSMark({ size = 28, variant = "dark" }) {
  const color = variant === "light" ? "#ffffff" : "#0a0a0a";
  const w = Math.round(size * 1.6);   // horizontal bar
  const h = Math.max(4, Math.round(size * 0.28));
  return (
    <span
      aria-hidden="true"
      style={{
        display: "inline-block",
        width: w,
        height: h,
        background: color,
        borderRadius: 999,
        flexShrink: 0,
      }}
    />
  );
}
const RocketMark = DSMark;


const HERO_TWEAK_DEFAULTS = {
  "titleLine1": "WE MADE.",
  "titleLine2": "WE LEAD.",
  "titleLine3": "MADE DIFFERENT.",
  "titleSize": 100,
  "titleLineGap": 1.45,
  "ledeText": "Built for ambition, engineered for performance. Made connects product development with international distribution, helping high-growth businesses enter the Brazilian market.",
  "ledeSize": 20,
  "ledeMarginTop": 60,
  "ledeMaxWidth": 120,
  "btn1Label": "About Us",
  "btn1Href": "pages/about-us.html",
  "btn2Label": "Business",
  "btn2Href": "pages/business.html",
  "navDropdownStyle": "minimal"
};

if (CURRENT_LANG_APP === "pt") {
  HERO_TWEAK_DEFAULTS.titleLine1 = L.heroTitle1;
  HERO_TWEAK_DEFAULTS.titleLine2 = L.heroTitle2;
  HERO_TWEAK_DEFAULTS.titleLine3 = L.heroTitle3;
  HERO_TWEAK_DEFAULTS.ledeText   = L.heroLede;
  HERO_TWEAK_DEFAULTS.btn1Label  = L.heroBtn1;
  HERO_TWEAK_DEFAULTS.btn2Label  = L.heroBtn2;
  HERO_TWEAK_DEFAULTS.btn1Href   = "about-us.html";
  HERO_TWEAK_DEFAULTS.btn2Href   = "business.html";  // TODO(pt): create pt/business.html
}
if (typeof window !== "undefined") window.HERO_TWEAK_DEFAULTS = HERO_TWEAK_DEFAULTS;

function Hero() {
  const titleRef = useRef(null);
  const ledeRef = useRef(null);
  const actionsRef = useRef(null);

  const useTweaksHook = (typeof window !== "undefined" && window.useTweaks) || null;
  const [tState, setTweak] = useTweaksHook ? useTweaksHook(HERO_TWEAK_DEFAULTS) : [HERO_TWEAK_DEFAULTS, () => {}];
  const t = tState;

  useEffect(() => {
    const g = window.gsap;
    if (!g) return;
    const lines = titleRef.current.querySelectorAll(".line");
    g.set(lines, { y: "105%" });
    g.to(lines, {
      y: 0,
      duration: 1.1,
      ease: "power3.out",
      stagger: 0.09,
      delay: 0.2,
    });
    g.to(ledeRef.current, { opacity: 1, y: 0, duration: 0.8, ease: "power2.out", delay: 0.9 });
    g.to(actionsRef.current, { opacity: 1, y: 0, duration: 0.8, ease: "power2.out", delay: 1.05 });
  }, [t.titleLine1, t.titleLine2, t.titleLine3]);

  const titleLines = [t.titleLine1, t.titleLine2, t.titleLine3].filter(l => l && l.trim() !== "");

  return (
    <section className="hero" data-screen-label="01 Hero" id="top">
      <div className="hero-inner hero-inner--centered">
        <h1
          className="hero-title hero-title--centered"
          ref={titleRef}
          style={{
            fontSize: `clamp(40px, ${t.titleSize * 0.065}vw + 20px, ${t.titleSize * 1.2}px)`,
            lineHeight: t.titleLineGap,
          }}
        >
          {titleLines.map((l, i) => (
            <span className="line-mask" key={i}>
              <span className="line">{l}</span>
            </span>
          ))}
        </h1>

        <div className="hero-below" style={{ marginTop: `${t.ledeMarginTop}px` }}>
          <p
            className="hero-lede"
            ref={ledeRef}
            style={{
              transform: "translateY(16px)",
              fontSize: `${t.ledeSize}px`,
              maxWidth: `${t.ledeMaxWidth}ch`,
              marginLeft: "auto",
              marginRight: "auto",
              textAlign: "center",
            }}
          >
            {t.ledeText}
          </p>
          <div
            className="hero-actions"
            ref={actionsRef}
            style={{ transform: "translateY(16px)" }}
          >
            <a className="btn btn-outline-light" href={t.btn1Href}>
              {t.btn1Label}
              <span className="btn-arrow">→</span>
            </a>
            <a className="btn btn-outline-light" href={t.btn2Href}>
              {t.btn2Label}
              <span className="btn-arrow">→</span>
            </a>
          </div>
        </div>
      </div>

      <HeroTweaks t={t} setTweak={setTweak} />
    </section>
  );
}

function HeroTweaks({ t, setTweak }) {
  const P = typeof window !== "undefined" ? window.TweaksPanel : null;
  const S = typeof window !== "undefined" ? window.TweakSection : null;
  const Text = typeof window !== "undefined" ? window.TweakText : null;
  const Num = typeof window !== "undefined" ? window.TweakNumber : null;
  const Slider = typeof window !== "undefined" ? window.TweakSlider : null;
  const Radio = typeof window !== "undefined" ? window.TweakRadio : null;
  if (!P || !S || !Text || !Slider || !Radio) return null;

  return (
    <P title="Tweaks">
      <S title="Title (centered)">
        <Text label="Line 1"     value={t.titleLine1}   onChange={(v) => setTweak("titleLine1", v)} />
        <Text label="Line 2"     value={t.titleLine2}   onChange={(v) => setTweak("titleLine2", v)} />
        <Text label="Line 3"     value={t.titleLine3}   onChange={(v) => setTweak("titleLine3", v)} />
        <Slider label="Size"     value={t.titleSize}    onChange={(v) => setTweak("titleSize", v)}    min={40} max={180} step={2} />
        <Slider label="Line gap" value={t.titleLineGap} onChange={(v) => setTweak("titleLineGap", v)} min={0.8} max={6} step={0.05} />
      </S>
      <S title="Lede (below title, centered)">
        <Text  label="Text"      value={t.ledeText}      onChange={(v) => setTweak("ledeText", v)} multiline />
        <Slider label="Size"     value={t.ledeSize}      onChange={(v) => setTweak("ledeSize", v)} min={14} max={32} step={1} />
        <Slider label="Width"    value={t.ledeMaxWidth}  onChange={(v) => setTweak("ledeMaxWidth", v)} min={20} max={90} step={1} />
        <Slider label="Top gap"  value={t.ledeMarginTop} onChange={(v) => setTweak("ledeMarginTop", v)} min={0} max={260} step={4} />
      </S>
      <S title="Buttons">
        <Text label="Btn 1 label" value={t.btn1Label} onChange={(v) => setTweak("btn1Label", v)} />
        <Text label="Btn 1 link"  value={t.btn1Href}  onChange={(v) => setTweak("btn1Href", v)} />
        <Text label="Btn 2 label" value={t.btn2Label} onChange={(v) => setTweak("btn2Label", v)} />
        <Text label="Btn 2 link"  value={t.btn2Href}  onChange={(v) => setTweak("btn2Href", v)} />
      </S>
      <S title="Nav dropdown">
        <Radio
          label="Style"
          value={t.navDropdownStyle}
          onChange={(v) => setTweak("navDropdownStyle", v)}
          options={[
            { value: "minimal",  label: "Minimal"  },
            { value: "bordered", label: "Bordered" },
            { value: "dark",     label: "Dark"     },
          ]}
        />
      </S>
    </P>
  );
}


function AnimatedTitle({ lines, className = "" }) {
  const ref = useRef(null);
  useEffect(() => {
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!g || !ST) return;
    const els = ref.current.querySelectorAll(".line");
    const t = g.to(els, {
      y: 0,
      duration: 1,
      ease: "power3.out",
      stagger: 0.08,
      scrollTrigger: {
        trigger: ref.current,
        start: "top 82%",
        toggleActions: "play none none none",
      },
    });
    return () => { t.scrollTrigger && t.scrollTrigger.kill(); t.kill(); };
  }, []);
  return (
    <h2 ref={ref} className={`big-title ${className}`}>
      {lines.map((l, i) => (
        <span className="line-mask" key={i}>
          <span className="line" dangerouslySetInnerHTML={{ __html: l }} />
        </span>
      ))}
    </h2>
  );
}

function ByLumora() {
  const ref = useRef(null);
  useEffect(() => {
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!g || !ST || !ref.current) return;
    const els = ref.current.querySelectorAll(".line");
    const t = g.to(els, {
      y: 0,
      duration: 1,
      ease: "power3.out",
      stagger: 0,
      scrollTrigger: {
        trigger: ref.current,
        start: "top 82%",
        toggleActions: "play none none none",
      },
    });
    return () => { t.scrollTrigger && t.scrollTrigger.kill(); t.kill(); };
  }, []);
  return (
    <div className="by-lumora-row" ref={ref}>
      <div className="by-lumora">
        <span className="by-lumora__spot by-lumora__spot--magenta" aria-hidden="true" />
        <span className="by-lumora__spot by-lumora__spot--cyan" aria-hidden="true" />
        <span className="by-lumora__spot by-lumora__spot--violet" aria-hidden="true" />
        <span className="line-mask by-lumora__by-mask">
          <span className="line by-lumora__by">{L.byLumoraBy}</span>
        </span>
        <span className="line-mask by-lumora__logo-mask">
          <span className="line by-lumora__logo-line">
            <picture>
              <source srcSet={A("assets/lumora-logo.webp")} type="image/webp" />
              <img
                src={A("assets/lumora-logo.png")}
                alt="LUMORA"
                className="by-lumora__logo"
                width="1024"
                height="170"
                loading="lazy"
                decoding="async"
              />
            </picture>
          </span>
        </span>
      </div>
      <span className="line-mask by-lumora__suffix-mask">
        <span className="line by-lumora__suffix">{L.byLumoraSuffix}</span>
      </span>
    </div>
  );
}

function ByKS() {
  const ref = useRef(null);
  useEffect(() => {
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!g || !ST || !ref.current) return;
    const els = ref.current.querySelectorAll(".line");
    const t = g.to(els, {
      y: 0,
      duration: 1,
      ease: "power3.out",
      stagger: 0,
      scrollTrigger: {
        trigger: ref.current,
        start: "top 82%",
        toggleActions: "play none none none",
      },
    });
    return () => { t.scrollTrigger && t.scrollTrigger.kill(); t.kill(); };
  }, []);
  return (
    <div className="by-ks" ref={ref}>
      <span className="line-mask by-ks__by-mask">
        <span className="line by-ks__by">{L.byKSBy}</span>
      </span>
      <span className="line-mask by-ks__logo-mask">
        <span className="line by-ks__logo-line">
          <span className="by-ks__spot by-ks__spot--magenta" aria-hidden="true" />
          <span className="by-ks__spot by-ks__spot--cyan" aria-hidden="true" />
          <span className="by-ks__spot by-ks__spot--violet" aria-hidden="true" />
          <img
            src={A("assets/ks-logo.png?v=20260811d")}
            alt="KS"
            className="by-ks__logo"
            width="150"
            height="150"
            loading="lazy"
            decoding="async"
          />
        </span>
      </span>
    </div>
  );
}

function Intro() {
  const [SE, setSE] = useState(() => (typeof window !== "undefined" ? window.ScrollExpand : null));
  useEffect(() => {
    if (SE) return;
    let cancelled = false;
    const check = () => {
      if (cancelled) return;
      if (typeof window !== "undefined" && window.ScrollExpand) {
        setSE(() => window.ScrollExpand);
      } else {
        setTimeout(check, 60);
      }
    };
    check();
    return () => { cancelled = true; };
  }, [SE]);

  const getHeroSrc = () =>
    (typeof window !== "undefined" && window.matchMedia("(max-width: 768px)").matches)
      ? A("assets/model-dsmade-mobile.mp4") : A("assets/model-dsmade.mp4");
  const [heroSrc, setHeroSrc] = useState(getHeroSrc);
  useEffect(() => {
    if (typeof window === "undefined") return;
    const mql = window.matchMedia("(max-width: 768px)");
    const onChange = () => setHeroSrc(getHeroSrc());
    if (mql.addEventListener) mql.addEventListener("change", onChange);
    else mql.addListener(onChange);
    return () => {
      if (mql.removeEventListener) mql.removeEventListener("change", onChange);
      else mql.removeListener(onChange);
    };
  }, []);

  return (
    <section className="section dark-section intro-section" data-screen-label="02 Intro" id="services">
      <div className="model-scroll-expand-host">
        {SE ? (
          <SE
            src={heroSrc}
            mediaType="video"
            alt=""
            title=""
            scrollHint={L.introScrollHint}
            startWidth={42}
            startHeight={58}
            startRadius={24}
            endRadius={0}
            mediaZoom={1.35}
            scrollDistance={1.5}
            smoothing={0.1}
            overlayScrim={0.45}
          />
        ) : null}
      </div>
    </section>
  );
}

function Partners() {
  const rowsRef = React.useRef([]);
  const containerRef = React.useRef(null);
  const SPEED_PX_PER_SEC = 60; // tweak here to change overall marquee pace
  const DIRECTIONS = [-1, +1];  // top row scrolls left, bottom scrolls right

  React.useEffect(() => {
    const halfWidths = [0, 0];
    const offsets    = [0, 0];
    let lastT = 0;
    let rafId = 0;
    let visible = true;

    const measure = () => {
      rowsRef.current.forEach((track, i) => {
        if (!track) return;
        const copyCount = track.children.length / 2;
        let hw = 0;
        for (let j = 0; j < copyCount; j++) {
          const child = track.children[j];
          if (child) hw += child.offsetWidth;
        }
        const gapStr = getComputedStyle(track).columnGap || getComputedStyle(track).gap;
        const gap = parseFloat(gapStr) || 0;
        hw += gap * copyCount; // include trailing gap between copies
        halfWidths[i] = hw || track.scrollWidth / 2;
      });
    };

    const tick = (t) => {
      if (!lastT) lastT = t;
      const dt = Math.min(0.1, (t - lastT) / 1000); // cap dt so tab-blur returns don't leap
      lastT = t;
      if (visible) {
        rowsRef.current.forEach((track, i) => {
          if (!track || !halfWidths[i]) return;
          const hw = halfWidths[i];
          offsets[i] += DIRECTIONS[i] * SPEED_PX_PER_SEC * dt;
          while (offsets[i] > 0)   offsets[i] -= hw;
          while (offsets[i] < -hw) offsets[i] += hw;
          track.style.transform = `translate3d(${offsets[i].toFixed(2)}px, 0, 0)`;
        });
      }
      rafId = requestAnimationFrame(tick);
    };

    measure();
    if (halfWidths[1]) offsets[1] = -halfWidths[1] * 0.5;
    rafId = requestAnimationFrame(tick);

    let remeasureCount = 0;
    const remeasureId = setInterval(() => {
      const before = halfWidths[1];
      measure();
      remeasureCount++;
      if (!before && halfWidths[1] && Math.abs(offsets[1]) < 1) {
        offsets[1] = -halfWidths[1] * 0.5;
      }
      if (remeasureCount > 20) clearInterval(remeasureId); // ~5s max
    }, 250);

    const io = new IntersectionObserver(
      (entries) => { visible = entries[0].isIntersecting; },
      { rootMargin: "200px 0px" }
    );
    if (containerRef.current) io.observe(containerRef.current);

    const ro = new ResizeObserver(() => { measure(); });
    if (containerRef.current) ro.observe(containerRef.current);

    const imgs = rowsRef.current
      .flatMap((t) => (t ? Array.from(t.querySelectorAll("img")) : []));
    imgs.forEach((img) => {
      if (img.complete) return;
      img.addEventListener("load", measure, { once: true });
    });
    window.addEventListener("resize", measure);

    return () => {
      cancelAnimationFrame(rafId);
      clearInterval(remeasureId);
      io.disconnect();
      ro.disconnect();
      window.removeEventListener("resize", measure);
    };
  }, []);

  const strategic = [
    "DS Plastic",
    "DS International",
    "DS da Amazônia",
    "Shine International",
    "Shine USA",
    "Lumora",
    "KS Cosméticos",
    "ED International",
    "Rell Máquinas",
    "DS Logis",
  ];
  const collab = [
    { name: "CMA CGM",           src: A("assets/partners/cma-cgm-white.png") },
    { name: "Maersk",            src: A("assets/partners/maersk-white.png") },
    { name: "Air Canada",        src: A("assets/partners/air-canada-white.png") },
    { name: "American Airlines", src: A("assets/partners/american-airlines-white.png") },
    { name: "Lotte Chemical",    src: A("assets/partners/lotte-chemical-white.png") },
    { name: "Banco Santander",   src: A("assets/partners/santander-white.png") },
    { name: "Banco Itaú",        src: A("assets/partners/itau-white.png") },
  ];

  return (
    <section className="section dark-section partners-section" data-screen-label="03 Partners" id="partners">
      <div className="container" ref={containerRef}>
        <div className="partners-row">
          <h4 className="partners-label" dangerouslySetInnerHTML={{__html: L.partnersGroupAffiliates.replace(/\n/g, '<br/>')}} />
          <div className="partners-logos">
            <div
              className="partners-marquee-track"
              aria-hidden="false"
              ref={(el) => (rowsRef.current[0] = el)}
            >
              {strategic.map((n, i) => (
                <div key={`a-${i}`} className="partner-logo partner-logo-lg">{n}</div>
              ))}
              {strategic.map((n, i) => (
                <div key={`b-${i}`} className="partner-logo partner-logo-lg" aria-hidden="true">{n}</div>
              ))}
            </div>
          </div>
        </div>
        <div className="partners-divider" />
        <div className="partners-row">
          <h4 className="partners-label" dangerouslySetInnerHTML={{__html: L.partnersStrategicPartner.replace(/\n/g, '<br/>')}} />
          <div className="partners-logos">
            <div
              className="partners-marquee-track partners-marquee-track--reverse"
              aria-hidden="false"
              ref={(el) => (rowsRef.current[1] = el)}
            >
              {collab.map((l, i) => {
                const slug = (l.src.split("/").pop() || "").replace(/\.[^.]+$/, "");
                return (
                  <div key={`a-${i}`} className="partner-logo partner-logo-img" data-logo={slug} title={l.name}>
                    <img src={l.src} alt={l.name} decoding="async" fetchpriority="high" />
                  </div>
                );
              })}
              {collab.map((l, i) => {
                const slug = (l.src.split("/").pop() || "").replace(/\.[^.]+$/, "");
                return (
                  <div key={`b-${i}`} className="partner-logo partner-logo-img" data-logo={slug} aria-hidden="true">
                    <img src={l.src} alt="" decoding="async" fetchpriority="high" />
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function KeyAffiliates() {
  const AG = typeof window !== "undefined" ? window.AccordionGallery : null;

  const items = [
    { image: A("assets/accordion/01-ds-plastic.jpg"), label: "DS Plastic", link: A("brands/ds-plastic.html") },
    { image: A("assets/accordion/02-global.jpg"), label: L.keyAffAccordionLumora, link: A("brands/lumora.html") },
    { image: A("assets/accordion/03-ds-international.jpg"), label: "DS International", link: A("brands/ds-international.html") },
    { image: A("assets/accordion/04-shine.jpg"), label: "Shine International", link: A("brands/shine-international.html") },
  ];

  return (
    <section className="section key-affiliates" data-screen-label="04 Key Affiliates" id="about" data-nav-theme="light">
      <div className="container">
        <div className="key-affiliates-head">
          <AnimatedTitle lines={L.keyAffTitle} />
        </div>

        <div className="key-affiliates-accordion-wrap">
          {AG ? (
            <AG
              items={items}
              defaultIndex={0}
              expandRatio={0.5}
              trigger="hover"
              accentColor="#ff2f6b"
              overlayColor="#0a0713"
              textColor="#ffffff"
              height={520}
              gap={12}
              radius={18}
              parallax={0.6}
              duration={0.75}
              ease="power2.inOut"
              tilt={0}
            />
          ) : null}
        </div>

        <div className="key-affiliates" aria-label="Key Affiliates">
          <span className="key-affiliates__dash" aria-hidden="true">—</span>
          <span className="key-affiliates__label">{L.keyAffFooterLabel}</span>
          <span className="key-affiliates__rule" aria-hidden="true" />
        </div>
      </div>
    </section>
  );
}

function CountUp({ target, suffix = "", prefix = "" }) {
  const [val, setVal] = useState(0);
  const liveRef = useRef(null);
  useEffect(() => {
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!g || !ST) return;
    const state = { v: 0 };
    const tw = g.to(state, {
      v: target,
      duration: 2,
      ease: "power2.out",
      onUpdate: () => setVal(Math.round(state.v)),
      scrollTrigger: {
        trigger: liveRef.current,
        start: "top 88%",
        toggleActions: "play none none none",
      },
    });
    return () => { tw.scrollTrigger && tw.scrollTrigger.kill(); tw.kill(); };
  }, [target]);
  const finalText = prefix + target.toLocaleString() + suffix;
  const liveText  = prefix + val.toLocaleString() + suffix;
  return (
    <span className="countup-slot">
      <span className="countup-ghost" aria-hidden="true">{finalText}</span>
      <span className="countup-live" ref={liveRef}>{liveText}</span>
    </span>
  );
}

function Status() {
  const stats = [
    { num: 40,   suffix: "+",              label: L.proofStats[0].label },
    { num: 600,  prefix: "$", suffix: "M+", label: L.proofStats[1].label },
    { num: 20,   suffix: "+",              label: L.proofStats[2].label },
    { num: 50,   suffix: "+",              label: L.proofStats[3].label },
  ];
  return (
    <section className="section status-section" data-screen-label="05 Status" id="ventures" data-nav-theme="light">
      <div className="container">
        <div className="proof-head">
          <AnimatedTitle lines={L.proofTitle} />
        </div>
        <div className="proof-grid">
          <div className="proof-list">
            {stats.map((s, i) => (
              <div className="proof-row" key={i}>
                <div className="proof-label">{s.label}</div>
                <div className="proof-num">
                  <CountUp target={s.num} prefix={s.prefix || ""} suffix={s.suffix || ""} />
                </div>
              </div>
            ))}
          </div>
          <div className="proof-visual proof-visual--statement">
            <article className="proof-headline">
              <span className="proof-headline__eyebrow">{L.proofEyebrow}</span>
              <h3 className="proof-headline__title">
                <span className="proof-headline__line">{L.proofHeadline1}</span>
                <span className="proof-headline__line proof-headline__line--em">{L.proofHeadline2}</span>
              </h3>
              <span className="proof-headline__rule" aria-hidden="true" />
            </article>
          </div>
        </div>
      </div>
    </section>
  );
}

function Lumora() {
  const [hover, setHover] = useState(-1);

  const items = [
    {
      title: L.lumoraCards[0].title,
      lines: L.lumoraCards[0].lines,
      accent: "green",
      photos: [
        { src: A("assets/drugstore-1.jpg"), label: "VOL. 01", num: "SS / 26" },
        { src: A("assets/drugstore-2.jpg"), label: "VOL. 02", num: "URBAN" },
      ],
    },
    {
      title: L.lumoraCards[1].title,
      lines: L.lumoraCards[1].lines,
      accent: "neutral",
      photos: [
        { src: A("assets/multibrand-1.jpg"), label: "VOL. 03", num: "FW / 26", pos: "50% 40%" },
        { src: A("assets/multibrand-2.jpg"), label: "VOL. 04", num: "PREMIUM", pos: "50% 35%" },
      ],
    },
    {
      title: L.lumoraCards[2].title,
      lines: L.lumoraCards[2].lines,
      accent: "green",
      photos: [
        { src: A("assets/regional-1.jpg"), label: "VOL. 05", num: "NORTH", pos: "50% 35%" },
        { src: A("assets/regional-2.jpg"), label: "VOL. 06", num: "SOUTH", pos: "50% 15%" },
      ],
    },
    {
      title: L.lumoraCards[3].title,
      lines: L.lumoraCards[3].lines,
      accent: "blue",
      photos: [
        { src: A("assets/local-1.jpg"), label: "VOL. 07", num: "STREET", pos: "50% 45%" },
        { src: A("assets/local-2.jpg"), label: "VOL. 08", num: "SELECT", pos: "50% 50%" },
      ],
    },
  ];

  const hoveredCol = hover < 0 ? -1 : hover % 2;
  const hoveredRow = hover < 0 ? -1 : Math.floor(hover / 2);

  return (
    <section className="section dark-section lumora-section" data-screen-label="06 Lumora">
      <div className="container">
        <div className="lumora-head lumora-head--with-partner">
          <AnimatedTitle lines={L.lumoraTitle} className="lumora-title" />
          <ByLumora />
        </div>

        <div
          className="paths-grid"
          onMouseLeave={() => setHover(-1)}
        >
          {[0, 1].map((colIdx) => {
            const topI = colIdx;
            const botI = colIdx + 2;
            let topFlex = 1, botFlex = 1;
            if (hoveredCol === colIdx) {
              if (hoveredRow === 0) { topFlex = 1.7; botFlex = 0.3; }
              else                  { topFlex = 0.3; botFlex = 1.7; }
            }
            return (
              <div className="paths-col" key={colIdx}>
                {[topI, botI].map((i, rowIdx) => {
                  const it = items[i];
                  const flex = rowIdx === 0 ? topFlex : botFlex;
                  return (
                    <article
                      key={i}
                      className={`path-card ${hover === i ? "is-hover" : ""} accent-${it.accent}`}
                      style={{ flex: `${flex} 1 0` }}
                      onMouseEnter={() => setHover(i)}
                      onFocus={() => setHover(i)}
                      onClick={() => setHover(hover === i ? -1 : i)}
                      tabIndex={0}
                    >
                      <div className="path-header">
                        <h3>{it.title}</h3>
                        <div className="path-plus" aria-hidden="true">
                          <svg className="path-plus-icon icon-plus" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
                            <path d="M12 5v14M5 12h14" />
                          </svg>
                          <svg className="path-plus-icon icon-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M5 12h14M13 6l6 6-6 6" />
                          </svg>
                        </div>
                      </div>
                      {it.photos && (
                        <div className="path-photos">
                          {it.photos.map((p, pi) => (
                            <div className="path-photo" key={pi}>
                              <img src={p.src} alt="" style={p.pos ? { objectPosition: p.pos } : undefined} />
                              <div className="path-photo__overlay" aria-hidden="true"></div>
                              <div className="path-photo__label">{p.label}</div>
                              <div className="path-photo__num">{p.num}</div>
                              <span className="path-photo__crop tl"></span>
                              <span className="path-photo__crop tr"></span>
                              <span className="path-photo__crop bl"></span>
                              <span className="path-photo__crop br"></span>
                            </div>
                          ))}
                        </div>
                      )}
                      <div className="path-body-center">
                        {it.lines.map((ln, k) => (
                          <p key={k}>{ln}</p>
                        ))}
                      </div>
                    </article>
                  );
                })}
              </div>
            );
          })}
        </div>
        <div className="lumora-cta-row">
          <a className="paths-cta" href={A("brands/lumora.html")} aria-label={L.lumoraLearnMoreAria}>
            <span className="paths-cta__label">{L.lumoraLearnMore}</span>
            <span className="paths-cta__arrow" aria-hidden="true">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="5" y1="12" x2="19" y2="12" />
                <polyline points="12 5 19 12 12 19" />
              </svg>
            </span>
          </a>
        </div>
      </div>
    </section>
  );
}

function KS() {

  const topRef = React.useRef(null);
  React.useEffect(() => {
    const topEl = topRef.current;
    if (!topEl) return;
    let raf = 0;
    const measure = () => {
      const dLine = Array.from(topEl.querySelectorAll(".line-mask"))
        .find(el => el.textContent.trim().toLowerCase().startsWith("delivered direct"));
      if (!dLine) return;
      const inner = dLine.querySelector(".line") || dLine.firstElementChild;
      if (!inner) return;
      const range = document.createRange();
      range.selectNodeContents(inner);
      const textRect = range.getBoundingClientRect();
      const topRect = topEl.getBoundingClientRect();
      const rightRel = textRect.right - topRect.left;
      if (rightRel > 0 && Number.isFinite(rightRel)) {
        topEl.style.setProperty("--dd-text-right", `${Math.round(rightRel)}px`);
      }
    };
    const schedule = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(measure);
    };
    schedule();
    const ro = new ResizeObserver(schedule);
    ro.observe(topEl);
    window.addEventListener("resize", schedule);
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(schedule).catch(() => {});
    }
    const t1 = setTimeout(schedule, 300);
    const t2 = setTimeout(schedule, 1200);
    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
      window.removeEventListener("resize", schedule);
      clearTimeout(t1);
      clearTimeout(t2);
    };
  }, []);

  return (
    <section className="section dark-section ks-section" data-screen-label="07 KS" id="paths">
      <div className="grain" aria-hidden="true" />
      <div className="container">
        <div className="paths-top" ref={topRef}>
          <AnimatedTitle lines={L.ksTitle} />
          <ByKS />
          <div className="paths-cta-row paths-cta-row--under-logo">
            <a className="paths-cta" href={CURRENT_LANG_APP === "pt" ? "about-us.html" : "pages/about-us.html"} aria-label={L.ksLearnMoreAria}>
              <span className="paths-cta__label">{L.ksLearnMore}</span>
              <span className="paths-cta__arrow" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="5" y1="12" x2="19" y2="12" />
                  <polyline points="12 5 19 12 12 19" />
                </svg>
              </span>
            </a>
          </div>
        </div>
        <div className="paths-phone-stage">
          {typeof window !== "undefined" && window.PhoneMockup
            ? <window.PhoneMockup />
            : null}
        </div>
        <div className="paths-cta-row paths-cta-row--under-phone">
          <a
            className="paths-cta"
            href="https://www.instagram.com/kscosmeticos_ofc/"
            target="_blank"
            rel="noopener noreferrer"
            aria-label={L.ksOpenInstagramAria}
          >
            <span className="paths-cta__label">{L.ksOpenInstagram}</span>
            <span className="paths-cta__arrow paths-cta__arrow--ig" aria-hidden="true">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="5" ry="5"/>
                <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
                <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>
              </svg>
            </span>
          </a>
        </div>
        <div className="paths-grid paths-grid--empty">
          {[0, 1].map((colIdx) => (
            <div className="paths-col" key={colIdx}>
              {[0, 1].map((rowIdx) => (
                <article
                  key={rowIdx}
                  className="path-card path-card--empty"
                  aria-label="Reserved slot"
                />
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function _PathsLegacyRemoved() {
  return null;
  return (
    <section>
      <div className="container">
        <div className="paths-grid">
          {[0, 1].map((colIdx) => {
            const topI = colIdx;
            const botI = colIdx + 2;
            let topFlex = 1, botFlex = 1;
            if (hoveredCol === colIdx) {
              if (hoveredRow === 0) { topFlex = 1.7; botFlex = 0.3; }
              else                  { topFlex = 0.3; botFlex = 1.7; }
            }
            return (
              <div className="paths-col" key={colIdx}>
                {[topI, botI].map((i, rowIdx) => {
                  const it = items[i];
                  const flex = rowIdx === 0 ? topFlex : botFlex;
                  return (
                    <article
                      key={i}
                      className={`path-card ${hover === i ? "is-hover" : ""} accent-${it.accent}`}
                      style={{ flex: `${flex} 1 0` }}
                      onMouseEnter={() => setHover(i)}
                      onFocus={() => setHover(i)}
                      onClick={() => setHover(hover === i ? -1 : i)}
                      tabIndex={0}
                    >
                      <div className="path-header">
                        <h3>{it.title}</h3>
                        <div className="path-plus" aria-hidden="true">
                          <svg className="path-plus-icon icon-plus" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
                            <path d="M12 5v14M5 12h14" />
                          </svg>
                          <svg className="path-plus-icon icon-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M5 12h14M13 6l6 6-6 6" />
                          </svg>
                        </div>
                      </div>
                      <div className="path-body">
                        <p>{it.body}</p>
                        <a
                          className="path-link"
                          href={`#/paths/${it.title.toLowerCase()}`}
                          aria-label={`Learn more about ${it.title}`}
                          onClick={(e) => e.stopPropagation()}
                        >
                          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M5 12h14M13 6l6 6-6 6" />
                          </svg>
                        </a>
                      </div>
                    </article>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function PressCard({ date, tag, title, teaser, href = "#", variant = "red" }) {
  return (
    <a
      className={`press-card press-card--${variant}`}
      href={href}
      aria-label={`${L.newsroomReadPressAria}: ${title}`}
    >
      <div className="press-card__pad">
        <div className="press-card__pad-inner">
          <div className="press-card__top">
            <span className="press-card__date">{date}</span>
            <span className="press-card__tag">{tag}</span>
          </div>
          <h3 className="press-card__title">{title}</h3>
          <div className="press-card__reveal">
            <p className="press-card__teaser">{teaser}</p>
            <span className="press-card__cta" aria-hidden="true">
              {L.newsroomReadFull}
              <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true">
                <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
              </svg>
            </span>
          </div>
        </div>
      </div>

      <div className="press-card__shell">
        <div className="press-card__shell-gloss" aria-hidden="true" />
        <span className="press-card__more" aria-hidden="true">
          {L.newsroomReadMore}
        </span>
      </div>
    </a>
  );
}

function Newsroom() {
  const gridRef = useRef(null);
  useEffect(() => {
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!g || !ST) return;
    const tiles = gridRef.current.querySelectorAll(".press-card, .tile");
    const t = g.to(tiles, {
      opacity: 1, y: 0, duration: 0.9, ease: "power3.out", stagger: 0.08,
      scrollTrigger: { trigger: gridRef.current, start: "top 80%" },
    });
    return () => { t.scrollTrigger && t.scrollTrigger.kill(); t.kill(); };
  }, []);
  return (
    <section className="section newsroom-section" data-screen-label="08 Newsroom" id="insights" data-nav-theme="light">
      <div className="container">
        <div className="newsroom-title">
          <AnimatedTitle lines={L.newsroomTitle} />
        </div>

        <div className="press-grid" ref={gridRef}>
          <PressCard
            date={L.newsroomCard1Date}
            tag={L.newsroomCard1Tag}
            title={L.newsroomCard1Title}
            teaser={L.newsroomCard1Teaser}
            href={A("press/lumora-launch.html")}
            variant="bronze"
          />
          <PressCard
            date={L.newsroomCard2Date}
            tag={L.newsroomCard2Tag}
            title={L.newsroomCard2Title}
            teaser={L.newsroomCard2Teaser}
            href={A("press/ds-made-homepage-renewed.html")}
          />
        </div>

        <div className="press-cta">
          <a className="pill-btn pill-btn--more" href={A("press/list.html")} aria-label={L.newsroomCtaAria}>
            <span className="pill-btn__label">{L.newsroomCta}</span>
            <span className="pill-btn__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24"><path d="M9 6l6 6-6 6" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" fill="none" strokeWidth="2"/></svg>
            </span>
          </a>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer" id="contact">
      <div className="grain" aria-hidden="true" />

      <div className="container footer-container">
        <div className="footer-top footer-top--solo">
          <a className="footer-logo" href="#top">
            <img
              src={A("assets/dsmade-official-white.png")}
              alt="DS Made"
              className="footer-logo-img"
            />
          </a>
        </div>

        <div className="footer-bottom">
          <div className="footer-socials">
            <a href="#">Linkedin</a>
            <a href="#">Twitter</a>
            <a href="#">IG Europe</a>
            <a href="#">IG Asia</a>
            <a href="#">IG MENA</a>
            <a href="#">Youtube</a>
          </div>
          <div className="footer-legal">
            <span>© 2026 DSMADE Group AG All rights reserved</span>
            <span className="dash">—</span>
            <a href="#">Privacy Policy</a>
            <span>|</span>
            <a href="#">Cookie policy</a>
            <span>|</span>
            <a href="#">Cookie preferences</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function GlobalAurora() {
  const rootRef = useRef(null);
  useEffect(() => {
    const el = rootRef.current;
    if (!el) return;

    let mx = 0.5, my = 0.5, raf = 0;
    const applyMouse = () => {
      el.style.setProperty("--mx", mx.toFixed(3));
      el.style.setProperty("--my", my.toFixed(3));
      raf = 0;
    };
    const onMove = (e) => {
      mx = e.clientX / window.innerWidth;
      my = e.clientY / window.innerHeight;
      if (!raf) raf = requestAnimationFrame(applyMouse);
    };

    const onScroll = () => {
      const y = window.scrollY;
      const vh = window.innerHeight;
      const startFade = vh * 2.4;
      const endFade   = vh * 3.4;
      let op = 1;
      if (y > startFade) {
        op = Math.max(0, 1 - (y - startFade) / (endFade - startFade));
      }
      el.style.setProperty("--ga-opacity", op.toFixed(3));
    };

    window.addEventListener("mousemove", onMove, { passive: true });
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("scroll", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div className="global-aurora" ref={rootRef} aria-hidden="true">
      <div className="ga-wall" />
    </div>
  );
}

function TopButton() {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const threshold = () => window.innerHeight * 0.8;
    const readY = () => {
      const lenis = window.__dsmadeLenis;
      if (lenis && typeof lenis.scroll === "number") return lenis.scroll;
      return window.scrollY;
    };
    const update = () => setVisible(readY() > threshold());
    update();

    let lenisSub = null;
    let pollId = 0;
    let pollCount = 0;
    const attachLenis = () => {
      const lenis = window.__dsmadeLenis;
      if (!lenis || typeof lenis.on !== "function") return false;
      const handler = () => update();
      lenis.on("scroll", handler);
      lenisSub = { lenis, handler };
      return true;
    };
    if (!attachLenis()) {
      pollId = setInterval(() => {
        pollCount += 1;
        if (attachLenis() || pollCount > 40) clearInterval(pollId);
      }, 50);
    }

    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update, { passive: true });
    return () => {
      if (pollId) clearInterval(pollId);
      if (lenisSub && typeof lenisSub.lenis.off === "function") {
        lenisSub.lenis.off("scroll", lenisSub.handler);
      }
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, []);
  const goTop = (e) => {
    e.preventDefault();
    const lenis = window.__dsmadeLenis;
    if (lenis && typeof lenis.scrollTo === "function") {
      lenis.scrollTo(0, { duration: 1.2 });
    } else {
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };
  return (
    <button
      type="button"
      className={`top-btn ${visible ? "is-visible" : ""}`}
      onClick={goTop}
      aria-label="Back to top"
    >
      <svg className="top-btn__arrow" viewBox="0 0 24 24" aria-hidden="true">
        <line x1="12" y1="19" x2="12" y2="5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        <polyline points="6 11 12 5 18 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      </svg>
      <span className="top-btn__label">Top</span>
    </button>
  );
}

function App() {
  useEffect(() => {
    const Lenis = window.Lenis;
    const g = window.gsap;
    const ST = window.ScrollTrigger;
    if (!Lenis || !g || !ST) return;

    g.registerPlugin(ST);

    const isMobile = typeof window !== "undefined" &&
      window.matchMedia &&
      window.matchMedia("(max-width: 900px)").matches;
    if (isMobile) return;

    const lenis = new Lenis({
      duration: 1.15,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      smoothWheel: true,
    });
    window.__dsmadeLenis = lenis;

    lenis.on("scroll", ST.update);
    const raf = (time) => { lenis.raf(time * 1000); };
    g.ticker.add(raf);
    g.ticker.lagSmoothing(0);

    return () => {
      g.ticker.remove(raf);
      lenis.destroy();
      if (window.__dsmadeLenis === lenis) window.__dsmadeLenis = null;
    };
  }, []);

  return (
    <>
      {window.SharedNav ? <window.SharedNav base="." /> : null}
      <GlobalAurora />
      <Hero />
      <Intro />
      <Partners />
      <KeyAffiliates />
      <Status />
      <Lumora />
      <KS />
      <Newsroom />
      {window.SharedFooter ? <window.SharedFooter base={CURRENT_LANG_APP === "pt" ? ".." : "."} /> : <Footer />}
      <TopButton />
    </>
  );
}

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

(function mountLiquidEther() {
  const mount = document.getElementById("liquid-ether-mount");
  if (!mount) return;
  if (typeof window.LiquidEther !== "function") {
    console.warn("[LiquidEther] component not loaded yet");
    return;
  }
  const LE = window.LiquidEther;
  ReactDOM.createRoot(mount).render(
    <LE
      colors={["#F97316", "#EAB308", "#fffcf9"]}
      mouseForce={20}
      cursorSize={100}
      resolution={0.5}
      isViscous={true}
      viscous={30}
      iterationsViscous={32}
      iterationsPoisson={32}
      isBounce={false}
      autoDemo={true}
      autoSpeed={0.5}
      autoIntensity={0.7}
      takeoverDuration={0}
      autoResumeDelay={0}
      autoRampDuration={0}
      BFECC={true}
      dt={0.014}
      scrollMode={true}
      scrollSensitivity={0.25}
    />
  );
})();
