// shared.jsx — componentes e hooks compartilhados entre todas as páginas.
// Depende de data.js (window.COPY, LOGOS, VARIANTS, ACCENTS, NAV_LINKS, TWEAK_DEFAULTS).

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

function linkTo(key, fallback) {
  return (window.MODRO_LINKS && window.MODRO_LINKS[key]) || fallback;
}

function asset(path) {
  if (/^(https?:)?\/\//.test(path) || String(path).startsWith("data:")) return path;
  const base = window.MODRO_ASSET_BASE || "";
  return `${base}${String(path).replace(/^\/+/, "")}`;
}

function whatsappHref(message) {
  const raw = window.MODRO_WHATSAPP || (window.COPY?.pt?.footer_phone || "");
  const phone = String(raw).replace(/\D/g, "");
  const text = message ? `?text=${encodeURIComponent(message)}` : "";
  return `https://wa.me/${phone}${text}`;
}

function renderModroPage(page) {
  const root = document.querySelector("[data-modro-root]") || document.getElementById("root");
  if (!root) return;
  ReactDOM.createRoot(root).render(page);
}

function useScrollEffects() {
  useEffect(() => {
    const nodes = Array.from(document.querySelectorAll(
      ".mc-app [data-reveal], .mc-app .mc-sec-head, .mc-app .mc-service, .mc-app .mc-diff-block, .mc-app .mc-purpose-block, .mc-app .mc-gal-item, .mc-app .mc-social, .mc-app .mc-client-stat"
    ));
    if (!nodes.length) return undefined;

    nodes.forEach((node, index) => {
      if (!node.hasAttribute("data-reveal")) node.setAttribute("data-reveal", "up");
      node.style.setProperty("--reveal-delay", `${Math.min(index % 4, 3) * 70}ms`);
    });

    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      nodes.forEach((node) => node.classList.add("is-visible"));
      return undefined;
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        entry.target.classList.add("is-visible");
        observer.unobserve(entry.target);
      });
    }, { threshold: 0.16, rootMargin: "0px 0px -8% 0px" });

    nodes.forEach((node) => observer.observe(node));
    return () => observer.disconnect();
  }, []);
}

function CountUp({ value, suffix = "", duration = 1100 }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(0);

  useEffect(() => {
    const el = ref.current;
    if (!el) return undefined;
    let frame = 0;
    let started = false;

    const run = () => {
      const start = performance.now();
      const tick = (now) => {
        const progress = Math.min((now - start) / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3);
        setShown(Math.round(value * eased));
        if (progress < 1) frame = requestAnimationFrame(tick);
      };
      frame = requestAnimationFrame(tick);
    };

    const observer = new IntersectionObserver((entries) => {
      if (started || !entries.some((entry) => entry.isIntersecting)) return;
      started = true;
      run();
      observer.disconnect();
    }, { threshold: 0.45 });

    observer.observe(el);
    return () => {
      observer.disconnect();
      cancelAnimationFrame(frame);
    };
  }, [value, duration]);

  return <span ref={ref}>{shown.toLocaleString("pt-BR")}{suffix}</span>;
}

// ─── Theming hook ────────────────────────────────────────────────────────────
function useTheme() {
  const [t, setTweaks] = useState(window.TWEAK_DEFAULTS);
  const setTweak = React.useCallback((keyOrEdits, val) => {
    const edits = typeof keyOrEdits === "object" && keyOrEdits !== null
      ? keyOrEdits
      : { [keyOrEdits]: val };
    setTweaks((prev) => ({ ...prev, ...edits }));
  }, []);
  const variant = window.VARIANTS[t.variant] || window.VARIANTS.studio;
  const theme = useMemo(
    () => ({ ...variant, accent: t.accent || variant.accentDefault }),
    [variant, t.accent]
  );
  const copy = window.COPY[t.lang] || window.COPY.pt;
  const navLinks = window.NAV_LINKS[t.lang] || window.NAV_LINKS.pt;

  // Apply theme to :root
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--bg", theme.bg);
    r.setProperty("--bg-alt", theme.bgAlt);
    r.setProperty("--bg-raised", theme.bgRaised);
    r.setProperty("--fg", theme.fg);
    r.setProperty("--fg-muted", theme.fgMuted);
    r.setProperty("--fg-faint", theme.fgFaint);
    r.setProperty("--rule", theme.rule);
    r.setProperty("--accent", theme.accent);
    r.setProperty("--on-accent", theme.onAccent);
    document.body.style.background = theme.bg;
    document.body.style.color = theme.fg;
    document.documentElement.setAttribute("data-variant", t.variant);
  }, [theme, t.variant]);

  // Density
  useEffect(() => {
    const map = { compact: 40, regular: 56, comfy: 72 };
    document.documentElement.style.setProperty("--sec-pad", `${map[t.density] || 56}px`);
  }, [t.density]);

  return { t, setTweak, theme, copy, navLinks };
}

