// Shared components — Nav, Footer, Cards, etc.
const { useState, useEffect, useRef, useMemo } = React;

// ----- Router (hash-based) -----
function useRoute() {
  const [route, setRoute] = useState(() => window.location.hash.slice(1) || "/");
  useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.slice(1) || "/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}
function navigate(to) {
  window.location.hash = to;
}
function Link({ to, children, className = "", style }) {
  return <a href={"#" + to} className={className} style={style} onClick={(e) => { if (e.metaKey || e.ctrlKey) return; }}>{children}</a>;
}

// ----- Wordmark -----
function Wordmark({ small = false }) {
  return (
    <Link to="/" className="wordmark" style={{ fontSize: small ? 20 : 26, textDecoration: "none" }}>
      <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
          <span style={{ fontStyle: "italic" }}>Dutch</span>
          <span style={{ fontSize: "0.65em", color: "var(--wine)", letterSpacing: "0.15em", textTransform: "uppercase", fontFamily: "var(--body)" }}>Art</span>
          <span>Gallery</span>
        </div>
        {!small && <div className="wordmark-sub" style={{ marginTop: 4 }}>Dallas · Since 1965</div>}
      </div>
    </Link>
  );
}

// ----- Nav -----
const NAV_ITEMS = [
  { to: "/gallery", label: "Gallery" },
  { to: "/framing", label: "Framing" },
  { to: "/events", label: "Events" },
  { to: "/about", label: "About" },
  { to: "/visit", label: "Visit" },
];

function UtilityBar() {
  return (
    <div className="utility-bar">
      <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", maxWidth: 1440 }}>
        <div>Dallas · Lake Highlands · Since 1965</div>
        <div style={{ display: "flex", gap: 28 }}>
          <a href="tel:2143487350">(214) 348-7350</a>
          <a href="#/visit">Visit</a>
        </div>
      </div>
    </div>
  );
}

function Navbar() {
  const route = useRoute();
  const [open, setOpen] = useState(false);
  const isActive = (to) => route === to || (to !== "/" && route.startsWith(to));
  return (
    <>
      <UtilityBar />
      <nav className="navbar">
        <div className="navbar-inner">
          <Wordmark small />
          <div className="nav-links">
            {NAV_ITEMS.map((n) => (
              <Link key={n.to} to={n.to} className={"nav-link" + (isActive(n.to) ? " active" : "")}>{n.label}</Link>
            ))}
          </div>
          <button className="mobile-toggle" aria-label="Menu" onClick={() => setOpen(true)}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="17" x2="21" y2="17"/></svg>
          </button>
        </div>
      </nav>
      <div className={"mobile-drawer" + (open ? " open" : "")}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingBottom: 24, borderBottom: "1px solid var(--hairline)" }}>
          <Wordmark small />
          <button onClick={() => setOpen(false)} style={{ background: "transparent", border: 0, fontSize: 28, cursor: "pointer", color: "var(--ink)" }}>×</button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 28, marginTop: 40 }}>
          {NAV_ITEMS.map((n) => (
            <a key={n.to} href={"#" + n.to} onClick={() => setOpen(false)} className="display" style={{ fontSize: 32, textDecoration: "none", fontStyle: "italic" }}>{n.label}</a>
          ))}
          <div style={{ marginTop: 24, paddingTop: 24, borderTop: "1px solid var(--hairline)" }}>
            <a href="tel:2143487350" style={{ textDecoration: "none", color: "var(--wine)", fontSize: 18 }}>(214) 348-7350</a>
            <div className="text-muted" style={{ fontSize: 13, marginTop: 8 }}>10233 Northwest Hwy #420<br/>Dallas, TX 75238</div>
          </div>
        </div>
      </div>
    </>
  );
}

