// components.jsx — shared UI: Nav, Footer, hooks, primitives
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ---------- hooks ----------
function useT() {
  const [lang, setLang] = useState(() => localStorage.getItem("invia.lang") || "fr");
  useEffect(() => {localStorage.setItem("invia.lang", lang);}, [lang]);
  const t = window.I18N[lang];
  return { t, lang, setLang };
}

function useScrollSpy() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return scrolled;
}

// ---------- in-view fade ----------
function InView({ children, as: As = "div", delay = 0, className = "", ...rest }) {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Fallback: in case IntersectionObserver is throttled (sandboxed iframes, etc.),
    // force visible after a short delay so content never stays invisible.
    const fallback = setTimeout(() => setVis(true), 700);
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => {if (e.isIntersecting) {setVis(true);clearTimeout(fallback);io.disconnect();}}),
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => {clearTimeout(fallback);io.disconnect();};
  }, []);
  return (
    <As ref={ref}
    className={`fade-up ${vis ? "in" : ""} ${className}`}
    style={{ "--d": `${delay}ms` }}
    {...rest}>
      {children}
    </As>);

}

// ---------- logo / mark ----------
// Uses real brand SVG: bleu (light bg) and blanc (dark bg) variants.
function BrandMark({ size = 28, variant = "bleu" }) {
  const src = variant === "blanc" ? "assets/logo-blanc.svg" : "assets/logo-bleu.svg";
  return (
    <img loading="lazy" decoding="async" className="brand-logo" src={src} alt="Invia Gestion Financière"
    style={{ height: size * 1.2, width: "auto", display: "block" }} />);

}

// ---------- nav ----------
function Nav({ current, go, lang, setLang }) {
  const t = window.I18N[lang];
  const scrolled = useScrollSpy();
  const [mobileOpen, setMobileOpen] = useState(false);
  const links = [
  { id: "home", label: t.nav.home },
  { id: "copropriete", label: t.nav.copropriete },
  { id: "professionnel", label: t.nav.professionnel },
  { id: "ressources", label: t.nav.ressources },
  { id: "cas", label: t.nav.cas },
  { id: "faq", label: t.nav.faq },
  { id: "apropos", label: t.nav.apropos },
  { id: "contact", label: t.nav.contact }];

  return (
    <>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div className="brand" onClick={() => go("home")}>
          <BrandMark size={40} />
        </div>
        <div className="nav-links">
          {links.map((l) =>
          <a key={l.id}
          className={`nav-link ${current === l.id ? "active" : ""}`}
          onClick={() => go(l.id)}>{l.label}</a>
          )}
        </div>
        <div className="nav-right">
          <div className="lang-toggle" role="group" aria-label="Language">
            <button className={lang === "fr" ? "active" : ""} onClick={() => setLang("fr")}>FR</button>
            <span className="sep">/</span>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a className="btn btn-primary" onClick={() => go("contact")}>
            {t.nav.cta}<span className="arr">→</span>
          </a>
          <button className="menu-btn" onClick={() => setMobileOpen(true)} aria-label="Open menu">
            <span></span><span></span><span></span>
          </button>
        </div>
      </nav>
      <div className={`mobile-menu ${mobileOpen ? "open" : ""}`}>
        <div className="row" style={{ justifyContent: "space-between", width: "100%" }}>
          <div className="brand"><BrandMark size={40} /></div>
          <button onClick={() => setMobileOpen(false)} aria-label="Close" style={{ fontSize: 28 }}>×</button>
        </div>
        <div className="mobile-menu-links">
          {links.map((l) => <a key={l.id} onClick={() => {setMobileOpen(false);go(l.id);}}>{l.label}</a>)}
        </div>
        <div className="mobile-menu-foot">
          <div className="lang-toggle" style={{ width: "fit-content", marginBottom: 16 }}>
            <button className={lang === "fr" ? "active" : ""} onClick={() => setLang("fr")}>FR</button>
            <span className="sep">/</span>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a className="btn btn-primary" onClick={() => {setMobileOpen(false);go("contact");}}>
            {t.nav.cta} <span className="arr">→</span>
          </a>
        </div>
      </div>
    </>);

}

