/* ============================================================
   Veranda Bouwer — shared components & icons
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------- Minimal line icons (simple, stroke-based) ---------- */
function Icon({ name, size = 22, stroke = 2, style }) {
  const p = { fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    diamond:  <><path {...p} d="M12 3l9 9-9 9-9-9z"/></>,
    ruler:    <><rect {...p} x="3" y="8" width="18" height="8" rx="1.5"/><path {...p} d="M7 8v3M11 8v4M15 8v3M19 8v4"/></>,
    shield:   <><path {...p} d="M12 3l7 3v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/><path {...p} d="M9 12l2 2 4-4"/></>,
    tools:    <><path {...p} d="M14.5 5.5a3.5 3.5 0 00-4.7 4.3L4 15.5 8.5 20l5.7-5.8a3.5 3.5 0 004.3-4.7l-2.4 2.4-2.1-.5-.5-2.1z"/></>,
    leaf:     <><path {...p} d="M5 19c0-8 6-14 14-14 0 8-6 14-14 14z"/><path {...p} d="M5 19c4-4 7-6 11-7"/></>,
    sun:      <><circle {...p} cx="12" cy="12" r="4"/><path {...p} d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5L19 19M19 5l-1.5 1.5M6.5 17.5L5 19"/></>,
    phone:    <><path {...p} d="M5 4h3l2 5-2 1.5a11 11 0 005 5L15 13l5 2v3a2 2 0 01-2 2A15 15 0 013 6a2 2 0 012-2z"/></>,
    mail:     <><rect {...p} x="3" y="5" width="18" height="14" rx="2"/><path {...p} d="M3 7l9 6 9-6"/></>,
    pin:      <><path {...p} d="M12 21s7-6.4 7-12a7 7 0 10-14 0c0 5.6 7 12 7 12z"/><circle {...p} cx="12" cy="9" r="2.6"/></>,
    clock:    <><circle {...p} cx="12" cy="12" r="9"/><path {...p} d="M12 7v5l3.5 2"/></>,
    arrow:    <><path {...p} d="M5 12h14M13 6l6 6-6 6"/></>,
    plus:     <><path {...p} d="M12 5v14M5 12h14"/></>,
    check:    <><path {...p} d="M5 12l5 5L20 6"/></>,
    star:     <><path {...p} d="M12 3l2.6 5.6L20.5 9.5l-4.3 4.2 1 6L12 17l-5.2 2.7 1-6L3.5 9.5l5.9-.9z"/></>,
    chevL:    <><path {...p} d="M15 6l-6 6 6 6"/></>,
    chevR:    <><path {...p} d="M9 6l6 6-6 6"/></>,
    x:        <><path {...p} d="M6 6l12 12M18 6L6 18"/></>,
    facebook: <><path {...p} d="M14 8h2V5h-2a3 3 0 00-3 3v2H9v3h2v6h3v-6h2.5l.5-3H14V8.5c0-.4.3-.5.5-.5z"/></>,
    instagram:<><rect {...p} x="4" y="4" width="16" height="16" rx="5"/><circle {...p} cx="12" cy="12" r="3.4"/><circle cx="17" cy="7" r="1.2" fill="currentColor" stroke="none"/></>,
    linkedin: <><rect {...p} x="4" y="4" width="16" height="16" rx="3"/><path {...p} d="M8 10v6M8 7v0M12 16v-3.5a1.8 1.8 0 013.6 0V16"/></>,
    quote:    <><path {...p} d="M9 7H6a2 2 0 00-2 2v3h4v-3M19 7h-3a2 2 0 00-2 2v3h4v-3"/></>,
    badge:    <><circle {...p} cx="12" cy="9" r="5"/><path {...p} d="M9 13l-1 8 4-2 4 2-1-8"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={style} aria-hidden="true">{paths[name]}</svg>
  );
}

/* ---------- Brand wordmark ---------- */
function Logo({ footer }) {
  return (
    <div className={"logo" + (footer ? " logo-footer" : "")}>
      <img className="logo-img" src="assets/logo.png" alt="De Veranda Bouwer" />
    </div>
  );
}

/* ---------- Navigation ---------- */
const NAV_ITEMS = [
  { key: "home",     label: "Home" },
  { key: "projects", label: "Projecten" },
  { key: "contact",  label: "Contact" },
];