// ─── Primitives ──────────────────────────────────────────────────────────────
function Section({ id, children, style, label, theme, eyebrow, title, kicker }) {
  return (
    <section id={id} data-screen-label={label} style={{ position: "relative", ...style }}>
      {(eyebrow || title) &&
      <div className="mc-sec-head">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {eyebrow}
          </div>
          {title && <h2 className="mc-sec-title">{title}</h2>}
          {kicker && <p className="mc-sec-kicker">{kicker}</p>}
        </div>
      }
      {children}
    </section>);

}

function Btn({ children, variant = "primary", href = "#", icon, theme, big }) {
  const styleMap = {
    primary: { background: theme.accent, color: theme.onAccent, border: `1px solid ${theme.accent}` },
    ghost: { background: "transparent", color: theme.fg, border: `1px solid ${theme.rule}` },
    inverse: { background: theme.fg, color: theme.bg, border: `1px solid ${theme.fg}` }
  };
  return (
    <a href={href} className={`mc-btn mc-btn-${variant} ${big ? "mc-btn-big" : ""}`} style={styleMap[variant]}>
      {icon && <span className="mc-btn-icon">{icon}</span>}
      <span>{children}</span>
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ marginLeft: 4 }}>
        <path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square" />
      </svg>
    </a>);

}

const WhatsIcon = () =>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
    <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.8-.7-1.4-1.7-1.6-2-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.3 5.2 4.6.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.1-.2-.2-.5-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.4 1.3 4.9L2 22l5.3-1.4c1.4.8 3 1.2 4.7 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z" />
  </svg>;


function BrandMark({ theme, large }) {
  const size = large ? 28 : 22;
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" style={{ flexShrink: 0 }}>
      <circle cx="20" cy="20" r="18" fill={theme.accent} opacity="0.08" />
      <circle cx="20" cy="20" r="18" stroke={theme.accent} strokeWidth="1" opacity="0.4" />
      {[0, 1, 2, 3, 4, 5, 6].map((row) => {
        const y = 6 + row * 4.5;
        const w = Math.sqrt(Math.max(0, 18 * 18 - (y - 20) * (y - 20))) * 2;
        const dots = Math.max(2, Math.floor(w / 3));
        return Array.from({ length: dots }).map((_, i) => {
          const x = 20 - w / 2 + w / (dots - 1) * i;
          const r = row < 3 ? 1.0 : 0.8;
          return <circle key={`${row}-${i}`} cx={x} cy={y} r={r} fill={theme.accent} opacity={row < 3 ? 0.95 : 0.55} />;
        });
      })}
    </svg>);

}

// ─── Nav (multipage) ─────────────────────────────────────────────────────────
function Nav({ theme, copy, navLinks, lang, setLang, current }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`mc-nav ${scrolled ? "scrolled" : ""}`} style={{ borderColor: theme.rule }}>
      <div className="mc-nav-inner">
        <a href={linkTo("home", "index.html")} className="mc-nav-brand">
          <BrandMark theme={theme} />
          <span>Modro</span>
          <span style={{ color: theme.fgMuted, fontWeight: 400 }}>Consultoria</span>
        </a>
        <div className="mc-nav-links">
          {navLinks.map((n) => {
            const active = current === n.key || current === n.href;
            return (
          <a key={n.href} href={n.href} className={active ? "active" : ""}
          style={active ? { color: theme.fg } : null}>
              {n.label}
            </a>
            );
          })}
        </div>
        <div className="mc-nav-right">
          <button className="mc-lang" onClick={() => setLang(lang === "pt" ? "en" : "pt")}>
            <span className={lang === "pt" ? "active" : ""}>PT</span>
            <span className="mc-lang-sep">/</span>
            <span className={lang === "en" ? "active" : ""}>EN</span>
          </button>
          <a href={linkTo("contato", "contato.html")} className="mc-nav-cta" style={{ background: theme.accent, color: theme.onAccent }}>
            <WhatsIcon /> WhatsApp
          </a>
        </div>
      </div>
    </nav>);

}

// ─── Hero (home) ─────────────────────────────────────────────────────────────
function Hero({ t, theme }) {
  return (
    <header className="mc-hero" data-screen-label="01 Hero">
      <HeroBackgroundVideo />
      <div className="mc-hero-grid">
        <div className="mc-hero-left" data-reveal="left">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {t.hero_eyebrow}
          </div>
          <h1 className="mc-hero-title">
            <span className="mc-hero-line">{t.hero_title_a}</span>
            <span className="mc-hero-line mc-hero-italic" style={{ color: theme.accent }}>{t.hero_title_b}</span>
            <span className="mc-hero-line mc-hero-muted">{t.hero_title_c}</span>
          </h1>
          <p className="mc-hero-lede">{t.hero_lede}</p>
          <div className="mc-hero-actions">
            <Btn theme={theme} variant="primary" icon={<WhatsIcon />} href={linkTo("contato", "contato.html")}>{t.cta_primary}</Btn>
            <Btn theme={theme} variant="ghost" href={linkTo("contato", "contato.html")}>{t.cta_secondary}</Btn>
          </div>
          <div className="mc-hero-meta">
            <div className="mc-meta-item"><span className="mc-meta-dot" style={{ background: theme.accent }}></span>{t.hero_meta_1}</div>
            <div className="mc-meta-item"><span className="mc-meta-dot" style={{ background: theme.accent }}></span>{t.hero_meta_2}</div>
            <div className="mc-meta-item"><span className="mc-meta-dot" style={{ background: theme.accent }}></span>{t.hero_meta_3}</div>
          </div>
        </div>
        <div className="mc-hero-right" data-reveal="right">
          <div className="mc-hero-proof">
            <span>{t.hero_meta_2}</span>
            <strong>{t.hero_meta_3}</strong>
            <small>{t.hero_meta_1}</small>
          </div>
        </div>
      </div>
      <div className="mc-hero-rule"></div>
    </header>);

}

