// Root app — wires everything together + Tweaks

const { BrandMark, UtilityStrip, Header, Hero, Marquee, Worlds, Picks, aed } = window.__sfApp1;
const { Editorial, HiddenPlayground, Values, Brands, Gifting, Visit, Happenings, Footer, CartDrawer, Toast } = window.__sfApp2;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "berry",
  "heroStyle": "magazine",
  "heroMotifs": true,
  "headline": "world",
  "marquee": true,
  "density": "comfortable"
}/*EDITMODE-END*/;

// Palette variants — all stay in the brief's spirit (warm paper + berry/sage/sun)
const PALETTES = {
  berry: {
    label: "Berry (default)",
    swatch: ["#FBF4EE", "#C0436A", "#7FA66A", "#E9B44C"],
    vars: {} // brief defaults
  },
  terracotta: {
    label: "Terracotta morning",
    swatch: ["#FBF4EE", "#C76B3F", "#7FA66A", "#E9B44C"],
    vars: { "--primary": "#C76B3F", "--primary-ink": "#9A4F2A", "--focus": "#E27A4F" }
  },
  sage: {
    label: "Sage hour",
    swatch: ["#FBF4EE", "#7FA66A", "#C0436A", "#E9B44C"],
    vars: { "--primary": "#4F7341", "--primary-ink": "#365228", "--focus": "#7FA66A" }
  },
  plum: {
    label: "Plum dusk",
    swatch: ["#FBF4EE", "#7B3A66", "#E9B44C", "#7FA66A"],
    vars: { "--primary": "#7B3A66", "--primary-ink": "#5A2649", "--focus": "#A85C8E" }
  },
};

