/* Pilgrim Wright — shared components */

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

/* ---------- Brand mark (compass-anchored monogram) ---------- */
function BrandMark({ size = 28 }) {
  return (
    <div className="nav__brand-mark" style={{ width: size, height: size, fontSize: size * 0.56 }}>
      <span>P</span>
    </div>
  );
}

/* ---------- Logo wordmark ---------- */
function Wordmark() {
  return (
    <div className="nav__brand">
      <BrandMark />
      <span style={{ fontFamily: "var(--font-serif)", fontWeight: 420, fontSize: 19 }}>
        Pilgrim Wright
      </span>
    </div>
  );
}

/* ---------- Compass mark (small "+") ---------- */
function CompassMark({ size = 12, style }) {
  return <span className="compass-mark" style={{ width: size, height: size, ...style }} />;
}

/* ---------- Topographic SVG (decorative path lines) ---------- */
function TopoLines({ opacity = 0.6, count = 7 }) {
  // Hand-tuned wavy contour lines that suggest a topographic map / horizon.
  const lines = useMemo(() => {
    const out = [];
    for (let i = 0; i < count; i++) {
      const y = 30 + i * 22;
      const amp = 8 + (i % 3) * 4;
      const phase = i * 0.7;
      let d = `M 0 ${y}`;
      for (let x = 20; x <= 800; x += 20) {
        const yy = y + Math.sin((x / 90) + phase) * amp + Math.cos((x / 160) + phase * 0.4) * (amp * 0.4);
        d += ` L ${x} ${yy.toFixed(1)}`;
      }
      out.push(d);
    }
    return out;
  }, [count]);
  return (
    <svg viewBox="0 0 800 220" preserveAspectRatio="none" className="topo-svg" style={{ opacity }}>
      {lines.map((d, i) => (
        <path key={i} d={d} fill="none" stroke="currentColor" strokeWidth="0.7" />
      ))}
    </svg>
  );
}

/* ---------- Compass rose (for hero decorative) ---------- */
function CompassRose({ size = 200, accent = false }) {
  return (
    <svg viewBox="0 0 200 200" width={size} height={size} style={{ display: "block" }}>
      <g fill="none" stroke="currentColor" strokeWidth="0.7">
        <circle cx="100" cy="100" r="92" />
        <circle cx="100" cy="100" r="64" />
        <circle cx="100" cy="100" r="36" />
        {Array.from({ length: 16 }).map((_, i) => {
          const a = (i * Math.PI * 2) / 16;
          const inner = i % 4 === 0 ? 36 : i % 2 === 0 ? 64 : 80;
          const outer = 92;
          return (
            <line
              key={i}
              x1={100 + Math.cos(a) * inner}
              y1={100 + Math.sin(a) * inner}
              x2={100 + Math.cos(a) * outer}
              y2={100 + Math.sin(a) * outer}
              strokeWidth={i % 4 === 0 ? "1" : "0.5"}
            />
          );
        })}
      </g>
      {/* N marker */}
      <text x="100" y="20" textAnchor="middle"
        style={{ font: 'italic 11px "Source Serif 4", serif', fill: accent ? "var(--accent-deep)" : "currentColor" }}>
        N
      </text>
      <text x="100" y="190" textAnchor="middle"
        style={{ font: '10px "JetBrains Mono", monospace', letterSpacing: "0.16em", fill: "currentColor" }}>
        S
      </text>
      <text x="14" y="104" textAnchor="middle"
        style={{ font: '10px "JetBrains Mono", monospace', letterSpacing: "0.16em", fill: "currentColor" }}>
        W
      </text>
      <text x="186" y="104" textAnchor="middle"
        style={{ font: '10px "JetBrains Mono", monospace', letterSpacing: "0.16em", fill: "currentColor" }}>
        E
      </text>
      {/* Compass needle */}
      <g transform="translate(100 100)">
        <polygon points="0,-70 6,0 0,18 -6,0" fill={accent ? "var(--accent)" : "var(--ink)"} />
        <polygon points="0,70 6,0 0,-18 -6,0" fill="none" stroke="currentColor" strokeWidth="0.8" />
        <circle r="3" fill="var(--paper)" stroke="currentColor" strokeWidth="0.8" />
      </g>
    </svg>
  );
}