function HeroBackgroundVideo() {
  const src = window.MODRO_HERO_VIDEO || "assets/hero-loop.mp4";
  const poster = window.MODRO_HERO_POSTER || "assets/hero-bg.jpg";
  return (
    <div className="mc-hero-bg" aria-hidden="true">
      <video
        className="mc-hero-bg-video"
        src={asset(src)}
        poster={asset(poster)}
        autoPlay
        muted
        loop
        playsInline
      />
      <div className="mc-hero-bg-overlay"></div>
    </div>
  );
}

// Page header — reusable for inner pages
function PageHero({ theme, eyebrow, title, lede }) {
  return (
    <header className="mc-page-hero" data-screen-label="01 Header">
      <div className="mc-page-hero-inner">
        <div className="mc-eyebrow">
          <span className="mc-tick" style={{ background: theme.accent }}></span>
          {eyebrow}
        </div>
        <h1 className="mc-page-title">{title}</h1>
        {lede && <p className="mc-page-lede">{lede}</p>}
      </div>
      <div className="mc-hero-rule"></div>
    </header>);

}

function HeroLoopVideo({ theme }) {
  const src = window.MODRO_HERO_VIDEO || "assets/hero-loop.mp4";
  const poster = window.MODRO_HERO_POSTER || "assets/hero-bg.jpg";
  return (
    <div className="mc-hero-video-panel" data-reveal="right" style={{ borderColor: theme.rule }}>
      <video
        className="mc-hero-video"
        src={asset(src)}
        poster={asset(poster)}
        autoPlay
        muted
        loop
        playsInline
      />
      <div className="mc-hero-video-shade"></div>
      <div className="mc-hero-video-badge" style={{ borderColor: theme.rule }}>
        <span style={{ color: theme.accent }}>EST.</span>
        <strong>1990</strong>
      </div>
      <div className="mc-hero-video-card" style={{ borderColor: theme.rule }}>
        <div>Reiner Modro</div>
        <span>Founder · Senior Advisor</span>
      </div>
    </div>
  );
}

function PortraitFrame({ theme }) {
  return (
    <div className="mc-portrait">
      <svg className="mc-portrait-grid" viewBox="0 0 400 520" preserveAspectRatio="none">
        <defs>
          <pattern id="mcg" width="40" height="40" patternUnits="userSpaceOnUse">
            <path d="M40 0H0V40" fill="none" stroke={theme.fgFaint} strokeWidth="1" />
          </pattern>
        </defs>
        <rect width="400" height="520" fill="url(#mcg)" />
      </svg>
      <div className="mc-portrait-img" style={{ background: theme.bgRaised }}>
        <svg viewBox="0 0 400 520" preserveAspectRatio="xMidYMid slice" style={{ width: "100%", height: "100%", display: "block" }}>
          <defs>
            <linearGradient id="prt" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor={theme.accent} stopOpacity="0.0" />
              <stop offset="1" stopColor={theme.accent} stopOpacity="0.18" />
            </linearGradient>
            <linearGradient id="prtbg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor={theme.bgAlt} />
              <stop offset="1" stopColor={theme.bg} />
            </linearGradient>
          </defs>
          <rect width="400" height="520" fill="url(#prtbg)" />
          <path d="M 0 520 L 0 440 Q 60 380 130 360 Q 200 340 270 360 Q 340 380 400 440 L 400 520 Z" fill={theme.fg} opacity="0.92" />
          <path d="M 175 380 Q 200 365 225 380 L 225 320 L 175 320 Z" fill={theme.fg} opacity="0.85" />
          <ellipse cx="200" cy="240" rx="78" ry="92" fill={theme.fg} opacity="0.95" />
          <path d="M 130 220 Q 140 150 200 145 Q 260 150 270 220 Q 268 195 250 185 Q 220 175 200 178 Q 180 175 150 185 Q 132 195 130 220 Z" fill={theme.fgMuted} />
          <ellipse cx="200" cy="240" rx="78" ry="92" fill="url(#prt)" />
          <path d="M 175 380 L 155 410 L 200 440 L 245 410 L 225 380 Z" fill={theme.bg} stroke={theme.fgFaint} strokeWidth="1" />
          <path d="M 195 410 L 205 410 L 210 470 L 200 480 L 190 470 Z" fill={theme.accent} opacity="0.7" />
        </svg>
      </div>
      <div className="mc-portrait-caption">
        <div className="mc-portrait-name">Reiner Modro</div>
        <div className="mc-portrait-role">Founder · Senior Advisor</div>
      </div>
      <div className="mc-portrait-stamp" style={{ borderColor: theme.rule }}>
        <span style={{ color: theme.accent, fontWeight: 600 }}>EST.</span>
        <span>1990</span>
      </div>
    </div>);

}

