// Strawberry Fields — main app
// All sections live here. Editorial layout, real data, original visual system.

const { useState, useEffect, useMemo, useRef, useCallback } = React;

// Format AED price — never invent
const aed = (n) => {
  const num = typeof n === "string" ? parseFloat(n) : n;
  return num.toLocaleString("en-AE", { minimumFractionDigits: 0, maximumFractionDigits: 2 });
};

// ---------- Brand mark (original — strawberry + hand-set wordmark) ----------
function BrandMark({ size = 28, withWord = true }) {
  return (
    <span className="brand-mark">
      <MotifStrawberry size={size} />
      {withWord && <span>Strawberry Fields</span>}
    </span>
  );
}

// ---------- Utility strip (delivery, hours, locale) ----------
function UtilityStrip({ locale, onLocale }) {
  return (
    <div className="utility-strip">
      <span className="us-pill"><span className="us-dot"></span>Free delivery in the UAE</span>
      <span className="us-pill">Open Tue–Sun, 09:30–19:30 · Alserkal Avenue WH G58</span>
      <span className="us-pill" style={{ display: "inline-flex", gap: 8 }}>
        <button
          onClick={() => onLocale("en")}
          style={{ fontWeight: locale === "en" ? 700 : 400, opacity: locale === "en" ? 1 : 0.7 }}
        >EN</button>
        <span style={{ opacity: 0.4 }}>·</span>
        <button
          onClick={() => onLocale("ar")}
          style={{ fontWeight: locale === "ar" ? 700 : 400, opacity: locale === "ar" ? 1 : 0.7, fontFamily: "Noto Kufi Arabic, var(--body)" }}
        >ع</button>
      </span>
    </div>
  );
}

