/* Willow Creek — shared site chrome: Icon, Header, Footer, Section, parallax + photo helpers.
   Exports to window.WC for the other screen scripts (Babel files don't share scope). */
const { useState, useEffect, useRef, useLayoutEffect } = React;

/* ---- Lucide icon wrapper ---- */
function Icon({ name, size = 20, color = "currentColor", strokeWidth = 2, style }) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el || !window.lucide) return;
    el.innerHTML = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    el.appendChild(i);
    window.lucide.createIcons({
      attrs: { width: size, height: size, stroke: color, "stroke-width": strokeWidth },
      nameAttr: "data-lucide",
    });
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} aria-hidden="true" style={{ display: "inline-flex", width: size, height: size, ...style }} />;
}

/* ---- Scroll + pointer parallax hook ----
   Returns a ref; children with [data-depth] translate by depth * scroll. */
function useParallax() {
  const ref = useRef(null);
  useEffect(() => {
    const root = ref.current;
    if (!root) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) return;
    let raf = 0;
    const layers = () => root.querySelectorAll("[data-depth]");
    let mx = 0, my = 0;
    const apply = () => {
      const vh = window.innerHeight;
      const rect = root.getBoundingClientRect();
      const progress = (vh - rect.top) / (vh + rect.height); // 0..1 through viewport
      layers().forEach((el) => {
        const d = parseFloat(el.getAttribute("data-depth")) || 0;
        const y = (progress - 0.5) * d * 400;
        const tx = mx * d * 46;
        const ty = my * d * 32;
        el.style.transform = `translate3d(${tx}px, ${y + ty}px, 0)`;
      });
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(apply); };
    const onMove = (e) => {
      mx = (e.clientX / window.innerWidth - 0.5) * 2;
      my = (e.clientY / window.innerHeight - 0.5) * 2;
      if (!raf) raf = requestAnimationFrame(apply);
    };
    apply();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("mousemove", onMove, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("mousemove", onMove);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);
  return ref;
}

/* ---- Reveal-on-scroll ---- */
function Reveal({ children, delay = 0, y = 24, style, ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If already in (or near) the viewport on mount, show immediately.
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight + 40 && r.bottom > -40) { setShown(true); return; }
    let io = null;
    if ("IntersectionObserver" in window) {
      io = new IntersectionObserver((entries) => {
        entries.forEach((en) => { if (en.isIntersecting) { setShown(true); io.disconnect(); } });
      }, { threshold: 0.15 });
      io.observe(el);
    }
    // Fail visible: if IO never fires (unsupported / throttled iframe), force show.
    const scrollCheck = () => {
      const b = el.getBoundingClientRect();
      if (b.top < window.innerHeight + 40 && b.bottom > -40) { setShown(true); cleanup(); }
    };
    const timer = setTimeout(() => { window.addEventListener("scroll", scrollCheck, { passive: true }); scrollCheck(); }, 600);
    const cleanup = () => { clearTimeout(timer); window.removeEventListener("scroll", scrollCheck); if (io) io.disconnect(); };
    return cleanup;
  }, []);
  return (
    <div ref={ref} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? "none" : `translateY(${y}px)`,
      transition: `opacity 0.7s var(--ease-out) ${delay}ms, transform 0.7s var(--ease-out) ${delay}ms`,
      ...style,
    }} {...rest}>{children}</div>
  );
}

