/* All pages — Home, Shop index/category/PDP, Makers index/profile, Atelier, Visit, Process, Gifts, Journal index/article, Help, Account */

// ————————————————————— HOME —————————————————————
function HomePage({ t, lang }) {
  // Live counts feed the four-doors section. While loading we render
  // the editorial copy without a count so the page never says a wrong number.
  const pieces = window.usePieces();
  const makers = window.useMakers();
  const piecesCount = pieces.length;
  const makersCount = makers.length;
  const piecesCopy = piecesCount > 0
    ? (lang === "en"
        ? `${piecesCount} piece${piecesCount === 1 ? "" : "s"}, four houses.`
        : `${piecesCount.toLocaleString("ar-EG")} قطعة، أربعة بيوت.`)
    : (lang === "en" ? "Four quiet houses." : "أربعة بيوتٍ هادئة.");
  const makersCopy = makersCount > 0
    ? (lang === "en"
        ? `${makersCount} artisan${makersCount === 1 ? "" : "s"}, across Egypt.`
        : `${makersCount.toLocaleString("ar-EG")} حرفيًّا في مصر.`)
    : (lang === "en" ? "Artisans across Egypt." : "حرفيّون من أنحاء مصر.");
  return (
    <>
      <Hero t={t} lang={lang} />
      <Story t={t} lang={lang} />
      <ProverbBreak
        ar="اللي يصبر يَنال"
        en="Patience yields. So does a slow loom, a slow kiln, a slow afternoon in the atelier."
        attribution={lang === "en" ? "Egyptian proverb" : "مَثَلٌ مصري"}
      />
      <Collections t={t} lang={lang} />
      <section style={{ padding: "100px 0", background: "var(--paper-2)", textAlign: "center" }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 18, justifyContent: "center" }}><span className="dot"></span>{lang === "en" ? "Keep exploring" : "تابع"}</div>
          <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 5vw, 72px)", lineHeight: 1.05 }}>
            {lang === "en" ? "Four quiet doors." : "أربعة أبوابٍ هادئة."}
          </h2>
          <div className="stat-grid-4" style={{ marginTop: 50 }}>
            {[
              { t: lang === "en" ? "Shop" : "المتجر", d: piecesCopy, to: "/shop", tone: "sand", image: "assets/doors/shop.png" },
              { t: lang === "en" ? "Makers" : "الصنّاع", d: makersCopy, to: "/makers", tone: "terracotta", image: "assets/doors/makers.png" },
              { t: lang === "en" ? "Atelier" : "المحترف", d: lang === "en" ? "How a piece leaves our door." : "كيف تخرج القطعة." , to: "/atelier", tone: "olive", image: "assets/doors/atelier.png" },
              { t: lang === "en" ? "Journal" : "اليوميّات", d: lang === "en" ? "Notes from Cairo and the road." : "ملاحظات من القاهرة." , to: "/journal", tone: "gold", image: "assets/doors/journal.png" },
            ].map((c, i) => (
              <a key={i} href={"#" + c.to} style={{ textDecoration: "none", color: "inherit" }}>
                <div style={{ aspectRatio: "1", borderRadius: "999px 999px 10px 10px / 600px 600px 10px 10px", overflow: "hidden", marginBottom: 16 }}>
                  <Placeholder tone={c.tone} label={c.t.toLowerCase()} meta="→" src={c.image} imgFit="contain" imgPad={26} alt={c.t} />
                </div>
                <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 32 }}>{c.t}</h3>
                <p style={{ fontSize: 14, color: "var(--olive)", marginTop: 4 }}>{c.d}</p>
              </a>
            ))}
          </div>
        </div>
      </section>
      <Letter t={t} lang={lang} />
    </>
  );
}

// ————————————————————— SHOP —————————————————————
// Each piece carries provenance, materials, color tags, region, dimensions,
// "how it's made" timeline (3-5 steps), care symbols, and a process gallery.
const ALL_PIECES = [
  {
    slug: "oasis-knot", num: "№017", name: "Oasis Knot", ar: "عقدة الواحة",
    cat: "macrame", type: "Wall Hanging", maker: "Nour Ibrahim", price: 1240,
    tone: "sand", shape: "arch", edition: "1 of 6", region: "Siwa → Cairo",
    image: "assets/products/oasis-knot.png",
    color: "Sand & ivory", material: "Egyptian cotton, palm fibre",
    dims: "92 × 64 cm · 680 g", made: "11 days",
    care: ["sun", "no-water", "hand", "feather"],
    steps: [
      { t: "Cotton sourced", d: "From a weaver in Mahalla El-Kubra", tone: "sand" },
      { t: "Cord twisted", d: "By hand on a weighted spindle, 3-ply", tone: "olive" },
      { t: "Knotted on frame", d: "11 days · 4,200 knots, four patterns", tone: "terracotta" },
      { t: "Trimmed & combed", d: "Fringe cut to length, brushed soft", tone: "sand" },
      { t: "Wax-sealed & boxed", d: "Numbered, signed, stamped", tone: "gold" },
    ],
    gallery: [
      { l: "atelier · top-floor flat", tone: "sand", shape: "horseshoe" },
      { l: "the loom", tone: "olive", shape: "square" },
      { l: "knotting hands", tone: "terracotta", shape: "circle" },
      { l: "morning light", tone: "gold", shape: "pointed" },
    ],
  },
  {
    slug: "fustat-bowl", num: "№018", name: "Fustat Bowl", ar: "طاسة الفسطاط",
    cat: "ceramics", type: "Bowl · Food-safe", maker: "Hassan El-Fustati", price: 980,
    tone: "terracotta", shape: "horseshoe", edition: "Open", region: "Fustat, Cairo",
    image: "assets/products/fustat-bowl.png",
    color: "Terracotta & cream", material: "Nile silt clay, food-safe glaze",
    dims: "Ø 22 × 7 cm · 480 g", made: "9 days incl. firing",
    care: ["drop", "hand", "thermo"],
    steps: [
      { t: "Silt dug", d: "From a riverbank near Helwan", tone: "terracotta" },
      { t: "Wedged & thrown", d: "On the wheel in Fustat, 8 minutes per bowl", tone: "olive" },
      { t: "First firing", d: "Bisque · 950°C · overnight cool", tone: "ink" },
      { t: "Glazed & re-fired", d: "Lead-free glaze · 1240°C", tone: "gold" },
      { t: "Tested & stamped", d: "Lead/cadmium tested, Cairo lab", tone: "sand" },
    ],
    gallery: [
      { l: "the kiln", tone: "ink", shape: "pointed" },
      { l: "throwing", tone: "terracotta", shape: "circle" },
      { l: "glaze tests", tone: "gold", shape: "square" },
      { l: "stacked", tone: "sand", shape: "horseshoe" },
    ],
  },
  {
    slug: "ward-el-nil", num: "№019", name: "Ward el-Nil", ar: "ورد النيل",
    cat: "candles", type: "Candle 220g", maker: "Layla Abd-el-Raheem", price: 420,
    tone: "olive", shape: "pointed", edition: "Season 01", region: "Alexandria",
    image: "assets/products/ward-el-nil.png",
    color: "Olive & ivory", material: "Coconut wax, jasmine, neroli",
    dims: "Ø 8 × 9 cm · 220 g", made: "4 hours · 36 hr cure",
    care: ["fire", "drop", "leaf"],
    steps: [
      { t: "Notes blended", d: "Jasmine harvested at 4am · Beheira", tone: "olive" },
      { t: "Wax melted slow", d: "Coconut + soy, 78°C, never higher", tone: "gold" },
      { t: "Poured by hand", d: "Two pours, twelve minutes apart", tone: "sand" },
      { t: "Cured 36 hours", d: "In a cool dark cabinet", tone: "ink" },
      { t: "Trimmed & wax-sealed", d: "Wick cut to 6mm, lid sealed", tone: "terracotta" },
    ],
    gallery: [
      { l: "jasmine field, 4am", tone: "olive", shape: "horseshoe" },
      { l: "the pour", tone: "gold", shape: "pointed" },
      { l: "the cure", tone: "ink", shape: "circle" },
      { l: "first burn", tone: "terracotta", shape: "square" },
    ],
  },
  {
    slug: "aswan-stone", num: "№020", name: "Aswan Stone", ar: "حجر أسوان",
    cat: "resin", type: "Tray · Alabaster", maker: "Karim Hamed", price: 1680,
    tone: "gold", shape: "keel", edition: "1 of 12", region: "Aswan",
    image: "assets/products/aswan-stone.png",
    color: "Honey & cream", material: "Alabaster aggregate, eco-resin",
    dims: "32 × 18 × 2 cm · 920 g", made: "5 days · 48 hr cure",
    care: ["sun", "drop", "hand"],
    steps: [
      { t: "Alabaster crushed", d: "Off-cuts from Aswan quarries", tone: "gold" },
      { t: "Mixed with resin", d: "Eco-resin, 4:1, no fillers", tone: "sand" },
      { t: "Cast & cured", d: "48 hours in a silicone mould", tone: "olive" },
      { t: "Sanded by hand", d: "Eight grits, 80 → 2000", tone: "terracotta" },
      { t: "Sealed & numbered", d: "Matte finish, edition 1/12", tone: "ink" },
    ],
    gallery: [
      { l: "quarry off-cuts", tone: "gold", shape: "square" },
      { l: "the cast", tone: "sand", shape: "horseshoe" },
      { l: "sanding", tone: "olive", shape: "circle" },
      { l: "in the light", tone: "terracotta", shape: "pointed" },
    ],
  },
  { slug: "palm-shadow", num: "№021", name: "Palm Shadow", ar: "ظلّ النخيل", cat: "macrame", type: "Runner · Palm fibre", maker: "Fayrouz Mostafa", price: 860, tone: "sand", shape: "horseshoe", edition: "1 of 8", region: "Minya", color: "Sand & olive", material: "Palm fibre, cotton warp", dims: "180 × 38 cm", made: "9 days", image: "assets/products/palm-shadow.png" },
  { slug: "midan-lantern", num: "№022", name: "Midan Lantern", ar: "فانوس الميدان", cat: "resin", type: "Sculpture", maker: "Omar Zaki", price: 2340, tone: "terracotta", shape: "pointed", edition: "1 of 3", region: "Luxor", color: "Terracotta & gold", material: "Cast resin, brass leaf", dims: "26 × 26 × 38 cm", made: "14 days", image: "assets/products/midan-lantern.png" },
  { slug: "khan-tumbler", num: "№023", name: "Khan Tumbler", ar: "كوب الخان", cat: "ceramics", type: "Cup · set of 4", maker: "Hassan El-Fustati", price: 640, tone: "gold", shape: "square", edition: "Open", region: "Fustat", color: "Honey-glaze", material: "Stoneware", dims: "Ø 7 × 9 cm · 4 cups", made: "7 days" },
  { slug: "bahari-cord", num: "№024", name: "Bahari Cord", ar: "حبل البحري", cat: "macrame", type: "Curtain · 1.8m", maker: "Nour Ibrahim", price: 1890, tone: "olive", shape: "arch", edition: "1 of 4", region: "Cairo", color: "Olive & ink", material: "Cotton, linen", dims: "180 × 110 cm", made: "16 days" },
  { slug: "oud-noir", num: "№025", name: "Oud Noir", ar: "عود أسود", cat: "candles", type: "Candle 320g", maker: "Layla Abd-el-Raheem", price: 580, tone: "terracotta", shape: "circle", edition: "Season 01", region: "Alexandria", color: "Ink & ember", material: "Coconut wax, oud, cedar", dims: "Ø 9 × 11 cm · 320 g", made: "5 hours" },
];
const CATS = { macrame: { en: "Macramé", ar: "مكرمية" }, candles: { en: "Candle & Scent", ar: "شموع" }, resin: { en: "Resin & Stone", ar: "راتنج" }, ceramics: { en: "Fired Earth", ar: "فخار" } };