// ─── Sections ────────────────────────────────────────────────────────────────
function LogoBand({ t, theme, show }) {
  if (!show) return null;
  const loop = [...window.LOGOS, ...window.LOGOS];
  return (
    <div className="mc-band-wrap" data-screen-label="02 Logos">
      <div className="mc-band-inner">
        <div className="mc-band-label-col">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            Clientes
          </div>
          <div className="mc-band-label">{t.band_label}</div>
        </div>
        <div className="mc-band-track-wrap">
          <div className="mc-band-track">
            {loop.map((l, i) =>
            <div key={`${l.name}-${i}`} className="mc-logo-cell" title={l.name}>
                <img src={asset(l.src)} alt={l.name} loading="lazy" />
              </div>
            )}
          </div>
          <div className="mc-band-fade mc-band-fade-l" style={{ background: `linear-gradient(90deg, ${theme.bg}, transparent)` }}></div>
          <div className="mc-band-fade mc-band-fade-r" style={{ background: `linear-gradient(270deg, ${theme.bg}, transparent)` }}></div>
        </div>
      </div>
    </div>);

}

function Problems({ t, theme }) {
  return (
    <Section id="resolvo" theme={theme} eyebrow={t.problems_eyebrow} title={t.problems_title} label="03 What I solve">
      <div className="mc-problems">
        {t.problems.map((p) =>
        <div key={p.n} className="mc-problem">
            <div className="mc-problem-num" style={{ color: theme.accent }}>{p.n}</div>
            <div className="mc-problem-body">
              <h3>{p.t}</h3>
              <p>{p.d}</p>
            </div>
          </div>
        )}
      </div>
    </Section>);

}

function Services({ t, theme }) {
  const [open, setOpen] = useState(0);
  return (
    <Section id="servicos" theme={theme} eyebrow={t.services_eyebrow} title={t.services_title} label="04 Services">
      <div className="mc-services">
        {t.services.map((s, i) => {
          const isOpen = open === i;
          return (
            <div key={s.code} className={`mc-service ${isOpen ? "open" : ""}`} onClick={() => setOpen(i)}>
              <div className="mc-service-head">
                <div className="mc-service-code" style={{ color: theme.accent }}>{s.code}</div>
                <h3 className="mc-service-title">{s.t}</h3>
                <div className="mc-service-toggle" style={{ borderColor: theme.rule }}>
                  <svg width="14" height="14" viewBox="0 0 14 14"><path d={isOpen ? "M3 7h8" : "M7 3v8M3 7h8"} stroke="currentColor" strokeWidth="1.5" /></svg>
                </div>
              </div>
              {isOpen &&
              <div className="mc-service-body">
                  <p>{s.d}</p>
                  <ul>
                    {s.deliverables.map((d) =>
                  <li key={d}><span className="mc-bullet" style={{ background: theme.accent }}></span>{d}</li>
                  )}
                  </ul>
                </div>
              }
            </div>);

        })}
      </div>
    </Section>);

}

function Results({ t, theme }) {
  return (
    <Section id="resultados" theme={theme} eyebrow={t.results_eyebrow} title={t.results_title} label="05 Results">
      <div className="mc-results">
        {t.results.map((r, i) =>
        <div key={i} className="mc-result">
            <div className="mc-result-v" style={{ color: theme.accent }}>{r.v}</div>
            <div className="mc-result-l">{r.l}</div>
            <div className="mc-result-c">{r.c}</div>
          </div>
        )}
      </div>
    </Section>);

}

function About({ t, theme }) {
  return (
    <Section id="sobre" theme={theme} label="06 About">
      <div className="mc-about">
        <div className="mc-about-left">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {t.about_eyebrow}
          </div>
          <h2 className="mc-sec-title">{t.about_title}</h2>
          <p className="mc-about-p">{t.about_p1}</p>
          <p className="mc-about-p">{t.about_p2}</p>
          {t.about_p3 && <p className="mc-about-p">{t.about_p3}</p>}
        </div>
        <div className="mc-about-right">
          <ol className="mc-timeline">
            {t.about_facts.map(([y, l], i) =>
            <li key={i}>
                <div className="mc-tl-year" style={{ color: theme.accent }}>{y}</div>
                <div className="mc-tl-label">{l}</div>
              </li>
            )}
          </ol>
        </div>
      </div>
    </Section>);

}