/* ---- Natural-toned photo placeholder (swap for real photography) ---- */
function Photo({ tone = "forest", label, icon, ratio = "4 / 3", radius = "var(--radius-xl)", style, children }) {
  const tones = {
    forest: "linear-gradient(150deg,#279a4e,#155c2e 70%,#0b1d12)",
    creek: "linear-gradient(150deg,#4fb3c2,#147381 70%,#0f5560)",
    dawn: "linear-gradient(150deg,#f8e4c9,#f08a4b 65%,#b34a12)",
    sage: "linear-gradient(150deg,#d9ec8f,#9cbf2e 70%,#279a4e)",
    room: "linear-gradient(150deg,#efe4d5,#cbbfa6 70%,#a0906f)",
  };
  return (
    <div style={{
      position: "relative", aspectRatio: ratio, borderRadius: radius, overflow: "hidden",
      background: tones[tone] || tones.forest, boxShadow: "var(--shadow-lg)",
      display: "flex", alignItems: "flex-end", ...style,
    }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 90% at 30% 15%, rgba(255,255,255,.28), transparent 55%)" }} />
      <div style={{ position: "absolute", inset: 0, opacity: 0.5,
        backgroundImage: "repeating-linear-gradient(115deg, rgba(255,255,255,.05) 0 2px, transparent 2px 9px)" }} />
      {icon && <div style={{ position: "absolute", top: 16, left: 16, color: "rgba(255,255,255,.85)" }}><Icon name={icon} size={26} /></div>}
      {label && (
        <div style={{ position: "relative", padding: "14px 16px", color: "#fffdf8", zIndex: 1 }}>
          <span style={{ fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700, letterSpacing: ".08em",
            textTransform: "uppercase", opacity: 0.9, background: "rgba(26,44,32,.35)", padding: "4px 10px",
            borderRadius: "var(--radius-pill)", backdropFilter: "blur(4px)" }}>{label}</span>
        </div>
      )}
      {children}
    </div>
  );
}

/* ---- Animated falling willow leaves (canvas) ---- */
function LeafField({ count = 18, near = false, style }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const canvas = canvasRef.current;
    if (reduce || !canvas) return;
    const ctx = canvas.getContext("2d");
    const palette = near ? ["#279a4e", "#155c2e", "#9cbf2e", "#e05e1b"] : ["#9cbf2e", "#c1dd55", "#3cb865", "#d9ec8f"];
    let W = 0, H = 0, leaves = [], run = true;
    const rand = (a, b) => a + Math.random() * (b - a);
    const resize = () => { const r = canvas.getBoundingClientRect(); W = canvas.width = Math.max(1, r.width); H = canvas.height = Math.max(1, r.height); };
    const spawn = (top) => ({
      x: rand(-30, 30) + rand(0, W), y: top ? rand(-H * 0.25, -16) : rand(-16, H),
      s: near ? rand(14, 26) : rand(7, 13), vy: near ? rand(50, 100) : rand(16, 40),
      sway: rand(22, 64) * (near ? 1.6 : 1), swaySpeed: rand(0.4, 1.1), phase: rand(0, Math.PI * 2),
      spin: rand(-1.2, 1.2), rot: rand(0, Math.PI * 2),
      color: palette[(Math.random() * palette.length) | 0], alpha: near ? rand(0.65, 0.95) : rand(0.45, 0.8),
    });
    resize();
    for (let i = 0; i < count; i++) leaves.push(spawn(false));
    window.addEventListener("resize", resize, { passive: true });
    let last = performance.now();
    const tick = (now) => {
      if (!run) return;
      const dt = Math.min(0.05, (now - last) / 1000); last = now;
      if (!document.hidden) {
        ctx.clearRect(0, 0, W, H);
        for (let k = 0; k < leaves.length; k++) {
          const L = leaves[k];
          L.phase += L.swaySpeed * dt; L.rot += L.spin * dt; L.y += L.vy * dt;
          if (L.y - L.s > H + 18) { leaves[k] = spawn(true); continue; }
          ctx.save();
          ctx.globalAlpha = L.alpha;
          ctx.translate(L.x + Math.sin(L.phase) * L.sway, L.y);
          ctx.rotate(L.rot);
          ctx.scale(0.55 + 0.45 * Math.abs(Math.cos(L.phase * 0.9)), 1);
          ctx.beginPath();
          ctx.moveTo(0, -L.s);
          ctx.quadraticCurveTo(L.s * 0.55, -L.s * 0.25, 0, L.s);
          ctx.quadraticCurveTo(-L.s * 0.55, -L.s * 0.25, 0, -L.s);
          ctx.fillStyle = L.color; ctx.fill();
          ctx.restore();
        }
        ctx.globalAlpha = 1;
      }
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
    return () => { run = false; window.removeEventListener("resize", resize); };
  }, [count, near]);
  return <canvas ref={canvasRef} aria-hidden="true" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none", ...style }} />;
}