function ShopPage({ t, lang, cat }) {
  const [sort, setSort] = React.useState("curated");
  const [query, setQuery] = React.useState("");
  const [filtersOpen, setFiltersOpen] = React.useState(false);
  const [filters, setFilters] = React.useState({ price: [], edition: [], maker: [], availability: [] });

  // Body scroll-lock + ESC handling while the sheet is open
  React.useEffect(() => {
    if (!filtersOpen) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setFiltersOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
    };
  }, [filtersOpen]);

  const togglePill = (group, val) => setFilters(f => ({
    ...f,
    [group]: f[group].includes(val) ? f[group].filter(x => x !== val) : [...f[group], val],
  }));
  const clearAllFilters = () => setFilters({ price: [], edition: [], maker: [], availability: [] });
  const activeFilterCount =
    filters.price.length + filters.edition.length + filters.maker.length + filters.availability.length;

  const FILTER_GROUPS = [
    { k: "price",        en: "Price · EGP",  ar: "السعر · ج.م", values: ["Under 500", "500 – 1,200", "1,200 – 2,400", "2,400+"] },
    { k: "edition",      en: "Edition",      ar: "الإصدار",     values: ["Open", "Numbered", "One-of-one"] },
    { k: "maker",        en: "Maker",        ar: "الصانع",       values: ["Nour Ibrahim", "Hassan El-Fustati", "Layla A.R.", "Omar Zaki", "+ 8 more"] },
    { k: "availability", en: "Availability", ar: "التوفّر",      values: ["In stock", "Made to order", "Pre-order"] },
  ];
  // Arabic display labels for the (English-keyed) filter values. Values stay
  // English so the matching logic is untouched; only the visible label localizes.
  const FILTER_VALUE_AR = {
    "Under 500": "أقل من ٥٠٠", "500 – 1,200": "٥٠٠ – ١٢٠٠", "1,200 – 2,400": "١٢٠٠ – ٢٤٠٠", "2,400+": "٢٤٠٠+",
    "Open": "إصدار مفتوح", "Numbered": "مرقّمة", "One-of-one": "فريدة",
    "+ 8 more": "+ ٨ آخرون",
    "In stock": "متوفّرة", "Made to order": "تُصنع عند الطلب", "Pre-order": "حجز مسبق",
  };
  const filterValueLabel = (v) => lang === "ar" ? (FILTER_VALUE_AR[v] || v) : v;
  const SORT_OPTIONS = [
    { k: "curated",   en: "Curated",            ar: "منتقى" },
    { k: "new",       en: "Newest first",       ar: "الأحدث" },
    { k: "priceAsc",  en: "Price · low to high", ar: "السعر ↑" },
    { k: "priceDesc", en: "Price · high to low", ar: "السعر ↓" },
  ];

  const _live = usePieces();
  const _all = _live.length > 0 ? _live : ALL_PIECES;
  let pieces = cat ? _all.filter(p => p.cat === cat) : _all;
  if (query.trim()) {
    const q = query.trim().toLowerCase();
    pieces = pieces.filter(p =>
      p.name.toLowerCase().includes(q) ||
      (p.ar && p.ar.includes(query.trim())) ||
      p.maker.toLowerCase().includes(q) ||
      (p.region || "").toLowerCase().includes(q) ||
      (p.material || "").toLowerCase().includes(q) ||
      (p.color || "").toLowerCase().includes(q)
    );
  }
  // Apply the active sidebar/sheet filters. Within a group the pills OR;
  // across groups they AND. (Previously `filters` only updated the badge count.)
  const _matchPrice = (price, sel) => sel.some(s =>
    s === "Under 500" ? price < 500 :
    s === "500 – 1,200" ? price >= 500 && price <= 1200 :
    s === "1,200 – 2,400" ? price > 1200 && price <= 2400 :
    s === "2,400+" ? price > 2400 : false);
  const _matchEdition = (ed, sel) => {
    const numbered = /\d+\s*of\s*\d+/i.test(ed), one = /\b1\s*of\s*1\b/i.test(ed);
    return sel.some(s => s === "Open" ? !numbered : s === "Numbered" ? (numbered && !one) : s === "One-of-one" ? one : false);
  };
  const _matchAvail = (stock, sel) => sel.some(s => s === "In stock" ? (stock || 0) > 0 : (stock || 0) <= 0);
  const _matchMaker = (maker, sel) => { const real = sel.filter(s => s !== "+ 8 more"); return real.length === 0 || real.includes(maker); };
  pieces = pieces.filter(p =>
    (filters.price.length === 0 || _matchPrice(p.price, filters.price)) &&
    (filters.edition.length === 0 || _matchEdition(p.edition || "", filters.edition)) &&
    (filters.maker.length === 0 || _matchMaker(p.maker || "", filters.maker)) &&
    (filters.availability.length === 0 || _matchAvail(p.stock, filters.availability)));
  if (sort === "priceAsc") pieces = [...pieces].sort((a, b) => a.price - b.price);
  else if (sort === "priceDesc") pieces = [...pieces].sort((a, b) => b.price - a.price);
  else if (sort === "new") pieces = [...pieces].reverse();
  const title = cat ? CATS[cat].en : (lang === "en" ? "All pieces" : "كل القطع");
  const ar = cat ? CATS[cat].ar : null;

  const crumbs = [{ label: lang === "en" ? "Shop" : "المتجر", to: "/shop" }];
  if (cat) crumbs.push({ label: title });

  return (
    <>
      <Breadcrumbs crumbs={crumbs} lang={lang} />
      <PageHeader
        eyebrow={lang === "en" ? `Catalogue · ${pieces.length} pieces` : `الكتالوج · ${pieces.length} قطعة`}
        title={lang === "en" ? title : (cat ? CATS[cat].ar : "كل القطع")}
        titleIt={!cat ? (lang === "en" ? "this season." : "هذا الموسم.") : null}
        kicker={lang === "en"
          ? "Every piece is approved, photographed, packed and shipped from our atelier in Cairo. Tap a card to read the full card."
          : "كل قطعة معتمدة ومصوّرة ومُغلّفة ومُرسلة من محترفنا في القاهرة."}
      />
      <SubNav
        activeKey={cat || "all"}
        tabs={[
          { k: "all", label: lang === "en" ? "All" : "الكل", count: _all.length, to: "/shop" },
          { k: "macrame", label: CATS.macrame[lang], count: _all.filter(p => p.cat === "macrame").length, to: "/shop/macrame" },
          { k: "candles", label: CATS.candles[lang], count: _all.filter(p => p.cat === "candles").length, to: "/shop/candles" },
          { k: "resin", label: CATS.resin[lang], count: _all.filter(p => p.cat === "resin").length, to: "/shop/resin" },
          { k: "ceramics", label: CATS.ceramics[lang], count: _all.filter(p => p.cat === "ceramics").length, to: "/shop/ceramics" },
        ]}
      />
      <section style={{ padding: "50px 0 120px", background: "var(--paper)" }}>
        <div className="container-wide shop-layout">
          {/* Sidebar filters — single, self-contained desktop affordance.
              Header shows the live result count + a clear-all when active so
              the user never needs a separate apply button. */}
          <aside className="shop-filters" style={{ position: "sticky", top: 130, alignSelf: "start" }}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", paddingBottom: 12, borderBottom: "1px solid var(--line)" }}>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink)" }}>
                {lang === "en" ? "Filters" : "الفلاتر"}
                {activeFilterCount > 0 && <span style={{ color: "var(--terracotta)", marginLeft: 8 }}>· {activeFilterCount.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")}</span>}
              </div>
              {activeFilterCount > 0 && (
                <button type="button" onClick={clearAllFilters} style={{ background: "transparent", border: 0, cursor: "pointer", fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", textDecoration: "underline", padding: 0 }}>
                  {lang === "en" ? "Clear" : "مسح"}
                </button>
              )}
            </div>
            {FILTER_GROUPS.map(g => (
              <FilterBlock key={g.k} title={lang === "en" ? g.en : g.ar}>
                {g.values.map(v => (
                  <label key={v} style={filterItem}>
                    <input type="checkbox" checked={filters[g.k].includes(v)} onChange={() => togglePill(g.k, v)} /> {filterValueLabel(v)}
                  </label>
                ))}
              </FilterBlock>
            ))}
            <div style={{ marginTop: 18, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
              <strong style={{ color: "var(--terracotta)", fontWeight: 500 }}>{pieces.length.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")}</strong> {lang === "en" ? (pieces.length === 1 ? "piece" : "pieces") : "قطعة"}
            </div>
          </aside>
          <div>
            <div style={{ marginBottom: 22, display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", border: "1px solid var(--line)", borderRadius: 999, background: "var(--paper-2)" }}>
              <Icon name="search" size={16} color="var(--muted)" />
              <input
                type="search"
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder={lang === "en" ? "Search by name, maker, region, material…" : "ابحث بالاسم أو الصانع أو المنطقة…"}
                aria-label={lang === "en" ? "Search pieces" : "ابحث"}
                style={{ flex: 1, border: 0, background: "transparent", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0, color: "var(--ink)" }}
              />
              {query && <button onClick={() => setQuery("")} aria-label="Clear search" style={{ background: "transparent", border: 0, color: "var(--muted)", cursor: "pointer", fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase" }}>{lang === "en" ? "Clear" : "مسح"}</button>}
            </div>
            {/* Mobile-only filter row + sort — replaces the broken sidebar stack */}
            <div className="shop-filterbar">
              <button
                type="button"
                className="shop-filterbar-btn"
                onClick={() => setFiltersOpen(true)}
                aria-haspopup="dialog"
                aria-expanded={filtersOpen}
                aria-controls="shop-fsheet"
              >
                <span className="lbl">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
                    <path d="M3 6h18M6 12h12M9 18h6" strokeLinecap="round" />
                  </svg>
                  {lang === "en" ? "Filters" : "الفلاتر"}
                </span>
                {activeFilterCount > 0 && <span className="badge">{activeFilterCount}</span>}
              </button>
              <label className="shop-filterbar-sort">
                <span className="sr-only">{lang === "en" ? "Sort" : "الترتيب"}</span>
                <select value={sort} onChange={e => setSort(e.target.value)}>
                  {SORT_OPTIONS.map(o => (
                    <option key={o.k} value={o.k}>{lang === "en" ? o.en : o.ar}</option>
                  ))}
                </select>
              </label>
            </div>
            <div className="shop-filterbar-meta">
              <strong>{pieces.length}</strong> {lang === "en" ? "pieces" : "قطعة"}
              {query && <span> · "{query}"</span>}
            </div>

            {/* Desktop results + sort row (unchanged) */}
            <div className="shop-results-row" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 28 }}>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
                {pieces.length} {lang === "en" ? "results" : "نتيجة"}{query && <span style={{ color: "var(--terracotta)" }}> · "{query}"</span>}
              </div>
              <select value={sort} onChange={e => setSort(e.target.value)}
                aria-label={lang === "en" ? "Sort pieces" : "ترتيب القطع"}
                style={{ padding: "8px 14px", border: "1px solid var(--line)", borderRadius: 999, background: "transparent", fontFamily: "var(--ff-sans)", fontSize: 13, minHeight: 36 }}>
                <option value="curated">{lang === "en" ? "Sort · Curated" : "الترتيب · منتقى"}</option>
                <option value="new">{lang === "en" ? "Newest first" : "الأحدث"}</option>
                <option value="priceAsc">{lang === "en" ? "Price · low to high" : "السعر ↑"}</option>
                <option value="priceDesc">{lang === "en" ? "Price · high to low" : "السعر ↓"}</option>
              </select>
            </div>
            <div className="shop-grid">
              {pieces.map((p, i) => <ShopCard key={i} p={p} lang={lang} />)}
            </div>
          </div>
        </div>
      </section>

      {/* Mobile filter sheet — slides up from bottom */}
      <div
        className={"shop-fsheet-overlay " + (filtersOpen ? "open" : "")}
        onClick={() => setFiltersOpen(false)}
        aria-hidden="true"
      />
      <aside
        id="shop-fsheet"
        className={"shop-fsheet " + (filtersOpen ? "open" : "")}
        role="dialog"
        aria-modal="true"
        aria-label={lang === "en" ? "Filter pieces" : "فلتر القطع"}
        aria-hidden={!filtersOpen}
      >
        <div className="shop-fsheet-grip" aria-hidden="true" />
        <div className="shop-fsheet-head">
          <div>
            <div className="shop-fsheet-eyebrow">
              {lang === "en" ? "Refine the catalogue" : "نقّ المختارات"}
            </div>
            <h2 className="shop-fsheet-title">
              {lang === "en" ? "Filters" : "الفلاتر"}
              {lang === "en"
                ? <em>by hand.</em>
                : <span className="ar">باليد.</span>}
            </h2>
          </div>
          <button
            type="button"
            className="shop-fsheet-close"
            onClick={() => setFiltersOpen(false)}
            aria-label={lang === "en" ? "Close filters" : "إغلاق"}
          >×</button>
        </div>

        <div className="shop-fsheet-body">
          {FILTER_GROUPS.map(g => {
            const selected = filters[g.k];
            return (
              <div key={g.k} className="shop-fsheet-section">
                <div className="shop-fsheet-section-head">
                  <div className="shop-fsheet-section-title">
                    {lang === "en" ? g.en : g.ar}
                    <span className="ar">{lang === "en" ? g.ar : g.en}</span>
                  </div>
                  {selected.length > 0 && (
                    <span className="shop-fsheet-section-count">
                      {selected.length.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")} {lang === "en" ? "selected" : "مختارة"}
                    </span>
                  )}
                </div>
                <div className="shop-fsheet-pills" role="group">
                  {g.values.map(v => {
                    const active = selected.includes(v);
                    return (
                      <button
                        key={v}
                        type="button"
                        className={"shop-fsheet-pill" + (active ? " active" : "")}
                        onClick={() => togglePill(g.k, v)}
                        aria-pressed={active}
                      >{filterValueLabel(v)}</button>
                    );
                  })}
                </div>
              </div>
            );
          })}

          <div className="shop-fsheet-section">
            <div className="shop-fsheet-section-head">
              <div className="shop-fsheet-section-title">
                {lang === "en" ? "Sort" : "الترتيب"}
                <span className="ar">{lang === "en" ? "الترتيب" : "Sort"}</span>
              </div>
            </div>
            <div className="shop-fsheet-radio" role="radiogroup">
              {SORT_OPTIONS.map(o => {
                const active = sort === o.k;
                return (
                  <label key={o.k} className={active ? "active" : ""}>
                    <span>{lang === "en" ? o.en : o.ar}</span>
                    <span className="dot" aria-hidden="true" />
                    <input
                      type="radio"
                      name="sort"
                      value={o.k}
                      checked={active}
                      onChange={() => setSort(o.k)}
                    />
                  </label>
                );
              })}
            </div>
          </div>
        </div>

        <div className="shop-fsheet-foot">
          <button
            type="button"
            className="btn ghost"
            onClick={clearAllFilters}
            disabled={activeFilterCount === 0}
            style={activeFilterCount === 0 ? { opacity: 0.4, cursor: "default" } : undefined}
          >
            {lang === "en" ? "Clear" : "مسح"}
          </button>
          <button
            type="button"
            className="btn"
            onClick={() => setFiltersOpen(false)}
          >
            {lang === "en"
              ? `Show ${pieces.length} ${pieces.length === 1 ? "piece" : "pieces"}`
              : `إظهار ${pieces.length.toLocaleString("ar-EG")} قطعة`}
            <span className="arrow">→</span>
          </button>
        </div>
      </aside>
    </>
  );
}
const filterItem = { display: "flex", gap: 10, alignItems: "center", padding: "8px 0", fontSize: 14, color: "var(--olive)", cursor: "pointer" };
function FilterBlock({ title, children }) {
  return (
    <div style={{ borderBottom: "1px solid var(--line-2)", padding: "16px 0" }}>
      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}
function ShopCard({ p, lang }) {
  return (
    <a href={"#/shop/" + p.cat + "/" + p.slug} style={{ textDecoration: "none", color: "inherit" }}>
      <div style={{ aspectRatio: "0.82", overflow: "hidden", marginBottom: 16 }}>
        <Placeholder tone={p.tone} shape={p.shape || "arch"} topLabel={p.num} label={p.name.toLowerCase()} meta={p.edition} alt={`${p.name} — ${p.type || "piece"} by ${p.maker}`} src={p.image} />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <div>
          <div style={{ display: "flex", gap: 10, alignItems: "baseline" }}>
            <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 24 }}>{p.name}</h3>
            <span className="ar" style={{ fontSize: 15, color: "var(--terracotta)" }}>{p.ar}</span>
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>{p.type} · {p.maker}</div>
        </div>
        <div style={{ fontFamily: "var(--ff-display)", fontSize: 20 }}>{window.fmtPrice(p.price, lang)}</div>
      </div>
    </a>
  );
}

// ————————————————————— PDP —————————————————————
const CARE_LABEL = {
  en: { sun: "Keep from direct sun", "no-water": "Do not wet", drop: "Handle with care", hand: "Hand-clean only", leaf: "Trim wick to 6mm", fire: "Burn 3 hr max", thermo: "Not for hot liquids", feather: "Dust with soft brush" },
  ar: { sun: "بعيدًا عن الشمس", "no-water": "لا يُغسل", drop: "تعامل بحذر", hand: "تنظيف يدوي", leaf: "قُصّ الفتيل ٦ مم", fire: "حرق ٣ ساعات", thermo: "لا للسوائل الساخنة", feather: "بالفرشاة الناعمة" },
};

function PDPPage({ t, lang, cat, slug, addToCart }) {
  const _live = usePieces();
  const _all = _live.length > 0 ? _live : ALL_PIECES;
  const p = _all.find(x => x.slug === slug) || _all[0] || ALL_PIECES[0];

  // Fire product_view analytics event once per piece per session
  React.useEffect(() => {
    if (!p?.id || !window.sb) return;
    const key = `_view_${p.id}`;
    if (sessionStorage.getItem(key)) return;
    sessionStorage.setItem(key, "1");
    const anon = localStorage.getItem("sanaa_anon_id");
    const makerCache = (window._makersCache || []).find(m => m.slug === p.makerSlug);
    window.sb.from("analytics_events").insert({
      event_type: "product_view",
      product_id: p.id,
      maker_id: makerCache?.id || null,
      anon_id: anon,
    }).then(() => {});
  }, [p?.id]);

  // Load real photos from product_images (uploaded by maker, approved by admin).
  // Empty until photos land → falls back to the editorial Placeholder gallery.
  // storage_path → resolved to a public URL via the bucket-aware helper so
  // bucket/CDN swaps don't require rewriting every product_images row.
  const [realImages, setRealImages] = React.useState([]);
  React.useEffect(() => {
    if (!p?.id || !window.sb) return;
    window.sb.from("product_images")
      .select("id, storage_path, alt_en, alt_ar, is_main, position")
      .eq("product_id", p.id)
      .order("position", { ascending: true })
      .then(({ data }) => {
        const rows = (data || []).map(r => ({
          ...r,
          url: window.sb.storage.from("product-images").getPublicUrl(r.storage_path).data?.publicUrl || "",
        }));
        setRealImages(rows);
      });
  }, [p?.id]);

  const [tab, setTab] = React.useState("details");
  const [qty, setQty] = React.useState(1);
  const [mainShot, setMainShot] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);
  const makerSlug = p.makerSlug || p.maker.toLowerCase().replace(/\s+/g, "-");
  const related = _all.filter(x => x.slug !== p.slug && (x.cat === p.cat || x.maker === p.maker)).slice(0, 4);
  const steps = p.steps || [
    { t: "Sourced", d: "Materials gathered locally", tone: "sand" },
    { t: "Made by hand", d: `Crafted over ${p.made || "several days"}`, tone: "olive" },
    { t: "Inspected", d: "Reviewed against our rubric", tone: "terracotta" },
    { t: "Wax-sealed", d: "Numbered & shipped from Cairo", tone: "gold" },
  ];
  const gallery = p.gallery || [
    { l: "detail", tone: "sand", shape: "horseshoe" },
    { l: "in situ", tone: "olive", shape: "square" },
    { l: "hands", tone: "terracotta", shape: "circle" },
    { l: "scale", tone: "gold", shape: "pointed" },
  ];
  const careCodes = p.care || ["sun", "hand", "feather"];

  return (
    <>
      <Breadcrumbs crumbs={[
        { label: lang === "en" ? "Shop" : "المتجر", to: "/shop" },
        { label: CATS[p.cat][lang], to: "/shop/" + p.cat },
        { label: p.name },
      ]} lang={lang} />
      <section style={{ padding: "50px 0 80px", background: "var(--paper)" }}>
        <div className="container-wide pdp-layout">
          <div>
            {/* Gallery: real product_images take precedence; editorial
                placeholders are the fallback during the seeding window */}
            {(() => {
              if (realImages.length > 0) {
                const ordered = [...realImages].sort((a, b) => {
                  if (a.is_main && !b.is_main) return -1;
                  if (b.is_main && !a.is_main) return 1;
                  return (a.position ?? 0) - (b.position ?? 0);
                });
                const mainIdx = Math.min(mainShot, ordered.length - 1);
                const main = ordered[mainIdx];
                return (
                  <>
                    <div style={{ aspectRatio: "0.9", overflow: "hidden", marginBottom: 14, borderRadius: 12 }}>
                      <img src={main.url} alt={(lang === "ar" ? main.alt_ar : main.alt_en) || `${p.name}`}
                        loading="lazy"
                        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                    </div>
                    {ordered.length > 1 && (
                      <div className="pdp-thumbs">
                        {ordered.map((g, i) => (
                          <button key={g.id} onClick={() => setMainShot(i)}
                            aria-label={(lang === "ar" ? g.alt_ar : g.alt_en) || `View photo ${i + 1}`}
                            aria-current={mainIdx === i ? "true" : undefined}
                            style={{ aspectRatio: "1", border: mainIdx === i ? "2px solid var(--ink)" : "1px solid var(--line)", borderRadius: 8, padding: 0, overflow: "hidden", cursor: "pointer", background: "transparent" }}>
                            <img src={g.url} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                          </button>
                        ))}
                      </div>
                    )}
                  </>
                );
              }
              // Fallback — editorial placeholders
              return (
                <>
                  <div style={{ aspectRatio: "0.9", overflow: "hidden", marginBottom: 14 }}>
                    <Placeholder tone={mainShot === 0 ? p.tone : gallery[mainShot - 1].tone} shape={mainShot === 0 ? p.shape : gallery[mainShot - 1].shape} topLabel={mainShot === 0 ? p.num : `0${mainShot + 1} · ${gallery[mainShot - 1].l}`} label={mainShot === 0 ? p.name.toLowerCase() : gallery[mainShot - 1].l} meta={mainShot === 0 ? p.edition : "process"} alt={`${p.name} — ${mainShot === 0 ? "main" : gallery[mainShot - 1].l}`} src={mainShot === 0 ? p.image : null} />
                  </div>
                  <div className="pdp-thumbs">
                    {[{ l: "main", tone: p.tone, shape: p.shape, image: p.image }, ...gallery].map((g, i) => (
                      <button key={i} onClick={() => setMainShot(i)} aria-label={`View ${g.l}`} style={{ aspectRatio: "1", border: mainShot === i ? "2px solid var(--ink)" : "1px solid var(--line)", borderRadius: 8, padding: 0, overflow: "hidden", cursor: "pointer", background: "transparent" }}>
                        <Placeholder tone={g.tone} shape={g.shape} label={g.l} meta=" " src={g.image} />
                      </button>
                    ))}
                  </div>
                </>
              );
            })()}
            {/* Audio note from the maker */}
            <div style={{ marginTop: 22, padding: "16px 18px", border: "1px solid var(--line)", borderRadius: 14, background: "var(--paper-2)", display: "flex", gap: 16, alignItems: "center" }}>
              <button onClick={() => setPlaying(!playing)} aria-label={playing ? "Pause" : "Play maker note"} style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--ink)", color: "var(--paper)", border: 0, cursor: "pointer", display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name={playing ? "pause" : "play"} size={16} />
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "A note from the maker · 47 sec · Arabic" : "كلمة من الصانع · ٤٧ث · بالعربيّة"}</div>
                <div style={{ marginTop: 6, color: "var(--terracotta)" }}><Waveform bars={32} color="var(--terracotta)" height={22} playing={playing} /></div>
              </div>
            </div>
          </div>
          <div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", display: "flex", gap: 14, flexWrap: "wrap" }}>
              <span>{p.num} · {p.edition}</span>
              {p.region && <span style={{ color: "var(--terracotta)" }}><Icon name="pin" size={11} /> {p.region}</span>}
            </div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginTop: 10, flexWrap: "wrap" }}>
              <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 6vw, 56px)", letterSpacing: "-0.01em" }}>{p.name}</h1>
              <span className="ar" style={{ fontSize: 26, color: "var(--terracotta)" }}>{p.ar}</span>
            </div>
            <div style={{ marginTop: 8 }}>
              <a href={"#/makers/" + makerSlug} style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>{lang === "en" ? `by ${p.maker} →` : `بيد ${p.maker} ←`}</a>
            </div>
            <p style={{ marginTop: 24, fontSize: 16, color: "var(--olive)", lineHeight: 1.65, maxWidth: 520 }}>
              {lang === "en" ? `${p.material || "Made carefully"}. ${p.dims ? p.dims + ". " : ""}Made over ${p.made || "several days"} in ${p.region || "Egypt"}.` : `صُنعت بعناية في ${p.region || "مصر"}.`}
            </p>

            {/* Provenance card */}
            <div className="pdp-promise" style={{ marginTop: 26, padding: "18px 22px", border: "1px solid var(--terracotta)", borderRadius: 14, background: "rgba(181,80,46,0.04)" }}>
              <WaxSeal size={64} edition={p.num} />
              <div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>{lang === "en" ? "Authenticated · Edition" : "موثّقة · إصدار"}</div>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 22, marginTop: 4 }}>{p.num} · {p.edition}</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: "var(--muted)", marginTop: 4 }}>{lang === "en" ? "Hand-stamped · scan QR for the maker's record" : "ختمٌ يدوي · امسح للسجل"}</div>
              </div>
              <div style={{ background: "var(--paper)", padding: 6, borderRadius: 8 }}>
                <QrMark size={64} color="var(--ink)" seed={p.slug} />
              </div>
            </div>

            <div style={{ marginTop: 26, padding: "22px 0", borderTop: "1px solid var(--ink)", borderBottom: "1px solid var(--ink)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)" }}>{lang === "en" ? "EGP" : "ج.م"}</div>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 44 }}>{p.price.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")}</div>
              </div>
              <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap", justifyContent: "flex-end" }}>
                <div style={{ display: "flex", gap: 6, alignItems: "center", border: "1px solid var(--line)", borderRadius: 999, padding: 6 }}>
                  <button onClick={() => setQty(Math.max(1, qty - 1))} aria-label="Decrease quantity" style={{ width: 32, height: 32, borderRadius: "50%", border: 0, background: "transparent", cursor: "pointer" }}>−</button>
                  <span style={{ fontFamily: "var(--ff-mono)", minWidth: 20, textAlign: "center" }}>{qty}</span>
                  <button onClick={() => setQty(qty + 1)} aria-label="Increase quantity" style={{ width: 32, height: 32, borderRadius: "50%", border: 0, background: "transparent", cursor: "pointer" }}>+</button>
                </div>
                <button className="btn" onClick={() => addToCart(p, qty)}>{lang === "en" ? "Add to bag" : "أضف"} <span className="arrow">→</span></button>
              </div>
            </div>

            {/* Care icon row */}
            <div style={{ marginTop: 22, display: "flex", gap: 18, flexWrap: "wrap" }}>
              {careCodes.map(c => (
                <div key={c} title={CARE_LABEL[lang][c] || c} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, color: "var(--olive)" }}>
                  <div style={{ width: 38, height: 38, borderRadius: "50%", border: "1px solid var(--line)", display: "grid", placeItems: "center", color: "var(--terracotta)" }}><Icon name={c} size={18} /></div>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 8, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--muted)", maxWidth: 76, textAlign: "center", lineHeight: 1.3 }}>{CARE_LABEL[lang][c] || c}</div>
                </div>
              ))}
            </div>

            {/* Tabs */}
            <div style={{ marginTop: 36 }}>
              <div style={{ display: "flex", gap: 0, borderBottom: "1px solid var(--line)", flexWrap: "wrap" }}>
                {[
                  { k: "details", l: lang === "en" ? "Details" : "التفاصيل" },
                  { k: "materials", l: lang === "en" ? "Materials" : "الخامات" },
                  { k: "shipping", l: lang === "en" ? "Shipping" : "الشحن" },
                  { k: "safety", l: lang === "en" ? "Safety" : "الأمان" },
                ].map(x => (
                  <button key={x.k} onClick={() => setTab(x.k)} style={{
                    padding: "14px 20px", background: "transparent", border: 0, cursor: "pointer",
                    fontFamily: "var(--ff-sans)", fontSize: 13,
                    borderBottom: tab === x.k ? "2px solid var(--terracotta)" : "2px solid transparent",
                    color: tab === x.k ? "var(--ink)" : "var(--muted)", marginBottom: -1,
                  }}>{x.l}</button>
                ))}
              </div>
              <div style={{ padding: "24px 0", fontSize: 14, color: "var(--olive)", lineHeight: 1.75 }}>
                {tab === "details" && (lang === "en"
                  ? <>Dimensions <strong>{p.dims || "—"}</strong> · {p.color || "tonal palette"} · made over <strong>{p.made || "several days"}</strong> · edition {p.edition}.</>
                  : <>المقاسات <strong>{p.dims || "—"}</strong> · {p.color || "تدرّجٌ لونيّ"} · صُنعت على مدى <strong>{p.made || "بضعة أيّام"}</strong> · إصدار {p.edition}.</>)}
                {tab === "materials" && (lang === "en"
                  ? <>{p.material || "Sourced from local Egyptian artisans."} Sourcing route: <strong>{p.region || "Cairo"}</strong>. Off-cuts and excess returned to the maker; nothing wasted.</>
                  : <>{p.material || "خاماتٌ من حرفيين مصريين محليين."} مسار التوريد: <strong>{p.region || "القاهرة"}</strong>. تُعاد القُصاصات والفائض إلى الصانع؛ لا شيء يُهدَر.</>)}
                {tab === "shipping" && (lang === "en"
                  ? <>Wax-sealed and packed in Zamalek. Egypt: Bosta next-day (greater Cairo) or 2–4 days. Regional: Aramex 3–7 days. Worldwide on request. Free pickup from the atelier (Mon–Sat, 11–18).</>
                  : <>تُختَم بالشمع وتُغلَّف في الزمالك. داخل مصر: بوسطة في اليوم التالي (القاهرة الكبرى) أو ٢–٤ أيّام. إقليميًّا: أرامكس ٣–٧ أيّام. شحنٌ عالميّ عند الطلب. استلامٌ مجّانيّ من المحترف (السبت–الخميس، ١١–١٨).</>)}
                {tab === "safety" && (lang === "en"
                  ? <>Cotton-cored wicks only. Ceramics tested for lead & cadmium by independent Cairo lab. Resin not food-contact unless stated. Certificate included with each piece.</>
                  : <>فتائل بقلبٍ قطنيٍّ فقط. يُفحَص الفخار من الرصاص والكادميوم في معملٍ مستقلّ بالقاهرة. الراتنج غير مخصّصٍ لملامسة الطعام ما لم يُذكَر ذلك. تُرفَق شهادةٌ مع كل قطعة.</>)}
              </div>

              {/* A discreet line for direct contact with the maker — same editorial tone */}
              {(() => {
                const makerCache = (window._makersCache || []).find(mk => mk.slug === makerSlug);
                if (!makerCache?.id) return null;
                return (
                  <div style={{ marginTop: 8, paddingTop: 18, borderTop: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                    <div style={{ fontFamily: "var(--ff-display)", fontStyle: "italic", fontSize: 17, color: "var(--olive)" }}>
                      {lang === "en" ? "Have a question for the maker?" : "لديك سؤال للصانع؟"}
                    </div>
                    <MessageMakerButton lang={lang} makerId={makerCache.id} makerSlug={makerCache.slug} makerName={p.maker} productId={p.id} productName={p.name} />
                  </div>
                );
              })()}
            </div>
          </div>
        </div>
      </section>

      {/* How it's made — timeline */}
      <section style={{ padding: "90px 0", background: "var(--paper-2)" }}>
        <div className="container-wide">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 50, flexWrap: "wrap", gap: 20 }}>
            <div>
              <div className="eyebrow"><span className="dot"></span>{lang === "en" ? "How it's made" : "كيف صُنعت"}</div>
              <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 4.4vw, 64px)", marginTop: 14, lineHeight: 1.05 }}>
                {lang === "en" ? <>From earth to <em style={{ color: "var(--terracotta)" }}>your hand.</em></> : <>من الأرض إلى <em style={{ color: "var(--terracotta)" }}>يدك.</em></>}
              </h2>
            </div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
              {steps.length} {lang === "en" ? "steps" : "خطوات"} · {p.made || "—"}
            </div>
          </div>
          <div className="proc-strip" style={{ "--cols": steps.length }}>
            <div className="proc-strip-rule" style={{ position: "absolute", top: 28, left: "8%", right: "8%", height: 1, background: "var(--line)" }} />
            {steps.map((s, i) => (
              <div key={i} style={{ position: "relative" }}>
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
                  <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--paper)", border: "1px solid var(--ink)", display: "grid", placeItems: "center", fontFamily: "var(--ff-display)", fontSize: 22, position: "relative", zIndex: 1 }}>{i + 1}</div>
                </div>
                <div style={{ aspectRatio: "0.9", borderRadius: 10, overflow: "hidden", marginBottom: 14 }}>
                  <Placeholder tone={s.tone || "sand"} shape={["horseshoe", "pointed", "square", "circle", "keel"][i % 5]} label={s.t.toLowerCase()} meta={`step 0${i + 1}`} />
                </div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)", marginBottom: 6 }}>STEP 0{i + 1}</div>
                <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 20, lineHeight: 1.2, marginBottom: 10, minHeight: "2.4em" }}>{s.t}</h3>
                <p style={{ fontSize: 13, color: "var(--olive)", lineHeight: 1.6 }}>{s.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Maker card — richer */}
      <section style={{ padding: "100px 0", background: "var(--paper)" }}>
        <div className="container-wide split-1-14">
          <div style={{ aspectRatio: "0.85", overflow: "hidden" }}>
            <Placeholder tone={p.tone} shape="arch" label={p.maker.toLowerCase()} meta="portrait" topLabel="The maker" alt={`Portrait of ${p.maker}`} />
          </div>
          <div>
            <div className="eyebrow"><span className="dot"></span>{lang === "en" ? "The hand behind this piece" : "اليد وراء هذه القطعة"}</div>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 5vw, 56px)", marginTop: 18, letterSpacing: "-0.01em" }}>{p.maker}</h2>
            <p style={{ marginTop: 16, fontSize: 17, color: "var(--olive)", lineHeight: 1.7, maxWidth: 560 }}>
              {lang === "en"
                ? `Working out of a quiet flat in ${p.region ? p.region.split(" → ").slice(-1)[0] : "Cairo"}. ${p.maker.split(" ")[0]} learned the craft from family and has been making with us since 2019. Each piece is signed and numbered.`
                : `يعمل بهدوءٍ في ${p.region || "القاهرة"}. تعلّم الحرفة من العائلة، ويصنع معنا منذ ٢٠١٩.`}
            </p>
            <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0, border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden", maxWidth: 520 }}>
              {[
                { k: lang === "en" ? "Pieces with us" : "قطع معنا", v: lang === "en" ? "8" : "٨" },
                { k: lang === "en" ? "Maker's split" : "نسبة الصانع", v: lang === "en" ? "82%" : "٨٢٪" },
                { k: lang === "en" ? "Lead time" : "مدّة التنفيذ", v: lang === "en" ? "2–5 wks" : "٢–٥ أسابيع" },
              ].map((s, i) => (
                <div key={i} style={{ padding: "14px 18px", borderRight: i < 2 ? "1px solid var(--line-2)" : "none" }}>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>{s.k}</div>
                  <div style={{ fontFamily: "var(--ff-display)", fontSize: 22, marginTop: 4 }}>{s.v}</div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a className="btn" href={"#/makers/" + makerSlug}>{lang === "en" ? "Open maker profile" : "صفحة الصانع"} →</a>
              <a className="btn ghost" href="#/atelier/visit">{lang === "en" ? "Visit the atelier" : "زُر المحترف"}</a>
            </div>
          </div>
        </div>
      </section>

      {/* Related pieces */}
      <section style={{ padding: "80px 0 120px", background: "var(--paper-2)" }}>
        <div className="container-wide">
          <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 44, marginBottom: 36 }}>
            {lang === "en" ? "Other pieces you may keep nearby" : "قطعٌ أخرى قد تحبّها"}
          </h2>
          <div className="shop-grid" style={{ gap: 28 }}>
            {related.map((r, i) => <ShopCard key={i} p={r} lang={lang} />)}
          </div>
        </div>
      </section>
    </>
  );
}

// ————————————————————— MAKERS —————————————————————
const MAKERS_FULL = [
  { slug: "nour-ibrahim", name: "Nour Ibrahim", ar: "نور إبراهيم", city: "Cairo", trade: "Macramé", since: 2019, tone: "sand", pieces: 8 },
  { slug: "hassan-el-fustati", name: "Hassan El-Fustati", ar: "حسن الفُسطاطي", city: "Fustat", trade: "Ceramics", since: 2011, tone: "terracotta", pieces: 5 },
  { slug: "layla-abd-el-raheem", name: "Layla Abd-el-Raheem", ar: "ليلى عبد الرحيم", city: "Alexandria", trade: "Candle & Scent", since: 2021, tone: "gold", pieces: 9 },
  { slug: "omar-zaki", name: "Omar Zaki", ar: "عمر زكي", city: "Luxor", trade: "Resin & Stone", since: 2018, tone: "olive", pieces: 6 },
  { slug: "fayrouz-mostafa", name: "Fayrouz Mostafa", ar: "فيروز مصطفى", city: "Minya", trade: "Palm Fibre", since: 2016, tone: "sand", pieces: 4 },
  { slug: "karim-hamed", name: "Karim Hamed", ar: "كريم حامد", city: "Aswan", trade: "Alabaster Resin", since: 2020, tone: "gold", pieces: 5 },
];

function MakersIndexPage({ t, lang }) {
  const _liveMakers = useMakers();
  const _makers = _liveMakers.length > 0 ? _liveMakers : MAKERS_FULL;
  return (
    <>
      <Breadcrumbs crumbs={[{ label: lang === "en" ? "Makers" : "الصنّاع" }]} lang={lang} />
      <PageHeader
        eyebrow={lang === "en" ? `The house · ${_makers.length} artisans` : `البيت · ${_makers.length} حرفيًّا`}
        title={lang === "en" ? "The hands" : "الأيدي"}
        titleIt={lang === "en" ? "behind each piece." : "خلف كل قطعة."}
        kicker={lang === "en"
          ? "We approve manually, score against an eight-point rubric, and publish every maker's split on their page. No exceptions, no hidden fees."
          : "نعتمد يدويًّا، ونقيّم وفق معيارٍ من ثماني نقاط، وننشر نسبة كل صانع على صفحته."}
      />
      <section style={{ padding: "60px 0 120px", background: "var(--paper)" }}>
        <div className="container-wide pieces-grid">
          {_makers.map((m, i) => (
            <a key={i} href={"#/makers/" + m.slug} style={{ textDecoration: "none", color: "inherit" }}>
              <div style={{ aspectRatio: "0.8", borderRadius: "999px 999px 10px 10px / 600px 600px 10px 10px", overflow: "hidden", marginBottom: 16 }}>
                <Placeholder tone={m.tone} topLabel={`M.${String(i + 1).padStart(2, "0")}`} label={m.name.toLowerCase()} meta={m.city} />
              </div>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                <div>
                  <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 28 }}>{m.name}</h3>
                  <div className="ar" style={{ fontSize: 15, color: "var(--terracotta)" }}>{m.ar}</div>
                </div>
                <Star8 size={12} color="var(--gold)" />
              </div>
              <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
                <span>{m.trade} · {m.city}</span>
                <span>{m.pieces} {lang === "en" ? "pieces" : "قطعة"}</span>
              </div>
            </a>
          ))}
        </div>
      </section>
    </>
  );
}