function Testimonials({ t, theme }) {
  const [active, setActive] = useState(0);
  return (
    <Section id="depoimentos" theme={theme} eyebrow={t.testimonials_eyebrow} title={t.testimonials_title} label="07 Testimonials">
      <div className="mc-testi">
        <div className="mc-testi-stage">
          {t.testimonials.map((tt, i) =>
          <blockquote key={i} className={`mc-testi-q ${active === i ? "active" : ""}`}>
              <div className="mc-quote-mark" style={{ color: theme.accent }}>"</div>
              <p>{tt.q}</p>
              <cite>{tt.a}</cite>
            </blockquote>
          )}
        </div>
        <div className="mc-testi-dots">
          {t.testimonials.map((_, i) =>
          <button key={i} className={`mc-dot ${active === i ? "active" : ""}`}
          onClick={() => setActive(i)}
          style={{ background: active === i ? theme.accent : theme.rule }} />
          )}
        </div>
      </div>
    </Section>);

}

function Materials({ t, theme }) {
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const submitMaterials = (e) => {
    e.preventDefault();
    setSubmitted(true);
    window.open(
      whatsappHref(`Olá, gostaria de receber os materiais da Modro Consultoria.\nEmail: ${email}`),
      "_blank",
      "noopener,noreferrer"
    );
  };
  return (
    <Section id="materiais" theme={theme} eyebrow={t.materials_eyebrow} title={t.materials_title} kicker={t.materials_lede} label="08 Resources">
      <div className="mc-materials">
        {t.materials.map((m) =>
        <div key={m.n} className="mc-material">
            <div className="mc-material-top">
              <span className="mc-material-tag" style={{ borderColor: theme.rule, color: theme.fgMuted }}>{m.tag}</span>
              <span className="mc-material-n" style={{ color: theme.accent }}>{m.n}</span>
            </div>
            <h3>{m.t}</h3>
            <p>{m.d}</p>
            <div className="mc-material-foot">
              <span className="mc-locked" style={{ color: theme.fgMuted }}>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><rect x="2" y="5" width="8" height="6" rx="1" stroke="currentColor" /><path d="M4 5V3.5a2 2 0 014 0V5" stroke="currentColor" /></svg>
                gated
              </span>
            </div>
          </div>
        )}
      </div>
      <form className="mc-form" onSubmit={submitMaterials}>
        <label className="mc-form-label">{t.materials_form_label}</label>
        <div className="mc-form-row">
          <input
            type="email"
            placeholder="nome@empresa.com.br"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required />
          
          <button type="submit" style={{ background: theme.accent, color: theme.onAccent }}>
            {submitted ? "✓" : t.materials_form_cta}
          </button>
        </div>
        {submitted && <div className="mc-form-ok">✓ Solicitação preparada para {email}.</div>}
      </form>
    </Section>);

}

function Insights({ t, theme }) {
  return (
    <Section id="insights" theme={theme} eyebrow={t.insights_eyebrow} title={t.insights_title} label="09 Insights">
      <div className="mc-insights">
        {t.insights.map((i, k) =>
        <a key={k} href="#" className="mc-insight">
            <div className="mc-insight-meta">
              <span>{i.d}</span>
              <span className="mc-insight-cat" style={{ color: theme.accent }}>{i.c}</span>
            </div>
            <h3>{i.t}</h3>
            <div className="mc-insight-foot">
              <span>{i.r}</span>
              <span className="mc-arrow">→</span>
            </div>
          </a>
        )}
      </div>
    </Section>);

}

function FinalCTA({ t, theme }) {
  return (
    <Section id="contato-cta" theme={theme} label="10 Contact CTA">
      <div className="mc-final" style={{ background: theme.bgRaised, borderColor: theme.rule }}>
        <div className="mc-final-inner">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {t.cta_secondary}
          </div>
          <h2 className="mc-final-title">{t.cta_final_title}</h2>
          <p className="mc-final-lede">{t.cta_final_lede}</p>
          <Btn theme={theme} variant="primary" big icon={<WhatsIcon />} href={whatsappHref()}>
            {t.cta_final_button}
          </Btn>
          <div className="mc-final-note">{t.cta_final_note}</div>
        </div>
      </div>
    </Section>);

}

