// ui.jsx — shared components for Melinda's
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ===== Router =====
function useHashRoute() {
  const [hash, setHash] = useState(() => window.location.hash.slice(1) || "/");
  useEffect(() => {
    const fn = () => { setHash(window.location.hash.slice(1) || "/"); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", fn);
    return () => window.removeEventListener("hashchange", fn);
  }, []);
  return hash;
}
function Link({ to, children, className, onClick, ...rest }) {
  return <a href={`#${to}`} className={className} onClick={onClick} {...rest}>{children}</a>;
}

// ===== Reveal on scroll =====
function Reveal({ children, delay = 0, as = "div", className = "", style = {} }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.15 });
    io.observe(el);
    const fallback = setTimeout(() => {
      if (!el) return;
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight && r.bottom > 0) setShown(true);
    }, 600);
    return () => { clearTimeout(fallback); io.disconnect(); };
  }, []);
  const Tag = as;
  return <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} style={{ ...style, transitionDelay: `${delay}ms` }}>{children}</Tag>;
}

// ===== Logo =====
function Logo({ light = false, size = 36 }) {
  return (
    <Link to="/" className="logo" style={{ display: "inline-flex", alignItems: "center", gap: 12, textDecoration: "none" }}>
      <img
        src="https://img1.wsimg.com/isteam/ip/48f62440-1494-4dda-af46-2c1f8533c26b/Just%20Logo%20transparent%20untensil%20fill.png"
        alt=""
        style={{ height: 56, display: "block", objectFit: "contain", flexShrink: 0 }}
      />
      <img
        src="https://img1.wsimg.com/isteam/ip/48f62440-1494-4dda-af46-2c1f8533c26b/blob-81b36a5.png/:/rs=h:320,cg:true,m/qt=q:95"
        alt="Melinda's Gluten Free"
        style={{ height: 56, display: "block", objectFit: "contain", flexShrink: 0 }}
      />
    </Link>
  );
}

// ===== Navbar =====
const NAV_GROUPS = [
  { label: "Menus", to: "/menu", children: [
    { label: "All Menus", to: "/menu" },
    { label: "Bakery Case", to: "/menu/case" },
    { label: "Vegan Menu", to: "/menu/vegan" },
  ]},
  { label: "Orders", to: "/order", children: [
    { label: "Special Orders", to: "/order" },
    { label: "Wedding Cakes", to: "/weddings" },
  ]},
  { label: "About", to: "/about", children: [
    { label: "About Us", to: "/about" },
    { label: "FAQs", to: "/faqs" },
    { label: "Contact Us", to: "/contact" },
  ]},
  { label: "More", to: "/take-and-bake", children: [
    { label: "How to Take & Bake", to: "/take-and-bake" },
    { label: "Recipes you'll love", to: "/recipes" },
    { label: "Gallery", to: "/gallery" },
  ]},
];