function MakerProfilePage({ t, lang, slug }) {
  const _liveMakers = useMakers();
  const _livePieces = usePieces();
  const _makers = _liveMakers.length > 0 ? _liveMakers : MAKERS_FULL;
  const _allPieces = _livePieces.length > 0 ? _livePieces : ALL_PIECES;
  const m = _makers.find(x => x.slug === slug) || _makers[0] || MAKERS_FULL[0];
  const theirs = _allPieces.filter(p => p.makerSlug === m.slug || p.maker.toLowerCase().replace(/\s+/g, "-") === m.slug);
  const [playing, setPlaying] = React.useState(false);
  return (
    <>
      <Breadcrumbs crumbs={[
        { label: lang === "en" ? "Makers" : "الصنّاع", to: "/makers" },
        { label: m.name },
      ]} lang={lang} />
      <section style={{ padding: "70px 0", background: "var(--paper)" }}>
        <div className="container-wide split-2">
          <div style={{ aspectRatio: "0.95", overflow: "hidden" }}>
            <Placeholder tone={m.tone} shape="arch" topLabel="Portrait" label={m.name.toLowerCase()} meta={m.city} alt={`Portrait of ${m.name}, ${m.trade} maker in ${m.city}`} />
          </div>
          <div>
            <div className="eyebrow"><span className="dot"></span>{lang === "en" ? `Maker since ${m.since}` : `صانعٌ منذ ${m.since}`}</div>
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(56px, 6vw, 88px)", marginTop: 18, letterSpacing: "-0.02em", lineHeight: 1 }}>
              {m.name}
              <div className="ar" style={{ fontSize: "0.45em", color: "var(--terracotta)", marginTop: 10 }}>{m.ar}</div>
            </h1>
            <div style={{ marginTop: 30, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0, border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden" }}>
              {[
                { k: lang === "en" ? "Trade" : "الحِرفة", v: m.trade },
                { k: lang === "en" ? "City" : "المدينة", v: m.city },
                { k: lang === "en" ? "Pieces with us" : "قطع معنا", v: m.pieces },
                { k: lang === "en" ? "Rubric score" : "درجة التقييم", v: lang === "en" ? "87 / 100" : "٨٧ / ١٠٠" },
                { k: lang === "en" ? "Shelf split" : "نسبة الصانع", v: lang === "en" ? "82%" : "٨٢٪" },
                { k: lang === "en" ? "Lead time" : "مدّة التنفيذ", v: lang === "en" ? "2–5 weeks" : "٢–٥ أسابيع" },
              ].map((s, i) => (
                <div key={i} style={{ padding: "14px 18px", borderRight: i % 3 < 2 ? "1px solid var(--line-2)" : "none", borderBottom: i < 3 ? "1px solid var(--line-2)" : "none" }}>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>{s.k}</div>
                  <div style={{ fontFamily: "var(--ff-display)", fontSize: 18, marginTop: 4 }}>{s.v}</div>
                </div>
              ))}
            </div>
            <p style={{ marginTop: 30, fontSize: 16, color: "var(--olive)", lineHeight: 1.65 }}>
              {lang === "en" ? "Works from a sunlit top-floor flat with four apprentices. Sources cotton from a weaver in Mahalla and palm fibre from Siwa oasis." : "تعمل من شقّةٍ مشمسة في الطابق العلوي مع أربع متدرّبات."}
            </p>

            {/* Audio interview */}
            <div style={{ marginTop: 24, padding: "16px 18px", border: "1px solid var(--line)", borderRadius: 14, background: "var(--paper-2)", display: "flex", gap: 16, alignItems: "center", maxWidth: 540 }}>
              <button onClick={() => setPlaying(!playing)} aria-label={playing ? "Pause interview" : "Play interview"} style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--terracotta)", color: "var(--paper)", border: 0, cursor: "pointer", display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name={playing ? "pause" : "play"} size={16} />
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Interview · 6:18 · Arabic with subtitles" : "مقابلة · ٦:١٨ · عربيّ"}</div>
                <div style={{ marginTop: 6, color: "var(--terracotta)" }}><Waveform bars={48} color="var(--terracotta)" height={26} playing={playing} /></div>
              </div>
            </div>

            {/* Message the maker — opens compose modal (only renders if maker has a real DB id) */}
            {m.id && (
              <div style={{ marginTop: 24 }}>
                <MessageMakerButton lang={lang} makerId={m.id} makerSlug={m.slug} makerName={m.name} />
              </div>
            )}
          </div>
        </div>
      </section>

      {/* A day in the workshop — video + photo strip */}
      <section style={{ padding: "90px 0", background: "var(--ink)", color: "var(--paper)" }}>
        <div className="container-wide">
          <div className="bigsplit-1614">
            <div style={{ position: "relative", aspectRatio: "1.6", overflow: "hidden", borderRadius: 14 }}>
              <Placeholder tone="terracotta" label="atelier · a working day" meta="Film · 4:12" topLabel="A day in the workshop" alt="Video still — the atelier mid-morning" />
              <button aria-label="Play workshop film" style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(14,13,16,0.25)", border: 0, cursor: "pointer", color: "var(--paper)" }}>
                <div style={{ width: 96, height: 96, borderRadius: "50%", background: "rgba(244,237,226,0.92)", color: "var(--ink)", display: "grid", placeItems: "center", boxShadow: "0 20px 60px -10px rgba(28,26,21,0.4)" }}>
                  <Icon name="play" size={32} />
                </div>
              </button>
              <div style={{ position: "absolute", bottom: 18, left: 22, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--paper)" }}>
                ◆ {lang === "en" ? "Filmed by Salma Abou-Zeid · Spring 2026" : "تصوير سلمى أبو زيد · ربيع ٢٠٢٦"}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateRows: "1fr 1fr", gap: 14 }}>
              <div style={{ overflow: "hidden", borderRadius: 14 }}>
                <Placeholder tone="sand" shape="horseshoe" label={lang === "en" ? "morning light" : "ضوء الصباح"} meta={lang === "en" ? "08:14" : "٠٨:١٤"} />
              </div>
              <div style={{ overflow: "hidden", borderRadius: 14 }}>
                <Placeholder tone="gold" shape="circle" label={lang === "en" ? "the wheel" : "العَجَلة"} meta={lang === "en" ? "11:30" : "١١:٣٠"} />
              </div>
            </div>
          </div>
          <div className="stat-grid-4" style={{ marginTop: 40, gap: 14 }}>
            {[
              { l: "tea break", lAr: "وقفة شاي", t: "13:20", tAr: "١٣:٢٠", tone: "sand", shape: "square" },
              { l: "the loom", lAr: "النَّول", t: "14:45", tAr: "١٤:٤٥", tone: "olive", shape: "horseshoe" },
              { l: "knotting", lAr: "العَقد", t: "16:00", tAr: "١٦:٠٠", tone: "terracotta", shape: "circle" },
              { l: "the call to maghrib", lAr: "أذان المغرب", t: "18:12", tAr: "١٨:١٢", tone: "gold", shape: "pointed" },
            ].map((p, i) => (
              <div key={i}>
                <div style={{ aspectRatio: "1", overflow: "hidden", marginBottom: 10 }}>
                  <Placeholder tone={p.tone} shape={p.shape} label={lang === "en" ? p.l : p.lAr} meta={lang === "en" ? p.t : p.tAr} />
                </div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "rgba(244,237,226,0.6)" }}>
                  {lang === "en" ? <>{p.t} · {p.l}</> : <>{p.tAr} · {p.lAr}</>}
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section style={{ padding: "60px 0 120px", background: "var(--paper-2)" }}>
        <div className="container-wide">
          <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(32px, 4.5vw, 48px)", marginBottom: 36 }}>{lang === "en" ? "Pieces by this maker" : "قطع هذا الصانع"} <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12, color: "var(--muted)", letterSpacing: "0.2em" }}>({theirs.length || "8"})</span></h2>
          <div className="pieces-grid">
            {(theirs.length ? theirs : _allPieces.slice(0, 3)).map((p, i) => <ShopCard key={i} p={p} lang={lang} />)}
          </div>
        </div>
      </section>
    </>
  );
}

// ————————————————————— ATELIER / VISIT / PROCESS —————————————————————

// Rich "Our story" editorial section — rooted in the meaning of صنعة
function OurStory({ lang }) {
  const en = lang === "en";
  return (
    <>
      {/* ——— I. THE NAME — صنعة as the opening idea ——— */}
      <section style={{ padding: "120px 0 80px", background: "var(--paper)", position: "relative", overflow: "hidden" }}>
        <div className="container-wide" style={{ maxWidth: 1180, margin: "0 auto", padding: "0 32px", textAlign: "center", position: "relative" }}>
          {/* tiny star above the title */}
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 28, opacity: 0.85 }}>
            <Star8 size={22} color="var(--terracotta)" />
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
            {en ? "i. The name" : "أوّلًا · الاسم"}
          </div>

          {/* The Arabic word, hero-sized */}
          <div style={{
            marginTop: 28,
            fontFamily: "var(--ff-ar)",
            fontSize: "clamp(96px, 14vw, 200px)",
            lineHeight: 0.9,
            color: "var(--ink)",
            direction: "rtl",
            letterSpacing: "-0.02em",
          }}>
            صَنْعَة
          </div>

          {/* Diacritical pronunciation + literal translation */}
          <div style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(20px, 2vw, 28px)", fontStyle: "italic", color: "var(--terracotta)" }}>
            ṣanʿah
          </div>

          {/* Three definitions, dictionary-style */}
          <div style={{
            marginTop: 50, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0,
            maxWidth: 1000, margin: "50px auto 0",
            borderTop: "1px solid var(--line-2)", borderBottom: "1px solid var(--line-2)",
          }} className="os-defs">
            {[
              { n: "1.", w: en ? "craft" : "حِرْفة", b: en ? "the doing of a thing well, with the hand." : "إتقانُ الشيءِ باليد." },
              { n: "2.", w: en ? "making" : "صُنْع", b: en ? "the slow, deliberate act of bringing into being." : "الفعلُ البطيءُ المتأنّي للإتيان بالشيء." },
              { n: "3.", w: en ? "mastery" : "إتقان", b: en ? "the dignity that gathers in a thing made well." : "الكرامة التي تتجمَّع في الشيءِ المُتقَن." },
            ].map((d, i) => (
              <div key={i} style={{
                padding: "32px 24px",
                borderLeft: i === 0 ? "none" : "1px dashed var(--line-2)",
                textAlign: "center",
              }} className="os-def">
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", color: "var(--terracotta)" }}>{d.n}</div>
                <div style={{ marginTop: 10, fontFamily: "var(--ff-display)", fontSize: 30, fontStyle: "italic", color: "var(--ink)" }}>{d.w}</div>
                <div style={{ marginTop: 10, fontSize: 14, lineHeight: 1.6, color: "var(--olive)" }}>{d.b}</div>
              </div>
            ))}
          </div>

          {/* Closing line */}
          <p style={{
            marginTop: 50, maxWidth: 720, margin: "50px auto 0",
            fontFamily: "var(--ff-display)", fontSize: "clamp(22px, 2.4vw, 30px)",
            lineHeight: 1.4, color: "var(--ink)",
          }}>
            {en ? <>We did not pick a brand name. We picked <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>a discipline</span> — and tried to deserve it.</>
                : <>لم نختر اسمَ علامةٍ تجاريّة. اخترنا <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>انضباطًا</span> — وحاولنا أن نستحقَّه.</>}
          </p>
        </div>

        {/* Faint star pattern in corners */}
        <div style={{ position: "absolute", top: 60, left: 60, opacity: 0.08 }} aria-hidden="true">
          <Star8 size={120} color="var(--terracotta)" />
        </div>
        <div style={{ position: "absolute", bottom: 60, right: 60, opacity: 0.08 }} aria-hidden="true">
          <Star8 size={120} color="var(--terracotta)" />
        </div>

        <style>{`
          @media (max-width: 760px) {
            .os-defs { grid-template-columns: 1fr !important; }
            .os-def { border-left: none !important; border-top: 1px dashed var(--line-2); }
            .os-def:first-child { border-top: none; }
          }
        `}</style>
      </section>

      {/* arabesque divider */}
      <div style={{ background: "var(--paper)", padding: "10px 0" }}>
        <ArabesqueStrip color="var(--gold)" height={26} />
      </div>

      {/* ——— II. THE LETTER — written by Marwa ——— */}
      <section style={{ padding: "100px 0 80px", background: "var(--paper)", position: "relative", overflow: "hidden" }}>
        <div className="container-wide" style={{ maxWidth: 1180, margin: "0 auto", padding: "0 32px", position: "relative" }}>
          <div style={{ textAlign: "center", marginBottom: 60 }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
              {en ? "ii. A letter" : "ثانيًا · رسالة"}
            </div>
            <h2 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 4.5vw, 56px)", lineHeight: 1.05 }}>
              {en ? <>From the founder, <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>April 2026.</span></>
                  : <>من المؤسِّسة، <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>أبريل ٢٠٢٦.</span></>}
            </h2>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.4fr)", gap: 80, alignItems: "start" }} className="os-letter">
            {/* Left — arched portrait frame (mihrab style) */}
            <div>
              <div className="arch" style={{
                aspectRatio: "3/4", maxWidth: 320,
                border: "1px solid var(--line-2)",
                background: "linear-gradient(160deg, #c89c6e 0%, #8a6648 60%, #5a3d28 100%)",
                position: "relative",
              }}>
                <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 30% 30%, rgba(255,235,200,0.25), transparent 55%)" }} />
                {/* tiny star at top of arch */}
                <div style={{ position: "absolute", top: 22, left: 0, right: 0, display: "flex", justifyContent: "center" }}>
                  <Star8 size={20} color="var(--paper)" />
                </div>
                <div style={{ position: "absolute", bottom: 18, left: 18, right: 18, color: "var(--paper)", textAlign: "center" }}>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.7 }}>Marwa Hasan</div>
                  <div style={{ fontFamily: "var(--ff-display)", fontSize: 22, fontStyle: "italic", marginTop: 4 }}>
                    {en ? "Cairo, 2026" : "القاهرة، ٢٠٢٦"}
                  </div>
                </div>
              </div>
              {/* Signature */}
              <div style={{ marginTop: 28, fontFamily: "var(--ff-display)", fontSize: 38, fontStyle: "italic", color: "var(--ink)", transform: "rotate(-3deg)" }}>
                Marwa
              </div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginTop: 6 }}>
                {en ? "Marwa Hasan, founder" : "مروة حسن، المؤسِّسة"}
              </div>
              {/* Star + Arabic seal motif */}
              <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 12, color: "var(--terracotta)" }}>
                <Star8 size={14} color="currentColor" />
                <div style={{ flex: 1, height: 1, background: "var(--line-2)" }} />
                <span style={{ fontFamily: "var(--ff-ar)", fontSize: 18, direction: "rtl", color: "var(--terracotta)" }}>صَنْعَة</span>
              </div>
            </div>

            {/* Right — the letter, with صنعة woven through */}
            <div>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 110, lineHeight: 0.7, color: "var(--terracotta)", marginBottom: -10 }}>"</div>
              <p style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(26px, 3.2vw, 38px)", lineHeight: 1.25, color: "var(--ink)", marginBottom: 28 }}>
                {en
                  ? <>My grandmother used to say of a tray of well-rolled grape leaves: <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>"this has ṣanʿah."</span> She did not mean the food — she meant the hand that did it without rushing.</>
                  : <>كانت جدّتي تقول عن صينيّة وَرق العنبِ المرصوصة جيّدًا: <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>«دي فيها صنعة»</span>. لم تكن تقصد الطعام — قصدت اليدَ التي صنعَتْها دون استعجال.</>
                }
              </p>
              <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--olive)", marginBottom: 18 }}>
                {en
                  ? "It was the highest praise in our house. Not 'beautiful', not 'expensive' — but ṣanʿah: the dignity a thing collects when somebody refused to hurry through it. I grew up looking for that quiet weight in everything from a tea-glass to a knot."
                  : "كان أعلى ثناءٍ في بيتنا. ليس «جميل»، وليس «غالٍ» — بل «صنعة»: الكرامة التي يجمعها الشيءُ حين يرفض أحدٌ أن يمرّ عليه على عجل. كبرتُ وأنا أبحث عن ذلك الثِّقَل الهادئ في كلّ شيء، من كوب الشاي إلى العقدة."
                }
              </p>
              <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--olive)", marginBottom: 18 }}>
                {en
                  ? <>By 2021 I was finding it less and less. The basket-maker on Khan el-Khalili had moved to imports. The candle stall in Bahari closed. Two of the women I bought from in Fustat had stopped — not because they couldn't make, but because they couldn't <em>price</em>. So I started a notebook of phone numbers.</>
                  : <>بحلول ٢٠٢١ كنتُ أجدُها أقلَّ فأقلّ. صانع السلالِ في خان الخليلي تحوَّل إلى المستوردات. كُشكُ الشموع في بحري أُغلق. سيِّدتانِ كنتُ أشتري منهما في الفسطاط توقَّفتا — ليس لأنّهما لم تستطيعا الصُّنع، بل لأنّهما لم تستطيعا <em>التسعير</em>. فبدأتُ دفترًا من أرقام الهاتف.</>
                }
              </p>
              <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--olive)", marginBottom: 18 }}>
                {en
                  ? <>SANAA is the answer I could build to that small terror. A <strong style={{ color: "var(--ink)" }}>house</strong>, not a marketplace — small enough to know every maker by their second cup of tea, strict enough that <strong style={{ color: "var(--terracotta)" }}>82 piastres of every pound</strong> stays with the hand that earned it.</>
                  : <>«صنعة» هي الإجابة التي استطعتُ بناءها على ذلك الذُّعرِ الصغير. <strong style={{ color: "var(--ink)" }}>بيتٌ</strong>، لا متجر — صغيرٌ بما يكفي لمعرفة كلّ صانعٍ مع كوب الشاي الثاني، صارمٌ بما يكفي ليبقى <strong style={{ color: "var(--terracotta)" }}>٨٢ قرشًا من كلّ جنيه</strong> مع اليدِ التي كسبته.</>
                }
              </p>
              <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--olive)" }}>
                {en
                  ? "Everything you see here — the names, the prices, the lead times, the photographs — was negotiated with the maker, not for them. We built the website so the work could move; we kept the rules so the work could stay itself."
                  : "كلّ ما تراه هنا — الأسماء، الأسعار، مدد الانتظار، الصور — تمَّ الاتفاق عليه مع الصانع، لا عنه. بنينا الموقعَ لتتحرَّك الصنعة؛ وأبقينا القواعد لتظلَّ الصنعةُ كما هي."
                }
              </p>
            </div>
          </div>

          <style>{`
            @media (max-width: 900px) {
              .os-letter { grid-template-columns: 1fr !important; gap: 50px !important; }
            }
          `}</style>
        </div>
      </section>

      {/* ProverbBreak — Egyptian saying about craft */}
      <ProverbBreak
        ar="«لا تستهنْ بالصنعةِ، فإنّها مفتاحُ الرزق.»"
        en="Do not belittle a craft — it is the key that opens the door of livelihood."
        attribution={en ? "— Egyptian proverb" : "— مَثَلٌ مصريّ"}
        tone="paper"
      />

      {/* ——— III. NUMBERS — quiet but proud ——— */}
      <section style={{ padding: "100px 0 80px", background: "var(--paper-2)", borderTop: "1px solid var(--line-2)", borderBottom: "1px solid var(--line-2)" }}>
        <div className="container-wide" style={{ maxWidth: 1280, margin: "0 auto", padding: "0 32px" }}>
          <div style={{ textAlign: "center", marginBottom: 60 }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
              {en ? "iii. The house, in numbers" : "ثالثًا · البيت بالأرقام"}
            </div>
            <h2 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(34px, 4vw, 50px)", lineHeight: 1.1 }}>
              {en ? <>Five things <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>we count.</span></>
                  : <>خمسةُ أشياءَ <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>نَعُدُّها.</span></>}
            </h2>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 24 }} className="os-numbers">
            {[
              { n: "12", l: en ? "Active makers" : "صانعًا نشطًا", s: en ? "Hand-picked, one trade each" : "اختيار يدويّ، حرفةٌ لكلٍّ" },
              { n: "8", l: en ? "Governorates" : "محافظات", s: en ? "Cairo · Giza · Alex · Fayoum · S. Sinai · Aswan · Luxor · Minya" : "القاهرة · الجيزة · الإسكندريّة · الفيّوم · جنوب سيناء · أسوان · الأقصر · المنيا" },
              { n: "82%", l: en ? "Stays with the maker" : "تبقى مع الصانع", s: en ? "Of every pound spent" : "من كلّ جنيه" },
              { n: "1 in 5", l: en ? "Application accepted" : "طلب يُقبل", s: en ? "Last twelve months" : "آخر اثني عشر شهرًا" },
              { n: "0", l: en ? "Stock photographs" : "صور أرشيفيّة", s: en ? "Every photo shot in the maker's own light" : "كلّ صورةٍ في ضوءِ الصانع نفسِه" },
            ].map((x, i) => (
              <div key={i} style={{ borderLeft: i === 0 ? "none" : "1px solid var(--line-2)", paddingLeft: i === 0 ? 0 : 24 }} className="os-num-cell">
                <div style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(38px, 4vw, 54px)", lineHeight: 1, color: "var(--terracotta)" }}>{x.n}</div>
                <div style={{ marginTop: 8, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink)", fontWeight: 500 }}>{x.l}</div>
                <div style={{ marginTop: 6, fontSize: 12, lineHeight: 1.5, color: "var(--muted)" }}>{x.s}</div>
              </div>
            ))}
          </div>
          <style>{`
            @media (max-width: 900px) { .os-numbers { grid-template-columns: repeat(2, 1fr) !important; gap: 32px 24px !important; }
              .os-num-cell { border-left: none !important; padding-left: 0 !important; }
            }
            @media (max-width: 480px) { .os-numbers { grid-template-columns: 1fr !important; } }
          `}</style>
        </div>
      </section>

      {/* ——— IV. THE TIMELINE — narrative, dated ——— */}
      <section style={{ padding: "120px 0 100px", background: "var(--paper)" }}>
        <div className="container-wide" style={{ maxWidth: 1180, margin: "0 auto", padding: "0 32px" }}>
          <div style={{ marginBottom: 60, display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
                {en ? "iv. How we began" : "رابعًا · كيف بدأنا"}
              </div>
              <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 4vw, 56px)", lineHeight: 1, marginTop: 12 }}>
                {en ? "Five years," : "خمس سنوات،"} <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>{en ? "in seven moments." : "في سبع لحظات."}</span>
              </h2>
            </div>
            <div style={{ fontSize: 13, color: "var(--muted)", maxWidth: 340, fontFamily: "var(--ff-display)", fontStyle: "italic" }}>
              {en ? "Not a press release. The actual things that happened." : "ليست نشرةً صحفيّة. ما حدث فعلًا."}
            </div>
          </div>

          <div style={{ position: "relative" }}>
            {/* Vertical thread */}
            <div style={{ position: "absolute", left: lang === "ar" ? "auto" : 22, right: lang === "ar" ? 22 : "auto", top: 12, bottom: 12, width: 1, background: "var(--line-2)" }} />
            {[
              { y: "2021", m: en ? "March" : "مارس", t: en ? "The first eleven names." : "الأحد عشر اسمًا الأوّل.", b: en ? "Marwa drives 1,840 km in three weeks — Old Cairo to Tunis village in Fayoum, on to Aswan, Luxor, and back through Minya — and comes home with a notebook of phone numbers and a Google Sheet of three hundred photographs." : "تقطع مروة ١٨٤٠ كم في ثلاثة أسابيع — من القاهرة القديمة إلى قرية تونس بالفيّوم، فأسوان، الأقصر، عودةً عبر المنيا — وتعود بدفترٍ من الأرقام وثلاثمائة صورة." },
              { y: "2021", m: en ? "September" : "سبتمبر", t: en ? "We open without a door." : "نفتتح بلا باب.", b: en ? "We launch online with seven makers and no physical address — the homepage becomes our showroom, the maker's own home becomes the studio. The first month, we sell eleven pieces and refuse to invent a fake address to look bigger." : "نفتتح إلكترونيًّا بسبعة صنّاع، بلا عنوانٍ ماديّ — الصفحة الرئيسيّة تصبح المعرض، وبيت الصانع نفسه يصبح الأستوديو. في الشهر الأوّل نبيع إحدى عشرة قطعة، ونرفض اختلاق عنوانٍ وهميّ لنبدوَ أكبر." },
              { y: "2022", m: en ? "April" : "أبريل", t: en ? "We write the rubric." : "نكتب الميثاق.", b: en ? "After a hard refusal — a maker we loved, work we couldn't certify — we sit down and write the maker rubric: ten criteria, scored out of 100, pass mark 75. We've used it ever since." : "بعد رفضٍ صعب، نجلس ونكتب ميثاق الصانع: عشرة معايير، علامة النجاح ٧٥/١٠٠." },
              { y: "2023", m: en ? "January" : "يناير", t: en ? "82 / 18." : "٨٢ / ١٨.", b: en ? "We end the year with a margin question and decide it the only way that felt right: 82% to the maker, 18% to the platform. It's stayed there since." : "ننهي السنة بسؤال هامش الربح، ونحسمه: ٨٢٪ للصانع، ١٨٪ للمنصّة. ولم يتغيّر." },
              { y: "2023", m: en ? "October" : "أكتوبر", t: en ? "The first workshop, in a maker's living room." : "أوّل ورشة، في صالة بيت صانعة.", b: en ? "Nour clears her own living room in Sayyida Zeinab and holds her first knot workshop. Six seats, sold out in two days. We learn the lesson early: the home is wherever the maker is." : "تُفرِغ نور صالة بيتها في السيّدة زينب وتُقيم أوّل ورشة عقد. ستّة مقاعد تُباع في يومين. نتعلّم الدرس مبكِّرًا: البيت حيث الصانع." },
              { y: "2024", m: en ? "August" : "أغسطس", t: en ? "Pop-ups, not premises." : "حلولٌ مؤقّتة، لا مقرّ.", b: en ? "We try our first three pop-ups — Dahab on the Sinai coast, Tunis village in Fayoum, and a Friday market in Old Cairo on Shar'a el-Moez. Each is hosted in a maker's own home or stall. The lesson holds: the work travels better when it stays where it is from." : "نُجرِّب أوّل ثلاث فعاليّات مؤقّتة — دهب على ساحل سيناء، قرية تونس بالفيّوم، سوقُ جمعةٍ في شارع المعزّ بالقاهرة القديمة. كلٌّ منها يُستضاف في بيت صانعٍ أو كُشكه. الدرس يثبت: الصنعة تسافر أفضل حين تبقى من حيث هي." },
              { y: "2026", m: en ? "April" : "أبريل", t: en ? "Where we are today." : "ما نحن عليه اليوم.", b: en ? <>Twelve makers across eight governorates. Three operations people working from their own homes. <strong style={{ color: "var(--terracotta)" }}>One open dream</strong> — a physical house, when the makers we serve are ready for it, and not a day before.</> : <>اثنا عشر صانعًا في ثماني محافظات. ثلاثة في العمليّات يعملون من بيوتهم. <strong style={{ color: "var(--terracotta)" }}>وحُلْمٌ واحدٌ مفتوح</strong> — بيتٌ ماديّ، حين يكون الصنّاع الذين نخدمهم جاهزين، ولا يومًا قبل ذلك.</> },
            ].map((s, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "60px 110px 1fr",
                gap: 28, padding: "26px 0", alignItems: "start",
                borderTop: i === 0 ? "none" : "1px dashed var(--line-2)",
              }} className="os-tl-row">
                {/* Bullet */}
                <div style={{ position: "relative", height: 24, paddingTop: 6 }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: "50%",
                    background: "var(--paper)", border: "2px solid var(--terracotta)",
                    display: "grid", placeItems: "center", marginLeft: 12,
                  }}>
                    <div style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--terracotta)" }} />
                  </div>
                </div>
                {/* Year */}
                <div>
                  <div style={{ fontFamily: "var(--ff-display)", fontSize: 36, lineHeight: 1, color: "var(--ink)" }}>{s.y}</div>
                  <div style={{ marginTop: 4, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{s.m}</div>
                </div>
                {/* Body */}
                <div style={{ paddingTop: 4 }}>
                  <h3 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(22px, 2.4vw, 28px)", lineHeight: 1.2, color: "var(--ink)" }}>{s.t}</h3>
                  <p style={{ marginTop: 10, fontSize: 15, lineHeight: 1.7, color: "var(--olive)", maxWidth: 640 }}>{s.b}</p>
                </div>
              </div>
            ))}
            <style>{`
              @media (max-width: 700px) {
                .os-tl-row { grid-template-columns: 40px 1fr !important; gap: 16px !important; }
                .os-tl-row > :nth-child(2) { grid-column: 2; padding-bottom: 4px; }
                .os-tl-row > :nth-child(3) { grid-column: 2; }
              }
            `}</style>
          </div>
        </div>
      </section>

      {/* ——— V. THE MAP OF THE HOUSE — dispersed makers ——— */}
      <section style={{ padding: "120px 0 100px", background: "var(--paper-2)", borderTop: "1px solid var(--line-2)", borderBottom: "1px solid var(--line-2)", position: "relative", overflow: "hidden" }}>
        <div className="container-wide" style={{ maxWidth: 1280, margin: "0 auto", padding: "0 32px", position: "relative" }}>
          <div style={{ marginBottom: 60, maxWidth: 720 }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
              {en ? "v. The map of the house" : "خامسًا · خريطة البيت"}
            </div>
            <h2 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 4.5vw, 56px)", lineHeight: 1.05 }}>
              {en ? <>The house has <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>no doorstep yet.</span></>
                  : <>البيت <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>بلا عتبةٍ بعد.</span></>}
            </h2>
            <p style={{ marginTop: 22, fontSize: 17, lineHeight: 1.7, color: "var(--olive)", maxWidth: 620 }}>
              {en
                ? <>It has <em>rooms</em>, though — eight of them, in eight governorates. Each room is the home or workshop of a maker. We did not gather them in one building; we built a roof of attention over the places they already are. <strong>One day,</strong> a real address. <strong>Until then,</strong> these eight rooms are the house.</>
                : <>لكنّ له <em>غرفًا</em> — ثمانية، في ثماني محافظات. كلّ غرفة هي بيتُ صانعٍ أو ورشتُه. لم نجمعهم في بنايةٍ واحدة؛ بنينا سقفَ انتباهٍ فوق أماكنهم التي هم فيها. <strong>يومًا ما</strong> سيكون لنا عنوان. <strong>إلى ذلك الحين</strong>، هذه الغرف الثماني هي البيت.</>
              }
            </p>
          </div>

          {/* The eight rooms grid */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 18 }} className="os-rooms">
            {[
              { gov: en ? "Cairo · Old Cairo" : "القاهرة · القديمة", n: "i.", spot: en ? "Shar'a el-Moez" : "شارع المعزّ", trade: en ? "Brass & metalwork" : "نحاسٌ ومعادن", count: 2, tone: "linear-gradient(150deg, #a8763e, #6b4622)", note: en ? "Above the workshops of the Fatimid spine — the oldest brass-row in the country." : "فوق ورش العمود الفاطميّ — أقدم صفّ نحاسٍ في البلاد." },
              { gov: en ? "Giza · Fustat" : "الجيزة · الفُسطاط", n: "ii.", spot: en ? "Pottery quarter" : "حيّ الفخّار", trade: en ? "Ceramics" : "فخّار", count: 2, tone: "linear-gradient(150deg, #b15535, #6e2e18)", note: en ? "The kilns have been lit on this same hill since 641 AD." : "أفرانٌ تُوقَد على هذا التلّ ذاته منذ ٦٤١م." },
              { gov: en ? "Alexandria · Bahari" : "الإسكندريّة · بحري", n: "iii.", spot: en ? "Anfoushi" : "الأنفوشي", trade: en ? "Candles & wax" : "شموعٌ وشمع", count: 1, tone: "linear-gradient(150deg, #4a6a82, #233a4d)", note: en ? "Sea-salt in the air, lavender drying on the rooftop." : "ملحُ البحرِ في الهواء، خُزامى تجفّ على السطح." },
              { gov: en ? "Fayoum · Tunis village" : "الفيّوم · قرية تونس", n: "iv.", spot: en ? "Lake Qarun escarpment" : "حافّة بحيرة قارون", trade: en ? "Ceramics & textile" : "فخّارٌ ونسيج", count: 2, tone: "linear-gradient(150deg, #8a7a4a, #4d4222)", note: en ? "Egypt's quietest pottery village. Two of our makers grew up at the wheel here." : "أهدأ قرى الفخّار في مصر. اثنان من صنّاعنا تربّيا على عجلتها." },
              { gov: en ? "South Sinai · Dahab" : "جنوب سيناء · دهب", n: "v.", spot: en ? "Asilah seaside" : "أصيلة الشاطئ", trade: en ? "Macramé & rope" : "عقدٌ وحبال", count: 1, tone: "linear-gradient(150deg, #2d6e7a, #103943)", note: en ? "Macramé learned from Bedouin saddle-makers, retaught beside the Red Sea." : "عقدٌ تعلّمته من سراج البدو، وأعادت تعليمه على ضفّة البحر الأحمر." },
              { gov: en ? "Aswan · Gharb Soheil" : "أسوان · غرب سهيل", n: "vi.", spot: en ? "Nubian shore" : "الشاطئ النوبيّ", trade: en ? "Beadwork & weaving" : "خَرَزٌ ونسج", count: 2, tone: "linear-gradient(150deg, #c4854e, #7a4f25)", note: en ? "Indigo and cobalt patterns older than the High Dam, mother to daughter." : "نقوش النيلة والكوبالت أقدم من السدّ العالي، من الأمّ للابنة." },
              { gov: en ? "Luxor · West Bank" : "الأقصر · البرّ الغربيّ", n: "vii.", spot: en ? "Qurna village" : "قرية القرنة", trade: en ? "Alabaster & stone" : "مرمرٌ وحجر", count: 1, tone: "linear-gradient(150deg, #b09875, #6e5a3c)", note: en ? "Alabaster cut in the same quarries that built Hatshepsut's temple." : "مرمر يُقطَع من المحاجر التي شُيِّدت منها معابد حتشبسوت." },
              { gov: en ? "Minya · Mallawi" : "المنيا · ملوي", n: "viii.", spot: en ? "Coptic cluster" : "العنقود القبطيّ", trade: en ? "Wood inlay" : "تطعيمُ الخشب", count: 1, tone: "linear-gradient(150deg, #6b6b3e, #3a3a1e)", note: en ? "A four-generation workshop — palm-wood inlay with bone and ebony." : "ورشة من أربعة أجيال — تطعيمُ خشبِ النخلِ بالعظم والأبنوس." },
            ].map((r, i) => (
              <div key={i} style={{
                background: "var(--paper)", border: "1px solid var(--line-2)", borderRadius: 14,
                overflow: "hidden", display: "flex", flexDirection: "column",
              }}>
                {/* card image — arch/medallion */}
                <div style={{ aspectRatio: "1.4", background: r.tone, position: "relative" }}>
                  <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 30% 30%, rgba(255,235,200,0.18), transparent 60%)" }} />
                  {/* roman numeral */}
                  <div style={{
                    position: "absolute", top: 14, left: 14,
                    fontFamily: "var(--ff-display)", fontSize: 26, color: "var(--paper)", fontStyle: "italic",
                  }}>{r.n}</div>
                  {/* maker count badge */}
                  <div style={{
                    position: "absolute", top: 14, right: 14,
                    padding: "3px 10px", borderRadius: 999,
                    background: "rgba(244,237,226,0.92)", color: "var(--ink)",
                    fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase",
                  }}>{r.count} {en ? (r.count === 1 ? "maker" : "makers") : "صنّاع"}</div>
                  {/* small star center-bottom */}
                  <div style={{ position: "absolute", bottom: 14, left: 0, right: 0, display: "flex", justifyContent: "center", opacity: 0.7 }}>
                    <Star8 size={14} color="var(--paper)" />
                  </div>
                </div>
                {/* body */}
                <div style={{ padding: "20px 20px 24px" }}>
                  <div style={{ fontFamily: "var(--ff-display)", fontSize: 22, lineHeight: 1.1, color: "var(--ink)" }}>{r.gov}</div>
                  <div style={{ marginTop: 4, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)", fontWeight: 500 }}>{r.spot} · {r.trade}</div>
                  <p style={{ marginTop: 14, fontSize: 13, lineHeight: 1.6, color: "var(--olive)" }}>{r.note}</p>
                </div>
              </div>
            ))}
          </div>

          {/* the dream line */}
          <div style={{ marginTop: 70, padding: "32px 36px", border: "1px dashed var(--terracotta)", borderRadius: 14, background: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }} className="os-dream">
            <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <Star8 size={22} color="var(--terracotta)" />
              <div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--terracotta)", fontWeight: 500 }}>
                  {en ? "The room we don't have yet" : "الغرفة التي لم نملكها بعد"}
                </div>
                <div style={{ marginTop: 8, fontFamily: "var(--ff-display)", fontSize: "clamp(22px, 2.4vw, 28px)", lineHeight: 1.2, color: "var(--ink)" }}>
                  {en ? <>One day — <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>a real address.</span></>
                      : <>يومًا ما — <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>عنوانٌ حقيقيّ.</span></>}
                </div>
                <p style={{ marginTop: 10, fontSize: 14, color: "var(--olive)", maxWidth: 540 }}>
                  {en ? "When the work makes a doorstep possible — and not before — we'll open one. Until then, the work itself is our front door." : "حين تجعل الصنعةُ العتبةَ ممكنة — لا قبل ذلك — سنفتح بابًا. وإلى أن يحين، الصنعةُ نفسُها هي بابنا الأماميّ."}
                </p>
              </div>
            </div>
          </div>

          <style>{`
            @media (max-width: 1100px) { .os-rooms { grid-template-columns: repeat(3, 1fr) !important; } }
            @media (max-width: 820px)  { .os-rooms { grid-template-columns: repeat(2, 1fr) !important; } }
            @media (max-width: 520px)  { .os-rooms { grid-template-columns: 1fr !important; } }
          `}</style>
        </div>
      </section>

      {/* ——— VI. WHAT WE COMMIT TO — values as a deliberate list ——— */}
      <section style={{ padding: "120px 0", background: "var(--ink)", color: "var(--paper)", position: "relative" }}>
        {/* faint diagonal */}
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, opacity: 0.05, pointerEvents: "none" }}>
          <DiagonalLinesBg color="var(--gold-soft)" spacing={28} strokeWidth={1} />
        </div>
        <div className="container-wide" style={{ maxWidth: 1280, margin: "0 auto", padding: "0 32px", position: "relative" }}>
          <div style={{ maxWidth: 720, marginBottom: 60 }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--gold-soft)" }}>
              {en ? "vi. The five rules of ṣanʿah" : "سادسًا · قواعد الصنعة الخمس"}
            </div>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(38px, 4.5vw, 60px)", lineHeight: 1.05, marginTop: 14 }}>
              {en ? "Five lines" : "خمسة سطور"} <span style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>{en ? "we don't bend." : "لا نُحايد فيها."}</span>
            </h2>
            <p style={{ marginTop: 18, fontSize: 15, lineHeight: 1.7, color: "rgba(244,237,226,0.7)", maxWidth: 580 }}>
              {en
                ? "We wrote these the night we had to refuse a maker we admired — because his work was beautiful, but the conditions weren't. We've kept them on the wall ever since."
                : "كتبناها في الليلةِ التي اضطُررنا فيها لرفض صانعٍ نُحبُّه — لأنّ عملَه كان جميلًا، لكنّ الظروفَ لم تكن. أبقيناها على الحائط منذُ ذلك الحين."
              }
            </p>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 0, borderTop: "1px solid rgba(244,237,226,0.12)" }} className="os-vals">
            {[
              { n: "01", h: en ? "The maker is named." : "الصانع يُذكَر باسمه.", b: en ? "Every piece carries the maker's name. We don't rebrand work as 'SANAA atelier' — it stays theirs." : "كلّ قطعة تحمل اسم صانعها. لا نعيد تعليمها." },
              { n: "02", h: en ? "82 / 18, always." : "٨٢ / ١٨ دائمًا.", b: en ? "Eighty-two to the maker, eighteen to the house. No category exceptions, no promotional discounts that come out of their share." : "اثنان وثمانون للصانع، ثمانية عشر للبيت. بلا استثناءات." },
              { n: "03", h: en ? "Prices are theirs." : "الأسعار لهم.", b: en ? "We advise on market range, but the final number is the maker's. We never override a price to clear stock." : "ننصح بنطاقٍ سوقيّ، لكنّ الرقم النهائيّ للصانع." },
              { n: "04", h: en ? "Photographed at home." : "تُصوَّر في بيتها.", b: en ? "Every piece is photographed at the atelier or in the maker's studio. No stock imagery, no flat lays." : "كلّ قطعةٍ تُصوَّر في محترفها. بلا صورٍ أرشيفيّة." },
              { n: "05", h: en ? "Slow, on purpose." : "بطيءٌ عن قصد.", b: en ? "Lead times reflect actual making time. We will not promise a hand-knotted piece in 48 hours." : "مدد الانتظار تعكس وقت الصنع الفعليّ. لا نَعِد بقطعة عقدٍ يدويّ خلال ٤٨ ساعة." },
            ].map((v, i) => (
              <div key={i} style={{
                padding: "32px 22px", borderLeft: i === 0 ? "none" : "1px solid rgba(244,237,226,0.12)",
                position: "relative",
              }} className="os-val">
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", color: "var(--gold-soft)", fontWeight: 500 }}>{v.n}</div>
                <h3 style={{ marginTop: 16, fontFamily: "var(--ff-display)", fontSize: 22, lineHeight: 1.2, color: "var(--paper)" }}>{v.h}</h3>
                <p style={{ marginTop: 14, fontSize: 13, lineHeight: 1.65, color: "rgba(244,237,226,0.7)" }}>{v.b}</p>
              </div>
            ))}
            <style>{`
              @media (max-width: 1100px) { .os-vals { grid-template-columns: repeat(2, 1fr) !important; }
                .os-val { border-left: none !important; border-top: 1px solid rgba(244,237,226,0.12) !important; }
                .os-val:nth-child(odd) { border-right: 1px solid rgba(244,237,226,0.12); }
              }
              @media (max-width: 600px) { .os-vals { grid-template-columns: 1fr !important; }
                .os-val:nth-child(odd) { border-right: none !important; }
              }
            `}</style>
          </div>
        </div>
      </section>

      {/* ——— VII. TEAM — small, real ——— */}
      <section style={{ padding: "120px 0 100px", background: "var(--paper)" }}>
        <div className="container-wide" style={{ maxWidth: 1180, margin: "0 auto", padding: "0 32px" }}>
          <div style={{ marginBottom: 50 }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--muted)" }}>
              {en ? "vii. The house team" : "سابعًا · فريق البيت"}
            </div>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 4vw, 52px)", lineHeight: 1, marginTop: 12 }}>
              {en ? "Four people," : "أربعة أشخاص،"} <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>{en ? "twelve makers." : "اثنا عشر صانعًا."}</span>
            </h2>
            <p style={{ marginTop: 18, fontSize: 16, color: "var(--olive)", maxWidth: 580 }}>
              {en
                ? "We work from our own homes — three cities between us. Every maker has a direct line to one of us; every approval crosses one of our desks within the same day."
                : "نعمل من بيوتنا — ثلاث مدنٍ بيننا. لكلّ صانع خطٌّ مباشر بأحدنا؛ وكلّ موافقةٍ تمرّ على أحد مكاتبنا في اليوم نفسه."
              }
            </p>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 22 }} className="os-team">
            {[
              { name: "Marwa Hasan", ar: "مروة حسن", role: en ? "Founder" : "المؤسِّسة", since: "2021", bio: en ? "Buyer's eye. Wrote the rubric. Drives most of the trips." : "عينُ المشتري. كتبت الميثاق.", tone: "linear-gradient(140deg, #c89c6e, #8a6648)" },
              { name: "Tarek el-Kady", ar: "طارق القاضي", role: en ? "Quality lead" : "مسؤول الجودة", since: "2025", bio: en ? "Goldsmith by training. Sees a glaze flaw at twenty paces." : "صائغٌ تدرَّب في الورش. يرى عيب الطلاء من بُعد.", tone: "linear-gradient(140deg, #7b8463, #4d5640)" },
              { name: "Sherif Adly", ar: "شريف عدلي", role: en ? "Operations" : "العمليّات", since: "2025", bio: en ? "Spreadsheets, shipping, the difficult phone calls." : "الجداول، الشحن، المكالمات الصعبة.", tone: "linear-gradient(140deg, #c26342, #8a3c22)" },
              { name: "Youmna Nabil", ar: "يمنى نبيل", role: en ? "Editor" : "المحرِّرة", since: "2026", bio: en ? "Writes the journal. Photographs every new piece." : "تكتب المجلّة. تصوِّر كلّ قطعة جديدة.", tone: "linear-gradient(140deg, #caa76c, #7d6635)" },
            ].map((p, i) => (
              <div key={i} style={{
                background: "var(--paper-2)", border: "1px solid var(--line-2)", borderRadius: 16,
                overflow: "hidden", display: "flex", flexDirection: "column",
              }}>
                <div style={{ aspectRatio: "1", background: p.tone, position: "relative" }}>
                  <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 30% 30%, rgba(255,235,200,0.22), transparent 60%)" }} />
                  <div style={{ position: "absolute", top: 14, left: 14, padding: "3px 10px", borderRadius: 999, background: "rgba(244,237,226,0.92)", fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink)" }}>
                    {en ? "Since" : "منذ"} {p.since}
                  </div>
                  <div style={{ position: "absolute", bottom: 14, left: 14, right: 14, color: "var(--paper)" }}>
                    <div style={{ fontFamily: "var(--ff-display)", fontSize: 24, lineHeight: 1.1 }}>{p.name}</div>
                    <div style={{ fontFamily: "var(--ff-display)", fontSize: 16, fontStyle: "italic", opacity: 0.85, marginTop: 2 }}>{p.ar}</div>
                  </div>
                </div>
                <div style={{ padding: "18px 20px" }}>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)", fontWeight: 500 }}>{p.role}</div>
                  <p style={{ marginTop: 8, fontSize: 13, lineHeight: 1.6, color: "var(--olive)" }}>{p.bio}</p>
                </div>
              </div>
            ))}
          </div>
          <style>{`
            @media (max-width: 1000px) { .os-team { grid-template-columns: repeat(2, 1fr) !important; } }
            @media (max-width: 540px)  { .os-team { grid-template-columns: 1fr !important; } }
          `}</style>
        </div>
      </section>

      {/* ——— VIII. CTA — invitation ——— */}
      <section style={{ padding: "100px 0 120px", background: "var(--paper-2)", borderTop: "1px solid var(--line-2)", position: "relative" }}>
        <div className="container-wide" style={{ maxWidth: 980, margin: "0 auto", padding: "0 32px", textAlign: "center" }}>
          {/* small star */}
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 22, opacity: 0.85 }}>
            <Star8 size={18} color="var(--terracotta)" />
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--terracotta)" }}>
            {en ? "viii. Come walk through the work" : "ثامنًا · تعالَ نتجوَّل في الصنعة"}
          </div>
          <h2 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(36px, 4.5vw, 56px)", lineHeight: 1.1 }}>
            {en ? "We don't have a doorstep." : "ليس لنا عتبةٌ بعد."} <span style={{ fontStyle: "italic", color: "var(--terracotta)", display: "block", marginTop: 6 }}>{en ? "We have the work." : "لكنّ لنا الصنعة."}</span>
          </h2>
          <p style={{ marginTop: 24, fontSize: 17, color: "var(--olive)", maxWidth: 640, margin: "24px auto 0", lineHeight: 1.7 }}>
            {en
              ? "Until a real house is right for the makers we serve, the work itself is our front room. Walk through it. Read the maker pages. Watch a piece take shape. Or, when we travel — Tunis village, Dahab, Old Cairo — come find us at the next pop-up."
              : "إلى أن يكون البيتُ الماديّ صائبًا للصنّاع الذين نخدمهم، الصنعةُ نفسُها هي صالتنا الأماميّة. تجوَّلْ فيها. اقرأ صفحات الصنّاع. شاهد قطعةً تتشكَّل. أو، حين نسافر — قرية تونس، دهب، القاهرة القديمة — تعالَ نلتقي في المحطّة التالية."
            }
          </p>
          <div style={{ marginTop: 38, display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
            <a href="#/makers" className="btn">{en ? "Meet the makers" : "تعرَّف على الصنّاع"} →</a>
            <a href="#/atelier/visit" className="btn ghost">{en ? "Next pop-up" : "المحطّة التالية"}</a>
          </div>
          {/* closing seal */}
          <div style={{ marginTop: 56, display: "inline-flex", alignItems: "center", gap: 14, padding: "12px 22px", border: "1px solid var(--line-2)", borderRadius: 999, background: "var(--paper)", color: "var(--terracotta)" }}>
            <Star8 size={12} color="currentColor" />
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.32em", textTransform: "uppercase", fontWeight: 500 }}>{en ? "Made with ṣanʿah" : "مصنوع"}</span>
            <span style={{ fontFamily: "var(--ff-ar)", fontSize: 16, direction: "rtl" }}>بصَنْعة</span>
          </div>
        </div>
      </section>
    </>
  );
}

