// LAM Shining — Main App
// State, palette/hero/card tweaks, scroll reveals, WhatsApp integration.

const { useState: useS, useEffect: useE, useRef: useR, useCallback: useC } = React;

const PALETTE_PRESETS = [
  { name: "pure",      swatches: ["#ffffff", "#0a0a0a", "#f4f2ed"] },
  { name: "ivory",     swatches: ["#f7f3eb", "#1a1612", "#ebe4d4"] },
  { name: "champagne", swatches: ["#fbf7ee", "#1a1612", "#a8854c"] },
  { name: "onyx",      swatches: ["#0a0a0a", "#f2ede2", "#d8c298"] },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#0a0a0a", "#f2ede2", "#d8c298"],
  "hero": "editorial",
  "card": "minimal"
}/*EDITMODE-END*/;

function paletteNameFor(arr) {
  const k = JSON.stringify((arr || []).map(s => String(s).toLowerCase()));
  const hit = PALETTE_PRESETS.find(p => JSON.stringify(p.swatches.map(s => s.toLowerCase())) === k);
  return hit ? hit.name : "pure";
}

function applyPalette(arr) {
  const name = paletteNameFor(arr);
  const p = PALETTES[name] || PALETTES.pure;
  const [bg, ink, accent, soft] = p;
  const root = document.documentElement;
  root.style.setProperty("--bg", bg);
  root.style.setProperty("--ink", ink);
  root.style.setProperty("--accent", accent);
  root.style.setProperty("--soft", soft);
  // Compute hair + mute from ink so things stay tonal.
  const isDark = name === "onyx";
  if (isDark) {
    root.style.setProperty("--hair", "rgba(242,237,226,.14)");
    root.style.setProperty("--mute", "rgba(242,237,226,.6)");
    document.body.setAttribute("data-dark", "1");
  } else {
    root.style.setProperty("--hair", "rgba(10,10,10,.12)");
    root.style.setProperty("--mute", "rgba(10,10,10,.55)");
    document.body.removeAttribute("data-dark");
  }
}

// Scroll-reveal observer
function useReveal() {
  useE(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    const scan = () => {
      document.querySelectorAll(".reveal:not(.in)").forEach(el => io.observe(el));
    };
    scan();
    const mo = new MutationObserver(scan);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => { io.disconnect(); mo.disconnect(); };
  }, []);
}