// ---------- Header / nav ----------
function Header({ cartCount, onOpenCart, locale, onLocale, onJump }) {
  const [openMenu, setOpenMenu] = useState(null); // "shop" | "happenings" | null
  const timerRef = useRef();

  const handleEnter = (key) => {
    clearTimeout(timerRef.current);
    setOpenMenu(key);
  };
  const handleLeave = () => {
    timerRef.current = setTimeout(() => setOpenMenu(null), 120);
  };

  return (
    <header className="site-header">
      <UtilityStrip locale={locale} onLocale={onLocale} />
      <div className="container">
        <div className="nav-row">
          <nav className="nav-left">
            <button
              className="nav-link has-menu"
              onMouseEnter={() => handleEnter("shop")}
              onMouseLeave={handleLeave}
              aria-expanded={openMenu === "shop"}
            >Shop</button>
            <a href="#picks" className="nav-link" onClick={(e) => { e.preventDefault(); onJump("picks"); }}>Curation</a>
            <a href="#playground" className="nav-link" onClick={(e) => { e.preventDefault(); onJump("playground"); }}>Hidden Playground</a>
            <a href="#happenings" className="nav-link" onClick={(e) => { e.preventDefault(); onJump("happenings"); }}>Happenings</a>
            <a href="#gifting" className="nav-link" onClick={(e) => { e.preventDefault(); onJump("gifting"); }}>Gifting</a>
          </nav>
          <a href="#top" onClick={(e) => { e.preventDefault(); onJump("top"); }}>
            <BrandMark />
          </a>
          <div className="nav-right">
            <button className="icon-btn" aria-label="Search">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
            </button>
            <button className="icon-btn" aria-label="Account">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>
            </button>
            <button className="icon-btn" aria-label="Bag" onClick={onOpenCart}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 7h12l-1 13H7L6 7Z"/><path d="M9 7a3 3 0 0 1 6 0"/></svg>
              {cartCount > 0 && <span className="badge">{cartCount}</span>}
            </button>
          </div>
        </div>
      </div>
      {openMenu === "shop" && (
        <div className="megamenu" onMouseEnter={() => handleEnter("shop")} onMouseLeave={handleLeave}>
          <div className="container">
            <div>
              <h4>By world</h4>
              <ul>
                {WORLDS.map(w => <li key={w.key}><a href="#">{w.title}</a></li>)}
              </ul>
            </div>
            <div>
              <h4>By moment</h4>
              <ul>
                <li><a href="#">New arrivals</a></li>
                <li><a href="#">Newborn essentials</a></li>
                <li><a href="#">First birthday</a></li>
                <li><a href="#">Big-kid room</a></li>
                <li><a href="#">Summer & beach</a></li>
              </ul>
            </div>
            <div>
              <h4>By brand</h4>
              <ul>
                <li><a href="#">Trixie</a></li>
                <li><a href="#">Konges Sløjd</a></li>
                <li><a href="#">Tinycottons</a></li>
                <li><a href="#">OMY</a></li>
                <li><a href="#">Adam Bike</a></li>
                <li><a href="#">All 48 brands →</a></li>
              </ul>
            </div>
            <div className="mm-feature">
              <img src="media/product-34-doorway-theatre.webp" alt="" />
              <span className="eyebrow" style={{ color: "var(--primary)" }}>Featured</span>
              <div className="display" style={{ fontSize: 22 }}>Strawberry Doorway Theatre</div>
              <div className="muted" style={{ fontSize: 13 }}>By MIMIKI · AED 325</div>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}

// ---------- Hero ----------
function Hero({ onShop }) {
  return (
    <section className="hero" id="top">
      {/* decorative motifs */}
      <MotifSun size={260} style={{ position: "absolute", top: -60, left: -80, opacity: 0.85 }} />
      <MotifLeaf size={140} style={{ position: "absolute", top: 220, left: 100, transform: "rotate(-20deg)" }} />
      <MotifSquiggle width={280} style={{ position: "absolute", bottom: 40, left: "30%" }} />
      <MotifBlob size={180} style={{ position: "absolute", bottom: 60, right: "8%", opacity: 0.4 }} />

      <div className="container">
        <div>
          <span className="eyebrow hero-eyebrow">A curated children's design house</span>
          <h1>
            A world of <span className="ital">magic</span><br/>
            &amp; <span className="underline">imagination</span> for<br/>
            the next generation.
          </h1>
          <p className="lede">
            Five hundred and fifteen carefully chosen objects from forty-eight design houses — and a real-life
            Hidden Playground at Alserkal Avenue, Dubai. Sustainable, design-led, parent-trusted.
          </p>
          <div className="hero-ctas">
            <button className="btn btn-primary" onClick={onShop}>
              Step into the shop
              <span aria-hidden>→</span>
            </button>
            <a href="#playground" className="btn btn-ghost">Visit the Hidden Playground</a>
          </div>
          <div className="hero-meta">
            <div><strong>515</strong>objects in store</div>
            <div><strong>48</strong>design houses</div>
            <div><strong>WH G58</strong>Alserkal Avenue, Dubai</div>
          </div>
        </div>
        <div className="hero-collage" aria-hidden>
          <div className="tile t1"><img src="media/product-22-nursery-light-train.webp" alt="" /></div>
          <div className="tile t2 contain"><img src="media/product-31-fairy-costume.webp" alt="" /></div>
          <div className="tile t3 contain"><img src="media/product-21-rug-chess.webp" alt="" /></div>
          <div className="tile t4"><img src="media/product-20-wallpaper-rainbows.webp" alt="" /></div>
          <span className="tag t1tag">Little Lights · Train</span>
          <span className="tag t4tag">Hibou Home · Wallpaper</span>
          <MotifStar size={36} style={{ position: "absolute", top: -10, right: 40, color: "#fff" }} />
          <MotifStar size={22} style={{ position: "absolute", bottom: 30, left: -10 }} />
        </div>
      </div>
    </section>
  );
}

// ---------- Marquee divider ----------
function Marquee() {
  const items = [
    "Sustainable", "Design-led", "Educational", "Parent-trusted", "Alserkal Avenue WH G58",
    "Hidden Playground", "48 design houses", "Made for ages 0–8",
  ];
  const seq = (
    <span>
      {items.map((t, i) => (
        <React.Fragment key={i}>
          {t}<span className="marquee-dot"></span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="marquee">
      <div className="marquee-track">{seq}{seq}{seq}</div>
    </div>
  );
}

// ---------- Shop by world ----------
function Worlds() {
  return (
    <section className="section" id="worlds">
      <div className="container">
        <div className="picks-head">
          <div>
            <span className="eyebrow">Shop by world</span>
            <h2 className="display">Eight worlds, gently curated.</h2>
          </div>
          <a href="#" className="btn-link">All categories →</a>
        </div>
        <div className="worlds">
          {WORLDS.map(w => (
            <div key={w.key} className={`world ${w.span} ${w.contain ? "contain" : ""} ${w.dark ? "" : "dark"}`} style={{
              background: w.key === "rooms" ? "var(--surface)" :
                          w.key === "baby"  ? "#EDE2D6" :
                          w.key === "toys"  ? "#F2E0C8" :
                          w.key === "books" ? "#E5DDD3" :
                          w.key === "outfits" ? "#F4E6D9" :
                          w.key === "outdoors" ? "#DBE6E8" :
                          w.key === "celebrate" ? "#F1D9DD" :
                          "#E8E0D4"
            }}>
              <img src={w.img} alt="" />
              <div className="scrim"></div>
              <div className="world-meta">
                <div>
                  <div className="world-title">{w.title}</div>
                  <div className="world-count">{w.count} objects</div>
                </div>
                <span className="world-arrow">→</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Curated picks ----------
function Picks({ onAdd }) {
  const [tab, setTab] = useState("editor");

  const filtered = useMemo(() => {
    const uniq = (arr) => {
      const seen = new Set();
      return arr.filter(p => seen.has(p.id) ? false : (seen.add(p.id), true));
    };
    if (tab === "editor")    return uniq(PRODUCTS.filter(p => p.tags.includes("editor")).concat(PRODUCTS)).slice(0, 8);
    if (tab === "new")       return uniq(PRODUCTS.filter(p => p.tags.includes("new")).concat(PRODUCTS.slice(8))).slice(0, 8);
    if (tab === "under100")  return uniq(PRODUCTS.filter(p => parseFloat(p.price) < 100)).slice(0, 8);
    if (tab === "heirloom")  return uniq(PRODUCTS.filter(p => parseFloat(p.price) >= 500)).slice(0, 8);
    return PRODUCTS.slice(0, 8);
  }, [tab]);

  return (
    <section className="section section--paper" id="picks">
      <div className="container">
        <div className="picks-head">
          <div>
            <span className="eyebrow">From our shelves</span>
            <h2 className="display">Curated, this week.</h2>
          </div>
          <div className="picks-tabs" role="tablist">
            {PICK_TABS.map(t => (
              <button
                key={t.id}
                role="tab"
                aria-pressed={tab === t.id}
                onClick={() => setTab(t.id)}
              >{t.label}</button>
            ))}
          </div>
        </div>
        <div className="picks-grid">
          {filtered.map(p => (
            <article key={p.id + tab} className="pcard" onClick={() => onAdd(p)}>
              <div className="pcard-img">
                <img src={p.img} alt={p.title} />
                {p.tags.includes("new") && <span className="pcard-tag">New</span>}
                {p.tags.includes("editor") && <span className="pcard-tag" style={{ color: "var(--secondary-ink)" }}>Editor</span>}
                {p.tags.includes("collab") && <span className="pcard-tag" style={{ color: "var(--terracotta)" }}>SF × collab</span>}
                {p.tags.includes("local") && <span className="pcard-tag" style={{ color: "var(--terracotta)" }}>Local voice</span>}
                <button className="pcard-add" aria-label={`Add ${p.title} to bag`} onClick={(e) => { e.stopPropagation(); onAdd(p); }}>＋</button>
              </div>
              <div className="pcard-vendor">{p.vendor}</div>
              <div className="pcard-title">{p.title}</div>
              <div className="pcard-price">
                {p.tags.includes("from") ? "From " : ""}AED {aed(p.price)}
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

window.__sfApp1 = { BrandMark, UtilityStrip, Header, Hero, Marquee, Worlds, Picks, aed };