/* ---- Slow-motion background video (free Pexels footage, graded to theme) ---- */
function VideoBG({ sources = [], poster, rate = 0.5, tint = "#1e7a3e", tintOpacity = 0.45, darken = 0.35, style }) {
  const vidRef = useRef(null);
  useEffect(() => {
    const v = vidRef.current;
    if (!v) return;
    const setRate = () => { try { v.playbackRate = rate; } catch (e) {} };
    const kick = () => { v.muted = true; setRate(); const p = v.play(); if (p && p.catch) p.catch(() => {}); };
    v.addEventListener("loadeddata", setRate);
    v.addEventListener("play", setRate);
    // Terminal failure only: hide the <video> (NOT the wrapper — the dark
    // gradient backdrop must stay so overlaid text remains readable).
    const lastSource = v.querySelector("source:last-of-type");
    const onTerminal = () => {
      if (v.error || v.networkState === 3 /* NETWORK_NO_SOURCE */) v.style.display = "none";
    };
    v.addEventListener("error", onTerminal);
    if (lastSource) lastSource.addEventListener("error", onTerminal);
    kick();
    const t1 = setTimeout(kick, 800), t2 = setTimeout(kick, 2500);
    const once = { passive: true, once: true };
    ["scroll", "pointerdown", "touchstart", "keydown"].forEach((ev) => window.addEventListener(ev, kick, once));
    const vis = () => { if (!document.hidden) kick(); };
    document.addEventListener("visibilitychange", vis);
    return () => {
      clearTimeout(t1); clearTimeout(t2);
      document.removeEventListener("visibilitychange", vis);
      v.removeEventListener("loadeddata", setRate);
      v.removeEventListener("play", setRate);
      v.removeEventListener("error", onTerminal);
      if (lastSource) lastSource.removeEventListener("error", onTerminal);
    };
  }, [rate]);
  return (
    <div aria-hidden="true" style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none",
      background: "var(--grad-canopy)", ...style }}>
      <video ref={vidRef} autoPlay muted loop playsInline preload="auto" poster={poster}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}>
        {sources.map((s, i) => <source key={i} src={s} type="video/mp4" />)}
      </video>
      <div style={{ position: "absolute", inset: 0, background: tint, mixBlendMode: "soft-light", opacity: tintOpacity }} />
      <div style={{ position: "absolute", inset: 0, background: `linear-gradient(180deg, rgba(11,29,18,${darken}) 0%, rgba(11,29,18,${darken * 0.3}) 40%, rgba(11,29,18,${darken * 1.4}) 100%)` }} />
    </div>
  );
}

/* Free-license footage (Pexels — free for commercial use, no attribution).
   File URLs verified against the Pexels pages:
   · Willow: pexels.com/video/weeping-willow-tree-branches-swaying-in-the-wind-13078332
   · Creek:  pexels.com/video/stream-flowing-over-rocks-6754982
   · Forest fallback: pexels.com/video/forest-852335 */
const FOOTAGE = {
  willow: {
    sources: [
      "https://videos.pexels.com/video-files/13078332/13078332-uhd_2560_1440_60fps.mp4",
      "https://www.pexels.com/download/video/13078332/",
      "https://videos.pexels.com/video-files/852335/852335-hd_1920_1080_24fps.mp4",
    ],
    poster: "https://images.pexels.com/videos/13078332/flowing-water-forest-nature-green-leaves-leaves-13078332.jpeg?auto=compress&cs=tinysrgb&w=1920",
  },
  creek: {
    sources: [
      "https://videos.pexels.com/video-files/6754982/6754982-hd_1920_1080_25fps.mp4",
      "https://www.pexels.com/download/video/6754982/",
      "https://videos.pexels.com/video-files/852335/852335-hd_1920_1080_24fps.mp4",
    ],
    poster: "https://images.pexels.com/videos/6754982/pexels-photo-6754982.jpeg?auto=compress&cs=tinysrgb&w=1920",
  },
};