// Track active section for nav underline
function useActiveSection() {
  const [active, setActive] = useS("home");
  useE(() => {
    const ids = ["home", "shop", "categories", "payment"];
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    if (els.length === 0) return;
    const io = new IntersectionObserver((entries) => {
      const visible = entries.filter(e => e.isIntersecting)
                              .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
      if (visible[0]) setActive(visible[0].target.id);
    }, { threshold: [0.2, 0.4, 0.6], rootMargin: "-80px 0px -40% 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
  return active;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [cart, setCart] = useS([]); // {product, qty}[]
  const [cartOpen, setCartOpen] = useS(false);
  const [menuOpen, setMenuOpen] = useS(false);
  const [modalProduct, setModalProduct] = useS(null);
  const [modalOpen, setModalOpen] = useS(false);
  const [filter, setFilter] = useS("all");
  const [toast, setToast] = useS("");
  const toastTimer = useR(null);

  useE(() => applyPalette(t.palette), [t.palette]);
  useReveal();
  const active = useActiveSection();

  const showToast = useC((msg) => {
    setToast(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(""), 2400);
  }, []);

  const addToCart = useC((product) => {
    setCart(prev => {
      const existing = prev.find(it => it.product.id === product.id);
      if (existing) {
        return prev.map(it => it.product.id === product.id ? { ...it, qty: it.qty + 1 } : it);
      }
      return [...prev, { product, qty: 1 }];
    });
    showToast(`Added · ${product.name}`);
  }, [showToast]);

  const incQty    = (id) => setCart(p => p.map(it => it.product.id === id ? { ...it, qty: it.qty + 1 } : it));
  const decQty    = (id) => setCart(p => p.flatMap(it => it.product.id === id
                                          ? (it.qty <= 1 ? [] : [{ ...it, qty: it.qty - 1 }])
                                          : [it]));
  const removeItem = (id) => setCart(p => p.filter(it => it.product.id !== id));

  const openProduct = useC((p) => {
    setModalProduct(p);
    setModalOpen(true);
  }, []);
  const closeProduct = () => { setModalOpen(false); setTimeout(() => setModalProduct(null), 350); };

  const waUrl = (text) => `https://wa.me/${BRAND.whatsapp}?text=${encodeURIComponent(text)}`;

  const orderOnWhatsApp = useC((product) => {
    const lines = [
      `Hello LAM Shining,`,
      ``,
      `I'd like to order:`,
      `• ${product.name} (${product.nameAr}) — EGP ${product.price.toLocaleString()}`,
      ``,
      `Could you confirm availability and share payment details? Thank you.`,
    ].join("\n");
    window.open(waUrl(lines), "_blank");
  }, []);

  const cartCheckout = useC(() => {
    if (cart.length === 0) return;
    const lines = [
      `Hello LAM Shining,`,
      ``,
      `I'd like to place an order:`,
      ...cart.map(({ product, qty }) =>
        `• ${product.name} × ${qty} — EGP ${(product.price * qty).toLocaleString()}`
      ),
      ``,
      `Total: EGP ${cart.reduce((s, it) => s + it.product.price * it.qty, 0).toLocaleString()}`,
      ``,
      `Could you confirm availability and share payment details? Thank you.`,
    ].join("\n");
    window.open(waUrl(lines), "_blank");
  }, [cart]);

  const generalWhatsApp = () => {
    window.open(waUrl(`Hello LAM Shining, I have a question about your collection.`), "_blank");
  };

  const navigateTo = useC((id) => {
    if (id === "home") {
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      const el = document.getElementById(id);
      if (el) {
        const y = el.getBoundingClientRect().top + window.pageYOffset - 60;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    }
  }, []);

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

  const handleCategoryPick = (catId) => {
    setFilter(catId);
    setTimeout(() => navigateTo("shop"), 80);
  };

  return (
    <React.Fragment>
      <Header
        cartCount={cartCount}
        activeSection={active}
        onCart={() => setCartOpen(true)}
        onMenu={() => setMenuOpen(true)}
        onNav={navigateTo}
      />

      <MobileDrawer
        open={menuOpen}
        onClose={() => setMenuOpen(false)}
        onNav={navigateTo}
      />

      <main>
        <Hero variant={t.hero} onShop={() => navigateTo("shop")} />
        <Ribbon />
        <Featured
          products={PRODUCTS}
          cardVariant={t.card}
          onOpen={openProduct}
          onAdd={addToCart}
          filter={filter}
          setFilter={setFilter}
        />
        <Categories onPick={handleCategoryPick} />
      </main>

      <Footer onNav={navigateTo} />

      <ProductModal
        product={modalProduct}
        open={modalOpen}
        onClose={closeProduct}
        onAdd={(p) => { addToCart(p); }}
        onWhatsApp={orderOnWhatsApp}
      />

      <Cart
        open={cartOpen}
        items={cart}
        onClose={() => setCartOpen(false)}
        onInc={incQty}
        onDec={decQty}
        onRemove={removeItem}
        onCheckout={cartCheckout}
      />

      <WhatsAppFab onClick={generalWhatsApp} />
      <Toast message={toast} />

      <TweaksPanel>
        <TweakSection label="Palette" />
        <TweakColor label="Theme" value={t.palette}
          options={PALETTE_PRESETS.map(p => p.swatches)}
          onChange={(arr) => setTweak("palette", arr)}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,.55)", marginTop: -4, lineHeight: 1.5 }}>
          {paletteNameFor(t.palette) === "pure"      && "Pure — white + black, editorial."}
          {paletteNameFor(t.palette) === "ivory"     && "Ivory — warm cream, soft black."}
          {paletteNameFor(t.palette) === "champagne" && "Champagne — cream + gold accent."}
          {paletteNameFor(t.palette) === "onyx"      && "Onyx — inverted, evening mood."}
        </div>

        <TweakSection label="Hero Layout" />
        <TweakSelect label="Variant" value={t.hero}
          options={[
            { value: "editorial", label: "Editorial — full bleed" },
            { value: "split",     label: "Split — text + image" },
            { value: "grand",     label: "Grand — centered serif" },
          ]}
          onChange={(v) => setTweak("hero", v)}
        />

        <TweakSection label="Product Card" />
        <TweakRadio label="Style" value={t.card}
          options={[
            { value: "minimal",   label: "Minimal" },
            { value: "bordered",  label: "Bordered" },
            { value: "editorial", label: "Editorial" },
          ]}
          onChange={(v) => setTweak("card", v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

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