// Maison Dahab — shared components
// Header (mega-menu + mobile drawer), product card, footer, contact FABs, Rise entrance helper.
const { useState, useEffect, useRef } = React;

// ---- fade-up-once entrance (IntersectionObserver) ----
function Rise({ children, delay = 0, as = "div", className = "", ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let done = false;
    let io = null;
    let iv = null;
    const reveal = () => {
      if (done) return;
      done = true;
      el.classList.add("is-in");
      if (io) io.disconnect();
      if (iv) clearInterval(iv);
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
    const check = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight || 800;
      if (r.top < vh * 0.96 && r.bottom > 0) reveal();
    };
    if ("IntersectionObserver" in window) {
      io = new IntersectionObserver((entries) => {
        entries.forEach((e) => { if (e.isIntersecting) reveal(); });
      }, { threshold: 0.08 });
      io.observe(el);
    }
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check);
    const t = setTimeout(check, 80); // initial in-view check
    iv = setInterval(check, 250); // env-proof fallback (some hosts never fire scroll/IO)
    return () => {
      clearTimeout(t);
      if (io) io.disconnect();
      if (iv) clearInterval(iv);
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={`rise ${className}`} style={{ "--rise-delay": `${delay}s` }} {...rest}>
      {children}
    </Tag>
  );
}

// ---- image slot wrapper (custom element) ----
function Slot({ slotId, placeholder, style, className }) {
  return (
    <image-slot
      id={slotId}
      shape="rect"
      src={IMG(slotId)}
      placeholder={placeholder || "photo bijou"}
      style={style}
      class={className}
    ></image-slot>
  );
}

// ---- icons (minimal strokes) ----
const Icon = {
  bag: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3">
      <path d="M5 8h14l-1 12H6L5 8z"></path>
      <path d="M9 8V6a3 3 0 0 1 6 0v2"></path>
    </svg>
  ),
  menu: (
    <svg width="20" height="20" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.3">
      <line x1="4" y1="8" x2="20" y2="8"></line>
      <line x1="4" y1="16" x2="20" y2="16"></line>
    </svg>
  ),
  close: (
    <svg width="18" height="18" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.3">
      <line x1="5" y1="5" x2="19" y2="19"></line>
      <line x1="19" y1="5" x2="5" y2="19"></line>
    </svg>
  ),
  search: (
    <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3">
      <circle cx="11" cy="11" r="7"></circle>
      <line x1="16.5" y1="16.5" x2="21" y2="21"></line>
    </svg>
  ),
  phone: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3">
      <path d="M5 4h4l1.5 4.5L8 10a12 12 0 0 0 6 6l1.5-2.5L20 15v4a1.5 1.5 0 0 1-1.7 1.5C10.5 19.6 4.4 13.5 3.5 5.7A1.5 1.5 0 0 1 5 4z"></path>
    </svg>
  ),
  wa: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2.5A9.5 9.5 0 0 0 3.8 16.8L2.5 21.5l4.8-1.3A9.5 9.5 0 1 0 12 2.5zm0 1.8a7.7 7.7 0 1 1-3.9 14.3l-.5-.3-2.7.7.7-2.6-.3-.5A7.7 7.7 0 0 1 12 4.3zm-2.9 3.6c-.2 0-.5.1-.7.4-.2.3-.9.9-.9 2.1s.9 2.4 1 2.6c.1.2 1.8 2.9 4.5 3.9 2.2.9 2.7.7 3.2.7.5-.1 1.5-.6 1.7-1.2.2-.6.2-1.1.2-1.2-.1-.1-.2-.2-.5-.3l-1.7-.8c-.2-.1-.4-.1-.6.1l-.8.9c-.1.2-.3.2-.5.1-.7-.3-1.5-.7-2.3-1.5-.6-.6-1-1.3-1.2-1.6-.1-.2 0-.4.1-.5l.5-.6c.1-.2.1-.3.2-.5s0-.3 0-.5l-.8-1.8c-.2-.4-.4-.3-.5-.3h-.4z"></path>
    </svg>
  ),
};