function AtelierPage({ t, lang }) {
  return (
    <>
      <Breadcrumbs crumbs={[{ label: lang === "en" ? "Atelier" : "المحترف" }]} lang={lang} />
      <PageHeader
        eyebrow={lang === "en" ? "The house · Zamalek, Cairo" : "البيت · الزمالك، القاهرة"}
        title={lang === "en" ? "A small house" : "بيتٌ صغير"}
        titleIt={lang === "en" ? "for the Egyptian hand." : "لليد المصريّة."}
        kicker={t.atelier_body}
      />
      <SubNav activeKey="about" tabs={[
        { k: "about", label: lang === "en" ? "Our story" : "قصّتنا", to: "/atelier" },
        { k: "process", label: lang === "en" ? "Our process" : "العمليّة", to: "/atelier/process" },
        { k: "visit", label: lang === "en" ? "Book a visit" : "احجز زيارة", to: "/atelier/visit" },
        { k: "workshops", label: lang === "en" ? "Workshops" : "ورش", to: "/atelier/workshops" },
      ]} />
      <OurStory lang={lang} />
    </>
  );
}
function VisitPage({ t, lang }) {
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Atelier" : "المحترف", to: "/atelier" }, { label: lang === "en" ? "Visit" : "زيارة" }]} lang={lang} />
    <SubNav activeKey="visit" tabs={[
      { k: "about", label: lang === "en" ? "Our story" : "قصّتنا", to: "/atelier" },
      { k: "process", label: lang === "en" ? "Our process" : "العمليّة", to: "/atelier/process" },
      { k: "visit", label: lang === "en" ? "Book a visit" : "احجز زيارة", to: "/atelier/visit" },
      { k: "workshops", label: lang === "en" ? "Workshops" : "ورش", to: "/atelier/workshops" },
    ]} />
    <Visit t={t} lang={lang} />
  </>);
}
function ProcessPage({ t, lang }) {
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Atelier" : "المحترف", to: "/atelier" }, { label: lang === "en" ? "Process" : "العمليّة" }]} lang={lang} />
    <SubNav activeKey="process" tabs={[
      { k: "about", label: lang === "en" ? "Our story" : "قصّتنا", to: "/atelier" },
      { k: "process", label: lang === "en" ? "Our process" : "العمليّة", to: "/atelier/process" },
      { k: "visit", label: lang === "en" ? "Book a visit" : "احجز زيارة", to: "/atelier/visit" },
      { k: "workshops", label: lang === "en" ? "Workshops" : "ورش", to: "/atelier/workshops" },
    ]} />
    <Atelier t={t} lang={lang} />
    <CraftTrail t={t} lang={lang} />
  </>);
}

// ————————————————————— WORKSHOPS —————————————————————
// Bilingual workshop-level labels. Keyed by the English label that both the
// editorial fallback (WORKSHOPS) and the live transform emit, plus the raw DB
// `level` enum values, so the badge localizes in AR without touching data.
const WORKSHOP_LEVELS = {
  "Beginner":         { en: "Beginner", ar: "للمبتدئين" },
  "beginner":         { en: "Beginner", ar: "للمبتدئين" },
  "Intermediate":     { en: "Intermediate", ar: "متوسّط" },
  "intermediate":     { en: "Intermediate", ar: "متوسّط" },
  "Advanced":         { en: "Advanced", ar: "متقدّم" },
  "advanced":         { en: "Advanced", ar: "متقدّم" },
  "All levels":       { en: "All levels", ar: "كل المستويات" },
  "Private session":  { en: "Private session", ar: "جلسة خاصّة" },
  "private":          { en: "Private session", ar: "جلسة خاصّة" },
  "Tailored":         { en: "Tailored", ar: "مُفصّلة" },
};
function fmtLevel(level, lang) {
  if (!level) return "";
  const hit = WORKSHOP_LEVELS[level];
  return hit ? hit[lang] : level;
}
// Localize a duration label ("3 hours", "3h", "45min", "By arrangement").
// Pulls out the numeric part (AR-Indic in Arabic) and translates the unit;
// non-numeric values (e.g. "By arrangement") fall back to a bilingual phrase.
function fmtLen(len, lang) {
  if (len == null || len === "") return "";
  const s = String(len);
  const m = s.match(/(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|min|mins|minute|minutes)/i);
  if (!m) {
    if (lang === "en") return s;
    if (/arrangement/i.test(s)) return "حسب الاتّفاق";
    return s; // leave anything unrecognized as-is
  }
  const num = Number(m[1]);
  const numStr = num.toLocaleString(lang === "ar" ? "ar-EG" : "en-US");
  const isHour = /^h/i.test(m[2]) || /hour/i.test(m[2]);
  if (lang === "en") return isHour ? `${numStr}h` : `${numStr}min`;
  return isHour
    ? `${numStr} ${num === 1 ? "ساعة" : (num === 2 ? "ساعتان" : "ساعات")}`
    : `${numStr} د`;
}
const WORKSHOPS = [
  { slug: "macrame-intro", title: "Macramé · First knots", ar: "مكرمية · أوّل العقد", host: "Nour Ibrahim", len: "3 hours", size: 6, price: 850, level: "Beginner", tone: "sand", date: "Sat · 18 Apr", time: "10:00 – 13:00", seats: 3, blurb: "Learn four foundational knots and leave with a small wall hanging of your own." },
  { slug: "ceramics-wheel", title: "Ceramics · Wheel basics", ar: "فخار · الدولاب", host: "Hassan El-Fustati", len: "4 hours", size: 4, price: 1200, level: "Beginner", tone: "terracotta", date: "Sun · 26 Apr", time: "11:00 – 15:00", seats: 1, blurb: "One morning at the wheel in Fustat. Your piece is fired and posted to you two weeks later." },
  { slug: "candle-pouring", title: "Scent · Candle pouring", ar: "شموع · السكب", host: "Layla Abd-el-Raheem", len: "2 hours", size: 8, price: 620, level: "All levels", tone: "gold", date: "Fri · 02 May", time: "18:00 – 20:00", seats: 5, blurb: "Blend two signature notes and pour a 220g candle to take home the same evening." },
  { slug: "resin-tray", title: "Resin · Stone & river", ar: "راتنج · حجر ونهر", host: "Karim Hamed", len: "5 hours", size: 4, price: 1480, level: "Intermediate", tone: "olive", date: "Sat · 10 May", time: "10:00 – 15:00", seats: 2, blurb: "Cast and sand an alabaster-aggregate tray. A quiet, slow workshop — lunch included." },
  { slug: "palm-weaving", title: "Palm fibre · Weaving", ar: "سعف · نسج", host: "Fayrouz Mostafa", len: "3 hours", size: 6, price: 780, level: "Beginner", tone: "sand", date: "Sun · 18 May", time: "10:00 – 13:00", seats: 6, blurb: "A classical Minya weave — taught outdoors on the atelier roof, with mint tea." },
  { slug: "private-studio", title: "Private · One-on-one", ar: "خاص · فردي", host: "Any maker", len: "By arrangement", size: 1, price: null, level: "Tailored", tone: "terracotta", date: "On request", time: "—", seats: 1, blurb: "A tailored session in your chosen craft. Write to us and we'll match a maker to you." },
];

