/* Router + Megamenu NavBar + Sub-nav + Breadcrumbs */

// Hash-based router
function useRoute() {
  const parse = () => {
    const h = (window.location.hash || "#/").replace(/^#/, "");
    const parts = h.split("/").filter(Boolean);
    return { path: "/" + parts.join("/"), parts };
  };
  const [route, setRoute] = React.useState(parse());
  React.useEffect(() => {
    const onHash = () => {
      setRoute(parse());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const go = (path) => { window.location.hash = path.startsWith("#") ? path : "#" + path; };
  return { route, go };
}

function L({ to, children, style, className }) {
  return <a href={"#" + to} style={{ color: "inherit", textDecoration: "none", ...style }} className={className}>{children}</a>;
}

// Resolve the signed-in user's role from `profiles`. Mirrors the exact pattern
// used by the platform admin gate (admin/admin-shell.jsx) and the maker
// dashboard guard (maker-admin.jsx): useAuth() exposes only the session, never
// the role, so the role lives in the profiles table and is fetched once here.
// Returns "" while loading / for guests so callers can gate UI safely.
function useRole() {
  const { user, loading } = useAuth();
  const [role, setRole] = React.useState("");
  React.useEffect(() => {
    if (loading) return;
    if (!user) { setRole(""); return; }
    let cancelled = false;
    window.sb.from("profiles").select("role").eq("id", user.id).single()
      .then(({ data, error }) => {
        if (cancelled) return;
        setRole(error ? "" : (data?.role || ""));
      })
      .catch(() => { if (!cancelled) setRole(""); });
    return () => { cancelled = true; };
  }, [user, loading]);
  return role;
}

// Top announcement bar
function TopBar({ t, lang, setLang }) {
  // B3 — route-scoped suppression. The maker dashboard (#/makers/admin) is a
  // seller workspace; the marketing strip ("Sham El-Nessim … 6 pieces
  // remaining") doesn't belong there. TopBar is mounted without a route prop,
  // so derive the active path from the hash and keep it in sync.
  const [hashPath, setHashPath] = React.useState(() => window.location.hash || "");
  React.useEffect(() => {
    const onHash = () => setHashPath(window.location.hash || "");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const isMakerDash = /^#\/makers\/admin\b/.test(hashPath);
  if (isMakerDash) return null;

  return (
    <div className="topbar">
      <span className="topbar-left">
        <Star8 size={10} color="var(--gold-soft)" />
        <span style={{ color: "var(--gold-soft)" }}>{lang === "en" ? "Spring · 2026" : "ربيع ٢٠٢٦"}</span>
        <span className="topbar-hide-sm" style={{ opacity: 0.45 }}>·</span>
        <span className="topbar-msg topbar-hide-sm">{lang === "en" ? "Sham El-Nessim collection live · 6 pieces remaining" : "مجموعة شمّ النسيم متاحة · ٦ قطع متبقّية"}</span>
      </span>
      <span className="topbar-right">
        <span className="topbar-hide-md" style={{ opacity: 0.6 }}>EGP · USD · AED</span>
        <span className="topbar-hide-md" style={{ opacity: 0.3 }}>·</span>
        {/* Account link — routes to the account orders tab where each order
            now opens a tracking view inline. No more floating "Track order"
            CTA that pretended to be standalone. */}
        <a className="topbar-hide-md" href="#/account" style={{ color: "inherit", textDecoration: "none", opacity: 0.7 }}>
          {lang === "en" ? "Your orders" : "طلباتك"}
        </a>
        <span className="topbar-hide-md" style={{ opacity: 0.3 }}>·</span>
        <button onClick={() => setLang(lang === "en" ? "ar" : "en")}
          aria-label={lang === "en" ? "Switch to Arabic" : "Switch to English"}
          style={{
          background: "transparent", border: "1px solid rgba(255,255,255,0.3)",
          color: "var(--paper)", padding: "8px 14px", borderRadius: 999,
          fontFamily: "inherit", fontSize: 10, letterSpacing: "0.18em",
          textTransform: "uppercase", cursor: "pointer",
          minHeight: 32, lineHeight: 1,
        }}>{lang === "en" ? "عربي" : "English"}</button>
      </span>
    </div>
  );
}

// Megamenu panels
const MEGA = {
  shop: [
    {
      h: "By house", items: [
        { n: "Macramé", ar: "مكرمية", to: "/shop/macrame", c: 14 },
        { n: "Candle & Scent", ar: "شموع", to: "/shop/candles", c: 18 },
        { n: "Resin & Stone", ar: "راتنج", to: "/shop/resin", c: 11 },
        { n: "Fired Earth", ar: "فخار", to: "/shop/ceramics", c: 5 },
      ],
    },
    {
      h: "Discover", items: [
        { n: "All pieces", ar: "كل القطع", to: "/shop", c: 48 },
        { n: "Gift guides", ar: "أدلّة الهدايا", to: "/gifts" },
      ],
    },
    {
      featured: true,
      h: "Piece of the month",
      title: "Oasis Knot",
      ar: "عقدة الواحة",
      price: "1,240 EGP",
      tone: "terracotta",
      to: "/shop/macrame/oasis-knot",
    },
  ],
  makers: [
    {
      h: "The house", items: [
        { n: "All 12 makers", ar: "كل الصنّاع", to: "/makers" },
        { n: "Maker dashboard", ar: "لوحة الصانع", to: "/makers/admin" },
      ],
    },
    {
      h: "Join us", items: [
        { n: "Apply as a maker", ar: "قدّم كصانع", to: "/makers/apply" },
      ],
    },
    {
      featured: true,
      h: "Spotlight",
      title: "Nour Ibrahim",
      ar: "نور إبراهيم",
      price: "Macramé · Cairo",
      tone: "sand",
      to: "/makers/nour-ibrahim",
    },
  ],
  atelier: [
    {
      h: "The house", items: [
        { n: "Our story", ar: "قصّتنا", to: "/atelier" },
        { n: "The six-step process", ar: "العمليّة", to: "/atelier/process" },
      ],
    },
    {
      h: "Visit", items: [
        { n: "Book a visit", ar: "احجز زيارة", to: "/atelier/visit" },
        { n: "Workshops", ar: "ورش", to: "/atelier/workshops" },
      ],
    },
    {
      featured: true,
      h: "Behind the door",
      title: "A small room above the river",
      ar: "غرفةٌ فوق النهر",
      price: "Zamalek · Cairo",
      tone: "olive",
      to: "/atelier/visit",
    },
  ],
  journal: [
    {
      h: "Read", items: [
        { n: "All entries", ar: "كل المقالات", to: "/journal" },
      ],
    },
    {
      h: "Subscribe", items: [
        { n: "Monthly letter", ar: "الرسالة الشهريّة", to: "/journal/letter" },
      ],
    },
    {
      featured: true,
      h: "Latest",
      title: "Three days in Fustat",
      ar: "ثلاثة أيّام في الفسطاط",
      price: "6 min · Apr 2026",
      tone: "terracotta",
      to: "/journal/fustat-kilns",
    },
  ],
};

function MegaPanel({ data, lang, onClose }) {
  const featured = data.find(d => d.featured);
  const cols = data.filter(d => !d.featured);
  return (
    <div style={{
      position: "absolute", top: "100%", left: 0, right: 0,
      background: "var(--paper)", borderTop: "1px solid var(--line-2)",
      borderBottom: "1px solid var(--line-2)",
      boxShadow: "0 24px 40px -20px rgba(28,26,21,0.18)",
      zIndex: 50,
    }}>
      <div className="container-wide" style={{ padding: "40px", display: "grid", gridTemplateColumns: `repeat(${cols.length}, 1fr) 1.3fr`, gap: 48 }}>
        {cols.map((c, i) => (
          <div key={i}>
            <div style={{
              fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em",
              textTransform: "uppercase", color: "var(--muted)", marginBottom: 20,
              paddingBottom: 12, borderBottom: "1px solid var(--line-2)",
            }}>{c.h}</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
              {c.items.map((it, j) => (
                <li key={j}>
                  <a href={"#" + it.to} onClick={onClose} style={{
                    display: "flex", justifyContent: "space-between", alignItems: "baseline",
                    textDecoration: "none", color: "var(--ink)", gap: 12,
                  }}>
                    <span>
                      <span style={{ fontFamily: "var(--ff-display)", fontSize: 22, letterSpacing: "-0.01em" }}>{lang === "en" ? it.n : it.ar}</span>
                      <span className="ar" style={{ fontSize: 14, color: "var(--muted)", marginLeft: 10 }}>{lang === "en" ? it.ar : it.n}</span>
                    </span>
                    {it.c != null && (
                      <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)" }}>({it.c})</span>
                    )}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        ))}
        {featured && (
          <a href={"#" + featured.to} onClick={onClose} style={{ textDecoration: "none", color: "inherit" }}>
            <div style={{
              fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em",
              textTransform: "uppercase", color: "var(--muted)", marginBottom: 20,
              paddingBottom: 12, borderBottom: "1px solid var(--line-2)",
            }}>{featured.h}</div>
            <div style={{ aspectRatio: "1.4", borderRadius: "12px", overflow: "hidden", marginBottom: 16 }}>
              <Placeholder tone={featured.tone} label={featured.title.toLowerCase()} meta={featured.price} topLabel="featured" />
            </div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 26 }}>{featured.title}</div>
              <div className="ar" style={{ fontSize: 16, color: "var(--terracotta)" }}>{featured.ar}</div>
            </div>
            <div style={{ marginTop: 6, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
              {featured.price} · {lang === "en" ? "See piece" : "القطعة"} →
            </div>
          </a>
        )}
      </div>
    </div>
  );
}

function MainNav({ t, lang, cart, setCartOpen, route }) {
  const [openMenu, setOpenMenu] = React.useState(null);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const role = useRole();
  const isAdmin = role === "admin" || role === "superadmin";
  // B3 — the maker dashboard (#/makers/admin) is a seller workspace, not the
  // storefront. Suppress the shopping-bag affordance there. (The platform
  // admin console at #/admin already takes over the whole page upstream.)
  const isMakerDash = route.parts && route.parts[0] === "makers" && route.parts[1] === "admin";
  const navItems = [
    { k: "shop", en: "Shop", ar: "المتجر", base: "/shop" },
    { k: "makers", en: "Makers", ar: "الصنّاع", base: "/makers" },
    { k: "atelier", en: "Atelier", ar: "المحترف", base: "/atelier" },
    { k: "journal", en: "Journal", ar: "اليوميّات", base: "/journal" },
    { k: "gifts", en: "Gifts", ar: "الهدايا", base: "/gifts" },
  ];

  // Close drawer on route change
  React.useEffect(() => {
    setDrawerOpen(false);
  }, [route.path]);

  // B3/B4 — tag <body> while on the maker dashboard so route-scoped CSS can
  // strip the marketing spacing assumptions and give dashboard content a
  // scroll offset clear of the sticky public header (no occluded revenue).
  React.useEffect(() => {
    document.body.classList.toggle("maker-dash", isMakerDash);
    return () => document.body.classList.remove("maker-dash");
  }, [isMakerDash]);

  // Lock body scroll + listen for ESC while drawer is open
  React.useEffect(() => {
    if (!drawerOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setDrawerOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [drawerOpen]);

  return (
    <>
      <header className="mainnav" onMouseLeave={() => setOpenMenu(null)}>
        <div className="mainnav-row">
          {/* Burger (mobile only via CSS) */}
          <button
            className="nav-burger"
            aria-label={lang === "en" ? "Open menu" : "افتح القائمة"}
            aria-expanded={drawerOpen}
            onClick={() => setDrawerOpen(true)}
          >
            <svg viewBox="0 0 18 12" fill="none" stroke="currentColor" strokeWidth="1.5">
              <line x1="0" y1="1.5" x2="18" y2="1.5" />
              <line x1="0" y1="6"   x2="18" y2="6"   />
              <line x1="0" y1="10.5" x2="18" y2="10.5" />
            </svg>
            <span className="hide-sm">{lang === "en" ? "Menu" : "القائمة"}</span>
          </button>

          <nav className="mainnav-links">
            {navItems.slice(0, 4).map(it => {
              const isActive = route.path.startsWith(it.base);
              return (
                <div key={it.k} onMouseEnter={() => setOpenMenu(it.k)} style={{ position: "relative", padding: "10px 0" }}>
                  <a href={"#" + it.base} style={{
                    color: "var(--ink)", textDecoration: "none",
                    fontWeight: isActive ? 500 : 400,
                    borderBottom: isActive ? "1px solid var(--terracotta)" : "1px solid transparent",
                    paddingBottom: 4,
                    display: "inline-flex", alignItems: "center", gap: 6,
                  }}>
                    {lang === "en" ? it.en : it.ar}
                    <span style={{ fontSize: 8, opacity: 0.5 }}>▾</span>
                  </a>
                </div>
              );
            })}
            <a href="#/gifts" style={{ color: "var(--ink)", textDecoration: "none", padding: "10px 0" }}>
              {lang === "en" ? "Gifts" : "الهدايا"}
            </a>
          </nav>

          <a href="#/" style={{ textDecoration: "none", justifySelf: "center" }} aria-label="SANAA home"><Wordmark size={28} /></a>

          <div className="mainnav-actions">
            <a className="mainnav-actions-secondary" href="#/help" style={{ color: "var(--ink)", textDecoration: "none" }}>{lang === "en" ? "Help" : "مساعدة"}</a>
            <span className="mainnav-actions-secondary" style={{ color: "var(--line)" }}>|</span>
            <button className="mainnav-actions-secondary" style={iconBtn} aria-label="search">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                <circle cx="11" cy="11" r="7" /><path d="M20 20l-3.5-3.5" />
              </svg>
            </button>
            <a href="#/account" style={iconBtn} aria-label="account">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                <circle cx="12" cy="8" r="4" /><path d="M4 21c0-4 3.6-7 8-7s8 3 8 7" />
              </svg>
            </a>
            {/* B2 — Admin link is for staff only. Render it solely when the
                signed-in user's role is admin/superadmin; guests, customers and
                makers never see it. (Makers reach their dashboard via account.) */}
            {isAdmin && (
              <a className="mainnav-actions-secondary" href="#/admin" style={{
                ...iconBtn, padding: "5px 11px", fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase",
                background: "var(--ink)", color: "var(--paper)", borderRadius: 999, fontWeight: 600,
              }} aria-label="admin">{lang === "en" ? "Admin" : "الإدارة"}</a>
            )}
            {/* B3 — no shopping bag on the maker dashboard. */}
            {!isMakerDash && (
              <button onClick={() => setCartOpen(true)} style={{ ...iconBtn, gap: 8 }} aria-label={lang === "en" ? "Open bag" : "افتح الحقيبة"}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                  <path d="M6 8h12l-1 12H7L6 8Z" /><path d="M9 8a3 3 0 1 1 6 0" />
                </svg>
                <span className="hide-sm">{lang === "en" ? "Bag" : "الحقيبة"} </span>
                <span style={{ color: "var(--terracotta)" }}>({cart})</span>
              </button>
            )}
          </div>

          {openMenu && MEGA[openMenu] && (
            <div className="megapanel">
              <MegaPanel data={MEGA[openMenu]} lang={lang} onClose={() => setOpenMenu(null)} />
            </div>
          )}
        </div>
      </header>

      {/* Mobile drawer — visible at <=980px */}
      <div className={"nav-drawer-overlay " + (drawerOpen ? "open" : "")} onClick={() => setDrawerOpen(false)} aria-hidden={!drawerOpen} />
      <aside className={"nav-drawer " + (drawerOpen ? "open" : "")} aria-label={lang === "en" ? "Site menu" : "قائمة الموقع"} aria-hidden={!drawerOpen}>
        <div className="nav-drawer-head">
          <Wordmark size={22} />
          <button onClick={() => setDrawerOpen(false)} aria-label={lang === "en" ? "Close menu" : "إغلاق"} style={{ background: "transparent", border: 0, fontSize: 26, cursor: "pointer", color: "var(--ink)", lineHeight: 1, minWidth: 44, minHeight: 44, display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 0 }}>×</button>
        </div>
        <div className="nav-drawer-section">{lang === "en" ? "Browse" : "تصفّح"}</div>
        <div className="nav-drawer-list">
          {navItems.map(it => {
            const isActive = route.path.startsWith(it.base);
            return (
              <a key={it.k} href={"#" + it.base} className={"nav-drawer-item" + (isActive ? " active" : "")}>
                <span>{lang === "en" ? it.en : it.ar}</span>
                <span className="ar">{lang === "en" ? it.ar : it.en}</span>
              </a>
            );
          })}
        </div>
        <div className="nav-drawer-section">{lang === "en" ? "Account" : "الحساب"}</div>
        <div className="nav-drawer-list">
          <a href="#/account" className="nav-drawer-item">
            <span>{lang === "en" ? "Sign in" : "تسجيل الدخول"}</span>
          </a>
          <a href="#/help" className="nav-drawer-item">
            <span>{lang === "en" ? "Help" : "مساعدة"}</span>
          </a>
          {/* B2 — staff-only Admin link, role-gated. */}
          {isAdmin && (
            <a href="#/admin" className="nav-drawer-item">
              <span>{lang === "en" ? "Admin" : "الإدارة"}</span>
            </a>
          )}
        </div>
        {/* B3 — no shopping bag on the maker dashboard. */}
        {!isMakerDash && (
          <div className="nav-drawer-foot">
            <button onClick={() => setCartOpen(true)} className="btn ghost" style={{ flex: 1, justifyContent: "center" }}>
              {lang === "en" ? `Bag (${cart})` : `الحقيبة (${cart})`}
            </button>
          </div>
        )}
      </aside>
    </>
  );
}
// 44×44 hit area for primary nav controls (WCAG 2.5.5 AAA). Padding sits
// behind the icon — visible chrome unchanged.
const iconBtn = { background: "transparent", border: 0, padding: 8, color: "var(--ink)", cursor: "pointer", display: "inline-flex", alignItems: "center", minWidth: 44, minHeight: 44, justifyContent: "center" };

// Breadcrumbs
function Breadcrumbs({ crumbs, lang }) {
  return (
    <div style={{
      padding: "18px 0",
      borderBottom: "1px solid var(--line-2)",
      background: "var(--paper)",
    }}>
      <div className="container-wide" style={{ display: "flex", gap: 12, alignItems: "center", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
        <a href="#/" style={{ color: "inherit", textDecoration: "none" }}>{lang === "en" ? "Home" : "الرئيسيّة"}</a>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <span>/</span>
            {c.to ? <a href={"#" + c.to} style={{ color: "inherit", textDecoration: "none" }}>{c.label}</a>
                  : <span style={{ color: "var(--ink)" }}>{c.label}</span>}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// Secondary in-page sub-nav (tab strip)
function SubNav({ tabs, activeKey, onChange }) {
  return (
    <div style={{ background: "var(--paper-2)", borderBottom: "1px solid var(--line-2)", position: "sticky", top: 65, zIndex: 30 }}>
      <div className="container-wide" style={{ display: "flex", gap: 0, overflowX: "auto", scrollbarWidth: "none" }}>
        {tabs.map(tab => (
          <button key={tab.k} onClick={() => (onChange ? onChange(tab.k) : (window.location.hash = tab.to))} style={{
            background: "transparent", border: 0, cursor: "pointer",
            padding: "18px 22px",
            fontFamily: "var(--ff-sans)", fontSize: 13,
            color: activeKey === tab.k ? "var(--ink)" : "var(--muted)",
            fontWeight: activeKey === tab.k ? 500 : 400,
            borderBottom: activeKey === tab.k ? "2px solid var(--terracotta)" : "2px solid transparent",
            whiteSpace: "nowrap",
          }}>
            {tab.label}{tab.count != null && <span style={{ marginLeft: 8, fontFamily: "var(--ff-mono)", fontSize: 10, color: "var(--muted)" }}>({tab.count})</span>}
          </button>
        ))}
      </div>
    </div>
  );
}

// Page header (title + eyebrow + optional meta)
function PageHeader({ eyebrow, title, titleIt, ar, kicker, children, tone = "paper" }) {
  return (
    <section style={{ padding: "70px 0 60px", background: tone === "paper" ? "var(--paper)" : tone === "paper2" ? "var(--paper-2)" : "var(--ink)", color: tone === "ink" ? "var(--paper)" : "var(--ink)" }}>
      <div className="container-wide">
        {eyebrow && (
          <div className="eyebrow" style={{ marginBottom: 20, color: tone === "ink" ? "var(--gold-soft)" : undefined }}>
            <span className="dot" style={{ background: tone === "ink" ? "var(--gold-soft)" : undefined }}></span>{eyebrow}
          </div>
        )}
        <div className="page-hd-grid">
          <h1 style={{
            fontFamily: "var(--ff-display)", fontSize: "clamp(48px, 6vw, 96px)",
            lineHeight: 0.98, letterSpacing: "-0.02em", margin: 0,
          }}>
            {title}
            {titleIt && <> <span style={{ fontStyle: "italic", color: tone === "ink" ? "var(--gold-soft)" : "var(--terracotta)" }}>{titleIt}</span></>}
            {ar && <div className="ar" style={{ marginTop: 12, fontSize: "0.48em", color: tone === "ink" ? "var(--gold-soft)" : "var(--terracotta)", fontFamily: "var(--ff-ar)" }}>{ar}</div>}
          </h1>
          {kicker && (
            <div style={{ fontSize: 15, lineHeight: 1.6, color: tone === "ink" ? "rgba(244,237,226,0.8)" : "var(--olive)", maxWidth: 460 }}>
              {kicker}
            </div>
          )}
        </div>
        {children}
      </div>
    </section>
  );
}

Object.assign(window, { useRoute, L, TopBar, MainNav, Breadcrumbs, SubNav, PageHeader });