/* ---- Layout container ---- */
function Container({ children, narrow = false, style }) {
  return <div style={{ width: "100%", maxWidth: narrow ? "var(--container-narrow)" : "var(--container-max)",
    margin: "0 auto", padding: "0 var(--gutter)", ...style }}>{children}</div>;
}

function Eyebrow({ children, style }) {
  return <span style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "var(--text-sm)",
    letterSpacing: "var(--ls-caps)", textTransform: "uppercase", color: "var(--brand-secondary)",
    display: "inline-flex", alignItems: "center", gap: 8, ...style }}>{children}</span>;
}

/* ---- Header / nav ---- */
const NAV = [
  { id: "home", label: "Home" },
  { id: "about", label: "Our Approach" },
  { id: "programs", label: "Programs" },
  { id: "home-tour", label: "The Home" },
  { id: "faq", label: "FAQ" },
  { id: "contact", label: "Contact" },
];

function Header({ route, go }) {
  const { Button } = window.WillowCreekDesignSystem_90378c;
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 100,
      background: scrolled ? "rgba(250,248,242,.86)" : "transparent",
      backdropFilter: scrolled ? "blur(14px) saturate(1.1)" : "none",
      borderBottom: scrolled ? "1px solid var(--border-subtle)" : "1px solid transparent",
      boxShadow: scrolled ? "var(--shadow-sm)" : "none",
      transition: "all var(--dur-base) var(--ease-out)",
    }}>
      <Container style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 76 }}>
        <a href="#home" onClick={(e) => { e.preventDefault(); go("home"); }} style={{ display: "inline-flex", alignItems: "center" }}>
          <img src="assets/logo-wordmark.svg" alt="Willow Creek Sober Living" style={{ height: 40 }} />
        </a>
        <nav style={{ display: "flex", alignItems: "center", gap: 4 }} className="wc-desktop-nav">
          {NAV.map((n) => (
            <a key={n.id} href={"#" + n.id} onClick={(e) => { e.preventDefault(); go(n.id); }}
               style={{ padding: "8px 14px", borderRadius: "var(--radius-pill)", fontFamily: "var(--font-sans)",
                 fontWeight: 600, fontSize: "var(--text-sm)",
                 color: route === n.id ? "var(--brand-primary)" : "var(--text-body)",
                 background: route === n.id ? "var(--surface-accent-soft)" : "transparent",
                 transition: "all var(--dur-fast) var(--ease-out)" }}>{n.label}</a>
          ))}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <a href="tel:19405550142" style={{ display: "inline-flex", alignItems: "center", gap: 7, fontWeight: 700,
            color: "var(--text-heading)", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)" }} className="wc-phone">
            <Icon name="phone" size={16} color="var(--brand-primary)" /> (940) 555-0142
          </a>
          <a href="portal/" title="Resident & staff portal" style={{ display: "inline-flex", alignItems: "center", gap: 6,
            padding: "8px 12px", borderRadius: "var(--radius-pill)", fontFamily: "var(--font-sans)", fontWeight: 600,
            fontSize: "var(--text-sm)", color: "var(--text-body)" }} className="wc-phone">
            <Icon name="circle-user-round" size={17} color="var(--brand-primary)" /> Portal
          </a>
          <Button variant="primary" size="sm" onClick={() => go("admissions")}>Start application</Button>
        </div>
      </Container>
    </header>
  );
}