function WorkshopsPage({ t, lang }) {
  const [filter, setFilter] = React.useState("all");
  // Live-first: published workshops from DB. Falls back to the hardcoded
  // editorial preview only while the table is empty (closed-beta seeding).
  const live = window.useWorkshops();
  const liveTransformed = live.map(w => {
    const minutes = w.duration_minutes || 0;
    const hours = minutes / 60;
    const len = hours >= 1
      ? `${Number.isInteger(hours) ? hours : hours.toFixed(1)}h`
      : `${minutes}min`;
    const seatsLeft = Math.max(0, (w.seats_total || 0) - (w.seats_taken || 0));
    const levelLabel = w.level === "beginner" ? "Beginner"
      : w.level === "intermediate" ? "Intermediate"
      : w.level === "private" ? "Private session"
      : (w.level || "All levels");
    const titleEn = w.title_en || "";
    return {
      slug: w.slug,
      title: lang === "en" ? titleEn : (w.title_ar || titleEn),
      ar: w.title_ar || "",
      blurb: lang === "en" ? (w.description_en || "") : (w.description_ar || w.description_en || ""),
      len,
      level: levelLabel,
      seats: seatsLeft,
      size: w.seats_total || 0,
      date: w.starts_at
        ? new Date(w.starts_at).toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB",
            { weekday: "short", day: "numeric", month: "short" })
        : "",
      host: w.makers?.name_en || "",
      maker_code: w.makers?.maker_code || "",
      city: w.city_en || w.makers?.city_en || "",
      price: Math.round((w.price_piastres || 0) / 100),
      tone: "sand",
    };
  });
  const source = liveTransformed.length > 0 ? liveTransformed : WORKSHOPS;
  const filtered = filter === "all" ? source : source.filter(w => {
    if (filter === "beginner") return w.level === "Beginner" || w.level === "All levels";
    if (filter === "full-day") return parseInt(w.len) >= 4;
    if (filter === "private") return w.size === 1;
    return true;
  });
  return (<>
    <Breadcrumbs crumbs={[
      { label: lang === "en" ? "Atelier" : "المحترف", to: "/atelier" },
      { label: lang === "en" ? "Workshops" : "ورش" },
    ]} lang={lang} />
    <SubNav activeKey="workshops" tabs={[
      { k: "about", label: lang === "en" ? "Our story" : "قصّتنا", to: "/atelier" },
      { k: "process", label: lang === "en" ? "Our process" : "العمليّة", to: "/atelier/process" },
      { k: "visit", label: lang === "en" ? "Book a visit" : "احجز زيارة", to: "/atelier/visit" },
      { k: "workshops", label: lang === "en" ? "Workshops" : "ورش", to: "/atelier/workshops" },
    ]} />
    <PageHeader
      eyebrow={lang === "en" ? "Six workshops · Spring 2026" : "ستّ ورش · ربيع ٢٠٢٦"}
      title={lang === "en" ? "Come learn" : "تعلّم"}
      titleIt={lang === "en" ? "from the hands." : "من الأيدي."}
      kicker={lang === "en"
        ? "Small groups — no more than eight, often as few as four. Each workshop is taught by the maker themselves, in their own workshop or ours. Tea, materials, and your finished piece are included."
        : "مجموعات صغيرة — لا تتجاوز ثمانية. كل ورشة يقدّمها الصانع بنفسه. الشاي والمواد والقطعة النهائيّة متضمّنة."}
    />
    <section style={{ padding: "20px 0 30px", background: "var(--paper)", borderBottom: "1px solid var(--line-2)" }}>
      <div className="container-wide" style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
        {[
          { k: "all", l: lang === "en" ? "All workshops" : "كل الورش", c: source.length },
          { k: "beginner", l: lang === "en" ? "Beginner-friendly" : "للمبتدئين", c: source.filter(w => w.level === "Beginner" || w.level === "All levels").length },
          { k: "full-day", l: lang === "en" ? "Half & full day" : "نصف / كامل يوم", c: source.filter(w => parseInt(w.len) >= 4).length },
          { k: "private", l: lang === "en" ? "Private session" : "خاصّة", c: source.filter(w => w.size === 1).length },
        ].map(f => (
          <button key={f.k} onClick={() => setFilter(f.k)} style={{
            padding: "8px 16px", border: "1px solid var(--line)", borderRadius: 999,
            background: filter === f.k ? "var(--ink)" : "transparent",
            color: filter === f.k ? "var(--paper)" : "var(--ink)",
            fontFamily: "var(--ff-sans)", fontSize: 13, cursor: "pointer",
          }}>{f.l} <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, opacity: 0.6, marginLeft: 6 }}>({f.c})</span></button>
        ))}
      </div>
    </section>
    <section style={{ padding: "60px 0 80px", background: "var(--paper)" }}>
      <div className="container-wide help-grid" style={{ gap: 32 }}>
        {filtered.map((w, i) => (
          <article key={i} className="help-row" style={{ border: "1px solid var(--line-2)", borderRadius: 14, overflow: "hidden", background: "var(--paper)" }}>
            <div style={{ position: "relative" }}>
              <Placeholder tone={w.tone} topLabel={`W.${String(i + 1).padStart(2, "0")}`} label={w.title.toLowerCase()} meta={fmtLevel(w.level, lang)} />
            </div>
            <div style={{ padding: "24px 26px", display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{fmtLevel(w.level, lang)} · {fmtLen(w.len, lang)}</div>
                <div style={{
                  fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase",
                  padding: "3px 10px", borderRadius: 999,
                  background: w.seats <= 2 ? "rgba(194, 99, 66, 0.1)" : "var(--paper-2)",
                  color: w.seats <= 2 ? "var(--terracotta)" : "var(--olive)",
                }}>{w.seats === 1 ? (lang === "en" ? "1 seat" : "مقعد واحد") : (lang === "en" ? `${w.seats} seats left` : `${w.seats.toLocaleString("ar-EG")} مقاعد`)}</div>
              </div>
              <div>
                <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 28, lineHeight: 1.05 }}>{w.title}</h3>
                <div className="ar" style={{ fontSize: 16, color: "var(--terracotta)", marginTop: 4 }}>{w.ar}</div>
              </div>
              <p style={{ fontSize: 14, color: "var(--olive)", lineHeight: 1.55, margin: "4px 0 6px" }}>{w.blurb}</p>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", display: "flex", gap: 14, flexWrap: "wrap", alignItems: "center" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="calendar" size={11} /> {w.date}</span>
                <span>{w.time}</span>
                <span>· {w.host}</span>
              </div>
              <div style={{ marginTop: "auto", paddingTop: 14, display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid var(--line-2)" }}>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 26 }}>{w.price ? window.fmtPrice(w.price, lang) : (lang === "en" ? "On request" : "حسب الطلب")}</div>
                <a className="btn" href={`#/atelier/workshops/${encodeURIComponent(w.slug)}`}>{w.seats === 0 ? (lang === "en" ? "Waitlist" : "قائمة الانتظار") : (lang === "en" ? "Reserve" : "احجز")} →</a>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
    <section style={{ padding: "80px 0", background: "var(--ink)", color: "var(--paper)" }}>
      <div className="container" style={{ maxWidth: 820, textAlign: "center" }}>
        <Star8 size={16} color="var(--gold-soft)" />
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 56, marginTop: 20, lineHeight: 1.05 }}>
          {lang === "en" ? "Gift a workshop." : "اهدِ ورشة."}
          <span style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>{lang === "en" ? " A good afternoon." : " ظهيرة جميلة."}</span>
        </h2>
        <p style={{ marginTop: 20, fontSize: 16, color: "rgba(244,237,226,0.72)", lineHeight: 1.65 }}>
          {lang === "en" ? "A gift card for any workshop, redeemable for twelve months. Wax-sealed, handwritten note, delivered in Cairo or posted anywhere." : "بطاقة هديّة لأيّة ورشة، سارية لمدّة ١٢ شهرًا."}
        </p>
        <div style={{ marginTop: 30, display: "flex", gap: 14, justifyContent: "center" }}>
          <a className="btn" href="#/gifts">{lang === "en" ? "Buy a workshop card" : "اشترِ بطاقة"} →</a>
          <a className="btn ghost" style={{ color: "var(--paper)", borderColor: "rgba(244,237,226,0.3)" }} href="#/help">{lang === "en" ? "FAQ about workshops" : "أسئلة شائعة"}</a>
        </div>
      </div>
    </section>
  </>);
}

// ————————————————————— JOURNAL —————————————————————
const ARTICLES = [
  { slug: "fustat-kilns", tag: "Field note", date: "Apr · 2026", title: "Three days in Fustat: the kilns that refused to close", read: "6 min", tone: "terracotta", shape: "pointed", author: "Salma Abou-Zeid", excerpt: "We spent a week with the last six potters of Old Cairo's pottery quarter. Their kilns have been hot since the 9th century. Here's why that matters in 2026." },
  { slug: "nour-grandmother", tag: "Maker", date: "Mar · 2026", title: "Nour learned to knot from her grandmother in Siwa, 1993", read: "4 min", tone: "sand", shape: "horseshoe", author: "Salma Abou-Zeid", excerpt: "A short film and a long conversation with Nour Ibrahim about inheritance, dialect, and the four knots her grandmother insisted she remember." },
  { slug: "tiered-packaging", tag: "Process", date: "Feb · 2026", title: "Why we tier our packaging — and what 'fragile' actually costs", read: "7 min", tone: "olive", shape: "square", author: "Operations · Mariam H.", excerpt: "An honest accounting of what it takes to get a hand-thrown bowl from Fustat to Stockholm intact. Numbers, mistakes, and the day we changed couriers." },
  { slug: "ward-el-nil-notes", tag: "Maker", date: "Feb · 2026", title: "Ward el-Nil: what jasmine smells like at four in the morning", read: "5 min", tone: "gold", shape: "circle", author: "Layla Abd-el-Raheem", excerpt: "Layla writes from Beheira, where the jasmine harvest begins before sunrise. Field notes, recipes, and the fragrance she has been chasing for nine years." },
  { slug: "lead-cadmium", tag: "Standards", date: "Jan · 2026", title: "How we test every glaze for lead and cadmium", read: "9 min", tone: "terracotta", shape: "keel", author: "Quality · Dr. Yara N.", excerpt: "An open document on our testing protocol, the labs we partner with, and why we publish every result — including the ones we wish we hadn't." },
  { slug: "oasis-siwa", tag: "Field note", date: "Dec · 2025", title: "An oasis, a loom, and a very slow afternoon", read: "8 min", tone: "sand", shape: "arch", author: "Salma Abou-Zeid", excerpt: "Notes from a week in Siwa with two weavers who refuse to use synthetic dye, even when it costs them a wholesale buyer." },
];
function JournalPage({ t, lang }) {
  // Live-first journal posts; falls back to the editorial preview when the
  // table is empty so the page never goes blank during the beta.
  const live = window.useJournal();
  const liveTransformed = live.map(p => ({
    slug: p.slug,
    title: lang === "en" ? p.title_en : (p.title_ar || p.title_en),
    tag: p.tag || "Journal",
    excerpt: lang === "en" ? (p.dek_en || "") : (p.dek_ar || p.dek_en || ""),
    date: p.published_at
      ? new Date(p.published_at).toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB",
          { day: "numeric", month: "short", year: "numeric" })
      : "",
    read: p.read_minutes ? `${p.read_minutes} min` : "",
    author: p.profiles?.full_name || "SANAA editorial",
    tone: "sand",
    shape: "square",
    _body: lang === "en" ? p.body_en : (p.body_ar || p.body_en),
    _hero: p.cover_image,
  }));
  const source = liveTransformed.length > 0 ? liveTransformed : ARTICLES;
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Journal" : "اليوميّات" }]} lang={lang} />
    <PageHeader
      eyebrow={lang === "en" ? `Notes from the atelier · ${source.length} ${source.length === 1 ? "piece" : "pieces"}` : `ملاحظات · ${source.length} مقالة`}
      title={lang === "en" ? "The" : "اليوميّات،"}
      titleIt={lang === "en" ? "journal." : "رسائل متأنّية."}
      kicker={lang === "en" ? "Field notes, maker stories, and long reads on the craft. Published slowly." : "ملاحظات ميدانيّة وقصص صنّاع."}
    />
    <section style={{ padding: "60px 0 120px", background: "var(--paper)" }}>
      <div className="container-wide journal-grid">
        {source.map((j, i) => (
          <a key={i} href={"#/journal/" + j.slug} className={i === 0 ? "journal-feature" : ""} style={{ textDecoration: "none", color: "inherit", gridColumn: i === 0 ? "1 / span 2" : "auto" }}>
            <div style={{ aspectRatio: i === 0 ? "1.6" : "0.95", overflow: "hidden", marginBottom: 18 }}>
              <Placeholder tone={j.tone} shape={j.shape || "square"} topLabel={j.tag} label={j.title.toLowerCase()} meta={j.date} alt={j.title} />
            </div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>
              <span style={{ color: "var(--terracotta)" }}>{j.tag}</span> · {j.date} · {j.read} · {j.author}
            </div>
            <h3 style={{ fontFamily: "var(--ff-display)", fontSize: i === 0 ? 38 : 24, lineHeight: 1.1, letterSpacing: "-0.01em" }}>{j.title}</h3>
            {j.excerpt && <p style={{ marginTop: 10, fontSize: 14, color: "var(--olive)", lineHeight: 1.6, maxWidth: i === 0 ? 620 : 380 }}>{j.excerpt}</p>}
          </a>
        ))}
      </div>
    </section>
    <Letter t={t} lang={lang} />
  </>);
}

function ArticlePage({ t, lang, slug }) {
  const live = window.useJournal();
  // Live-first lookup by slug; fall back to the editorial preview only when
  // the DB row doesn't exist yet (closed-beta seeding).
  const livePost = live.find(p => p.slug === slug);
  const a = livePost
    ? {
        slug: livePost.slug,
        title: lang === "en" ? livePost.title_en : (livePost.title_ar || livePost.title_en),
        tag: livePost.tag || "Journal",
        date: livePost.published_at
          ? new Date(livePost.published_at).toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB",
              { day: "numeric", month: "short", year: "numeric" })
          : "",
        read: livePost.read_minutes ? `${livePost.read_minutes} min` : "",
        author: livePost.profiles?.full_name || "SANAA editorial",
        tone: "sand",
        _body: lang === "en" ? livePost.body_en : (livePost.body_ar || livePost.body_en),
        _hero: livePost.cover_image,
      }
    : (ARTICLES.find(x => x.slug === slug) || ARTICLES[0]);
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Journal" : "اليوميّات", to: "/journal" }, { label: a.title }]} lang={lang} />
    <article style={{ padding: "70px 0 100px", background: "var(--paper)" }}>
      <div className="container" style={{ maxWidth: 780 }}>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 22 }}>
          <span style={{ color: "var(--terracotta)" }}>{a.tag}</span> · {a.date} · {a.read} · {a.author}
        </div>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(44px, 5vw, 72px)", lineHeight: 1.05, letterSpacing: "-0.02em" }}>{a.title}</h1>
        <div style={{ aspectRatio: "1.7", margin: "40px 0", borderRadius: 12, overflow: "hidden" }}>
          {a._hero
            ? <img src={a._hero} alt={a.title} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} loading="lazy" />
            : <Placeholder tone={a.tone} label={a.title.toLowerCase()} meta={a.date} topLabel="Hero" alt={a.title} />}
        </div>
        {(() => {
          // Treat any leftover editorial placeholder as "not yet written" so a
          // visitor never sees Lorem. We render the real body only when it is a
          // non-empty string that doesn't carry the old placeholder marker.
          const body = typeof a._body === "string" ? a._body.trim() : "";
          const isPlaceholder = !body || /placeholder paragraph body|فقرة نائبة/i.test(body);
          if (!isPlaceholder) {
            // Render real body as paragraphs (split on blank lines). Preserves
            // editorial typography without introducing a markdown lib.
            return body.split(/\n\s*\n/).map((para, i) => (
              <p key={i} style={{ fontSize: 18, lineHeight: 1.75, color: "var(--ink)", marginBottom: 24, whiteSpace: "pre-wrap" }}>{para.trim()}</p>
            ));
          }
          // Calm "being written" state — no fake editorial, no Lorem.
          return (
            <div style={{ margin: "48px 0", padding: "48px 36px", textAlign: "center", border: "1px solid var(--line-2)", borderRadius: 14, background: "var(--paper-2)" }}>
              <div style={{ display: "flex", justifyContent: "center", marginBottom: 22, opacity: 0.85 }}>
                <Star8 size={20} color="var(--terracotta)" />
              </div>
              <h2 style={{ fontFamily: "var(--ff-display)", fontStyle: "italic", fontSize: "clamp(26px, 3vw, 36px)", lineHeight: 1.2, color: "var(--ink)" }}>
                {lang === "en" ? "This piece is being written." : "هذه المقالة قيد الكتابة."}
              </h2>
              <p style={{ marginTop: 16, fontSize: 16, color: "var(--olive)", lineHeight: 1.7, maxWidth: 460, margin: "16px auto 0" }}>
                {lang === "en"
                  ? "We publish the journal slowly, by hand. Come back soon — or read another note in the meantime."
                  : "ننشر اليوميّات على مهلٍ، باليد. عُد قريبًا — أو اقرأ ملاحظةً أخرى في انتظار ذلك."}
              </p>
              <a href="#/journal" className="btn ghost" style={{ marginTop: 28 }}>
                {lang === "en" ? "Back to the journal" : "العودة إلى اليوميّات"} →
              </a>
            </div>
          );
        })()}
      </div>
    </article>
  </>);
}

// ————————————————————— GIFTS / HELP / ACCOUNT / APPLY —————————————————————
function GiftsPage({ t, lang }) {
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Gifts" : "الهدايا" }]} lang={lang} />
    <PageHeader
      eyebrow={lang === "en" ? "Gifting house" : "بيت الهدايا"}
      title={lang === "en" ? "Four guides," : "أربعة أدلّة،"}
      titleIt={lang === "en" ? "one good decision." : "قرارٌ جيّد."}
      kicker={lang === "en" ? "Wax-sealed, handwritten note card, free wrap. Egypt next-day, region in three." : "ختم شمع، بطاقة بخطّ اليد، تغليف مجّاني."}
    />
    <GiftGuide t={t} lang={lang} />
    <section style={{ padding: "80px 0", background: "var(--paper)" }}>
      <div className="container" style={{ maxWidth: 800, textAlign: "center" }}>
        <div className="eyebrow" style={{ justifyContent: "center", marginBottom: 18 }}><span className="dot"></span>{lang === "en" ? "Gift cards" : "بطاقات هدايا"}</div>
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 56 }}>{lang === "en" ? "When you cannot choose, let them choose." : "عندما لا تستطيع أن تختار."}</h2>
        <div style={{ marginTop: 30, display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
          {[500, 1000, 2500, 5000].map(v => (
            <button key={v} className="btn ghost">{window.fmtPrice(v, lang)}</button>
          ))}
        </div>
      </div>
    </section>
  </>);
}

function HelpPage({ t, lang }) {
  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Help" : "مساعدة" }]} lang={lang} />
    <PageHeader
      eyebrow={lang === "en" ? "Help centre" : "مركز المساعدة"}
      title={lang === "en" ? "How can we" : "كيف يمكننا"}
      titleIt={lang === "en" ? "help?" : "المساعدة؟"}
      kicker={lang === "en" ? "Most answers are here. If not, a real human replies within the day at hello@sanaa.eg." : "أغلب الإجابات هنا."}
    />
    <section style={{ padding: "60px 0", background: "var(--paper-2)" }}>
      <div className="container-wide stat-grid-4">
        {[
          { t: "Shipping & tracking", ar: "الشحن", c: 7 },
          { t: "Returns", ar: "الإرجاع", c: 5 },
          { t: "Product care", ar: "العناية", c: 9 },
          { t: "Commissions", ar: "الطلبات الخاصة", c: 6 },
          { t: "Gift cards", ar: "بطاقات هدايا", c: 4 },
          { t: "Wholesale", ar: "الجملة", c: 3 },
          { t: "Account & orders", ar: "الحساب", c: 8 },
          { t: "Payments", ar: "الدفع", c: 5 },
        ].map((c, i) => (
          <a key={i} href="#/help" style={{ textDecoration: "none", color: "inherit", padding: "28px 24px", border: "1px solid var(--line)", borderRadius: 14, background: "var(--paper)", display: "block" }}>
            <Star8 size={14} color="var(--terracotta)" />
            <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 24, marginTop: 16 }}>{c.t}</h3>
            <div className="ar" style={{ fontSize: 14, color: "var(--muted)" }}>{c.ar}</div>
            <div style={{ marginTop: 12, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>{c.c} {lang === "en" ? "articles" : "مقالات"} →</div>
          </a>
        ))}
      </div>
    </section>
    <FAQ t={t} lang={lang} />
  </>);
}