/* ---------- Button ---------- */
function Btn({ variant = "primary", arrow, children, onClick, type, href }) {
  const cls = `btn btn--${variant}`;
  const inner = (
    <>
      <span>{children}</span>
      {arrow && (
        <svg width="14" height="10" viewBox="0 0 14 10" fill="none">
          <path d="M1 5 L13 5 M9 1 L13 5 L9 9" stroke="currentColor" strokeWidth="1.2" />
        </svg>
      )}
    </>
  );
  if (href) {
    return <a href={href} className={cls} onClick={onClick}>{inner}</a>;
  }
  return <button type={type || "button"} className={cls} onClick={onClick}>{inner}</button>;
}

/* ---------- Scroll reveal hook ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === "undefined") {
      el.classList.add("in");
      return;
    }
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          el.classList.add("in");
          io.disconnect();
        }
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ delay = 0, children, as = "div", className = "", style }) {
  const ref = useReveal();
  const Comp = as;
  return (
    <Comp ref={ref} className={`reveal ${className}`} style={{ "--reveal-delay": `${delay}ms`, ...style }}>
      {children}
    </Comp>
  );
}

/* ---------- Nav ---------- */
const NAV_LINKS = [
  { id: "home", label: "Home", num: "01" },
  { id: "services", label: "Services", num: "02" },
  { id: "audiences", label: "Who We Serve", num: "03" },
  { id: "about", label: "About", num: "04" },
  { id: "contact", label: "Contact", num: "05" },
];

function Nav({ page, navigate }) {
  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);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
  }, [open]);

  return (
    <>
      <nav className={`nav ${scrolled ? "nav--scrolled" : ""}`}>
        <div className="container">
          <div className="nav__inner">
            <a href="#" onClick={(e) => { e.preventDefault(); navigate("home"); }}>
              <Wordmark />
            </a>
            <div className="nav__links">
              {NAV_LINKS.slice(1).map((l) => (
                <a key={l.id}
                   href={`#${l.id}`}
                   className={page === l.id ? "active" : ""}
                   onClick={(e) => { e.preventDefault(); navigate(l.id); }}>
                  {l.label}
                </a>
              ))}
            </div>
            <div className="nav__cta">
              <Btn variant="secondary" arrow onClick={() => navigate("contact")}>
                Book a consultation
              </Btn>
              <button className="nav__burger" aria-label="Menu" onClick={() => setOpen(true)}>
                <span></span>
              </button>
            </div>
          </div>
        </div>
      </nav>

      <div className={`mobile-menu ${open ? "open" : ""}`}>
        <div className="mobile-menu__top">
          <Wordmark />
          <button className="mobile-menu__close" aria-label="Close" onClick={() => setOpen(false)} />
        </div>
        <div className="mobile-menu__links">
          {NAV_LINKS.map((l) => (
            <a key={l.id} href={`#${l.id}`}
               onClick={(e) => { e.preventDefault(); navigate(l.id); setOpen(false); }}>
              <span>{l.label}</span>
              <span className="num">{l.num} ↗</span>
            </a>
          ))}
        </div>
        <div style={{ marginTop: "auto", paddingTop: 24, borderTop: "1px solid var(--line)" }}>
          <Btn variant="primary" arrow onClick={() => { navigate("contact"); setOpen(false); }}>
            Book a consultation
          </Btn>
          <div style={{ marginTop: 24, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--text-muted)" }}>
            pilgrimwright.ai · Massachusetts
          </div>
        </div>
      </div>
    </>
  );
}

