/* Pieces grid + Journal + Atelier process + Newsletter + Footer */

const PIECES = [
  { num: "№ 017", name: "Oasis Knot", ar: "عقدة الواحة", type: "Wall Hanging", maker: "Nour Ibrahim", price: "1,240", tone: "sand", edition: "1 of 6", slug: "oasis-knot", cat: "macrame", image: "assets/products/oasis-knot.png" },
  { num: "№ 018", name: "Fustat Bowl", ar: "طاسة الفسطاط", type: "Ceramics · Food-safe", maker: "Hassan El-Fustati", price: "980", tone: "terracotta", edition: "Open", slug: "fustat-bowl", cat: "ceramics", image: "assets/products/fustat-bowl.png" },
  { num: "№ 019", name: "Ward el-Nil", ar: "ورد النيل", type: "Scented Candle · 220g", maker: "Layla Abd-el-Raheem", price: "420", tone: "olive", edition: "Season 01", slug: "ward-el-nil", cat: "candles", image: "assets/products/ward-el-nil.png" },
  { num: "№ 020", name: "Aswan Stone", ar: "حجر أسوان", type: "Resin Tray · Alabaster", maker: "Karim Hamed", price: "1,680", tone: "gold", edition: "1 of 12", slug: "aswan-stone", cat: "resin", image: "assets/products/aswan-stone.png" },
  { num: "№ 021", name: "Palm Shadow", ar: "ظلّ النخيل", type: "Table Runner · Palm fibre", maker: "Fayrouz Mostafa", price: "860", tone: "sand", edition: "1 of 8", slug: "palm-shadow", cat: "macrame", image: "assets/products/palm-shadow.png" },
  { num: "№ 022", name: "Midan Lantern", ar: "فانوس الميدان", type: "Resin Sculpture", maker: "Omar Zaki", price: "2,340", tone: "terracotta", edition: "1 of 3", slug: "midan-lantern", cat: "resin", image: "assets/products/midan-lantern.png" },
];

function Pieces({ t, lang }) {
  const livePieces = usePieces();
  const featured = livePieces.length > 0
    ? livePieces.slice(0, 6)
    : PIECES.map(p => ({ ...p, cat: p.cat || "macrame", slug: p.slug || p.name.toLowerCase().replace(/\s+/g, "-") }));
  const total = livePieces.length > 0 ? livePieces.length : 48;

  return (
    <section style={{ padding: "140px 0", background: "var(--paper)" }}>
      <div className="container-wide">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", gap: 40, marginBottom: 64, flexWrap: "wrap" }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span className="dot"></span>{t.pieces_eyebrow}
            </div>
            <h2 style={{
              fontFamily: "var(--ff-display)", fontSize: "clamp(48px, 5.5vw, 96px)", lineHeight: 1.0,
              color: "var(--ink)", letterSpacing: "-0.02em",
            }}>
              {t.pieces_title} <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>{t.pieces_title_it}</span>
            </h2>
          </div>
          <div style={{
            display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center",
            fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
          }}>
            {[lang === "en" ? `All ${total}` : `الكل ${total}`, lang === "en" ? "Macramé" : "مكرامية", lang === "en" ? "Candle" : "شموع", lang === "en" ? "Resin" : "ريزن", lang === "en" ? "Ceramics" : "خزف"].map((f, i) => (
              <a key={i} href={i === 0 ? "#/shop" : `#/shop/${["","macrame","candles","resin","ceramics"][i]}`} style={{
                padding: "8px 16px", borderRadius: 999, textDecoration: "none",
                border: i === 0 ? "1px solid var(--ink)" : "1px solid var(--line)",
                background: i === 0 ? "var(--ink)" : "transparent",
                color: i === 0 ? "var(--paper)" : "var(--ink)",
                fontFamily: "inherit", fontSize: "inherit", letterSpacing: "inherit", textTransform: "inherit",
                cursor: "pointer",
              }}>{f}</a>
            ))}
          </div>
        </div>

        <div className="pieces-grid">
          {featured.map((p, i) => (
            <PieceCard key={i} p={p} lang={lang} />
          ))}
        </div>

        <div style={{ marginTop: 70, display: "flex", justifyContent: "center" }}>
          <a href="#/shop" className="btn ghost">{lang === "en" ? `View all ${total} pieces` : `شاهد الـ ${total} قطعة`} <span className="arrow">→</span></a>
        </div>
      </div>
    </section>
  );
}