// Customer return-request modal — schema-backed (return_requests table).
// Customer-facing reason codes match the spec's intent (damaged / not-as-
// described / wrong-item / changed-mind / other). Photo upload deferred —
// adds storage friction in the closed beta.
function ReturnRequestModal({ open, onClose, lang, order, onSubmitted }) {
  const [reason, setReason] = React.useState("damaged");
  const [text, setText] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    setReason("damaged"); setText(""); setErr(""); setDone(false);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  if (!open || !order) return null;

  const REASONS = [
    { k: "damaged",          en: "Arrived damaged",         ar: "وصلت تالفة" },
    { k: "not_as_described", en: "Not as described",        ar: "لا تطابق الوصف" },
    { k: "wrong_item",       en: "Wrong item shipped",      ar: "قطعة خاطئة" },
    { k: "changed_mind",     en: "Changed my mind (14d)",   ar: "غيّرت رأيي" },
    { k: "other",            en: "Other (please explain)",  ar: "آخر (وضّح)" },
  ];

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr("");
    const { error } = await window.sb.from("return_requests").insert({
      order_id: order.id,
      customer_id: order.user_id || (await window.sb.auth.getUser()).data.user?.id,
      reason_code: reason,
      reason_text: text || null,
    });
    setBusy(false);
    if (error) {
      console.warn("return_requests insert:", error.message);
      setErr(lang === "en" ? "We couldn't submit your request. Please try again." : "تعذّر إرسال طلبك. حاول مرّة أخرى.");
      return;
    }
    setDone(true);
    if (onSubmitted) onSubmitted();
    setTimeout(onClose, 1800);
  };

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(28,26,21,0.6)", zIndex: 92 }} />
      <div role="dialog" aria-modal="true" aria-label={lang === "en" ? "Request return" : "طلب إرجاع"}
        style={{ position: "fixed", top: "50%", left: "50%", transform: "translate(-50%, -50%)", zIndex: 93, width: "min(540px, 96vw)", maxHeight: "92vh", overflowY: "auto", background: "var(--paper)", borderRadius: 18, padding: "32px 32px 28px", boxShadow: "0 30px 80px -20px rgba(28,26,21,0.5)" }}>
        <button onClick={onClose} aria-label={lang === "en" ? "Close" : "إغلاق"} style={{ position: "absolute", top: 10, right: 14, background: "transparent", border: 0, fontSize: 22, cursor: "pointer", color: "var(--muted)", minWidth: 44, minHeight: 44, display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 0, lineHeight: 1 }}>×</button>
        {done ? (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <Star8 size={28} color="var(--olive)" />
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 30, marginTop: 16 }}>{lang === "en" ? "Return requested." : "تمّ طلب الإرجاع."}</h2>
            <p style={{ marginTop: 10, color: "var(--olive)", fontSize: 13, lineHeight: 1.55 }}>
              {lang === "en"
                ? "SANAA will reach out within one business day to coordinate pickup."
                : "سيتواصل فريق صَنعة خلال يوم عمل لترتيب الاستلام."}
            </p>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
              {order.order_number}
            </div>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 30, marginTop: 4, marginBottom: 12 }}>
              {lang === "en" ? "Request a return" : "طلب إرجاع"}
            </h2>
            <p style={{ fontSize: 13, color: "var(--olive)", marginBottom: 22, lineHeight: 1.55 }}>
              {lang === "en"
                ? "Returns are accepted within 14 days of delivery, in line with Egyptian Consumer Protection Agency rules. SANAA covers return shipping if we were at fault."
                : "نقبل الإرجاع خلال ١٤ يومًا من الاستلام، وفقًا لقواعد جهاز حماية المستهلك. شحن الإرجاع علينا إذا كان الخطأ منّا."}
            </p>
            <fieldset style={{ border: 0, padding: 0, margin: "0 0 18px 0" }}>
              <legend style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>
                {lang === "en" ? "Reason" : "السبب"}
              </legend>
              {REASONS.map(r => (
                <label key={r.k} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", cursor: "pointer", fontSize: 14 }}>
                  <input type="radio" name="reason" value={r.k}
                    checked={reason === r.k} onChange={() => setReason(r.k)}
                    style={{ accentColor: "var(--terracotta)" }} />
                  <span>{r[lang] || r.en}</span>
                </label>
              ))}
            </fieldset>
            <div style={{ marginBottom: 18 }}>
              <label htmlFor="return-text" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
                {lang === "en" ? "Tell us more (optional)" : "أخبرنا أكثر (اختياري)"}
              </label>
              <textarea id="return-text" rows={4} value={text} onChange={e => setText(e.target.value)}
                placeholder={lang === "en" ? "Anything we should know before we collect the piece?" : "أيّ تفاصيل قبل استلام القطعة؟"}
                style={{ display: "block", width: "100%", marginTop: 6, padding: "11px 14px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0, boxSizing: "border-box", resize: "vertical" }} />
            </div>
            {err && <div style={{ color: "var(--terracotta)", fontSize: 13, marginBottom: 12 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <button type="submit" disabled={busy} className="btn" style={{ opacity: busy ? 0.6 : 1 }}>
                {busy ? "…" : (lang === "en" ? "Submit return" : "إرسال")} →
              </button>
              <button type="button" onClick={onClose} className="btn ghost">
                {lang === "en" ? "Cancel" : "إلغاء"}
              </button>
            </div>
          </form>
        )}
      </div>
    </>
  );
}

function AccountPage({ t, lang, user }) {
  const [tab, setTab] = React.useState("orders");
  const [authMode, setAuthMode] = React.useState("login");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [name, setName] = React.useState("");
  const [authError, setAuthError] = React.useState("");
  const [authLoading, setAuthLoading] = React.useState(false);
  const [orders, setOrders] = React.useState([]);
  const [ordersLoading, setOrdersLoading] = React.useState(false);
  const [signupDone, setSignupDone] = React.useState(false);
  const [unreadMsgs, setUnreadMsgs] = React.useState(0);
  const [returns, setReturns] = React.useState([]);
  const [returnFor, setReturnFor] = React.useState(null); // order row when modal open
  const [bookings, setBookings] = React.useState([]);
  const [bookingsLoading, setBookingsLoading] = React.useState(true);
  const [cancellingId, setCancellingId] = React.useState(null);

  React.useEffect(() => {
    if (!user) return;
    setOrdersLoading(true);
    window.sb.from("orders")
      .select("id, order_number, created_at, total_piastres, status, delivered_at, order_items(id)")
      .eq("user_id", user.id)
      .order("created_at", { ascending: false })
      .limit(10)
      .then(({ data }) => { setOrders(data || []); setOrdersLoading(false); });

    // Per-order return state (one row per order if requested)
    window.sb.from("return_requests")
      .select("id, order_id, status, reason_code, created_at, resolved_at")
      .eq("customer_id", user.id)
      .order("created_at", { ascending: false })
      .then(({ data }) => setReturns(data || []));

    // Unread message count for the badge
    window.sb.from("conversations").select("unread_for_customer").eq("customer_id", user.id)
      .then(({ data }) => setUnreadMsgs((data || []).reduce((s, c) => s + (c.unread_for_customer || 0), 0)));

    // Workshop bookings (live)
    window.sb.from("workshop_bookings")
      .select("id, booking_ref, status, seats, total_piastres, waitlist_position, hold_expires_at, confirmed_at, cancelled_at, refund_status, placed_at, workshops:workshop_id(id, slug, title_en, title_ar, starts_at, duration_minutes, city_en, city_ar, address_en, address_ar, status, makers:host_maker_id(name_en, name_ar, slug))")
      .eq("user_id", user.id)
      .order("placed_at", { ascending: false })
      .then(({ data }) => { setBookings(data || []); setBookingsLoading(false); });
  }, [user && user.id, tab]);

  // Realtime: bump badge when conversations change (unconditional — hook handles null id internally)
  window.useRealtimeConversations("customer_id", user?.id, () => {
    if (!user) return;
    window.sb.from("conversations").select("unread_for_customer").eq("customer_id", user.id)
      .then(({ data }) => setUnreadMsgs((data || []).reduce((s, c) => s + (c.unread_for_customer || 0), 0)));
  });

  // Translate raw auth errors into SANAA-tone copy. Customers never see
  // "Invalid login credentials" / "AuthApiError" verbatim.
  const _authCopy = (raw) => {
    const t = ((raw && (raw.code || raw.message)) || "").toString().toLowerCase();
    if (t.includes("invalid login") || t.includes("invalid_credentials") || t.includes("invalid email") || t.includes("invalid_grant"))
      return lang === "en" ? "Those credentials didn't match. Please try again."
                           : "البيانات لا تطابق سجلّاتنا. حاول مرّة أخرى.";
    if (t.includes("user not found"))
      return lang === "en" ? "No account found with that email."
                           : "لا يوجد حساب بهذا البريد.";
    if (t.includes("user already") || t.includes("already registered"))
      return lang === "en" ? "An account with this email already exists. Sign in instead."
                           : "يوجد حساب بهذا البريد. سجّل الدخول.";
    if (t.includes("password") && t.includes("short"))
      return lang === "en" ? "Please choose a password of at least 8 characters."
                           : "اختر كلمة مرور لا تقلّ عن ٨ أحرف.";
    if (t.includes("rate limit") || t.includes("too many"))
      return lang === "en" ? "Too many attempts. Please pause for a minute and try again."
                           : "محاولات كثيرة. خذ دقيقة ثم حاول مرّة أخرى.";
    if (t.includes("network") || t.includes("failed to fetch"))
      return lang === "en" ? "We couldn't reach SANAA. Please check your connection and try again."
                           : "تعذّر الوصول. تأكّد من اتصالك وحاول مرّة أخرى.";
    return lang === "en" ? "We couldn't sign you in right now. Please try again in a moment."
                         : "تعذّر تسجيل دخولك الآن. حاول بعد قليل.";
  };

  const handleSignIn = async (e) => {
    e.preventDefault();
    setAuthError("");
    setAuthLoading(true);
    try {
      const { error } = await window.sb.auth.signInWithPassword({ email, password });
      if (error) setAuthError(_authCopy(error));
    } catch (ex) {
      setAuthError(_authCopy(ex));
      window._logClientError?.("signin_error", (ex && ex.message) || String(ex));
    } finally {
      setAuthLoading(false);
    }
  };

  const handleSignUp = async (e) => {
    e.preventDefault();
    setAuthError("");
    setAuthLoading(true);
    try {
      const { error } = await window.sb.auth.signUp({ email, password, options: { data: { full_name: name } } });
      if (error) setAuthError(_authCopy(error));
      else setSignupDone(true);
    } catch (ex) {
      setAuthError(_authCopy(ex));
      window._logClientError?.("signup_error", (ex && ex.message) || String(ex));
    } finally {
      setAuthLoading(false);
    }
  };

  const handleSignOut = () => window.sb.auth.signOut();

  if (!user) {
    if (signupDone) return (
      <>
        <Breadcrumbs crumbs={[{ label: lang === "en" ? "Account" : "الحساب" }]} lang={lang} />
        <section style={{ padding: "80px 0", background: "var(--paper)", textAlign: "center" }}>
          <div className="container" style={{ maxWidth: 480 }}>
            <Star8 size={32} color="var(--terracotta)" />
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 48, marginTop: 20 }}>
              {lang === "en" ? "Almost there." : "على وشك."}
            </h1>
            <p style={{ marginTop: 16, fontSize: 16, color: "var(--olive)", lineHeight: 1.6 }}>
              {lang === "en"
                ? "We sent a confirmation link to your email. Tap it to activate your account."
                : "أرسلنا رابط تأكيد إلى بريدك. انقر عليه لتفعيل حسابك."}
            </p>
          </div>
        </section>
      </>
    );

    return (
      <>
        <Breadcrumbs crumbs={[{ label: lang === "en" ? "Account" : "الحساب" }]} lang={lang} />
        <section style={{ padding: "80px 0", background: "var(--paper)" }}>
          <div className="container" style={{ maxWidth: 480 }}>
            <div style={{ marginBottom: 32, textAlign: "center" }}>
              <Star8 size={28} color="var(--terracotta)" />
              <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 48, marginTop: 16 }}>
                {authMode === "login" ? (lang === "en" ? "Welcome back." : "أهلًا مجدّدًا.") : (lang === "en" ? "Join the house." : "انضم للبيت.")}
              </h1>
            </div>
            <div style={{ display: "flex", gap: 0, marginBottom: 32, border: "1px solid var(--line)", borderRadius: 999, overflow: "hidden" }}>
              {[["login", lang === "en" ? "Sign in" : "دخول"], ["signup", lang === "en" ? "New account" : "حساب جديد"]].map(([mode, label]) => (
                <button key={mode} onClick={() => { setAuthMode(mode); setAuthError(""); }} style={{
                  flex: 1, padding: "12px 0", border: 0, cursor: "pointer",
                  background: authMode === mode ? "var(--ink)" : "transparent",
                  color: authMode === mode ? "var(--paper)" : "var(--muted)",
                  fontFamily: "var(--ff-sans)", fontSize: 14, transition: "all 0.2s",
                }}>{label}</button>
              ))}
            </div>
            <form onSubmit={authMode === "login" ? handleSignIn : handleSignUp} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              {authMode === "signup" && (
                <div>
                  <label htmlFor="acct-name" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", display: "block", marginBottom: 8 }}>{lang === "en" ? "Your name" : "اسمك"}</label>
                  <input id="acct-name" name="name" autoComplete="name" value={name} onChange={e => setName(e.target.value)} placeholder={lang === "en" ? "Nour Ibrahim" : "نور إبراهيم"} style={{ display: "block", width: "100%", padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15, outline: 0 }} />
                </div>
              )}
              <div>
                <label htmlFor="acct-email" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", display: "block", marginBottom: 8 }}>{lang === "en" ? "Email" : "البريد"}</label>
                <input id="acct-email" name="email" autoComplete="email" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" required style={{ display: "block", width: "100%", padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15, outline: 0 }} />
              </div>
              <div>
                <label htmlFor="acct-password" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", display: "block", marginBottom: 8 }}>{lang === "en" ? "Password" : "كلمة المرور"}</label>
                <input id="acct-password" name="password" autoComplete={authMode === "signup" ? "new-password" : "current-password"} type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" required style={{ display: "block", width: "100%", padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15, outline: 0 }} />
              </div>
              {authError && <div style={{ padding: "12px 16px", background: "rgba(194,99,66,0.08)", border: "1px solid rgba(194,99,66,0.3)", borderRadius: 10, fontSize: 14, color: "var(--terracotta)" }}>{authError}</div>}
              <button type="submit" className="btn" disabled={authLoading} style={{ marginTop: 8, justifyContent: "center", opacity: authLoading ? 0.6 : 1 }}>
                {authLoading ? (lang === "en" ? "One moment…" : "لحظة…") : authMode === "login" ? (lang === "en" ? "Sign in →" : "دخول →") : (lang === "en" ? "Create account →" : "إنشاء حساب →")}
              </button>
            </form>
          </div>
        </section>
      </>
    );
  }

  const displayName = (user.user_metadata && user.user_metadata.full_name) || (user.email ? user.email.split("@")[0] : (lang === "en" ? "there" : "بك"));
  return (
    <>
      <Breadcrumbs crumbs={[{ label: lang === "en" ? "Account" : "الحساب" }]} lang={lang} />
      <section style={{ padding: "60px 0", background: "var(--paper)" }}>
        <div className="container-wide">
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(34px, 6vw, 64px)" }}>{lang === "en" ? `Assalāmu ʿalaykum, ${displayName}.` : `أهلًا ${displayName}.`}</h1>
            <button onClick={handleSignOut} style={{ background: "transparent", border: "1px solid var(--line)", padding: "10px 20px", borderRadius: 999, cursor: "pointer", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
              {lang === "en" ? "Sign out" : "خروج"}
            </button>
          </div>
          <div style={{ marginTop: 8, fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", color: "var(--muted)" }}>{user.email}</div>
          <div className="shop-layout" style={{ marginTop: 50 }}>
            <nav className="account-nav" style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {[
                { k: "orders",    l: lang === "en" ? "Orders"           : "الطلبات",        c: orders.length || null },
                { k: "workshops", l: lang === "en" ? "Workshops"        : "الورش",          c: bookings.length || null },
                { k: "messages",  l: lang === "en" ? "Inbox"            : "صندوق الرسائل",  c: unreadMsgs || null, badge: unreadMsgs > 0 },
                { k: "saved",     l: lang === "en" ? "Saved pieces"     : "المحفوظات", soon: true },
                { k: "addresses", l: lang === "en" ? "Addresses"        : "العناوين",  soon: true },
                { k: "payment",   l: lang === "en" ? "Payment"          : "الدفع",     soon: true },
                { k: "account",   l: lang === "en" ? "Account settings" : "إعدادات الحساب" },
              ].map(x => {
                const isActive = tab === x.k;
                return (
                <button key={x.k} onClick={() => setTab(x.k)} style={{
                  textAlign: "left",
                  padding: "12px 14px 12px 16px",
                  borderRadius: 10,
                  background: isActive ? "var(--paper-2)" : "transparent",
                  color: isActive ? "var(--ink)" : "var(--muted)",
                  border: 0,
                  borderLeft: isActive ? "2px solid var(--terracotta)" : "2px solid transparent",
                  cursor: "pointer",
                  fontFamily: "var(--ff-sans)",
                  fontSize: 14,
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  transition: "background .15s, color .15s",
                }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    {x.badge && <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--terracotta)", flexShrink: 0 }} />}
                    {x.l}
                  </span>
                  {x.c != null && (
                    <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: x.badge ? "var(--terracotta)" : "var(--muted)", letterSpacing: "0.1em" }}>{x.c}</span>
                  )}
                  {x.soon && (
                    <span style={{ fontFamily: "var(--ff-mono)", fontSize: 8, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--muted)", border: "1px solid var(--line)", borderRadius: 999, padding: "2px 7px" }}>{lang === "en" ? "soon" : "قريبًا"}</span>
                  )}
                </button>
                );
              })}
            </nav>
            <div style={{ padding: 32, border: "1px solid var(--line)", borderRadius: 14 }}>
              {tab === "orders" && (
                <div>
                  <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 32, marginBottom: 24 }}>{lang === "en" ? "Your orders" : "طلباتك"}</h2>
                  {ordersLoading && <div style={{ color: "var(--muted)", fontFamily: "var(--ff-mono)", fontSize: 12, padding: "40px 0", textAlign: "center" }}>{lang === "en" ? "Loading…" : "جارٍ التحميل…"}</div>}
                  {!ordersLoading && orders.length === 0 && (
                    <div style={{ padding: "60px 0", textAlign: "center", color: "var(--muted)" }}>
                      <Star8 size={24} color="var(--gold)" />
                      <p style={{ marginTop: 20, fontFamily: "var(--ff-display)", fontSize: 22 }}>{lang === "en" ? "No orders yet." : "لا طلبات بعد."}</p>
                      <a href="#/shop" className="btn" style={{ display: "inline-flex", marginTop: 16 }}>{lang === "en" ? "Browse the shop" : "تصفّح المتجر"} →</a>
                    </div>
                  )}
                  {orders.map((o, i) => {
                    // Map internal order_status enum to the simplified
                    // customer-facing label (same logic as the
                    // _v_customer_order_status view server-side).
                    const cs = ({
                      pending: "pending_confirmation",
                      pending_confirmation: "pending_confirmation",
                      confirmed: "confirmed",
                      in_preparation: "in_preparation",
                      packed: "in_preparation",
                      ready_for_dispatch: "ready_for_dispatch",
                      shipped: "shipped",
                      delivered: "delivered",
                      return_requested: "return_requested",
                      returned: "returned",
                      refunded: "refunded",
                      cancelled: "cancelled",
                    })[o.status] || o.status;
                    const CUSTOMER_LABEL = {
                      pending_confirmation: lang === "en" ? "Pending confirmation" : "بانتظار التأكيد",
                      confirmed: lang === "en" ? "Confirmed" : "مؤكَّد",
                      in_preparation: lang === "en" ? "In preparation" : "قيد التحضير",
                      ready_for_dispatch: lang === "en" ? "Ready to ship" : "جاهز للشحن",
                      shipped: lang === "en" ? "Shipped" : "مُرسَل",
                      delivered: lang === "en" ? "Delivered" : "وصل",
                      return_requested: lang === "en" ? "Return requested" : "طلب إرجاع",
                      returned: lang === "en" ? "Returned" : "مُرجَع",
                      refunded: lang === "en" ? "Refunded" : "مستردّ",
                      cancelled: lang === "en" ? "Cancelled" : "ملغى",
                    };
                    const label = CUSTOMER_LABEL[cs] || cs;
                    const RETURN_LABEL = {
                      requested: lang === "en" ? "requested" : "مطلوب",
                      approved: lang === "en" ? "approved" : "مقبول",
                      rejected: lang === "en" ? "rejected" : "مرفوض",
                      received: lang === "en" ? "received" : "مُستلَم",
                      refunded: lang === "en" ? "refunded" : "مستردّ",
                      refund_failed: lang === "en" ? "refund failed" : "تعذّر الاسترداد",
                      cancelled: lang === "en" ? "cancelled" : "ملغى",
                    };
                    const positive = cs === "delivered";
                    // Return eligibility: delivered within the last 14 days
                    // and no existing open return for this order.
                    const existingReturn = returns.find(r => r.order_id === o.id);
                    let daysSinceDelivered = null;
                    if (o.delivered_at) {
                      daysSinceDelivered = Math.floor(
                        (Date.now() - new Date(o.delivered_at).getTime()) / 86_400_000
                      );
                    }
                    const canRequestReturn =
                      cs === "delivered" && daysSinceDelivered !== null &&
                      daysSinceDelivered <= 14 && !existingReturn;
                    // The whole row is a single editorial anchor — no
                    // separate "Track →" pill anymore. Clicking anywhere on
                    // the row opens the operational concierge view.
                    return (
                      <a key={o.id || i} href={`#/track/${encodeURIComponent(o.order_number)}`}
                        aria-label={lang === "en"
                          ? `Follow order ${o.order_number} · ${label}`
                          : `متابعة الطلب ${o.order_number} · ${label}`}
                        className="orders-row"
                        style={{
                          textDecoration: "none", color: "inherit",
                          display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr auto", gap: 20,
                          alignItems: "center",
                          padding: "22px 0", borderTop: "1px solid var(--line-2)",
                        }}>
                        <div>
                          <div style={{ fontFamily: "var(--ff-display)", fontSize: 22 }}>{o.order_number}</div>
                          <div style={{ marginTop: 2, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)" }}>
                            {window.fmtDate(o.created_at, lang, { day: "numeric", month: "short", year: "numeric" })}
                            {" · "}
                            {(o.order_items || []).length} {lang === "en" ? ((o.order_items || []).length === 1 ? "piece" : "pieces") : "قطع"}
                          </div>
                        </div>
                        <div style={{ fontFamily: "var(--ff-display)", fontSize: 20 }}>{Math.round((o.total_piastres || 0) / 100).toLocaleString(lang === "ar" ? "ar-EG" : "en-GB")} <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: "var(--muted)" }}>{lang === "en" ? "EGP" : "ج.م"}</span></div>
                        <div style={{ padding: "4px 12px", borderRadius: 999, display: "inline-block", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", background: positive ? "var(--paper-2)" : "rgba(194,99,66,0.1)", color: positive ? "var(--olive)" : "var(--terracotta)", justifySelf: "start" }}>{label}</div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
                          {existingReturn ? (
                            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--olive)", textTransform: "uppercase" }}>
                              {lang === "en" ? `Return · ${RETURN_LABEL[existingReturn.status] || existingReturn.status}` : `إرجاع · ${RETURN_LABEL[existingReturn.status] || existingReturn.status}`}
                            </span>
                          ) : canRequestReturn ? (
                            <button
                              onClick={(ev) => { ev.preventDefault(); ev.stopPropagation(); setReturnFor(o); }}
                              className="btn ghost"
                              style={{ padding: "8px 14px", fontSize: 11, minHeight: 36, letterSpacing: "0.18em" }}
                            >
                              {lang === "en" ? "Request return" : "طلب إرجاع"} →
                            </button>
                          ) : null}
                          <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--terracotta)", textTransform: "uppercase" }}>
                            {lang === "en" ? "Follow →" : "متابعة →"}
                          </span>
                        </div>
                      </a>
                    );
                  })}
                </div>
              )}
              {tab === "messages" && (
                <div>
                  <div style={{ marginBottom: 6, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
                    <span className="dot" style={{ display: "inline-block", width: 6, height: 6, background: "var(--terracotta)", borderRadius: "50%", marginRight: 10, verticalAlign: "middle" }}></span>
                    {lang === "en" ? "From the makers" : "من الصنّاع"}
                  </div>
                  <h2 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(28px, 3vw, 36px)", marginBottom: 4, letterSpacing: "-0.01em" }}>
                    {lang === "en" ? "Your inbox" : "صندوقك"}
                    {unreadMsgs > 0 && <span style={{ fontSize: "0.55em", color: "var(--terracotta)", marginLeft: 14, fontStyle: "italic", fontWeight: 400 }}>{unreadMsgs} {lang === "en" ? (unreadMsgs === 1 ? "new reply" : "new replies") : "جديد"}</span>}
                  </h2>
                  <p style={{ marginTop: 6, marginBottom: 24, fontSize: 13, color: "var(--olive)", fontStyle: "italic", maxWidth: 560 }}>
                    {lang === "en"
                      ? "Conversations between you and the makers behind your pieces."
                      : "محادثاتك مع الصنّاع."}
                  </p>
                  <CustomerMessages lang={lang} user={user} />
                </div>
              )}
              {tab === "account" && (
                <div>
                  <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 32, marginBottom: 24 }}>{lang === "en" ? "Account settings" : "إعدادات الحساب"}</h2>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase", marginBottom: 8 }}>{lang === "en" ? "Email" : "البريد"}</div>
                    <div style={{ fontFamily: "var(--ff-display)", fontSize: 24 }}>{user.email}</div>
                  </div>
                  <button onClick={handleSignOut} className="btn ghost" style={{ marginTop: 24 }}>{lang === "en" ? "Sign out →" : "خروج →"}</button>
                </div>
              )}
              {tab === "workshops" && (
                <div>
                  <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 32, marginBottom: 8 }}>{lang === "en" ? "Your workshops" : "ورشك"}</h2>
                  <p style={{ marginBottom: 24, fontSize: 13, color: "var(--olive)", fontStyle: "italic" }}>
                    {lang === "en"
                      ? "Upcoming and past bookings. WhatsApp reminders are sent the day before."
                      : "حجوزاتك القادمة والماضية. نُرسل تذكير واتساب اليوم السابق."}
                  </p>
                  {bookingsLoading && <div style={{ color: "var(--muted)", fontFamily: "var(--ff-mono)", fontSize: 12, padding: "40px 0", textAlign: "center" }}>{lang === "en" ? "Loading…" : "جارٍ التحميل…"}</div>}
                  {!bookingsLoading && bookings.length === 0 && (
                    <div style={{ padding: "60px 0", textAlign: "center", color: "var(--muted)" }}>
                      <Star8 size={24} color="var(--gold)" />
                      <p style={{ marginTop: 20, fontFamily: "var(--ff-display)", fontSize: 22 }}>{lang === "en" ? "No bookings yet." : "لا حجوزات بعد."}</p>
                      <a href="#/atelier/workshops" className="btn" style={{ display: "inline-flex", marginTop: 16 }}>{lang === "en" ? "Browse workshops" : "تصفّح الورش"} →</a>
                    </div>
                  )}
                  {bookings.map((b) => {
                    const w = b.workshops || {};
                    const startsAt = w.starts_at ? new Date(w.starts_at) : null;
                    const isPast = startsAt ? startsAt.getTime() < Date.now() : false;
                    const STATUS_LABEL = {
                      pending: { en: "Pending", ar: "قيد الانتظار", tone: "gold" },
                      pending_payment: { en: "Pending payment", ar: "بانتظار الدفع", tone: "gold" },
                      confirmed: { en: "Confirmed", ar: "مؤكَّد", tone: "olive" },
                      waitlisted: { en: "Waitlisted", ar: "قائمة الانتظار", tone: "gold" },
                      attended: { en: "Attended", ar: "حضرت", tone: "olive" },
                      no_show: { en: "Missed", ar: "لم تحضر", tone: "terracotta" },
                      cancelled: { en: "Cancelled", ar: "ملغى", tone: "muted" },
                      refunded: { en: "Refunded", ar: "مسترد", tone: "muted" },
                    }[b.status] || { en: b.status, ar: b.status, tone: "muted" };
                    const canCancel = ["pending","pending_payment","confirmed","waitlisted"].includes(b.status) && !isPast;
                    const refundEligible = canCancel && startsAt &&
                      (startsAt.getTime() - Date.now()) / 3_600_000 >= 48;
                    return (
                      <div key={b.id} style={{ padding: "20px 0", borderTop: "1px solid var(--line-2)", display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr auto", gap: 20, alignItems: "center" }}>
                        <div>
                          <a href={`#/atelier/workshops/${w.slug}`} style={{ textDecoration: "none", color: "inherit", borderBottom: "1px dotted var(--line)" }}>
                            <div style={{ fontFamily: "var(--ff-display)", fontSize: 20 }}>{lang === "en" ? w.title_en : (w.title_ar || w.title_en)}</div>
                          </a>
                          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)", marginTop: 4 }}>
                            {b.booking_ref} · {(lang === "ar" ? (w.makers?.name_ar || w.makers?.name_en) : w.makers?.name_en) || ""}
                          </div>
                        </div>
                        <div>
                          <div style={{ fontFamily: "var(--ff-display)", fontSize: 18 }}>
                            {startsAt ? startsAt.toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB",
                              { day: "numeric", month: "short", year: "numeric" }) : "—"}
                          </div>
                          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)" }}>
                            {startsAt ? startsAt.toLocaleTimeString(lang === "ar" ? "ar-EG" : "en-GB", { hour: "2-digit", minute: "2-digit" }) : ""}
                          </div>
                        </div>
                        <div>
                          <div style={{ fontFamily: "var(--ff-display)", fontSize: 18 }}>{Math.round((b.total_piastres || 0) / 100).toLocaleString(lang === "ar" ? "ar-EG" : "en-GB")} {lang === "en" ? "EGP" : "ج.م"}</div>
                          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: "var(--muted)" }}>{b.seats} {lang === "en" ? (b.seats === 1 ? "seat" : "seats") : "مقعد"}{b.waitlist_position ? ` · #${b.waitlist_position}` : ""}</div>
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
                          <AdminPill tone={STATUS_LABEL.tone}>{lang === "en" ? STATUS_LABEL.en : STATUS_LABEL.ar}</AdminPill>
                          {canCancel && (
                            <button
                              disabled={cancellingId === b.id}
                              onClick={async () => {
                                if (!confirm(lang === "en"
                                    ? `Cancel booking ${b.booking_ref}? ${refundEligible ? "You're within the refund window." : "This is after the refund window — no refund will be issued."}`
                                    : `إلغاء الحجز ${b.booking_ref}؟ ${refundEligible ? "ضمن نافذة الاسترداد." : "خارج نافذة الاسترداد."}`)) return;
                                setCancellingId(b.id);
                                try {
                                  const session = (await window.sb.auth.getSession()).data?.session;
                                  const res = await fetch(`${window.SB_URL}/functions/v1/workshop_cancel`, {
                                    method: "POST",
                                    headers: { "Content-Type": "application/json", "apikey": window.SB_ANON, "Authorization": "Bearer " + (session?.access_token || window.SB_ANON) },
                                    body: JSON.stringify({ booking_id: b.id, reason: "customer_cancellation" }),
                                  });
                                  const data = await res.json().catch(() => ({}));
                                  if (!res.ok || !data.ok) {
                                    if (data.error) console.warn("workshop_cancel:", data.error);
                                    alert((lang === "en" ? data.friendly_en : data.friendly_ar)
                                      || (lang === "en" ? "We couldn't cancel that booking. Please try again." : "تعذّر إلغاء الحجز. حاول مرّة أخرى."));
                                  } else {
                                    window.sb.from("workshop_bookings")
                                      .select("id, booking_ref, status, seats, total_piastres, waitlist_position, hold_expires_at, confirmed_at, cancelled_at, refund_status, placed_at, workshops:workshop_id(id, slug, title_en, title_ar, starts_at, duration_minutes, city_en, city_ar, address_en, address_ar, status, makers:host_maker_id(name_en, name_ar, slug))")
                                      .eq("user_id", user.id)
                                      .order("placed_at", { ascending: false })
                                      .then(({ data }) => setBookings(data || []));
                                  }
                                } catch (ex) {
                                  alert(lang === "en" ? "We couldn't reach SANAA. Please try again." : "تعذّر الوصول. حاول مرّة أخرى.");
                                } finally {
                                  setCancellingId(null);
                                }
                              }}
                              style={{ background: "transparent", border: "1px solid var(--line)", padding: "5px 12px", borderRadius: 999, cursor: "pointer", fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--terracotta)", textTransform: "uppercase", opacity: cancellingId === b.id ? 0.5 : 1 }}
                            >
                              {cancellingId === b.id ? "…" : (lang === "en" ? "Cancel" : "إلغاء")}
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
              {tab !== "orders" && tab !== "messages" && tab !== "account" && tab !== "workshops" && (
                <div style={{ padding: 80, textAlign: "center", color: "var(--muted)" }}><Star8 size={24} color="var(--gold)" /><p style={{ marginTop: 20, fontFamily: "var(--ff-display)", fontSize: 24 }}>{lang === "en" ? "Coming soon." : "قريبًا."}</p></div>
              )}
            </div>
          </div>
        </div>
      </section>
      <ReturnRequestModal
        open={!!returnFor}
        order={returnFor}
        lang={lang}
        onClose={() => setReturnFor(null)}
        onSubmitted={() => {
          // Refresh the per-user return list so the button hides for that order
          if (user) {
            window.sb.from("return_requests")
              .select("id, order_id, status, reason_code, created_at, resolved_at")
              .eq("customer_id", user.id)
              .order("created_at", { ascending: false })
              .then(({ data }) => setReturns(data || []));
          }
        }}
      />
    </>
  );
}

function ApplyPage({ t, lang }) {
  const [form, setForm] = React.useState({ name: "", email: "", city: "", trade: "", years: "", phone: "", portfolio: "", story: "" });
  const [status, setStatus] = React.useState("idle"); // idle | submitting | done | error
  const [err, setErr] = React.useState("");
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email) { setErr(lang === "en" ? "Name and email are required." : "الاسم والبريد مطلوبان."); return; }
    setStatus("submitting"); setErr("");
    try {
      const { error } = await window.sb.from("maker_applications").insert({
        name: form.name,
        email: form.email,
        phone: form.phone || null,
        trade: form.trade || null,
        city: form.city.split(",")[0]?.trim() || null,
        governorate: form.city.split(",")[1]?.trim() || form.city || null,
        portfolio_links: form.portfolio ? [form.portfolio] : null,
        story: form.story || null,
      });
      if (error) throw error;
      setStatus("done");
    } catch (ex) {
      console.warn("maker apply submit:", ex?.message || ex);
      setErr(lang === "en" ? "We couldn't submit your application. Please try again." : "تعذّر إرسال طلبك. حاول مرّة أخرى.");
      setStatus("error");
    }
  };

  const inp = { display: "block", width: "100%", marginTop: 8, padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15, outline: 0, boxSizing: "border-box" };

  return (<>
    <Breadcrumbs crumbs={[{ label: lang === "en" ? "Makers" : "الصنّاع", to: "/makers" }, { label: lang === "en" ? "Apply" : "قدّم" }]} lang={lang} />
    <PageHeader
      eyebrow={lang === "en" ? "Maker programme" : "برنامج الصنّاع"}
      title={lang === "en" ? "Apply to" : "قدّم"}
      titleIt={lang === "en" ? "the house." : "للبيت."}
      kicker={lang === "en" ? "We accept fewer than one in five. Bring your work, your story, and one unedited process video." : "نقبل أقل من واحدٍ من كل خمسة."}
    />
    <section style={{ padding: "60px 0 120px", background: "var(--paper-2)" }}>
      <div className="container" style={{ maxWidth: 720 }}>
        {status === "done" ? (
          <div style={{ textAlign: "center", padding: "60px 20px", background: "var(--paper)", borderRadius: 14, border: "1px solid var(--line-2)" }}>
            <Star8 size={32} color="var(--olive)" />
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 40, marginTop: 16 }}>
              {lang === "en" ? "Application received." : "تمّ استلام طلبك."}
            </h2>
            <p style={{ marginTop: 12, color: "var(--olive)" }}>
              {lang === "en" ? "We review every application within ten days. We'll write to you at " + form.email + "." : "نراجع كل طلب خلال عشرة أيام."}
            </p>
          </div>
        ) : (
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <div>
              <label htmlFor="apply-name" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Your name" : "اسمك"}</label>
              <input id="apply-name" name="name" required value={form.name} onChange={set("name")} placeholder="Nour Ibrahim" style={inp} />
            </div>
            <div>
              <label htmlFor="apply-email" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Email" : "البريد"}</label>
              <input id="apply-email" name="email" required type="email" value={form.email} onChange={set("email")} placeholder="you@example.com" style={inp} />
            </div>
            <div>
              <label htmlFor="apply-city" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "City & governorate" : "المدينة"}</label>
              <input id="apply-city" name="city" value={form.city} onChange={set("city")} placeholder="Cairo, Cairo" style={inp} />
            </div>
            <div>
              <label htmlFor="apply-trade" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Your craft" : "حرفتك"}</label>
              <input id="apply-trade" name="trade" value={form.trade} onChange={set("trade")} placeholder="Macramé / Ceramics / Candle / Resin" style={inp} />
            </div>
            <div>
              <label htmlFor="apply-phone" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "WhatsApp" : "واتساب"}</label>
              <input id="apply-phone" name="phone" type="tel" value={form.phone} onChange={set("phone")} placeholder="+20 ..." style={inp} />
            </div>
            <div>
              <label htmlFor="apply-portfolio" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Link to process video (unedited)" : "رابط فيديو (غير معدّل)"}</label>
              <input id="apply-portfolio" name="portfolio" type="url" value={form.portfolio} onChange={set("portfolio")} placeholder="https://..." style={inp} />
            </div>
            <div>
              <label htmlFor="apply-story" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Tell us your story" : "احكِ قصّتك"}</label>
              <textarea id="apply-story" name="story" rows={6} value={form.story} onChange={set("story")} style={{ ...inp, resize: "vertical" }} />
            </div>
            {err && <div style={{ color: "var(--terracotta)", fontSize: 13 }}>{err}</div>}
            <button type="submit" disabled={status === "submitting"} className="btn" style={{ alignSelf: "flex-start", marginTop: 10, opacity: status === "submitting" ? 0.6 : 1 }}>
              {status === "submitting" ? (lang === "en" ? "Sending…" : "جاري الإرسال…") : (lang === "en" ? "Submit application" : "إرسال")} →
            </button>
          </form>
        )}
      </div>
    </section>
  </>);
}

