// ============================================================
// TERREXO — Shared components (nav, footer, marks, helpers)
// Loaded after React + data/site.js
// ============================================================

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

// --- Responsive breakpoint hook ---
function useMobile(bp = 768) {
  const [m, setM] = useState(window.innerWidth < bp);
  useEffect(() => {
    const h = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", h, { passive: true });
    return () => window.removeEventListener("resize", h);
  }, [bp]);
  return m;
}

// --- Logo / wordmark ---
function Wordmark({ size = 22, dark = false, lockup = true }) {
  const color = dark ? "#FAFAF7" : "#161A18";
  return (
    <a href="index.html" style={{ display: "inline-flex", alignItems: "center", gap: 10, color }}>
      <svg width={size + 6} height={size + 6} viewBox="0 0 32 32" fill="none">
        <path d="M3 24 L16 6 L29 24 Z" stroke={color} strokeWidth="1.6" fill="none"/>
        <path d="M9 24 L16 14 L23 24 Z" fill={color}/>
        <circle cx="16" cy="14" r="1.6" fill={dark ? "#161A18" : "#FAFAF7"}/>
      </svg>
      {lockup && (
        <span style={{
          fontFamily: "var(--font-sans)",
          fontWeight: 600,
          fontSize: size,
          letterSpacing: "-0.025em",
          color,
        }}>
          Terrexo<span style={{ color: "var(--sage)" }}>.</span>
        </span>
      )}
    </a>
  );
}