function PieceCard({ p, lang }) {
  const [hover, setHover] = React.useState(false);
  const href = p.slug && p.cat ? `#/shop/${p.cat}/${p.slug}` : "#/shop";
  const priceDisplay = typeof p.price === "number"
    ? p.price.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")
    : (lang === "ar" ? String(p.price).replace(/[0-9]/g, d => "٠١٢٣٤٥٦٧٨٩"[d]) : p.price);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => { window.location.hash = href; }}
      style={{ cursor: "pointer" }}
    >
      <div style={{
        aspectRatio: "0.82",
        borderRadius: "999px 999px 10px 10px / 600px 600px 10px 10px",
        overflow: "hidden", position: "relative",
        transition: "transform 0.5s ease",
        transform: hover ? "translateY(-6px)" : "translateY(0)",
      }}>
        <Placeholder tone={p.tone} topLabel={p.num} label={p.name.toLowerCase()} meta={p.edition} src={p.image} alt={`${p.name} — ${p.type || "piece"}${p.maker ? ` by ${p.maker}` : ""}`} />
        {/* Quick-add on hover */}
        <div style={{
          position: "absolute", left: "50%", bottom: 30,
          transform: `translateX(-50%) translateY(${hover ? "0" : "20px"})`,
          opacity: hover ? 1 : 0,
          transition: "all 0.4s ease",
          background: "var(--paper)", color: "var(--ink)",
          padding: "12px 22px", borderRadius: 999,
          fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
          boxShadow: "0 12px 30px -10px rgba(28,26,21,0.4)",
        }}>
          {lang === "en" ? "Quick look" : "نظرة سريعة"}
        </div>
      </div>
      <div style={{ padding: "22px 4px 0", display: "flex", justifyContent: "space-between", alignItems: "start", gap: 20 }}>
        <div>
          <div style={{ display: "flex", gap: 10, alignItems: "baseline", flexWrap: "wrap" }}>
            <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 28, color: "var(--ink)" }}>{p.name}</h3>
            <span className="ar" style={{ fontSize: 18, color: "var(--terracotta)" }}>{p.ar}</span>
          </div>
          <div style={{
            marginTop: 4, fontFamily: "var(--ff-mono)", fontSize: 10,
            letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)",
          }}>
            {p.type} · {p.maker}
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: "var(--ff-display)", fontSize: 24, color: "var(--ink)" }}>{priceDisplay}</div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)" }}>{lang === "en" ? "EGP" : "ج.م"}</div>
        </div>
      </div>
    </div>
  );
}