// ─────── REVIEW (tokenised, no-login, mobile-first) ──────────────
// Customers reach this from a WhatsApp/email link after delivery.
// SANAA editorial language preserved: paper card, mono eyebrows, serif
// headings, terracotta star fills.
function StarRow({ label, value, onChange, lang }) {
  return (
    <div style={{ padding: "14px 0", borderBottom: "1px solid var(--line-2)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <label style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
          {label}
        </label>
        <div role="radiogroup" aria-label={label} style={{ display: "flex", gap: 6 }}>
          {[1, 2, 3, 4, 5].map(n => {
            const filled = value >= n;
            return (
              <button
                key={n}
                type="button"
                role="radio"
                aria-checked={value === n}
                aria-label={`${n} ${lang === "en" ? "stars" : "نجوم"}`}
                onClick={() => onChange(n)}
                style={{
                  background: "transparent",
                  border: 0,
                  cursor: "pointer",
                  padding: 4,
                  minWidth: 44, minHeight: 44,
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  color: filled ? "var(--terracotta)" : "var(--line)",
                  fontSize: 26, lineHeight: 1,
                  transition: "color 0.15s",
                }}
              >
                {/* Hand-drawn eight-point star — matches the Star8 motif used site-wide.
                    Fill follows the button's currentColor (terracotta when chosen,
                    line-grey otherwise); aria-checked carries the state for AT. */}
                <Star8 size={24} />
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ReviewPage({ lang, token }) {
  const [state, setState] = React.useState("loading"); // loading | invalid | form | submitting | done | error
  const [reason, setReason] = React.useState(null);     // invalid_token | already_used | expired | already_reviewed
  const [orderInfo, setOrderInfo] = React.useState(null);
  const [ratings, setRatings] = React.useState({ product: 0, craft: 0, shipping: 0, sanaa: 0, website: 0 });
  const [comment, setComment] = React.useState("");
  const [buyAgain, setBuyAgain] = React.useState(null);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    if (!token) { setState("invalid"); setReason("invalid_token"); return; }
    window.sb.rpc("validate_review_token", { p_token: token })
      .then(({ data, error }) => {
        if (error) { setState("invalid"); setReason("invalid_token"); return; }
        if (!data?.valid) { setState("invalid"); setReason(data?.reason || "invalid_token"); return; }
        setOrderInfo(data);
        setState("form");
      });
  }, [token]);

  const submit = async (e) => {
    e.preventDefault();
    if (Object.values(ratings).some(v => v < 1)) {
      setErr(lang === "en" ? "Please rate every category." : "قيّم كل بند.");
      return;
    }
    setState("submitting"); setErr("");
    const { data, error } = await window.sb.rpc("submit_review", {
      p_token: token,
      p_rating_product: ratings.product,
      p_rating_craft: ratings.craft,
      p_rating_shipping: ratings.shipping,
      p_rating_sanaa: ratings.sanaa,
      p_rating_website: ratings.website,
      p_comment: comment || null,
      p_would_buy_again: buyAgain,
    });
    if (error || !data?.ok) {
      if (error?.message) console.warn("submit_review:", error.message);
      setState("error");
      setErr(lang === "en" ? "We couldn't save your review. Please try again." : "تعذّر حفظ تقييمك. حاول مرّة أخرى.");
      return;
    }
    setState("done");
  };

  if (state === "loading") {
    return (
      <section style={{ padding: "120px 0", textAlign: "center", background: "var(--paper)" }}>
        <div className="container">
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>
            {lang === "en" ? "Loading…" : "تحميل…"}
          </div>
        </div>
      </section>
    );
  }

  if (state === "invalid") {
    const REASON_MSG = {
      invalid_token:    { en: "This link is not valid.",                       ar: "هذا الرابط غير صالح." },
      unknown_token:    { en: "This link is not recognised.",                  ar: "الرابط غير معروف." },
      already_used:     { en: "This review has already been submitted.",       ar: "تمّت المراجعة من قبل." },
      expired:          { en: "This link has expired.",                        ar: "انتهت صلاحيّة الرابط." },
      already_reviewed: { en: "A review for this order already exists.",       ar: "توجد مراجعة لهذا الطلب." },
    };
    const msg = REASON_MSG[reason] || REASON_MSG.invalid_token;
    return (
      <section style={{ padding: "120px 0", textAlign: "center", background: "var(--paper)" }}>
        <div className="container">
          <Star8 size={32} color="var(--gold-soft)" />
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(32px, 5vw, 48px)", marginTop: 20, letterSpacing: "-0.01em" }}>
            {msg[lang] || msg.en}
          </h1>
          <p style={{ marginTop: 12, fontSize: 14, color: "var(--olive)" }}>
            {lang === "en" ? "If you believe this is a mistake, write to hello@sanaa.eg." : "للاستفسار: hello@sanaa.eg"}
          </p>
          <a href="#/" className="btn ghost" style={{ marginTop: 26, display: "inline-flex" }}>
            {lang === "en" ? "Back home" : "الرئيسيّة"} →
          </a>
        </div>
      </section>
    );
  }

  if (state === "done") {
    return (
      <section style={{ padding: "120px 0", textAlign: "center", background: "var(--paper)" }}>
        <div className="container">
          <Star8 size={36} color="var(--olive)" />
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 6vw, 64px)", marginTop: 20, letterSpacing: "-0.02em" }}>
            {lang === "en" ? "Thank you." : "شكرًا لك."}
          </h1>
          <p style={{ marginTop: 14, fontSize: 16, color: "var(--olive)", fontStyle: "italic", maxWidth: 480, marginLeft: "auto", marginRight: "auto", lineHeight: 1.65 }}>
            {lang === "en"
              ? "Your review reaches the maker today. It shapes how we tend the next piece."
              : "تصل مراجعتك إلى الصانع اليوم. تُشكّل كيف نُحضّر القطعة القادمة."}
          </p>
          <a href="#/shop" className="btn" style={{ marginTop: 32, display: "inline-flex" }}>
            {lang === "en" ? "Browse the shop" : "تصفّح المتجر"} →
          </a>
        </div>
      </section>
    );
  }

  // Form state — mobile-first single column, max-width 560 for tablet/desktop
  const LABELS = lang === "en"
    ? { product: "The piece itself", craft: "The maker's craft", shipping: "Shipping & wrapping", sanaa: "SANAA service", website: "Browsing experience" }
    : { product: "القطعة نفسها",      craft: "حِرفة الصانع",     shipping: "الشحن والتغليف",        sanaa: "خدمة صَنعة",     website: "تجربة الموقع" };

  return (
    <section style={{ padding: "60px 0 100px", background: "var(--paper)" }}>
      <div className="container" style={{ maxWidth: 600 }}>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
          {orderInfo?.order_number}
        </div>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 5vw, 56px)", marginTop: 8, letterSpacing: "-0.02em", lineHeight: 1.05 }}>
          {lang === "en" ? <>Tell us how it<br /><span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>arrived.</span></> : <>أخبرنا كيف<br /><span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>وصلت.</span></>}
        </h1>
        <p style={{ marginTop: 14, fontSize: 15, color: "var(--olive)", lineHeight: 1.6 }}>
          {lang === "en"
            ? "Five quick taps. Your words go to the maker by hand, and they help the next piece be better."
            : "خمس نقرات. كلماتك تصل إلى الصانع، وتساعد القطعة القادمة."}
        </p>

        <form onSubmit={submit} style={{ marginTop: 40 }}>
          <StarRow label={LABELS.product}  value={ratings.product}  onChange={v => setRatings(r => ({ ...r, product: v }))}  lang={lang} />
          <StarRow label={LABELS.craft}    value={ratings.craft}    onChange={v => setRatings(r => ({ ...r, craft: v }))}    lang={lang} />
          <StarRow label={LABELS.shipping} value={ratings.shipping} onChange={v => setRatings(r => ({ ...r, shipping: v }))} lang={lang} />
          <StarRow label={LABELS.sanaa}    value={ratings.sanaa}    onChange={v => setRatings(r => ({ ...r, sanaa: v }))}    lang={lang} />
          <StarRow label={LABELS.website}  value={ratings.website}  onChange={v => setRatings(r => ({ ...r, website: v }))}  lang={lang} />

          <div style={{ marginTop: 32 }}>
            <label htmlFor="review-comment" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
              {lang === "en" ? "A line to the maker (optional)" : "كلمة للصانع (اختياري)"}
            </label>
            <textarea id="review-comment" rows={4}
              value={comment} onChange={e => setComment(e.target.value)}
              placeholder={lang === "en" ? "What surprised you? What made you pause?" : "ما الذي لفتك؟"}
              maxLength={2000}
              style={{ display: "block", width: "100%", marginTop: 10, padding: "14px 16px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15, outline: 0, boxSizing: "border-box", resize: "vertical", lineHeight: 1.55 }} />
          </div>

          <fieldset style={{ border: 0, padding: 0, marginTop: 28 }}>
            <legend style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 14 }}>
              {lang === "en" ? "Would you buy from SANAA again?" : "هل ستشتري من صَنعة مرّةً أخرى؟"}
            </legend>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              {[
                { v: true,  en: "Yes",     ar: "نعم" },
                { v: false, en: "Not sure",ar: "لستُ متأكدًا" },
              ].map(o => {
                const sel = buyAgain === o.v;
                return (
                  <button key={String(o.v)} type="button" onClick={() => setBuyAgain(o.v)}
                    aria-pressed={sel}
                    style={{
                      padding: "12px 22px", borderRadius: 999,
                      border: `1px solid ${sel ? "var(--ink)" : "var(--line)"}`,
                      background: sel ? "var(--ink)" : "transparent",
                      color: sel ? "var(--paper)" : "var(--ink)",
                      fontFamily: "var(--ff-sans)", fontSize: 14, cursor: "pointer", minHeight: 44,
                    }}>
                    {o[lang] || o.en}
                  </button>
                );
              })}
            </div>
          </fieldset>

          {err && <div style={{ marginTop: 22, color: "var(--terracotta)", fontSize: 14 }}>{err}</div>}

          <button type="submit" disabled={state === "submitting"} className="btn"
            style={{ marginTop: 38, width: "100%", justifyContent: "center", padding: "18px 28px", fontSize: 14, opacity: state === "submitting" ? 0.6 : 1 }}>
            {state === "submitting" ? (lang === "en" ? "Sending…" : "إرسال…") : (lang === "en" ? "Send my review" : "أرسل المراجعة")} →
          </button>
        </form>
      </div>
    </section>
  );
}

// ─────── ORDER TRACKING — luxury operational visualisation ──────────
// Customer reaches this from a WhatsApp/email "Track order" link, or by
// entering an order number on the form. Reads public_order_tracking()
// which returns only the public_visible event subset.

// Narrative copy per public event — replaces machine statuses with calm
// editorial prose. Falls back to the event's bundled label_en/ar.
const TRACKING_NARRATIVE = {
  "order.created":             { en: "Your order has reached SANAA. We're confirming it now.",                ar: "وصلَ طلبك إلى صَنعة. نؤكّده الآن." },
  "order.confirmed":           { en: "Confirmed. The maker has been notified.",                                ar: "تمّ التأكيد. تمّ إخبار الصانع." },
  "order.in_preparation":      { en: "Your piece is currently being hand-finished in the atelier.",            ar: "يجري الانتهاء من قطعتك يدويًّا في المحترف." },
  "maker.accepted":            { en: "The maker has accepted production.",                                     ar: "اعتمد الصانع الإنتاج." },
  "maker.production_started":  { en: "Production has started in the maker's workshop.",                        ar: "بدأ العمل في ورشة الصانع." },
  "maker.ready_for_qc":        { en: "Final quality review is underway in our atelier.",                       ar: "تجري مراجعة الجودة النهائيّة في محترفنا." },
  "qc.passed":                 { en: "Quality check passed. Preparing for dispatch.",                          ar: "تمّت مراجعة الجودة. نستعدّ للشحن." },
  "maker.packed":              { en: "Packed by hand in recycled tissue, sealed with our wax mark.",           ar: "غُلِّفت يدويًّا، خُتمت بشمعنا." },
  "order.ready_for_dispatch":  { en: "Ready for dispatch.",                                                    ar: "جاهز للشحن." },
  "shipment.created":          { en: "A courier has been assigned.",                                           ar: "تمّ تعيين مندوب." },
  "shipment.handed_to_courier":{ en: "Your order is now with our delivery partner.",                           ar: "طلبك مع شريك التوصيل." },
  "shipment.in_transit":       { en: "In transit toward you.",                                                 ar: "في الطريق إليك." },
  "order.shipped":             { en: "Shipped.",                                                                ar: "تمّ الشحن." },
  "order.delivered":           { en: "Delivered. We hope it arrives whole.",                                   ar: "وصل الطلب. نأمل أن يصلك كاملًا." },
  "shipment.delivered":        { en: "Delivered. We hope it arrives whole.",                                   ar: "وصل الطلب." },
  "shipment.failed":           { en: "A delivery attempt was made. The courier will retry.",                   ar: "جرت محاولة توصيل. سيُعاد المحاولة." },
  "return.requested":          { en: "Your return request is with SANAA support.",                             ar: "طلب الإرجاع لدى فريق صَنعة." },
  "return.approved":           { en: "Return approved. We'll coordinate pickup.",                              ar: "تمّت الموافقة على الإرجاع. سنرتّب الاستلام." },
  "return.received":           { en: "Return received in our atelier.",                                        ar: "استُلم الإرجاع في محترفنا." },
  "return.refunded":           { en: "Refund issued.",                                                          ar: "تمّ ردّ المبلغ." },
  "return.rejected":           { en: "We weren't able to accept this return.",                                 ar: "تعذّر قبول الإرجاع." },
  "order.cancelled":           { en: "Order cancelled.",                                                        ar: "تمّ إلغاء الطلب." },
  "order.refunded":            { en: "Refund issued.",                                                          ar: "تمّ ردّ المبلغ." },
};

// Ordered milestones for the visual progress rail at the top of the page.
// Each entry maps to one of the public_visible kinds. We show whichever
// is the most-advanced one the order has touched.
const TRACKING_MILESTONES = [
  { k: "order.created",            en: "Received",       ar: "استُلم" },
  { k: "order.confirmed",          en: "Confirmed",      ar: "تأكّد" },
  { k: "order.in_preparation",     en: "In preparation", ar: "قيد التحضير" },
  { k: "maker.ready_for_qc",       en: "Quality review", ar: "مراجعة الجودة" },
  { k: "order.ready_for_dispatch", en: "Ready",          ar: "جاهز" },
  { k: "order.shipped",            en: "Shipped",        ar: "تمّ الشحن" },
  { k: "order.delivered",          en: "Delivered",      ar: "وصل" },
];

function _trackingMilestoneIndex(events) {
  // Returns the index of the latest milestone the order has reached. -1 if none.
  const eventKinds = new Set(events.map(e => e.kind));
  let last = -1;
  for (let i = 0; i < TRACKING_MILESTONES.length; i++) {
    if (eventKinds.has(TRACKING_MILESTONES[i].k)) last = i;
  }
  // Cancelled / refunded short-circuit the rail.
  if (eventKinds.has("order.cancelled") || eventKinds.has("order.refunded")) return -2;
  return last;
}

function TrackOrderPage({ lang, orderNumber }) {
  const { user } = window.useAuth();
  const [num, setNum] = React.useState(orderNumber || "");
  const [factor, setFactor] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle|loading|found|not_found|denied|rate_limited
  const [data, setData] = React.useState(null);

  // Logged-in owners reach tracking from their orders list; the RPC verifies
  // ownership from the JWT, so no second factor is needed for them.
  React.useEffect(() => {
    if (!user || !orderNumber) { return; }
    setState("loading");
    window.sb.rpc("public_order_tracking", { p_order_number: orderNumber })
      .then(({ data, error }) => {
        if (error || !data || data.found === false) { setState("not_found"); return; }
        setData(data); setState("found");
      });
  }, [user, orderNumber]);

  // Guests must present the order number AND a second factor (phone last-4 or
  // the checkout email). A wrong factor and an unknown order return the same
  // "denied" result, so order numbers can't be enumerated.
  const lookup = (e) => {
    if (e) e.preventDefault();
    const n = (num || "").trim().toUpperCase();
    const f = (factor || "").trim();
    if (!n || !f) return;
    setState("loading");
    window.sb.rpc("public_order_tracking", { p_order_number: n, p_factor: f })
      .then(({ data, error }) => {
        if (error) {
          const code = error.code || ""; const msg = (error.message || "").toLowerCase();
          setState((code === "PT429" || msg.includes("rate_limited")) ? "rate_limited" : "denied");
          return;
        }
        if (!data || data.found === false) { setState("denied"); return; }
        setData(data); setState("found");
      });
  };

  // Breadcrumb intentionally roots the page inside the customer's account
  // ecosystem — never a standalone "Track order" widget. Signed-in users
  // see a real "← Back to your orders" link; guests see the lookup form.
  const breadcrumbs = user
    ? [
        { label: lang === "en" ? "Account" : "الحساب", to: "/account" },
        { label: lang === "en" ? "Order follow-up" : "متابعة الطلب" },
      ]
    : [{ label: lang === "en" ? "Order follow-up" : "متابعة الطلب" }];

  // The form is only shown to guests who arrived via a WhatsApp / email
  // link without an order number. Signed-in customers never see a lookup
  // input — they get there from their orders list.
  const showLookupForm = !user; // guests always verify with order number + factor

  return (
    <>
      <Breadcrumbs crumbs={breadcrumbs} lang={lang} />
      <section style={{ padding: "60px 0 100px", background: "var(--paper)" }}>
        <div className="container" style={{ maxWidth: 760 }}>
          {/* Quiet eyebrow + back affordance for signed-in customers */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
              {lang === "en" ? "Order follow-up" : "متابعة الطلب"}
            </div>
            {user && (
              <a href="#/account" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", textDecoration: "none" }}>
                ← {lang === "en" ? "Your orders" : "طلباتك"}
              </a>
            )}
          </div>

          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 5vw, 60px)", marginTop: 8, letterSpacing: "-0.02em", lineHeight: 1.05 }}>
            {lang === "en"
              ? <>Your piece is in <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>good hands.</span></>
              : <>قطعتك في <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>أيدٍ أمينة.</span></>}
          </h1>

          {showLookupForm && (
            <form onSubmit={lookup} style={{ marginTop: 32, display: "grid", gap: 10, maxWidth: 460 }}>
              <input
                type="text"
                value={num}
                onChange={e => setNum(e.target.value)}
                placeholder="SAN-2026-000123"
                aria-label={lang === "en" ? "SANAA order number" : "رقم طلب صَنعة"}
                style={{ padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--paper)", fontFamily: "var(--ff-mono)", fontSize: 14, letterSpacing: "0.08em", outline: 0 }}
              />
              <input
                type="text"
                value={factor}
                onChange={e => setFactor(e.target.value)}
                placeholder={lang === "en" ? "Phone last 4 digits, or checkout email" : "آخر ٤ أرقام للهاتف، أو بريد الطلب"}
                aria-label={lang === "en" ? "Phone last 4 digits or checkout email" : "آخر ٤ أرقام للهاتف أو بريد الطلب"}
                style={{ padding: "14px 18px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0 }}
              />
              <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
                {lang === "en"
                  ? "For your privacy, we confirm it's your order with the phone's last 4 digits or the email you used at checkout."
                  : "لخصوصيتك، نتأكّد أنّه طلبك عبر آخر ٤ أرقام من الهاتف أو البريد المُستخدم في الطلب."}
              </div>
              <button type="submit" className="btn" style={{ padding: "14px 22px", justifySelf: "start" }}>
                {lang === "en" ? "Follow" : "متابعة"} →
              </button>
            </form>
          )}

          {state === "idle" && !showLookupForm && (
            <div style={{ marginTop: 28, padding: "20px 22px", background: "var(--paper-2)", borderRadius: 12, fontSize: 14, color: "var(--olive)", lineHeight: 1.6 }}>
              {lang === "en"
                ? "Open any order from your list to follow its progress with us."
                : "افتح أيّ طلب من قائمتك لمتابعة تقدّمه معنا."}
            </div>
          )}

          {state === "loading" && (
            <div style={{ marginTop: 40, fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>
              {lang === "en" ? "Loading…" : "تحميل…"}
            </div>
          )}

          {state === "not_found" && (
            <div style={{ marginTop: 40, padding: "26px 24px", background: "var(--paper-2)", borderRadius: 14 }}>
              <Star8 size={20} color="var(--gold-soft)" />
              <h3 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: 26, lineHeight: 1.1 }}>
                {lang === "en" ? "We couldn't find that order." : "لم نجد هذا الطلب."}
              </h3>
              <p style={{ marginTop: 8, fontSize: 14, color: "var(--olive)", lineHeight: 1.6 }}>
                {lang === "en"
                  ? "Double-check the order number — they look like SAN-2026-000123. If something still feels off, write to hello@sanaa.eg and a real human replies the same day."
                  : "تأكّد من رقم الطلب — يأتي على شكل SAN-2026-000123. لأيّ مساعدة: hello@sanaa.eg."}
              </p>
              {user && (
                <a href="#/account" className="btn ghost" style={{ marginTop: 20, display: "inline-flex" }}>
                  {lang === "en" ? "Back to your orders" : "العودة إلى طلباتك"} →
                </a>
              )}
            </div>
          )}

          {state === "denied" && (
            <div style={{ marginTop: 28, padding: "26px 24px", background: "var(--paper-2)", borderRadius: 14 }}>
              <Star8 size={20} color="var(--gold-soft)" />
              <h3 style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: 26, lineHeight: 1.1 }}>
                {lang === "en" ? "We couldn't verify that order." : "تعذّر تأكيد هذا الطلب."}
              </h3>
              <p style={{ marginTop: 8, fontSize: 14, color: "var(--olive)", lineHeight: 1.6 }}>
                {lang === "en"
                  ? "Check the order number, and that the phone's last 4 digits or the email match what you used at checkout. Still stuck? hello@sanaa.eg replies the same day."
                  : "تأكّد من رقم الطلب، ومن تطابق آخر ٤ أرقام للهاتف أو البريد مع ما استخدمته في الطلب. لأيّ مساعدة: hello@sanaa.eg."}
              </p>
            </div>
          )}

          {state === "rate_limited" && (
            <div style={{ marginTop: 28, padding: "26px 24px", background: "var(--paper-2)", borderRadius: 14 }}>
              <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 26, lineHeight: 1.1 }}>
                {lang === "en" ? "Too many attempts." : "محاولات كثيرة."}
              </h3>
              <p style={{ marginTop: 8, fontSize: 14, color: "var(--olive)", lineHeight: 1.6 }}>
                {lang === "en" ? "Please wait a minute, then try again." : "انتظر دقيقة، ثمّ أعد المحاولة."}
              </p>
            </div>
          )}

          {state === "found" && data && <TrackingDetails lang={lang} data={data} />}
        </div>
      </section>
    </>
  );
}

function TrackingDetails({ lang, data }) {
  const events = data.events || [];
  const idx = _trackingMilestoneIndex(events);
  const isCancelled = idx === -2;
  const latestEvent = events[events.length - 1];
  const latestNarrative = latestEvent
    ? (TRACKING_NARRATIVE[latestEvent.kind] || { en: latestEvent.label_en, ar: latestEvent.label_ar })
    : null;

  return (
    <>
      <div style={{ marginTop: 44, padding: "26px 26px 22px", border: "1px solid var(--line-2)", borderRadius: 14, background: "var(--paper-2)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, flexWrap: "wrap" }}>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", color: "var(--terracotta)", textTransform: "uppercase" }}>
            {data.order_number}
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.18em", color: "var(--muted)" }}>
            {data.placed_at ? window.fmtDate(data.placed_at, lang, { day: "numeric", month: "short", year: "numeric" }) : ""}
          </div>
        </div>
        {latestNarrative && (
          <div style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: "clamp(22px, 2.4vw, 28px)", lineHeight: 1.35, color: "var(--ink)" }}>
            {latestNarrative[lang] || latestNarrative.en}
          </div>
        )}
      </div>

      {/* Milestone rail — vertical on mobile, horizontal on tablet+ */}
      {!isCancelled && (
        <ol className="tracking-rail" style={{ listStyle: "none", padding: 0, margin: "44px 0 0", display: "grid", gap: 0 }}>
          {TRACKING_MILESTONES.map((m, i) => {
            const reached = i <= idx;
            const isCurrent = i === idx;
            return (
              <li key={m.k} style={{
                display: "grid",
                gridTemplateColumns: "44px 1fr",
                gap: 16,
                alignItems: "flex-start",
                padding: "14px 0",
                position: "relative",
              }}>
                {/* Connector line behind the dot */}
                {i < TRACKING_MILESTONES.length - 1 && (
                  <span aria-hidden="true" style={{
                    position: "absolute",
                    left: 21, top: 38, bottom: -14, width: 2,
                    background: reached ? "var(--terracotta)" : "var(--line)",
                  }} />
                )}
                <span aria-hidden="true" style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: reached ? "var(--terracotta)" : "var(--paper)",
                  border: reached ? "2px solid var(--terracotta)" : "2px solid var(--line)",
                  marginTop: 4,
                  display: "inline-block",
                  alignSelf: "start", justifySelf: "center",
                }} />
                <div>
                  <div style={{
                    fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em",
                    textTransform: "uppercase",
                    color: isCurrent ? "var(--terracotta)" : (reached ? "var(--olive)" : "var(--muted)"),
                  }}>
                    {m[lang] || m.en}
                  </div>
                  {(() => {
                    const evt = events.find(e => e.kind === m.k);
                    const copy = TRACKING_NARRATIVE[m.k];
                    if (!evt) return null;
                    return (
                      <>
                        <div style={{ marginTop: 6, fontFamily: "var(--ff-display)", fontSize: 18, lineHeight: 1.35, color: reached ? "var(--ink)" : "var(--muted)" }}>
                          {(copy && (copy[lang] || copy.en)) || evt.label_en}
                        </div>
                        <div style={{ marginTop: 2, fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.18em", color: "var(--muted)" }}>
                          {evt.occurred_at ? window.fmtDateTime(evt.occurred_at, lang) : ""}
                        </div>
                      </>
                    );
                  })()}
                </div>
              </li>
            );
          })}
        </ol>
      )}

      {/* Shipment block — appears once a courier has been assigned. Customer-safe
          fields only (courier display name + expected date); no tracking number,
          tracking URL, or recipient details are exposed by public_order_tracking. */}
      {data.shipment && data.shipment.status && (
        <div style={{ marginTop: 44, padding: "22px 24px", border: "1px solid var(--line-2)", borderRadius: 14 }}>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
            {lang === "en" ? "Delivery" : "التوصيل"}
          </div>
          <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 18 }}>
            {data.shipment.courier && (
              <div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>{lang === "en" ? "Courier" : "المندوب"}</div>
                <div style={{ marginTop: 4, fontFamily: "var(--ff-display)", fontSize: 18 }}>{data.shipment.courier}</div>
              </div>
            )}
            {data.shipment.estimated_delivery_at && (
              <div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>{lang === "en" ? "Expected" : "متوقّع"}</div>
                <div style={{ marginTop: 4, fontFamily: "var(--ff-display)", fontSize: 18 }}>
                  {window.fmtDate(data.shipment.estimated_delivery_at, lang, { day: "numeric", month: "short" })}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Support CTA */}
      <div style={{ marginTop: 36, padding: "20px 22px", background: "var(--paper-2)", borderRadius: 12, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
        <div style={{ fontSize: 14, color: "var(--olive)", lineHeight: 1.55, maxWidth: 460 }}>
          {lang === "en"
            ? "If anything needs adjusting, SANAA support replies the same day."
            : "إن احتجت لأيّ تعديل، يردّ فريق صَنعة في اليوم نفسه."}
        </div>
        <a href="https://wa.me/201000000000" target="_blank" rel="noopener" className="btn ghost" style={{ display: "inline-flex" }}>
          {lang === "en" ? "Message SANAA on WhatsApp" : "راسل صَنعة على واتساب"} →
        </a>
      </div>
    </>
  );
}

function NotFoundPage({ lang }) {
  return (
    <section style={{ padding: "140px 0", textAlign: "center", background: "var(--paper)" }}>
      <div className="container">
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 30 }}><Star8 size={40} color="var(--terracotta)" /></div>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 96 }}>404</h1>
        <p style={{ fontFamily: "var(--ff-display)", fontSize: 28, color: "var(--olive)", fontStyle: "italic" }}>{lang === "en" ? "That door is closed." : "هذا الباب مُغلق."}</p>
        <div style={{ marginTop: 30 }}><a className="btn" href="#/">{lang === "en" ? "Back home" : "الرئيسيّة"} →</a></div>
      </div>
    </section>
  );
}