// ─── Contact form (full page) ────────────────────────────────────────────────
function ContactForm({ t, theme }) {
  const [sent, setSent] = useState(false);
  const [data, setData] = useState({ name: "", company: "", email: "", phone: "", topic: t.contact_form_topics[0], msg: "" });
  const upd = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));
  const submitContact = (e) => {
    e.preventDefault();
    setSent(true);
    const message = [
      "Olá, gostaria de conversar com a Modro Consultoria.",
      `Nome: ${data.name}`,
      `Empresa: ${data.company}`,
      `Email: ${data.email}`,
      data.phone ? `Telefone: ${data.phone}` : "",
      `Assunto: ${data.topic}`,
      `Mensagem: ${data.msg}`
    ].filter(Boolean).join("\n");
    window.open(whatsappHref(message), "_blank", "noopener,noreferrer");
  };
  return (
    <Section id="contato-form" theme={theme} label="02 Form">
      <div className="mc-contact">
        <div className="mc-contact-form">
          <form onSubmit={submitContact}>
            <div className="mc-cf-row">
              <label>
                <span>{t.contact_form_name}</span>
                <input required value={data.name} onChange={upd("name")} />
              </label>
              <label>
                <span>{t.contact_form_company}</span>
                <input required value={data.company} onChange={upd("company")} />
              </label>
            </div>
            <div className="mc-cf-row">
              <label>
                <span>{t.contact_form_email}</span>
                <input type="email" required value={data.email} onChange={upd("email")} />
              </label>
              <label>
                <span>{t.contact_form_phone}</span>
                <input type="tel" value={data.phone} onChange={upd("phone")} />
              </label>
            </div>
            <label className="mc-cf-full">
              <span>{t.contact_form_topic}</span>
              <select value={data.topic} onChange={upd("topic")}>
                {t.contact_form_topics.map((tp) => <option key={tp}>{tp}</option>)}
              </select>
            </label>
            <label className="mc-cf-full">
              <span>{t.contact_form_msg}</span>
              <textarea rows="5" required value={data.msg} onChange={upd("msg")} />
            </label>
            <button type="submit" className="mc-cf-submit" style={{ background: theme.accent, color: theme.onAccent }}>
              {sent ? "✓ Abrindo WhatsApp" : t.contact_form_send}
            </button>
          </form>
        </div>
        <aside className="mc-contact-side" style={{ borderColor: theme.rule }}>
          <div className="mc-cf-aside-h">{t.contact_or}</div>
          <a href={whatsappHref()} className="mc-cf-channel" style={{ background: theme.accent, color: theme.onAccent }}>
            <WhatsIcon /> WhatsApp · resposta em 4h
          </a>
          <a href={`mailto:${t.footer_email}`} className="mc-cf-channel-ghost" style={{ borderColor: theme.rule, color: theme.fg }}>
            ✉ {t.footer_email}
          </a>
          <a href={`tel:${t.footer_phone}`} className="mc-cf-channel-ghost" style={{ borderColor: theme.rule, color: theme.fg }}>
            ☎ {t.footer_phone}
          </a>
          <div className="mc-cf-addr" style={{ color: theme.fgMuted, borderColor: theme.rule }}>
            {t.footer_addr}
          </div>
        </aside>
      </div>
    </Section>);

}

// ─── Footer (multipage) ──────────────────────────────────────────────────────
function Footer({ theme, copy, navLinks }) {
  return (
    <footer className="mc-footer" style={{ borderColor: theme.rule }}>
      <div className="mc-footer-grid">
        <div>
          <div className="mc-logo-mark" style={{ color: theme.fg }}>
            <BrandMark theme={theme} large /> {copy.footer_tag}
          </div>
          <div className="mc-footer-tag" style={{ color: theme.fgMuted }}>"{copy.tagline}"</div>
          <div className="mc-footer-meta">{copy.footer_addr}</div>
          <a href={`mailto:${copy.footer_email}`} className="mc-footer-email">{copy.footer_email}</a>
        </div>
        <div className="mc-footer-cols">
          <div>
            <div className="mc-footer-h">Site</div>
            {navLinks.map((n) =>
            <a key={n.href} href={n.href}>{n.label}</a>
            )}
          </div>
          <div>
            <div className="mc-footer-h">Contato</div>
            <a href={whatsappHref()}>WhatsApp</a>
            <a href={`mailto:${copy.footer_email}`}>Email</a>
            <a href="https://www.linkedin.com/in/reiner-modro/" target="_blank" rel="noreferrer">LinkedIn</a>
          </div>
        </div>
      </div>
      <div className="mc-footer-bottom">
        <span>© 2026 Modro Consultoria</span>
        <span>CNPJ 80.733.223/0001-05</span>
      </div>
    </footer>);

}

// ─── Tweaks panel (shared on every page) ─────────────────────────────────────
function GlobalTweaks({ t, setTweak }) {
  return (
    <TweaksPanel>
      <TweakSection label="Direção visual" />
      <TweakRadio
        label="Variante"
        value={t.variant}
        options={["editorial", "studio"]}
        onChange={(v) => setTweak({ variant: v, accent: window.VARIANTS[v].accentDefault })} />
      
      <TweakColor
        label="Acento"
        value={t.accent}
        options={window.ACCENTS[t.variant] || window.ACCENTS.studio}
        onChange={(v) => setTweak("accent", v)} />
      
      <TweakSection label="Layout" />
      <TweakRadio
        label="Densidade"
        value={t.density}
        options={["compact", "regular", "comfy"]}
        onChange={(v) => setTweak("density", v)} />
      
      <TweakToggle label="Logos de clientes" value={t.showLogos} onChange={(v) => setTweak("showLogos", v)} />
      <TweakSection label="Idioma" />
      <TweakRadio
        label="Lang"
        value={t.lang}
        options={["pt", "en"]}
        onChange={(v) => setTweak("lang", v)} />
      
    </TweaksPanel>);

}