function NavDropdown({ group, light = false }) {
  const [open, setOpen] = useState(false);
  const closeTimer = useRef(null);
  const openIt = () => { clearTimeout(closeTimer.current); setOpen(true); };
  const closeIt = () => { closeTimer.current = setTimeout(() => setOpen(false), 120); };
  const baseColor = light ? "rgba(253,248,240,0.85)" : "var(--color-stone)";
  const hoverColor = light ? "var(--color-cream)" : "var(--color-espresso)";
  return (
    <div
      onMouseEnter={openIt}
      onMouseLeave={closeIt}
      onFocus={openIt}
      onBlur={closeIt}
      style={{ position: "relative" }}
    >
      <Link to={group.to}
        style={{
          fontSize: 14, fontWeight: 500, color: open ? hoverColor : baseColor,
          transition: "color 200ms", display: "inline-flex", alignItems: "center", gap: 4
        }}>
        {group.label}
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"
          style={{ transform: open ? "rotate(180deg)" : "rotate(0)", transition: "transform 200ms", opacity: 0.55 }}>
          <path d="M2.5 4 L5 6.5 L7.5 4"/>
        </svg>
      </Link>
      <div style={{
        position: "absolute", top: "100%", left: -14, marginTop: 8, minWidth: 220,
        background: "var(--color-white-warm)",
        border: "1px solid var(--color-border)",
        borderRadius: 16,
        boxShadow: "var(--shadow-float)",
        padding: 8,
        opacity: open ? 1 : 0,
        transform: open ? "translateY(0)" : "translateY(-4px)",
        pointerEvents: open ? "auto" : "none",
        transition: "opacity 180ms var(--ease-out-expo), transform 180ms var(--ease-out-expo)"
      }}>
        {group.children.map((c) => (
          <Link key={c.to} to={c.to}
            style={{
              display: "block", padding: "10px 14px", borderRadius: 10,
              fontSize: 14, fontWeight: 500, color: "var(--color-espresso)",
              transition: "background 160ms"
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--color-honey-light)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >{c.label}</Link>
        ))}
      </div>
    </div>
  );
}

function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [openGroup, setOpenGroup] = useState(null);
  const route = useHashRoute();
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 60);
    fn(); window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  // Hero is dark teal on home + weddings callout; when at top of those pages, nav goes light.
  const onDarkHero = route === "/" && !scrolled;
  return (
    <>
      <nav style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
        background: scrolled ? "rgba(253,248,240,0.92)" : "transparent",
        backdropFilter: scrolled ? "blur(20px)" : "none",
        borderBottom: scrolled ? "1px solid var(--color-border)" : "1px solid transparent",
        transition: "all 300ms var(--ease-out-expo)"
      }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 72 }}>
          <Logo light={onDarkHero}/>
          <div className="nav-links" style={{ display: "flex", gap: 26, alignItems: "center" }}>
            {NAV_GROUPS.map((g) => <NavDropdown key={g.label} group={g} light={onDarkHero}/>) }
            <Link to="/menu" className={`btn btn-sm ${onDarkHero ? "btn-cream-solid" : "btn-primary"}`}>See the menu →</Link>
          </div>
          <button className="nav-burger" onClick={() => setOpen(true)} aria-label="Open menu"
            style={{ color: onDarkHero ? "var(--color-cream)" : "var(--color-espresso)" }}>
            <svg width="22" height="22" viewBox="0 0 22 22" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round">
              <path d="M3 6h16M3 11h16M3 16h16"/>
            </svg>
          </button>
        </div>
      </nav>

      {open && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 100, background: "var(--color-cream)",
          padding: 24, display: "flex", flexDirection: "column", animation: "fadeIn 250ms ease-out",
          overflowY: "auto"
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Logo />
            <button onClick={() => setOpen(false)} aria-label="Close menu" style={{ padding: 8 }}>
              <svg width="22" height="22" viewBox="0 0 22 22" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round">
                <path d="M5 5l12 12M17 5L5 17"/>
              </svg>
            </button>
          </div>
          <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-start", gap: 4, paddingTop: 32, paddingBottom: 80 }}>
            {NAV_GROUPS.map((g) => {
              const isOpenG = openGroup === g.label;
              return (
                <div key={g.label} style={{ borderBottom: "1px solid var(--color-border)" }}>
                  <button onClick={() => setOpenGroup(isOpenG ? null : g.label)} style={{
                    display: "flex", justifyContent: "space-between", alignItems: "center", width: "100%",
                    fontFamily: "var(--display)", fontSize: 32, fontWeight: 500, color: "var(--color-espresso)",
                    padding: "14px 0", textAlign: "left"
                  }}>
                    <span>{g.label}</span>
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"
                      style={{ transform: isOpenG ? "rotate(180deg)" : "rotate(0)", transition: "transform 220ms" }}>
                      <path d="M4 7 L9 12 L14 7"/>
                    </svg>
                  </button>
                  <div style={{
                    display: "grid",
                    gridTemplateRows: isOpenG ? "1fr" : "0fr",
                    transition: "grid-template-rows 280ms var(--ease-out-expo)"
                  }}>
                    <div style={{ overflow: "hidden" }}>
                      <div style={{ display: "flex", flexDirection: "column", gap: 2, paddingBottom: 14, paddingLeft: 4 }}>
                        {g.children.map((c) => (
                          <Link key={c.to} to={c.to} onClick={() => setOpen(false)} style={{
                            fontFamily: "var(--body)", fontSize: 17, color: "var(--color-cocoa)", padding: "8px 0"
                          }}>{c.label}</Link>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
            <Link to="/menu" onClick={() => setOpen(false)} className="btn btn-primary" style={{ marginTop: 32, alignSelf: "flex-start", padding: "16px 28px", fontSize: 16 }}>
              See the menu →
            </Link>
          </div>
        </div>
      )}
      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        .nav-burger { display: none; padding: 8px; color: var(--color-espresso); }
        @media (max-width: 1024px) {
          .nav-links { display: none !important; }
          .nav-burger { display: block !important; }
        }
      `}</style>
    </>
  );
}

// ===== Footer =====
function Footer() {
  return (
    <footer style={{ background: "var(--color-espresso)", color: "rgba(253,248,240,0.7)", paddingTop: 80, paddingBottom: 40 }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 48, marginBottom: 64 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
              <img
                src="https://img1.wsimg.com/isteam/ip/48f62440-1494-4dda-af46-2c1f8533c26b/Just%20Logo%20transparent%20untensil%20fill.png"
                alt=""
                style={{ display: "block", height: 72, objectFit: "contain", flexShrink: 0 }}
              />
              <img
                src="https://img1.wsimg.com/isteam/ip/48f62440-1494-4dda-af46-2c1f8533c26b/blob-81b36a5.png/:/rs=h:320,cg:true,m/qt=q:95"
                alt="Melinda's Gluten Free"
                style={{ display: "block", height: 72, objectFit: "contain", flexShrink: 0 }}
              />
            </div>
            <p style={{ fontFamily: "var(--display)", fontStyle: "italic", fontSize: 16, color: "rgba(253,248,240,0.6)", maxWidth: 220 }}>Your friend when gluten isn't.</p>
          </div>
          <div>
            <div className="section-label" style={{ color: "var(--color-honey)", marginBottom: 14 }}>Hours</div>
            <div style={{ fontSize: 14, lineHeight: 1.8 }}>
              <div>Tue–Sun · 8am–3pm</div>
              <div>Closed Mondays</div>
              <div style={{ marginTop: 8, color: "rgba(253,248,240,0.45)" }}>Closed Dec 24 – Jan 1</div>
            </div>
          </div>
          <div>
            <div className="section-label" style={{ color: "var(--color-honey)", marginBottom: 14 }}>Visit</div>
            <div style={{ fontSize: 14, lineHeight: 1.8 }}>
              <div>1420 41st Avenue</div>
              <div>Capitola, CA 95010</div>
              <a href="tel:8313165081" style={{ color: "var(--color-honey)", display: "inline-block", marginTop: 8, fontWeight: 600 }}>(831) 316-5081</a>
            </div>
          </div>
          <div>
            <div className="section-label" style={{ color: "var(--color-honey)", marginBottom: 14 }}>Explore</div>
            <div style={{ fontSize: 14, lineHeight: 2 }}>
              <Link to="/menu" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Menu</Link>
              <Link to="/order" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Special Orders</Link>
              <Link to="/weddings" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Wedding Cakes</Link>
              <Link to="/about" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>About</Link>
              <Link to="/faqs" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>FAQs</Link>
              <Link to="/take-and-bake" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Take & Bake</Link>
              <Link to="/recipes" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Recipes</Link>
              <Link to="/gallery" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Gallery</Link>
              <Link to="/contact" style={{ display: "block", color: "rgba(253,248,240,0.7)" }}>Contact</Link>
            </div>
          </div>
          <div>
            <div className="section-label" style={{ color: "var(--color-honey)", marginBottom: 14 }}>Follow</div>
            <div style={{ display: "flex", gap: 12 }}>
              <a href="#" aria-label="Instagram" style={{ width: 38, height: 38, borderRadius: 999, border: "1px solid rgba(253,248,240,0.18)", display: "grid", placeItems: "center", color: "var(--color-cream)" }}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="2" width="12" height="12" rx="3"/><circle cx="8" cy="8" r="2.5"/><circle cx="11.5" cy="4.5" r=".5" fill="currentColor"/></svg>
              </a>
              <a href="#" aria-label="Facebook" style={{ width: 38, height: 38, borderRadius: 999, border: "1px solid rgba(253,248,240,0.18)", display: "grid", placeItems: "center", color: "var(--color-cream)" }}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M10 5h-1.5a1 1 0 0 0-1 1V8H6v2h1.5v4h2v-4H11l.5-2H9.5V6.5a.5.5 0 0 1 .5-.5h1V4z"/></svg>
              </a>
            </div>
            <div style={{ marginTop: 14, fontSize: 13 }}>
              <a href="mailto:melindasgf@gmail.com" style={{ color: "var(--color-honey)" }}>melindasgf@gmail.com</a>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 16, flexWrap: "wrap", paddingTop: 28, borderTop: "1px solid rgba(255,255,255,0.08)", fontSize: 12, color: "rgba(253,248,240,0.4)" }}>
          <div>© 2026 Melinda's Gluten-Free Bakery · All rights reserved</div>
          <div>Baked from scratch in Capitola, CA</div>
        </div>
      </div>
    </footer>
  );
}

// ===== Mobile Order Bar =====
function MobileOrderBar({ hide = false }) {
  if (hide) return null;
  return (
    <div className="mobile-order-bar">
      <Link to="/menu" className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 20px" }}>
        See the menu →
      </Link>
    </div>
  );
}

Object.assign(window, { useHashRoute, Link, Reveal, Logo, Navbar, Footer, MobileOrderBar });