// --- Top nav ---
function Nav({ active = "", dark = false }) {
  const [scrolled, setScrolled] = useState(false);
  const [progress, setProgress] = useState(0);
  const [lang, setLang] = useState("FR");
  const [open, setOpen] = useState(false);
  const isMobile = useMobile(960);

  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 30);
      const h = document.documentElement.scrollHeight - window.innerHeight;
      setProgress(h > 0 ? (window.scrollY / h) * 100 : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (!isMobile && open) setOpen(false);
  }, [isMobile]);

  const inkColor = dark ? "#FAFAF7" : "#161A18";
  const bg = (scrolled || open)
    ? (dark ? "rgba(22,26,24,.94)" : "rgba(250,250,247,.96)")
    : "transparent";

  return (
    <>
      <div className="scroll-progress" style={{ width: progress + "%" }} />
      <header style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
        backdropFilter: (scrolled || open) ? "blur(14px) saturate(140%)" : "none",
        WebkitBackdropFilter: (scrolled || open) ? "blur(14px) saturate(140%)" : "none",
        background: bg,
        borderBottom: (scrolled || open) ? "1px solid var(--rule)" : "1px solid transparent",
        transition: "background .35s var(--ease), border-color .35s var(--ease)",
        color: inkColor,
      }}>
        <div className="container-wide" style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          height: 76,
        }}>
          <Wordmark dark={dark} />

          {/* Desktop nav */}
          {!isMobile && (
            <nav style={{ display: "flex", alignItems: "center", gap: 36 }}>
              {window.TERREXO.nav.map(item => (
                <a key={item.href} href={item.href} className="link-grow" style={{
                  fontSize: 14,
                  fontWeight: active === item.href ? 600 : 400,
                  color: inkColor,
                  opacity: active === item.href ? 1 : 0.78,
                }}>
                  {item.label}
                </a>
              ))}
            </nav>
          )}

          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            {!isMobile && (
              <div style={{ display: "flex", gap: 2, fontFamily: "var(--font-mono)", fontSize: 11 }}>
                {window.TERREXO.languages.map((l) => (
                  <button key={l} onClick={() => setLang(l)} style={{
                    background: "transparent",
                    border: 0,
                    cursor: "pointer",
                    padding: "6px 8px",
                    color: lang === l ? inkColor : (dark ? "rgba(250,250,247,.45)" : "rgba(22,26,24,.45)"),
                    fontWeight: lang === l ? 600 : 400,
                    letterSpacing: "0.08em",
                  }}>{l}</button>
                ))}
              </div>
            )}
            {!isMobile && (
              <a href="contact.html" className="btn btn-primary" style={
                dark ? { background: "var(--paper)", color: "var(--ink)", borderColor: "var(--paper)" } : {}
              }>
                Demander un devis <ArrowIcon />
              </a>
            )}

            {/* Hamburger button */}
            {isMobile && (
              <button
                onClick={() => setOpen(o => !o)}
                aria-label={open ? "Fermer le menu" : "Ouvrir le menu"}
                style={{
                  background: "transparent", border: 0, cursor: "pointer",
                  padding: 10, color: inkColor,
                  display: "flex", flexDirection: "column", gap: 5,
                  justifyContent: "center", width: 44, height: 44,
                }}
              >
                <span style={{
                  display: "block", width: 22, height: 1.5, background: "currentColor",
                  transition: "transform .3s var(--ease-out)",
                  transform: open ? "translateY(6.5px) rotate(45deg)" : "none",
                }}/>
                <span style={{
                  display: "block", width: 22, height: 1.5, background: "currentColor",
                  transition: "opacity .2s var(--ease)",
                  opacity: open ? 0 : 1,
                }}/>
                <span style={{
                  display: "block", width: 22, height: 1.5, background: "currentColor",
                  transition: "transform .3s var(--ease-out)",
                  transform: open ? "translateY(-6.5px) rotate(-45deg)" : "none",
                }}/>
              </button>
            )}
          </div>
        </div>

        {/* Mobile drawer */}
        {isMobile && (
          <div style={{
            overflow: "hidden",
            maxHeight: open ? "100vh" : 0,
            opacity: open ? 1 : 0,
            transition: "max-height .4s var(--ease-out), opacity .25s var(--ease)",
            background: dark ? "rgba(22,26,24,.97)" : "rgba(250,250,247,.98)",
            borderTop: open ? "1px solid var(--rule)" : "none",
          }}>
            <div className="container-wide" style={{ paddingTop: 20, paddingBottom: 36 }}>
              <nav>
                {window.TERREXO.nav.map(item => (
                  <a key={item.href} href={item.href} style={{
                    display: "flex", alignItems: "center", justifyContent: "space-between",
                    fontSize: 22, letterSpacing: "-0.02em",
                    fontWeight: active === item.href ? 600 : 400,
                    color: inkColor,
                    padding: "14px 0",
                    borderBottom: "1px solid var(--rule)",
                    opacity: active === item.href ? 1 : 0.75,
                    textDecoration: "none",
                  }}>
                    {item.label}
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" style={{ opacity: 0.4 }}>
                      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </a>
                ))}
              </nav>
              <div style={{ marginTop: 28, display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center" }}>
                <a href="contact.html" className="btn btn-primary" style={
                  dark ? { background: "var(--paper)", color: "var(--ink)", borderColor: "var(--paper)" } : {}
                }>
                  Demander un devis <ArrowIcon />
                </a>
                <div style={{ display: "flex", gap: 2, fontFamily: "var(--font-mono)", fontSize: 11 }}>
                  {window.TERREXO.languages.map((l) => (
                    <button key={l} onClick={() => setLang(l)} style={{
                      background: "transparent", border: 0, cursor: "pointer",
                      padding: "6px 8px",
                      color: lang === l ? inkColor : (dark ? "rgba(250,250,247,.45)" : "rgba(22,26,24,.45)"),
                      fontWeight: lang === l ? 600 : 400,
                      letterSpacing: "0.08em",
                    }}>{l}</button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}
      </header>
    </>
  );
}

function ArrowIcon({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// --- Footer ---
function Footer() {
  const T = window.TERREXO;
  const isMobile = useMobile(768);
  const isTablet = useMobile(1024);

  return (
    <footer>
      <div className="container-wide" style={{ paddingTop: isMobile ? 60 : 100, paddingBottom: 40 }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : (isTablet ? "1fr 1fr" : "2fr 1fr 1fr 1.2fr"),
          gap: isMobile ? 40 : 60,
          paddingBottom: isMobile ? 40 : 80,
          borderBottom: "1px solid rgba(250,250,247,.12)",
        }}>
          {/* Brand + CTA */}
          <div>
            <div className="h2 serif italic" style={{ marginBottom: 28, maxWidth: 520, color: "var(--paper)" }}>
              Un projet en tête ?<br/>
              Venez nous le raconter.
            </div>
            <a href="contact.html" className="btn btn-on-dark">
              Démarrer un projet <ArrowIcon />
            </a>
            <div style={{ marginTop: isMobile ? 32 : 64, display: "flex", gap: 40, fontSize: 13, opacity: 0.7, flexWrap: "wrap" }}>
              <div>
                <div className="eyebrow" style={{ color: "rgba(250,250,247,.45)", marginBottom: 8 }}>Atelier</div>
                <div>{T.brand.address}</div>
                <div style={{ marginTop: 4 }}>{T.brand.hours}</div>
              </div>
              <div>
                <div className="eyebrow" style={{ color: "rgba(250,250,247,.45)", marginBottom: 8 }}>Contact</div>
                <div>{T.brand.phone}</div>
                <div style={{ marginTop: 4 }}>{T.brand.email}</div>
              </div>
            </div>
          </div>

          {/* Nav links */}
          <div>
            <div className="eyebrow" style={{ color: "rgba(250,250,247,.45)", marginBottom: 18 }}>Navigation</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              {T.nav.map(n => <li key={n.href}><a href={n.href} className="link-grow">{n.label}</a></li>)}
            </ul>
          </div>

          {/* Service links */}
          <div>
            <div className="eyebrow" style={{ color: "rgba(250,250,247,.45)", marginBottom: 18 }}>Services</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              {T.services.map(s => (
                <li key={s.slug}>
                  <a href={`service.html?s=${s.slug}`} className="link-grow">{s.title}</a>
                </li>
              ))}
            </ul>
          </div>

          {/* Newsletter */}
          <div>
            <div className="eyebrow" style={{ color: "rgba(250,250,247,.45)", marginBottom: 18 }}>Newsletter</div>
            <p style={{ fontSize: 14, opacity: 0.7, marginTop: 0, marginBottom: 18, lineHeight: 1.5 }}>
              Quelques notes par saison sur l'artisanat, les chantiers et la rénovation au Luxembourg.
            </p>
            <div style={{ display: "flex", borderBottom: "1px solid rgba(250,250,247,.3)", paddingBottom: 8 }}>
              <input
                placeholder="vous@exemple.lu"
                style={{
                  flex: 1, background: "transparent", border: 0, outline: "none",
                  color: "var(--paper)", fontSize: 15, fontFamily: "inherit", padding: "8px 0",
                }}
              />
              <button style={{ background: "transparent", border: 0, color: "var(--paper)", cursor: "pointer", padding: "8px 0" }}>
                <ArrowIcon size={16} />
              </button>
            </div>
          </div>
        </div>

        {/* Bottom bar */}
        <div style={{
          display: "flex",
          flexDirection: isMobile ? "column" : "row",
          justifyContent: isMobile ? "center" : "space-between",
          alignItems: "center",
          gap: isMobile ? 10 : 0,
          paddingTop: 28,
          fontSize: 12, opacity: 0.55, fontFamily: "var(--font-mono)",
          textAlign: isMobile ? "center" : "initial",
        }}>
          <div>© Terrexo S.à r.l. — RCS Luxembourg B 248 902</div>
          {!isMobile && (
            <div style={{ display: "flex", gap: 28 }}>
              <a href="#">Mentions légales</a>
              <a href="#">Confidentialité</a>
              <a href="#">Garantie décennale</a>
            </div>
          )}
          <div>Foetz · Luxembourg — 49.512°N, 6.011°E</div>
        </div>
      </div>
    </footer>
  );
}

// --- Section header ---
function SectionHead({ eyebrow, title, lead, action }) {
  return (
    <div className="section-head sr">
      <div>
        <div className="eyebrow" style={{ marginBottom: 16 }}>{eyebrow}</div>
        <h2 className="h1" style={{ maxWidth: "9ch" }}>{title}</h2>
      </div>
      <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 24 }}>
        {lead && <p className="body-lg" style={{ margin: 0, color: "var(--ink-2)", maxWidth: "44ch" }}>{lead}</p>}
        {action}
      </div>
    </div>
  );
}

// --- Stat counter ---
function Stat({ value, label, suffix = "" }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const start = performance.now();
          const dur = 1600;
          const isFloat = !Number.isInteger(value);
          const tick = (t) => {
            const p = Math.min((t - start) / dur, 1);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(isFloat ? +(value * eased).toFixed(1) : Math.round(value * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          obs.disconnect();
        }
      });
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [value]);

  return (
    <div ref={ref} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div className="stat-num">{n}{suffix}</div>
      <div style={{ fontSize: 13, color: "var(--ink-3)", fontFamily: "var(--font-mono)", letterSpacing: "0.04em", textTransform: "uppercase" }}>{label}</div>
    </div>
  );
}

// --- Project card ---
function ProjectCard({ p, large = false }) {
  return (
    <a href={`projet.html?p=${p.slug}`} className="sr" style={{ display: "block" }}>
      <div className="media" style={{ aspectRatio: large ? "4 / 3" : "5 / 4", marginBottom: 18, borderRadius: "var(--r-md)" }}>
        <img src={p.cover} alt={p.title} loading="lazy" />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16 }}>
        <div>
          <div className={large ? "h3" : "h4"} style={{ fontWeight: 500, letterSpacing: "-0.01em" }}>{p.title}</div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4, fontFamily: "var(--font-mono)" }}>
            {p.location} · {p.serviceLabel}
          </div>
        </div>
        <div className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.year}</div>
      </div>
    </a>
  );
}