// ─── Page Shell ──────────────────────────────────────────────────────────────
// Wraps every page with Nav + content + Footer.
function PageShell({ current, children }) {
  const { t, setTweak, theme, copy, navLinks } = useTheme();
  const showTweaks = typeof TweaksPanel !== "undefined" && new URLSearchParams(window.location.search).has("tweaks");
  useScrollEffects();
  return (
    <div className="mc-app" id="top" data-variant={t.variant}>
      <Nav theme={theme} copy={copy} navLinks={navLinks} lang={t.lang} setLang={(v) => setTweak("lang", v)} current={current} />
      {children({ t, setTweak, theme, copy, navLinks })}
      <Footer theme={theme} copy={copy} navLinks={navLinks} />
      {showTweaks && <GlobalTweaks t={t} setTweak={setTweak} />}
    </div>);

}

// Expose to window so per-page scripts can use them.
Object.assign(window, {
  linkTo, asset, whatsappHref, renderModroPage, useTheme, Section, Btn, WhatsIcon, BrandMark, Nav, Hero, PageHero, PortraitFrame,
  LogoBand, Problems, Services, Results, About, Testimonials, Materials, Insights,
  FinalCTA, ContactForm, Footer, GlobalTweaks, PageShell
});


// ─── Couto-style sections ────────────────────────────────────────────────────
function Manifesto({ t, theme }) {
  return (
    <section className="mc-manifesto" data-screen-label="Manifesto" style={{ borderColor: theme.rule }}>
      <div className="mc-manifesto-inner">
        <div className="mc-manifesto-mark" style={{ color: theme.accent }}>"</div>
        <p className="mc-manifesto-q">{t.manifesto_quote}</p>
        <div className="mc-manifesto-cite">— Reiner Modro</div>
      </div>
    </section>);

}

function Purpose({ t, theme }) {
  return (
    <Section id="proposito" theme={theme} eyebrow={t.purpose_eyebrow} title={t.purpose_title} kicker={t.purpose_lede} label="Purpose">
      <div className="mc-purpose">
        {t.purpose_blocks.map((b) =>
        <div key={b.n} className="mc-purpose-block">
            <div className="mc-purpose-n" style={{ color: theme.accent, borderColor: theme.rule }}>{b.n}</div>
            <h3>{b.t}</h3>
            <p>{b.d}</p>
          </div>
        )}
      </div>
    </Section>);

}

function Differentials({ t, theme }) {
  return (
    <Section id="diferenciais" theme={theme} eyebrow={t.diff_eyebrow} title={t.diff_title} kicker={t.diff_lede} label="Differentials">
      <div className="mc-diff">
        {t.diff_blocks.map((b, i) =>
        <div key={i} className="mc-diff-block">
            <div className="mc-diff-icon" style={{ borderColor: theme.rule, color: theme.accent }}>
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <circle cx="11" cy="11" r="9" stroke="currentColor" strokeWidth="1.4" />
                <path d="M7 11l3 3 5-6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square" fill="none" />
              </svg>
            </div>
            <h3>{b.t}</h3>
            <p>{b.d}</p>
          </div>
        )}
      </div>
    </Section>);

}

function ClientResults({ t, theme }) {
  return (
    <Section id="clientes" theme={theme} label="Clients">
      <div className="mc-clients">
        <div className="mc-clients-copy" data-reveal="left">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {t.clients_eyebrow}
          </div>
          <h2 className="mc-clients-title">{t.clients_title}</h2>
          <p className="mc-clients-lede">{t.clients_lede}</p>
          <Btn theme={theme} variant="primary" icon={<WhatsIcon />} href={linkTo("contato", "contato.html")}>
            {t.clients_cta}
          </Btn>
        </div>
        <div className="mc-client-stats">
          {t.client_stats.map((stat, index) => (
            <article className="mc-client-stat" key={`${stat.value}-${index}`} style={{ borderColor: theme.rule }}>
              <div className="mc-client-value" style={{ color: theme.accent }}>
                <CountUp value={stat.value} suffix={stat.suffix} />
              </div>
              <p>{stat.label}</p>
              <span className="mc-client-line" style={{ background: theme.accent }}></span>
            </article>
          ))}
        </div>
      </div>
      <div className="mc-client-logos" data-reveal="up">
        {window.LOGOS.map((logo) => (
          <div className="mc-client-logo" key={logo.name} style={{ borderColor: theme.rule }}>
            <img src={asset(logo.src)} alt={logo.name} loading="lazy" />
          </div>
        ))}
      </div>
    </Section>
  );
}

function TrustBand({ t, theme }) {
  const loop = [...window.LOGOS, ...window.LOGOS];
  return (
    <Section id="confianca" theme={theme} eyebrow={t.trust_eyebrow} title={t.trust_title} kicker={t.trust_lede} label="Trust">
      <div className="mc-trust-track-wrap">
        <div className="mc-band-track">
          {loop.map((l, i) =>
          <div key={`${l.name}-${i}`} className="mc-logo-cell" title={l.name}>
              <img src={asset(l.src)} alt={l.name} loading="lazy" />
            </div>
          )}
        </div>
        <div className="mc-band-fade mc-band-fade-l" style={{ background: `linear-gradient(90deg, ${theme.bg}, transparent)` }}></div>
        <div className="mc-band-fade mc-band-fade-r" style={{ background: `linear-gradient(270deg, ${theme.bg}, transparent)` }}></div>
      </div>
    </Section>);

}