function Navbar({ page, go }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const nav = (k) => { go(k); setOpen(false); };
  return (
    <header className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="wrap nav-inner">
        <a href="#" onClick={(e) => { e.preventDefault(); nav("home"); }} aria-label="Veranda Bouwer home"><Logo /></a>
        <nav className="nav-links">
          {NAV_ITEMS.map((it) => (
            <a key={it.key} href="#" className={"nav-link" + (page === it.key ? " active" : "")}
               onClick={(e) => { e.preventDefault(); nav(it.key); }}>{it.label}</a>
          ))}
        </nav>
        <div className="nav-right">
          <a href="#" className="btn btn-primary" onClick={(e) => { e.preventDefault(); nav("contact"); }}>
            Vraag een offerte aan <Icon name="arrow" size={17} className="arr" />
          </a>
          <button className={"nav-toggle" + (open ? " open" : "")} aria-label="Menu" onClick={() => setOpen(o => !o)}>
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>
      <div className={"mobile-menu" + (open ? " open" : "")}>
        {NAV_ITEMS.map((it) => (
          <a key={it.key} href="#" className={page === it.key ? "active" : ""}
             onClick={(e) => { e.preventDefault(); nav(it.key); }}>{it.label}</a>
        ))}
        <a href="#" className="btn btn-primary" onClick={(e) => { e.preventDefault(); nav("contact"); }}>Vraag een offerte aan</a>
      </div>
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ go }) {
  const link = (k) => (e) => { e.preventDefault(); go(k); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <Logo footer />
            <p className="footer-about">
              Vakmanschap in overkappingen en veranda's uit Helmond. Wij ontwerpen, bouwen en
              installeren buitenruimtes waar u jarenlang van geniet, op maat, met oog voor detail.
            </p>
            <div className="socials">
              <a className="social" href="https://www.facebook.com/DeVerandaBouwer" target="_blank" rel="noopener noreferrer" aria-label="Facebook: De Veranda Bouwer" title="De Veranda Bouwer"><Icon name="facebook" size={20} /></a>
              <a className="social" href="https://www.instagram.com/de_veranda_bouwer" target="_blank" rel="noopener noreferrer" aria-label="Instagram: de_veranda_bouwer" title="de_veranda_bouwer"><Icon name="instagram" size={20} /></a>
            </div>
          </div>
          <div className="footer-col">
            <h5>Navigatie</h5>
            <a href="#" onClick={link("home")}>Home</a>
            <a href="#" onClick={link("projects")}>Projecten</a>
            <a href="#" onClick={link("contact")}>Contact</a>
            <a href="#" onClick={link("contact")}>Offerte aanvragen</a>
          </div>
          <div className="footer-col">
            <h5>Diensten</h5>
            <a href="#" onClick={link("projects")}>Glazen veranda's</a>
            <a href="#" onClick={link("projects")}>Aluminium overkappingen</a>
            <a href="#" onClick={link("projects")}>Lessenaarsdaken</a>
            <a href="#" onClick={link("projects")}>Terrasoverkappingen</a>
          </div>
          <div className="footer-col footer-contact">
            <h5>Contact</h5>
            <div className="row"><span className="ic"><Icon name="phone" size={17} /></span><a href="tel:+31640749627">+31 6 40749627</a></div>
            <div className="row"><span className="ic"><Icon name="mail" size={17} /></span><a href="mailto:info@de-verandabouwer.nl">info@de-verandabouwer.nl</a></div>
            <div className="row"><span className="ic"><Icon name="pin" size={17} /></span><span>Achterdijk 4<br />Helmond, Noord-Brabant</span></div>
            <div className="row"><span className="ic"><Icon name="clock" size={17} /></span><span>Ma–Vr 08:00–17:30</span></div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} De Veranda Bouwer · KvK 86960148 · BTW NL004338514B21 · IBAN NL04 INGB 0008 4391 42</span>
          <div style={{ display: "flex", gap: 20 }}>
            <a href="#">Privacybeleid</a>
            <a href="#">Algemene voorwaarden</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Scroll reveal hook ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- Premium scroll effects: progress bar + hero parallax ---------- */
function useScrollFX(dep) {
  useEffect(() => {
    const bar = document.getElementById("scrollbar");
    const heroImg = document.querySelector(".hero-img");
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const y = window.scrollY;
        const h = document.documentElement.scrollHeight - window.innerHeight;
        if (bar) bar.style.transform = "scaleX(" + (h > 0 ? Math.min(1, y / h) : 0) + ")";
        if (heroImg && !reduce) heroImg.style.transform = "translate3d(0," + (y * 0.05) + "px,0) scale(1.12)";
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener("scroll", onScroll); if (raf) cancelAnimationFrame(raf); };
  }, [dep]);
}

/* ---------- Count-up for [data-count] numbers when scrolled into view ---------- */
function useCountUp(dep) {
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const els = document.querySelectorAll("[data-count]:not([data-counted])");
    const run = (el) => {
      el.setAttribute("data-counted", "1");
      const target = parseFloat(el.getAttribute("data-count"));
      const dec = parseInt(el.getAttribute("data-decimals") || "0", 10);
      const suffix = el.getAttribute("data-suffix") || "";
      const fmt = (n) => (dec ? n.toFixed(dec).replace(".", ",") : Math.round(n).toString()) + suffix;
      if (reduce) { el.textContent = fmt(target); return; }
      const dur = 1200, start = performance.now();
      const tick = (now) => {
        const t = Math.min(1, (now - start) / dur);
        const eased = 1 - Math.pow(1 - t, 3);
        el.textContent = fmt(target * eased);
        if (t < 1) requestAnimationFrame(tick); else el.textContent = fmt(target);
      };
      requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { run(e.target); io.unobserve(e.target); } });
    }, { threshold: 0.25 });
    const vh = window.innerHeight || 800;
    els.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.top < vh && r.bottom > 0) { run(el); }
      else { io.observe(el); }
    });
    return () => io.disconnect();
  }, [dep]);
}

/* ---------- Image slot wrapper (web component in React) ---------- */
function Slot({ id, placeholder, src, fit, className, style }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (el && src && !el.getAttribute("src")) el.setAttribute("src", src);
  }, [src]);
  return React.createElement("image-slot", {
    ref, id, placeholder: placeholder || "Sleep hier een foto", fit: fit || "cover",
    class: className, style,
  });
}

Object.assign(window, { Icon, Logo, Navbar, Footer, useReveal, useScrollFX, useCountUp, Slot, NAV_ITEMS });