function App() {
  const t = window.useTweaks(TWEAK_DEFAULTS);
  const tweaks = t[0];
  const setTweak = t[1];

  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [toast, setToast] = React.useState("");
  const [locale, setLocale] = React.useState("en");
  const toastTimer = React.useRef();

  // Apply palette CSS vars
  React.useEffect(() => {
    const root = document.documentElement;
    // reset first
    ["--primary","--primary-ink","--focus"].forEach(v => root.style.removeProperty(v));
    const vars = PALETTES[tweaks.palette]?.vars || {};
    Object.entries(vars).forEach(([k, v]) => root.style.setProperty(k, v));
  }, [tweaks.palette]);

  // Apply RTL when Arabic is selected
  React.useEffect(() => {
    document.documentElement.dir = locale === "ar" ? "rtl" : "ltr";
    document.documentElement.lang = locale;
  }, [locale]);

  const addToCart = (p) => {
    if (!p) return;
    setCart(prev => {
      const found = prev.find(x => x.id === p.id);
      if (found) return prev.map(x => x.id === p.id ? { ...x, qty: x.qty + 1 } : x);
      return [...prev, { ...p, qty: 1 }];
    });
    setToast(`Added · ${p.title}`);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(""), 1800);
  };

  const changeQty = (id, qty) => setCart(prev => prev.map(x => x.id === id ? { ...x, qty } : x));
  const removeItem = (id) => setCart(prev => prev.filter(x => x.id !== id));

  const jumpTo = (id) => {
    if (id === "top") return window.scrollTo({ top: 0, behavior: "smooth" });
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 90;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };

  const cartCount = cart.reduce((s, x) => s + x.qty, 0);

  // Tweakable hero headline variants
  const headlineVariants = {
    world: <>A world of <span className="ital">magic</span><br/>&amp; <span className="underline">imagination</span> for<br/>the next generation.</>,
    curated: <>Objects, <span className="ital">curated</span> the way<br/>grown-ups <span className="underline">choose art.</span></>,
    playground: <>A <span className="ital">strawberry</span> tucked<br/>between the <span className="underline">galleries.</span></>,
  };

  return (
    <>
      <Header
        cartCount={cartCount}
        onOpenCart={() => setCartOpen(true)}
        locale={locale}
        onLocale={setLocale}
        onJump={jumpTo}
      />

      {tweaks.heroStyle === "magazine" ? (
        <window.HeroMagazine
          headlineKey={tweaks.headline}
          onShop={() => jumpTo("worlds")}
          onPlayground={() => jumpTo("playground")}
          onAdd={addToCart}
        />
      ) : (
      <section className="hero" id="top">
        {tweaks.heroMotifs && (
          <>
            <MotifSun size={260} style={{ position: "absolute", top: -60, left: -80, opacity: 0.85, zIndex: 0 }} />
            <MotifLeaf size={140} style={{ position: "absolute", top: 220, left: 100, transform: "rotate(-20deg)", zIndex: 0 }} />
            <MotifSquiggle width={280} style={{ position: "absolute", bottom: 40, left: "30%", zIndex: 0 }} />
            <MotifBlob size={180} style={{ position: "absolute", bottom: 60, right: "8%", opacity: 0.4, zIndex: 0 }} />
          </>
        )}
        <div className="container">
          <div>
            <span className="eyebrow hero-eyebrow">A curated children's design house</span>
            <h1>{headlineVariants[tweaks.headline] || headlineVariants.world}</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={() => jumpTo("worlds")}>
                Step into the shop <span aria-hidden>→</span>
              </button>
              <button className="btn btn-ghost" onClick={() => jumpTo("playground")}>Visit the Hidden Playground</button>
            </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} color="var(--primary)" style={{ position: "absolute", bottom: 30, left: -10 }} />
          </div>
        </div>
      </section>
      )}

      {tweaks.marquee && <Marquee />}

      <Worlds />
      <Picks onAdd={addToCart} />
      <Editorial />
      <HiddenPlayground />
      <Values />
      <Brands />
      <Gifting onAdd={addToCart} />
      <Visit />
      <Happenings />
      <Footer />

      <CartDrawer
        open={cartOpen}
        items={cart}
        onClose={() => setCartOpen(false)}
        onChange={changeQty}
        onRemove={removeItem}
      />
      <Toast msg={toast} />

      {/* Tweaks */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Palette">
          <window.TweakRadio
            label="Story"
            value={tweaks.palette}
            options={Object.entries(PALETTES).map(([k, v]) => ({ value: k, label: v.label }))}
            onChange={v => setTweak("palette", v)}
          />
          <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
            {(PALETTES[tweaks.palette]?.swatch || []).map((c, i) => (
              <div key={i} style={{ width: 28, height: 28, borderRadius: 8, background: c, border: "1px solid rgba(0,0,0,0.08)" }}></div>
            ))}
          </div>
        </window.TweakSection>

        <window.TweakSection title="Hero">
          <window.TweakRadio
            label="Style"
            value={tweaks.heroStyle}
            options={[
              { value: "magazine", label: "Magazine cover" },
              { value: "split", label: "Split / collage" },
            ]}
            onChange={v => setTweak("heroStyle", v)}
          />
          <window.TweakSelect
            label="Headline"
            value={tweaks.headline}
            options={[
              { value: "world", label: "World of magic & imagination" },
              { value: "curated", label: "Curated the way grown-ups choose art" },
              { value: "playground", label: "Tucked between the galleries" },
            ]}
            onChange={v => setTweak("headline", v)}
          />
          <window.TweakToggle
            label="Show illustrated motifs"
            value={tweaks.heroMotifs}
            onChange={v => setTweak("heroMotifs", v)}
          />
        </window.TweakSection>

        <window.TweakSection title="Page">
          <window.TweakToggle
            label="Marquee strip"
            value={tweaks.marquee}
            onChange={v => setTweak("marquee", v)}
          />
        </window.TweakSection>

        <window.TweakSection title="Try a flow">
          <window.TweakButton onClick={() => { addToCart(PRODUCTS[0]); setCartOpen(true); }}>Add wooden kitchen → open bag</window.TweakButton>
          <window.TweakButton onClick={() => { setLocale(locale === "en" ? "ar" : "en"); }}>Toggle EN ↔ ع (RTL)</window.TweakButton>
          <window.TweakButton onClick={() => jumpTo("playground")}>Jump to Hidden Playground</window.TweakButton>
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