// ---- header ----
function Header({ nav, cartCount, onOpenCart, onOpenMenu }) {
  const [openMega, setOpenMega] = useState(null); // top-level cat id
  const closeTimer = useRef(null);
  const enter = (id) => { clearTimeout(closeTimer.current); setOpenMega(id); };
  const leave = () => { closeTimer.current = setTimeout(() => setOpenMega(null), 150); };

  return (
    <header className="hdr">
      <div className="wrap hdr__bar">
        <button className="iconbtn only-mobile" aria-label="Menu" onClick={onOpenMenu}>{Icon.menu}</button>

        <a className="hdr__logo" href="#/" aria-label="Maison Dahab — accueil">
          <span className="mark">Maison <em>Dahab</em></span>
          <span className="sub">Bijouterie — Or 18k & 21k</span>
        </a>

        <nav className="hdr__nav only-desktop" aria-label="Collections">
          {DB.topCategories().map((cat) => (
            <div key={cat.id} className="hdr__navitem" onMouseEnter={() => enter(cat.id)} onMouseLeave={leave}>
              <button
                className={`hdr__navlink ${openMega === cat.id ? "is-open" : ""}`}
                onClick={() => { setOpenMega(null); nav(`#/collection/${cat.id}`); }}
              >
                {cat.name}
              </button>
              {openMega === cat.id && (
                <div className="mega" onMouseEnter={() => enter(cat.id)} onMouseLeave={leave}>
                  <div className="mega__col">
                    <div className="mega__title">{cat.name}</div>
                    {DB.childrenOf(cat.id).map((sub) => (
                      <button key={sub.id} className="mega__link" onClick={() => { setOpenMega(null); nav(`#/collection/${sub.id}`); }}>
                        {sub.name}
                        <small>{DB.inCategory(sub.id).length} pièces</small>
                      </button>
                    ))}
                    <button className="mega__link" onClick={() => { setOpenMega(null); nav(`#/collection/${cat.id}`); }}>
                      Tout voir
                      <small>{DB.inCategory(cat.id).length} pièces</small>
                    </button>
                  </div>
                  <div className="mega__visual">
                    <Slot slotId={`mega-${cat.id}`} placeholder={`photo — ${cat.name.toLowerCase()}`} style={{ width: "100%", height: "100%", minHeight: "190px" }} />
                  </div>
                </div>
              )}
            </div>
          ))}
        </nav>

        <div className="hdr__actions">
          <button className="iconbtn only-desktop" aria-label="Rechercher" onClick={() => nav("#/collection")}>{Icon.search}</button>
          <button className="iconbtn" aria-label="Panier" onClick={onOpenCart}>
            {Icon.bag}
            {cartCount > 0 && <span className="badge">{cartCount}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

// ---- mobile nav drawer ----
function MobileNav({ nav, onClose }) {
  const [open, setOpen] = useState(null);
  const go = (hash) => { onClose(); nav(hash); };
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose}></div>
      <aside className="drawer drawer--left" role="dialog" aria-label="Navigation">
        <div className="drawer__head">
          <h3 className="serif">Collections</h3>
          <button className="iconbtn" aria-label="Fermer" onClick={onClose}>{Icon.close}</button>
        </div>
        <div className="drawer__body">
          {DB.topCategories().map((cat) => (
            <div key={cat.id} className="mnav__group">
              <button className={`mnav__top ${open === cat.id ? "is-open" : ""}`} onClick={() => setOpen(open === cat.id ? null : cat.id)}>
                {cat.name}
                <span className="chev">›</span>
              </button>
              {open === cat.id && (
                <div className="mnav__subs">
                  <button className="mnav__sub" onClick={() => go(`#/collection/${cat.id}`)}>Tout voir</button>
                  {DB.childrenOf(cat.id).map((sub) => (
                    <button key={sub.id} className="mnav__sub" onClick={() => go(`#/collection/${sub.id}`)}>{sub.name}</button>
                  ))}
                </div>
              )}
            </div>
          ))}
          <div className="mnav__group">
            <button className="mnav__top" onClick={() => go("#/collection")}>Toutes les pièces<span className="chev">›</span></button>
          </div>
        </div>
        <div className="drawer__foot">
          <div style={{ display: "flex", flexDirection: "column", gap: "6px", fontSize: "12px", color: "var(--muted)", letterSpacing: "0.08em" }}>
            <span>Boutique — Casablanca</span>
            <span>{BOUTIQUE_PHONE}</span>
          </div>
        </div>
      </aside>
    </React.Fragment>
  );
}

// ---- product card ----
function ProductCard({ product, onOpen, onAdd, delay = 0 }) {
  const cat = DB.category(product.category);
  return (
    <Rise delay={delay}>
      <article className="pcard" onClick={() => onOpen(product.id)}>
        <div className="pcard__img">
          <span className="pcard__carat">{product.attributes.carat}</span>
          <Slot slotId={product.images[0]} placeholder={`photo — ${product.name.toLowerCase()}`} />
        </div>
        <div className="pcard__body">
          <span className="pcard__name">{product.name}</span>
          <span className="pcard__sub">{cat ? cat.name : ""} · {product.attributes.weight}</span>
          <div className="pcard__row">
            <span className="price">{FMT_MAD(product.price)}</span>
            <button
              className="pcard__add"
              onClick={(e) => { e.stopPropagation(); onAdd(product.id); }}
            >
              Ajouter
            </button>
          </div>
        </div>
      </article>
    </Rise>
  );
}

// ---- floating contact ----
function ContactFabs() {
  return (
    <div className="contact-fab">
      <a className="fab fab--wa" href={BOUTIQUE_WHATSAPP} target="_blank" rel="noopener" aria-label="WhatsApp">{Icon.wa}</a>
      <a className="fab" href={`tel:${BOUTIQUE_PHONE.replace(/\s/g, "")}`} aria-label="Appeler">{Icon.phone}</a>
    </div>
  );
}

// ---- footer ----
function Footer({ nav }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer__in">
          <div className="footer__brand">
            <span className="mark">Maison <em>Dahab</em></span>
            <p>Bijouterie artisanale — or jaune 18 et 21 carats, façonné à Casablanca depuis 1987.</p>
          </div>
          <div>
            <h4>Collections</h4>
            <div className="footer__links">
              {DB.topCategories().map((c) => (
                <button key={c.id} onClick={() => nav(`#/collection/${c.id}`)}>{c.name}</button>
              ))}
            </div>
          </div>
          <div>
            <h4>La maison</h4>
            <div className="footer__links">
              <span>L'atelier</span>
              <span>Gravure & sur-mesure</span>
              <span>Reprise d'or</span>
            </div>
          </div>
          <div>
            <h4>Contact</h4>
            <div className="footer__links">
              <span>{BOUTIQUE_PHONE}</span>
              <span>Quartier des Habous, Casablanca</span>
              <span>Lun–Sam · 9h30 – 19h30</span>
            </div>
          </div>
        </div>
        <div className="footer__base">
          <span>© 2026 Maison Dahab — Bijouterie</span>
          <span>Prix indicatifs — selon le cours du jour de l'or</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Rise, Slot, Icon, Header, MobileNav, ProductCard, ContactFabs, Footer });