function Footer({ go }) {
  return (
    <footer style={{ background: "var(--surface-inverse)", color: "var(--sage-200)", marginTop: 0 }}>
      <Container style={{ padding: "var(--space-10) var(--gutter) var(--space-7)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1.3fr", gap: "var(--space-7)", alignItems: "start" }} className="wc-footer-grid">
          <div>
            <img src="assets/logo-wordmark-inverse.svg" alt="Willow Creek Sober Living" style={{ height: 44 }} />
            <p style={{ marginTop: 16, maxWidth: "34ch", lineHeight: 1.6, color: "var(--sage-200)" }}>
              A structured, supportive sober living home for the hardest, most hopeful season of your life.
            </p>
            <div style={{ display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap" }}>
              {[["instagram", "Instagram"], ["youtube", "YouTube"], ["facebook", "Facebook"], ["twitter", "X"], ["linkedin", "LinkedIn"]].map(([s, label]) => (
                <a key={s} href="#" aria-label={label} onClick={(e) => e.preventDefault()}
                  onMouseEnter={(e) => { e.currentTarget.style.background = "var(--moss-400)"; e.currentTarget.style.color = "var(--forest-900)"; e.currentTarget.style.transform = "translateY(-3px)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,.07)"; e.currentTarget.style.color = "var(--sage-200)"; e.currentTarget.style.transform = "translateY(0)"; }}
                  style={{ width: 44, height: 44, borderRadius: "var(--radius-md)",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    background: "rgba(255,255,255,.07)", color: "var(--sage-200)",
                    border: "1px solid rgba(255,255,255,.12)",
                    transition: "all var(--dur-fast) var(--ease-out)" }}><Icon name={s} size={20} /></a>
              ))}
            </div>
          </div>
          <FooterCol title="Explore" links={[["about","Our Approach"],["programs","Programs"],["home-tour","The Home"],["faq","FAQ"]]} go={go} />
          <FooterCol title="Get started" links={[["admissions","Apply now"],["contact","Schedule a tour"],["contact","Contact us"]]} go={go} />
          <div>
            <h4 style={{ fontFamily: "var(--font-display)", color: "var(--sand-50)", fontSize: "var(--text-md)", margin: "0 0 14px" }}>Visit</h4>
            <p style={{ margin: 0, lineHeight: 1.7, color: "var(--sage-200)", fontSize: "var(--text-sm)" }}>
              2013 Mark Twain Lane<br />Denton, TX 76210<br />
              <a href="tel:19405550142" style={{ color: "var(--sand-50)" }}>(940) 555-0142</a><br />
              <a href="mailto:avira25.llc@gmail.com" style={{ color: "var(--sand-50)" }}>avira25.llc@gmail.com</a>
            </p>
          </div>
        </div>
        <div style={{ marginTop: "var(--space-8)", paddingTop: "var(--space-5)", borderTop: "1px solid rgba(255,255,255,.1)",
          display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, fontSize: "var(--text-sm)", color: "var(--sage-300)" }}>
          <span>© 2026 Willow Creek Sober Living.</span>
          <span style={{ display: "inline-flex", gap: 18 }}>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: "var(--sage-300)" }}>Privacy</a>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: "var(--sage-300)" }}>Fair Housing</a>
          </span>
        </div>
      </Container>
    </footer>
  );
}
function FooterCol({ title, links, go }) {
  return (
    <div>
      <h4 style={{ fontFamily: "var(--font-display)", color: "var(--sand-50)", fontSize: "var(--text-md)", margin: "0 0 14px" }}>{title}</h4>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {links.map(([id, label], i) => (
          <li key={i}><a href={"#" + id} onClick={(e) => { e.preventDefault(); go(id); }}
            style={{ color: "var(--sage-200)", fontSize: "var(--text-sm)" }}>{label}</a></li>
        ))}
      </ul>
    </div>
  );
}

/* Crisis strip — always available */
function CrisisBar() {
  return (
    <div style={{ background: "var(--forest-800)", color: "var(--sage-100)", fontSize: "var(--text-sm)", fontWeight: 500 }}>
      <Container style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, minHeight: 38, textAlign: "center", flexWrap: "wrap" }}>
        <Icon name="life-buoy" size={15} color="var(--sage-300)" />
        In crisis? Call or text <a href="tel:988" style={{ color: "#fffdf8", fontWeight: 700 }}>988</a> — the Suicide &amp; Crisis Lifeline, free & confidential, 24/7.
      </Container>
    </div>
  );
}

window.WC = { Icon, useParallax, Reveal, Photo, Container, Eyebrow, Header, Footer, CrisisBar, LeafField, VideoBG, FOOTAGE, NAV };
