/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

/* ---------- Cart Drawer ---------- */
function CartDrawer({ open, onClose, items, navigate, setItems }) {
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const [gift, setGift] = useState(false);
  const total = subtotal + (gift ? 30 : 0);

  return (
    <>
      <div className={"drawer-back" + (open ? " on" : "")} onClick={onClose} />
      <aside className={"drawer" + (open ? " on" : "")} aria-hidden={!open}>
        <div className="drawer__head">
          <h3>Your Bag <span style={{ color: "var(--muted)", fontSize: 14, fontFamily: "var(--sans)" }}>· {items.length}</span></h3>
          <button className="drawer__close" onClick={onClose} aria-label="Close"><Icon.Close /></button>
        </div>
        <div className="drawer__body">
          {items.length === 0 ? (
            <div className="drawer__empty">
              <Icon.Bag />
              <h4>Your bag is quiet.</h4>
              <p className="body-m">Add a piece and the story begins.</p>
              <button className="btn btn--ghost btn--sm" style={{ marginTop: 16 }} onClick={() => { onClose(); navigate("/shop"); }}>Browse the boutique</button>
            </div>
          ) : items.map((it, idx) => (
            <div className="drawer__item" key={it.id + it.size + idx}>
              <img src={it.image} alt="" />
              <div>
                <div className="name">{it.name}</div>
                <div className="meta">Size {it.size} · Qty {it.qty}</div>
                <button className="rm" onClick={() => setItems(items.filter((_, i) => i !== idx))}>Remove</button>
              </div>
              <div className="price">AED {(it.price * it.qty).toLocaleString()}</div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div className="drawer__foot">
            <label className="drawer__giftnote">
              <input type="checkbox" checked={gift} onChange={(e) => setGift(e.target.checked)} />
              Add Pearla gift wrap &amp; handwritten note · AED 30
            </label>
            <div className="drawer__row"><span>Subtotal</span><span>AED {subtotal.toLocaleString()}</span></div>
            {gift && <div className="drawer__row"><span>Gift wrap</span><span>AED 30</span></div>}
            <div className="drawer__row total"><span>Total</span><span>AED {total.toLocaleString()}</span></div>
            <p className="label" style={{ color: "var(--muted)", textAlign: "center" }}>Shipping calculated at checkout · 2–7 days worldwide</p>
            <button className="btn" style={{ width: "100%", justifyContent: "center" }}>Checkout via Shopify <Icon.ArrowR /></button>
            <a className="btn btn--ghost" href="https://wa.me/971528009555" target="_blank" style={{ width: "100%", justifyContent: "center" }}><Icon.Wa /> Enquire on WhatsApp</a>
          </div>
        )}
      </aside>
    </>
  );
}

/* ---------- Search overlay ---------- */
function SearchOverlay({ open, onClose, navigate }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);
  const results = q.length < 2 ? [] : window.PEARLA_DATA.products
    .filter(p => (p.name + " " + p.category + " " + p.collection).toLowerCase().includes(q.toLowerCase()))
    .slice(0, 6);
  const popular = ["Midnight Muse", "Ramadan & Eid", "S'élever", "Caftans under 1000"];

  return (
    <div className={"drawer-back" + (open ? " on" : "")} onClick={onClose} style={{ background: "rgba(16,13,10,0.55)" }}>
      {open && (
        <div style={{
          position: "absolute", top: 76, left: 0, right: 0,
          background: "var(--bg)", borderBottom: "1px solid var(--line)",
          padding: "32px var(--gutter)"
        }} onClick={(e) => e.stopPropagation()}>
          <div className="wrap" style={{ padding: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, borderBottom: "1px solid var(--ink)", paddingBottom: 14 }}>
              <Icon.Search />
              <input ref={inputRef} type="text" placeholder="Search pieces, collections, the scent…"
                value={q} onChange={(e) => setQ(e.target.value)}
                style={{ flex: 1, border: 0, background: "transparent", fontFamily: "var(--serif)", fontSize: 28, color: "var(--ink)" }} />
              <button className="nav__icon-btn" onClick={onClose}><Icon.Close /></button>
            </div>
            {q.length < 2 ? (
              <div style={{ paddingTop: 24 }}>
                <span className="label">Popular searches</span>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 12 }}>
                  {popular.map(t => (
                    <button key={t} className="btn btn--ghost btn--sm" onClick={() => setQ(t.split(" ")[0])}>{t}</button>
                  ))}
                </div>
              </div>
            ) : (
              <div style={{ paddingTop: 24 }}>
                {results.length === 0 ? (
                  <p className="muted">No matches. Try "abaya", "lace" or "scent".</p>
                ) : (
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
                    {results.map(p => (
                      <a key={p.id} onClick={() => { onClose(); navigate("/product/" + p.id); }}
                        style={{ display: "flex", gap: 14, padding: 10, border: "1px solid var(--line)", cursor: "pointer" }}>
                        <img src={p.image} alt="" style={{ width: 64, aspectRatio: "3/4", objectFit: "cover" }} />
                        <div>
                          <div style={{ fontFamily: "var(--serif)", fontSize: 18 }}>{p.name}</div>
                          <div className="label">{p.category}</div>
                          <div className="body-m" style={{ marginTop: 6 }}>AED {p.price.toLocaleString()}</div>
                        </div>
                      </a>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- App ---------- */
const DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "modest-luxe",
  "displayFont": "Cormorant Garamond",
  "showPedigree": true,
  "showFragrance": true,
  "showSocial": true,
  "showDrop": true,
  "denser": false
}/*EDITMODE-END*/;

const PALETTES = {
  "modest-luxe": {
    name: "Modest luxe",
    swatch: ["#FBF7F1", "#1B1814", "#B59A66"],
    vars: { "--bg": "#FBF7F1", "--ink": "#1B1814", "--noir": "#100D0A", "--gold": "#B59A66", "--gold-deep": "#8A6F3F", "--bone": "#EEE7DB", "--paper": "#F5EFE5", "--line": "#E6DCCD", "--line-strong": "#D5C8B0", "--muted": "#6B5F4F" }
  },
  "stone-noir": {
    name: "Stone noir",
    swatch: ["#EFECE4", "#1A1A1C", "#8E8276"],
    vars: { "--bg": "#EFECE4", "--ink": "#1A1A1C", "--noir": "#0E0E10", "--gold": "#8E8276", "--gold-deep": "#5E544A", "--bone": "#E0DCD2", "--paper": "#E6E2D8", "--line": "#D1CCBF", "--line-strong": "#B7B1A1", "--muted": "#6A645B" }
  },
  "blush-ink": {
    name: "Blush & ink",
    swatch: ["#FAEEEA", "#22171A", "#C28A8A"],
    vars: { "--bg": "#FAEEEA", "--ink": "#22171A", "--noir": "#140C10", "--gold": "#C28A8A", "--gold-deep": "#8E5A5A", "--bone": "#F1DEDA", "--paper": "#F5E5E1", "--line": "#E8D2CC", "--line-strong": "#CFAAA3", "--muted": "#7A5A5A" }
  },
  "midnight-pearl": {
    name: "Midnight pearl",
    swatch: ["#11131A", "#EDE6D8", "#B3A06B"],
    vars: { "--bg": "#11131A", "--ink": "#EDE6D8", "--noir": "#0A0B10", "--gold": "#B3A06B", "--gold-deep": "#D6C28A", "--bone": "#1E202A", "--paper": "#181B25", "--line": "#2A2D38", "--line-strong": "#3A3E4A", "--muted": "#9A9486" }
  }
};

function App() {
  const [route, setRoute] = useState(window.location.hash.replace("#", "") || "/");
  const [bag, setBag] = useState([]);
  const [bagOpen, setBagOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [favs, setFavs] = useState(new Set());
  const [toast, setToast] = useState("");
  const [tweaks, setTweaks] = useState(DEFAULTS);

  const navigate = (r) => {
    setRoute(r);
    window.location.hash = r;
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  useEffect(() => {
    const onHash = () => setRoute(window.location.hash.replace("#", "") || "/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  /* apply tweaks (palette + font) */
  useEffect(() => {
    const root = document.documentElement;
    const pal = PALETTES[tweaks.palette] || PALETTES["modest-luxe"];
    Object.entries(pal.vars).forEach(([k, v]) => root.style.setProperty(k, v));
    root.style.setProperty("--serif", `"${tweaks.displayFont}", Georgia, serif`);
    document.body.dataset.denser = tweaks.denser ? "1" : "0";
  }, [tweaks]);

  const setTweak = (key, val) => {
    const next = typeof key === "object" ? { ...tweaks, ...key } : { ...tweaks, [key]: val };
    setTweaks(next);
    window.parent?.postMessage({ type: "__edit_mode_set_keys", edits: typeof key === "object" ? key : { [key]: val } }, "*");
  };

  const onAdd = (p, size) => {
    setBag(prev => {
      const existing = prev.findIndex(it => it.id === p.id && it.size === size);
      if (existing >= 0) {
        const c = prev.slice();
        c[existing] = { ...c[existing], qty: c[existing].qty + 1 };
        return c;
      }
      return [...prev, { id: p.id, name: p.name, price: p.price, image: p.image, size, qty: 1 }];
    });
    setToast(`Added — ${p.name}`);
    setTimeout(() => setToast(""), 1800);
  };

  const toggleFav = (id) => {
    setFavs(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const bagCount = bag.reduce((s, it) => s + it.qty, 0);

  /* route resolver */
  let page;
  if (route === "/" || route === "") {
    page = (
      <>
        <Hero navigate={navigate} />
        {tweaks.showPedigree && <Pedigree />}
        <CollectionsBlock navigate={navigate} />
        {tweaks.showDrop && <SeasonalDrop navigate={navigate} />}
        <ProductsBlock navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} />
        <GiftingBlock navigate={navigate} />
        {tweaks.showFragrance && <FragranceBlock navigate={navigate} />}
        <FounderBlock navigate={navigate} />
        {tweaks.showSocial && <SocialBlock />}
        <Newsletter />
      </>
    );
  } else if (route === "/shop") {
    page = <ShopPage navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} />;
  } else if (route === "/collections") {
    page = <CollectionsIndex navigate={navigate} />;
  } else if (route.startsWith("/collections/")) {
    page = <ShopPage navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} filterCollection={route.split("/")[2]} />;
  } else if (route.startsWith("/product/")) {
    page = <ProductDetail id={route.split("/")[2]} navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} />;
  } else if (route === "/fragrance") {
    page = <FragrancePage navigate={navigate} onAdd={onAdd} />;
  } else if (route === "/gifting") {
    page = <GiftingPage navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} />;
  } else if (route === "/about") {
    page = <AboutPage navigate={navigate} />;
  } else if (route === "/contact") {
    page = <ContactPage />;
  } else {
    page = <ShopPage navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav} />;
  }

  return (
    <div data-screen-label={"01 " + (route === "/" ? "Home" : route.slice(1).replace(/\//g, " · "))}>
      <Announcement />
      <Navbar route={route} navigate={navigate} bagCount={bagCount}
        openBag={() => setBagOpen(true)} openSearch={() => setSearchOpen(true)} />
      <main>{page}</main>
      <Footer navigate={navigate} />

      <CartDrawer open={bagOpen} onClose={() => setBagOpen(false)} items={bag} setItems={setBag} navigate={navigate} />
      <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} navigate={navigate} />

      <a className="fab" href="https://wa.me/971528009555" target="_blank" aria-label="WhatsApp the atelier"><Icon.Wa /></a>

      <div className={"toast" + (toast ? " on" : "")}>{toast}</div>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Palette">
          <TweakColor label="Mood"
            value={(PALETTES[tweaks.palette] || PALETTES["modest-luxe"]).swatch}
            options={Object.keys(PALETTES).map(k => PALETTES[k].swatch)}
            onChange={(swatch) => {
              const key = Object.keys(PALETTES).find(k => JSON.stringify(PALETTES[k].swatch) === JSON.stringify(swatch));
              if (key) setTweak("palette", key);
            }} />
          <div className="label" style={{ marginTop: 6 }}>{(PALETTES[tweaks.palette] || PALETTES["modest-luxe"]).name}</div>
        </TweakSection>
        <TweakSection title="Type">
          <TweakSelect label="Display serif" value={tweaks.displayFont}
            options={["Cormorant Garamond", "Fraunces", "EB Garamond", "DM Serif Display", "Playfair Display"]}
            onChange={(v) => setTweak("displayFont", v)} />
        </TweakSection>
        <TweakSection title="Home sections">
          <TweakToggle label="Pedigree strip (AFW)" value={tweaks.showPedigree} onChange={(v) => setTweak("showPedigree", v)} />
          <TweakToggle label="Seasonal drop marquee" value={tweaks.showDrop} onChange={(v) => setTweak("showDrop", v)} />
          <TweakToggle label="Fragrance band" value={tweaks.showFragrance} onChange={(v) => setTweak("showFragrance", v)} />
          <TweakToggle label="Social strip" value={tweaks.showSocial} onChange={(v) => setTweak("showSocial", v)} />
        </TweakSection>
        <TweakSection title="Jump to a screen">
          {[
            ["Home", "/"], ["Shop", "/shop"], ["Collections", "/collections"],
            ["A Collection — Princess", "/collections/princess-and-the-pearl"],
            ["Product — Celestial Bloom", "/product/celestial-bloom-abaya"],
            ["Fragrance", "/fragrance"], ["Gifting", "/gifting"],
            ["About", "/about"], ["Contact", "/contact"]
          ].map(([label, path]) => (
            <TweakButton key={path} label={label} onClick={() => navigate(path)} />
          ))}
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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