// ---------- footer ----------
function Footer({ go, lang }) {
  const t = window.I18N[lang];
  const f = t.footer;
  return (
    <footer>
      <div className="footer-grid">
        <div>
          <div className="brand" style={{ marginBottom: 18 }}>
            <BrandMark size={44} variant="blanc" />
          </div>
          <p style={{ color: "rgba(244,239,230,0.7)", maxWidth: 320, fontSize: 14 }}>{f.tag}</p>
        </div>
        <div className="footer-col">
          <h5>{f.navTitle}</h5>
          <ul>
            <li><a onClick={() => go("home")}>{t.nav.home}</a></li>
            <li><a onClick={() => go("copropriete")}>{t.nav.copropriete}</a></li>
            <li><a onClick={() => go("professionnel")}>{t.nav.professionnel}</a></li>
            <li><a onClick={() => go("ressources")}>{t.nav.ressources}</a></li>
            <li><a onClick={() => go("cas")}>{t.nav.cas}</a></li>
            <li><a onClick={() => go("faq")}>{t.nav.faq}</a></li>
            <li><a onClick={() => go("glossaire")}>{lang === "fr" ? "Glossaire" : "Glossary"}</a></li>
            <li><a onClick={() => go("apropos")}>{t.nav.apropos}</a></li>
            <li><a onClick={() => go("contact")}>{t.nav.contact}</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>{f.addrMtlTitle}</h5>
          <ul>
            <li>{f.addrMtlLine1}</li>
            <li>{f.addrMtlLine2}</li>
            <li style={{ marginTop: 8 }}><a href={`tel:${f.addrMtlPhone.replace(/\s/g, '')}`}>{f.addrMtlPhone}</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>{f.addrQcTitle}</h5>
          <ul>
            <li>{f.addrQcLine1}</li>
            <li>{f.addrQcLine2}</li>
            <li style={{ marginTop: 8 }}><a href={`tel:${f.addrQcPhone.replace(/\s/g, '')}`}>{f.addrQcPhone}</a></li>
            <li style={{ marginTop: 8 }}><a href={`mailto:${f.email}`}>{f.email}</a></li>
            {f.socials && f.socials.length > 0 &&
            <li style={{ marginTop: 18 }}>
                <h5 style={{ marginBottom: 10 }}>{f.socialTitle}</h5>
                <div style={{ display: "flex", gap: 14 }}>
                  {f.socials.map((s, i) =>
                <a key={i} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.name}
                style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 32, height: 32, borderRadius: "50%", border: "1px solid var(--on-ink-line)", color: "rgba(244,239,230,0.85)", transition: "border-color .2s, color .2s" }}
                onMouseEnter={(e) => {e.currentTarget.style.borderColor = "rgba(244,239,230,0.6)";e.currentTarget.style.color = "var(--cream)";}}
                onMouseLeave={(e) => {e.currentTarget.style.borderColor = "var(--on-ink-line)";e.currentTarget.style.color = "rgba(244,239,230,0.85)";}}>
                  
                      {s.name === "LinkedIn" ?
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z" /></svg> :

                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M22.68 0H1.32C.59 0 0 .58 0 1.3v21.4C0 23.42.59 24 1.32 24h11.5v-9.29H9.7V11.1h3.13V8.4c0-3.1 1.9-4.79 4.66-4.79 1.32 0 2.46.1 2.79.14v3.24h-1.92c-1.5 0-1.79.71-1.79 1.76v2.31h3.58l-.47 3.62h-3.11V24h6.1c.73 0 1.32-.58 1.32-1.3V1.3C24 .58 23.41 0 22.68 0z" /></svg>
                  }
                    </a>
                )}
                </div>
              </li>
            }
          </ul>
        </div>
      </div>
      <div style={{ maxWidth: "var(--container)", margin: "0 auto", paddingTop: 32, borderTop: "1px solid var(--on-ink-line)", display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 32, alignItems: "start", paddingBottom: 8 }}>
          <div>
            <h5 style={{ color: "rgba(244,239,230,0.85)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", margin: "0 0 10px" }}>{f.amfTitle}</h5>
            <p style={{ color: "rgba(244,239,230,0.65)", fontSize: 13, lineHeight: 1.6, maxWidth: 460, margin: "0 0 14px" }}>{f.amfIntro}</p>
            <a href={f.amfHref} target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, color: "rgba(244,239,230,0.9)", borderBottom: "1px solid rgba(244,239,230,0.35)", paddingBottom: 2 }}>{f.amfLink} ↗</a>
          </div>
          <dl style={{ display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 18, rowGap: 6, margin: 0, fontSize: 13, alignSelf: "start" }}>
            {f.amfRows.map((r, i) =>
            <React.Fragment key={i}>
                <dt style={{ color: "rgba(244,239,230,0.5)" }}>{r.k}</dt>
                <dd style={{ color: "rgba(244,239,230,0.9)", margin: 0, fontVariantNumeric: "tabular-nums" }}>{r.v}</dd>
              </React.Fragment>
            )}
          </dl>
        </div>
        {f.repNote &&
        <p style={{ color: "rgba(244,239,230,0.55)", fontSize: 12, lineHeight: 1.6, maxWidth: 980, paddingTop: 16, borderTop: "1px solid var(--on-ink-line)" }}>{f.repNote}</p>
        }
        <p style={{ color: "rgba(244,239,230,0.55)", fontSize: 12, lineHeight: 1.6, maxWidth: 980 }}>{f.sflNote}</p>
        <p style={{ color: "rgba(244,239,230,0.45)", fontSize: 10.5, lineHeight: 1.7, maxWidth: 980, textTransform: "uppercase", letterSpacing: "0.04em" }}>{f.sflDisclaimer}</p>
        <div style={{ display: "flex", gap: 20, flexWrap: "wrap", marginTop: 4 }}>
          {f.legal.map((l, i) => {
            const common = { key: i, style: { fontSize: 12, color: "rgba(244,239,230,0.6)" } };
            if (l.external) return <a {...common} href={l.href} target="_blank" rel="noopener noreferrer">{l.label} <span aria-hidden="true">↗</span></a>;
            return <a {...common} href="#" onClick={(e) => {e.preventDefault();go(l.target);}}>{l.label}</a>;
          })}
        </div>
      </div>
      <div className="footer-bottom" style={{ marginTop: 32 }}>
        <span>{f.copyright}</span>
      </div>
    </footer>);

}