// --- Scroll reveal hook (init for whole page) ---
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".sr");
    const obs = new IntersectionObserver(entries => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          const idx = [...e.target.parentElement.children].indexOf(e.target);
          e.target.style.transitionDelay = (Math.min(idx, 6) * 0.06) + "s";
          e.target.classList.add("in");
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    els.forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

// --- Final CTA (small, used across many pages) ---
function FinalCTASmall() {
  return (
    <section className="section">
      <div className="container-wide" style={{ textAlign: "center" }}>
        <h2 className="h-display sr" style={{ maxWidth: "16ch", margin: "0 auto" }}>
          Vous savez ce que vous voulez ?<br/>
          <span className="serif italic" style={{ fontWeight: 400 }}>Ou pas du tout ?</span>
        </h2>
        <p className="body-lg sr" style={{ marginTop: 32, color: "var(--ink-2)", maxWidth: "50ch", marginLeft: "auto", marginRight: "auto" }}>
          Dans les deux cas, on commence par une visite. Gratuite, sans engagement.
        </p>
        <div className="sr" style={{ marginTop: 40 }}>
          <a href="contact.html" className="btn btn-primary">Prendre rendez-vous <ArrowIcon /></a>
        </div>
      </div>
    </section>
  );
}

// Expose globally
Object.assign(window, {
  Wordmark, Nav, Footer, SectionHead, Stat, ProjectCard, ArrowIcon,
  useScrollReveal, FinalCTASmall, useMobile,
});