// ————————————————————— WORKSHOP DETAIL + BOOKING —————————————————————
// Live workshop record by slug. Falls back to the editorial preview only
// if the slug matches a hardcoded fixture (closed-beta seeding) so the
// page never goes blank during transition.
function WorkshopDetailPage({ t, lang, slug, user }) {
  const [ws, setWs] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [bookOpen, setBookOpen] = React.useState(false);
  const [bookedRef, setBookedRef] = React.useState(null);
  const [bookedStatus, setBookedStatus] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true); setError("");
    window.sb.from("workshops")
      .select("*, makers:host_maker_id(name_en, name_ar, slug, city_en, trade_en, maker_code, story_en, story_ar, portrait_image)")
      .eq("slug", slug)
      .maybeSingle()
      .then(({ data, error }) => {
        if (cancelled) return;
        // Never surface raw Postgres/REST error strings to the UI (info-disclosure).
        if (error) { setError("load_failed"); setLoading(false); return; }
        setWs(data || null); setLoading(false);
      });
    return () => { cancelled = true; };
  }, [slug]);

  // Re-fetch on book-success to reflect new seats_taken / status.
  const refetch = React.useCallback(() => {
    window.sb.from("workshops")
      .select("*, makers:host_maker_id(name_en, name_ar, slug, city_en, trade_en, maker_code, story_en, story_ar, portrait_image)")
      .eq("slug", slug)
      .maybeSingle()
      .then(({ data }) => { if (data) setWs(data); });
  }, [slug]);

  if (loading) {
    return (
      <section style={{ padding: "120px 0", textAlign: "center", background: "var(--paper)" }}>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 12, color: "var(--muted)", letterSpacing: "0.2em" }}>
          {lang === "en" ? "LOADING…" : "جاري التحميل…"}
        </div>
      </section>
    );
  }
  if (!ws) {
    return (
      <section style={{ padding: "120px 0", textAlign: "center", background: "var(--paper)" }}>
        <Star8 size={32} color="var(--terracotta)" />
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 48, marginTop: 20 }}>
          {error
            ? (lang === "en" ? "We couldn't load this workshop." : "تعذّر تحميل هذه الورشة.")
            : (lang === "en" ? "That workshop has closed." : "هذه الورشة مُغلقة.")}
        </h2>
        <p style={{ marginTop: 14, color: "var(--olive)" }}>
          {error
            ? (lang === "en" ? "Please try again in a moment." : "حاول مرّة أخرى بعد قليل.")
            : ""}
        </p>
        <a className="btn" href="#/atelier/workshops" style={{ marginTop: 24, display: "inline-flex" }}>
          {lang === "en" ? "All workshops" : "كل الورش"} →
        </a>
      </section>
    );
  }

  const seatsLeft = Math.max(0, (ws.seats_total || 0) - (ws.seats_taken || 0));
  const isPast = new Date(ws.starts_at).getTime() <= Date.now();
  const isCancelled = ws.status === "cancelled";
  const isFull = seatsLeft === 0 && !isCancelled && !isPast;
  const bookable = !isPast && !isCancelled && (ws.status === "published" || ws.status === "fully_booked");
  const startsAt = new Date(ws.starts_at);
  const endsAt = new Date(startsAt.getTime() + (ws.duration_minutes || 0) * 60_000);
  const dateLine = startsAt.toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB",
    { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  const timeLine = `${startsAt.toLocaleTimeString(lang === "ar" ? "ar-EG" : "en-GB", { hour: "2-digit", minute: "2-digit" })} – ${endsAt.toLocaleTimeString(lang === "ar" ? "ar-EG" : "en-GB", { hour: "2-digit", minute: "2-digit" })}`;
  const priceEgp = Math.round((ws.price_piastres || 0) / 100);
  const occupancyPct = ws.seats_total > 0 ? Math.round(100 * (ws.seats_taken || 0) / ws.seats_total) : 0;

  return (
    <>
      <Breadcrumbs crumbs={[
        { label: lang === "en" ? "Atelier" : "المحترف", to: "/atelier" },
        { label: lang === "en" ? "Workshops" : "ورش", to: "/atelier/workshops" },
        { label: (lang === "en" ? ws.title_en : (ws.title_ar || ws.title_en)) || "" },
      ]} lang={lang} />

      {bookedRef && (
        <section style={{ padding: "30px 0", background: "rgba(123,132,99,0.08)", borderBottom: "1px solid var(--line-2)" }}>
          <div className="container-wide" style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
            <Star8 size={20} color="var(--olive)" />
            <div style={{ flex: 1, minWidth: 240 }}>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 22, color: "var(--olive)" }}>
                {bookedStatus === "confirmed"
                  ? (lang === "en" ? "Your seat is held." : "تمّ تأكيد مقعدك.")
                  : (lang === "en" ? "You're on the waitlist." : "أنت في قائمة الانتظار.")}
              </div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--muted)", marginTop: 4 }}>
                {(lang === "en" ? "Ref · " : "مرجع · ") + bookedRef}
              </div>
            </div>
            <a className="btn ghost" href="#/account">{lang === "en" ? "My workshops" : "ورشي"} →</a>
          </div>
        </section>
      )}

      <section style={{ padding: "60px 0 30px", background: "var(--paper)" }}>
        <div className="container-wide" style={{ display: "grid", gridTemplateColumns: "minmax(0,1.6fr) minmax(0,1fr)", gap: 60, alignItems: "start" }}>
          <div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--terracotta)" }}>
              {lang === "en" ? "Workshop" : "ورشة"} · {ws.level ? fmtLevel(ws.level, lang) : "—"}
            </div>
            <h1 style={{ fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 6vw, 76px)", lineHeight: 1.02, marginTop: 12 }}>
              {lang === "en" ? ws.title_en : (ws.title_ar || ws.title_en)}
            </h1>
            {ws.title_ar && lang === "en" && (
              <div className="ar" style={{ fontSize: 24, color: "var(--terracotta)", marginTop: 8 }}>{ws.title_ar}</div>
            )}
            <p style={{ fontSize: 17, color: "var(--olive)", lineHeight: 1.7, marginTop: 28, maxWidth: 620 }}>
              {lang === "en" ? (ws.description_en || "") : (ws.description_ar || ws.description_en || "")}
            </p>

            {ws.materials_en || ws.materials_ar ? (
              <div style={{ marginTop: 36, padding: 24, background: "var(--paper-2)", borderRadius: 14 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--muted)" }}>
                  {lang === "en" ? "Materials included" : "المواد متضمّنة"}
                </div>
                <div style={{ marginTop: 8, fontSize: 14, lineHeight: 1.7 }}>
                  {lang === "en" ? (ws.materials_en || "") : (ws.materials_ar || ws.materials_en || "")}
                </div>
              </div>
            ) : null}

            {ws.cancellation_policy_en || ws.cancellation_policy_ar ? (
              <div style={{ marginTop: 24 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6 }}>
                  {lang === "en" ? "Cancellation policy" : "سياسة الإلغاء"}
                </div>
                <p style={{ fontSize: 13, color: "var(--olive)", lineHeight: 1.6, fontStyle: "italic" }}>
                  {lang === "en" ? (ws.cancellation_policy_en || "") : (ws.cancellation_policy_ar || ws.cancellation_policy_en || "")}
                </p>
              </div>
            ) : (
              <div style={{ marginTop: 24, fontSize: 12, color: "var(--muted)", fontStyle: "italic" }}>
                {lang === "en"
                  ? `Full refund up to ${ws.refund_window_hours || 48} hours before the start. After that, the seat is yours to gift to a friend.`
                  : `استرداد كامل قبل البدء بـ${ws.refund_window_hours || 48} ساعة. بعدها يمكنك إهداء المقعد لصديق.`}
              </div>
            )}

            {ws.makers && (
              <div style={{ marginTop: 50, paddingTop: 36, borderTop: "1px solid var(--line-2)" }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--muted)" }}>
                  {lang === "en" ? "Taught by" : "بصُحبة"}
                </div>
                <a href={`#/makers/${ws.makers.slug}`} style={{ textDecoration: "none", color: "inherit" }}>
                  <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 32, marginTop: 8 }}>{ws.makers.name_en}</h3>
                </a>
                <div style={{ fontSize: 13, color: "var(--olive)", marginTop: 4 }}>
                  {ws.makers.trade_en} · {ws.makers.city_en}
                </div>
              </div>
            )}
          </div>

          {/* Right rail — booking card */}
          <aside style={{
            position: "sticky", top: 100,
            border: "1px solid var(--line)", borderRadius: 16, background: "var(--paper)",
            padding: 28, boxShadow: "0 1px 3px rgba(28,26,21,0.04)",
          }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--muted)" }}>
              {dateLine}
            </div>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 28, marginTop: 4 }}>{timeLine}</div>
            <div style={{ marginTop: 4, fontSize: 13, color: "var(--olive)" }}>
              {(ws.city_en || ws.makers?.city_en) ? `· ${lang === "en" ? (ws.city_en || ws.makers.city_en) : (ws.city_ar || ws.city_en || ws.makers.city_en)}` : ""}
              {ws.address_en ? ` · ${lang === "en" ? ws.address_en : (ws.address_ar || ws.address_en)}` : ""}
            </div>

            <div style={{ marginTop: 26, fontFamily: "var(--ff-display)", fontSize: 44 }}>
              {priceEgp ? window.fmtPrice(priceEgp, lang) : (lang === "en" ? "On request" : "حسب الطلب")}
            </div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", color: "var(--muted)", marginTop: 4 }}>
              {lang === "en" ? "Per seat · materials & tea included" : "للمقعد الواحد · المواد والشاي متضمّنة"}
            </div>

            {/* Occupancy bar */}
            <div style={{ marginTop: 28 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)", textTransform: "uppercase" }}>
                <span>{lang === "en" ? `${seatsLeft} of ${ws.seats_total} seats left` : `${seatsLeft} من ${ws.seats_total} متبقّي`}</span>
                <span>{occupancyPct}%</span>
              </div>
              <div style={{ marginTop: 6, height: 4, background: "var(--paper-2)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ width: `${occupancyPct}%`, height: "100%", background: occupancyPct >= 100 ? "var(--terracotta)" : "var(--olive)", transition: "width .3s" }} />
              </div>
            </div>

            <div style={{ marginTop: 28 }}>
              {isPast ? (
                <button disabled className="btn" style={{ width: "100%", justifyContent: "center", opacity: 0.5 }}>
                  {lang === "en" ? "Workshop has ended" : "انتهت الورشة"}
                </button>
              ) : isCancelled ? (
                <button disabled className="btn" style={{ width: "100%", justifyContent: "center", opacity: 0.5, background: "var(--terracotta)" }}>
                  {lang === "en" ? "Cancelled" : "ملغاة"}
                </button>
              ) : isFull && !ws.waitlist_enabled ? (
                <button disabled className="btn" style={{ width: "100%", justifyContent: "center", opacity: 0.5 }}>
                  {lang === "en" ? "Fully booked" : "مكتمل"}
                </button>
              ) : (
                <button onClick={() => setBookOpen(true)} className="btn" style={{ width: "100%", justifyContent: "center" }}>
                  {isFull
                    ? (lang === "en" ? "Join waitlist" : "انضم لقائمة الانتظار")
                    : (lang === "en" ? "Reserve a seat" : "احجز مقعدًا")} →
                </button>
              )}
            </div>

            <div style={{ marginTop: 18, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)", lineHeight: 1.7, textAlign: "center" }}>
              {lang === "en" ? "WhatsApp confirmation + reminder the day before" : "تأكيد واتساب + تذكير اليوم السابق"}
            </div>
          </aside>
        </div>
      </section>

      <WorkshopBookingModal
        open={bookOpen}
        onClose={() => setBookOpen(false)}
        lang={lang}
        user={user}
        workshop={ws}
        seatsLeft={seatsLeft}
        onBooked={(result) => {
          setBookedRef(result.booking_ref);
          setBookedStatus(result.status);
          setBookOpen(false);
          refetch();
        }}
      />
    </>
  );
}

function WorkshopBookingModal({ open, onClose, lang, user, workshop, seatsLeft, onBooked }) {
  const [seats, setSeats] = React.useState(1);
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [notes, setNotes] = React.useState("");
  const [status, setStatus] = React.useState("idle");
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    if (!open) return;
    setStatus("idle"); setErr("");
    if (user) {
      setName(user.user_metadata?.full_name || "");
      setEmail(user.email || "");
      // Phone may live on profiles; fetch once.
      window.sb.from("profiles").select("phone, full_name").eq("id", user.id).maybeSingle()
        .then(({ data }) => {
          if (data?.phone) setPhone(data.phone);
          if (data?.full_name && !name) setName(data.full_name);
        });
    }
  }, [open, user]);

  if (!open || !workshop) return null;

  const isWaitlist = seatsLeft === 0;
  const totalEgp = Math.round((workshop.price_piastres || 0) * seats / 100);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setStatus("submitting");
    try {
      const idemKey = `ws-${workshop.id}-${user?.id || "guest"}-${Date.now()}`;
      const url = `${window.SB_URL}/functions/v1/workshop_book`;
      const session = (await window.sb.auth.getSession()).data?.session;
      const headers = {
        "Content-Type": "application/json",
        "apikey": window.SB_ANON,
        "Authorization": "Bearer " + (session?.access_token || window.SB_ANON),
      };
      const res = await fetch(url, {
        method: "POST", headers,
        body: JSON.stringify({
          workshop_id: workshop.id,
          seats,
          guest_name: name,
          guest_email: email,
          guest_phone: phone,
          notes: notes || null,
          idempotency_key: idemKey,
          payment_method: "cod",
          anon_id: localStorage.getItem("sanaa_anon_id") || null,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        if (data.error) console.warn("workshop_book:", data.error);
        setErr((lang === "en" ? data.friendly_en : data.friendly_ar)
          || (lang === "en" ? "We couldn't complete that booking. Please try again." : "تعذّر إتمام الحجز. حاول مرّة أخرى."));
        setStatus("error");
        return;
      }
      setStatus("done");
      onBooked?.(data.booking);
    } catch (ex) {
      console.warn("workshop_book", ex);
      setErr(lang === "en"
        ? "We couldn't reach SANAA right now. Please try again in a moment."
        : "تعذّر الوصول. حاول بعد لحظات.");
      setStatus("error");
    }
  };

  const inp = { display: "block", width: "100%", marginTop: 6, padding: "11px 14px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0, boxSizing: "border-box" };
  const lbl = { fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(28,26,21,0.6)", backdropFilter: "blur(4px)", zIndex: 9000, display: "grid", placeItems: "center", padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--paper)", borderRadius: 18, maxWidth: 540, width: "100%", padding: 36, maxHeight: "90vh", overflowY: "auto" }}>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--terracotta)" }}>
          {isWaitlist ? (lang === "en" ? "Waitlist" : "قائمة انتظار") : (lang === "en" ? "Reserve a seat" : "حجز مقعد")}
        </div>
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 32, marginTop: 8, lineHeight: 1.1 }}>
          {lang === "en" ? workshop.title_en : (workshop.title_ar || workshop.title_en)}
        </h2>
        <div style={{ marginTop: 6, fontFamily: "var(--ff-mono)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.18em" }}>
          {new Date(workshop.starts_at).toLocaleString(lang === "ar" ? "ar-EG" : "en-GB",
            { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" })}
        </div>

        <form onSubmit={submit} style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <label style={lbl}>{lang === "en" ? "Your name" : "اسمك"} *</label>
              <input required value={name} onChange={e => setName(e.target.value)} style={inp} />
            </div>
            <div>
              <label style={lbl}>{lang === "en" ? "Seats" : "المقاعد"}</label>
              <select value={seats} onChange={e => setSeats(Number(e.target.value))} style={inp}>
                {Array.from({ length: Math.max(1, Math.min(isWaitlist ? 2 : seatsLeft, 4)) }, (_, i) => i + 1).map(n => (
                  <option key={n} value={n}>{n}</option>
                ))}
              </select>
            </div>
          </div>
          <div>
            <label style={lbl}>{lang === "en" ? "Email" : "البريد"} *</label>
            <input required type="email" value={email} onChange={e => setEmail(e.target.value)} style={inp} placeholder="you@example.com" />
          </div>
          <div>
            <label style={lbl}>{lang === "en" ? "WhatsApp phone" : "رقم واتساب"} *</label>
            <input required value={phone} onChange={e => setPhone(e.target.value)} style={inp} placeholder="+20 100 000 0000" />
          </div>
          <div>
            <label style={lbl}>{lang === "en" ? "Anything we should know? (optional)" : "ملاحظة (اختياري)"}</label>
            <textarea rows={2} value={notes} onChange={e => setNotes(e.target.value)} style={{ ...inp, resize: "vertical" }} />
          </div>

          <div style={{ marginTop: 8, padding: 16, background: "var(--paper-2)", borderRadius: 10, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
              {lang === "en" ? "Total · pay at the workshop" : "الإجمالي · ادفع في الورشة"}
            </div>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 28 }}>
              {totalEgp ? window.fmtPrice(totalEgp, lang) : "—"}
            </div>
          </div>

          {err && (
            <div style={{ padding: 12, background: "rgba(194,99,66,0.08)", border: "1px solid rgba(194,99,66,0.3)", borderRadius: 10, fontSize: 13, color: "var(--terracotta)" }}>{err}</div>
          )}

          <div style={{ display: "flex", gap: 12, marginTop: 8 }}>
            <button type="button" onClick={onClose} className="btn ghost" style={{ flex: 1, justifyContent: "center" }}>
              {lang === "en" ? "Cancel" : "إلغاء"}
            </button>
            <button type="submit" disabled={status === "submitting"} className="btn" style={{ flex: 2, justifyContent: "center", opacity: status === "submitting" ? 0.6 : 1 }}>
              {status === "submitting"
                ? (lang === "en" ? "Holding your seat…" : "حجز المقعد…")
                : isWaitlist
                  ? (lang === "en" ? "Join the waitlist" : "انضم للقائمة")
                  : (lang === "en" ? "Confirm booking" : "تأكيد الحجز")} →
            </button>
          </div>
          <div style={{ marginTop: 4, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.18em", color: "var(--muted)", textAlign: "center" }}>
            {lang === "en"
              ? "By booking, you accept the cancellation policy."
              : "بإتمام الحجز، توافق على سياسة الإلغاء."}
          </div>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage, ShopPage, PDPPage, MakersIndexPage, MakerProfilePage, AtelierPage, VisitPage, ProcessPage, WorkshopsPage, WorkshopDetailPage, JournalPage, ArticlePage, GiftsPage, HelpPage, AccountPage, ApplyPage, ReviewPage, TrackOrderPage, NotFoundPage });