// ----- Footer -----
function Footer() {
  return (
    <footer>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1.2fr", gap: 48 }} className="footer-grid">
          <div>
            <div className="display" style={{ fontSize: 30, color: "#f6efde", marginBottom: 12 }}>
              <em>Dutch</em> Art Gallery
            </div>
            <div style={{ fontSize: 11, letterSpacing: "0.28em", textTransform: "uppercase", color: "#a89c87" }}>Dallas · Since 1965</div>
            <p style={{ fontSize: 14, marginTop: 24, maxWidth: 320, lineHeight: 1.7 }}>
              A family-owned art gallery and custom framing studio in Lake Highlands. Three generations of the Massar family.
            </p>
          </div>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase", color: "#a89c87", marginBottom: 18 }}>Visit</div>
            <div style={{ fontSize: 14, lineHeight: 2 }}>
              <a href="#/gallery">Gallery</a><br/>
              <a href="#/framing">Custom Framing</a><br/>
              <a href="#/events">Events</a><br/>
              <a href="#/about">About</a><br/>
              <a href="#/visit">Visit</a>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase", color: "#a89c87", marginBottom: 18 }}>Contact</div>
            <div style={{ fontSize: 14, lineHeight: 1.9 }}>
              10233 Northwest Hwy<br/>Suite #420<br/>Dallas, TX 75238<br/><br/>
              <a href="tel:2143487350">(214) 348-7350</a><br/>
              <a href="mailto:pam@dutchartgallery.net">pam@dutchartgallery.net</a>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase", color: "#a89c87", marginBottom: 18 }}>Gallery News</div>
            <p style={{ fontSize: 13, lineHeight: 1.6, marginTop: 0, marginBottom: 14, color: "#c8bfae" }}>New art, monthly events, artist spotlights.</p>
            <form onSubmit={(e) => { e.preventDefault(); alert("Thanks — we'll be in touch."); }} style={{ display: "flex", gap: 0, border: "1px solid #3a332a" }}>
              <input type="email" required placeholder="Email address" style={{ background: "transparent", color: "#f6efde", border: 0, fontSize: 13, padding: "12px 14px", flex: 1 }} />
              <button type="submit" style={{ background: "#f6efde", color: "var(--ink)", border: 0, padding: "0 18px", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", cursor: "pointer", fontWeight: 500 }}>Join</button>
            </form>
            <div style={{ marginTop: 24, fontSize: 13 }}>
              <a href="https://www.facebook.com/DutchArtGallery/" target="_blank" rel="noopener">Facebook ↗</a>
            </div>
          </div>
        </div>
        <div style={{ borderTop: "1px solid #3a332a", marginTop: 56, paddingTop: 28, display: "flex", justifyContent: "space-between", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "#807466" }}>
          <div>© 2026 Dutch Art Gallery</div>
          <div>dutchartgallery.net</div>
        </div>
      </div>
    </footer>
  );
}

// ----- Painted artwork tile -----
function ArtCanvas({ seed = 0, ratio = "1 / 1", title, framed = false, src = null }) {
  const style = paintedCanvas(seed);
  return (
    <div style={{ aspectRatio: ratio, ...(framed ? { padding: 14, background: "#f6efde", boxShadow: "0 1px 0 #d6c79e inset, 0 0 0 1px #c9b07a, 0 18px 44px -28px rgba(26,22,18,0.45)" } : {}) }}>
      {src
        ? <img src={src} alt={title || ""} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        : <div className="canvas-placeholder" style={{ width: "100%", height: "100%", ...style }} />
      }
    </div>
  );
}

// ----- Eyebrow -----
function Eyebrow({ children, withRule = true, color }) {
  return (
    <div className={withRule ? "eyebrow-rule eyebrow" : "eyebrow"} style={color ? { color } : {}}>{children}</div>
  );
}

// ----- Stat block -----
function Stat({ value, label }) {
  return (
    <div style={{ textAlign: "left" }}>
      <div className="display" style={{ fontSize: "clamp(48px, 5vw, 72px)", lineHeight: 1, fontWeight: 400 }}>{value}</div>
      <div className="eyebrow" style={{ marginTop: 12 }}>{label}</div>
    </div>
  );
}

// ----- Section heading helper -----
function SectionHead({ eyebrow, title, sub, align = "left" }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === "center" ? 720 : 880, margin: align === "center" ? "0 auto" : 0 }}>
      {eyebrow && <Eyebrow withRule={align !== "center"}>{eyebrow}</Eyebrow>}
      {title && <h2 className="display" style={{ fontSize: "clamp(40px, 5.2vw, 72px)", margin: "20px 0 0", textWrap: "balance" }}>{title}</h2>}
      {sub && <p style={{ marginTop: 18, fontSize: 17, color: "var(--ink-body)", maxWidth: 620, marginLeft: align === "center" ? "auto" : 0, marginRight: align === "center" ? "auto" : 0 }}>{sub}</p>}
    </div>
  );
}

// ----- Fade-up wrapper -----
function FadeUp({ children, delay = 0, as = "div", ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Fallback: ensure content always becomes visible even if IO never fires
    // (hidden iframes, prefetch, throttled tabs, etc.)
    const fallback = setTimeout(() => setSeen(true), 600);
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); clearTimeout(fallback); }
    }, { threshold: 0.05 });
    io.observe(el);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, []);
  const Tag = as;
  return <Tag ref={ref} className={"fade-up" + (seen ? " in" : "")} style={{ transitionDelay: delay + "ms" }} {...rest}>{children}</Tag>;
}

Object.assign(window, { useRoute, navigate, Link, Wordmark, Navbar, Footer, ArtCanvas, Eyebrow, Stat, SectionHead, FadeUp, NAV_ITEMS });
