// Shared chrome: Nav + Footer + tiny SVG illustrations

// ────────────────────────────────────────────
// Simple inline icons / illustrations
// ────────────────────────────────────────────
function WaveGlyph({ style }) {
  return (
    <svg viewBox="0 0 120 32" style={style} aria-hidden="true">
      <path d="M0 16 Q 15 4, 30 16 T 60 16 T 90 16 T 120 16" stroke="currentColor" strokeWidth="1.3" fill="none" />
      <path d="M0 22 Q 15 10, 30 22 T 60 22 T 90 22 T 120 22" stroke="currentColor" strokeWidth="1.3" fill="none" opacity="0.55" />
    </svg>
  );
}

function PyramidGlyph({ style }) {
  return (
    <svg viewBox="0 0 60 40" style={style} aria-hidden="true">
      <path d="M4 38 L30 4 L56 38 Z" stroke="currentColor" strokeWidth="1.2" fill="none" />
      <path d="M14 38 L30 22 L46 38" stroke="currentColor" strokeWidth="1.2" fill="none" />
      <line x1="30" y1="4" x2="30" y2="38" stroke="currentColor" strokeWidth="1.2" />
    </svg>
  );
}

function SunGlyph({ style }) {
  return (
    <svg viewBox="0 0 60 60" style={style} aria-hidden="true">
      <circle cx="30" cy="30" r="10" stroke="currentColor" strokeWidth="1.2" fill="none" />
      {Array.from({ length: 12 }).map((_, i) => {
        const a = (i * Math.PI) / 6;
        const x1 = 30 + Math.cos(a) * 16;
        const y1 = 30 + Math.sin(a) * 16;
        const x2 = 30 + Math.cos(a) * 22;
        const y2 = 30 + Math.sin(a) * 22;
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="currentColor" strokeWidth="1.2" />;
      })}
    </svg>
  );
}

// Placeholder image box (for cases without a photo)
function ImgPlaceholder({ label, style, aspect = "4/5" }) {
  return (
    <div className="img-ph" style={{ aspectRatio: aspect, ...style }}>
      <svg className="img-ph-stripes" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
        <defs>
          <pattern id="stripes" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
            <line x1="0" y1="0" x2="0" y2="8" stroke="currentColor" strokeWidth="0.8" />
          </pattern>
        </defs>
        <rect width="100" height="100" fill="url(#stripes)" />
      </svg>
      <span className="img-ph-label">{label}</span>
    </div>
  );
}

// ────────────────────────────────────────────
// Top navigation
// ────────────────────────────────────────────
function TopNav({ route, setRoute, lang, setLang, t }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const Link = window.__bbRouter.Link;
  const links = [
    { id: "catalog", label: t.nav.experiences },
    { id: "about", label: t.nav.about },
    { id: "journal", label: t.nav.journal },
    { id: "contact", label: t.nav.contact },
  ];

  // Map deep routes back to the nav section they belong to, so "Experiences" stays
  // highlighted while browsing a detail page or checkout, and "Journal" stays highlighted
  // while reading a post.
  const ROUTE_SECTION = {
    catalog: "catalog", detail: "catalog", checkout: "catalog", "checkout-success": "catalog",
    journal: "journal", "journal-post": "journal",
    about: "about",
    contact: "contact",
  };
  const activeSection = ROUTE_SECTION[route];

  return (
    <header className={`topnav ${scrolled ? "scrolled" : ""} ${["home", "detail", "journal-post"].includes(route) ? "on-hero" : ""}`}>
      <div className="topnav-inner">
        <Link route="home" className="brand">
          <span className="brand-word">
            <span className="brand-word-main">
              <span className="brand-bacalar">Bacalar</span>
              <span className="brand-dot">·</span>
              <span className="brand-beyond">Beyond</span>
            </span>
          </span>
        </Link>

        <nav className="topnav-links">
          {links.map((l) => (
            <Link key={l.id} route={l.id} className={activeSection === l.id ? "active" : ""}>
              {l.label}
            </Link>
          ))}
        </nav>

        <div className="topnav-right">
          <div className="lang-toggle" role="group" aria-label="Language">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <span>·</span>
            <button className={lang === "es" ? "on" : ""} onClick={() => setLang("es")}>ES</button>
          </div>
          <CartButton lang={lang} />
          <Link route="catalog" className="btn btn-primary btn-sm">
            {t.nav.book}
            <span className="btn-arrow">→</span>
          </Link>
        </div>
      </div>
    </header>
  );
}