// ---------- sticky mobile cta ----------
function StickyCTA({ go, lang }) {
  const t = window.I18N[lang];
  const labels = [t.nav.cta, t.nav.ctaAlt];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % labels.length), 5000);
    return () => clearInterval(id);
  }, [labels.length]);
  return (
    <a className="sticky-cta" onClick={() => go("contact")}>
      <span key={idx} className="sticky-cta-label">{labels[idx]}</span>
      <span style={{ fontSize: 18 }}>→</span>
    </a>);

}

// ---------- ticker ----------
function Ticker({ items }) {
  const list = [...items, ...items];
  return (
    <div className="ticker" aria-hidden>
      <div className="ticker-track">
        {list.map((it, i) =>
        <div className="ticker-item" key={i}>
            <span className="sep">◆</span> {it}
          </div>
        )}
      </div>
      <div className="ticker-track">
        {list.map((it, i) =>
        <div className="ticker-item" key={"b" + i}>
            <span className="sep">◆</span> {it}
          </div>
        )}
      </div>
    </div>);

}

// ---------- decorative chart (sparse, premium) ----------
function GrowthChart({ height = 280 }) {
  // two compounding curves: standard 2.5%, invia 4.8%
  const W = 600,H = height,padL = 40,padR = 20,padT = 20,padB = 28;
  const innerW = W - padL - padR,innerH = H - padT - padB;
  const years = 10;
  const startVal = 100;
  const ptsFor = (rate) => {
    const arr = [];
    for (let y = 0; y <= years; y++) {
      const v = startVal * Math.pow(1 + rate, y);
      arr.push(v);
    }
    return arr;
  };
  const standard = ptsFor(0.025);
  const invia = ptsFor(0.048);
  const max = invia[invia.length - 1] * 1.05;
  const min = startVal * 0.95;
  const xFor = (i) => padL + i / years * innerW;
  const yFor = (v) => padT + innerH - (v - min) / (max - min) * innerH;
  const pathFor = (arr) => arr.map((v, i) => `${i === 0 ? "M" : "L"} ${xFor(i).toFixed(1)} ${yFor(v).toFixed(1)}`).join(" ");
  const areaFor = (arr) => `${pathFor(arr)} L ${xFor(years)} ${padT + innerH} L ${padL} ${padT + innerH} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={height} style={{ display: "block" }}>
      <defs>
        <linearGradient id="gradInvia" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#B8945C" stopOpacity="0.18" />
          <stop offset="100%" stopColor="#B8945C" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* horizontal grid */}
      {[0, 0.25, 0.5, 0.75, 1].map((p, i) => {
        const y = padT + innerH * p;
        return <line key={i} x1={padL} x2={W - padR} y1={y} y2={y} stroke="rgba(14,26,43,0.08)" strokeDasharray={p === 1 ? "" : "2 4"} />;
      })}
      {/* x labels */}
      {[0, 5, 10].map((yr) =>
      <text key={yr} x={xFor(yr)} y={H - 8} fill="rgba(14,26,43,0.55)" fontSize="10" fontFamily="JetBrains Mono, monospace" textAnchor="middle">{yr}Y</text>
      )}
      <path d={areaFor(invia)} fill="url(#gradInvia)" />
      <path d={pathFor(standard)} fill="none" stroke="rgba(14,26,43,0.5)" strokeWidth="1.5" strokeDasharray="3 3" />
      <path d={pathFor(invia)} fill="none" stroke="#B8945C" strokeWidth="2" />
      {/* end labels */}
      <circle cx={xFor(years)} cy={yFor(invia[years])} r="4" fill="#B8945C" />
      <circle cx={xFor(years)} cy={yFor(standard[years])} r="3" fill="rgba(14,26,43,0.5)" />
      <text x={xFor(years) - 8} y={yFor(invia[years]) - 10} fill="#0E1A2B" fontSize="11" fontFamily="JetBrains Mono, monospace" textAnchor="end">+{Math.round((invia[years] / standard[years] - 1) * 100)}%</text>
    </svg>);

}

// ---------- placeholder block ----------
function Placeholder({ label = "PLACEHOLDER", h = 320, dark = false, children }) {
  return (
    <div className={`placeholder ${dark ? "dark" : ""}`} style={{ height: h }}>
      {children || <span className="placeholder-label">{label}</span>}
    </div>);

}

Object.assign(window, { useT, useScrollSpy, InView, BrandMark, Nav, Footer, StickyCTA, Ticker, GrowthChart, Placeholder });