/* ---------- Footer ---------- */
function Footer({ navigate }) {
  const [submitted, setSubmitted] = useState(false);
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__cols">
          <div className="footer__brand">
            <div className="display" style={{ fontSize: 40, color: "var(--paper)", maxWidth: 380, lineHeight: 1.1 }}>
              A trusted guide for the journey ahead.
            </div>
            <div style={{ marginTop: 28, color: "rgba(244,237,224,0.6)", fontSize: 14, lineHeight: 1.6, maxWidth: 320 }}>
              Pilgrim Wright is an AI consultancy based in Massachusetts,
              serving non-profits, faith communities, and small businesses
              across New England and beyond.
            </div>
          </div>
          <div className="footer__col">
            <h4>Navigate</h4>
            <ul>
              {NAV_LINKS.map((l) => (
                <li key={l.id}>
                  <a href={`#${l.id}`} onClick={(e) => { e.preventDefault(); navigate(l.id); window.scrollTo(0, 0); }}>
                    {l.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
          <div className="footer__col">
            <h4>Services</h4>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("services"); }}>Readiness Assessment</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("services"); }}>Implementation & Training</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate("services"); }}>Ongoing Advisory</a></li>
            </ul>
          </div>
          <div className="footer__col">
            <h4>Field Notes</h4>
            <div style={{ fontSize: 14, lineHeight: 1.55, color: "rgba(244,237,224,0.65)" }}>
              A monthly letter on practical AI for mission-driven teams. No hype.
            </div>
            {submitted ? (
              <div style={{ marginTop: 14, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent-soft)" }}>
                ✓ Welcome aboard
              </div>
            ) : (
              <form
                className="footer__news"
                onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}
              >
                <input type="email" required placeholder="your@email.com" />
                <button type="submit">Subscribe →</button>
              </form>
            )}
          </div>
        </div>
        <div className="footer__bottom">
          <div>© 2026 Pilgrim Wright LLC · Plymouth, Massachusetts</div>
          <div style={{ display: "flex", gap: 28 }}>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="mailto:hello@pilgrimwright.ai">hello@pilgrimwright.ai</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Service / pillar card ---------- */
function PillarCard({ num, title, body, outcomes, who, onClick, accent }) {
  return (
    <article className={`card lift ${accent ? "card--accent" : ""}`} onClick={onClick}
             style={{ display: "flex", flexDirection: "column", gap: 0, cursor: onClick ? "pointer" : "default" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div className="card__num">{num}</div>
        <CompassMark style={{ color: "var(--accent)" }} />
      </div>
      <h3 className="card__title">{title}</h3>
      <p className="card__body">{body}</p>
      {outcomes && (
        <ul style={{
          marginTop: 24, paddingTop: 18, borderTop: "1px dashed var(--line)",
          listStyle: "none", padding: "18px 0 0", display: "flex", flexDirection: "column", gap: 8,
          fontSize: 14, color: "var(--ink-soft)"
        }}>
          {outcomes.map((o, i) => (
            <li key={i} style={{ display: "flex", gap: 10 }}>
              <span style={{ color: "var(--accent)", fontFamily: "var(--font-mono)", fontSize: 11, paddingTop: 4 }}>
                0{i + 1}
              </span>
              <span>{o}</span>
            </li>
          ))}
        </ul>
      )}
      {who && (
        <div style={{ marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--text-muted)" }}>
          For: {who}
        </div>
      )}
    </article>
  );
}

/* ---------- Testimonial card ---------- */
function Testimonial({ quote, name, role, org, accent }) {
  return (
    <figure className="card" style={{ display: "flex", flexDirection: "column", gap: 24, background: "rgba(255,255,255,0.4)" }}>
      <span className="quote-mark" style={{ color: accent ? "var(--accent)" : "var(--accent)" }}>"</span>
      <blockquote className="quote" style={{ margin: 0 }}>{quote}</blockquote>
      <figcaption style={{ display: "flex", alignItems: "center", gap: 14, marginTop: "auto", paddingTop: 14, borderTop: "1px solid var(--line)" }}>
        <div className="placeholder" style={{ width: 44, height: 44, padding: 0, borderRadius: "50%", fontSize: 9 }}>
          Photo
        </div>
        <div>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 16, color: "var(--ink)" }}>{name}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 4 }}>
            {role} · {org}
          </div>
        </div>
      </figcaption>
    </figure>
  );
}

/* ---------- Page Hero (for non-home pages) ---------- */
function PageHero({ num, kicker, title, lede, children }) {
  return (
    <section className="page-hero">
      <div className="container">
        <div className="page-hero__meta">
          <span className="kicker kicker--muted">{num}</span>
          <span style={{ width: 24, height: 1, background: "var(--line)" }} />
          <span className="kicker">{kicker}</span>
        </div>
        <h1 className="display page-hero__title">{title}</h1>
        {lede && <p className="lede page-hero__lede">{lede}</p>}
        {children}
      </div>
    </section>
  );
}

/* Export everything globally */
Object.assign(window, {
  BrandMark, Wordmark, CompassMark, TopoLines, CompassRose,
  Btn, Reveal, useReveal,
  Nav, Footer,
  PillarCard, Testimonial, PageHero,
  NAV_LINKS,
});