// ——— Atelier: the six-step process ———
function Atelier({ t, lang }) {
  const steps = lang === "en" ? [
    { n: "i.", t: "Applied", d: "Maker submits work plus one unedited process video." },
    { n: "ii.", t: "Scored", d: "Eight-point rubric. 75+ onboard, 60–74 waitlist." },
    { n: "iii.", t: "Photographed", d: "Shot in daylight on one standard set." },
    { n: "iv.", t: "Quality-checked", d: "Written standard. Lead and cadmium tested where needed." },
    { n: "v.", t: "Wrapped", d: "Recycled tissue, wax-sealed with a numbered mark." },
    { n: "vi.", t: "Released", d: "Posted from Zamalek with a tracked courier." },
  ] : [
    { n: "١.", t: "تقديم", d: "يُقدّم الصانع عمله مع فيديو صنعٍ غير معدّل." },
    { n: "٢.", t: "تقييم", d: "معيارٌ من ثماني نقاط. ٧٥+ قبول، ٦٠-٧٤ قائمة انتظار." },
    { n: "٣.", t: "تصوير", d: "في ضوء النهار على استديوٍ موحّد." },
    { n: "٤.", t: "فحص", d: "معيارٌ مكتوب. فحص الرصاص والكادميوم عند الحاجة." },
    { n: "٥.", t: "تغليف", d: "ورقٌ مُعاد تدويره، ختم شمعٍ مرقّم." },
    { n: "٦.", t: "إرسال", d: "من الزمالك مع شركة شحنٍ متتبَّعة." },
  ];
  return (
    <section id="atelier" style={{ padding: "140px 0", background: "var(--paper-2)", borderTop: "1px solid var(--line-2)" }}>
      <div className="container-wide">
        <div className="atelier-grid">
          <div style={{ position: "sticky", top: 120 }}>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span className="dot"></span>{t.atelier_eyebrow}
            </div>
            <h2 style={{
              fontFamily: "var(--ff-display)", fontSize: "clamp(44px, 4.8vw, 84px)", lineHeight: 1.02,
              letterSpacing: "-0.02em", color: "var(--ink)",
            }}>
              {t.atelier_title}<br />
              <span style={{ fontStyle: "italic", color: "var(--terracotta)" }}>{t.atelier_title_it}</span>
            </h2>
            <p style={{ marginTop: 28, fontSize: 16, color: "var(--olive)", lineHeight: 1.6, maxWidth: 460 }}>
              {t.atelier_body}
            </p>

            <div style={{ marginTop: 50, aspectRatio: "1.4", borderRadius: 12, overflow: "hidden" }}>
              <Placeholder tone="olive" topLabel="Atelier · Zamalek" label="the packing table, morning light" meta="Cairo" />
            </div>
          </div>

          <div>
            {steps.map((s, i) => (
              <div key={i} className="atelier-step" style={{
                borderBottom: i < steps.length - 1 ? "1px solid var(--line)" : "none",
              }}>
                <div style={{
                  fontFamily: "var(--ff-display)", fontStyle: "italic",
                  fontSize: 44, color: "var(--terracotta)", lineHeight: 1,
                }}>{s.n}</div>
                <div>
                  <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 36, color: "var(--ink)" }}>{s.t}</h3>
                  <p style={{ marginTop: 8, fontSize: 15, color: "var(--olive)", lineHeight: 1.55, maxWidth: 440 }}>{s.d}</p>
                </div>
                <div style={{
                  width: 40, height: 40, borderRadius: "50%",
                  border: "1px solid var(--line)", display: "grid", placeItems: "center",
                  color: "var(--muted)",
                }}>
                  <Star8 size={12} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ——— Journal ———
const JOURNAL = [
  { tag: "Field note", date: "Apr · 2026", title: "Three days in Fustat: the kilns that refused to close", read: "6 min", tone: "terracotta" },
  { tag: "Maker", date: "Mar · 2026", title: "Nour learned to knot from her grandmother in 1993", read: "4 min", tone: "sand" },
  { tag: "Process", date: "Feb · 2026", title: "Why we tier packaging, and what 'fragile' actually costs", read: "7 min", tone: "olive" },
];

function Journal({ t, lang }) {
  return (
    <section id="journal" style={{ padding: "140px 0", background: "var(--paper)" }}>
      <div className="container-wide">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", gap: 40, marginBottom: 64, flexWrap: "wrap" }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span className="dot"></span>{t.journal_eyebrow}
            </div>
            <h2 style={{
              fontFamily: "var(--ff-display)", fontSize: "clamp(48px, 5.5vw, 96px)", lineHeight: 1.0,
              color: "var(--ink)", letterSpacing: "-0.02em",
            }}>
              <span style={{ fontStyle: "italic" }}>{t.journal_title}</span>
            </h2>
          </div>
          <a href="#" style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--ink)", paddingBottom: 4, fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase" }}>
            {lang === "en" ? "All entries →" : "الكل →"}
          </a>
        </div>

        <div className="journal-grid">
          {JOURNAL.map((j, i) => (
            <article key={i} style={{ cursor: "pointer" }}>
              <div style={{ aspectRatio: i === 0 ? "1.3" : "0.9", borderRadius: 10, overflow: "hidden", marginBottom: 20 }}>
                <Placeholder tone={j.tone} topLabel={j.tag} label={j.title.toLowerCase()} meta={j.date} />
              </div>
              <div style={{ display: "flex", gap: 10, alignItems: "center", fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>
                <span style={{ color: "var(--terracotta)" }}>{j.tag}</span>
                <span>·</span>
                <span>{j.date}</span>
                <span>·</span>
                <span>{j.read}</span>
              </div>
              <h3 style={{
                fontFamily: "var(--ff-display)",
                fontSize: i === 0 ? 36 : 26,
                lineHeight: 1.1, color: "var(--ink)", maxWidth: 480,
              }}>
                {j.title}
              </h3>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ——— Letter / Newsletter ———
function Letter({ t, lang }) {
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  return (
    <section style={{ padding: "120px 0", background: "var(--terracotta)", color: "var(--paper)", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.18 }}>
        <DiagonalLinesBg color="var(--paper)" spacing={14} strokeWidth={1.2} angle={45} />
      </div>
      <div className="container" style={{ position: "relative", textAlign: "center" }}>
        <div className="eyebrow" style={{ marginBottom: 28, color: "var(--paper)", opacity: 0.8 }}>
          <span className="dot" style={{ background: "var(--paper)" }}></span>{t.letter_eyebrow}
        </div>
        <h2 style={{
          fontFamily: "var(--ff-display)", fontSize: "clamp(40px, 8vw, 104px)", lineHeight: 1.05,
          letterSpacing: "-0.02em", fontStyle: "italic",
        }}>
          {t.letter_title}
        </h2>
        <p style={{ marginTop: 24, fontSize: 18, opacity: 0.85, maxWidth: 560, margin: "24px auto 0" }}>
          {t.letter_body}
        </p>

        <form
          onSubmit={async (e) => {
            e.preventDefault();
            if (!email || sending) return;
            setSending(true);
            try {
              await window.sb.functions.invoke("newsletter_subscribe", {
                body: { email, locale: lang },
              });
            } catch (err) {
              console.warn("newsletter:", err);
            }
            setSent(true);
            setSending(false);
          }}
          className="letter-form"
          style={{
            marginTop: 48, maxWidth: 560, margin: "48px auto 0",
            background: "rgba(250,246,238,0.12)", border: "1px solid rgba(250,246,238,0.35)",
            backdropFilter: "blur(8px)",
          }}
        >
          <input
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder={t.letter_placeholder}
            type="email"
            name="email"
            autoComplete="email"
            aria-label={lang === "en" ? "Email for the SANAA letter" : "البريد لرسائل صَنعة"}
            style={{
              flex: 1, background: "transparent", border: 0, outline: 0,
              color: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 15,
              padding: "14px 0",
            }}
          />
          <button type="submit" style={{
            background: "var(--ink)", color: "var(--paper)", border: 0, cursor: "pointer",
            padding: "14px 26px", borderRadius: 999,
            fontFamily: "var(--ff-sans)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase",
          }}>
            {sent ? (lang === "en" ? "Received ✓" : "وصلَت ✓") : sending ? (lang === "en" ? "Sending…" : "جارٍ الإرسال…") : t.letter_cta}
          </button>
        </form>

        <div style={{ marginTop: 24, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.7 }}>
          {lang === "en" ? "Issued on the first of each month · 2,412 readers" : "تصدر في أوّل كل شهر · ٢٤١٢ قارئًا"}
        </div>
      </div>
    </section>
  );
}

// ——— Footer ———
function Footer({ t, lang }) {
  const cols = lang === "en" ? [
    { h: "Shop", l: ["Macramé", "Candles", "Resin", "Ceramics", "Gift Cards", "Editions"] },
    { h: "House", l: ["About SANAA", "Our Makers", "The Journal", "Atelier Visits", "Press"] },
    { h: "Help", l: ["Shipping", "Returns", "Care Guide", "Wholesale", "Contact"] },
  ] : [
    { h: "المتجر", l: ["مكرمية", "شموع", "راتنج", "فخار", "بطاقات هدايا", "إصدارات"] },
    { h: "البيت", l: ["عن صَنعة", "صنّاعنا", "اليوميّات", "زيارة المحترف", "الصحافة"] },
    { h: "المساعدة", l: ["الشحن", "الإرجاع", "دليل العناية", "جملة", "تواصل"] },
  ];
  // Real hash routes per column item (language-independent), indexed [col][item].
  const colRoutes = [
    ["#/shop/macrame", "#/shop/candles", "#/shop/resin", "#/shop/ceramics", "#/gifts", "#/shop"],
    ["#/atelier", "#/makers", "#/journal", "#/atelier/visit", "#/journal"],
    ["#/help", "#/help", "#/help", "#/help", "#/help"],
  ];
  return (
    <footer id="contact" style={{ background: "var(--ink)", color: "var(--paper)", padding: "100px 0 40px" }}>
      <div className="container-wide">
        <div className="footer-grid">
          <div>
            <Wordmark size={32} color="var(--paper)" />
            <p style={{ marginTop: 22, maxWidth: 280, color: "rgba(244,237,226,0.7)", fontSize: 14, lineHeight: 1.55 }}>
              {t.footer_tag}
            </p>
            <div style={{ marginTop: 26, display: "flex", gap: 14 }}>
              {[
                { s: "IG", href: "https://instagram.com/sanaa.eg", label: "Instagram" },
                { s: "TT", href: "https://www.tiktok.com/@sanaa.eg", label: "TikTok" },
                { s: "PN", href: "https://www.pinterest.com/sanaaeg", label: "Pinterest" },
                { s: "EM", href: "mailto:hello@sanaa.eg", label: lang === "en" ? "Email" : "البريد الإلكتروني" },
              ].map(({ s, href, label }, i) => {
                const external = href.startsWith("http");
                return (
                  <a key={i} href={href} aria-label={label}
                    {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                    style={{
                      width: 36, height: 36, borderRadius: "50%",
                      border: "1px solid rgba(244,237,226,0.25)",
                      display: "grid", placeItems: "center",
                      color: "var(--paper)", textDecoration: "none",
                      fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.1em",
                    }}>{s}</a>
                );
              })}
            </div>
          </div>
          {cols.map((c, i) => (
            <div key={i}>
              <div style={{
                fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em",
                textTransform: "uppercase", color: "var(--gold-soft)", marginBottom: 20,
              }}>{c.h}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 2 }}>
                {c.l.map((item, j) => (
                  <li key={j}><a href={(colRoutes[i] && colRoutes[i][j]) || "#/help"} style={{ color: "rgba(244,237,226,0.8)", textDecoration: "none", fontSize: 14, display: "inline-block", padding: "9px 0" }}>{item}</a></li>
                ))}
              </ul>
            </div>
          ))}
          <div>
            <div style={{
              fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em",
              textTransform: "uppercase", color: "var(--gold-soft)", marginBottom: 20,
            }}>{lang === "en" ? "Atelier" : "المحترف"}</div>
            <p style={{ fontSize: 14, color: "rgba(244,237,226,0.8)", lineHeight: 1.7 }}>
              {lang === "en" ? "14 Shar'a Abou el-Feda" : "١٤ شارع أبو الفداء"}<br />
              {lang === "en" ? "Zamalek, Cairo 11211" : "الزمالك، القاهرة ١١٢١١"}<br />
              {lang === "en" ? "Open Tue–Sat · by appointment" : "الثلاثاء–السبت · بموعد"}<br />
              <span className={lang === "ar" ? "ar" : undefined} dir="ltr" style={{ marginTop: 10, display: "inline-block", color: "var(--gold-soft)" }}>{lang === "en" ? "+202 2735 0000" : "+٢٠٢ ٢٧٣٥ ٠٠٠٠"}</span>
            </p>
          </div>
        </div>

        <div style={{
          marginTop: 80, paddingTop: 28, borderTop: "1px solid rgba(244,237,226,0.12)",
          display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16,
          fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
          color: "rgba(244,237,226,0.55)",
        }}>
          <span>© 2026 SANAA · صَنعة · {lang === "en" ? "Registered with GAFI · Cairo" : "مسجّلة لدى الهيئة العامة للاستثمار"}</span>
          <span style={{ display: "flex", gap: 20, alignItems: "center" }}>
            <a href="#/help" style={{ color: "inherit", textDecoration: "none", display: "inline-block", padding: "9px 0" }}>{lang === "en" ? "Privacy" : "الخصوصية"}</a>
            <a href="#/help" style={{ color: "inherit", textDecoration: "none", display: "inline-block", padding: "9px 0" }}>{lang === "en" ? "Terms" : "الشروط"}</a>
            <a href="#/help" style={{ color: "inherit", textDecoration: "none", display: "inline-block", padding: "9px 0" }}>{lang === "en" ? "Cookies" : "ملفات الارتباط"}</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Pieces, Atelier, Journal, Letter, Footer });