// ────────────────────────────────────────────
// Footer
// ────────────────────────────────────────────
function Footer({ lang, t, setRoute }) {
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const Link = window.__bbRouter.Link;
  return (
    <footer className="site-footer">
      <div className="site-footer-top">
        <div className="site-footer-brand">
          <Link route="home" className="footer-wordmark">
            <span>Bacalar</span>
            <em>Beyond</em>
          </Link>
          <p className="footer-tag">{t.footer.tagline}</p>
        </div>

        <div className="site-footer-cols">
          <div>
            <h5>{t.footer.cols.visit}</h5>
            <p>{t.footer.office}</p>
            <p>{t.footer.hours}</p>
          </div>
          <div>
            <h5>{t.footer.cols.journeys}</h5>
            <Link route="catalog">{t.footer.links.water}</Link>
            <Link route="catalog">{t.footer.links.ruins}</Link>
            <Link route="catalog">{t.footer.links.biosphere}</Link>
            <Link route="catalog">{t.footer.links.private}</Link>
          </div>
          <div>
            <h5>{t.footer.cols.house}</h5>
            <Link route="about">{t.nav.about}</Link>
            <Link route="contact">{t.footer.links.contact}</Link>
            <Link route="journal">{t.footer.links.journal}</Link>
          </div>
          <div className="footer-news">
            <h5>{t.footer.newsletter}</h5>
            {sent ? (
              <p className="sent">{t.footer.links.sent}</p>
            ) : (
              <form onSubmit={(e) => { e.preventDefault(); if (email) setSent(true); }}>
                <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder={t.footer.placeholder} />
                <button type="submit">{t.footer.subscribe}</button>
              </form>
            )}
          </div>
        </div>
      </div>

      <div className="site-footer-bottom">
        <WaveGlyph style={{ width: 60, height: 16, color: "var(--sand)", opacity: 0.6 }} />
        <span>{t.footer.rights}</span>
        <span className="mono">21.01° N · 88.39° W</span>
      </div>
    </footer>
  );
}

// ────────────────────────────────────────────
// Cart icon button — reads live count from the cart store, pulses on add
// ────────────────────────────────────────────
function CartButton({ lang }) {
  const cart = window.__bbCart.useCart();
  const count = cart.rowCount;
  const prevRef = React.useRef(count);
  const [bump, setBump] = React.useState(false);

  React.useEffect(() => {
    if (count > prevRef.current) {
      setBump(true);
      const t = setTimeout(() => setBump(false), 500);
      return () => clearTimeout(t);
    }
    prevRef.current = count;
  }, [count]);

  return (
    <button
      type="button"
      className={`cart-btn ${bump ? "cart-btn-bump" : ""}`}
      onClick={() => cart.openDrawer()}
      aria-label={`${window.COPY[lang].cart.eyebrow}, ${count}`}
    >
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M4 7h16l-1.3 12.2a2 2 0 0 1-2 1.8H7.3a2 2 0 0 1-2-1.8L4 7z" />
        <path d="M8 7V5.5A3.5 3.5 0 0 1 11.5 2h1A3.5 3.5 0 0 1 16 5.5V7" />
      </svg>
      {count > 0 && <span className="cart-btn-badge">{count}</span>}
    </button>
  );
}

Object.assign(window, { TopNav, Footer, CartButton, WaveGlyph, PyramidGlyph, SunGlyph, ImgPlaceholder });