function InCompany({ t, theme }) {
  return (
    <Section id="incompany" theme={theme} label="InCompany">
      <div className="mc-incompany" style={{ background: theme.bgRaised, borderColor: theme.rule }}>
        <div className="mc-incompany-left">
          <div className="mc-eyebrow">
            <span className="mc-tick" style={{ background: theme.accent }}></span>
            {t.incompany_eyebrow}
          </div>
          <h2 className="mc-sec-title">{t.incompany_title}</h2>
          <p className="mc-incompany-lede">{t.incompany_lede}</p>
          <Btn theme={theme} variant="primary" icon={<WhatsIcon />} href={linkTo("contato", "contato.html")}>
            {t.incompany_cta}
          </Btn>
        </div>
        <div className="mc-incompany-right">
          <ul className="mc-incompany-topics">
            {t.incompany_topics.map((tp, i) =>
            <li key={tp} style={{ borderColor: theme.rule }}>
                <span className="mc-incompany-n" style={{ color: theme.accent }}>{String(i + 1).padStart(2, "0")}</span>
                <span>{tp}</span>
              </li>
            )}
          </ul>
        </div>
      </div>
    </Section>);

}

function Socials({ t, theme }) {
  const items = [
  { tag: "LinkedIn", h: "in/reiner-modro", d: "Notas semanais sobre indústria, sucessão e governança em PME.", href: "https://www.linkedin.com/in/reiner-modro/" },
  { tag: "Instagram", h: "@reinermodro", d: "Bastidores de visitas técnicas, fábricas e conselhos.", href: "https://www.instagram.com/reinermodro/" },
  { tag: "YouTube", h: "@rmodro", d: "Conversas longas com diretores industriais e sucessores.", href: "https://www.youtube.com/@rmodro" }];

  return (
    <Section id="acompanhe" theme={theme} eyebrow={t.socials_eyebrow} title={t.socials_title} kicker={t.socials_lede} label="Socials">
      <div className="mc-socials">
        {items.map((s) =>
        <a key={s.tag} href={s.href} target="_blank" rel="noreferrer" className="mc-social" style={{ borderColor: theme.rule }}>
            <div className="mc-social-tag" style={{ color: theme.fgMuted }}>{s.tag}</div>
            <div className="mc-social-h" style={{ color: theme.fg }}>{s.h}</div>
            <div className="mc-social-d" style={{ color: theme.fgMuted }}>{s.d}</div>
            <div className="mc-social-arrow" style={{ color: theme.accent }}>→</div>
          </a>
        )}
      </div>
    </Section>);

}

Object.assign(window, { Manifesto, Purpose, Differentials, ClientResults, TrustBand, InCompany, Socials });


// ─── Gallery & Video ──────────────────────────────────────────────────────
function VideoEmbed({ t, theme }) {
  return (
    <Section id="video" theme={theme} eyebrow="Vídeo" title="Conheça o impacto real de Reiner em uma conversa." kicker="Uma entrevista que resume método, trajetória e o jeito de trabalhar." label="Video">
      <div className="mc-video-wrap" style={{ borderColor: theme.rule }}>
        <iframe
          className="mc-video"
          src="https://www.youtube-nocookie.com/embed/UjMr7gWXRyc?rel=0"
          title="Reiner Modro — entrevista"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          referrerPolicy="strict-origin-when-cross-origin"
          allowFullScreen>
        </iframe>
      </div>
    </Section>);

}

function Gallery({ t, theme }) {
  const photos = [
  { src: "assets/gallery/g1.jpg", c: "Visita técnica · Delta Máquinas Têxteis" },
  { src: "assets/gallery/g2.jpg", c: "Reunião na Öpller Industrial" },
  { src: "assets/gallery/g3.jpg", c: "Inauguração · linha Delta + Tronix" },
  { src: "assets/gallery/g4.jpg", c: "Registro · Reiner Modro e Werner R. Voigt" },
  { src: "assets/gallery/g5.jpg", c: "Homenagem · evento profissional" }, // (era g4 antes)
  { src: "assets/gallery/g6.jpg", c: "Palestra · formação de sucessores" },
  { src: "assets/gallery/g7.jpg", c: "Visita à Skymsen" },
  { src: "assets/gallery/g8.jpg", c: "Reunião na Delta Máquinas Têxteis" },
  { src: "assets/gallery/g9.jpg", c: "Feira · estande Skymsen" }];

  return (
    <Section id="galeria" theme={theme} eyebrow="Galeria" title="Bastidores das visitas e reuniões." kicker="Registros de campo de fábricas, conselhos, palestras e reuniões com clientes." label="Gallery">
      <div className="mc-gal">
        {photos.map((p, i) =>
        <figure key={i} className="mc-gal-item" style={{ borderColor: theme.rule }}>
            <img src={asset(p.src)} alt={p.c} loading="lazy" />
            <figcaption style={{ color: theme.fgMuted }}>{p.c}</figcaption>
          </figure>
        )}
      </div>
    </Section>);

}

Object.assign(window, { VideoEmbed, Gallery });
